diff --git a/.gitignore b/.gitignore index f99867f73a..0b40b42f79 100644 --- a/.gitignore +++ b/.gitignore @@ -59,3 +59,4 @@ __pycache__/ # Test tool cache directories .tox/ .cache/ +.pytest_cache/ diff --git a/contrib/src/ai/aiBehaviors.cxx b/contrib/src/ai/aiBehaviors.cxx index 727e7e12f4..1ace436e5b 100644 --- a/contrib/src/ai/aiBehaviors.cxx +++ b/contrib/src/ai/aiBehaviors.cxx @@ -13,6 +13,10 @@ #include "aiBehaviors.h" +using std::cout; +using std::endl; +using std::string; + static const float _PI = 3.14; AIBehaviors::AIBehaviors() { @@ -21,16 +25,16 @@ AIBehaviors::AIBehaviors() { _previous_conflict = false; _conflict = false; - _seek_obj = NULL; - _flee_obj = NULL; - _pursue_obj = NULL; - _evade_obj = NULL; - _arrival_obj = NULL; - _wander_obj = NULL; - _flock_group = NULL; - _path_follow_obj = NULL; - _path_find_obj = NULL; - _obstacle_avoidance_obj = NULL; + _seek_obj = nullptr; + _flee_obj = nullptr; + _pursue_obj = nullptr; + _evade_obj = nullptr; + _arrival_obj = nullptr; + _wander_obj = nullptr; + _flock_group = nullptr; + _path_follow_obj = nullptr; + _path_find_obj = nullptr; + _obstacle_avoidance_obj = nullptr; turn_off("seek"); turn_off("flee"); @@ -267,7 +271,7 @@ LVecBase3 AIBehaviors::calculate_prioritized() { accumulate_force("obstacle_avoidance", force); } - if(_path_follow_obj!=NULL) { + if(_path_follow_obj!=nullptr) { if(_path_follow_obj->_start) { _path_follow_obj->do_follow(); } @@ -286,13 +290,13 @@ LVecBase3 AIBehaviors::calculate_prioritized() { } if(is_on(_arrival)) { - if(_seek_obj != NULL) { + if(_seek_obj != nullptr) { LVecBase3 dirn = _steering_force; dirn.normalize(); _steering_force = ((_steering_force.length() - _arrival_force.length()) * dirn); } - if(_pursue_obj != NULL) { + if(_pursue_obj != nullptr) { LVecBase3 dirn = _steering_force; dirn.normalize(); _steering_force = ((_steering_force.length() - _arrival_force.length()) * _arrival_obj->_arrival_direction); @@ -320,10 +324,10 @@ void AIBehaviors::remove_ai(string ai_type) { } case 1: { - if(_seek_obj != NULL) { + if(_seek_obj != nullptr) { turn_off("seek"); delete _seek_obj; - _seek_obj = NULL; + _seek_obj = nullptr; } break; } @@ -338,10 +342,10 @@ void AIBehaviors::remove_ai(string ai_type) { } case 3: { - if(_pursue_obj != NULL) { + if(_pursue_obj != nullptr) { turn_off("pursue"); delete _pursue_obj; - _pursue_obj = NULL; + _pursue_obj = nullptr; } break; } @@ -356,59 +360,59 @@ void AIBehaviors::remove_ai(string ai_type) { } case 5: { - if(_arrival_obj != NULL) { + if(_arrival_obj != nullptr) { turn_off("arrival"); turn_off("arrival_activate"); delete _arrival_obj; - _arrival_obj = NULL; + _arrival_obj = nullptr; } break; } case 6: { - if(_flock_group != NULL) { + if(_flock_group != nullptr) { turn_off("flock"); turn_off("flock_activate"); - _flock_group = NULL; + _flock_group = nullptr; } break; } case 7: { - if(_wander_obj != NULL) { + if(_wander_obj != nullptr) { turn_off("wander"); delete _wander_obj; - _wander_obj = NULL; + _wander_obj = nullptr; } break; } case 8: { - if(_obstacle_avoidance_obj !=NULL) { + if(_obstacle_avoidance_obj !=nullptr) { turn_off("obstacle_avoidance"); delete _obstacle_avoidance_obj; - _obstacle_avoidance_obj = NULL; + _obstacle_avoidance_obj = nullptr; } break; } case 9: { - if(_pursue_obj != NULL && _path_follow_obj != NULL) { + if(_pursue_obj != nullptr && _path_follow_obj != nullptr) { turn_off("pursue"); delete _pursue_obj; - _pursue_obj = NULL; + _pursue_obj = nullptr; delete _path_follow_obj; - _path_follow_obj = NULL; + _path_follow_obj = nullptr; } break; } case 16: { - if(_pursue_obj != NULL && _path_follow_obj != NULL) { + if(_pursue_obj != nullptr && _path_follow_obj != nullptr) { turn_off("pursue"); delete _pursue_obj; - _pursue_obj = NULL; + _pursue_obj = nullptr; delete _path_follow_obj; - _path_follow_obj = NULL; + _path_follow_obj = nullptr; } break; } @@ -436,7 +440,7 @@ void AIBehaviors::pause_ai(string ai_type) { } case 1: { - if(_seek_obj != NULL) { + if(_seek_obj != nullptr) { turn_off("seek"); } break; @@ -451,7 +455,7 @@ void AIBehaviors::pause_ai(string ai_type) { } case 3: { - if(_pursue_obj != NULL) { + if(_pursue_obj != nullptr) { turn_off("pursue"); } break; @@ -466,7 +470,7 @@ void AIBehaviors::pause_ai(string ai_type) { } case 5: { - if(_arrival_obj != NULL) { + if(_arrival_obj != nullptr) { turn_off("arrival"); turn_off("arrival_activate"); } @@ -474,7 +478,7 @@ void AIBehaviors::pause_ai(string ai_type) { } case 6: { - if(_flock_group != NULL) { + if(_flock_group != nullptr) { turn_off("flock"); turn_off("flock_activate"); } @@ -482,14 +486,14 @@ void AIBehaviors::pause_ai(string ai_type) { } case 7: { - if(_wander_obj != NULL) { + if(_wander_obj != nullptr) { turn_off("wander"); } break; } case 8: { - if(_obstacle_avoidance_obj != NULL) { + if(_obstacle_avoidance_obj != nullptr) { turn_off("obstacle_avoidance"); turn_off("obstacle_avoidance_activate"); } @@ -497,14 +501,14 @@ void AIBehaviors::pause_ai(string ai_type) { } case 9: { - if(_pursue_obj != NULL && _path_follow_obj != NULL) { + if(_pursue_obj != nullptr && _path_follow_obj != nullptr) { turn_off("pursue"); _path_follow_obj->_start = false; } break; } case 16: { - if(_pursue_obj != NULL && _path_follow_obj != NULL) { + if(_pursue_obj != nullptr && _path_follow_obj != nullptr) { turn_off("pursue"); _path_follow_obj->_start = false; } @@ -534,7 +538,7 @@ void AIBehaviors::resume_ai(string ai_type) { } case 1: { - if(_seek_obj != NULL) { + if(_seek_obj != nullptr) { turn_on("seek"); } break; @@ -548,7 +552,7 @@ void AIBehaviors::resume_ai(string ai_type) { } case 3: { - if(_pursue_obj != NULL) { + if(_pursue_obj != nullptr) { turn_on("pursue"); } break; @@ -562,42 +566,42 @@ void AIBehaviors::resume_ai(string ai_type) { } case 5: { - if(_arrival_obj != NULL) { + if(_arrival_obj != nullptr) { turn_on("arrival"); } break; } case 6: { - if(_flock_group != NULL) { + if(_flock_group != nullptr) { turn_on("flock"); } break; } case 7: { - if(_wander_obj != NULL) { + if(_wander_obj != nullptr) { turn_on("wander"); } break; } case 8: { - if(_obstacle_avoidance_obj != NULL) { + if(_obstacle_avoidance_obj != nullptr) { turn_on("obstacle_avoidance"); } break; } case 9: { - if(_pursue_obj != NULL && _path_follow_obj != NULL) { + if(_pursue_obj != nullptr && _path_follow_obj != nullptr) { turn_on("pursue"); _path_follow_obj->_start = true; } break; } case 16: { - if(_pursue_obj != NULL && _path_follow_obj != NULL) { + if(_pursue_obj != nullptr && _path_follow_obj != nullptr) { turn_off("pursue"); _path_follow_obj->_start = false; } diff --git a/contrib/src/ai/aiBehaviors.h b/contrib/src/ai/aiBehaviors.h index 6a20876db8..3524a32b63 100644 --- a/contrib/src/ai/aiBehaviors.h +++ b/contrib/src/ai/aiBehaviors.h @@ -28,8 +28,8 @@ class PathFollow; class PathFind; class ObstacleAvoidance; -typedef list > ListFlee; -typedef list > ListEvade; +typedef std::list > ListFlee; +typedef std::list > ListEvade; /** * This class implements all the steering behaviors of the AI framework, such @@ -113,21 +113,21 @@ public: ~AIBehaviors(); bool is_on(_behavior_type bt); - bool is_on(string ai_type); // special cases for pathfollow and pathfinding + bool is_on(std::string ai_type); // special cases for pathfollow and pathfinding bool is_off(_behavior_type bt); - bool is_off(string ai_type); // special cases for pathfollow and pathfinding - void turn_on(string ai_type); - void turn_off(string ai_type); + bool is_off(std::string ai_type); // special cases for pathfollow and pathfinding + void turn_on(std::string ai_type); + void turn_off(std::string ai_type); bool is_conflict(); - void accumulate_force(string force_type, LVecBase3 force); + void accumulate_force(std::string force_type, LVecBase3 force); LVecBase3 calculate_prioritized(); void flock_activate(); LVecBase3 do_flock(); - int char_to_int(string ai_type); + int char_to_int(std::string ai_type); PUBLISHED: void seek(NodePath target_object, float seek_wt = 1.0); @@ -150,21 +150,21 @@ PUBLISHED: void path_follow(float follow_wt); void add_to_path(LVecBase3 pos); - void start_follow(string type = "normal"); + void start_follow(std::string type = "normal"); // should have different function names. void init_path_find(const char* navmesh_filename); - void path_find_to(LVecBase3 pos, string type = "normal"); - void path_find_to(NodePath target, string type = "normal"); + void path_find_to(LVecBase3 pos, std::string type = "normal"); + void path_find_to(NodePath target, std::string type = "normal"); void add_static_obstacle(NodePath obstacle); void add_dynamic_obstacle(NodePath obstacle); - void remove_ai(string ai_type); - void pause_ai(string ai_type); - void resume_ai(string ai_type); + void remove_ai(std::string ai_type); + void pause_ai(std::string ai_type); + void resume_ai(std::string ai_type); - string behavior_status(string ai_type); + std::string behavior_status(std::string ai_type); }; #endif diff --git a/contrib/src/ai/aiCharacter.cxx b/contrib/src/ai/aiCharacter.cxx index 7009a353f1..58485081c3 100644 --- a/contrib/src/ai/aiCharacter.cxx +++ b/contrib/src/ai/aiCharacter.cxx @@ -13,7 +13,7 @@ #include "aiCharacter.h" -AICharacter::AICharacter(string model_name, NodePath model_np, double mass, double movt_force, double max_force) { +AICharacter::AICharacter(std::string model_name, NodePath model_np, double mass, double movt_force, double max_force) { _name = model_name; _ai_char_np = model_np; @@ -24,6 +24,8 @@ AICharacter::AICharacter(string model_name, NodePath model_np, double mass, doub _velocity = LVecBase3(0.0, 0.0, 0.0); _steering_force = LVecBase3(0.0, 0.0, 0.0); + _world = nullptr; + _steering = new AIBehaviors(); _steering->_ai_char = this; @@ -31,6 +33,7 @@ AICharacter::AICharacter(string model_name, NodePath model_np, double mass, doub } AICharacter::~AICharacter() { + nassertv(_world == nullptr); } /** diff --git a/contrib/src/ai/aiCharacter.h b/contrib/src/ai/aiCharacter.h index 244f9bc45e..81b3a01210 100644 --- a/contrib/src/ai/aiCharacter.h +++ b/contrib/src/ai/aiCharacter.h @@ -15,6 +15,7 @@ #define _AICHARACTER_H #include "aiBehaviors.h" +#include "referenceCount.h" /** * This class is used for creating the AI characters. It assigns both physics @@ -25,13 +26,13 @@ class AIBehaviors; class AIWorld; -class EXPCL_PANDAAI AICharacter { +class EXPCL_PANDAAI AICharacter : public ReferenceCount { public: double _mass; double _max_force; LVecBase3 _velocity; LVecBase3 _steering_force; - string _name; + std::string _name; double _movt_force; unsigned int _ai_char_flock_id; AIWorld *_world; @@ -62,7 +63,7 @@ PUBLISHED: // This function is used to enable or disable the guides for path finding. void set_pf_guide(bool pf_guide); - explicit AICharacter(string model_name, NodePath model_np, double mass, double movt_force, double max_force); + explicit AICharacter(std::string model_name, NodePath model_np, double mass, double movt_force, double max_force); ~AICharacter(); }; diff --git a/contrib/src/ai/aiNode.cxx b/contrib/src/ai/aiNode.cxx index a37927ae63..1812cf6cc1 100644 --- a/contrib/src/ai/aiNode.cxx +++ b/contrib/src/ai/aiNode.cxx @@ -15,7 +15,7 @@ AINode::AINode(int grid_x, int grid_y, LVecBase3 pos, float w, float l, float h) { for (int i = 0; i < 8; ++i) { - _neighbours[i] = NULL; + _neighbours[i] = nullptr; } _position = pos; @@ -29,8 +29,8 @@ AINode::AINode(int grid_x, int grid_y, LVecBase3 pos, float w, float l, float h) _score = 0; _cost = 0; _heuristic = 0; - _next = NULL; - _prv_node = NULL; + _next = nullptr; + _prv_node = nullptr; } AINode::~AINode() { diff --git a/contrib/src/ai/aiPathFinder.cxx b/contrib/src/ai/aiPathFinder.cxx index 58f11bfc39..be2b2dd56a 100644 --- a/contrib/src/ai/aiPathFinder.cxx +++ b/contrib/src/ai/aiPathFinder.cxx @@ -74,7 +74,7 @@ void PathFinder::generate_path() { add_to_clist(nxt_node); } } - cout<<"DESTINATION NOT REACHABLE MATE!"<_neighbours[i] != NULL) { + if(parent_node->_neighbours[i] != nullptr) { if(parent_node->_neighbours[i]->_status == parent_node->_neighbours[i]->neutral && parent_node->_neighbours[i]->_type == true) { // Link the neighbor to the parent node. @@ -340,10 +340,10 @@ Node* find_in_mesh(NavMesh nav_mesh, LVecBase3 pos, int grid_size) { for(int i = 0; i < size; ++i) { for(int j = 0; j < size; ++j) { - if(nav_mesh[i][j] != NULL && nav_mesh[i][j]->contains(x, y)) { + if(nav_mesh[i][j] != nullptr && nav_mesh[i][j]->contains(x, y)) { return(nav_mesh[i][j]); } } } - return NULL; + return nullptr; } diff --git a/contrib/src/ai/aiPathFinder.h b/contrib/src/ai/aiPathFinder.h index 1595cb2777..4b2e2c976a 100644 --- a/contrib/src/ai/aiPathFinder.h +++ b/contrib/src/ai/aiPathFinder.h @@ -18,8 +18,8 @@ #include "cmath.h" #include "lineSegs.h" -typedef vector NodeArray; -typedef vector NavMesh; +typedef std::vector NodeArray; +typedef std::vector NavMesh; Node* find_in_mesh(NavMesh nav_mesh, LVecBase3 pos, int grid_size); @@ -32,8 +32,8 @@ class EXPCL_PANDAAI PathFinder { public: Node *_src_node; Node *_dest_node; - vector _open_list; - vector _closed_list; + std::vector _open_list; + std::vector _closed_list; NavMesh _grid; diff --git a/contrib/src/ai/aiWorld.cxx b/contrib/src/ai/aiWorld.cxx index 6abac9f990..bbdf894e13 100644 --- a/contrib/src/ai/aiWorld.cxx +++ b/contrib/src/ai/aiWorld.cxx @@ -14,44 +14,56 @@ #include "aiWorld.h" AIWorld::AIWorld(NodePath render) { - _ai_char_pool = new AICharPool(); - _render = render; + _render = std::move(render); } AIWorld::~AIWorld() { } void AIWorld::add_ai_char(AICharacter *ai_char) { - _ai_char_pool->append(ai_char); + _ai_char_pool.push_back(ai_char); ai_char->_window_render = _render; ai_char->_world = this; } -void AIWorld::remove_ai_char(string name) { - _ai_char_pool->del(name); - remove_ai_char_from_flock(name); +void AIWorld::remove_ai_char(std::string name) { + AICharPool::iterator it; + for (it = _ai_char_pool.begin(); it != _ai_char_pool.end(); ++it) { + AICharacter *ai_char = *it; + if (ai_char->_name == name) { + nassertv(ai_char->_world == this); + ai_char->_world = nullptr; + _ai_char_pool.erase(it); + break; + } + } + + remove_ai_char_from_flock(std::move(name)); } -void AIWorld::remove_ai_char_from_flock(string name) { - AICharPool::node *ai_pool; - ai_pool = _ai_char_pool->_head; - while((ai_pool) != NULL) { - for(unsigned int i = 0; i < _flock_pool.size(); ++i) { - if(ai_pool->_ai_char->_ai_char_flock_id == _flock_pool[i]->get_id()) { - for(unsigned int j = 0; j<_flock_pool[i]->_ai_char_list.size(); ++j) { - if(_flock_pool[i]->_ai_char_list[j]->_name == name) { - _flock_pool[i]->_ai_char_list.erase(_flock_pool[i]->_ai_char_list.begin() + j); +void AIWorld::remove_ai_char_from_flock(std::string name) { + for (AICharacter *ai_char : _ai_char_pool) { + for (Flock *flock : _flock_pool) { + if (ai_char->_ai_char_flock_id == flock->get_id()) { + for (size_t j = 0; j < flock->_ai_char_list.size(); ++j) { + if (flock->_ai_char_list[j]->_name == name) { + flock->_ai_char_list.erase(flock->_ai_char_list.begin() + j); return; } } } } - ai_pool = ai_pool->_next; } } +/** + * This function prints the names of the AI characters that have been added to + * the AIWorld. Useful for debugging purposes. + */ void AIWorld::print_list() { - _ai_char_pool->print_list(); + for (AICharacter *ai_char : _ai_char_pool) { + std::cout << ai_char->_name << std::endl; + } } /** @@ -59,12 +71,8 @@ void AIWorld::print_list() { * characters which have been added to the AIWorld. */ void AIWorld::update() { - AICharPool::node *ai_pool; - ai_pool = _ai_char_pool->_head; - - while((ai_pool)!=NULL) { - ai_pool->_ai_char->update(); - ai_pool = ai_pool->_next; + for (AICharacter *ai_char : _ai_char_pool) { + ai_char->update(); } } @@ -91,7 +99,7 @@ Flock AIWorld::get_flock(unsigned int flock_id) { return *_flock_pool[i]; } } - Flock *null_flock = NULL; + Flock *null_flock = nullptr; return *null_flock; } @@ -104,7 +112,7 @@ void AIWorld::remove_flock(unsigned int flock_id) { for(unsigned int j = 0; j < _flock_pool[i]->_ai_char_list.size(); ++j) { _flock_pool[i]->_ai_char_list[j]->get_ai_behaviors()->turn_off("flock_activate"); _flock_pool[i]->_ai_char_list[j]->get_ai_behaviors()->turn_off("flock"); - _flock_pool[i]->_ai_char_list[j]->get_ai_behaviors()->_flock_group = NULL; + _flock_pool[i]->_ai_char_list[j]->get_ai_behaviors()->_flock_group = nullptr; } _flock_pool.erase(_flock_pool.begin() + i); break; @@ -142,86 +150,6 @@ void AIWorld::flock_on(unsigned int flock_id) { } } -AICharPool::AICharPool() { - _head = NULL; -} - -AICharPool::~AICharPool() { -} - -void AICharPool::append(AICharacter *ai_ch) { - node *q; - node *t; - - if(_head == NULL) { - q = new node(); - q->_ai_char = ai_ch; - q->_next = NULL; - _head = q; - } - else { - q = _head; - while( q->_next != NULL) { - q = q->_next; - } - - t = new node(); - t->_ai_char = ai_ch; - t->_next = NULL; - q->_next = t; - } -} - -void AICharPool::del(string name) { - node *q; - node *r; - q = _head; - - if(_head==NULL) { - return; - } - - // Only one node in the linked list - if(q->_next == NULL) { - if(q->_ai_char->_name == name) { - _head = NULL; - delete q; - } - return; - } - - r = q; - while( q != NULL) { - if( q->_ai_char->_name == name) { - // Special case - if(q == _head) { - _head = q->_next; - delete q; - return; - } - - r->_next = q->_next; - delete q; - return; - } - r = q; - q = q->_next; - } -} - -/** - * This function prints the ai characters in the AICharPool. Used for - * debugging purposes. - */ -void AICharPool::print_list() { - node* q; - q = _head; - while(q != NULL) { - cout<_ai_char->_name<_next; - } -} - /** * This function adds the nodepath as an obstacle that is needed by the * obstacle avoidance behavior. diff --git a/contrib/src/ai/aiWorld.h b/contrib/src/ai/aiWorld.h index f85e1dc584..67576c6745 100644 --- a/contrib/src/ai/aiWorld.h +++ b/contrib/src/ai/aiWorld.h @@ -21,27 +21,6 @@ class AICharacter; class Flock; -/** - * This class implements a linked list of AI Characters allowing the user to - * add and delete characters from the linked list. This will be used in the - * AIWorld class. - */ -class EXPCL_PANDAAI AICharPool { - public: - struct node { - AICharacter * _ai_char; - node * _next; - } ; - - node* _head; - AICharPool(); - ~AICharPool(); - void append(AICharacter *ai_ch); - void del(string name); - void print_list(); -}; - - /** * A class that implements the virtual AI world which keeps track of the AI * characters active at any given time. It contains a linked list of AI @@ -51,20 +30,21 @@ class EXPCL_PANDAAI AICharPool { */ class EXPCL_PANDAAI AIWorld { private: - AICharPool * _ai_char_pool; + typedef std::vector AICharPool; + AICharPool _ai_char_pool; NodePath _render; public: - vector _obstacles; + std::vector _obstacles; typedef std::vector FlockPool; FlockPool _flock_pool; - void remove_ai_char_from_flock(string name); + void remove_ai_char_from_flock(std::string name); PUBLISHED: AIWorld(NodePath render); ~AIWorld(); void add_ai_char(AICharacter *ai_ch); - void remove_ai_char(string name); + void remove_ai_char(std::string name); void add_flock(Flock *flock); void flock_off(unsigned int flock_id); diff --git a/contrib/src/ai/arrival.cxx b/contrib/src/ai/arrival.cxx index f9fba9438a..966a6b2611 100644 --- a/contrib/src/ai/arrival.cxx +++ b/contrib/src/ai/arrival.cxx @@ -48,7 +48,7 @@ LVecBase3 Arrival::do_arrival() { _ai_char->_steering->_steering_force = LVecBase3(0.0, 0.0, 0.0); _ai_char->_steering->_arrival_force = LVecBase3(0.0, 0.0, 0.0); - if(_ai_char->_steering->_seek_obj != NULL) { + if(_ai_char->_steering->_seek_obj != nullptr) { _ai_char->_steering->turn_off("arrival"); _ai_char->_steering->turn_on("arrival_activate"); } @@ -62,11 +62,11 @@ LVecBase3 Arrival::do_arrival() { double u = _ai_char->get_velocity().length(); LVecBase3 desired_force = ((u * u) / (2 * distance)) * _ai_char->get_mass(); - if(_ai_char->_steering->_seek_obj != NULL) { + if(_ai_char->_steering->_seek_obj != nullptr) { return(desired_force); } - if(_ai_char->_steering->_pursue_obj != NULL) { + if(_ai_char->_steering->_pursue_obj != nullptr) { if(distance > _arrival_distance) { _ai_char->_steering->turn_off("arrival"); @@ -77,7 +77,7 @@ LVecBase3 Arrival::do_arrival() { return(desired_force); } - cout<<"Arrival works only with seek and pursue"< AICharList; + typedef std::vector AICharList; AICharList _ai_char_list; PUBLISHED: diff --git a/contrib/src/ai/meshNode.cxx b/contrib/src/ai/meshNode.cxx index 043dc5b60c..26189f6bbf 100644 --- a/contrib/src/ai/meshNode.cxx +++ b/contrib/src/ai/meshNode.cxx @@ -3,7 +3,7 @@ Node::Node(int grid_x, int grid_y, LVecBase3 pos, float w, float l, float h) { for(int i = 0; i < 8; ++i) { - _neighbours[i] = NULL; + _neighbours[i] = nullptr; } _position = pos; @@ -17,8 +17,8 @@ Node::Node(int grid_x, int grid_y, LVecBase3 pos, float w, float l, float h) { _score = 0; _cost = 0; _heuristic = 0; - _next = NULL; - _prv_node = NULL; + _next = nullptr; + _prv_node = nullptr; } Node::~Node() { diff --git a/contrib/src/ai/obstacleAvoidance.cxx b/contrib/src/ai/obstacleAvoidance.cxx index faf8a1ff05..87ce79026b 100644 --- a/contrib/src/ai/obstacleAvoidance.cxx +++ b/contrib/src/ai/obstacleAvoidance.cxx @@ -36,7 +36,6 @@ obstacle_detection() { double distance = 0x7fff ; double expanded_radius = 0; LVecBase3 to_obstacle; - LVecBase3 prev_avoidance; for(unsigned int i = 0; i < _ai_char->_world->_obstacles.size(); ++i) { PT(BoundingVolume) bounds = _ai_char->_world->_obstacles[i].get_bounds(); CPT(BoundingSphere) bsphere = bounds->as_bounding_sphere(); diff --git a/contrib/src/ai/pathFind.cxx b/contrib/src/ai/pathFind.cxx index 39093da197..ee58f4940d 100644 --- a/contrib/src/ai/pathFind.cxx +++ b/contrib/src/ai/pathFind.cxx @@ -13,6 +13,10 @@ #include "pathFind.h" +using std::cout; +using std::endl; +using std::string; + PathFind::PathFind(AICharacter *ai_ch) { _ai_char = ai_ch; @@ -23,7 +27,7 @@ PathFind::PathFind(AICharacter *ai_ch) { _pen->set_color(1.0, 0.0, 0.0); _pen->set_thickness(2.0); - _path_finder_obj = NULL; + _path_finder_obj = nullptr; _dynamic_avoid = false; } @@ -46,7 +50,7 @@ void PathFind::create_nav_mesh(const char* navmesh_filename) { string fields[10]; // Open data file for reading. - ifstream nav_mesh_file (navmesh_filename); + std::ifstream nav_mesh_file (navmesh_filename); if(nav_mesh_file.is_open()) { // Capture the grid size from the file. @@ -56,9 +60,9 @@ void PathFind::create_nav_mesh(const char* navmesh_filename) { // Initialize the stage mesh with NULL nodes. for(int r = 0; r < _grid_size; ++r) { - _nav_mesh.push_back(vector()); + _nav_mesh.push_back(std::vector()); for(int c = 0; c < _grid_size; ++c) { - _nav_mesh[r].push_back(NULL); + _nav_mesh[r].push_back(nullptr); } } @@ -68,7 +72,7 @@ void PathFind::create_nav_mesh(const char* navmesh_filename) { // Begin reading data from the file. while(!nav_mesh_file.eof()) { getline(nav_mesh_file, line); - stringstream linestream (line); + std::stringstream linestream (line); // Stores all the data members in the line to the array. Data // structure: @@ -111,7 +115,7 @@ void PathFind::create_nav_mesh(const char* navmesh_filename) { * _nav_mesh. */ void PathFind::assign_neighbor_nodes(const char* navmesh_filename){ - ifstream nav_mesh_file (navmesh_filename); + std::ifstream nav_mesh_file (navmesh_filename); // Stage variables. int gd_x, gd_y, gd_xn, gd_yn; @@ -125,7 +129,7 @@ void PathFind::assign_neighbor_nodes(const char* navmesh_filename){ while(!nav_mesh_file.eof()) { getline(nav_mesh_file, ln); // Gets main node data only. No neighbor nodes. - stringstream linestream (ln); + std::stringstream linestream (ln); for(int i = 0; i < 10; ++i) { getline(linestream, fields[i], ','); } @@ -135,7 +139,7 @@ void PathFind::assign_neighbor_nodes(const char* navmesh_filename){ gd_y = atoi(fields[3].c_str()); for(int i = 0; i < 8; ++i) { getline(nav_mesh_file, ln); // Gets neighbor node data only. No main nodes. - stringstream linestream_n (ln); + std::stringstream linestream_n (ln); for(int j = 0; j < 10; ++j) { getline(linestream_n, fields_n[j], ','); } @@ -150,7 +154,7 @@ void PathFind::assign_neighbor_nodes(const char* navmesh_filename){ } else if(fields_n[0] == "1" && fields_n[1] == "1") { // NULL neighbor. - _nav_mesh[gd_y][gd_x]->_neighbours[i] = NULL; + _nav_mesh[gd_y][gd_x]->_neighbours[i] = nullptr; } else { cout<<"Warning: Corrupt data!"<_ai_char_np.get_pos(_ai_char->_window_render), _grid_size); - if(src == NULL) { + if(src == nullptr) { cout<<"couldnt find source"<find_path(src, dst); trace_path(src); } @@ -248,22 +252,22 @@ void PathFind::path_find(NodePath target, string type) { Node* src = find_in_mesh(_nav_mesh, _ai_char->_ai_char_np.get_pos(_ai_char->_window_render), _grid_size); - if(src == NULL) { + if(src == nullptr) { cout<<"couldnt find source"<find_path(src, dst); trace_path(src); } - if(_ai_char->_steering->_path_follow_obj!=NULL) { + if(_ai_char->_steering->_path_follow_obj!=nullptr) { if(!_ai_char->_steering->_path_follow_obj->_start) { _ai_char->_steering->start_follow("pathfind"); } @@ -277,12 +281,12 @@ void PathFind::clear_path() { // Initialize to zero for(int i = 0; i < _grid_size; ++i) { for(int j = 0; j < _grid_size; ++j) { - if(_nav_mesh[i][j] != NULL) { + if(_nav_mesh[i][j] != nullptr) { _nav_mesh[i][j]->_status = _nav_mesh[i][j]->neutral; _nav_mesh[i][j]->_cost = 0; _nav_mesh[i][j]->_heuristic = 0; _nav_mesh[i][j]->_score = 0; - _nav_mesh[i][j]->_prv_node = NULL; + _nav_mesh[i][j]->_prv_node = nullptr; } } } @@ -333,7 +337,7 @@ void PathFind::add_obstacle_to_mesh(NodePath obstacle) { Node* temp = find_in_mesh(_nav_mesh, obstacle.get_pos(), _grid_size); - if(temp != NULL) { + if(temp != nullptr) { float left = temp->_position.get_x() - np_sphere->get_radius(); float right = temp->_position.get_x() + np_sphere->get_radius(); float top = temp->_position.get_y() + np_sphere->get_radius(); @@ -341,7 +345,7 @@ void PathFind::add_obstacle_to_mesh(NodePath obstacle) { for(int i = 0; i < _grid_size; ++i) { for(int j = 0; j < _grid_size; ++j) { - if(_nav_mesh[i][j] != NULL && _nav_mesh[i][j]->_type == true) { + if(_nav_mesh[i][j] != nullptr && _nav_mesh[i][j]->_type == true) { if(_nav_mesh[i][j]->_position.get_x() >= left && _nav_mesh[i][j]->_position.get_x() <= right && _nav_mesh[i][j]->_position.get_y() >= down && _nav_mesh[i][j]->_position.get_y() <= top) { _nav_mesh[i][j]->_type = false; diff --git a/contrib/src/ai/pathFind.h b/contrib/src/ai/pathFind.h index eb82f9ff99..cd26cc234f 100644 --- a/contrib/src/ai/pathFind.h +++ b/contrib/src/ai/pathFind.h @@ -40,9 +40,9 @@ public: LVecBase3 _prev_position; PT(GeomNode) _parent; LineSegs *_pen; - vector _previous_obstacles; + std::vector _previous_obstacles; bool _dynamic_avoid; - vector _dynamic_obstacle; + std::vector _dynamic_obstacle; PathFind(AICharacter *ai_ch); ~PathFind(); @@ -56,8 +56,8 @@ public: void clear_previous_obstacles(); void set_path_find(const char* navmesh_filename); - void path_find(LVecBase3 pos, string type = "normal"); - void path_find(NodePath target, string type = "normal"); + void path_find(LVecBase3 pos, std::string type = "normal"); + void path_find(NodePath target, std::string type = "normal"); void add_obstacle_to_mesh(NodePath obstacle); void dynamic_avoid(NodePath obstacle); }; diff --git a/contrib/src/ai/pathFollow.cxx b/contrib/src/ai/pathFollow.cxx index 576bb04f75..dd7720e318 100644 --- a/contrib/src/ai/pathFollow.cxx +++ b/contrib/src/ai/pathFollow.cxx @@ -23,7 +23,7 @@ void PathFollow::add_to_path(LVecBase3 pos) { /** * This function initiates the path follow behavior. */ -void PathFollow::start(string type) { +void PathFollow::start(std::string type) { _type = type; _start = true; if(_path.size() > 0) { diff --git a/contrib/src/ai/pathFollow.h b/contrib/src/ai/pathFollow.h index e2d09a27bc..16b221314e 100644 --- a/contrib/src/ai/pathFollow.h +++ b/contrib/src/ai/pathFollow.h @@ -13,18 +13,18 @@ class EXPCL_PANDAAI PathFollow { public: AICharacter *_ai_char; float _follow_weight; - vector _path; + std::vector _path; int _curr_path_waypoint; bool _start; NodePath _dummy; - string _type; + std::string _type; ClockObject *_myClock; float _time; PathFollow(AICharacter *ai_ch, float follow_wt); ~PathFollow(); void add_to_path(LVecBase3 pos); - void start(string type); + void start(std::string type); void do_follow(); bool check_if_possible(); }; diff --git a/contrib/src/rplight/gpuCommand.I b/contrib/src/rplight/gpuCommand.I index 3531eed2ba..0171442b08 100644 --- a/contrib/src/rplight/gpuCommand.I +++ b/contrib/src/rplight/gpuCommand.I @@ -74,7 +74,7 @@ inline float GPUCommand::convert_int_to_float(int v) const { */ inline void GPUCommand::push_float(float v) { if (_current_index >= GPU_COMMAND_ENTRIES) { - gpucommand_cat.error() << "Out of bounds! Exceeded command size of " << GPU_COMMAND_ENTRIES << endl; + gpucommand_cat.error() << "Out of bounds! Exceeded command size of " << GPU_COMMAND_ENTRIES << std::endl; return; } _data[_current_index++] = v; diff --git a/contrib/src/rplight/gpuCommand.cxx b/contrib/src/rplight/gpuCommand.cxx index 2bd468c902..0b977bc5bb 100644 --- a/contrib/src/rplight/gpuCommand.cxx +++ b/contrib/src/rplight/gpuCommand.cxx @@ -57,13 +57,13 @@ GPUCommand::GPUCommand(CommandType command_type) { * in mind that integers might be shown in their binary float representation, * depending on the setting in the GPUCommand::convert_int_to_float method. */ -void GPUCommand::write(ostream &out) const { - out << "GPUCommand(type=" << _command_type << ", size=" << _current_index << ", data = {" << endl; +void GPUCommand::write(std::ostream &out) const { + out << "GPUCommand(type=" << _command_type << ", size=" << _current_index << ", data = {" << std::endl; for (size_t k = 0; k < GPU_COMMAND_ENTRIES; ++k) { out << std::setw(12) << std::fixed << std::setprecision(5) << _data[k] << " "; - if (k % 6 == 5 || k == GPU_COMMAND_ENTRIES - 1) out << endl; + if (k % 6 == 5 || k == GPU_COMMAND_ENTRIES - 1) out << std::endl; } - out << "})" << endl; + out << "})" << std::endl; } /** diff --git a/contrib/src/rplight/gpuCommand.h b/contrib/src/rplight/gpuCommand.h index 7fa784b975..c6d5809b37 100644 --- a/contrib/src/rplight/gpuCommand.h +++ b/contrib/src/rplight/gpuCommand.h @@ -73,7 +73,7 @@ PUBLISHED: inline static bool get_uses_integer_packing(); void write_to(const PTA_uchar &dest, size_t command_index); - void write(ostream &out) const; + void write(std::ostream &out) const; private: diff --git a/contrib/src/rplight/gpuCommandList.h b/contrib/src/rplight/gpuCommandList.h index f2ec280116..1551afe630 100644 --- a/contrib/src/rplight/gpuCommandList.h +++ b/contrib/src/rplight/gpuCommandList.h @@ -48,7 +48,7 @@ PUBLISHED: MAKE_PROPERTY(num_commands, get_num_commands); protected: - queue _commands; + std::queue _commands; }; #endif // GPUCOMMANDLIST_H diff --git a/contrib/src/rplight/iesDataset.cxx b/contrib/src/rplight/iesDataset.cxx index 2975268138..9aafbf2f86 100644 --- a/contrib/src/rplight/iesDataset.cxx +++ b/contrib/src/rplight/iesDataset.cxx @@ -27,7 +27,9 @@ #include "iesDataset.h" +#ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES +#endif #include NotifyCategoryDef(iesdataset, "") @@ -139,7 +141,7 @@ float IESDataset::get_candela_value(float vertical_angle, float horizontal_angle iesdataset_cat.error() << "Invalid horizontal lerp: " << lerp << ", requested angle was " << horizontal_angle << ", prev = " << prev_angle << ", cur = " << curr_angle - << endl; + << std::endl; } return curr_value * lerp + prev_value * (1-lerp); @@ -190,7 +192,7 @@ float IESDataset::get_vertical_candela_value(size_t horizontal_angle_idx, float iesdataset_cat.error() << "ERROR: Invalid vertical lerp: " << lerp << ", requested angle was " << vertical_angle << ", prev = " << prev_angle << ", cur = " << curr_angle - << endl; + << std::endl; } return curr_value * lerp + prev_value * (1-lerp); diff --git a/contrib/src/rplight/internalLightManager.cxx b/contrib/src/rplight/internalLightManager.cxx index ea45c518fd..616e089cbc 100644 --- a/contrib/src/rplight/internalLightManager.cxx +++ b/contrib/src/rplight/internalLightManager.cxx @@ -29,6 +29,8 @@ #include +using std::endl; + NotifyCategoryDef(lightmgr, ""); @@ -133,7 +135,7 @@ void InternalLightManager::setup_shadows(RPLight* light) { } // Init all sources - for (int i = 0; i < num_sources; ++i) { + for (size_t i = 0; i < num_sources; ++i) { ShadowSource* source = light->get_shadow_source(i); // Set the source as dirty, so it gets updated in the beginning @@ -355,7 +357,7 @@ bool InternalLightManager::compare_shadow_sources(const ShadowSource* a, const S void InternalLightManager::update_shadow_sources() { // Find all dirty shadow sources and make a list of them - vector sources_to_update; + std::vector sources_to_update; for (auto iter = _shadow_sources.begin(); iter != _shadow_sources.end(); ++iter) { ShadowSource* source = *iter; if (source) { @@ -393,7 +395,7 @@ void InternalLightManager::update_shadow_sources() { // Free the regions of all sources which will get updated. We have to take into // account that only a limited amount of sources can get updated per frame. - size_t update_slots = min(sources_to_update.size(), + size_t update_slots = std::min(sources_to_update.size(), _shadow_manager->get_num_update_slots_left()); for(size_t i = 0; i < update_slots; ++i) { if (sources_to_update[i]->has_region()) { diff --git a/contrib/src/rplight/pointerSlotStorage.h b/contrib/src/rplight/pointerSlotStorage.h index 2d908c5795..d63594209b 100644 --- a/contrib/src/rplight/pointerSlotStorage.h +++ b/contrib/src/rplight/pointerSlotStorage.h @@ -45,6 +45,7 @@ class PointerSlotStorage {}; using std::tr1::array; #else #include +using std::array; #endif /** @@ -169,7 +170,7 @@ public: _num_entries--; // Update maximum index - if (slot == _max_index) { + if ((int)slot == _max_index) { while (_max_index >= 0 && !_data[_max_index--]); } } @@ -202,7 +203,7 @@ public: nassertv(slot >= 0 && slot < SIZE); nassertv(_data[slot] == nullptr); // Slot already taken! nassertv(ptr != nullptr); // nullptr passed as argument! - _max_index = max(_max_index, (int)slot); + _max_index = std::max(_max_index, (int)slot); _data[slot] = ptr; _num_entries++; } diff --git a/contrib/src/rplight/pssmCameraRig.cxx b/contrib/src/rplight/pssmCameraRig.cxx index b9560a80d2..8b8c22fd20 100644 --- a/contrib/src/rplight/pssmCameraRig.cxx +++ b/contrib/src/rplight/pssmCameraRig.cxx @@ -27,7 +27,9 @@ #include "pssmCameraRig.h" +#ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES +#endif #include #include "orthographicLens.h" diff --git a/contrib/src/rplight/pssmCameraRig.h b/contrib/src/rplight/pssmCameraRig.h index ce0567bbbf..33cefe6dc1 100644 --- a/contrib/src/rplight/pssmCameraRig.h +++ b/contrib/src/rplight/pssmCameraRig.h @@ -96,9 +96,9 @@ protected: inline LPoint3 get_interpolated_point(CoordinateOrigin origin, float depth); LVecBase3 get_snap_offset(const LMatrix4& mat, size_t resolution); - vector _cam_nodes; - vector _cameras; - vector _max_film_sizes; + std::vector _cam_nodes; + std::vector _cameras; + std::vector _max_film_sizes; // Current near and far points // Order: UL, UR, LL, LR (See CoordinateOrigin) diff --git a/contrib/src/rplight/rpLight.I b/contrib/src/rplight/rpLight.I index 9b21906310..c0e2422651 100644 --- a/contrib/src/rplight/rpLight.I +++ b/contrib/src/rplight/rpLight.I @@ -33,7 +33,7 @@ * * @return Amount of shadow sources */ -inline int RPLight::get_num_shadow_sources() const { +inline size_t RPLight::get_num_shadow_sources() const { return _shadow_sources.size(); } @@ -278,7 +278,7 @@ inline RPLight::LightType RPLight::get_light_type() const { */ inline void RPLight::set_casts_shadows(bool flag) { if (has_slot()) { - cerr << "Light is already attached, can not call set_casts_shadows!" << endl; + std::cerr << "Light is already attached, can not call set_casts_shadows!" << std::endl; return; } _casts_shadows = flag; diff --git a/contrib/src/rplight/rpLight.h b/contrib/src/rplight/rpLight.h index 13665c23ad..51bca24a76 100644 --- a/contrib/src/rplight/rpLight.h +++ b/contrib/src/rplight/rpLight.h @@ -57,7 +57,7 @@ public: virtual void update_shadow_sources() = 0; virtual void write_to_command(GPUCommand &cmd); - inline int get_num_shadow_sources() const; + inline size_t get_num_shadow_sources() const; inline ShadowSource* get_shadow_source(size_t index) const; inline void clear_shadow_sources(); @@ -122,7 +122,7 @@ protected: LightType _light_type; float _near_plane; - vector _shadow_sources; + std::vector _shadow_sources; }; #include "rpLight.I" diff --git a/contrib/src/rplight/rpSpotLight.cxx b/contrib/src/rplight/rpSpotLight.cxx index 649e0b1beb..3fd677a34c 100644 --- a/contrib/src/rplight/rpSpotLight.cxx +++ b/contrib/src/rplight/rpSpotLight.cxx @@ -27,7 +27,9 @@ #include "rpSpotLight.h" +#ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES +#endif #include diff --git a/contrib/src/rplight/shadowAtlas.I b/contrib/src/rplight/shadowAtlas.I index f48fc451f1..0b1812fa28 100644 --- a/contrib/src/rplight/shadowAtlas.I +++ b/contrib/src/rplight/shadowAtlas.I @@ -118,7 +118,7 @@ inline int ShadowAtlas::get_required_tiles(size_t resolution) const { if (resolution % _tile_size != 0) { shadowatlas_cat.error() << "Resolution " << resolution << " is not a multiple " - << "of the shadow atlas tile size (" << _tile_size << ")!" << endl; + << "of the shadow atlas tile size (" << _tile_size << ")!" << std::endl; return 1; } return resolution / _tile_size; diff --git a/contrib/src/rplight/shadowAtlas.cxx b/contrib/src/rplight/shadowAtlas.cxx index 15d4ea1bd0..2f76aae33d 100644 --- a/contrib/src/rplight/shadowAtlas.cxx +++ b/contrib/src/rplight/shadowAtlas.cxx @@ -131,13 +131,13 @@ LVecBase4i ShadowAtlas::find_and_reserve_region(size_t tile_width, size_t tile_h // Check for empty region if (tile_width < 1 || tile_height < 1) { - shadowatlas_cat.error() << "Called find_and_reserve_region with null-region!" << endl; + shadowatlas_cat.error() << "Called find_and_reserve_region with null-region!" << std::endl; return LVecBase4i(-1); } // Check for region bigger than the shadow atlas if (tile_width > _num_tiles || tile_height > _num_tiles) { - shadowatlas_cat.error() << "Requested region exceeds shadow atlas size!" << endl; + shadowatlas_cat.error() << "Requested region exceeds shadow atlas size!" << std::endl; return LVecBase4i(-1); } @@ -155,7 +155,7 @@ LVecBase4i ShadowAtlas::find_and_reserve_region(size_t tile_width, size_t tile_h // When we reached this part, we couldn't find a free region, so the atlas // seems to be full. shadowatlas_cat.error() << "Failed to find a free region of size " << tile_width - << " x " << tile_height << "!" << endl; + << " x " << tile_height << "!" << std::endl; return LVecBase4i(-1); } @@ -173,12 +173,12 @@ LVecBase4i ShadowAtlas::find_and_reserve_region(size_t tile_width, size_t tile_h void ShadowAtlas::free_region(const LVecBase4i& region) { // Out of bounds check, can't hurt nassertv(region.get_x() >= 0 && region.get_y() >= 0); - nassertv(region.get_x() + region.get_z() <= _num_tiles && region.get_y() + region.get_w() <= _num_tiles); + nassertv(region.get_x() + region.get_z() <= (int)_num_tiles && region.get_y() + region.get_w() <= (int)_num_tiles); _num_used_tiles -= region.get_z() * region.get_w(); - for (size_t x = 0; x < region.get_z(); ++x) { - for (size_t y = 0; y < region.get_w(); ++y) { + for (int x = 0; x < region.get_z(); ++x) { + for (int y = 0; y < region.get_w(); ++y) { // Could do an assert here, that the tile should have been used (=true) before set_tile(region.get_x() + x, region.get_y() + y, false); } diff --git a/contrib/src/rplight/shadowManager.I b/contrib/src/rplight/shadowManager.I index f5d87c463e..983c044f6f 100644 --- a/contrib/src/rplight/shadowManager.I +++ b/contrib/src/rplight/shadowManager.I @@ -52,7 +52,7 @@ inline void ShadowManager::set_max_updates(size_t max_updates) { nassertv(max_updates >= 0); nassertv(_atlas == nullptr); // ShadowManager was already initialized if (max_updates == 0) { - shadowmanager_cat.warning() << "max_updates set to 0, no shadows will be updated." << endl; + shadowmanager_cat.warning() << "max_updates set to 0, no shadows will be updated." << std::endl; } _max_updates = max_updates; } @@ -170,7 +170,7 @@ inline bool ShadowManager::add_update(const ShadowSource* source) { if (_queued_updates.size() >= _max_updates) { if (shadowmanager_cat.is_debug()) { - shadowmanager_cat.debug() << "cannot update source, out of update slots" << endl; + shadowmanager_cat.debug() << "cannot update source, out of update slots" << std::endl; } return false; } diff --git a/contrib/src/rplight/tagStateManager.I b/contrib/src/rplight/tagStateManager.I index 058832e60d..2da15e4ecd 100644 --- a/contrib/src/rplight/tagStateManager.I +++ b/contrib/src/rplight/tagStateManager.I @@ -35,7 +35,7 @@ * @param source Camera which will be used to render shadows */ inline void TagStateManager:: -register_camera(const string& name, Camera* source) { +register_camera(const std::string& name, Camera* source) { ContainerList::iterator entry = _containers.find(name); nassertv(entry != _containers.end()); register_camera(entry->second, source); @@ -49,7 +49,7 @@ register_camera(const string& name, Camera* source) { * @param source Camera to unregister */ inline void TagStateManager:: -unregister_camera(const string& name, Camera* source) { +unregister_camera(const std::string& name, Camera* source) { ContainerList::iterator entry = _containers.find(name); nassertv(entry != _containers.end()); unregister_camera(entry->second, source); @@ -67,8 +67,8 @@ unregister_camera(const string& name, Camera* source) { * @param sort Determines the sort with which the shader will be applied. */ inline void TagStateManager:: -apply_state(const string& state, NodePath np, Shader* shader, - const string &name, int sort) { +apply_state(const std::string& state, NodePath np, Shader* shader, + const std::string &name, int sort) { ContainerList::iterator entry = _containers.find(state); nassertv(entry != _containers.end()); apply_state(entry->second, np, shader, name, sort); @@ -83,7 +83,7 @@ apply_state(const string& state, NodePath np, Shader* shader, * @return Bit mask of the render pass */ inline BitMask32 TagStateManager:: -get_mask(const string &container_name) { +get_mask(const std::string &container_name) { if (container_name == "gbuffer") { return BitMask32::bit(1); } diff --git a/contrib/src/rplight/tagStateManager.cxx b/contrib/src/rplight/tagStateManager.cxx index ddc996f9a4..30653d1f79 100644 --- a/contrib/src/rplight/tagStateManager.cxx +++ b/contrib/src/rplight/tagStateManager.cxx @@ -27,6 +27,8 @@ #include "tagStateManager.h" +using std::endl; + NotifyCategoryDef(tagstatemgr, ""); @@ -77,7 +79,7 @@ TagStateManager:: */ void TagStateManager:: apply_state(StateContainer& container, NodePath np, Shader* shader, - const string &name, int sort) { + const std::string &name, int sort) { if (tagstatemgr_cat.is_spam()) { tagstatemgr_cat.spam() << "Constructing new state " << name << " with shader " << shader << endl; diff --git a/contrib/src/rplight/tagStateManager.h b/contrib/src/rplight/tagStateManager.h index 6c26e5cbf6..b05e364333 100644 --- a/contrib/src/rplight/tagStateManager.h +++ b/contrib/src/rplight/tagStateManager.h @@ -52,36 +52,36 @@ PUBLISHED: TagStateManager(NodePath main_cam_node); ~TagStateManager(); - inline void apply_state(const string& state, NodePath np, Shader* shader, const string &name, int sort); + inline void apply_state(const std::string& state, NodePath np, Shader* shader, const std::string &name, int sort); void cleanup_states(); - inline void register_camera(const string& state, Camera* source); - inline void unregister_camera(const string& state, Camera* source); - inline BitMask32 get_mask(const string &container_name); + inline void register_camera(const std::string& state, Camera* source); + inline void unregister_camera(const std::string& state, Camera* source); + inline BitMask32 get_mask(const std::string &container_name); private: - typedef vector CameraList; - typedef pmap TagStateList; + typedef std::vector CameraList; + typedef pmap TagStateList; struct StateContainer { CameraList cameras; TagStateList tag_states; - string tag_name; + std::string tag_name; BitMask32 mask; bool write_color; StateContainer() {}; - StateContainer(const string &tag_name, size_t mask, bool write_color) + StateContainer(const std::string &tag_name, size_t mask, bool write_color) : tag_name(tag_name), mask(BitMask32::bit(mask)), write_color(write_color) {}; }; void apply_state(StateContainer& container, NodePath np, Shader* shader, - const string& name, int sort); + const std::string& name, int sort); void cleanup_container_states(StateContainer& container); void register_camera(StateContainer &container, Camera* source); void unregister_camera(StateContainer &container, Camera* source); - typedef pmap ContainerList; + typedef pmap ContainerList; ContainerList _containers; NodePath _main_cam_node; diff --git a/direct/src/dcparse/dcparse.cxx b/direct/src/dcparse/dcparse.cxx index 3d02ef669c..b12323bb4a 100644 --- a/direct/src/dcparse/dcparse.cxx +++ b/direct/src/dcparse/dcparse.cxx @@ -19,6 +19,9 @@ #include "indent.h" #include "panda_getopt.h" +using std::cerr; +using std::cout; + void usage() { cerr << @@ -103,8 +106,8 @@ write_complete_field_list(const DCFile &file) { cout << field->get_class()->get_name() << "::"; } cout << field->get_name(); - if (field->as_atomic_field() != (DCAtomicField *)NULL || - field->as_molecular_field() != (DCMolecularField *)NULL) { + if (field->as_atomic_field() != nullptr || + field->as_molecular_field() != nullptr) { // It's a "method". cout << "()"; } diff --git a/direct/src/dcparser/dcArrayParameter.cxx b/direct/src/dcparser/dcArrayParameter.cxx index 7485a34a5d..2f2ea69932 100644 --- a/direct/src/dcparser/dcArrayParameter.cxx +++ b/direct/src/dcparser/dcArrayParameter.cxx @@ -16,6 +16,8 @@ #include "dcClassParameter.h" #include "hashGenerator.h" +using std::string; + /** * */ @@ -58,7 +60,7 @@ DCArrayParameter(DCParameter *element_type, const DCUnsignedIntRange &size) : _pack_type = PT_array; DCSimpleParameter *simple_type = _element_type->as_simple_parameter(); - if (simple_type != (DCSimpleParameter *)NULL) { + if (simple_type != nullptr) { if (simple_type->get_type() == ST_char) { // We make a special case for char[] arrays: these we format as a // string. (It will still accept an array of ints packed into it.) We @@ -148,7 +150,7 @@ get_array_size() const { */ DCParameter *DCArrayParameter:: append_array_specification(const DCUnsignedIntRange &size) { - if (get_typedef() != (DCTypedef *)NULL) { + if (get_typedef() != nullptr) { // If this was a typedef, wrap it directly. return new DCArrayParameter(this, size); } @@ -201,13 +203,13 @@ validate_num_nested_fields(int num_nested_fields) const { * identifier. */ void DCArrayParameter:: -output_instance(ostream &out, bool brief, const string &prename, +output_instance(std::ostream &out, bool brief, const string &prename, const string &name, const string &postname) const { - if (get_typedef() != (DCTypedef *)NULL) { + if (get_typedef() != nullptr) { output_typedef_name(out, brief, prename, name, postname); } else { - ostringstream strm; + std::ostringstream strm; strm << "["; _array_size_range.output(strm); @@ -236,7 +238,7 @@ pack_string(DCPackData &pack_data, const string &value, bool &pack_error, bool &range_error) const { // We can only pack a string if the array element type is char or int8. DCSimpleParameter *simple_type = _element_type->as_simple_parameter(); - if (simple_type == (DCSimpleParameter *)NULL) { + if (simple_type == nullptr) { pack_error = true; return; } @@ -306,7 +308,7 @@ unpack_string(const char *data, size_t length, size_t &p, string &value, bool &pack_error, bool &range_error) const { // We can only unpack a string if the array element type is char or int8. DCSimpleParameter *simple_type = _element_type->as_simple_parameter(); - if (simple_type == (DCSimpleParameter *)NULL) { + if (simple_type == nullptr) { pack_error = true; return; } diff --git a/direct/src/dcparser/dcArrayParameter.h b/direct/src/dcparser/dcArrayParameter.h index 10a8f022c2..fd5008fb97 100644 --- a/direct/src/dcparser/dcArrayParameter.h +++ b/direct/src/dcparser/dcArrayParameter.h @@ -46,14 +46,14 @@ public: virtual DCPackerInterface *get_nested_field(int n) const; virtual bool validate_num_nested_fields(int num_nested_fields) const; - virtual void output_instance(ostream &out, bool brief, const string &prename, - const string &name, const string &postname) const; + virtual void output_instance(std::ostream &out, bool brief, const std::string &prename, + const std::string &name, const std::string &postname) const; virtual void generate_hash(HashGenerator &hashgen) const; - virtual void pack_string(DCPackData &pack_data, const string &value, + virtual void pack_string(DCPackData &pack_data, const std::string &value, bool &pack_error, bool &range_error) const; virtual bool pack_default_value(DCPackData &pack_data, bool &pack_error) const; virtual void unpack_string(const char *data, size_t length, size_t &p, - string &value, bool &pack_error, bool &range_error) const; + std::string &value, bool &pack_error, bool &range_error) const; protected: virtual bool do_check_match(const DCPackerInterface *other) const; diff --git a/direct/src/dcparser/dcAtomicField.cxx b/direct/src/dcparser/dcAtomicField.cxx index 0d2ace8f35..3efebfa2d6 100644 --- a/direct/src/dcparser/dcAtomicField.cxx +++ b/direct/src/dcparser/dcAtomicField.cxx @@ -19,6 +19,8 @@ #include +using std::string; + /** * */ @@ -73,7 +75,7 @@ get_num_elements() const { */ DCParameter *DCAtomicField:: get_element(int n) const { - nassertr(n >= 0 && n < (int)_elements.size(), NULL); + nassertr(n >= 0 && n < (int)_elements.size(), nullptr); return _elements[n]; } @@ -127,7 +129,7 @@ DCSubatomicType DCAtomicField:: get_element_type(int n) const { nassertr(n >= 0 && n < (int)_elements.size(), ST_invalid); DCSimpleParameter *simple_parameter = _elements[n]->as_simple_parameter(); - nassertr(simple_parameter != (DCSimpleParameter *)NULL, ST_invalid); + nassertr(simple_parameter != nullptr, ST_invalid); return simple_parameter->get_type(); } @@ -143,7 +145,7 @@ int DCAtomicField:: get_element_divisor(int n) const { nassertr(n >= 0 && n < (int)_elements.size(), 1); DCSimpleParameter *simple_parameter = _elements[n]->as_simple_parameter(); - nassertr(simple_parameter != (DCSimpleParameter *)NULL, 1); + nassertr(simple_parameter != nullptr, 1); return simple_parameter->get_divisor(); } @@ -151,7 +153,7 @@ get_element_divisor(int n) const { * */ void DCAtomicField:: -output(ostream &out, bool brief) const { +output(std::ostream &out, bool brief) const { out << _name << "("; if (!_elements.empty()) { @@ -174,7 +176,7 @@ output(ostream &out, bool brief) const { * stream. */ void DCAtomicField:: -write(ostream &out, bool brief, int indent_level) const { +write(std::ostream &out, bool brief, int indent_level) const { indent(out, indent_level); output(out, brief); out << ";"; @@ -207,7 +209,7 @@ generate_hash(HashGenerator &hashgen) const { */ DCPackerInterface *DCAtomicField:: get_nested_field(int n) const { - nassertr(n >= 0 && n < (int)_elements.size(), NULL); + nassertr(n >= 0 && n < (int)_elements.size(), nullptr); return _elements[n]; } @@ -270,7 +272,7 @@ do_check_match_atomic_field(const DCAtomicField *other) const { * */ void DCAtomicField:: -output_element(ostream &out, bool brief, DCParameter *element) const { +output_element(std::ostream &out, bool brief, DCParameter *element) const { element->output(out, brief); if (!brief && element->has_default_value()) { diff --git a/direct/src/dcparser/dcAtomicField.h b/direct/src/dcparser/dcAtomicField.h index c002ecf15a..e0d7cee58e 100644 --- a/direct/src/dcparser/dcAtomicField.h +++ b/direct/src/dcparser/dcAtomicField.h @@ -29,7 +29,7 @@ */ class DCAtomicField : public DCField { public: - DCAtomicField(const string &name, DCClass *dclass, bool bogus_field); + DCAtomicField(const std::string &name, DCClass *dclass, bool bogus_field); virtual ~DCAtomicField(); PUBLISHED: @@ -40,17 +40,17 @@ PUBLISHED: DCParameter *get_element(int n) const; // These five methods are deprecated and will be removed soon. - string get_element_default(int n) const; + std::string get_element_default(int n) const; bool has_element_default(int n) const; - string get_element_name(int n) const; + std::string get_element_name(int n) const; DCSubatomicType get_element_type(int n) const; int get_element_divisor(int n) const; public: void add_element(DCParameter *element); - virtual void output(ostream &out, bool brief) const; - virtual void write(ostream &out, bool brief, int indent_level) const; + virtual void output(std::ostream &out, bool brief) const; + virtual void write(std::ostream &out, bool brief, int indent_level) const; virtual void generate_hash(HashGenerator &hashgen) const; virtual DCPackerInterface *get_nested_field(int n) const; @@ -60,7 +60,7 @@ protected: virtual bool do_check_match_atomic_field(const DCAtomicField *other) const; private: - void output_element(ostream &out, bool brief, DCParameter *element) const; + void output_element(std::ostream &out, bool brief, DCParameter *element) const; typedef pvector Elements; Elements _elements; diff --git a/direct/src/dcparser/dcClass.I b/direct/src/dcparser/dcClass.I index a33fe53bc5..edba84f726 100644 --- a/direct/src/dcparser/dcClass.I +++ b/direct/src/dcparser/dcClass.I @@ -22,7 +22,7 @@ get_dc_file() const { /** * Returns the name of this class. */ -INLINE const string &DCClass:: +INLINE const std::string &DCClass:: get_name() const { return _name; } diff --git a/direct/src/dcparser/dcClass.cxx b/direct/src/dcparser/dcClass.cxx index d11a116415..4c428db595 100644 --- a/direct/src/dcparser/dcClass.cxx +++ b/direct/src/dcparser/dcClass.cxx @@ -25,6 +25,10 @@ #include "py_panda.h" #endif +using std::ostream; +using std::ostringstream; +using std::string; + #ifdef WITHIN_PANDA #include "pStatTimer.h" @@ -80,11 +84,11 @@ DCClass(DCFile *dc_file, const string &name, bool is_struct, bool bogus_class) : _bogus_class(bogus_class) { _number = -1; - _constructor = NULL; + _constructor = nullptr; #ifdef HAVE_PYTHON - _class_def = NULL; - _owner_class_def = NULL; + _class_def = nullptr; + _owner_class_def = nullptr; #endif } @@ -93,7 +97,7 @@ DCClass(DCFile *dc_file, const string &name, bool is_struct, bool bogus_class) : */ DCClass:: ~DCClass() { - if (_constructor != (DCField *)NULL) { + if (_constructor != nullptr) { delete _constructor; } @@ -137,7 +141,7 @@ get_num_parents() const { */ DCClass *DCClass:: get_parent(int n) const { - nassertr(n >= 0 && n < (int)_parents.size(), NULL); + nassertr(n >= 0 && n < (int)_parents.size(), nullptr); return _parents[n]; } @@ -147,7 +151,7 @@ get_parent(int n) const { */ bool DCClass:: has_constructor() const { - return (_constructor != (DCField *)NULL); + return (_constructor != nullptr); } /** @@ -177,13 +181,13 @@ DCField *DCClass:: get_field(int n) const { #ifndef NDEBUG //[ if (n < 0 || n >= (int)_fields.size()) { - cerr << *this << " " + std::cerr << *this << " " << "n:" << n << " _fields.size():" - << (int)_fields.size() << endl; + << (int)_fields.size() << std::endl; // __asm { int 3 } } #endif //] - nassertr_always(n >= 0 && n < (int)_fields.size(), NULL); + nassertr_always(n >= 0 && n < (int)_fields.size(), nullptr); return _fields[n]; } @@ -205,13 +209,13 @@ get_field_by_name(const string &name) const { Parents::const_iterator pi; for (pi = _parents.begin(); pi != _parents.end(); ++pi) { DCField *result = (*pi)->get_field_by_name(name); - if (result != (DCField *)NULL) { + if (result != nullptr) { return result; } } // Nobody knew what this field is. - return (DCField *)NULL; + return nullptr; } /** @@ -232,7 +236,7 @@ get_field_by_index(int index_number) const { Parents::const_iterator pi; for (pi = _parents.begin(); pi != _parents.end(); ++pi) { DCField *result = (*pi)->get_field_by_index(index_number); - if (result != (DCField *)NULL) { + if (result != nullptr) { // Cache this result for future lookups. ((DCClass *)this)->_fields_by_index[index_number] = result; return result; @@ -240,7 +244,7 @@ get_field_by_index(int index_number) const { } // Nobody knew what this field is. - return (DCField *)NULL; + return nullptr; } /** @@ -250,7 +254,7 @@ get_field_by_index(int index_number) const { int DCClass:: get_num_inherited_fields() const { if (dc_multiple_inheritance && dc_virtual_inheritance && - _dc_file != (DCFile *)NULL) { + _dc_file != nullptr) { _dc_file->check_inherited_fields(); if (_inherited_fields.empty()) { ((DCClass *)this)->rebuild_inherited_fields(); @@ -283,12 +287,12 @@ get_num_inherited_fields() const { DCField *DCClass:: get_inherited_field(int n) const { if (dc_multiple_inheritance && dc_virtual_inheritance && - _dc_file != (DCFile *)NULL) { + _dc_file != nullptr) { _dc_file->check_inherited_fields(); if (_inherited_fields.empty()) { ((DCClass *)this)->rebuild_inherited_fields(); } - nassertr(n >= 0 && n < (int)_inherited_fields.size(), NULL); + nassertr(n >= 0 && n < (int)_inherited_fields.size(), nullptr); return _inherited_fields[n]; } else { @@ -349,7 +353,7 @@ output(ostream &out) const { */ bool DCClass:: has_class_def() const { - return (_class_def != NULL); + return (_class_def != nullptr); } #endif // HAVE_PYTHON @@ -373,7 +377,7 @@ set_class_def(PyObject *class_def) { */ PyObject *DCClass:: get_class_def() const { - if (_class_def == NULL) { + if (_class_def == nullptr) { Py_INCREF(Py_None); return Py_None; } @@ -390,7 +394,7 @@ get_class_def() const { */ bool DCClass:: has_owner_class_def() const { - return (_owner_class_def != NULL); + return (_owner_class_def != nullptr); } #endif // HAVE_PYTHON @@ -414,7 +418,7 @@ set_owner_class_def(PyObject *owner_class_def) { */ PyObject *DCClass:: get_owner_class_def() const { - if (_owner_class_def == NULL) { + if (_owner_class_def == nullptr) { Py_INCREF(Py_None); return Py_None; } @@ -441,7 +445,7 @@ receive_update(PyObject *distobj, DatagramIterator &di) const { int field_id = packer.raw_unpack_uint16(); DCField *field = get_field_by_index(field_id); - if (field == (DCField *)NULL) { + if (field == nullptr) { ostringstream strm; strm << "Received update for field " << field_id << ", not in class " @@ -478,7 +482,7 @@ receive_update_broadcast_required(PyObject *distobj, DatagramIterator &di) const int num_fields = get_num_inherited_fields(); for (int i = 0; i < num_fields && !PyErr_Occurred(); ++i) { DCField *field = get_inherited_field(i); - if (field->as_molecular_field() == (DCMolecularField *)NULL && + if (field->as_molecular_field() == nullptr && field->is_required() && field->is_broadcast()) { packer.begin_unpack(field); field->receive_update(packer, distobj); @@ -513,7 +517,7 @@ receive_update_broadcast_required_owner(PyObject *distobj, int num_fields = get_num_inherited_fields(); for (int i = 0; i < num_fields && !PyErr_Occurred(); ++i) { DCField *field = get_inherited_field(i); - if (field->as_molecular_field() == (DCMolecularField *)NULL && + if (field->as_molecular_field() == nullptr && field->is_required() && (field->is_ownrecv() || field->is_broadcast())) { packer.begin_unpack(field); field->receive_update(packer, distobj); @@ -546,7 +550,7 @@ receive_update_all_required(PyObject *distobj, DatagramIterator &di) const { int num_fields = get_num_inherited_fields(); for (int i = 0; i < num_fields && !PyErr_Occurred(); ++i) { DCField *field = get_inherited_field(i); - if (field->as_molecular_field() == (DCMolecularField *)NULL && + if (field->as_molecular_field() == nullptr && field->is_required()) { packer.begin_unpack(field); field->receive_update(packer, distobj); @@ -585,7 +589,7 @@ void DCClass:: direct_update(PyObject *distobj, const string &field_name, const string &value_blob) { DCField *field = get_field_by_name(field_name); - nassertv_always(field != NULL); + nassertv_always(field != nullptr); DCPacker packer; packer.set_unpack_data(value_blob); @@ -645,7 +649,7 @@ bool DCClass:: pack_required_field(DCPacker &packer, PyObject *distobj, const DCField *field) const { const DCParameter *parameter = field->as_parameter(); - if (parameter != (DCParameter *)NULL) { + if (parameter != nullptr) { // This is the easy case: to pack a parameter, we just look on the class // object for the data element. string field_name = field->get_name(); @@ -668,7 +672,7 @@ pack_required_field(DCPacker &packer, PyObject *distobj, } PyObject *result = PyObject_GetAttrString(distobj, (char *)field_name.c_str()); - nassertr(result != (PyObject *)NULL, false); + nassertr(result != nullptr, false); // Now pack the value into the datagram. bool pack_ok = parameter->pack_args(packer, result); @@ -677,7 +681,7 @@ pack_required_field(DCPacker &packer, PyObject *distobj, return pack_ok; } - if (field->as_molecular_field() != (DCMolecularField *)NULL) { + if (field->as_molecular_field() != nullptr) { ostringstream strm; strm << "Cannot pack molecular field " << field->get_name() << " for generate"; @@ -686,7 +690,7 @@ pack_required_field(DCPacker &packer, PyObject *distobj, } const DCAtomicField *atom = field->as_atomic_field(); - nassertr(atom != (DCAtomicField *)NULL, false); + nassertr(atom != nullptr, false); // We need to get the initial value of this field. There isn't a good, // robust way to get this; presently, we just mangle the "setFoo()" name of @@ -740,16 +744,16 @@ pack_required_field(DCPacker &packer, PyObject *distobj, } PyObject *func = PyObject_GetAttrString(distobj, (char *)getter_name.c_str()); - nassertr(func != (PyObject *)NULL, false); + nassertr(func != nullptr, false); PyObject *empty_args = PyTuple_New(0); PyObject *result = PyObject_CallObject(func, empty_args); Py_DECREF(empty_args); Py_DECREF(func); - if (result == (PyObject *)NULL) { + if (result == nullptr) { // We don't set this as an exception, since presumably the Python method // itself has already triggered a Python exception. - cerr << "Error when calling " << getter_name << "\n"; + std::cerr << "Error when calling " << getter_name << "\n"; return false; } @@ -789,7 +793,7 @@ Datagram DCClass:: client_format_update(const string &field_name, DOID_TYPE do_id, PyObject *args) const { DCField *field = get_field_by_name(field_name); - if (field == (DCField *)NULL) { + if (field == nullptr) { ostringstream strm; strm << "No field named " << field_name << " in class " << get_name() << "\n"; @@ -810,7 +814,7 @@ Datagram DCClass:: ai_format_update(const string &field_name, DOID_TYPE do_id, CHANNEL_TYPE to_id, CHANNEL_TYPE from_id, PyObject *args) const { DCField *field = get_field_by_name(field_name); - if (field == (DCField *)NULL) { + if (field == nullptr) { ostringstream strm; strm << "No field named " << field_name << " in class " << get_name() << "\n"; @@ -832,7 +836,7 @@ Datagram DCClass:: ai_format_update_msg_type(const string &field_name, DOID_TYPE do_id, CHANNEL_TYPE to_id, CHANNEL_TYPE from_id, int msg_type, PyObject *args) const { DCField *field = get_field_by_name(field_name); - if (field == (DCField *)NULL) { + if (field == nullptr) { ostringstream strm; strm << "No field named " << field_name << " in class " << get_name() << "\n"; @@ -871,7 +875,7 @@ client_format_generate_CMU(PyObject *distobj, DOID_TYPE do_id, int num_fields = get_num_inherited_fields(); for (int i = 0; i < num_fields; ++i) { DCField *field = get_inherited_field(i); - if (field->is_required() && field->as_molecular_field() == NULL) { + if (field->is_required() && field->as_molecular_field() == nullptr) { packer.begin_pack(field); if (!pack_required_field(packer, distobj, field)) { return Datagram(); @@ -897,7 +901,7 @@ client_format_generate_CMU(PyObject *distobj, DOID_TYPE do_id, Py_XDECREF(py_field_name); DCField *field = get_field_by_name(field_name); - if (field == (DCField *)NULL) { + if (field == nullptr) { ostringstream strm; strm << "No field named " << field_name << " in class " << get_name() << "\n"; @@ -956,7 +960,7 @@ ai_format_generate(PyObject *distobj, DOID_TYPE do_id, int num_fields = get_num_inherited_fields(); for (int i = 0; i < num_fields; ++i) { DCField *field = get_inherited_field(i); - if (field->is_required() && field->as_molecular_field() == NULL) { + if (field->is_required() && field->as_molecular_field() == nullptr) { packer.begin_pack(field); if (!pack_required_field(packer, distobj, field)) { return Datagram(); @@ -980,7 +984,7 @@ ai_format_generate(PyObject *distobj, DOID_TYPE do_id, Py_XDECREF(py_field_name); DCField *field = get_field_by_name(field_name); - if (field == (DCField *)NULL) { + if (field == nullptr) { ostringstream strm; strm << "No field named " << field_name << " in class " << get_name() << "\n"; @@ -1042,7 +1046,7 @@ write(ostream &out, bool brief, int indent_level) const { } out << "\n"; - if (_constructor != (DCField *)NULL) { + if (_constructor != nullptr) { _constructor->write(out, brief, indent_level + 2); } @@ -1098,7 +1102,7 @@ output_instance(ostream &out, bool brief, const string &prename, out << " {"; - if (_constructor != (DCField *)NULL) { + if (_constructor != nullptr) { _constructor->output(out, brief); out << "; "; } @@ -1134,7 +1138,7 @@ generate_hash(HashGenerator &hashgen) const { hashgen.add_int((*pi)->get_number()); } - if (_constructor != (DCField *)NULL) { + if (_constructor != nullptr) { _constructor->generate_hash(hashgen); } @@ -1247,20 +1251,20 @@ shadow_inherited_field(const string &name) { */ bool DCClass:: add_field(DCField *field) { - nassertr(field->get_class() == this || field->get_class() == NULL, false); + nassertr(field->get_class() == this || field->get_class() == nullptr, false); field->set_class(this); - if (_dc_file != (DCFile *)NULL) { + if (_dc_file != nullptr) { _dc_file->mark_inherited_fields_stale(); } if (!field->get_name().empty()) { if (field->get_name() == _name) { // This field is a constructor. - if (_constructor != (DCField *)NULL) { + if (_constructor != nullptr) { // We already have a constructor. return false; } - if (field->as_atomic_field() == (DCAtomicField *)NULL) { + if (field->as_atomic_field() == nullptr) { // The constructor must be an atomic field. return false; } @@ -1278,7 +1282,7 @@ add_field(DCField *field) { } } - if (_dc_file != (DCFile *)NULL && + if (_dc_file != nullptr && ((dc_virtual_inheritance && dc_sort_inheritance_by_file) || !is_struct())) { if (dc_multiple_inheritance) { _dc_file->set_new_index_number(field); diff --git a/direct/src/dcparser/dcClass.h b/direct/src/dcparser/dcClass.h index 73ad9e43d3..9f7945b372 100644 --- a/direct/src/dcparser/dcClass.h +++ b/direct/src/dcparser/dcClass.h @@ -43,7 +43,7 @@ class DCParameter; */ class DCClass : public DCDeclaration { public: - DCClass(DCFile *dc_file, const string &name, + DCClass(DCFile *dc_file, const std::string &name, bool is_struct, bool bogus_class); ~DCClass(); @@ -53,7 +53,7 @@ PUBLISHED: INLINE DCFile *get_dc_file() const; - INLINE const string &get_name() const; + INLINE const std::string &get_name() const; INLINE int get_number() const; int get_num_parents() const; @@ -65,7 +65,7 @@ PUBLISHED: int get_num_fields() const; DCField *get_field(int n) const; - DCField *get_field_by_name(const string &name) const; + DCField *get_field_by_name(const std::string &name) const; DCField *get_field_by_index(int index_number) const; int get_num_inherited_fields() const; @@ -78,7 +78,7 @@ PUBLISHED: INLINE void start_generate(); INLINE void stop_generate(); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; #ifdef HAVE_PYTHON bool has_class_def() const; @@ -94,9 +94,9 @@ PUBLISHED: void receive_update_all_required(PyObject *distobj, DatagramIterator &di) const; void receive_update_other(PyObject *distobj, DatagramIterator &di) const; - void direct_update(PyObject *distobj, const string &field_name, - const string &value_blob); - void direct_update(PyObject *distobj, const string &field_name, + void direct_update(PyObject *distobj, const std::string &field_name, + const std::string &value_blob); + void direct_update(PyObject *distobj, const std::string &field_name, const Datagram &datagram); bool pack_required_field(Datagram &datagram, PyObject *distobj, const DCField *field) const; @@ -105,11 +105,11 @@ PUBLISHED: - Datagram client_format_update(const string &field_name, + Datagram client_format_update(const std::string &field_name, DOID_TYPE do_id, PyObject *args) const; - Datagram ai_format_update(const string &field_name, DOID_TYPE do_id, + Datagram ai_format_update(const std::string &field_name, DOID_TYPE do_id, CHANNEL_TYPE to_id, CHANNEL_TYPE from_id, PyObject *args) const; - Datagram ai_format_update_msg_type(const string &field_name, DOID_TYPE do_id, + Datagram ai_format_update_msg_type(const std::string &field_name, DOID_TYPE do_id, CHANNEL_TYPE to_id, CHANNEL_TYPE from_id, int msg_type, PyObject *args) const; Datagram ai_format_generate(PyObject *distobj, DOID_TYPE do_id, ZONEID_TYPE parent_id, ZONEID_TYPE zone_id, CHANNEL_TYPE district_channel_id, CHANNEL_TYPE from_channel_id, @@ -120,10 +120,10 @@ PUBLISHED: #endif public: - virtual void output(ostream &out, bool brief) const; - virtual void write(ostream &out, bool brief, int indent_level) const; - void output_instance(ostream &out, bool brief, const string &prename, - const string &name, const string &postname) const; + virtual void output(std::ostream &out, bool brief) const; + virtual void write(std::ostream &out, bool brief, int indent_level) const; + void output_instance(std::ostream &out, bool brief, const std::string &prename, + const std::string &name, const std::string &postname) const; void generate_hash(HashGenerator &hashgen) const; void clear_inherited_fields(); void rebuild_inherited_fields(); @@ -133,7 +133,7 @@ public: void set_number(int number); private: - void shadow_inherited_field(const string &name); + void shadow_inherited_field(const std::string &name); #ifdef WITHIN_PANDA PStatCollector _class_update_pcollector; @@ -144,7 +144,7 @@ private: DCFile *_dc_file; - string _name; + std::string _name; bool _is_struct; bool _bogus_class; int _number; @@ -157,7 +157,7 @@ private: typedef pvector Fields; Fields _fields, _inherited_fields; - typedef pmap FieldsByName; + typedef pmap FieldsByName; FieldsByName _fields_by_name; typedef pmap FieldsByIndex; diff --git a/direct/src/dcparser/dcClassParameter.cxx b/direct/src/dcparser/dcClassParameter.cxx index be5ca00283..a3bc68d5eb 100644 --- a/direct/src/dcparser/dcClassParameter.cxx +++ b/direct/src/dcparser/dcClassParameter.cxx @@ -119,7 +119,7 @@ get_class() const { */ DCPackerInterface *DCClassParameter:: get_nested_field(int n) const { - nassertr(n >= 0 && n < (int)_nested_fields.size(), NULL); + nassertr(n >= 0 && n < (int)_nested_fields.size(), nullptr); return _nested_fields[n]; } @@ -128,9 +128,9 @@ get_nested_field(int n) const { * identifier. */ void DCClassParameter:: -output_instance(ostream &out, bool brief, const string &prename, - const string &name, const string &postname) const { - if (get_typedef() != (DCTypedef *)NULL) { +output_instance(std::ostream &out, bool brief, const std::string &prename, + const std::string &name, const std::string &postname) const { + if (get_typedef() != nullptr) { output_typedef_name(out, brief, prename, name, postname); } else { diff --git a/direct/src/dcparser/dcClassParameter.h b/direct/src/dcparser/dcClassParameter.h index e846d48f88..3657190bf9 100644 --- a/direct/src/dcparser/dcClassParameter.h +++ b/direct/src/dcparser/dcClassParameter.h @@ -39,8 +39,8 @@ PUBLISHED: public: virtual DCPackerInterface *get_nested_field(int n) const; - virtual void output_instance(ostream &out, bool brief, const string &prename, - const string &name, const string &postname) const; + virtual void output_instance(std::ostream &out, bool brief, const std::string &prename, + const std::string &name, const std::string &postname) const; virtual void generate_hash(HashGenerator &hashgen) const; protected: diff --git a/direct/src/dcparser/dcDeclaration.cxx b/direct/src/dcparser/dcDeclaration.cxx index fd86238b4a..bf8830f046 100644 --- a/direct/src/dcparser/dcDeclaration.cxx +++ b/direct/src/dcparser/dcDeclaration.cxx @@ -26,7 +26,7 @@ DCDeclaration:: */ DCClass *DCDeclaration:: as_class() { - return (DCClass *)NULL; + return nullptr; } /** @@ -34,7 +34,7 @@ as_class() { */ const DCClass *DCDeclaration:: as_class() const { - return (DCClass *)NULL; + return nullptr; } /** @@ -42,7 +42,7 @@ as_class() const { */ DCSwitch *DCDeclaration:: as_switch() { - return (DCSwitch *)NULL; + return nullptr; } /** @@ -50,14 +50,14 @@ as_switch() { */ const DCSwitch *DCDeclaration:: as_switch() const { - return (DCSwitch *)NULL; + return nullptr; } /** * Write a string representation of this instance to . */ void DCDeclaration:: -output(ostream &out) const { +output(std::ostream &out) const { output(out, true); } @@ -65,6 +65,6 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void DCDeclaration:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { write(out, false, indent_level); } diff --git a/direct/src/dcparser/dcDeclaration.h b/direct/src/dcparser/dcDeclaration.h index 218473aef4..0fd4392ca6 100644 --- a/direct/src/dcparser/dcDeclaration.h +++ b/direct/src/dcparser/dcDeclaration.h @@ -36,15 +36,15 @@ PUBLISHED: virtual DCSwitch *as_switch(); virtual const DCSwitch *as_switch() const; - virtual void output(ostream &out) const; - void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level) const; public: - virtual void output(ostream &out, bool brief) const=0; - virtual void write(ostream &out, bool brief, int indent_level) const=0; + virtual void output(std::ostream &out, bool brief) const=0; + virtual void write(std::ostream &out, bool brief, int indent_level) const=0; }; -INLINE ostream &operator << (ostream &out, const DCDeclaration &decl) { +INLINE std::ostream &operator << (std::ostream &out, const DCDeclaration &decl) { decl.output(out); return out; } diff --git a/direct/src/dcparser/dcField.I b/direct/src/dcparser/dcField.I index 24a14cff08..aabf5cf114 100644 --- a/direct/src/dcparser/dcField.I +++ b/direct/src/dcparser/dcField.I @@ -42,7 +42,7 @@ has_default_value() const { * explicitly set (e.g. has_default_value() returns true), returns that * value; otherwise, returns an implicit default for the field. */ -INLINE const string &DCField:: +INLINE const std::string &DCField:: get_default_value() const { if (_default_value_stale) { ((DCField *)this)->refresh_default_value(); @@ -138,7 +138,7 @@ is_airecv() const { * Write a string representation of this instance to . */ INLINE void DCField:: -output(ostream &out) const { +output(std::ostream &out) const { output(out, true); } @@ -146,7 +146,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ INLINE void DCField:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { write(out, false, indent_level); } @@ -172,7 +172,7 @@ set_class(DCClass *dclass) { * Establishes a default value for this field. */ INLINE void DCField:: -set_default_value(const string &default_value) { +set_default_value(const std::string &default_value) { _default_value = default_value; _has_default_value = true; _default_value_stale = false; diff --git a/direct/src/dcparser/dcField.cxx b/direct/src/dcparser/dcField.cxx index a44412638a..4f255dea7d 100644 --- a/direct/src/dcparser/dcField.cxx +++ b/direct/src/dcparser/dcField.cxx @@ -26,12 +26,14 @@ #include "pStatTimer.h" #endif +using std::string; + /** * */ DCField:: DCField() : - _dclass(NULL) + _dclass(nullptr) #ifdef WITHIN_PANDA , _field_update_pcollector("DCField") @@ -108,7 +110,7 @@ as_field() const { */ DCAtomicField *DCField:: as_atomic_field() { - return (DCAtomicField *)NULL; + return nullptr; } /** @@ -117,7 +119,7 @@ as_atomic_field() { */ const DCAtomicField *DCField:: as_atomic_field() const { - return (DCAtomicField *)NULL; + return nullptr; } /** @@ -126,7 +128,7 @@ as_atomic_field() const { */ DCMolecularField *DCField:: as_molecular_field() { - return (DCMolecularField *)NULL; + return nullptr; } /** @@ -135,7 +137,7 @@ as_molecular_field() { */ const DCMolecularField *DCField:: as_molecular_field() const { - return (DCMolecularField *)NULL; + return nullptr; } /** @@ -143,7 +145,7 @@ as_molecular_field() const { */ DCParameter *DCField:: as_parameter() { - return (DCParameter *)NULL; + return nullptr; } /** @@ -151,7 +153,7 @@ as_parameter() { */ const DCParameter *DCField:: as_parameter() const { - return (DCParameter *)NULL; + return nullptr; } /** @@ -232,10 +234,10 @@ pack_args(DCPacker &packer, PyObject *sequence) const { } if (!Notify::ptr()->has_assert_failed()) { - ostringstream strm; + std::ostringstream strm; PyObject *exc_type = PyExc_Exception; - if (as_parameter() != (DCParameter *)NULL) { + if (as_parameter() != nullptr) { // If it's a parameter-type field, the value may or may not be a // sequence. if (packer.had_pack_error()) { @@ -251,7 +253,7 @@ pack_args(DCPacker &packer, PyObject *sequence) const { } else { // If it's a molecular or atomic field, the value should be a sequence. PyObject *tuple = PySequence_Tuple(sequence); - if (tuple == (PyObject *)NULL) { + if (tuple == nullptr) { strm << "Value for " << get_name() << " not a sequence: " \ << get_pystr(sequence); exc_type = PyExc_TypeError; @@ -287,8 +289,8 @@ pack_args(DCPacker &packer, PyObject *sequence) const { */ PyObject *DCField:: unpack_args(DCPacker &packer) const { - nassertr(!packer.had_error(), NULL); - nassertr(packer.get_current_field() == this, NULL); + nassertr(!packer.had_error(), nullptr); + nassertr(packer.get_current_field() == this, nullptr); size_t start_byte = packer.get_num_unpacked_bytes(); PyObject *object = packer.unpack_object(); @@ -303,7 +305,7 @@ unpack_args(DCPacker &packer) const { } if (!Notify::ptr()->has_assert_failed()) { - ostringstream strm; + std::ostringstream strm; PyObject *exc_type = PyExc_Exception; if (packer.had_pack_error()) { @@ -315,7 +317,7 @@ unpack_args(DCPacker &packer) const { dg.dump_hex(strm); size_t error_byte = packer.get_num_unpacked_bytes() - start_byte; strm << "Error detected on byte " << error_byte - << " (" << hex << error_byte << dec << " hex)"; + << " (" << std::hex << error_byte << std::dec << " hex)"; exc_type = PyExc_RuntimeError; } else { @@ -329,7 +331,7 @@ unpack_args(DCPacker &packer) const { } Py_XDECREF(object); - return NULL; + return nullptr; } #endif // HAVE_PYTHON @@ -340,10 +342,10 @@ unpack_args(DCPacker &packer) const { */ void DCField:: receive_update(DCPacker &packer, PyObject *distobj) const { - if (as_parameter() != (DCParameter *)NULL) { + if (as_parameter() != nullptr) { // If it's a parameter-type field, just store a new value on the object. PyObject *value = unpack_args(packer); - if (value != (PyObject *)NULL) { + if (value != nullptr) { PyObject_SetAttrString(distobj, (char *)_name.c_str(), value); } Py_DECREF(value); @@ -362,9 +364,9 @@ receive_update(DCPacker &packer, PyObject *distobj) const { // method. PyObject *args = unpack_args(packer); - if (args != (PyObject *)NULL) { + if (args != nullptr) { PyObject *func = PyObject_GetAttrString(distobj, (char *)_name.c_str()); - nassertv(func != (PyObject *)NULL); + nassertv(func != nullptr); PyObject *result; { @@ -499,7 +501,7 @@ pack_default_value(DCPackData &pack_data, bool &) const { void DCField:: set_name(const string &name) { DCPackerInterface::set_name(name); - if (_dclass != (DCClass *)NULL) { + if (_dclass != nullptr) { _dclass->_dc_file->mark_inherited_fields_stale(); } } @@ -510,12 +512,12 @@ set_name(const string &name) { */ string DCField:: get_pystr(PyObject *value) { - if (value == NULL) { + if (value == nullptr) { return "(null)"; } PyObject *str = PyObject_Str(value); - if (str != NULL) { + if (str != nullptr) { #if PY_MAJOR_VERSION >= 3 string result = PyUnicode_AsUTF8(str); #else @@ -526,7 +528,7 @@ get_pystr(PyObject *value) { } PyObject *repr = PyObject_Repr(value); - if (repr != NULL) { + if (repr != nullptr) { #if PY_MAJOR_VERSION >= 3 string result = PyUnicode_AsUTF8(repr); #else @@ -536,9 +538,9 @@ get_pystr(PyObject *value) { return result; } - if (value->ob_type != NULL) { + if (value->ob_type != nullptr) { PyObject *typestr = PyObject_Str((PyObject *)(value->ob_type)); - if (typestr != NULL) { + if (typestr != nullptr) { #if PY_MAJOR_VERSION >= 3 string result = PyUnicode_AsUTF8(typestr); #else @@ -562,7 +564,7 @@ refresh_default_value() { packer.begin_pack(this); packer.pack_default_value(); if (!packer.end_pack()) { - cerr << "Error while packing default value for " << get_name() << "\n"; + std::cerr << "Error while packing default value for " << get_name() << "\n"; } else { _default_value.assign(packer.get_data(), packer.get_length()); } diff --git a/direct/src/dcparser/dcField.h b/direct/src/dcparser/dcField.h index e7f2dbcd3c..6744ea93d4 100644 --- a/direct/src/dcparser/dcField.h +++ b/direct/src/dcparser/dcField.h @@ -37,7 +37,7 @@ class HashGenerator; class DCField : public DCPackerInterface, public DCKeywordList { public: DCField(); - DCField(const string &name, DCClass *dclass); + DCField(const std::string &name, DCClass *dclass); virtual ~DCField(); PUBLISHED: @@ -53,13 +53,13 @@ PUBLISHED: virtual DCParameter *as_parameter(); virtual const DCParameter *as_parameter() const; - string format_data(const string &packed_data, bool show_field_names = true); - string parse_string(const string &formatted_string); + std::string format_data(const std::string &packed_data, bool show_field_names = true); + std::string parse_string(const std::string &formatted_string); - bool validate_ranges(const string &packed_data) const; + bool validate_ranges(const std::string &packed_data) const; INLINE bool has_default_value() const; - INLINE const string &get_default_value() const; + INLINE const std::string &get_default_value() const; INLINE bool is_bogus_field() const; @@ -73,8 +73,8 @@ PUBLISHED: INLINE bool is_ownrecv() const; INLINE bool is_airecv() const; - INLINE void output(ostream &out) const; - INLINE void write(ostream &out, int indent_level) const; + INLINE void output(std::ostream &out) const; + INLINE void write(std::ostream &out, int indent_level) const; #ifdef HAVE_PYTHON bool pack_args(DCPacker &packer, PyObject *sequence) const; @@ -90,18 +90,18 @@ PUBLISHED: #endif public: - virtual void output(ostream &out, bool brief) const=0; - virtual void write(ostream &out, bool brief, int indent_level) const=0; + virtual void output(std::ostream &out, bool brief) const=0; + virtual void write(std::ostream &out, bool brief, int indent_level) const=0; virtual void generate_hash(HashGenerator &hashgen) const; virtual bool pack_default_value(DCPackData &pack_data, bool &pack_error) const; - virtual void set_name(const string &name); + virtual void set_name(const std::string &name); INLINE void set_number(int number); INLINE void set_class(DCClass *dclass); - INLINE void set_default_value(const string &default_value); + INLINE void set_default_value(const std::string &default_value); #ifdef HAVE_PYTHON - static string get_pystr(PyObject *value); + static std::string get_pystr(PyObject *value); #endif protected: @@ -115,14 +115,14 @@ protected: bool _bogus_field; private: - string _default_value; + std::string _default_value; #ifdef WITHIN_PANDA PStatCollector _field_update_pcollector; #endif }; -INLINE ostream &operator << (ostream &out, const DCField &field) { +INLINE std::ostream &operator << (std::ostream &out, const DCField &field) { field.output(out); return out; } diff --git a/direct/src/dcparser/dcFile.cxx b/direct/src/dcparser/dcFile.cxx index 9dc7009dca..be69b4b18c 100644 --- a/direct/src/dcparser/dcFile.cxx +++ b/direct/src/dcparser/dcFile.cxx @@ -28,6 +28,9 @@ #include "configVariableList.h" #endif +using std::cerr; +using std::string; + /** * @@ -122,8 +125,8 @@ read(Filename filename) { #ifdef WITHIN_PANDA filename.set_text(); VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); - istream *in = vfs->open_read_file(filename, true); - if (in == (istream *)NULL) { + std::istream *in = vfs->open_read_file(filename, true); + if (in == nullptr) { cerr << "Cannot open " << filename << " for reading.\n"; return false; } @@ -163,7 +166,7 @@ read(Filename filename) { * (in which case the file might have been partially read). */ bool DCFile:: -read(istream &in, const string &filename) { +read(std::istream &in, const string &filename) { cerr << "DCFile::read of " << filename << "\n"; dc_init_parser(in, filename, *this); dcyyparse(); @@ -203,7 +206,7 @@ write(Filename filename, bool brief) const { * Returns true if the description is successfully written, false otherwise. */ bool DCFile:: -write(ostream &out, bool brief) const { +write(std::ostream &out, bool brief) const { if (!_imports.empty()) { Imports::const_iterator ii; for (ii = _imports.begin(); ii != _imports.end(); ++ii) { @@ -247,7 +250,7 @@ get_num_classes() const { */ DCClass *DCFile:: get_class(int n) const { - nassertr(n >= 0 && n < (int)_classes.size(), NULL); + nassertr(n >= 0 && n < (int)_classes.size(), nullptr); return _classes[n]; } @@ -263,7 +266,7 @@ get_class_by_name(const string &name) const { return (*ni).second->as_class(); } - return (DCClass *)NULL; + return nullptr; } /** @@ -278,7 +281,7 @@ get_switch_by_name(const string &name) const { return (*ni).second->as_switch(); } - return (DCSwitch *)NULL; + return nullptr; } /** @@ -291,13 +294,13 @@ get_switch_by_name(const string &name) const { */ DCField *DCFile:: get_field_by_index(int index_number) const { - nassertr(dc_multiple_inheritance, NULL); + nassertr(dc_multiple_inheritance, nullptr); if (index_number >= 0 && index_number < (int)_fields_by_index.size()) { return _fields_by_index[index_number]; } - return NULL; + return nullptr; } /** @@ -352,7 +355,7 @@ get_num_typedefs() const { */ DCTypedef *DCFile:: get_typedef(int n) const { - nassertr(n >= 0 && n < (int)_typedefs.size(), NULL); + nassertr(n >= 0 && n < (int)_typedefs.size(), nullptr); return _typedefs[n]; } @@ -368,7 +371,7 @@ get_typedef_by_name(const string &name) const { return (*ni).second; } - return NULL; + return nullptr; } /** @@ -394,9 +397,9 @@ get_keyword(int n) const { const DCKeyword *DCFile:: get_keyword_by_name(const string &name) const { const DCKeyword *keyword = _keywords.get_keyword_by_name(name); - if (keyword == (const DCKeyword *)NULL) { + if (keyword == nullptr) { keyword = _default_keywords.get_keyword_by_name(name); - if (keyword != (const DCKeyword *)NULL) { + if (keyword != nullptr) { // One of the historical default keywords was used, but wasn't defined. // Define it implicitly right now. ((DCFile *)this)->_keywords.add_keyword(keyword); @@ -612,11 +615,11 @@ setup_default_keywords() { { "clrecv", 0x0040 }, { "ownsend", 0x0080 }, { "airecv", 0x0100 }, - { NULL, 0 } + { nullptr, 0 } }; _default_keywords.clear_keywords(); - for (int i = 0; default_keywords[i].name != NULL; ++i) { + for (int i = 0; default_keywords[i].name != nullptr; ++i) { DCKeyword *keyword = new DCKeyword(default_keywords[i].name, default_keywords[i].flag); diff --git a/direct/src/dcparser/dcFile.h b/direct/src/dcparser/dcFile.h index 8ad67e1ace..7d7550804f 100644 --- a/direct/src/dcparser/dcFile.h +++ b/direct/src/dcparser/dcFile.h @@ -41,32 +41,32 @@ PUBLISHED: #endif bool read(Filename filename); - bool read(istream &in, const string &filename = string()); + bool read(std::istream &in, const std::string &filename = std::string()); bool write(Filename filename, bool brief) const; - bool write(ostream &out, bool brief) const; + bool write(std::ostream &out, bool brief) const; int get_num_classes() const; DCClass *get_class(int n) const; - DCClass *get_class_by_name(const string &name) const; - DCSwitch *get_switch_by_name(const string &name) const; + DCClass *get_class_by_name(const std::string &name) const; + DCSwitch *get_switch_by_name(const std::string &name) const; DCField *get_field_by_index(int index_number) const; INLINE bool all_objects_valid() const; int get_num_import_modules() const; - string get_import_module(int n) const; + std::string get_import_module(int n) const; int get_num_import_symbols(int n) const; - string get_import_symbol(int n, int i) const; + std::string get_import_symbol(int n, int i) const; int get_num_typedefs() const; DCTypedef *get_typedef(int n) const; - DCTypedef *get_typedef_by_name(const string &name) const; + DCTypedef *get_typedef_by_name(const std::string &name) const; int get_num_keywords() const; const DCKeyword *get_keyword(int n) const; - const DCKeyword *get_keyword_by_name(const string &name) const; + const DCKeyword *get_keyword_by_name(const std::string &name) const; unsigned long get_hash() const; @@ -74,10 +74,10 @@ public: void generate_hash(HashGenerator &hashgen) const; bool add_class(DCClass *dclass); bool add_switch(DCSwitch *dswitch); - void add_import_module(const string &import_module); - void add_import_symbol(const string &import_symbol); + void add_import_module(const std::string &import_module); + void add_import_symbol(const std::string &import_symbol); bool add_typedef(DCTypedef *dtypedef); - bool add_keyword(const string &name); + bool add_keyword(const std::string &name); void add_thing_to_delete(DCDeclaration *decl); void set_new_index_number(DCField *field); @@ -91,13 +91,13 @@ private: typedef pvector Classes; Classes _classes; - typedef pmap ThingsByName; + typedef pmap ThingsByName; ThingsByName _things_by_name; - typedef pvector ImportSymbols; + typedef pvector ImportSymbols; class Import { public: - string _module; + std::string _module; ImportSymbols _symbols; }; @@ -107,7 +107,7 @@ private: typedef pvector Typedefs; Typedefs _typedefs; - typedef pmap TypedefsByName; + typedef pmap TypedefsByName; TypedefsByName _typedefs_by_name; DCKeywordList _keywords; diff --git a/direct/src/dcparser/dcKeyword.cxx b/direct/src/dcparser/dcKeyword.cxx index 17dcab8df2..ef9c497b7d 100644 --- a/direct/src/dcparser/dcKeyword.cxx +++ b/direct/src/dcparser/dcKeyword.cxx @@ -19,7 +19,7 @@ * */ DCKeyword:: -DCKeyword(const string &name, int historical_flag) : +DCKeyword(const std::string &name, int historical_flag) : _name(name), _historical_flag(historical_flag) { @@ -35,7 +35,7 @@ DCKeyword:: /** * Returns the name of this keyword. */ -const string &DCKeyword:: +const std::string &DCKeyword:: get_name() const { return _name; } @@ -64,7 +64,7 @@ clear_historical_flag() { * Write a string representation of this instance to . */ void DCKeyword:: -output(ostream &out, bool brief) const { +output(std::ostream &out, bool brief) const { out << "keyword " << _name; } @@ -72,7 +72,7 @@ output(ostream &out, bool brief) const { * */ void DCKeyword:: -write(ostream &out, bool, int indent_level) const { +write(std::ostream &out, bool, int indent_level) const { indent(out, indent_level) << "keyword " << _name << ";\n"; } diff --git a/direct/src/dcparser/dcKeyword.h b/direct/src/dcparser/dcKeyword.h index 76c212c093..a82bd1ef0f 100644 --- a/direct/src/dcparser/dcKeyword.h +++ b/direct/src/dcparser/dcKeyword.h @@ -27,22 +27,22 @@ class HashGenerator; */ class DCKeyword : public DCDeclaration { public: - DCKeyword(const string &name, int historical_flag = ~0); + DCKeyword(const std::string &name, int historical_flag = ~0); virtual ~DCKeyword(); PUBLISHED: - const string &get_name() const; + const std::string &get_name() const; public: int get_historical_flag() const; void clear_historical_flag(); - virtual void output(ostream &out, bool brief) const; - virtual void write(ostream &out, bool brief, int indent_level) const; + virtual void output(std::ostream &out, bool brief) const; + virtual void write(std::ostream &out, bool brief, int indent_level) const; void generate_hash(HashGenerator &hashgen) const; private: - const string _name; + const std::string _name; // This flag is only kept for historical reasons, so we can preserve the // file's hash code if no new flags are in use. diff --git a/direct/src/dcparser/dcKeywordList.cxx b/direct/src/dcparser/dcKeywordList.cxx index d3f2d0347e..cdfdd4f7f5 100644 --- a/direct/src/dcparser/dcKeywordList.cxx +++ b/direct/src/dcparser/dcKeywordList.cxx @@ -57,7 +57,7 @@ DCKeywordList:: * Returns true if this list includes the indicated keyword, false otherwise. */ bool DCKeywordList:: -has_keyword(const string &name) const { +has_keyword(const std::string &name) const { return (_keywords_by_name.find(name) != _keywords_by_name.end()); } @@ -83,7 +83,7 @@ get_num_keywords() const { */ const DCKeyword *DCKeywordList:: get_keyword(int n) const { - nassertr(n >= 0 && n < (int)_keywords.size(), NULL); + nassertr(n >= 0 && n < (int)_keywords.size(), nullptr); return _keywords[n]; } @@ -92,14 +92,14 @@ get_keyword(int n) const { * is no keyword in the list with that name. */ const DCKeyword *DCKeywordList:: -get_keyword_by_name(const string &name) const { +get_keyword_by_name(const std::string &name) const { KeywordsByName::const_iterator ni; ni = _keywords_by_name.find(name); if (ni != _keywords_by_name.end()) { return (*ni).second; } - return NULL; + return nullptr; } /** @@ -148,7 +148,7 @@ clear_keywords() { * */ void DCKeywordList:: -output_keywords(ostream &out) const { +output_keywords(std::ostream &out) const { Keywords::const_iterator ki; for (ki = _keywords.begin(); ki != _keywords.end(); ++ki) { out << " " << (*ki)->get_name(); diff --git a/direct/src/dcparser/dcKeywordList.h b/direct/src/dcparser/dcKeywordList.h index ada61ffaa0..d9905c64db 100644 --- a/direct/src/dcparser/dcKeywordList.h +++ b/direct/src/dcparser/dcKeywordList.h @@ -31,11 +31,11 @@ public: ~DCKeywordList(); PUBLISHED: - bool has_keyword(const string &name) const; + bool has_keyword(const std::string &name) const; bool has_keyword(const DCKeyword *keyword) const; int get_num_keywords() const; const DCKeyword *get_keyword(int n) const; - const DCKeyword *get_keyword_by_name(const string &name) const; + const DCKeyword *get_keyword_by_name(const std::string &name) const; bool compare_keywords(const DCKeywordList &other) const; @@ -45,14 +45,14 @@ public: bool add_keyword(const DCKeyword *keyword); void clear_keywords(); - void output_keywords(ostream &out) const; + void output_keywords(std::ostream &out) const; void generate_hash(HashGenerator &hashgen) const; private: typedef pvector Keywords; Keywords _keywords; - typedef pmap KeywordsByName; + typedef pmap KeywordsByName; KeywordsByName _keywords_by_name; int _flags; diff --git a/direct/src/dcparser/dcLexer.cxx.prebuilt b/direct/src/dcparser/dcLexer.cxx.prebuilt index f99b920f81..660f96b5cb 100644 --- a/direct/src/dcparser/dcLexer.cxx.prebuilt +++ b/direct/src/dcparser/dcLexer.cxx.prebuilt @@ -610,11 +610,11 @@ static int error_count = 0; static int warning_count = 0; // This is the pointer to the current input stream. -static istream *input_p = NULL; +static std::istream *input_p = nullptr; // This is the name of the dc file we're parsing. We keep it so we // can print it out for error messages. -static string dc_filename; +static std::string dc_filename; // This is the initial token state returned by the lexer. It allows // the yacc grammar to start from initial points. @@ -626,7 +626,7 @@ static int initial_token; //////////////////////////////////////////////////////////////////// void -dc_init_lexer(istream &in, const string &filename) { +dc_init_lexer(std::istream &in, const std::string &filename) { input_p = ∈ dc_filename = filename; line_number = 0; @@ -671,7 +671,9 @@ dcyywrap(void) { } void -dcyyerror(const string &msg) { +dcyyerror(const std::string &msg) { + using std::cerr; + cerr << "\nError"; if (!dc_filename.empty()) { cerr << " in " << dc_filename; @@ -686,7 +688,9 @@ dcyyerror(const string &msg) { } void -dcyywarning(const string &msg) { +dcyywarning(const std::string &msg) { + using std::cerr; + cerr << "\nWarning"; if (!dc_filename.empty()) { cerr << " in " << dc_filename; @@ -740,7 +744,7 @@ input_chars(char *buffer, int &result, int max_size) { // Define this macro carefully, since different flex versions call it // with a different type for result. #define YY_INPUT(buffer, result, max_size) { \ - int int_result; \ + int int_result = 0; \ input_chars((buffer), int_result, (max_size)); \ (result) = int_result; \ } @@ -762,9 +766,9 @@ read_char(int &line, int &col) { // scan_quoted_string reads a string delimited by quotation marks and // returns it. -static string +static std::string scan_quoted_string(char quote_mark) { - string result; + std::string result; // We don't touch the current line number and column number during // scanning, so that if we detect an error while scanning the string @@ -884,9 +888,9 @@ scan_quoted_string(char quote_mark) { // scan_hex_string reads a string of hexadecimal digits delimited by // angle brackets and returns the representative string. -static string +static std::string scan_hex_string() { - string result; + std::string result; // We don't touch the current line number and column number during // scanning, so that if we detect an error while scanning the string @@ -916,7 +920,7 @@ scan_hex_string() { line_number = line; col_number = col; dcyyerror("Invalid hex digit."); - return string(); + return std::string(); } odd = !odd; @@ -930,10 +934,10 @@ scan_hex_string() { if (c == EOF) { dcyyerror("This hex string is unterminated."); - return string(); + return std::string(); } else if (odd) { dcyyerror("Odd number of hex digits."); - return string(); + return std::string(); } line_number = line; diff --git a/direct/src/dcparser/dcLexer.lxx b/direct/src/dcparser/dcLexer.lxx index 4dbd18299d..3c20a69b5f 100644 --- a/direct/src/dcparser/dcLexer.lxx +++ b/direct/src/dcparser/dcLexer.lxx @@ -35,11 +35,11 @@ static int error_count = 0; static int warning_count = 0; // This is the pointer to the current input stream. -static istream *input_p = NULL; +static std::istream *input_p = nullptr; // This is the name of the dc file we're parsing. We keep it so we // can print it out for error messages. -static string dc_filename; +static std::string dc_filename; // This is the initial token state returned by the lexer. It allows // the yacc grammar to start from initial points. @@ -51,7 +51,7 @@ static int initial_token; //////////////////////////////////////////////////////////////////// void -dc_init_lexer(istream &in, const string &filename) { +dc_init_lexer(std::istream &in, const std::string &filename) { input_p = ∈ dc_filename = filename; line_number = 0; @@ -96,7 +96,9 @@ dcyywrap(void) { } void -dcyyerror(const string &msg) { +dcyyerror(const std::string &msg) { + using std::cerr; + cerr << "\nError"; if (!dc_filename.empty()) { cerr << " in " << dc_filename; @@ -111,7 +113,9 @@ dcyyerror(const string &msg) { } void -dcyywarning(const string &msg) { +dcyywarning(const std::string &msg) { + using std::cerr; + cerr << "\nWarning"; if (!dc_filename.empty()) { cerr << " in " << dc_filename; @@ -129,7 +133,7 @@ dcyywarning(const string &msg) { // stdio FILE pointer. This is flex-specific. static void input_chars(char *buffer, int &result, int max_size) { - nassertv(input_p != NULL); + nassertv(input_p != nullptr); if (*input_p) { input_p->read(buffer, max_size); result = input_p->gcount(); @@ -150,7 +154,7 @@ input_chars(char *buffer, int &result, int max_size) { // Truncate it at the newline. char *end = strchr(current_line, '\n'); - if (end != NULL) { + if (end != nullptr) { *end = '\0'; } } @@ -165,7 +169,7 @@ input_chars(char *buffer, int &result, int max_size) { // Define this macro carefully, since different flex versions call it // with a different type for result. #define YY_INPUT(buffer, result, max_size) { \ - int int_result; \ + int int_result = 0; \ input_chars((buffer), int_result, (max_size)); \ (result) = int_result; \ } @@ -187,9 +191,9 @@ read_char(int &line, int &col) { // scan_quoted_string reads a string delimited by quotation marks and // returns it. -static string +static std::string scan_quoted_string(char quote_mark) { - string result; + std::string result; // We don't touch the current line number and column number during // scanning, so that if we detect an error while scanning the string @@ -309,9 +313,9 @@ scan_quoted_string(char quote_mark) { // scan_hex_string reads a string of hexadecimal digits delimited by // angle brackets and returns the representative string. -static string +static std::string scan_hex_string() { - string result; + std::string result; // We don't touch the current line number and column number during // scanning, so that if we detect an error while scanning the string @@ -341,7 +345,7 @@ scan_hex_string() { line_number = line; col_number = col; dcyyerror("Invalid hex digit."); - return string(); + return std::string(); } odd = !odd; @@ -355,10 +359,10 @@ scan_hex_string() { if (c == EOF) { dcyyerror("This hex string is unterminated."); - return string(); + return std::string(); } else if (odd) { dcyyerror("Odd number of hex digits."); - return string(); + return std::string(); } line_number = line; @@ -733,9 +737,9 @@ REALNUM ([+-]?(([0-9]+[.])|([0-9]*[.][0-9]+))([eE][+-]?[0-9]+)?) accept(); dcyylval.str = dcyytext; - if (dc_file != (DCFile *)NULL) { + if (dc_file != nullptr) { const DCKeyword *keyword = dc_file->get_keyword_by_name(dcyylval.str); - if (keyword != (DCKeyword *)NULL) { + if (keyword != nullptr) { dcyylval.u.keyword = keyword; return KEYWORD; } diff --git a/direct/src/dcparser/dcLexerDefs.h b/direct/src/dcparser/dcLexerDefs.h index 8c480ad98a..eb6b517045 100644 --- a/direct/src/dcparser/dcLexerDefs.h +++ b/direct/src/dcparser/dcLexerDefs.h @@ -16,14 +16,14 @@ #include "dcbase.h" -void dc_init_lexer(istream &in, const string &filename); +void dc_init_lexer(std::istream &in, const std::string &filename); void dc_start_parameter_value(); void dc_start_parameter_description(); int dc_error_count(); int dc_warning_count(); -void dcyyerror(const string &msg); -void dcyywarning(const string &msg); +void dcyyerror(const std::string &msg); +void dcyywarning(const std::string &msg); int dcyylex(); diff --git a/direct/src/dcparser/dcMolecularField.cxx b/direct/src/dcparser/dcMolecularField.cxx index 4bb0c3241f..b5e18094a9 100644 --- a/direct/src/dcparser/dcMolecularField.cxx +++ b/direct/src/dcparser/dcMolecularField.cxx @@ -22,7 +22,7 @@ * */ DCMolecularField:: -DCMolecularField(const string &name, DCClass *dclass) : DCField(name, dclass) { +DCMolecularField(const std::string &name, DCClass *dclass) : DCField(name, dclass) { _got_keywords = false; } @@ -59,7 +59,7 @@ get_num_atomics() const { */ DCAtomicField *DCMolecularField:: get_atomic(int n) const { - nassertr(n >= 0 && n < (int)_fields.size(), NULL); + nassertr(n >= 0 && n < (int)_fields.size(), nullptr); return _fields[n]; } @@ -109,7 +109,7 @@ add_atomic(DCAtomicField *atomic) { * */ void DCMolecularField:: -output(ostream &out, bool brief) const { +output(std::ostream &out, bool brief) const { out << _name; if (!_fields.empty()) { @@ -130,7 +130,7 @@ output(ostream &out, bool brief) const { * stream. */ void DCMolecularField:: -write(ostream &out, bool brief, int indent_level) const { +write(std::ostream &out, bool brief, int indent_level) const { indent(out, indent_level); output(out, brief); if (!brief) { @@ -161,7 +161,7 @@ generate_hash(HashGenerator &hashgen) const { */ DCPackerInterface *DCMolecularField:: get_nested_field(int n) const { - nassertr(n >= 0 && n < (int)_nested_fields.size(), NULL); + nassertr(n >= 0 && n < (int)_nested_fields.size(), nullptr); return _nested_fields[n]; } diff --git a/direct/src/dcparser/dcMolecularField.h b/direct/src/dcparser/dcMolecularField.h index 6d532a1b23..db7d850e00 100644 --- a/direct/src/dcparser/dcMolecularField.h +++ b/direct/src/dcparser/dcMolecularField.h @@ -27,7 +27,7 @@ class DCParameter; */ class DCMolecularField : public DCField { public: - DCMolecularField(const string &name, DCClass *dclass); + DCMolecularField(const std::string &name, DCClass *dclass); PUBLISHED: virtual DCMolecularField *as_molecular_field(); @@ -39,8 +39,8 @@ PUBLISHED: public: void add_atomic(DCAtomicField *atomic); - virtual void output(ostream &out, bool brief) const; - virtual void write(ostream &out, bool brief, int indent_level) const; + virtual void output(std::ostream &out, bool brief) const; + virtual void write(std::ostream &out, bool brief, int indent_level) const; virtual void generate_hash(HashGenerator &hashgen) const; virtual DCPackerInterface *get_nested_field(int n) const; diff --git a/direct/src/dcparser/dcNumericRange.I b/direct/src/dcparser/dcNumericRange.I index debc9bbcd5..bd41418205 100644 --- a/direct/src/dcparser/dcNumericRange.I +++ b/direct/src/dcparser/dcNumericRange.I @@ -58,7 +58,7 @@ is_in_range(Number num) const { return true; } - TYPENAME Ranges::const_iterator ri; + typename Ranges::const_iterator ri; for (ri = _ranges.begin(); ri != _ranges.end(); ++ri) { if (num >= (*ri)._min && num <= (*ri)._max) { return true; @@ -96,7 +96,7 @@ has_one_value() const { * by the numeric range. */ template -INLINE TYPENAME DCNumericRange::Number DCNumericRange:: +INLINE typename DCNumericRange::Number DCNumericRange:: get_one_value() const { nassertr(has_one_value(), 0); return _ranges[0]._min; @@ -110,7 +110,7 @@ void DCNumericRange:: generate_hash(HashGenerator &hashgen) const { if (!_ranges.empty()) { hashgen.add_int(_ranges.size()); - TYPENAME Ranges::const_iterator ri; + typename Ranges::const_iterator ri; for (ri = _ranges.begin(); ri != _ranges.end(); ++ri) { // We don't account for the fractional part of floating-point ranges // here. Shouldn't be a real issue. @@ -125,9 +125,9 @@ generate_hash(HashGenerator &hashgen) const { */ template void DCNumericRange:: -output(ostream &out, Number divisor) const { +output(std::ostream &out, Number divisor) const { if (!_ranges.empty()) { - TYPENAME Ranges::const_iterator ri; + typename Ranges::const_iterator ri; ri = _ranges.begin(); output_minmax(out, divisor, *ri); ++ri; @@ -145,13 +145,13 @@ output(ostream &out, Number divisor) const { */ template void DCNumericRange:: -output_char(ostream &out, Number divisor) const { +output_char(std::ostream &out, Number divisor) const { if (divisor != 1) { output(out, divisor); } else { if (!_ranges.empty()) { - TYPENAME Ranges::const_iterator ri; + typename Ranges::const_iterator ri; ri = _ranges.begin(); output_minmax_char(out, *ri); ++ri; @@ -187,7 +187,7 @@ add_range(Number min, Number max) { return false; } - TYPENAME Ranges::const_iterator ri; + typename Ranges::const_iterator ri; for (ri = _ranges.begin(); ri != _ranges.end(); ++ri) { if ((min >= (*ri)._min && min <= (*ri)._max) || (max >= (*ri)._min && max <= (*ri)._max) || @@ -227,7 +227,7 @@ get_num_ranges() const { * Returns the minimum value defined by the nth component. */ template -INLINE TYPENAME DCNumericRange::Number DCNumericRange:: +INLINE typename DCNumericRange::Number DCNumericRange:: get_min(int n) const { nassertr(n >= 0 && n < (int)_ranges.size(), 0); return _ranges[n]._min; @@ -237,7 +237,7 @@ get_min(int n) const { * Returns the maximum value defined by the nth component. */ template -INLINE TYPENAME DCNumericRange::Number DCNumericRange:: +INLINE typename DCNumericRange::Number DCNumericRange:: get_max(int n) const { nassertr(n >= 0 && n < (int)_ranges.size(), 0); return _ranges[n]._max; @@ -248,7 +248,7 @@ get_max(int n) const { */ template INLINE void DCNumericRange:: -output_minmax(ostream &out, Number divisor, const MinMax &range) const { +output_minmax(std::ostream &out, Number divisor, const MinMax &range) const { if (divisor == 1) { if (range._min == range._max) { out << range._min; @@ -271,12 +271,12 @@ output_minmax(ostream &out, Number divisor, const MinMax &range) const { */ template INLINE void DCNumericRange:: -output_minmax_char(ostream &out, const MinMax &range) const { +output_minmax_char(std::ostream &out, const MinMax &range) const { if (range._min == range._max) { - DCPacker::enquote_string(out, '\'', string(1, range._min)); + DCPacker::enquote_string(out, '\'', std::string(1, range._min)); } else { - DCPacker::enquote_string(out, '\'', string(1, range._min)); + DCPacker::enquote_string(out, '\'', std::string(1, range._min)); out << "-"; - DCPacker::enquote_string(out, '\'', string(1, range._max)); + DCPacker::enquote_string(out, '\'', std::string(1, range._max)); } } diff --git a/direct/src/dcparser/dcNumericRange.h b/direct/src/dcparser/dcNumericRange.h index 6539c05422..b3450f89e4 100644 --- a/direct/src/dcparser/dcNumericRange.h +++ b/direct/src/dcparser/dcNumericRange.h @@ -40,8 +40,8 @@ public: void generate_hash(HashGenerator &hashgen) const; - void output(ostream &out, Number divisor = 1) const; - void output_char(ostream &out, Number divisor = 1) const; + void output(std::ostream &out, Number divisor = 1) const; + void output_char(std::ostream &out, Number divisor = 1) const; public: INLINE void clear(); @@ -60,8 +60,8 @@ private: Number _min; Number _max; }; - INLINE void output_minmax(ostream &out, Number divisor, const MinMax &range) const; - INLINE void output_minmax_char(ostream &out, const MinMax &range) const; + INLINE void output_minmax(std::ostream &out, Number divisor, const MinMax &range) const; + INLINE void output_minmax_char(std::ostream &out, const MinMax &range) const; typedef pvector Ranges; Ranges _ranges; diff --git a/direct/src/dcparser/dcPackData.I b/direct/src/dcparser/dcPackData.I index 3766f64d2f..ac68d40313 100644 --- a/direct/src/dcparser/dcPackData.I +++ b/direct/src/dcparser/dcPackData.I @@ -16,7 +16,7 @@ */ INLINE DCPackData:: DCPackData() { - _buffer = NULL; + _buffer = nullptr; _allocated_size = 0; _used_length = 0; } @@ -26,7 +26,7 @@ DCPackData() { */ INLINE DCPackData:: ~DCPackData() { - if (_buffer != (const char *)NULL) { + if (_buffer != nullptr) { delete[] _buffer; } } @@ -82,16 +82,16 @@ rewrite_data(size_t position, const char *buffer, size_t size) { */ INLINE char *DCPackData:: get_rewrite_pointer(size_t position, size_t size) { - nassertr(position + size <= _used_length, NULL); + nassertr(position + size <= _used_length, nullptr); return _buffer + position; } /** * Returns the data buffer as a string. Also see get_data(). */ -INLINE string DCPackData:: +INLINE std::string DCPackData:: get_string() const { - return string(_buffer, _used_length); + return std::string(_buffer, _used_length); } /** @@ -129,7 +129,7 @@ INLINE char *DCPackData:: take_data() { char *data = _buffer; - _buffer = NULL; + _buffer = nullptr; _allocated_size = 0; _used_length = 0; diff --git a/direct/src/dcparser/dcPackData.cxx b/direct/src/dcparser/dcPackData.cxx index 4276c735f4..2c0c19a61d 100644 --- a/direct/src/dcparser/dcPackData.cxx +++ b/direct/src/dcparser/dcPackData.cxx @@ -27,7 +27,7 @@ set_used_length(size_t size) { if (_used_length > 0) { memcpy(new_buf, _buffer, _used_length); } - if (_buffer != NULL) { + if (_buffer != nullptr) { delete[] _buffer; } _buffer = new_buf; diff --git a/direct/src/dcparser/dcPackData.h b/direct/src/dcparser/dcPackData.h index 99cd0abbd5..7f891a1d5d 100644 --- a/direct/src/dcparser/dcPackData.h +++ b/direct/src/dcparser/dcPackData.h @@ -34,7 +34,7 @@ public: INLINE char *get_rewrite_pointer(size_t position, size_t size); PUBLISHED: - INLINE string get_string() const; + INLINE std::string get_string() const; INLINE size_t get_length() const; public: INLINE const char *get_data() const; diff --git a/direct/src/dcparser/dcPacker.I b/direct/src/dcparser/dcPacker.I index c159b0cb77..8c640d77b1 100644 --- a/direct/src/dcparser/dcPacker.I +++ b/direct/src/dcparser/dcPacker.I @@ -24,7 +24,7 @@ clear_data() { delete[] _unpack_data; _owns_unpack_data = false; } - _unpack_data = NULL; + _unpack_data = nullptr; } /** @@ -35,7 +35,7 @@ clear_data() { */ INLINE bool DCPacker:: has_nested_fields() const { - if (_current_field == NULL) { + if (_current_field == nullptr) { return false; } else { return _current_field->has_nested_fields(); @@ -65,7 +65,7 @@ get_num_nested_fields() const { */ INLINE bool DCPacker:: more_nested_fields() const { - return (_current_field != (DCPackerInterface *)NULL && !_pack_error); + return (_current_field != nullptr && !_pack_error); } /** @@ -112,7 +112,7 @@ get_last_switch() const { */ INLINE DCPackType DCPacker:: get_pack_type() const { - if (_current_field == NULL) { + if (_current_field == nullptr) { return PT_invalid; } else { return _current_field->get_pack_type(); @@ -123,10 +123,10 @@ get_pack_type() const { * Returns the name of the current field, if it has a name, or the empty * string if the field does not have a name or there is no current field. */ -INLINE string DCPacker:: +INLINE std::string DCPacker:: get_current_field_name() const { - if (_current_field == NULL) { - return string(); + if (_current_field == nullptr) { + return std::string(); } else { return _current_field->get_name(); } @@ -138,7 +138,7 @@ get_current_field_name() const { INLINE void DCPacker:: pack_double(double value) { nassertv(_mode == M_pack || _mode == M_repack); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { _current_field->pack_double(_pack_data, value, _pack_error, _range_error); @@ -152,7 +152,7 @@ pack_double(double value) { INLINE void DCPacker:: pack_int(int value) { nassertv(_mode == M_pack || _mode == M_repack); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { _current_field->pack_int(_pack_data, value, _pack_error, _range_error); @@ -166,7 +166,7 @@ pack_int(int value) { INLINE void DCPacker:: pack_uint(unsigned int value) { nassertv(_mode == M_pack || _mode == M_repack); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { _current_field->pack_uint(_pack_data, value, _pack_error, _range_error); @@ -180,7 +180,7 @@ pack_uint(unsigned int value) { INLINE void DCPacker:: pack_int64(int64_t value) { nassertv(_mode == M_pack || _mode == M_repack); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { _current_field->pack_int64(_pack_data, value, _pack_error, _range_error); @@ -194,7 +194,7 @@ pack_int64(int64_t value) { INLINE void DCPacker:: pack_uint64(uint64_t value) { nassertv(_mode == M_pack || _mode == M_repack); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { _current_field->pack_uint64(_pack_data, value, _pack_error, _range_error); @@ -206,9 +206,9 @@ pack_uint64(uint64_t value) { * Packs the indicated numeric or string value into the stream. */ INLINE void DCPacker:: -pack_string(const string &value) { +pack_string(const std::string &value) { nassertv(_mode == M_pack || _mode == M_repack); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { _current_field->pack_string(_pack_data, value, _pack_error, _range_error); @@ -221,9 +221,9 @@ pack_string(const string &value) { * packed field element, or a whole group of field elements at once. */ INLINE void DCPacker:: -pack_literal_value(const string &value) { +pack_literal_value(const std::string &value) { nassertv(_mode == M_pack || _mode == M_repack); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { _pack_data.append_data(value.data(), value.length()); @@ -238,7 +238,7 @@ INLINE double DCPacker:: unpack_double() { double value = 0.0; nassertr(_mode == M_unpack, value); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { @@ -257,7 +257,7 @@ INLINE int DCPacker:: unpack_int() { int value = 0; nassertr(_mode == M_unpack, value); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { @@ -276,7 +276,7 @@ INLINE unsigned int DCPacker:: unpack_uint() { unsigned int value = 0; nassertr(_mode == M_unpack, value); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { @@ -295,7 +295,7 @@ INLINE int64_t DCPacker:: unpack_int64() { int64_t value = 0; nassertr(_mode == M_unpack, value); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { @@ -314,7 +314,7 @@ INLINE uint64_t DCPacker:: unpack_uint64() { uint64_t value = 0; nassertr(_mode == M_unpack, value); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { @@ -329,11 +329,11 @@ unpack_uint64() { /** * Unpacks the current numeric or string value from the stream. */ -INLINE string DCPacker:: +INLINE std::string DCPacker:: unpack_string() { - string value; + std::string value; nassertr(_mode == M_unpack, value); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { @@ -349,12 +349,12 @@ unpack_string() { * Returns the literal string that represents the packed value of the current * field, and advances the field pointer. */ -INLINE string DCPacker:: +INLINE std::string DCPacker:: unpack_literal_value() { size_t start = _unpack_p; unpack_skip(); - nassertr(_unpack_p >= start, string()); - return string(_unpack_data + start, _unpack_p - start); + nassertr(_unpack_p >= start, std::string()); + return std::string(_unpack_data + start, _unpack_p - start); } /** @@ -363,7 +363,7 @@ unpack_literal_value() { INLINE void DCPacker:: unpack_double(double &value) { nassertv(_mode == M_unpack); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { @@ -379,7 +379,7 @@ unpack_double(double &value) { INLINE void DCPacker:: unpack_int(int &value) { nassertv(_mode == M_unpack); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { @@ -395,7 +395,7 @@ unpack_int(int &value) { INLINE void DCPacker:: unpack_uint(unsigned int &value) { nassertv(_mode == M_unpack); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { @@ -411,7 +411,7 @@ unpack_uint(unsigned int &value) { INLINE void DCPacker:: unpack_int64(int64_t &value) { nassertv(_mode == M_unpack); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { @@ -427,7 +427,7 @@ unpack_int64(int64_t &value) { INLINE void DCPacker:: unpack_uint64(uint64_t &value) { nassertv(_mode == M_unpack); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { @@ -441,9 +441,9 @@ unpack_uint64(uint64_t &value) { * Unpacks the current numeric or string value from the stream. */ INLINE void DCPacker:: -unpack_string(string &value) { +unpack_string(std::string &value) { nassertv(_mode == M_unpack); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { @@ -458,7 +458,7 @@ unpack_string(string &value) { * field, and advances the field pointer. */ INLINE void DCPacker:: -unpack_literal_value(string &value) { +unpack_literal_value(std::string &value) { size_t start = _unpack_p; unpack_skip(); nassertv(_unpack_p >= start); @@ -536,7 +536,7 @@ get_length() const { /** * Returns the packed data buffer as a string. Also see get_data(). */ -INLINE string DCPacker:: +INLINE std::string DCPacker:: get_string() const { return _pack_data.get_string(); } @@ -556,16 +556,16 @@ get_unpack_length() const { * unpacking; it is separate from the pack data returned by get_string(), * which is filled during packing. Also see get_unpack_data(). */ -INLINE string DCPacker:: +INLINE std::string DCPacker:: get_unpack_string() const { - return string(_unpack_data, _unpack_length); + return std::string(_unpack_data, _unpack_length); } /** * Copies the packed data into the indicated string. Also see get_data(). */ INLINE void DCPacker:: -get_string(string &data) const { +get_string(std::string &data) const { data.assign(_pack_data.get_data(), _pack_data.get_length()); } @@ -613,7 +613,7 @@ append_data(const char *buffer, size_t size) { */ INLINE char *DCPacker:: get_write_pointer(size_t size) { - nassertr(_mode == M_idle, NULL); + nassertr(_mode == M_idle, nullptr); return _pack_data.get_write_pointer(size); } @@ -722,7 +722,7 @@ raw_pack_float64(double value) { * Packs the data into the buffer between packing sessions. */ INLINE void DCPacker:: -raw_pack_string(const string &value) { +raw_pack_string(const std::string &value) { nassertv(_mode == M_idle); DCPackerInterface::do_pack_uint16(_pack_data.get_write_pointer(2), value.length()); _pack_data.append_data(value.data(), value.length()); @@ -773,7 +773,7 @@ raw_unpack_int64() { */ INLINE void DCPacker:: raw_unpack_int8(int &value) { - nassertv(_mode == M_idle && _unpack_data != NULL); + nassertv(_mode == M_idle && _unpack_data != nullptr); if (_unpack_p + 1 > _unpack_length) { _pack_error = true; return; @@ -787,7 +787,7 @@ raw_unpack_int8(int &value) { */ INLINE void DCPacker:: raw_unpack_int16(int &value) { - nassertv(_mode == M_idle && _unpack_data != NULL); + nassertv(_mode == M_idle && _unpack_data != nullptr); if (_unpack_p + 2 > _unpack_length) { _pack_error = true; return; @@ -801,7 +801,7 @@ raw_unpack_int16(int &value) { */ INLINE void DCPacker:: raw_unpack_int32(int &value) { - nassertv(_mode == M_idle && _unpack_data != NULL); + nassertv(_mode == M_idle && _unpack_data != nullptr); if (_unpack_p + 4 > _unpack_length) { _pack_error = true; return; @@ -863,9 +863,9 @@ raw_unpack_float64() { /** * Unpacks the data from the buffer between unpacking sessions. */ -INLINE string DCPacker:: +INLINE std::string DCPacker:: raw_unpack_string() { - string value; + std::string value; raw_unpack_string(value); return value; } @@ -875,7 +875,7 @@ raw_unpack_string() { */ INLINE void DCPacker:: raw_unpack_int64(int64_t &value) { - nassertv(_mode == M_idle && _unpack_data != NULL); + nassertv(_mode == M_idle && _unpack_data != nullptr); if (_unpack_p + 8 > _unpack_length) { _pack_error = true; return; @@ -889,7 +889,7 @@ raw_unpack_int64(int64_t &value) { */ INLINE void DCPacker:: raw_unpack_uint8(unsigned int &value) { - nassertv(_mode == M_idle && _unpack_data != NULL); + nassertv(_mode == M_idle && _unpack_data != nullptr); if (_unpack_p + 1 > _unpack_length) { _pack_error = true; return; @@ -903,7 +903,7 @@ raw_unpack_uint8(unsigned int &value) { */ INLINE void DCPacker:: raw_unpack_uint16(unsigned int &value) { - nassertv(_mode == M_idle && _unpack_data != NULL); + nassertv(_mode == M_idle && _unpack_data != nullptr); if (_unpack_p + 2 > _unpack_length) { _pack_error = true; return; @@ -917,7 +917,7 @@ raw_unpack_uint16(unsigned int &value) { */ INLINE void DCPacker:: raw_unpack_uint32(unsigned int &value) { - nassertv(_mode == M_idle && _unpack_data != NULL); + nassertv(_mode == M_idle && _unpack_data != nullptr); if (_unpack_p + 4 > _unpack_length) { _pack_error = true; return; @@ -931,7 +931,7 @@ raw_unpack_uint32(unsigned int &value) { */ INLINE void DCPacker:: raw_unpack_uint64(uint64_t &value) { - nassertv(_mode == M_idle && _unpack_data != NULL); + nassertv(_mode == M_idle && _unpack_data != nullptr); if (_unpack_p + 8 > _unpack_length) { _pack_error = true; return; @@ -945,7 +945,7 @@ raw_unpack_uint64(uint64_t &value) { */ INLINE void DCPacker:: raw_unpack_float64(double &value) { - nassertv(_mode == M_idle && _unpack_data != NULL); + nassertv(_mode == M_idle && _unpack_data != nullptr); if (_unpack_p + 8 > _unpack_length) { _pack_error = true; return; @@ -958,8 +958,8 @@ raw_unpack_float64(double &value) { * Unpacks the data from the buffer between unpacking sessions. */ INLINE void DCPacker:: -raw_unpack_string(string &value) { - nassertv(_mode == M_idle && _unpack_data != NULL); +raw_unpack_string(std::string &value) { + nassertv(_mode == M_idle && _unpack_data != nullptr); unsigned int string_length = raw_unpack_uint16(); if (_unpack_p + string_length > _unpack_length) { @@ -981,13 +981,13 @@ advance() { _current_field_index >= _num_nested_fields) { // Done with all the fields on this parent. The caller must now call // pop(). - _current_field = NULL; + _current_field = nullptr; // But if the parent is a switch record, we make a special case so we can // get the alternate fields. - if (_current_parent != (DCPackerInterface *)NULL) { + if (_current_parent != nullptr) { const DCSwitchParameter *switch_parameter = ((DCPackerInterface *)_current_parent)->as_switch_parameter(); - if (switch_parameter != (DCSwitchParameter *)NULL) { + if (switch_parameter != nullptr) { handle_switch(switch_parameter); } } @@ -995,7 +995,7 @@ advance() { } else if (_pop_marker != 0 && _unpack_p >= _pop_marker) { // Done with all the fields on this parent. The caller must now call // pop(). - _current_field = NULL; + _current_field = nullptr; } else { // We have another field to advance to. @@ -1009,7 +1009,7 @@ advance() { */ INLINE void *DCPacker::StackElement:: operator new(size_t size) { - if (_deleted_chain != (DCPacker::StackElement *)NULL) { + if (_deleted_chain != nullptr) { StackElement *obj = _deleted_chain; _deleted_chain = _deleted_chain->_next; return obj; diff --git a/direct/src/dcparser/dcPacker.cxx b/direct/src/dcparser/dcPacker.cxx index 794d5e1690..ebab348f6f 100644 --- a/direct/src/dcparser/dcPacker.cxx +++ b/direct/src/dcparser/dcPacker.cxx @@ -23,7 +23,13 @@ #include "py_panda.h" #endif -DCPacker::StackElement *DCPacker::StackElement::_deleted_chain = NULL; +using std::istream; +using std::istringstream; +using std::ostream; +using std::ostringstream; +using std::string; + +DCPacker::StackElement *DCPacker::StackElement::_deleted_chain = nullptr; int DCPacker::StackElement::_num_ever_allocated = 0; /** @@ -32,15 +38,15 @@ int DCPacker::StackElement::_num_ever_allocated = 0; DCPacker:: DCPacker() { _mode = M_idle; - _unpack_data = NULL; + _unpack_data = nullptr; _unpack_length = 0; _owns_unpack_data = false; _unpack_p = 0; - _live_catalog = NULL; + _live_catalog = nullptr; _parse_error = false; _pack_error = false; _range_error = false; - _stack = NULL; + _stack = nullptr; clear(); } @@ -73,11 +79,11 @@ begin_pack(const DCPackerInterface *root) { _range_error = false; _root = root; - _catalog = NULL; - _live_catalog = NULL; + _catalog = nullptr; + _live_catalog = nullptr; _current_field = root; - _current_parent = NULL; + _current_parent = nullptr; _current_field_index = 0; _num_nested_fields = 0; } @@ -94,7 +100,7 @@ end_pack() { _mode = M_idle; - if (_stack != NULL || _current_field != NULL || _current_parent != NULL) { + if (_stack != nullptr || _current_field != nullptr || _current_parent != nullptr) { _pack_error = true; } @@ -146,7 +152,7 @@ set_unpack_data(const char *unpack_data, size_t unpack_length, void DCPacker:: begin_unpack(const DCPackerInterface *root) { nassertv(_mode == M_idle); - nassertv(_unpack_data != NULL); + nassertv(_unpack_data != nullptr); _mode = M_unpack; _parse_error = false; @@ -154,11 +160,11 @@ begin_unpack(const DCPackerInterface *root) { _range_error = false; _root = root; - _catalog = NULL; - _live_catalog = NULL; + _catalog = nullptr; + _live_catalog = nullptr; _current_field = root; - _current_parent = NULL; + _current_parent = nullptr; _current_field_index = 0; _num_nested_fields = 0; } @@ -175,13 +181,13 @@ end_unpack() { _mode = M_idle; - if (_stack != NULL || _current_field != NULL || _current_parent != NULL) { + if (_stack != nullptr || _current_field != nullptr || _current_parent != nullptr) { // This happens if we have not unpacked all of the fields. However, this // is not an error if we have called seek() during the unpack session (in // which case the _catalog will be non-NULL). On the other hand, if the // catalog is still NULL, then we have never called seek() and it is an // error not to unpack all values. - if (_catalog == (DCPackerCatalog *)NULL) { + if (_catalog == nullptr) { _pack_error = true; } } @@ -206,7 +212,7 @@ end_unpack() { void DCPacker:: begin_repack(const DCPackerInterface *root) { nassertv(_mode == M_idle); - nassertv(_unpack_data != NULL); + nassertv(_unpack_data != nullptr); nassertv(_unpack_p == 0); _mode = M_repack; @@ -220,14 +226,14 @@ begin_repack(const DCPackerInterface *root) { _root = root; _catalog = _root->get_catalog(); _live_catalog = _catalog->get_live_catalog(_unpack_data, _unpack_length); - if (_live_catalog == NULL) { + if (_live_catalog == nullptr) { _pack_error = true; } // We don't begin at the first field in repack mode. Instead, you must // explicitly call seek(). - _current_field = NULL; - _current_parent = NULL; + _current_field = nullptr; + _current_parent = nullptr; _current_field_index = 0; _num_nested_fields = 0; } @@ -262,12 +268,12 @@ end_repack() { */ bool DCPacker:: seek(const string &field_name) { - if (_catalog == (DCPackerCatalog *)NULL) { + if (_catalog == nullptr) { _catalog = _root->get_catalog(); _live_catalog = _catalog->get_live_catalog(_unpack_data, _unpack_length); } - nassertr(_catalog != (DCPackerCatalog *)NULL, false); - if (_live_catalog == NULL) { + nassertr(_catalog != nullptr, false); + if (_live_catalog == nullptr) { _pack_error = true; return false; } @@ -292,12 +298,12 @@ seek(const string &field_name) { */ bool DCPacker:: seek(int seek_index) { - if (_catalog == (DCPackerCatalog *)NULL) { + if (_catalog == nullptr) { _catalog = _root->get_catalog(); _live_catalog = _catalog->get_live_catalog(_unpack_data, _unpack_length); } - nassertr(_catalog != (DCPackerCatalog *)NULL, false); - if (_live_catalog == NULL) { + nassertr(_catalog != nullptr, false); + if (_live_catalog == nullptr) { _pack_error = true; return false; } @@ -324,9 +330,9 @@ seek(int seek_index) { return true; } else if (_mode == M_repack) { - nassertr(_catalog != (DCPackerCatalog *)NULL, false); + nassertr(_catalog != nullptr, false); - if (_stack != NULL || _current_field != NULL) { + if (_stack != nullptr || _current_field != nullptr) { // It is an error to reseek while the stack is nonempty--that means we // haven't finished packing the current field. _pack_error = true; @@ -334,7 +340,7 @@ seek(int seek_index) { } const DCPackerCatalog::Entry &entry = _live_catalog->get_entry(seek_index); - if (entry._parent->as_switch_parameter() != (DCSwitchParameter *)NULL) { + if (entry._parent->as_switch_parameter() != nullptr) { // If the parent is a DCSwitch, that can only mean that the seeked field // is a switch parameter. We can't support seeking to a switch // parameter and modifying it directly--what would happen to all of the @@ -357,7 +363,7 @@ seek(int seek_index) { _catalog->release_live_catalog(_live_catalog); _live_catalog = _catalog->get_live_catalog(_unpack_data, _unpack_length); - if (_live_catalog == NULL) { + if (_live_catalog == nullptr) { _pack_error = true; return false; } @@ -470,7 +476,7 @@ push() { if (_num_nested_fields >= 0 && _current_field_index >= _num_nested_fields) { - _current_field = NULL; + _current_field = nullptr; } else { _current_field = _current_parent->get_nested_field(_current_field_index); @@ -487,7 +493,7 @@ push() { */ void DCPacker:: pop() { - if (_current_field != NULL && _num_nested_fields >= 0) { + if (_current_field != nullptr && _num_nested_fields >= 0) { // Oops, didn't pack or unpack enough values. _pack_error = true; @@ -497,7 +503,7 @@ pop() { _pack_error = true; } - if (_stack == NULL) { + if (_stack == nullptr) { // Unbalanced pop(). _pack_error = true; @@ -528,7 +534,7 @@ pop() { _current_field_index = _stack->_current_field_index; _push_marker = _stack->_push_marker; _pop_marker = _stack->_pop_marker; - _num_nested_fields = (_current_parent == NULL) ? 0 : _current_parent->get_num_nested_fields(); + _num_nested_fields = (_current_parent == nullptr) ? 0 : _current_parent->get_num_nested_fields(); StackElement *next = _stack->_next; delete _stack; @@ -545,7 +551,7 @@ pop() { void DCPacker:: pack_default_value() { nassertv(_mode == M_pack || _mode == M_repack); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { if (_current_field->pack_default_value(_pack_data, _pack_error)) { @@ -571,7 +577,7 @@ pack_default_value() { void DCPacker:: unpack_validate() { nassertv(_mode == M_unpack); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { @@ -597,7 +603,7 @@ unpack_validate() { void DCPacker:: unpack_skip() { nassertv(_mode == M_unpack); - if (_current_field == NULL) { + if (_current_field == nullptr) { _pack_error = true; } else { @@ -739,11 +745,11 @@ pack_object(PyObject *object) { (PyObject_HasAttrString(object, "__len__") != 0); bool is_instance = false; - const DCClass *dclass = NULL; + const DCClass *dclass = nullptr; const DCPackerInterface *current_field = get_current_field(); - if (current_field != (DCPackerInterface *)NULL) { + if (current_field != nullptr) { const DCClassParameter *class_param = get_current_field()->as_class_parameter(); - if (class_param != (DCClassParameter *)NULL) { + if (class_param != nullptr) { dclass = class_param->get_class(); if (dclass->has_class_def()) { @@ -771,7 +777,7 @@ pack_object(PyObject *object) { // (3) Otherwise, it is considered to be a class object. - if (dclass != (DCClass *)NULL && (is_instance || !is_sequence)) { + if (dclass != nullptr && (is_instance || !is_sequence)) { // The supplied object is either an instance of the expected class // object, or it is not a sequence--this is case (1) or (3). pack_class_object(dclass, object); @@ -782,11 +788,11 @@ pack_object(PyObject *object) { int size = PySequence_Size(object); for (int i = 0; i < size; ++i) { PyObject *element = PySequence_GetItem(object, i); - if (element != (PyObject *)NULL) { + if (element != nullptr) { pack_object(element); Py_DECREF(element); } else { - cerr << "Unable to extract item " << i << " from sequence.\n"; + std::cerr << "Unable to extract item " << i << " from sequence.\n"; } } pop(); @@ -812,7 +818,7 @@ pack_object(PyObject *object) { */ PyObject *DCPacker:: unpack_object() { - PyObject *object = NULL; + PyObject *object = nullptr; DCPackType pack_type = get_pack_type(); @@ -896,14 +902,14 @@ unpack_object() { case PT_class: { const DCClassParameter *class_param = get_current_field()->as_class_parameter(); - if (class_param != (DCClassParameter *)NULL) { + if (class_param != nullptr) { const DCClass *dclass = class_param->get_class(); if (dclass->has_class_def()) { // If we know what kind of class object this is and it has a valid // constructor, create the class object instead of just a tuple. object = unpack_class_object(dclass); - if (object == (PyObject *)NULL) { - cerr << "Unable to construct object of class " + if (object == nullptr) { + std::cerr << "Unable to construct object of class " << dclass->get_name() << "\n"; } else { break; @@ -939,7 +945,7 @@ unpack_object() { break; } - nassertr(object != (PyObject *)NULL, NULL); + nassertr(object != nullptr, nullptr); return object; } #endif // HAVE_PYTHON @@ -995,10 +1001,10 @@ unpack_and_format(ostream &out, bool show_field_names) { DCPackType pack_type = get_pack_type(); if (show_field_names && !get_current_field_name().empty()) { - nassertv(_current_field != (DCPackerInterface *)NULL); + nassertv(_current_field != nullptr); const DCField *field = _current_field->as_field(); - if (field != (DCField *)NULL && - field->as_parameter() != (DCParameter *)NULL) { + if (field != nullptr && + field->as_parameter() != nullptr) { out << field->get_name() << " = "; } } @@ -1135,7 +1141,7 @@ void DCPacker:: handle_switch(const DCSwitchParameter *switch_parameter) { // First, get the value from the key. This is either found in the unpack or // the pack data, depending on what mode we're in. - const DCPackerInterface *new_parent = NULL; + const DCPackerInterface *new_parent = nullptr; if (_mode == M_pack || _mode == M_repack) { const char *data = _pack_data.get_data(); @@ -1147,7 +1153,7 @@ handle_switch(const DCSwitchParameter *switch_parameter) { (_unpack_data + _push_marker, _unpack_p - _push_marker); } - if (new_parent == (DCPackerInterface *)NULL) { + if (new_parent == nullptr) { // This means an invalid value was packed for the key. _range_error = true; return; @@ -1173,20 +1179,20 @@ handle_switch(const DCSwitchParameter *switch_parameter) { void DCPacker:: clear() { clear_stack(); - _current_field = NULL; - _current_parent = NULL; + _current_field = nullptr; + _current_parent = nullptr; _current_field_index = 0; _num_nested_fields = 0; _push_marker = 0; _pop_marker = 0; - _last_switch = NULL; + _last_switch = nullptr; - if (_live_catalog != (DCPackerCatalog::LiveCatalog *)NULL) { + if (_live_catalog != nullptr) { _catalog->release_live_catalog(_live_catalog); - _live_catalog = NULL; + _live_catalog = nullptr; } - _catalog = NULL; - _root = NULL; + _catalog = nullptr; + _root = nullptr; } /** @@ -1194,7 +1200,7 @@ clear() { */ void DCPacker:: clear_stack() { - while (_stack != (StackElement *)NULL) { + while (_stack != nullptr) { StackElement *next = _stack->_next; delete _stack; _stack = next; @@ -1212,7 +1218,7 @@ pack_class_object(const DCClass *dclass, PyObject *object) { push(); while (more_nested_fields() && !_pack_error) { const DCField *field = get_current_field()->as_field(); - nassertv(field != (DCField *)NULL); + nassertv(field != nullptr); get_class_element(dclass, object, field); } pop(); @@ -1227,36 +1233,36 @@ pack_class_object(const DCClass *dclass, PyObject *object) { PyObject *DCPacker:: unpack_class_object(const DCClass *dclass) { PyObject *class_def = dclass->get_class_def(); - nassertr(class_def != (PyObject *)NULL, NULL); + nassertr(class_def != nullptr, nullptr); - PyObject *object = NULL; + PyObject *object = nullptr; if (!dclass->has_constructor()) { // If the class uses a default constructor, go ahead and create the Python // object for it now. - object = PyObject_CallObject(class_def, NULL); - if (object == (PyObject *)NULL) { - return NULL; + object = PyObject_CallObject(class_def, nullptr); + if (object == nullptr) { + return nullptr; } } push(); - if (object == (PyObject *)NULL && more_nested_fields()) { + if (object == nullptr && more_nested_fields()) { // The first nested field will be the constructor. const DCField *field = get_current_field()->as_field(); - nassertr(field != (DCField *)NULL, object); + nassertr(field != nullptr, object); nassertr(field == dclass->get_constructor(), object); set_class_element(class_def, object, field); // By now, the object should have been constructed. - if (object == (PyObject *)NULL) { - return NULL; + if (object == nullptr) { + return nullptr; } } while (more_nested_fields()) { const DCField *field = get_current_field()->as_field(); - nassertr(field != (DCField *)NULL, object); + nassertr(field != nullptr, object); set_class_element(class_def, object, field); } @@ -1287,8 +1293,8 @@ set_class_element(PyObject *class_def, PyObject *&object, push(); while (more_nested_fields()) { const DCField *field = get_current_field()->as_field(); - nassertv(field != (DCField *)NULL); - nassertv(object != (PyObject *)NULL); + nassertv(field != nullptr); + nassertv(object != nullptr); set_class_element(class_def, object, field); } pop(); @@ -1307,7 +1313,7 @@ set_class_element(PyObject *class_def, PyObject *&object, PyObject *element = unpack_object(); if (pack_type == PT_field) { - if (object == (PyObject *)NULL) { + if (object == nullptr) { // If the object hasn't been constructed yet, assume this is the // constructor. object = PyObject_CallObject(class_def, element); @@ -1315,7 +1321,7 @@ set_class_element(PyObject *class_def, PyObject *&object, } else { if (PyObject_HasAttrString(object, (char *)field_name.c_str())) { PyObject *func = PyObject_GetAttrString(object, (char *)field_name.c_str()); - if (func != (PyObject *)NULL) { + if (func != nullptr) { PyObject *result = PyObject_CallObject(func, element); Py_XDECREF(result); Py_DECREF(func); @@ -1324,7 +1330,7 @@ set_class_element(PyObject *class_def, PyObject *&object, } } else { - nassertv(object != (PyObject *)NULL); + nassertv(object != nullptr); PyObject_SetAttrString(object, (char *)field_name.c_str(), element); } @@ -1353,7 +1359,7 @@ get_class_element(const DCClass *dclass, PyObject *object, push(); while (more_nested_fields() && !_pack_error) { const DCField *field = get_current_field()->as_field(); - nassertv(field != (DCField *)NULL); + nassertv(field != nullptr); get_class_element(dclass, object, field); } pop(); diff --git a/direct/src/dcparser/dcPacker.h b/direct/src/dcparser/dcPacker.h index 380d40600c..9de32ff2cd 100644 --- a/direct/src/dcparser/dcPacker.h +++ b/direct/src/dcparser/dcPacker.h @@ -41,7 +41,7 @@ PUBLISHED: void begin_pack(const DCPackerInterface *root); bool end_pack(); - void set_unpack_data(const string &data); + void set_unpack_data(const std::string &data); public: void set_unpack_data(const char *unpack_data, size_t unpack_length, bool owns_unpack_data); @@ -53,7 +53,7 @@ PUBLISHED: void begin_repack(const DCPackerInterface *root); bool end_repack(); - bool seek(const string &field_name); + bool seek(const std::string &field_name); bool seek(int seek_index); INLINE bool has_nested_fields() const; @@ -64,7 +64,7 @@ PUBLISHED: INLINE const DCPackerInterface *get_current_field() const; INLINE const DCSwitchParameter *get_last_switch() const; INLINE DCPackType get_pack_type() const; - INLINE string get_current_field_name() const; + INLINE std::string get_current_field_name() const; void push(); void pop(); @@ -74,8 +74,8 @@ PUBLISHED: INLINE void pack_uint(unsigned int value); INLINE void pack_int64(int64_t value); INLINE void pack_uint64(uint64_t value); - INLINE void pack_string(const string &value); - INLINE void pack_literal_value(const string &value); + INLINE void pack_string(const std::string &value); + INLINE void pack_literal_value(const std::string &value); void pack_default_value(); INLINE double unpack_double(); @@ -83,8 +83,8 @@ PUBLISHED: INLINE unsigned int unpack_uint(); INLINE int64_t unpack_int64(); INLINE uint64_t unpack_uint64(); - INLINE string unpack_string(); - INLINE string unpack_literal_value(); + INLINE std::string unpack_string(); + INLINE std::string unpack_literal_value(); void unpack_validate(); void unpack_skip(); @@ -96,8 +96,8 @@ public: INLINE void unpack_uint(unsigned int &value); INLINE void unpack_int64(int64_t &value); INLINE void unpack_uint64(uint64_t &value); - INLINE void unpack_string(string &value); - INLINE void unpack_literal_value(string &value); + INLINE void unpack_string(std::string &value); + INLINE void unpack_literal_value(std::string &value); PUBLISHED: @@ -106,10 +106,10 @@ PUBLISHED: PyObject *unpack_object(); #endif - bool parse_and_pack(const string &formatted_object); - bool parse_and_pack(istream &in); - string unpack_and_format(bool show_field_names = true); - void unpack_and_format(ostream &out, bool show_field_names = true); + bool parse_and_pack(const std::string &formatted_object); + bool parse_and_pack(std::istream &in); + std::string unpack_and_format(bool show_field_names = true); + void unpack_and_format(std::ostream &out, bool show_field_names = true); INLINE bool had_parse_error() const; INLINE bool had_pack_error() const; @@ -118,11 +118,11 @@ PUBLISHED: INLINE size_t get_num_unpacked_bytes() const; INLINE size_t get_length() const; - INLINE string get_string() const; + INLINE std::string get_string() const; INLINE size_t get_unpack_length() const; - INLINE string get_unpack_string() const; + INLINE std::string get_unpack_string() const; public: - INLINE void get_string(string &data) const; + INLINE void get_string(std::string &data) const; INLINE const char *get_data() const; INLINE char *take_data(); @@ -147,7 +147,7 @@ PUBLISHED: INLINE void raw_pack_uint32(unsigned int value); INLINE void raw_pack_uint64(uint64_t value); INLINE void raw_pack_float64(double value); - INLINE void raw_pack_string(const string &value); + INLINE void raw_pack_string(const std::string &value); // this is a hack to allw me to get in and out of 32bit Mode Faster need to // agree with channel_type in dcbase.h @@ -164,7 +164,7 @@ PUBLISHED: INLINE unsigned int raw_unpack_uint32(); INLINE uint64_t raw_unpack_uint64(); INLINE double raw_unpack_float64(); - INLINE string raw_unpack_string(); + INLINE std::string raw_unpack_string(); public: INLINE void raw_unpack_int8(int &value); @@ -176,11 +176,11 @@ public: INLINE void raw_unpack_uint32(unsigned int &value); INLINE void raw_unpack_uint64(uint64_t &value); INLINE void raw_unpack_float64(double &value); - INLINE void raw_unpack_string(string &value); + INLINE void raw_unpack_string(std::string &value); public: - static void enquote_string(ostream &out, char quote_mark, const string &str); - static void output_hex_string(ostream &out, const string &str); + static void enquote_string(std::ostream &out, char quote_mark, const std::string &str); + static void output_hex_string(std::ostream &out, const std::string &str); private: INLINE void advance(); diff --git a/direct/src/dcparser/dcPackerCatalog.I b/direct/src/dcparser/dcPackerCatalog.I index 657609927d..1755db75e8 100644 --- a/direct/src/dcparser/dcPackerCatalog.I +++ b/direct/src/dcparser/dcPackerCatalog.I @@ -52,7 +52,7 @@ get_entry(int n) const { * get_entry(). */ int DCPackerCatalog::LiveCatalog:: -find_entry_by_name(const string &name) const { +find_entry_by_name(const std::string &name) const { return _catalog->find_entry_by_name(name); } diff --git a/direct/src/dcparser/dcPackerCatalog.cxx b/direct/src/dcparser/dcPackerCatalog.cxx index 0f13322009..594c7b6742 100644 --- a/direct/src/dcparser/dcPackerCatalog.cxx +++ b/direct/src/dcparser/dcPackerCatalog.cxx @@ -16,12 +16,14 @@ #include "dcPacker.h" #include "dcSwitchParameter.h" +using std::string; + /** * The catalog is created only by DCPackerInterface::get_catalog(). */ DCPackerCatalog:: DCPackerCatalog(const DCPackerInterface *root) : _root(root) { - _live_catalog = NULL; + _live_catalog = nullptr; } /** @@ -34,7 +36,7 @@ DCPackerCatalog(const DCPackerCatalog ©) : _entries_by_name(copy._entries_by_name), _entries_by_field(copy._entries_by_field) { - _live_catalog = NULL; + _live_catalog = nullptr; } /** @@ -42,7 +44,7 @@ DCPackerCatalog(const DCPackerCatalog ©) : */ DCPackerCatalog:: ~DCPackerCatalog() { - if (_live_catalog != (LiveCatalog *)NULL) { + if (_live_catalog != nullptr) { delete _live_catalog; } @@ -92,7 +94,7 @@ find_entry_by_field(const DCPackerInterface *field) const { */ const DCPackerCatalog::LiveCatalog *DCPackerCatalog:: get_live_catalog(const char *data, size_t length) const { - if (_live_catalog != (LiveCatalog *)NULL) { + if (_live_catalog != nullptr) { // Return the previously-allocated live catalog; it will be the same as // this one since it's based on a fixed-length field. return _live_catalog; @@ -111,13 +113,13 @@ get_live_catalog(const char *data, size_t length) const { DCPacker packer; packer.set_unpack_data(data, length, false); packer.begin_unpack(_root); - const DCSwitchParameter *last_switch = NULL; + const DCSwitchParameter *last_switch = nullptr; r_fill_live_catalog(live_catalog, packer, last_switch); bool okflag = packer.end_unpack(); if (!okflag) { delete live_catalog; - return NULL; + return nullptr; } if (_root->has_fixed_structure()) { @@ -188,7 +190,7 @@ r_fill_catalog(const string &name_prefix, const DCPackerInterface *field, const DCPackerInterface *parent, int field_index) { string next_name_prefix = name_prefix; - if (parent != (const DCPackerInterface *)NULL && !field->get_name().empty()) { + if (parent != nullptr && !field->get_name().empty()) { // Record this entry in the catalog. next_name_prefix += field->get_name(); add_entry(next_name_prefix, field, parent, field_index); @@ -197,7 +199,7 @@ r_fill_catalog(const string &name_prefix, const DCPackerInterface *field, } const DCSwitchParameter *switch_parameter = field->as_switch_parameter(); - if (switch_parameter != (DCSwitchParameter *)NULL) { + if (switch_parameter != nullptr) { // If we come upon a DCSwitch while building the catalog, save the // name_prefix at this point so we'll have it again when we later // encounter the switch while unpacking a live record (and so we can @@ -211,7 +213,7 @@ r_fill_catalog(const string &name_prefix, const DCPackerInterface *field, // It's ok if num_nested is -1. for (int i = 0; i < num_nested; i++) { DCPackerInterface *nested = field->get_nested_field(i); - if (nested != (DCPackerInterface *)NULL) { + if (nested != nullptr) { r_fill_catalog(next_name_prefix, nested, field, i); } } @@ -255,10 +257,10 @@ r_fill_live_catalog(LiveCatalog *live_catalog, DCPacker &packer, last_switch = packer.get_last_switch(); const DCPackerInterface *switch_case = packer.get_current_parent(); - nassertv(switch_case != (DCPackerInterface *)NULL); + nassertv(switch_case != nullptr); const DCPackerCatalog *switch_catalog = live_catalog->_catalog->update_switch_fields(last_switch, switch_case); - nassertv(switch_catalog != (DCPackerCatalog *)NULL); + nassertv(switch_catalog != nullptr); live_catalog->_catalog = switch_catalog; // And we also have to expand the live catalog to hold the new entries. @@ -317,7 +319,7 @@ update_switch_fields(const DCSwitchParameter *switch_parameter, int num_nested = switch_case->get_num_nested_fields(); for (int i = 1; i < num_nested; i++) { DCPackerInterface *nested = switch_case->get_nested_field(i); - if (nested != (DCPackerInterface *)NULL) { + if (nested != nullptr) { switch_catalog->r_fill_catalog(name_prefix, nested, switch_case, i); } } diff --git a/direct/src/dcparser/dcPackerCatalog.h b/direct/src/dcparser/dcPackerCatalog.h index 71469d6744..c03b1b5fc6 100644 --- a/direct/src/dcparser/dcPackerCatalog.h +++ b/direct/src/dcparser/dcPackerCatalog.h @@ -37,7 +37,7 @@ public: // and its relationship to its parent. class Entry { public: - string _name; + std::string _name; const DCPackerInterface *_field; const DCPackerInterface *_parent; int _field_index; @@ -58,7 +58,7 @@ public: INLINE int get_num_entries() const; INLINE const Entry &get_entry(int n) const; - INLINE int find_entry_by_name(const string &name) const; + INLINE int find_entry_by_name(const std::string &name) const; INLINE int find_entry_by_field(const DCPackerInterface *field) const; private: @@ -71,17 +71,17 @@ public: INLINE int get_num_entries() const; INLINE const Entry &get_entry(int n) const; - int find_entry_by_name(const string &name) const; + int find_entry_by_name(const std::string &name) const; int find_entry_by_field(const DCPackerInterface *field) const; const LiveCatalog *get_live_catalog(const char *data, size_t length) const; void release_live_catalog(const LiveCatalog *live_catalog) const; private: - void add_entry(const string &name, const DCPackerInterface *field, + void add_entry(const std::string &name, const DCPackerInterface *field, const DCPackerInterface *parent, int field_index); - void r_fill_catalog(const string &name_prefix, const DCPackerInterface *field, + void r_fill_catalog(const std::string &name_prefix, const DCPackerInterface *field, const DCPackerInterface *parent, int field_index); void r_fill_live_catalog(LiveCatalog *live_catalog, DCPacker &packer, const DCSwitchParameter *&last_switch) const; @@ -96,7 +96,7 @@ private: typedef pvector Entries; Entries _entries; - typedef pmap EntriesByName; + typedef pmap EntriesByName; EntriesByName _entries_by_name; typedef pmap EntriesByField; @@ -105,7 +105,7 @@ private: typedef pmap SwitchCatalogs; SwitchCatalogs _switch_catalogs; - typedef pmap SwitchPrefixes; + typedef pmap SwitchPrefixes; SwitchPrefixes _switch_prefixes; friend class DCPackerInterface; diff --git a/direct/src/dcparser/dcPackerInterface.I b/direct/src/dcparser/dcPackerInterface.I index a97964bc47..160cc4fdd9 100644 --- a/direct/src/dcparser/dcPackerInterface.I +++ b/direct/src/dcparser/dcPackerInterface.I @@ -14,7 +14,7 @@ /** * Returns the name of this field, or empty string if the field is unnamed. */ -INLINE const string &DCPackerInterface:: +INLINE const std::string &DCPackerInterface:: get_name() const { return _name; } diff --git a/direct/src/dcparser/dcPackerInterface.cxx b/direct/src/dcparser/dcPackerInterface.cxx index dc731a479a..d17ff1f7b7 100644 --- a/direct/src/dcparser/dcPackerInterface.cxx +++ b/direct/src/dcparser/dcPackerInterface.cxx @@ -17,6 +17,8 @@ #include "dcParserDefs.h" #include "dcLexerDefs.h" +using std::string; + /** * */ @@ -32,7 +34,7 @@ DCPackerInterface(const string &name) : _has_nested_fields = false; _num_nested_fields = -1; _pack_type = PT_invalid; - _catalog = NULL; + _catalog = nullptr; } /** @@ -50,7 +52,7 @@ DCPackerInterface(const DCPackerInterface ©) : _num_nested_fields(copy._num_nested_fields), _pack_type(copy._pack_type) { - _catalog = NULL; + _catalog = nullptr; } /** @@ -58,7 +60,7 @@ DCPackerInterface(const DCPackerInterface ©) : */ DCPackerInterface:: ~DCPackerInterface() { - if (_catalog != (DCPackerCatalog *)NULL) { + if (_catalog != nullptr) { delete _catalog; } } @@ -83,7 +85,7 @@ find_seek_index(const string &name) const { */ DCField *DCPackerInterface:: as_field() { - return (DCField *)NULL; + return nullptr; } /** @@ -91,7 +93,7 @@ as_field() { */ const DCField *DCPackerInterface:: as_field() const { - return (DCField *)NULL; + return nullptr; } /** @@ -99,7 +101,7 @@ as_field() const { */ DCSwitchParameter *DCPackerInterface:: as_switch_parameter() { - return (DCSwitchParameter *)NULL; + return nullptr; } /** @@ -107,7 +109,7 @@ as_switch_parameter() { */ const DCSwitchParameter *DCPackerInterface:: as_switch_parameter() const { - return (DCSwitchParameter *)NULL; + return nullptr; } /** @@ -115,7 +117,7 @@ as_switch_parameter() const { */ DCClassParameter *DCPackerInterface:: as_class_parameter() { - return (DCClassParameter *)NULL; + return nullptr; } /** @@ -123,7 +125,7 @@ as_class_parameter() { */ const DCClassParameter *DCPackerInterface:: as_class_parameter() const { - return (DCClassParameter *)NULL; + return nullptr; } /** @@ -139,13 +141,13 @@ bool DCPackerInterface:: check_match(const string &description, DCFile *dcfile) const { bool match = false; - istringstream strm(description); + std::istringstream strm(description); dc_init_parser_parameter_description(strm, "check_match", dcfile); dcyyparse(); dc_cleanup_parser(); DCField *field = dc_get_parameter_description(); - if (field != NULL) { + if (field != nullptr) { match = check_match(field); delete field; } @@ -184,7 +186,7 @@ calc_num_nested_fields(size_t) const { */ DCPackerInterface *DCPackerInterface:: get_nested_field(int) const { - return NULL; + return nullptr; } /** @@ -367,7 +369,7 @@ unpack_skip(const char *data, size_t length, size_t &p, */ const DCPackerCatalog *DCPackerInterface:: get_catalog() const { - if (_catalog == (DCPackerCatalog *)NULL) { + if (_catalog == nullptr) { ((DCPackerInterface *)this)->make_catalog(); } return _catalog; @@ -432,8 +434,8 @@ do_check_match_molecular_field(const DCMolecularField *) const { */ void DCPackerInterface:: make_catalog() { - nassertv(_catalog == (DCPackerCatalog *)NULL); + nassertv(_catalog == nullptr); _catalog = new DCPackerCatalog(this); - _catalog->r_fill_catalog("", this, NULL, 0); + _catalog->r_fill_catalog("", this, nullptr, 0); } diff --git a/direct/src/dcparser/dcPackerInterface.h b/direct/src/dcparser/dcPackerInterface.h index 42284ac54f..171ed3f0ca 100644 --- a/direct/src/dcparser/dcPackerInterface.h +++ b/direct/src/dcparser/dcPackerInterface.h @@ -66,13 +66,13 @@ END_PUBLISH */ class DCPackerInterface { public: - DCPackerInterface(const string &name = string()); + DCPackerInterface(const std::string &name = std::string()); DCPackerInterface(const DCPackerInterface ©); virtual ~DCPackerInterface(); PUBLISHED: - INLINE const string &get_name() const; - int find_seek_index(const string &name) const; + INLINE const std::string &get_name() const; + int find_seek_index(const std::string &name) const; virtual DCField *as_field(); virtual const DCField *as_field() const; @@ -82,10 +82,10 @@ PUBLISHED: virtual const DCClassParameter *as_class_parameter() const; INLINE bool check_match(const DCPackerInterface *other) const; - bool check_match(const string &description, DCFile *dcfile = NULL) const; + bool check_match(const std::string &description, DCFile *dcfile = nullptr) const; public: - virtual void set_name(const string &name); + virtual void set_name(const std::string &name); INLINE bool has_fixed_byte_size() const; INLINE size_t get_fixed_byte_size() const; INLINE bool has_fixed_structure() const; @@ -111,7 +111,7 @@ public: bool &pack_error, bool &range_error) const; virtual void pack_uint64(DCPackData &pack_data, uint64_t value, bool &pack_error, bool &range_error) const; - virtual void pack_string(DCPackData &pack_data, const string &value, + virtual void pack_string(DCPackData &pack_data, const std::string &value, bool &pack_error, bool &range_error) const; virtual bool pack_default_value(DCPackData &pack_data, bool &pack_error) const; @@ -126,7 +126,7 @@ public: virtual void unpack_uint64(const char *data, size_t length, size_t &p, uint64_t &value, bool &pack_error, bool &range_error) const; virtual void unpack_string(const char *data, size_t length, size_t &p, - string &value, bool &pack_error, bool &range_error) const; + std::string &value, bool &pack_error, bool &range_error) const; virtual bool unpack_validate(const char *data, size_t length, size_t &p, bool &pack_error, bool &range_error) const; virtual bool unpack_skip(const char *data, size_t length, size_t &p, @@ -184,7 +184,7 @@ private: void make_catalog(); protected: - string _name; + std::string _name; bool _has_fixed_byte_size; size_t _fixed_byte_size; bool _has_fixed_structure; diff --git a/direct/src/dcparser/dcParameter.cxx b/direct/src/dcparser/dcParameter.cxx index a1fcfecca7..61b13ff04a 100644 --- a/direct/src/dcparser/dcParameter.cxx +++ b/direct/src/dcparser/dcParameter.cxx @@ -17,12 +17,15 @@ #include "dcindent.h" #include "dcTypedef.h" +using std::ostream; +using std::string; + /** * */ DCParameter:: DCParameter() { - _typedef = NULL; + _typedef = nullptr; _has_fixed_byte_size = false; _has_fixed_structure = false; _num_nested_fields = -1; @@ -66,7 +69,7 @@ as_parameter() const { */ DCSimpleParameter *DCParameter:: as_simple_parameter() { - return NULL; + return nullptr; } /** @@ -74,7 +77,7 @@ as_simple_parameter() { */ const DCSimpleParameter *DCParameter:: as_simple_parameter() const { - return NULL; + return nullptr; } /** @@ -82,7 +85,7 @@ as_simple_parameter() const { */ DCClassParameter *DCParameter:: as_class_parameter() { - return NULL; + return nullptr; } /** @@ -90,7 +93,7 @@ as_class_parameter() { */ const DCClassParameter *DCParameter:: as_class_parameter() const { - return NULL; + return nullptr; } /** @@ -98,7 +101,7 @@ as_class_parameter() const { */ DCSwitchParameter *DCParameter:: as_switch_parameter() { - return NULL; + return nullptr; } /** @@ -106,7 +109,7 @@ as_switch_parameter() { */ const DCSwitchParameter *DCParameter:: as_switch_parameter() const { - return NULL; + return nullptr; } /** @@ -114,7 +117,7 @@ as_switch_parameter() const { */ DCArrayParameter *DCParameter:: as_array_parameter() { - return NULL; + return nullptr; } /** @@ -122,7 +125,7 @@ as_array_parameter() { */ const DCArrayParameter *DCParameter:: as_array_parameter() const { - return NULL; + return nullptr; } /** diff --git a/direct/src/dcparser/dcParameter.h b/direct/src/dcparser/dcParameter.h index 6c8ae910a6..59a34dc440 100644 --- a/direct/src/dcparser/dcParameter.h +++ b/direct/src/dcparser/dcParameter.h @@ -60,18 +60,18 @@ public: void set_typedef(const DCTypedef *dtypedef); virtual DCParameter *append_array_specification(const DCUnsignedIntRange &size); - virtual void output(ostream &out, bool brief) const; - virtual void write(ostream &out, bool brief, int indent_level) const; - virtual void output_instance(ostream &out, bool brief, const string &prename, - const string &name, const string &postname) const=0; - virtual void write_instance(ostream &out, bool brief, int indent_level, - const string &prename, const string &name, - const string &postname) const; - void output_typedef_name(ostream &out, bool brief, const string &prename, - const string &name, const string &postname) const; - void write_typedef_name(ostream &out, bool brief, int indent_level, - const string &prename, const string &name, - const string &postname) const; + virtual void output(std::ostream &out, bool brief) const; + virtual void write(std::ostream &out, bool brief, int indent_level) const; + virtual void output_instance(std::ostream &out, bool brief, const std::string &prename, + const std::string &name, const std::string &postname) const=0; + virtual void write_instance(std::ostream &out, bool brief, int indent_level, + const std::string &prename, const std::string &name, + const std::string &postname) const; + void output_typedef_name(std::ostream &out, bool brief, const std::string &prename, + const std::string &name, const std::string &postname) const; + void write_typedef_name(std::ostream &out, bool brief, int indent_level, + const std::string &prename, const std::string &name, + const std::string &postname) const; virtual void generate_hash(HashGenerator &hashgen) const; private: diff --git a/direct/src/dcparser/dcParser.cxx.prebuilt b/direct/src/dcparser/dcParser.cxx.prebuilt index a7f911e452..80df4b2b09 100644 --- a/direct/src/dcparser/dcParser.cxx.prebuilt +++ b/direct/src/dcparser/dcParser.cxx.prebuilt @@ -101,6 +101,10 @@ #define YYINITDEPTH 1000 #define YYMAXDEPTH 1000 +using std::istream; +using std::ostringstream; +using std::string; + DCFile *dc_file = (DCFile *)NULL; static DCClass *current_class = (DCClass *)NULL; static DCSwitch *current_switch = (DCSwitch *)NULL; diff --git a/direct/src/dcparser/dcParser.yxx b/direct/src/dcparser/dcParser.yxx index 5c39b398e4..0a5c3d6aa0 100644 --- a/direct/src/dcparser/dcParser.yxx +++ b/direct/src/dcparser/dcParser.yxx @@ -29,18 +29,22 @@ #define YYINITDEPTH 1000 #define YYMAXDEPTH 1000 -DCFile *dc_file = (DCFile *)NULL; -static DCClass *current_class = (DCClass *)NULL; -static DCSwitch *current_switch = (DCSwitch *)NULL; -static DCAtomicField *current_atomic = (DCAtomicField *)NULL; -static DCMolecularField *current_molecular = (DCMolecularField *)NULL; -static DCParameter *current_parameter = (DCParameter *)NULL; +using std::istream; +using std::ostringstream; +using std::string; + +DCFile *dc_file = nullptr; +static DCClass *current_class = nullptr; +static DCSwitch *current_switch = nullptr; +static DCAtomicField *current_atomic = nullptr; +static DCMolecularField *current_molecular = nullptr; +static DCParameter *current_parameter = nullptr; static DCKeywordList current_keyword_list; static DCPacker default_packer; static DCPacker *current_packer; static DCDoubleRange double_range; static DCUnsignedIntRange uint_range; -static DCField *parameter_description = (DCField *)NULL; +static DCField *parameter_description = nullptr; //////////////////////////////////////////////////////////////////// // Defining the interface to the parser. @@ -55,7 +59,7 @@ dc_init_parser(istream &in, const string &filename, DCFile &file) { void dc_init_parser_parameter_value(istream &in, const string &filename, DCPacker &packer) { - dc_file = NULL; + dc_file = nullptr; current_packer = &packer; dc_init_lexer(in, filename); dc_start_parameter_value(); @@ -66,7 +70,7 @@ dc_init_parser_parameter_description(istream &in, const string &filename, DCFile *file) { dc_file = file; dc_init_lexer(in, filename); - parameter_description = NULL; + parameter_description = nullptr; dc_start_parameter_description(); } @@ -77,7 +81,7 @@ dc_get_parameter_description() { void dc_cleanup_parser() { - dc_file = (DCFile *)NULL; + dc_file = nullptr; } %} @@ -181,7 +185,7 @@ dc: { if (!dc_file->add_class($2)) { DCClass *old_class = dc_file->get_class_by_name($2->get_name()); - if (old_class != (DCClass *)NULL && old_class->is_bogus_class()) { + if (old_class != nullptr && old_class->is_bogus_class()) { yyerror("Base class defined after its first reference: " + $2->get_name()); } else { yyerror("Duplicate class name: " + $2->get_name()); @@ -249,7 +253,7 @@ import_symbol_list: typedef_decl: KW_TYPEDEF parameter_with_default { - if ($2 != (DCParameter *)NULL) { + if ($2 != nullptr) { DCTypedef *dtypedef = new DCTypedef($2); if (!dc_file->add_typedef(dtypedef)) { @@ -304,13 +308,13 @@ dclass: dclass_name: IDENTIFIER { - if (dc_file == (DCFile *)NULL) { + if (dc_file == nullptr) { yyerror("No DCFile available, so no class names are predefined."); - $$ = NULL; + $$ = nullptr; } else { DCClass *dclass = dc_file->get_class_by_name($1); - if (dclass == (DCClass *)NULL) { + if (dclass == nullptr) { // Create a bogus class as a forward reference. dclass = new DCClass(dc_file, $1, false, true); dc_file->add_class(dclass); @@ -332,7 +336,7 @@ dclass_derivation: dclass_base_list: dclass_name { - if ($1 != (DCClass *)NULL) { + if ($1 != nullptr) { current_class->add_parent($1); } } @@ -342,7 +346,7 @@ dclass_base_list: yyerror("Multiple inheritance is not supported without \"dc-multiple-inheritance 1\" in your Config.prc file."); } else { - if ($3 != (DCClass *)NULL) { + if ($3 != nullptr) { current_class->add_parent($3); } } @@ -354,7 +358,7 @@ dclass_fields: | dclass_fields ';' | dclass_fields dclass_field ';' { - if ($2 == (DCField *)NULL) { + if ($2 == nullptr) { // Pass this error up. } else if (!current_class->add_field($2)) { yyerror("Duplicate field name: " + $2->get_name()); @@ -367,7 +371,7 @@ dclass_fields: dclass_field: atomic_field keyword_list { - if ($1 != (DCField *)NULL) { + if ($1 != nullptr) { if ($1->get_name().empty()) { yyerror("Field name required."); } @@ -379,14 +383,14 @@ dclass_field: | unnamed_parameter_with_default keyword_list { yyerror("Unnamed parameters are not allowed on a dclass"); - if ($1 != (DCField *)NULL) { + if ($1 != nullptr) { $1->copy_keywords(current_keyword_list); } $$ = $1; } | named_parameter_with_default keyword_list { - if ($1 != (DCField *)NULL) { + if ($1 != nullptr) { $1->copy_keywords(current_keyword_list); } $$ = $1; @@ -408,13 +412,13 @@ struct: struct_name: IDENTIFIER { - if (dc_file == (DCFile *)NULL) { + if (dc_file == nullptr) { yyerror("No DCFile available, so no struct names are predefined."); - $$ = NULL; + $$ = nullptr; } else { DCClass *dstruct = dc_file->get_class_by_name($1); - if (dstruct == (DCClass *)NULL) { + if (dstruct == nullptr) { // Create a bogus class as a forward reference. dstruct = new DCClass(dc_file, $1, false, true); dc_file->add_class(dstruct); @@ -436,13 +440,13 @@ struct_derivation: struct_base_list: struct_name { - if ($1 != (DCClass *)NULL) { + if ($1 != nullptr) { current_class->add_parent($1); } } | struct_base_list ',' struct_name { - if ($3 != (DCClass *)NULL) { + if ($3 != nullptr) { current_class->add_parent($3); } } @@ -453,7 +457,7 @@ struct_fields: | struct_fields ';' | struct_fields struct_field ';' { - if ($2 == (DCField *)NULL) { + if ($2 == nullptr) { // Pass this error up. } else if (!current_class->add_field($2)) { yyerror("Duplicate field name: " + $2->get_name()); @@ -483,7 +487,7 @@ struct_field: atomic_field: optional_name '(' { - if (current_class == (DCClass *)NULL) { + if (current_class == nullptr) { yyerror("Cannot define a method outside of a struct or class."); DCClass *temp_class = new DCClass(dc_file, "temp", false, false); // memory leak. current_atomic = new DCAtomicField($1, temp_class, false); @@ -511,7 +515,7 @@ nonempty_parameter_list: atomic_element: parameter_with_default { - if ($1 != (DCParameter *)NULL) { + if ($1 != nullptr) { current_atomic->add_element($1); } } @@ -538,14 +542,14 @@ named_parameter_with_default: { current_packer = &default_packer; current_packer->clear_data(); - if ($1 != (DCField *)NULL) { + if ($1 != nullptr) { current_packer->begin_pack($1); } } parameter_value { bool is_valid = false; - if ($1 != (DCField *)NULL) { + if ($1 != nullptr) { is_valid = $1->is_valid(); } if (current_packer->end_pack()) { @@ -568,14 +572,14 @@ unnamed_parameter_with_default: { current_packer = &default_packer; current_packer->clear_data(); - if ($1 != (DCField *)NULL) { + if ($1 != nullptr) { current_packer->begin_pack($1); } } parameter_value { bool is_valid = false; - if ($1 != (DCField *)NULL) { + if ($1 != nullptr) { is_valid = $1->is_valid(); } if (current_packer->end_pack()) { @@ -636,7 +640,7 @@ simple_type_name: | simple_type_name '(' double_range ')' { DCSimpleParameter *simple_param = $1->as_simple_parameter(); - nassertr(simple_param != (DCSimpleParameter *)NULL, 0); + nassertr(simple_param != nullptr, 0); if (!simple_param->set_range(double_range)) { yyerror("Inappropriate range for type"); } @@ -645,7 +649,7 @@ simple_type_name: | simple_type_name '/' small_unsigned_integer { DCSimpleParameter *simple_param = $1->as_simple_parameter(); - nassertr(simple_param != (DCSimpleParameter *)NULL, 0); + nassertr(simple_param != nullptr, 0); if (!simple_param->is_numeric_type()) { yyerror("A divisor is only valid on a numeric type."); @@ -661,7 +665,7 @@ simple_type_name: | simple_type_name '%' number { DCSimpleParameter *simple_param = $1->as_simple_parameter(); - nassertr(simple_param != (DCSimpleParameter *)NULL, 0); + nassertr(simple_param != nullptr, 0); if (!simple_param->is_numeric_type()) { yyerror("A divisor is only valid on a numeric type."); @@ -676,22 +680,22 @@ type_name: simple_type_name | IDENTIFIER { - if (dc_file == (DCFile *)NULL) { + if (dc_file == nullptr) { yyerror("Invalid type."); - $$ = NULL; + $$ = nullptr; } else { DCTypedef *dtypedef = dc_file->get_typedef_by_name($1); - if (dtypedef == (DCTypedef *)NULL) { + if (dtypedef == nullptr) { // Maybe it's a class name. DCClass *dclass = dc_file->get_class_by_name($1); - if (dclass != (DCClass *)NULL) { + if (dclass != nullptr) { // Create an implicit typedef for this. dtypedef = new DCTypedef(new DCClassParameter(dclass), true); } else { // Maybe it's a switch name. DCSwitch *dswitch = dc_file->get_switch_by_name($1); - if (dswitch != (DCSwitch *)NULL) { + if (dswitch != nullptr) { // This also gets an implicit typedef. dtypedef = new DCTypedef(new DCSwitchParameter(dswitch), true); } else { @@ -709,10 +713,10 @@ type_name: | struct { // This is an inline struct definition. - if ($1 == (DCClass *)NULL) { - $$ = NULL; + if ($1 == nullptr) { + $$ = nullptr; } else { - if (dc_file != (DCFile *)NULL) { + if (dc_file != nullptr) { dc_file->add_thing_to_delete($1); } else { // This is a memory leak--this happens when we put an anonymous @@ -725,10 +729,10 @@ type_name: | switch { // This is an inline switch definition. - if ($1 == (DCSwitch *)NULL) { - $$ = NULL; + if ($1 == nullptr) { + $$ = nullptr; } else { - if (dc_file != (DCFile *)NULL) { + if (dc_file != nullptr) { dc_file->add_thing_to_delete($1); } else { // This is a memory leak--this happens when we put an anonymous @@ -840,8 +844,8 @@ type_definition: type_name | type_definition '[' uint_range ']' { - if ($1 == (DCParameter *)NULL) { - $$ = NULL; + if ($1 == nullptr) { + $$ = nullptr; } else { $$ = $1->append_array_specification(uint_range); } @@ -857,7 +861,7 @@ parameter_definition: | parameter_definition '/' small_unsigned_integer { DCSimpleParameter *simple_param = $1->as_simple_parameter(); - if (simple_param == NULL || simple_param->get_typedef() != (DCTypedef *)NULL) { + if (simple_param == nullptr || simple_param->get_typedef() != nullptr) { yyerror("A divisor is only allowed on a primitive type."); } else if (!simple_param->is_numeric_type()) { @@ -872,7 +876,7 @@ parameter_definition: | parameter_definition '%' number { DCSimpleParameter *simple_param = $1->as_simple_parameter(); - if (simple_param == NULL || simple_param->get_typedef() != (DCTypedef *)NULL) { + if (simple_param == nullptr || simple_param->get_typedef() != nullptr) { yyerror("A modulus is only allowed on a primitive type."); } else if (!simple_param->is_numeric_type()) { @@ -1184,8 +1188,8 @@ atomic_name: IDENTIFIER { DCField *field = current_class->get_field_by_name($1); - $$ = (DCAtomicField *)NULL; - if (field == (DCField *)NULL) { + $$ = nullptr; + if (field == nullptr) { // Maybe the field is unknown because the class is partially // bogus. In that case, allow it for now; create a bogus field as // a placeholder. @@ -1200,7 +1204,7 @@ atomic_name: } else { $$ = field->as_atomic_field(); - if ($$ == (DCAtomicField *)NULL) { + if ($$ == nullptr) { yyerror("Not an atomic field: " + $1); } } @@ -1210,13 +1214,13 @@ atomic_name: molecular_atom_list: atomic_name { - if ($1 != (DCAtomicField *)NULL) { + if ($1 != nullptr) { current_molecular->add_atomic($1); } } | molecular_atom_list ',' atomic_name { - if ($3 != (DCAtomicField *)NULL) { + if ($3 != nullptr) { current_molecular->add_atomic($3); if (!$3->is_bogus_field() && !current_molecular->compare_keywords(*$3)) { yyerror("Mismatched keywords in molecule between " + @@ -1258,7 +1262,7 @@ switch_fields: { if (!current_switch->is_field_valid()) { yyerror("case declaration required before first element"); - } else if ($2 != (DCField *)NULL) { + } else if ($2 != nullptr) { if (!current_switch->add_field($2)) { yyerror("Duplicate field name: " + $2->get_name()); } diff --git a/direct/src/dcparser/dcParserDefs.h b/direct/src/dcparser/dcParserDefs.h index fec0ab95a5..da1747ab15 100644 --- a/direct/src/dcparser/dcParserDefs.h +++ b/direct/src/dcparser/dcParserDefs.h @@ -26,10 +26,10 @@ class DCParameter; class DCKeyword; class DCPacker; -void dc_init_parser(istream &in, const string &filename, DCFile &file); -void dc_init_parser_parameter_value(istream &in, const string &filename, +void dc_init_parser(std::istream &in, const std::string &filename, DCFile &file); +void dc_init_parser_parameter_value(std::istream &in, const std::string &filename, DCPacker &packer); -void dc_init_parser_parameter_description(istream &in, const string &filename, +void dc_init_parser_parameter_description(std::istream &in, const std::string &filename, DCFile *file); DCField *dc_get_parameter_description(); void dc_cleanup_parser(); @@ -60,7 +60,7 @@ public: DCParameter *parameter; const DCKeyword *keyword; } u; - string str; + std::string str; }; // The yacc-generated code expects to use the symbol 'YYSTYPE' to refer to the diff --git a/direct/src/dcparser/dcSimpleParameter.cxx b/direct/src/dcparser/dcSimpleParameter.cxx index bd1d6cd086..bd2cb05534 100644 --- a/direct/src/dcparser/dcSimpleParameter.cxx +++ b/direct/src/dcparser/dcSimpleParameter.cxx @@ -20,8 +20,10 @@ #include "hashGenerator.h" #include +using std::string; + DCSimpleParameter::NestedFieldMap DCSimpleParameter::_nested_field_map; -DCClassParameter *DCSimpleParameter::_uint32uint8_type = NULL; +DCClassParameter *DCSimpleParameter::_uint32uint8_type = nullptr; /** * @@ -186,7 +188,7 @@ DCSimpleParameter(DCSubatomicType type, unsigned int divisor) : _nested_field = create_uint32uint8_type(); } else { - _nested_field = NULL; + _nested_field = nullptr; } } @@ -2171,9 +2173,9 @@ unpack_skip(const char *data, size_t length, size_t &p, * identifier. */ void DCSimpleParameter:: -output_instance(ostream &out, bool brief, const string &prename, +output_instance(std::ostream &out, bool brief, const string &prename, const string &name, const string &postname) const { - if (get_typedef() != (DCTypedef *)NULL) { + if (get_typedef() != nullptr) { output_typedef_name(out, brief, prename, name, postname); } else { @@ -2342,7 +2344,7 @@ do_check_match_array_parameter(const DCArrayParameter *other) const { // We cannot match a fixed-size array. return false; } - if (_nested_field == NULL) { + if (_nested_field == nullptr) { // Only an array-style simple parameter can match a DCArrayParameter. return false; } @@ -2374,8 +2376,8 @@ create_nested_field(DCSubatomicType type, unsigned int divisor) { */ DCPackerInterface *DCSimpleParameter:: create_uint32uint8_type() { - if (_uint32uint8_type == NULL) { - DCClass *dclass = new DCClass(NULL, "", true, false); + if (_uint32uint8_type == nullptr) { + DCClass *dclass = new DCClass(nullptr, "", true, false); dclass->add_field(new DCSimpleParameter(ST_uint32)); dclass->add_field(new DCSimpleParameter(ST_uint8)); _uint32uint8_type = new DCClassParameter(dclass); diff --git a/direct/src/dcparser/dcSimpleParameter.h b/direct/src/dcparser/dcSimpleParameter.h index 5e2e39c498..b6da9a8bff 100644 --- a/direct/src/dcparser/dcSimpleParameter.h +++ b/direct/src/dcparser/dcSimpleParameter.h @@ -60,7 +60,7 @@ public: bool &pack_error, bool &range_error) const; virtual void pack_uint64(DCPackData &pack_data, uint64_t value, bool &pack_error, bool &range_error) const; - virtual void pack_string(DCPackData &pack_data, const string &value, + virtual void pack_string(DCPackData &pack_data, const std::string &value, bool &pack_error, bool &range_error) const; virtual bool pack_default_value(DCPackData &pack_data, bool &pack_error) const; @@ -75,14 +75,14 @@ public: virtual void unpack_uint64(const char *data, size_t length, size_t &p, uint64_t &value, bool &pack_error, bool &range_error) const; virtual void unpack_string(const char *data, size_t length, size_t &p, - string &value, bool &pack_error, bool &range_error) const; + std::string &value, bool &pack_error, bool &range_error) const; virtual bool unpack_validate(const char *data, size_t length, size_t &p, bool &pack_error, bool &range_error) const; virtual bool unpack_skip(const char *data, size_t length, size_t &p, bool &pack_error) const; - virtual void output_instance(ostream &out, bool brief, const string &prename, - const string &name, const string &postname) const; + virtual void output_instance(std::ostream &out, bool brief, const std::string &prename, + const std::string &name, const std::string &postname) const; virtual void generate_hash(HashGenerator &hashgen) const; protected: diff --git a/direct/src/dcparser/dcSubatomicType.cxx b/direct/src/dcparser/dcSubatomicType.cxx index 1489fe3a3f..841edf7155 100644 --- a/direct/src/dcparser/dcSubatomicType.cxx +++ b/direct/src/dcparser/dcSubatomicType.cxx @@ -13,8 +13,8 @@ #include "dcSubatomicType.h" -ostream & -operator << (ostream &out, DCSubatomicType type) { +std::ostream & +operator << (std::ostream &out, DCSubatomicType type) { switch (type) { case ST_int8: return out << "int8"; diff --git a/direct/src/dcparser/dcSubatomicType.h b/direct/src/dcparser/dcSubatomicType.h index 383533857b..03b0f68fd4 100644 --- a/direct/src/dcparser/dcSubatomicType.h +++ b/direct/src/dcparser/dcSubatomicType.h @@ -60,6 +60,6 @@ enum DCSubatomicType { }; END_PUBLISH -ostream &operator << (ostream &out, DCSubatomicType type); +std::ostream &operator << (std::ostream &out, DCSubatomicType type); #endif diff --git a/direct/src/dcparser/dcSwitch.cxx b/direct/src/dcparser/dcSwitch.cxx index 0215a9919c..5b23505209 100644 --- a/direct/src/dcparser/dcSwitch.cxx +++ b/direct/src/dcparser/dcSwitch.cxx @@ -18,6 +18,9 @@ #include "dcindent.h" #include "dcPacker.h" +using std::ostream; +using std::string; + /** * The key_parameter must be recently allocated via new; it will be deleted * via delete when the switch destructs. @@ -27,7 +30,7 @@ DCSwitch(const string &name, DCField *key_parameter) : _name(name), _key_parameter(key_parameter) { - _default_case = NULL; + _default_case = nullptr; _fields_added = false; } @@ -36,7 +39,7 @@ DCSwitch(const string &name, DCField *key_parameter) : */ DCSwitch:: ~DCSwitch() { - nassertv(_key_parameter != (DCField *)NULL); + nassertv(_key_parameter != nullptr); delete _key_parameter; Cases::iterator ci; @@ -121,7 +124,7 @@ get_case_by_value(const string &case_value) const { */ DCPackerInterface *DCSwitch:: get_case(int n) const { - nassertr(n >= 0 && n < (int)_cases.size(), NULL); + nassertr(n >= 0 && n < (int)_cases.size(), nullptr); return _cases[n]->_fields; } @@ -157,8 +160,8 @@ get_num_fields(int case_index) const { */ DCField *DCSwitch:: get_field(int case_index, int n) const { - nassertr(case_index >= 0 && case_index < (int)_cases.size(), NULL); - nassertr(n >= 0 && n < (int)_cases[case_index]->_fields->_fields.size(), NULL); + nassertr(case_index >= 0 && case_index < (int)_cases.size(), nullptr); + nassertr(n >= 0 && n < (int)_cases[case_index]->_fields->_fields.size(), nullptr); return _cases[case_index]->_fields->_fields[n]; } @@ -168,7 +171,7 @@ get_field(int case_index, int n) const { */ DCField *DCSwitch:: get_field_by_name(int case_index, const string &name) const { - nassertr(case_index >= 0 && case_index < (int)_cases.size(), NULL); + nassertr(case_index >= 0 && case_index < (int)_cases.size(), nullptr); const FieldsByName &fields_by_name = _cases[case_index]->_fields->_fields_by_name; FieldsByName::const_iterator ni; @@ -177,7 +180,7 @@ get_field_by_name(int case_index, const string &name) const { return (*ni).second; } - return NULL; + return nullptr; } /** @@ -226,7 +229,7 @@ add_invalid_case() { */ bool DCSwitch:: add_default() { - if (_default_case != (SwitchFields *)NULL) { + if (_default_case != nullptr) { add_invalid_case(); return false; } @@ -286,12 +289,12 @@ apply_switch(const char *value_data, size_t length) const { } // Unexpected value--use the default. - if (_default_case != (SwitchFields *)NULL) { + if (_default_case != nullptr) { return _default_case; } // No default. - return NULL; + return nullptr; } /** @@ -326,26 +329,26 @@ output_instance(ostream &out, bool brief, const string &prename, _key_parameter->output(out, brief); out << ") {"; - const SwitchFields *last_fields = NULL; + const SwitchFields *last_fields = nullptr; Cases::const_iterator ci; for (ci = _cases.begin(); ci != _cases.end(); ++ci) { const SwitchCase *dcase = (*ci); - if (dcase->_fields != last_fields && last_fields != (SwitchFields *)NULL) { + if (dcase->_fields != last_fields && last_fields != nullptr) { last_fields->output(out, brief); } last_fields = dcase->_fields; out << "case " << _key_parameter->format_data(dcase->_value, false) << ": "; } - if (_default_case != (SwitchFields *)NULL) { - if (_default_case != last_fields && last_fields != (SwitchFields *)NULL) { + if (_default_case != nullptr) { + if (_default_case != last_fields && last_fields != nullptr) { last_fields->output(out, brief); } last_fields = _default_case; out << "default: "; } - if (last_fields != (SwitchFields *)NULL) { + if (last_fields != nullptr) { last_fields->output(out, brief); } @@ -372,12 +375,12 @@ write_instance(ostream &out, bool brief, int indent_level, _key_parameter->output(out, brief); out << ") {\n"; - const SwitchFields *last_fields = NULL; + const SwitchFields *last_fields = nullptr; Cases::const_iterator ci; for (ci = _cases.begin(); ci != _cases.end(); ++ci) { const SwitchCase *dcase = (*ci); - if (dcase->_fields != last_fields && last_fields != (SwitchFields *)NULL) { + if (dcase->_fields != last_fields && last_fields != nullptr) { last_fields->write(out, brief, indent_level + 2); } last_fields = dcase->_fields; @@ -385,15 +388,15 @@ write_instance(ostream &out, bool brief, int indent_level, << "case " << _key_parameter->format_data(dcase->_value, false) << ":\n"; } - if (_default_case != (SwitchFields *)NULL) { - if (_default_case != last_fields && last_fields != (SwitchFields *)NULL) { + if (_default_case != nullptr) { + if (_default_case != last_fields && last_fields != nullptr) { last_fields->write(out, brief, indent_level + 2); } last_fields = _default_case; indent(out, indent_level) << "default:\n"; } - if (last_fields != (SwitchFields *)NULL) { + if (last_fields != nullptr) { last_fields->write(out, brief, indent_level + 2); } @@ -428,7 +431,7 @@ generate_hash(HashGenerator &hashgen) const { } } - if (_default_case != (SwitchFields *)NULL) { + if (_default_case != nullptr) { const SwitchFields *fields = _default_case; hashgen.add_int(fields->_fields.size()); Fields::const_iterator fi; @@ -446,7 +449,7 @@ generate_hash(HashGenerator &hashgen) const { */ bool DCSwitch:: pack_default_value(DCPackData &pack_data, bool &pack_error) const { - SwitchFields *fields = NULL; + SwitchFields *fields = nullptr; DCPacker packer; packer.begin_pack(_key_parameter); if (!_cases.empty()) { @@ -466,7 +469,7 @@ pack_default_value(DCPackData &pack_data, bool &pack_error) const { pack_error = true; } - if (fields == (SwitchFields *)NULL) { + if (fields == nullptr) { pack_error = true; } else { @@ -528,7 +531,7 @@ do_check_match_switch(const DCSwitch *other) const { */ DCSwitch::SwitchFields *DCSwitch:: start_new_case() { - SwitchFields *fields = NULL; + SwitchFields *fields = nullptr; if (_current_fields.empty() || _fields_added) { // If we have recently encountered a break (which removes all of the @@ -587,7 +590,7 @@ DCSwitch::SwitchFields:: */ DCPackerInterface *DCSwitch::SwitchFields:: get_nested_field(int n) const { - nassertr(n >= 0 && n < (int)_fields.size(), NULL); + nassertr(n >= 0 && n < (int)_fields.size(), nullptr); return _fields[n]; } diff --git a/direct/src/dcparser/dcSwitch.h b/direct/src/dcparser/dcSwitch.h index 77eefdbb6f..17e4e856a2 100644 --- a/direct/src/dcparser/dcSwitch.h +++ b/direct/src/dcparser/dcSwitch.h @@ -29,29 +29,29 @@ class DCField; */ class DCSwitch : public DCDeclaration { public: - DCSwitch(const string &name, DCField *key_parameter); + DCSwitch(const std::string &name, DCField *key_parameter); virtual ~DCSwitch(); PUBLISHED: virtual DCSwitch *as_switch(); virtual const DCSwitch *as_switch() const; - const string &get_name() const; + const std::string &get_name() const; DCField *get_key_parameter() const; int get_num_cases() const; - int get_case_by_value(const string &case_value) const; + int get_case_by_value(const std::string &case_value) const; DCPackerInterface *get_case(int n) const; DCPackerInterface *get_default_case() const; - string get_value(int case_index) const; + std::string get_value(int case_index) const; int get_num_fields(int case_index) const; DCField *get_field(int case_index, int n) const; - DCField *get_field_by_name(int case_index, const string &name) const; + DCField *get_field_by_name(int case_index, const std::string &name) const; public: bool is_field_valid() const; - int add_case(const string &value); + int add_case(const std::string &value); void add_invalid_case(); bool add_default(); bool add_field(DCField *field); @@ -59,13 +59,13 @@ public: const DCPackerInterface *apply_switch(const char *value_data, size_t length) const; - virtual void output(ostream &out, bool brief) const; - virtual void write(ostream &out, bool brief, int indent_level) const; - void output_instance(ostream &out, bool brief, const string &prename, - const string &name, const string &postname) const; - void write_instance(ostream &out, bool brief, int indent_level, - const string &prename, const string &name, - const string &postname) const; + virtual void output(std::ostream &out, bool brief) const; + virtual void write(std::ostream &out, bool brief, int indent_level) const; + void output_instance(std::ostream &out, bool brief, const std::string &prename, + const std::string &name, const std::string &postname) const; + void write_instance(std::ostream &out, bool brief, int indent_level, + const std::string &prename, const std::string &name, + const std::string &postname) const; virtual void generate_hash(HashGenerator &hashgen) const; virtual bool pack_default_value(DCPackData &pack_data, bool &pack_error) const; @@ -73,19 +73,19 @@ public: public: typedef pvector Fields; - typedef pmap FieldsByName; + typedef pmap FieldsByName; class SwitchFields : public DCPackerInterface { public: - SwitchFields(const string &name); + SwitchFields(const std::string &name); ~SwitchFields(); virtual DCPackerInterface *get_nested_field(int n) const; bool add_field(DCField *field); bool do_check_match_switch_case(const SwitchFields *other) const; - void output(ostream &out, bool brief) const; - void write(ostream &out, bool brief, int indent_level) const; + void output(std::ostream &out, bool brief) const; + void write(std::ostream &out, bool brief, int indent_level) const; protected: virtual bool do_check_match(const DCPackerInterface *other) const; @@ -98,13 +98,13 @@ public: class SwitchCase { public: - SwitchCase(const string &value, SwitchFields *fields); + SwitchCase(const std::string &value, SwitchFields *fields); ~SwitchCase(); bool do_check_match_switch_case(const SwitchCase *other) const; public: - string _value; + std::string _value; SwitchFields *_fields; }; @@ -112,7 +112,7 @@ private: SwitchFields *start_new_case(); private: - string _name; + std::string _name; DCField *_key_parameter; typedef pvector Cases; @@ -137,7 +137,7 @@ private: bool _fields_added; // This map indexes into the _cases vector, above. - typedef pmap CasesByValue; + typedef pmap CasesByValue; CasesByValue _cases_by_value; }; diff --git a/direct/src/dcparser/dcSwitchParameter.cxx b/direct/src/dcparser/dcSwitchParameter.cxx index 0dcc741861..d4f2c10394 100644 --- a/direct/src/dcparser/dcSwitchParameter.cxx +++ b/direct/src/dcparser/dcSwitchParameter.cxx @@ -15,6 +15,8 @@ #include "dcSwitch.h" #include "hashGenerator.h" +using std::string; + /** * */ @@ -66,7 +68,7 @@ DCSwitchParameter(const DCSwitch *dswitch) : // Also consider the default case, if there is one. const DCSwitch::SwitchFields *fields = (DCSwitch::SwitchFields *)_dswitch->get_default_case(); - if (fields != (DCSwitch::SwitchFields *)NULL) { + if (fields != nullptr) { if (!fields->has_fixed_byte_size() || fields->get_fixed_byte_size() != _fixed_byte_size) { _has_fixed_byte_size = false; @@ -153,9 +155,9 @@ apply_switch(const char *value_data, size_t length) const { * identifier. */ void DCSwitchParameter:: -output_instance(ostream &out, bool brief, const string &prename, +output_instance(std::ostream &out, bool brief, const string &prename, const string &name, const string &postname) const { - if (get_typedef() != (DCTypedef *)NULL) { + if (get_typedef() != nullptr) { output_typedef_name(out, brief, prename, name, postname); } else { @@ -168,10 +170,10 @@ output_instance(ostream &out, bool brief, const string &prename, * identifier. */ void DCSwitchParameter:: -write_instance(ostream &out, bool brief, int indent_level, +write_instance(std::ostream &out, bool brief, int indent_level, const string &prename, const string &name, const string &postname) const { - if (get_typedef() != (DCTypedef *)NULL) { + if (get_typedef() != nullptr) { write_typedef_name(out, brief, indent_level, prename, name, postname); } else { diff --git a/direct/src/dcparser/dcSwitchParameter.h b/direct/src/dcparser/dcSwitchParameter.h index 0303af620f..51b8b673f6 100644 --- a/direct/src/dcparser/dcSwitchParameter.h +++ b/direct/src/dcparser/dcSwitchParameter.h @@ -41,11 +41,11 @@ public: const DCPackerInterface *apply_switch(const char *value_data, size_t length) const; - virtual void output_instance(ostream &out, bool brief, const string &prename, - const string &name, const string &postname) const; - virtual void write_instance(ostream &out, bool brief, int indent_level, - const string &prename, const string &name, - const string &postname) const; + virtual void output_instance(std::ostream &out, bool brief, const std::string &prename, + const std::string &name, const std::string &postname) const; + virtual void write_instance(std::ostream &out, bool brief, int indent_level, + const std::string &prename, const std::string &name, + const std::string &postname) const; virtual void generate_hash(HashGenerator &hashgen) const; virtual bool pack_default_value(DCPackData &pack_data, bool &pack_error) const; diff --git a/direct/src/dcparser/dcTypedef.cxx b/direct/src/dcparser/dcTypedef.cxx index cc45f74d49..a83f68e895 100644 --- a/direct/src/dcparser/dcTypedef.cxx +++ b/direct/src/dcparser/dcTypedef.cxx @@ -16,6 +16,8 @@ #include "dcSimpleParameter.h" #include "dcindent.h" +using std::string; + /** * The DCTypedef object becomes the owner of the supplied parameter pointer * and will delete it upon destruction. @@ -72,7 +74,7 @@ get_name() const { */ string DCTypedef:: get_description() const { - ostringstream strm; + std::ostringstream strm; _parameter->output(strm, true); return strm.str(); } @@ -122,7 +124,7 @@ set_number(int number) { * Write a string representation of this instance to . */ void DCTypedef:: -output(ostream &out, bool brief) const { +output(std::ostream &out, bool brief) const { out << "typedef "; _parameter->output(out, false); } @@ -131,7 +133,7 @@ output(ostream &out, bool brief) const { * */ void DCTypedef:: -write(ostream &out, bool brief, int indent_level) const { +write(std::ostream &out, bool brief, int indent_level) const { indent(out, indent_level) << "typedef "; diff --git a/direct/src/dcparser/dcTypedef.h b/direct/src/dcparser/dcTypedef.h index 62797fc8ff..654c8998a8 100644 --- a/direct/src/dcparser/dcTypedef.h +++ b/direct/src/dcparser/dcTypedef.h @@ -26,13 +26,13 @@ class DCParameter; class DCTypedef : public DCDeclaration { public: DCTypedef(DCParameter *parameter, bool implicit = false); - DCTypedef(const string &name); + DCTypedef(const std::string &name); virtual ~DCTypedef(); PUBLISHED: int get_number() const; - const string &get_name() const; - string get_description() const; + const std::string &get_name() const; + std::string get_description() const; bool is_bogus_typedef() const; bool is_implicit_typedef() const; @@ -41,8 +41,8 @@ public: DCParameter *make_new_parameter() const; void set_number(int number); - virtual void output(ostream &out, bool brief) const; - virtual void write(ostream &out, bool brief, int indent_level) const; + virtual void output(std::ostream &out, bool brief) const; + virtual void write(std::ostream &out, bool brief, int indent_level) const; private: DCParameter *_parameter; diff --git a/direct/src/dcparser/dcbase.h b/direct/src/dcparser/dcbase.h index 6d65f16524..4f2712f148 100644 --- a/direct/src/dcparser/dcbase.h +++ b/direct/src/dcparser/dcbase.h @@ -60,10 +60,7 @@ #include #endif -using namespace std; - #define INLINE inline -#define TYPENAME typename // These symbols are used within the Panda environment for exporting classes // and functions to the scripting language. They're largely meaningless if @@ -82,7 +79,7 @@ using namespace std; // Panda defines a special Filename class. We'll use an ordinary string // instead. -typedef string Filename; +typedef std::string Filename; // Panda defines WORDS_BIGENDIAN on a bigendian machine; otherwise, the // machine is assumed to be littleendian. Outside of Panda, you're @@ -92,15 +89,15 @@ typedef string Filename; #include #include #include -#define pvector vector -#define pmap map -#define pset set +#define pvector std::vector +#define pmap std::map +#define pset std::set #include -typedef ifstream pifstream; -typedef ofstream pofstream; -typedef fstream pfstream; +typedef std::ifstream pifstream; +typedef std::ofstream pofstream; +typedef std::fstream pfstream; #endif // WITHIN_PANDA diff --git a/direct/src/dcparser/dcindent.cxx b/direct/src/dcparser/dcindent.cxx index ae466667ac..b7b9f20793 100644 --- a/direct/src/dcparser/dcindent.cxx +++ b/direct/src/dcparser/dcindent.cxx @@ -18,8 +18,8 @@ /** * */ -ostream & -indent(ostream &out, int indent_level) { +std::ostream & +indent(std::ostream &out, int indent_level) { for (int i = 0; i < indent_level; i++) { out << ' '; } diff --git a/direct/src/dcparser/dcindent.h b/direct/src/dcparser/dcindent.h index 48cfddb7d7..a14f982199 100644 --- a/direct/src/dcparser/dcindent.h +++ b/direct/src/dcparser/dcindent.h @@ -29,8 +29,8 @@ * stream itself. Useful for indenting a series of lines of text by a given * amount. */ -ostream & -indent(ostream &out, int indent_level); +std::ostream & +indent(std::ostream &out, int indent_level); #endif // WITHIN_PANDA diff --git a/direct/src/dcparser/hashGenerator.cxx b/direct/src/dcparser/hashGenerator.cxx index b5a092f95c..900fd4bf42 100644 --- a/direct/src/dcparser/hashGenerator.cxx +++ b/direct/src/dcparser/hashGenerator.cxx @@ -48,9 +48,9 @@ add_int(int num) { * Adds a string to the hash, by breaking it down into a sequence of integers. */ void HashGenerator:: -add_string(const string &str) { +add_string(const std::string &str) { add_int(str.length()); - string::const_iterator si; + std::string::const_iterator si; for (si = str.begin(); si != str.end(); ++si) { add_int(*si); } diff --git a/direct/src/dcparser/hashGenerator.h b/direct/src/dcparser/hashGenerator.h index 6137196a39..94031cd2f6 100644 --- a/direct/src/dcparser/hashGenerator.h +++ b/direct/src/dcparser/hashGenerator.h @@ -25,7 +25,7 @@ public: HashGenerator(); void add_int(int num); - void add_string(const string &str); + void add_string(const std::string &str); unsigned long get_hash() const; diff --git a/direct/src/dcparser/primeNumberGenerator.h b/direct/src/dcparser/primeNumberGenerator.h index d66a6f536d..8b24ae6b5c 100644 --- a/direct/src/dcparser/primeNumberGenerator.h +++ b/direct/src/dcparser/primeNumberGenerator.h @@ -22,7 +22,7 @@ #include "vector_int.h" #else -typedef vector vector_int; +typedef std::vector vector_int; #endif /** diff --git a/direct/src/deadrec/smoothMover.cxx b/direct/src/deadrec/smoothMover.cxx index 727f10f9b3..d15ad745c6 100644 --- a/direct/src/deadrec/smoothMover.cxx +++ b/direct/src/deadrec/smoothMover.cxx @@ -95,7 +95,7 @@ mark_position() { LVector3 pos_delta = _sample._pos - _smooth_pos; LVecBase3 hpr_delta = _sample._hpr - _smooth_hpr; double age = timestamp - _smooth_timestamp; - age = min(age, _max_position_age); + age = std::min(age, _max_position_age); set_smooth_pos(_sample._pos, _sample._hpr, timestamp); if (age != 0.0) { @@ -272,13 +272,13 @@ compute_smooth_position(double timestamp) { // Find the newest of the points before the indicated time. Assume that // this will be no older than _last_point_before. - i = max(0, _last_point_before); + i = std::max(0, _last_point_before); while (i < num_points && _points[i]._timestamp < timestamp) { point_before = i; timestamp_before = _points[i]._timestamp; ++i; } - point_way_before = max(point_before - 1, -1); + point_way_before = std::max(point_before - 1, -1); // Now the next point is presumably the oldest point after the indicated // time. @@ -527,7 +527,7 @@ get_latest_position() { * */ void SmoothMover:: -output(ostream &out) const { +output(std::ostream &out) const { out << "SmoothMover, " << _points.size() << " sample points."; } @@ -535,7 +535,7 @@ output(ostream &out) const { * */ void SmoothMover:: -write(ostream &out) const { +write(std::ostream &out) const { out << "SmoothMover, " << _points.size() << " sample points:\n"; int num_points = _points.size(); for (int i = 0; i < num_points; i++) { diff --git a/direct/src/deadrec/smoothMover.h b/direct/src/deadrec/smoothMover.h index aee12bca8e..f456f00518 100644 --- a/direct/src/deadrec/smoothMover.h +++ b/direct/src/deadrec/smoothMover.h @@ -137,8 +137,8 @@ PUBLISHED: INLINE void set_default_to_standing_still(bool flag); INLINE bool get_default_to_standing_still(); - void output(ostream &out) const; - void write(ostream &out) const; + void output(std::ostream &out) const; + void write(std::ostream &out) const; private: void set_smooth_pos(const LPoint3 &pos, const LVecBase3 &hpr, diff --git a/direct/src/directd/directd.cxx b/direct/src/directd/directd.cxx index 1b4601fc41..817706acb5 100644 --- a/direct/src/directd/directd.cxx +++ b/direct/src/directd/directd.cxx @@ -34,6 +34,11 @@ #error Buildsystem error: BUILDING_DIRECT_DIRECTD not defined #endif +using std::cerr; +using std::cout; +using std::endl; +using std::string; + namespace { // ...This section is part of the old stuff from the original // implementation. The new stuff that uses job objects doesn't need this @@ -83,7 +88,7 @@ namespace { // If we can't open the process with PROCESS_TERMINATE rights, then we // give up immediately. hProc = OpenProcess(SYNCHRONIZE|PROCESS_TERMINATE, FALSE, dwPID); - if(hProc == NULL) { + if(hProc == nullptr) { return TA_FAILED; } @@ -115,7 +120,7 @@ namespace { ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); - if (CreateProcess(NULL, (char*)cmd.c_str(), + if (CreateProcess(nullptr, (char*)cmd.c_str(), 0, 0, 1, NORMAL_PRIORITY_CLASS, 0, 0, &si, &pi)) { pid=pi.dwProcessId; @@ -148,7 +153,7 @@ DirectD::~DirectD() { int DirectD::client_ready(const string& server_host, int port, const string& cmd) { - stringstream ss; + std::stringstream ss; ss<<"!"< client_ready() @@ -102,7 +102,7 @@ PUBLISHED: * Call this function from the server when import ShowbaseGlobal is nearly * finished. */ - int server_ready(const string& client_host, int port); + int server_ready(const std::string& client_host, int port); /** * Call connect_to from client for each server. returns the port number of @@ -110,28 +110,28 @@ PUBLISHED: * second argument). The return value can be used for the port arguemnt in * disconnect_from(). */ - int connect_to(const string& server_host, int port); + int connect_to(const std::string& server_host, int port); /** * This is the counterpart to connect_to(). Pass the same server_host as for * connect_to(), but pass the return value from connect_to() for the port, not * the port passed to connect_to(). */ - void disconnect_from(const string& server_host, int port); + void disconnect_from(const std::string& server_host, int port); /** * Send the same command string to all current connections. */ - void send_command(const string& cmd); + void send_command(const std::string& cmd); protected: - void start_app(const string& cmd); + void start_app(const std::string& cmd); void kill_app(int index); void kill_all(); - virtual void handle_command(const string& cmd); + virtual void handle_command(const std::string& cmd); void handle_datagram(NetDatagram& datagram); - void send_one_message(const string& host_name, - int port, const string& message); + void send_one_message(const std::string& host_name, + int port, const std::string& message); QueuedConnectionManager _cm; QueuedConnectionReader _reader; diff --git a/direct/src/directdServer/directdClient.cxx b/direct/src/directdServer/directdClient.cxx index 550c3f2862..9223143c5b 100644 --- a/direct/src/directdServer/directdClient.cxx +++ b/direct/src/directdServer/directdClient.cxx @@ -13,6 +13,12 @@ #include "directdClient.h" +using std::cerr; +using std::cin; +using std::cout; +using std::endl; +using std::string; + DirectDClient::DirectDClient() { } @@ -24,7 +30,7 @@ DirectDClient::cli_command(const string& cmd) { cerr<<"command "<> code; string host; @@ -49,7 +55,7 @@ DirectDClient::run_client(const string& host, int port) { connect_to(host, port); while (!cin.fail() && _connections.size()!=0) { - cout << "directd send: " << flush; + cout << "directd send: " << std::flush; string d; cin >> d; cli_command(d); diff --git a/direct/src/directdServer/directdClient.h b/direct/src/directdServer/directdClient.h index 9c50908950..8c5dd03fc2 100644 --- a/direct/src/directdServer/directdClient.h +++ b/direct/src/directdServer/directdClient.h @@ -21,8 +21,8 @@ public: DirectDClient(); ~DirectDClient(); - void run_client(const string& host, int port); + void run_client(const std::string& host, int port); protected: - void cli_command(const string& cmd); + void cli_command(const std::string& cmd); }; diff --git a/direct/src/directdServer/directdServer.cxx b/direct/src/directdServer/directdServer.cxx index 2eefe03e58..c25dde5733 100644 --- a/direct/src/directdServer/directdServer.cxx +++ b/direct/src/directdServer/directdServer.cxx @@ -13,6 +13,10 @@ #include "directdServer.h" +using std::cerr; +using std::endl; +using std::string; + DirectDServer::DirectDServer() { } @@ -61,8 +65,8 @@ void DirectDServer::read_command(string& cmd) { try { pifstream f; - f.open("directdCommand", ios::in | ios::binary); - stringstream ss; + f.open("directdCommand", std::ios::in | std::ios::binary); + std::stringstream ss; const int buf_size=512; char buf[buf_size]; f.getline(buf, buf_size); diff --git a/direct/src/directdServer/directdServer.h b/direct/src/directdServer/directdServer.h index 767f34807a..ec76fff41d 100644 --- a/direct/src/directdServer/directdServer.h +++ b/direct/src/directdServer/directdServer.h @@ -29,6 +29,6 @@ public: void run_server(int port); protected: - void read_command(string& cmd); - virtual void handle_command(const string& cmd); + void read_command(std::string& cmd); + virtual void handle_command(const std::string& cmd); }; diff --git a/direct/src/distributed/cConnectionRepository.I b/direct/src/distributed/cConnectionRepository.I index 16e57ba432..7395a48c2d 100644 --- a/direct/src/distributed/cConnectionRepository.I +++ b/direct/src/distributed/cConnectionRepository.I @@ -220,7 +220,7 @@ get_msg_type() const { * Returns event string that will be thrown if the datagram reader queue * overflows. */ -INLINE const string &CConnectionRepository:: +INLINE const std::string &CConnectionRepository:: get_overflow_event_name() { return _overflow_event_name; } diff --git a/direct/src/distributed/cConnectionRepository.cxx b/direct/src/distributed/cConnectionRepository.cxx index e247c2bd55..6e429bfbec 100644 --- a/direct/src/distributed/cConnectionRepository.cxx +++ b/direct/src/distributed/cConnectionRepository.cxx @@ -28,6 +28,9 @@ #include "py_panda.h" #endif +using std::endl; +using std::string; + const string CConnectionRepository::_overflow_event_name = "CRDatagramOverflow"; #ifndef CPPPARSER @@ -41,10 +44,10 @@ CConnectionRepository:: CConnectionRepository(bool has_owner_view, bool threaded_net) : _lock("CConnectionRepository::_lock"), #ifdef HAVE_PYTHON - _python_repository(NULL), + _python_repository(nullptr), #endif #ifdef HAVE_OPENSSL - _http_conn(NULL), + _http_conn(nullptr), #endif #ifdef HAVE_NET _cw(&_qcm, threaded_net ? 1 : 0), @@ -95,7 +98,7 @@ set_tcp_header_size(int tcp_header_size) { _tcp_header_size = tcp_header_size; #ifdef HAVE_OPENSSL - if (_http_conn != (SocketStream *)NULL) { + if (_http_conn != nullptr) { _http_conn->set_tcp_header_size(tcp_header_size); } #endif @@ -157,7 +160,7 @@ try_connect_net(const URLSpec &url) { _qcm.open_TCP_client_connection(url.get_server(), url.get_port(), game_server_timeout_ms); - if (_net_conn != (Connection *)NULL) { + if (_net_conn != nullptr) { _net_conn->set_no_delay(true); _qcr.add_connection(_net_conn); return true; @@ -209,7 +212,7 @@ start_delay(double min_delay, double max_delay) { _qcr.start_delay(min_delay, max_delay); #endif // HAVE_NET #ifdef HAVE_OPENSSL - if (_http_conn != (SocketStream *)NULL) { + if (_http_conn != nullptr) { _http_conn->start_delay(min_delay, max_delay); } #endif // HAVE_OPENSSL @@ -233,7 +236,7 @@ stop_delay() { _qcr.stop_delay(); #endif // HAVE_NET #ifdef HAVE_OPENSSL - if (_http_conn != (SocketStream *)NULL) { + if (_http_conn != nullptr) { _http_conn->stop_delay(); } #endif // HAVE_OPENSSL @@ -278,7 +281,7 @@ check_datagram() { #ifdef HAVE_PYTHON // For now, we need to stuff this field onto the Python structure, to // support legacy code that expects to find it there. - if (_python_repository != (PyObject *)NULL) { + if (_python_repository != nullptr) { #if defined(HAVE_THREADS) && !defined(SIMPLE_THREADS) PyGILState_STATE gstate; gstate = PyGILState_Ensure(); @@ -353,7 +356,7 @@ is_connected() { _qcm.close_connection(reset_connection); if (reset_connection == _net_conn) { // Whoops, lost our connection. - _net_conn = NULL; + _net_conn = nullptr; return false; } } @@ -370,7 +373,7 @@ is_connected() { // Connection lost. delete _http_conn; - _http_conn = NULL; + _http_conn = nullptr; } #endif // HAVE_OPENSSL @@ -406,7 +409,7 @@ send_datagram(const Datagram &dg) { bool result = _bdc.SendMessage(dg); if (!result && _bdc.IsConnected()) { #ifdef HAVE_PYTHON - ostringstream s; + std::ostringstream s; #if PY_VERSION_HEX >= 0x03030000 PyObject *exc_type = PyExc_ConnectionError; @@ -607,7 +610,7 @@ disconnect() { #ifdef HAVE_NET if (_net_conn) { _qcm.close_connection(_net_conn); - _net_conn = NULL; + _net_conn = nullptr; } #endif // HAVE_NET @@ -615,7 +618,7 @@ disconnect() { if (_http_conn) { _http_conn->close(); delete _http_conn; - _http_conn = NULL; + _http_conn = nullptr; } #endif // HAVE_OPENSSL @@ -684,11 +687,11 @@ handle_update_field() { PStatTimer timer(_update_pcollector); unsigned int do_id = _di.get_uint32(); - if (_python_repository != (PyObject *)NULL) + if (_python_repository != nullptr) { PyObject *doId2do = PyObject_GetAttrString(_python_repository, "doId2do"); - nassertr(doId2do != NULL, false); + nassertr(doId2do != nullptr, false); #ifdef USE_PYTHON_2_2_OR_EARLIER PyObject *doId = PyInt_FromLong(do_id); @@ -699,14 +702,14 @@ handle_update_field() { Py_DECREF(doId); Py_DECREF(doId2do); - if (distobj != NULL) { + if (distobj != nullptr) { PyObject *dclass_obj = PyObject_GetAttrString(distobj, "dclass"); - nassertr(dclass_obj != NULL, false); + nassertr(dclass_obj != nullptr, false); PyObject *dclass_this = PyObject_GetAttrString(dclass_obj, "this"); Py_DECREF(dclass_obj); - nassertr(dclass_this != NULL, false); + nassertr(dclass_this != nullptr, false); DCClass *dclass = (DCClass *)PyLong_AsVoidPtr(dclass_this); Py_DECREF(dclass_this); @@ -715,7 +718,7 @@ handle_update_field() { // 'neverDisable' attribute set to non-zero if (_in_quiet_zone) { PyObject *neverDisable = PyObject_GetAttrString(distobj, "neverDisable"); - nassertr(neverDisable != NULL, false); + nassertr(neverDisable != nullptr, false); unsigned int cNeverDisable = PyLong_AsLong(neverDisable); if (!cNeverDisable) { @@ -772,14 +775,14 @@ handle_update_field_owner() { PStatTimer timer(_update_pcollector); unsigned int do_id = _di.get_uint32(); - if (_python_repository != (PyObject *)NULL) { + if (_python_repository != nullptr) { PyObject *doId2do = PyObject_GetAttrString(_python_repository, "doId2do"); - nassertr(doId2do != NULL, false); + nassertr(doId2do != nullptr, false); PyObject *doId2ownerView = PyObject_GetAttrString(_python_repository, "doId2ownerView"); - nassertr(doId2ownerView != NULL, false); + nassertr(doId2ownerView != nullptr, false); #ifdef USE_PYTHON_2_2_OR_EARLIER PyObject *doId = PyInt_FromLong(do_id); @@ -791,13 +794,13 @@ handle_update_field_owner() { PyObject *distobjOV = PyDict_GetItem(doId2ownerView, doId); Py_DECREF(doId2ownerView); - if (distobjOV != NULL) { + if (distobjOV != nullptr) { PyObject *dclass_obj = PyObject_GetAttrString(distobjOV, "dclass"); - nassertr(dclass_obj != NULL, false); + nassertr(dclass_obj != nullptr, false); PyObject *dclass_this = PyObject_GetAttrString(dclass_obj, "this"); Py_DECREF(dclass_obj); - nassertr(dclass_this != NULL, false); + nassertr(dclass_this != nullptr, false); DCClass *dclass = (DCClass *)PyLong_AsVoidPtr(dclass_this); Py_DECREF(dclass_this); @@ -834,13 +837,13 @@ handle_update_field_owner() { Py_DECREF(doId); Py_DECREF(doId2do); - if (distobj != NULL) { + if (distobj != nullptr) { PyObject *dclass_obj = PyObject_GetAttrString(distobj, "dclass"); - nassertr(dclass_obj != NULL, false); + nassertr(dclass_obj != nullptr, false); PyObject *dclass_this = PyObject_GetAttrString(dclass_obj, "this"); Py_DECREF(dclass_obj); - nassertr(dclass_this != NULL, false); + nassertr(dclass_this != nullptr, false); DCClass *dclass = (DCClass *)PyLong_AsVoidPtr(dclass_this); Py_DECREF(dclass_this); @@ -849,8 +852,9 @@ handle_update_field_owner() { vector_uchar data = _di.get_remaining_bytes(); DCPacker packer; packer.set_unpack_data((const char *)data.data(), data.size(), false); - int field_id = packer.raw_unpack_uint16(); - DCField *field = dclass->get_field_by_index(field_id); + + //int field_id = packer.raw_unpack_uint16(); + //DCField *field = dclass->get_field_by_index(field_id); if (true) {//field->is_broadcast()) { // It's a good idea to ensure the reference count to distobj is raised // while we call the update method--otherwise, the update method might @@ -883,7 +887,7 @@ handle_update_field_owner() { * description on the indicated output stream. */ void CConnectionRepository:: -describe_message(ostream &out, const string &prefix, +describe_message(std::ostream &out, const string &prefix, const Datagram &dg) const { DCPacker packer; @@ -914,19 +918,19 @@ describe_message(ostream &out, const string &prefix, string msgName; #ifdef HAVE_PYTHON - if (_python_repository != (PyObject *)NULL) { + if (_python_repository != nullptr) { PyObject *msgId = PyLong_FromLong(msg_type); - nassertv(msgId != NULL); + nassertv(msgId != nullptr); #if PY_MAJOR_VERSION >= 3 PyObject *methodName = PyUnicode_FromString("_getMsgName"); #else PyObject *methodName = PyString_FromString("_getMsgName"); #endif - nassertv(methodName != NULL); + nassertv(methodName != nullptr); PyObject *result = PyObject_CallMethodObjArgs(_python_repository, methodName, - msgId, NULL); - nassertv(result != NULL); + msgId, nullptr); + nassertv(result != nullptr); #if PY_MAJOR_VERSION >= 3 msgName += string(PyUnicode_AsUTF8(result)); @@ -951,13 +955,13 @@ describe_message(ostream &out, const string &prefix, // It's an update message. Figure out what dclass the object is based on // its doId, so we can decode the rest of the message. do_id = packer.raw_unpack_uint32(); - DCClass *dclass = NULL; + DCClass *dclass = nullptr; #ifdef HAVE_PYTHON - if (_python_repository != (PyObject *)NULL) { + if (_python_repository != nullptr) { PyObject *doId2do = PyObject_GetAttrString(_python_repository, "doId2do"); - nassertv(doId2do != NULL); + nassertv(doId2do != nullptr); #ifdef USE_PYTHON_2_2_OR_EARLIER PyObject *doId = PyInt_FromLong(do_id); @@ -968,13 +972,13 @@ describe_message(ostream &out, const string &prefix, Py_DECREF(doId); Py_DECREF(doId2do); - if (distobj != NULL) { + if (distobj != nullptr) { PyObject *dclass_obj = PyObject_GetAttrString(distobj, "dclass"); - nassertv(dclass_obj != NULL); + nassertv(dclass_obj != nullptr); PyObject *dclass_this = PyObject_GetAttrString(dclass_obj, "this"); Py_DECREF(dclass_obj); - nassertv(dclass_this != NULL); + nassertv(dclass_this != nullptr); dclass = (DCClass *)PyLong_AsVoidPtr(dclass_this); Py_DECREF(dclass_this); @@ -984,7 +988,7 @@ describe_message(ostream &out, const string &prefix, int field_id = packer.raw_unpack_uint16(); - if (dclass == (DCClass *)NULL) { + if (dclass == nullptr) { out << full_prefix << "update for unknown object " << do_id << ", field " << field_id << "\n"; @@ -992,7 +996,7 @@ describe_message(ostream &out, const string &prefix, out << full_prefix << ":" << dclass->get_name() << "(" << do_id << ")."; DCField *field = dclass->get_field_by_index(field_id); - if (field == (DCField *)NULL) { + if (field == nullptr) { out << "unknown field " << field_id << "\n"; } else { diff --git a/direct/src/distributed/cConnectionRepository.h b/direct/src/distributed/cConnectionRepository.h index 420c995e37..c67d4aad23 100644 --- a/direct/src/distributed/cConnectionRepository.h +++ b/direct/src/distributed/cConnectionRepository.h @@ -122,7 +122,7 @@ PUBLISHED: // INLINE unsigned char get_sec_code() const; BLOCKING INLINE unsigned int get_msg_type() const; - INLINE static const string &get_overflow_event_name(); + INLINE static const std::string &get_overflow_event_name(); BLOCKING bool is_connected(); @@ -161,7 +161,7 @@ private: bool handle_update_field(); bool handle_update_field_owner(); - void describe_message(ostream &out, const string &prefix, + void describe_message(std::ostream &out, const std::string &prefix, const Datagram &dg) const; private: @@ -205,11 +205,11 @@ private: CHANNEL_TYPE _msg_sender; unsigned int _msg_type; - static const string _overflow_event_name; + static const std::string _overflow_event_name; bool _want_message_bundling; unsigned int _bundling_msgs; - typedef std::vector< string > BundledMsgVector; + typedef std::vector< std::string > BundledMsgVector; BundledMsgVector _bundle_msgs; static PStatCollector _update_pcollector; diff --git a/direct/src/distributed/cDistributedSmoothNodeBase.cxx b/direct/src/distributed/cDistributedSmoothNodeBase.cxx index 14a665d9b9..67e273644f 100644 --- a/direct/src/distributed/cDistributedSmoothNodeBase.cxx +++ b/direct/src/distributed/cDistributedSmoothNodeBase.cxx @@ -26,12 +26,12 @@ static const double network_time_precision = 100.0; // Matches ClockDelta.py */ CDistributedSmoothNodeBase:: CDistributedSmoothNodeBase() { - _repository = NULL; + _repository = nullptr; _is_ai = false; _ai_id = 0; #ifdef HAVE_PYTHON - _clock_delta = NULL; + _clock_delta = nullptr; #endif _currL[0] = 0; @@ -268,9 +268,9 @@ broadcast_pos_hpr_xy() { * indicated field name, up until the arguments. */ void CDistributedSmoothNodeBase:: -begin_send_update(DCPacker &packer, const string &field_name) { +begin_send_update(DCPacker &packer, const std::string &field_name) { DCField *field = _dclass->get_field_by_name(field_name); - nassertv(field != (DCField *)NULL); + nassertv(field != nullptr); if (_is_ai) { @@ -298,9 +298,9 @@ begin_send_update(DCPacker &packer, const string &field_name) { void CDistributedSmoothNodeBase:: finish_send_update(DCPacker &packer) { #ifdef HAVE_PYTHON - nassertv(_clock_delta != NULL); + nassertv(_clock_delta != nullptr); PyObject *clock_delta = PyObject_GetAttrString(_clock_delta, "delta"); - nassertv(clock_delta != NULL); + nassertv(clock_delta != nullptr); double delta = PyFloat_AsDouble(clock_delta); Py_DECREF(clock_delta); #else @@ -319,20 +319,20 @@ finish_send_update(DCPacker &packer) { bool pack_ok = packer.end_pack(); if (pack_ok) { Datagram dg(packer.get_data(), packer.get_length()); - nassertv(_repository != NULL); + nassertv(_repository != nullptr); _repository->send_datagram(dg); } else { #ifndef NDEBUG if (packer.had_range_error()) { - ostringstream error; + std::ostringstream error; error << "Node position out of range for DC file: " << _node_path << " pos = " << _store_xyz << " hpr = " << _store_hpr << " zoneId = " << _currL[0]; #ifdef HAVE_PYTHON - string message = error.str(); + std::string message = error.str(); distributed_cat.warning() << message << "\n"; PyErr_SetString(PyExc_ValueError, message.c_str()); @@ -364,5 +364,5 @@ set_curr_l(uint64_t l) { void CDistributedSmoothNodeBase:: print_curr_l() { - cout << "printCurrL: sent l: " << _currL[1] << " last set l: " << _currL[0] << "\n"; + std::cout << "printCurrL: sent l: " << _currL[1] << " last set l: " << _currL[0] << "\n"; } diff --git a/direct/src/distributed/cDistributedSmoothNodeBase.h b/direct/src/distributed/cDistributedSmoothNodeBase.h index d2c43e285c..6c57f6a2bf 100644 --- a/direct/src/distributed/cDistributedSmoothNodeBase.h +++ b/direct/src/distributed/cDistributedSmoothNodeBase.h @@ -69,7 +69,7 @@ private: INLINE void d_setSmPosHpr(PN_stdfloat x, PN_stdfloat y, PN_stdfloat z, PN_stdfloat h, PN_stdfloat p, PN_stdfloat r); INLINE void d_setSmPosHprL(PN_stdfloat x, PN_stdfloat y, PN_stdfloat z, PN_stdfloat h, PN_stdfloat p, PN_stdfloat r, uint64_t l); - void begin_send_update(DCPacker &packer, const string &field_name); + void begin_send_update(DCPacker &packer, const std::string &field_name); void finish_send_update(DCPacker &packer); enum Flags { diff --git a/direct/src/interval/cConstrainHprInterval.cxx b/direct/src/interval/cConstrainHprInterval.cxx index bfd6f6d86d..0cd3e26a35 100644 --- a/direct/src/interval/cConstrainHprInterval.cxx +++ b/direct/src/interval/cConstrainHprInterval.cxx @@ -26,7 +26,7 @@ TypeHandle CConstrainHprInterval::_type_handle; * node's local orientation will be copied unaltered. */ CConstrainHprInterval:: -CConstrainHprInterval(const string &name, double duration, +CConstrainHprInterval(const std::string &name, double duration, const NodePath &node, const NodePath &target, bool wrt, const LVecBase3 hprOffset) : CConstraintInterval(name, duration), @@ -69,7 +69,7 @@ priv_step(double t) { * */ void CConstrainHprInterval:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_name() << ":"; out << " dur " << get_duration(); } diff --git a/direct/src/interval/cConstrainHprInterval.h b/direct/src/interval/cConstrainHprInterval.h index 73c790100d..6338814b7d 100644 --- a/direct/src/interval/cConstrainHprInterval.h +++ b/direct/src/interval/cConstrainHprInterval.h @@ -26,7 +26,7 @@ */ class EXPCL_DIRECT_INTERVAL CConstrainHprInterval : public CConstraintInterval { PUBLISHED: - explicit CConstrainHprInterval(const string &name, double duration, + explicit CConstrainHprInterval(const std::string &name, double duration, const NodePath &node, const NodePath &target, bool wrt, const LVecBase3 hprOffset=LVector3::zero()); @@ -34,7 +34,7 @@ PUBLISHED: INLINE const NodePath &get_target() const; virtual void priv_step(double t); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: NodePath _node; diff --git a/direct/src/interval/cConstrainPosHprInterval.cxx b/direct/src/interval/cConstrainPosHprInterval.cxx index 7b0944c3e4..4e30d9f56e 100644 --- a/direct/src/interval/cConstrainPosHprInterval.cxx +++ b/direct/src/interval/cConstrainPosHprInterval.cxx @@ -27,7 +27,7 @@ TypeHandle CConstrainPosHprInterval::_type_handle; * unaltered. */ CConstrainPosHprInterval:: -CConstrainPosHprInterval(const string &name, double duration, +CConstrainPosHprInterval(const std::string &name, double duration, const NodePath &node, const NodePath &target, bool wrt, const LVecBase3 posOffset, const LVecBase3 hprOffset) : @@ -72,7 +72,7 @@ priv_step(double t) { * */ void CConstrainPosHprInterval:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_name() << ":"; out << " dur " << get_duration(); } diff --git a/direct/src/interval/cConstrainPosHprInterval.h b/direct/src/interval/cConstrainPosHprInterval.h index 44fedae0f6..a96aa097de 100644 --- a/direct/src/interval/cConstrainPosHprInterval.h +++ b/direct/src/interval/cConstrainPosHprInterval.h @@ -26,7 +26,7 @@ */ class EXPCL_DIRECT_INTERVAL CConstrainPosHprInterval : public CConstraintInterval { PUBLISHED: - explicit CConstrainPosHprInterval(const string &name, double duration, + explicit CConstrainPosHprInterval(const std::string &name, double duration, const NodePath &node, const NodePath &target, bool wrt, const LVecBase3 posOffset=LVector3::zero(), const LVecBase3 hprOffset=LVector3::zero()); @@ -35,7 +35,7 @@ PUBLISHED: INLINE const NodePath &get_target() const; virtual void priv_step(double t); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: NodePath _node; diff --git a/direct/src/interval/cConstrainPosInterval.cxx b/direct/src/interval/cConstrainPosInterval.cxx index fe8f235654..1cc967617c 100644 --- a/direct/src/interval/cConstrainPosInterval.cxx +++ b/direct/src/interval/cConstrainPosInterval.cxx @@ -26,7 +26,7 @@ TypeHandle CConstrainPosInterval::_type_handle; * node's local position will be copied unaltered. */ CConstrainPosInterval:: -CConstrainPosInterval(const string &name, double duration, +CConstrainPosInterval(const std::string &name, double duration, const NodePath &node, const NodePath &target, bool wrt, const LVecBase3 posOffset) : CConstraintInterval(name, duration), @@ -73,7 +73,7 @@ priv_step(double t) { * */ void CConstrainPosInterval:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_name() << ":"; out << " dur " << get_duration(); } diff --git a/direct/src/interval/cConstrainPosInterval.h b/direct/src/interval/cConstrainPosInterval.h index 1e66d3aca0..edb379559f 100644 --- a/direct/src/interval/cConstrainPosInterval.h +++ b/direct/src/interval/cConstrainPosInterval.h @@ -25,7 +25,7 @@ */ class EXPCL_DIRECT_INTERVAL CConstrainPosInterval : public CConstraintInterval { PUBLISHED: - explicit CConstrainPosInterval(const string &name, double duration, + explicit CConstrainPosInterval(const std::string &name, double duration, const NodePath &node, const NodePath &target, bool wrt, const LVecBase3 posOffset=LVector3::zero()); @@ -33,7 +33,7 @@ PUBLISHED: INLINE const NodePath &get_target() const; virtual void priv_step(double t); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: NodePath _node; diff --git a/direct/src/interval/cConstrainTransformInterval.cxx b/direct/src/interval/cConstrainTransformInterval.cxx index f816f3bbc1..a21c109bde 100644 --- a/direct/src/interval/cConstrainTransformInterval.cxx +++ b/direct/src/interval/cConstrainTransformInterval.cxx @@ -27,7 +27,7 @@ TypeHandle CConstrainTransformInterval::_type_handle; * local transform will be copied unaltered. */ CConstrainTransformInterval:: -CConstrainTransformInterval(const string &name, double duration, +CConstrainTransformInterval(const std::string &name, double duration, const NodePath &node, const NodePath &target, bool wrt) : CConstraintInterval(name, duration), @@ -72,7 +72,7 @@ priv_step(double t) { * */ void CConstrainTransformInterval:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_name() << ":"; out << " dur " << get_duration(); } diff --git a/direct/src/interval/cConstrainTransformInterval.h b/direct/src/interval/cConstrainTransformInterval.h index a4bb537ec1..41da174670 100644 --- a/direct/src/interval/cConstrainTransformInterval.h +++ b/direct/src/interval/cConstrainTransformInterval.h @@ -24,7 +24,7 @@ */ class EXPCL_DIRECT_INTERVAL CConstrainTransformInterval : public CConstraintInterval { PUBLISHED: - explicit CConstrainTransformInterval(const string &name, double duration, + explicit CConstrainTransformInterval(const std::string &name, double duration, const NodePath &node, const NodePath &target, bool wrt); @@ -32,7 +32,7 @@ PUBLISHED: INLINE const NodePath &get_target() const; virtual void priv_step(double t); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: NodePath _node; diff --git a/direct/src/interval/cConstraintInterval.cxx b/direct/src/interval/cConstraintInterval.cxx index 708caed9fa..71ac457cb4 100644 --- a/direct/src/interval/cConstraintInterval.cxx +++ b/direct/src/interval/cConstraintInterval.cxx @@ -19,7 +19,7 @@ TypeHandle CConstraintInterval::_type_handle; * */ CConstraintInterval:: -CConstraintInterval(const string &name, double duration) : +CConstraintInterval(const std::string &name, double duration) : CInterval(name, duration, true) { } diff --git a/direct/src/interval/cConstraintInterval.h b/direct/src/interval/cConstraintInterval.h index 96a47946ec..97a174b51f 100644 --- a/direct/src/interval/cConstraintInterval.h +++ b/direct/src/interval/cConstraintInterval.h @@ -26,7 +26,7 @@ PUBLISHED: bool bogus_variable; public: - CConstraintInterval(const string &name, double duration); + CConstraintInterval(const std::string &name, double duration); public: static TypeHandle get_class_type() { diff --git a/direct/src/interval/cInterval.I b/direct/src/interval/cInterval.I index 7650bddbee..f42fe8e62a 100644 --- a/direct/src/interval/cInterval.I +++ b/direct/src/interval/cInterval.I @@ -14,7 +14,7 @@ /** * Returns the interval's name. */ -INLINE const string &CInterval:: +INLINE const std::string &CInterval:: get_name() const { return _name; } @@ -64,7 +64,7 @@ is_stopped() const { * own. */ INLINE void CInterval:: -set_done_event(const string &event) { +set_done_event(const std::string &event) { _done_event = event; } @@ -73,7 +73,7 @@ set_done_event(const string &event) { * state, whether it is explicitly finished or whether it gets there on its * own. */ -INLINE const string &CInterval:: +INLINE const std::string &CInterval:: get_done_event() const { return _done_event; } @@ -219,8 +219,8 @@ check_started(TypeHandle type, const char *method_name) const { } } -INLINE ostream & -operator << (ostream &out, const CInterval &ival) { +INLINE std::ostream & +operator << (std::ostream &out, const CInterval &ival) { ival.output(out); return out; } diff --git a/direct/src/interval/cInterval.cxx b/direct/src/interval/cInterval.cxx index 84325720ab..0e7dba1554 100644 --- a/direct/src/interval/cInterval.cxx +++ b/direct/src/interval/cInterval.cxx @@ -19,6 +19,9 @@ #include "eventQueue.h" #include "pStatTimer.h" +using std::ostream; +using std::string; + PStatCollector CInterval::_root_pcollector("App:Show code:ivalLoop"); TypeHandle CInterval::_type_handle; @@ -41,7 +44,7 @@ CInterval(const string &name, double duration, bool open_ended) : _curr_t(0.0), _name(name), _pname(get_pstats_name(name)), - _duration(max(duration, 0.0)), + _duration(std::max(duration, 0.0)), _open_ended(open_ended), _dirty(false), _ival_pcollector(_root_pcollector, _pname) diff --git a/direct/src/interval/cInterval.h b/direct/src/interval/cInterval.h index 07672f352f..979dba4547 100644 --- a/direct/src/interval/cInterval.h +++ b/direct/src/interval/cInterval.h @@ -34,11 +34,11 @@ class CIntervalManager; */ class EXPCL_DIRECT_INTERVAL CInterval : public TypedReferenceCount { public: - CInterval(const string &name, double duration, bool open_ended); + CInterval(const std::string &name, double duration, bool open_ended); virtual ~CInterval(); PUBLISHED: - INLINE const string &get_name() const; + INLINE const std::string &get_name() const; INLINE double get_duration() const; INLINE bool get_open_ended() const; @@ -63,8 +63,8 @@ PUBLISHED: INLINE State get_state() const; INLINE bool is_stopped() const; - INLINE void set_done_event(const string &event); - INLINE const string &get_done_event() const; + INLINE void set_done_event(const std::string &event); + INLINE const std::string &get_done_event() const; void set_t(double t); INLINE double get_t() const; @@ -110,8 +110,8 @@ PUBLISHED: virtual void priv_reverse_finalize(); virtual void priv_interrupt(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; void setup_play(double start_time, double end_time, double play_rate, bool do_loop); @@ -147,9 +147,9 @@ protected: State _state; double _curr_t; - string _name; - string _pname; - string _done_event; + std::string _name; + std::string _pname; + std::string _done_event; double _duration; bool _auto_pause; @@ -201,8 +201,8 @@ private: friend class CMetaInterval; }; -INLINE ostream &operator << (ostream &out, const CInterval &ival); -EXPCL_DIRECT_INTERVAL ostream &operator << (ostream &out, CInterval::State state); +INLINE std::ostream &operator << (std::ostream &out, const CInterval &ival); +EXPCL_DIRECT_INTERVAL std::ostream &operator << (std::ostream &out, CInterval::State state); #include "cInterval.I" diff --git a/direct/src/interval/cIntervalManager.I b/direct/src/interval/cIntervalManager.I index 44ca1062cc..c2622fb5e8 100644 --- a/direct/src/interval/cIntervalManager.I +++ b/direct/src/interval/cIntervalManager.I @@ -34,8 +34,8 @@ get_event_queue() const { return _event_queue; } -INLINE ostream & -operator << (ostream &out, const CIntervalManager &ival_mgr) { +INLINE std::ostream & +operator << (std::ostream &out, const CIntervalManager &ival_mgr) { ival_mgr.output(out); return out; } diff --git a/direct/src/interval/cIntervalManager.cxx b/direct/src/interval/cIntervalManager.cxx index bd6189b349..137f30c0ff 100644 --- a/direct/src/interval/cIntervalManager.cxx +++ b/direct/src/interval/cIntervalManager.cxx @@ -108,7 +108,7 @@ add_c_interval(CInterval *interval, bool external) { * interval, or -1 if there is not. */ int CIntervalManager:: -find_c_interval(const string &name) const { +find_c_interval(const std::string &name) const { MutexHolder holder(_lock); NameIndex::const_iterator ni = _name_index.find(name); @@ -125,7 +125,7 @@ CInterval *CIntervalManager:: get_c_interval(int index) const { MutexHolder holder(_lock); - nassertr(index >= 0 && index < (int)_intervals.size(), NULL); + nassertr(index >= 0 && index < (int)_intervals.size(), nullptr); return _intervals[index]._interval; } @@ -140,14 +140,14 @@ remove_c_interval(int index) { nassertv(index >= 0 && index < (int)_intervals.size()); IntervalDef &def = _intervals[index]; - nassertv(def._interval != (CInterval *)NULL); + nassertv(def._interval != nullptr); NameIndex::iterator ni = _name_index.find(def._interval->get_name()); nassertv(ni != _name_index.end()); nassertv((*ni).second == index); _name_index.erase(ni); - def._interval = (CInterval *)NULL; + def._interval = nullptr; def._next_slot = _first_slot; _first_slot = index; } @@ -171,7 +171,7 @@ interrupt() { while (ni != _name_index.end()) { int index = (*ni).second; const IntervalDef &def = _intervals[index]; - nassertr(def._interval != (CInterval *)NULL, num_paused); + nassertr(def._interval != nullptr, num_paused); if (def._interval->get_auto_pause() || def._interval->get_auto_finish()) { // This interval may be interrupted. if (def._interval->get_auto_pause()) { @@ -262,7 +262,7 @@ step() { while (ni != _name_index.end()) { int index = (*ni).second; const IntervalDef &def = _intervals[index]; - nassertv(def._interval != (CInterval *)NULL); + nassertv(def._interval != nullptr); if (!def._interval->step_play()) { // This interval is finished and wants to be removed from the active // list. @@ -299,7 +299,7 @@ get_next_event() { while (_next_event_index < (int)_intervals.size()) { IntervalDef &def = _intervals[_next_event_index]; - if (def._interval != (CInterval *)NULL) { + if (def._interval != nullptr) { if ((def._flags & F_external) != 0 && def._interval->check_t_callback()) { return _next_event_index; @@ -338,7 +338,7 @@ get_next_removal() { nassertr(index >= 0 && index < (int)_intervals.size(), -1); IntervalDef &def = _intervals[index]; - def._interval = (CInterval *)NULL; + def._interval = nullptr; def._next_slot = _first_slot; _first_slot = index; return index; @@ -351,7 +351,7 @@ get_next_removal() { * */ void CIntervalManager:: -output(ostream &out) const { +output(std::ostream &out) const { MutexHolder holder(_lock); out << "CIntervalManager, " << (int)_name_index.size() << " intervals."; @@ -361,7 +361,7 @@ output(ostream &out) const { * */ void CIntervalManager:: -write(ostream &out) const { +write(std::ostream &out) const { MutexHolder holder(_lock); // We need to write this line so that it's clear what's going on when there @@ -373,7 +373,7 @@ write(ostream &out) const { int index = (*ni).second; nassertv(index >= 0 && index < (int)_intervals.size()); const IntervalDef &def = _intervals[index]; - nassertv(def._interval != (CInterval *)NULL); + nassertv(def._interval != nullptr); out << *def._interval << "\n"; } @@ -384,7 +384,7 @@ write(ostream &out) const { int index = (*ri); nassertv(index >= 0 && index < (int)_intervals.size()); const IntervalDef &def = _intervals[index]; - nassertv(def._interval != (CInterval *)NULL); + nassertv(def._interval != nullptr); out << "(R)" << *def._interval << "\n"; } } @@ -395,7 +395,7 @@ write(ostream &out) const { */ CIntervalManager *CIntervalManager:: get_global_ptr() { - if (_global_ptr == (CIntervalManager *)NULL) { + if (_global_ptr == nullptr) { _global_ptr = new CIntervalManager; } return _global_ptr; @@ -433,7 +433,7 @@ remove_index(int index) { if ((def._flags & F_external) != 0) { _removed.push_back(index); } else { - def._interval = (CInterval *)NULL; + def._interval = nullptr; def._next_slot = _first_slot; _first_slot = index; } diff --git a/direct/src/interval/cIntervalManager.h b/direct/src/interval/cIntervalManager.h index d4279c25fb..33f3d29ff1 100644 --- a/direct/src/interval/cIntervalManager.h +++ b/direct/src/interval/cIntervalManager.h @@ -45,7 +45,7 @@ PUBLISHED: INLINE EventQueue *get_event_queue() const; int add_c_interval(CInterval *interval, bool external); - int find_c_interval(const string &name) const; + int find_c_interval(const std::string &name) const; CInterval *get_c_interval(int index) const; void remove_c_interval(int index); @@ -58,8 +58,8 @@ PUBLISHED: int get_next_event(); int get_next_removal(); - void output(ostream &out) const; - void write(ostream &out) const; + void output(std::ostream &out) const; + void write(std::ostream &out) const; static CIntervalManager *get_global_ptr(); @@ -79,7 +79,7 @@ private: }; typedef pvector Intervals; Intervals _intervals; - typedef pmap NameIndex; + typedef pmap NameIndex; NameIndex _name_index; typedef vector_int Removed; Removed _removed; @@ -93,7 +93,7 @@ private: static CIntervalManager *_global_ptr; }; -INLINE ostream &operator << (ostream &out, const CInterval &ival_mgr); +INLINE std::ostream &operator << (std::ostream &out, const CInterval &ival_mgr); #include "cIntervalManager.I" diff --git a/direct/src/interval/cLerpAnimEffectInterval.I b/direct/src/interval/cLerpAnimEffectInterval.I index cc9c42adf8..08c48949f2 100644 --- a/direct/src/interval/cLerpAnimEffectInterval.I +++ b/direct/src/interval/cLerpAnimEffectInterval.I @@ -15,7 +15,7 @@ * */ INLINE CLerpAnimEffectInterval:: -CLerpAnimEffectInterval(const string &name, double duration, +CLerpAnimEffectInterval(const std::string &name, double duration, CLerpInterval::BlendType blend_type) : CLerpInterval(name, duration, blend_type) { @@ -30,7 +30,7 @@ CLerpAnimEffectInterval(const string &name, double duration, * for output. */ INLINE void CLerpAnimEffectInterval:: -add_control(AnimControl *control, const string &name, +add_control(AnimControl *control, const std::string &name, float begin_effect, float end_effect) { _controls.push_back(ControlDef(control, name, begin_effect, end_effect)); } @@ -39,7 +39,7 @@ add_control(AnimControl *control, const string &name, * */ INLINE CLerpAnimEffectInterval::ControlDef:: -ControlDef(AnimControl *control, const string &name, +ControlDef(AnimControl *control, const std::string &name, float begin_effect, float end_effect) : _control(control), _name(name), diff --git a/direct/src/interval/cLerpAnimEffectInterval.cxx b/direct/src/interval/cLerpAnimEffectInterval.cxx index d91bf8612e..4f7986a7c4 100644 --- a/direct/src/interval/cLerpAnimEffectInterval.cxx +++ b/direct/src/interval/cLerpAnimEffectInterval.cxx @@ -43,7 +43,7 @@ priv_step(double t) { * */ void CLerpAnimEffectInterval:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_name() << ": "; if (_controls.empty()) { diff --git a/direct/src/interval/cLerpAnimEffectInterval.h b/direct/src/interval/cLerpAnimEffectInterval.h index af657cb7cc..6200ffea9c 100644 --- a/direct/src/interval/cLerpAnimEffectInterval.h +++ b/direct/src/interval/cLerpAnimEffectInterval.h @@ -31,23 +31,23 @@ */ class EXPCL_DIRECT_INTERVAL CLerpAnimEffectInterval : public CLerpInterval { PUBLISHED: - INLINE explicit CLerpAnimEffectInterval(const string &name, double duration, + INLINE explicit CLerpAnimEffectInterval(const std::string &name, double duration, BlendType blend_type); - INLINE void add_control(AnimControl *control, const string &name, + INLINE void add_control(AnimControl *control, const std::string &name, float begin_effect, float end_effect); virtual void priv_step(double t); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: class ControlDef { public: - INLINE ControlDef(AnimControl *control, const string &name, + INLINE ControlDef(AnimControl *control, const std::string &name, float begin_effect, float end_effect); PT(AnimControl) _control; - string _name; + std::string _name; float _begin_effect; float _end_effect; }; diff --git a/direct/src/interval/cLerpInterval.I b/direct/src/interval/cLerpInterval.I index 04b37b438a..c0c101cfc4 100644 --- a/direct/src/interval/cLerpInterval.I +++ b/direct/src/interval/cLerpInterval.I @@ -15,7 +15,7 @@ * */ INLINE CLerpInterval:: -CLerpInterval(const string &name, double duration, +CLerpInterval(const std::string &name, double duration, CLerpInterval::BlendType blend_type) : CInterval(name, duration, true), _blend_type(blend_type) diff --git a/direct/src/interval/cLerpInterval.cxx b/direct/src/interval/cLerpInterval.cxx index b1eec3a135..43a291f94e 100644 --- a/direct/src/interval/cLerpInterval.cxx +++ b/direct/src/interval/cLerpInterval.cxx @@ -21,7 +21,7 @@ TypeHandle CLerpInterval::_type_handle; * string, or BT_invalid if the string doesn't match anything. */ CLerpInterval::BlendType CLerpInterval:: -string_blend_type(const string &blend_type) { +string_blend_type(const std::string &blend_type) { if (blend_type == "easeIn") { return BT_ease_in; } else if (blend_type == "easeOut") { @@ -49,7 +49,7 @@ compute_delta(double t) const { return 1.0; } t /= duration; - t = min(max(t, 0.0), 1.0); + t = std::min(std::max(t, 0.0), 1.0); switch (_blend_type) { case BT_ease_in: diff --git a/direct/src/interval/cLerpInterval.h b/direct/src/interval/cLerpInterval.h index 7011fd70e9..6587066f04 100644 --- a/direct/src/interval/cLerpInterval.h +++ b/direct/src/interval/cLerpInterval.h @@ -32,13 +32,13 @@ PUBLISHED: }; public: - INLINE CLerpInterval(const string &name, double duration, + INLINE CLerpInterval(const std::string &name, double duration, BlendType blend_type); PUBLISHED: INLINE BlendType get_blend_type() const; - static BlendType string_blend_type(const string &blend_type); + static BlendType string_blend_type(const std::string &blend_type); protected: double compute_delta(double t) const; diff --git a/direct/src/interval/cLerpNodePathInterval.cxx b/direct/src/interval/cLerpNodePathInterval.cxx index 8c9423106f..2fbc8a7e75 100644 --- a/direct/src/interval/cLerpNodePathInterval.cxx +++ b/direct/src/interval/cLerpNodePathInterval.cxx @@ -47,7 +47,7 @@ TypeHandle CLerpNodePathInterval::_type_handle; * otherwise, it is reset. */ CLerpNodePathInterval:: -CLerpNodePathInterval(const string &name, double duration, +CLerpNodePathInterval(const std::string &name, double duration, CLerpInterval::BlendType blend_type, bool bake_in_start, bool fluid, const NodePath &node, const NodePath &other) : @@ -57,7 +57,7 @@ CLerpNodePathInterval(const string &name, double duration, _flags(0), _texture_stage(TextureStage::get_default()), _override(0), - _slerp(NULL) + _slerp(nullptr) { if (bake_in_start) { _flags |= F_bake_in_start; @@ -191,7 +191,7 @@ priv_step(double t) { _flags &= ~F_slerp_setup; } } - nassertv(_slerp != NULL); + nassertv(_slerp != nullptr); (this->*_slerp)(quat, d); } if ((_flags & F_end_scale) != 0) { @@ -404,7 +404,7 @@ priv_step(double t) { color.set(1.0f, 1.0f, 1.0f, 1.0f); const RenderAttrib *attrib = state->get_attrib(ColorAttrib::get_class_type()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const ColorAttrib *ca = DCAST(ColorAttrib, attrib); if (ca->get_color_type() == ColorAttrib::T_flat) { color = ca->get_color(); @@ -428,7 +428,7 @@ priv_step(double t) { color_scale.set(1.0f, 1.0f, 1.0f, 1.0f); const RenderAttrib *attrib = state->get_attrib(ColorScaleAttrib::get_class_type()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const ColorScaleAttrib *csa = DCAST(ColorScaleAttrib, attrib); color_scale = csa->get_scale(); } @@ -446,7 +446,7 @@ priv_step(double t) { const RenderAttrib *attrib = state->get_attrib(TexMatrixAttrib::get_class_type()); CPT(TexMatrixAttrib) tma; - if (attrib != (const TexMatrixAttrib *)NULL) { + if (attrib != nullptr) { tma = DCAST(TexMatrixAttrib, attrib); transform = tma->get_transform(_texture_stage); } else { @@ -544,7 +544,7 @@ priv_reverse_instant() { * */ void CLerpNodePathInterval:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_name() << ":"; if ((_flags & F_end_pos) != 0) { diff --git a/direct/src/interval/cLerpNodePathInterval.h b/direct/src/interval/cLerpNodePathInterval.h index a134faebf0..d079f8eaa0 100644 --- a/direct/src/interval/cLerpNodePathInterval.h +++ b/direct/src/interval/cLerpNodePathInterval.h @@ -25,7 +25,7 @@ */ class EXPCL_DIRECT_INTERVAL CLerpNodePathInterval : public CLerpInterval { PUBLISHED: - explicit CLerpNodePathInterval(const string &name, double duration, + explicit CLerpNodePathInterval(const std::string &name, double duration, BlendType blend_type, bool bake_in_start, bool fluid, const NodePath &node, const NodePath &other); @@ -68,7 +68,7 @@ PUBLISHED: virtual void priv_reverse_initialize(double t); virtual void priv_reverse_instant(); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: void setup_slerp(); diff --git a/direct/src/interval/cMetaInterval.I b/direct/src/interval/cMetaInterval.I index ae30cd9792..0140e6e019 100644 --- a/direct/src/interval/cMetaInterval.I +++ b/direct/src/interval/cMetaInterval.I @@ -58,8 +58,8 @@ get_def_type(int n) const { */ INLINE CInterval *CMetaInterval:: get_c_interval(int n) const { - nassertr(n >= 0 && n < (int)_defs.size(), NULL); - nassertr(_defs[n]._type == DT_c_interval, NULL); + nassertr(n >= 0 && n < (int)_defs.size(), nullptr); + nassertr(_defs[n]._type == DT_c_interval, nullptr); return _defs[n]._c_interval; } diff --git a/direct/src/interval/cMetaInterval.cxx b/direct/src/interval/cMetaInterval.cxx index dd5f1386f2..d43ea9cebf 100644 --- a/direct/src/interval/cMetaInterval.cxx +++ b/direct/src/interval/cMetaInterval.cxx @@ -21,6 +21,8 @@ #include // for log10() #include // for sprintf() +using std::string; + TypeHandle CMetaInterval::_type_handle; /** @@ -66,7 +68,7 @@ clear_intervals() { Defs::iterator di; for (di = _defs.begin(); di != _defs.end(); ++di) { IntervalDef &def = (*di); - if (def._c_interval != (CInterval *)NULL) { + if (def._c_interval != nullptr) { CInterval::Parents::iterator pi = find(def._c_interval->_parents.begin(), def._c_interval->_parents.end(), @@ -122,7 +124,7 @@ int CMetaInterval:: add_c_interval(CInterval *c_interval, double rel_time, RelativeStart rel_to) { nassertr(_event_queue.empty() && !_processing_events, -1); - nassertr(c_interval != (CInterval *)NULL, -1); + nassertr(c_interval != nullptr, -1); c_interval->_parents.push_back(this); c_interval->_ival_pcollector = PStatCollector(_ival_pcollector, c_interval->_pname); @@ -669,7 +671,7 @@ pop_event() { * */ void CMetaInterval:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { recompute(); // How many digits of precision should we output for time? @@ -698,7 +700,7 @@ write(ostream &out, int indent_level) const { * Outputs a list of all events in the order in which they occur. */ void CMetaInterval:: -timeline(ostream &out) const { +timeline(std::ostream &out) const { recompute(); // How many digits of precision should we output for time? @@ -756,7 +758,7 @@ do_recompute() { // We do a stable_sort() to guarantee ordering of events that have the same // start time. These must be invoked in the order in which they appear. - stable_sort(_events.begin(), _events.end(), IndirectLess()); + std::stable_sort(_events.begin(), _events.end(), IndirectLess()); _duration = int_to_double_time(_end_time); } @@ -1124,7 +1126,7 @@ recompute_level(int n, int level_begin, int &level_end) { previous_begin = begin_time; previous_end = end_time; - level_end = max(level_end, end_time); + level_end = std::max(level_end, end_time); n++; } @@ -1169,7 +1171,7 @@ get_begin_time(const CMetaInterval::IntervalDef &def, int level_begin, * Formats an event for output, for write() or timeline(). */ void CMetaInterval:: -write_event_desc(ostream &out, const CMetaInterval::IntervalDef &def, +write_event_desc(std::ostream &out, const CMetaInterval::IntervalDef &def, int &extra_indent_level) const { switch (def._type) { case DT_c_interval: diff --git a/direct/src/interval/cMetaInterval.h b/direct/src/interval/cMetaInterval.h index f1956f4167..40fb03d102 100644 --- a/direct/src/interval/cMetaInterval.h +++ b/direct/src/interval/cMetaInterval.h @@ -31,7 +31,7 @@ */ class EXPCL_DIRECT_INTERVAL CMetaInterval : public CInterval { PUBLISHED: - explicit CMetaInterval(const string &name); + explicit CMetaInterval(const std::string &name); virtual ~CMetaInterval(); enum RelativeStart { @@ -44,20 +44,20 @@ PUBLISHED: INLINE double get_precision() const; void clear_intervals(); - int push_level(const string &name, + int push_level(const std::string &name, double rel_time, RelativeStart rel_to); int add_c_interval(CInterval *c_interval, double rel_time = 0.0f, RelativeStart rel_to = RS_previous_end); - int add_ext_index(int ext_index, const string &name, + int add_ext_index(int ext_index, const std::string &name, double duration, bool open_ended, double rel_time, RelativeStart rel_to); int pop_level(double duration = -1.0); - bool set_interval_start_time(const string &name, double rel_time, + bool set_interval_start_time(const std::string &name, double rel_time, RelativeStart rel_to = RS_level_begin); - double get_interval_start_time(const string &name) const; - double get_interval_end_time(const string &name) const; + double get_interval_start_time(const std::string &name) const; + double get_interval_end_time(const std::string &name) const; enum DefType { DT_c_interval, @@ -86,8 +86,8 @@ PUBLISHED: INLINE EventType get_event_type() const; void pop_event(); - virtual void write(ostream &out, int indent_level) const; - void timeline(ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; + void timeline(std::ostream &out) const; protected: virtual void do_recompute(); @@ -98,7 +98,7 @@ private: DefType _type; PT(CInterval) _c_interval; int _ext_index; - string _ext_name; + std::string _ext_name; double _ext_duration; bool _ext_open_ended; double _rel_time; @@ -159,7 +159,7 @@ private: int get_begin_time(const IntervalDef &def, int level_begin, int previous_begin, int previous_end); - void write_event_desc(ostream &out, const IntervalDef &def, + void write_event_desc(std::ostream &out, const IntervalDef &def, int &extra_indent_level) const; diff --git a/direct/src/interval/hideInterval.cxx b/direct/src/interval/hideInterval.cxx index ed335dc307..46498800e0 100644 --- a/direct/src/interval/hideInterval.cxx +++ b/direct/src/interval/hideInterval.cxx @@ -20,13 +20,13 @@ TypeHandle HideInterval::_type_handle; * */ HideInterval:: -HideInterval(const NodePath &node, const string &name) : +HideInterval(const NodePath &node, const std::string &name) : CInterval(name, 0.0, true), _node(node) { nassertv(!node.is_empty()); if (_name.empty()) { - ostringstream name_strm; + std::ostringstream name_strm; name_strm << "HideInterval-" << node.node()->get_name() << "-" << ++_unique_index; _name = name_strm.str(); diff --git a/direct/src/interval/hideInterval.h b/direct/src/interval/hideInterval.h index 91cd1a9bda..8428d3ab70 100644 --- a/direct/src/interval/hideInterval.h +++ b/direct/src/interval/hideInterval.h @@ -23,7 +23,7 @@ */ class EXPCL_DIRECT_INTERVAL HideInterval : public CInterval { PUBLISHED: - explicit HideInterval(const NodePath &node, const string &name = string()); + explicit HideInterval(const NodePath &node, const std::string &name = std::string()); virtual void priv_instant(); virtual void priv_reverse_instant(); diff --git a/direct/src/interval/showInterval.cxx b/direct/src/interval/showInterval.cxx index 53bc7d2346..b014100f2f 100644 --- a/direct/src/interval/showInterval.cxx +++ b/direct/src/interval/showInterval.cxx @@ -20,13 +20,13 @@ TypeHandle ShowInterval::_type_handle; * */ ShowInterval:: -ShowInterval(const NodePath &node, const string &name) : +ShowInterval(const NodePath &node, const std::string &name) : CInterval(name, 0.0, true), _node(node) { nassertv(!node.is_empty()); if (_name.empty()) { - ostringstream name_strm; + std::ostringstream name_strm; name_strm << "ShowInterval-" << node.node()->get_name() << "-" << ++_unique_index; _name = name_strm.str(); diff --git a/direct/src/interval/showInterval.h b/direct/src/interval/showInterval.h index bff66d8366..c50db953a2 100644 --- a/direct/src/interval/showInterval.h +++ b/direct/src/interval/showInterval.h @@ -23,7 +23,7 @@ */ class EXPCL_DIRECT_INTERVAL ShowInterval : public CInterval { PUBLISHED: - explicit ShowInterval(const NodePath &node, const string &name = string()); + explicit ShowInterval(const NodePath &node, const std::string &name = std::string()); virtual void priv_instant(); virtual void priv_reverse_instant(); diff --git a/direct/src/motiontrail/cMotionTrail.cxx b/direct/src/motiontrail/cMotionTrail.cxx index 988a59c5dc..e578ea2f63 100644 --- a/direct/src/motiontrail/cMotionTrail.cxx +++ b/direct/src/motiontrail/cMotionTrail.cxx @@ -55,14 +55,14 @@ CMotionTrail ( ) { _resolution_distance = 0.5f; // node path states - _geom_node = 0; + _geom_node = nullptr; // real-time data _vertex_index = 0; - _vertex_data = 0; - _triangles = 0; + _vertex_data = nullptr; + _triangles = nullptr; - _vertex_array = 0; + _vertex_array = nullptr; } /** @@ -298,7 +298,7 @@ add_geometry_quad (LVector4 &v0, LVector4 &v1, LVector4 &v2, LVector4 &v3, LVect */ void CMotionTrail::end_geometry ( ) { static CPT(RenderState) state; - if (state == (RenderState *)NULL) { + if (state == nullptr) { state = RenderState::make(ColorAttrib::make_vertex()); } @@ -674,7 +674,7 @@ update_motion_trail (PN_stdfloat current_time, LMatrix4 *transform) { } for (index = 0; index < total_vertices; index++) { - nurbs_curve_result_array [index] = 0; + nurbs_curve_result_array [index] = nullptr; } delete[] nurbs_curve_result_array; @@ -804,6 +804,6 @@ update_motion_trail (PN_stdfloat current_time, LMatrix4 *transform) { this -> end_geometry ( ); delete[] _vertex_array; - _vertex_array = 0; + _vertex_array = nullptr; } } diff --git a/direct/src/plugin/binaryXml.cxx b/direct/src/plugin/binaryXml.cxx index 6363f12d8e..7dc4a60268 100644 --- a/direct/src/plugin/binaryXml.cxx +++ b/direct/src/plugin/binaryXml.cxx @@ -15,6 +15,11 @@ #include "p3d_lock.h" #include +using std::istream; +using std::ostream; +using std::ostringstream; +using std::string; + static const bool debug_xml_output = false; static LOCK xml_lock; @@ -69,11 +74,11 @@ write_xml_node(ostream &out, TiXmlNode *xnode) { // Now write out the node type. NodeType type = NT_element; - if (xnode->ToDocument() != NULL) { + if (xnode->ToDocument() != nullptr) { type = NT_document; - } else if (xnode->ToElement() != NULL) { + } else if (xnode->ToElement() != nullptr) { type = NT_element; - } else if (xnode->ToText() != NULL) { + } else if (xnode->ToText() != nullptr) { type = NT_text; } else { type = NT_unknown; @@ -88,10 +93,10 @@ write_xml_node(ostream &out, TiXmlNode *xnode) { if (type == NT_element) { // Write the element attributes. TiXmlElement *xelement = xnode->ToElement(); - assert(xelement != NULL); + assert(xelement != nullptr); const TiXmlAttribute *xattrib = xelement->FirstAttribute(); - while (xattrib != NULL) { + while (xattrib != nullptr) { // We have an attribute. out.put((char)true); @@ -114,7 +119,7 @@ write_xml_node(ostream &out, TiXmlNode *xnode) { // Now write all of the children. TiXmlNode *xchild = xnode->FirstChild(); - while (xchild != NULL) { + while (xchild != nullptr) { // We have a child. out.put((char)true); write_xml_node(out, xchild); @@ -136,13 +141,13 @@ read_xml_node(istream &in, char *&buffer, xml_uint32 &buffer_length, xml_uint32 value_length; in.read((char *)&value_length, sizeof(value_length)); if (in.gcount() != sizeof(value_length)) { - return NULL; + return nullptr; } xml_uint32 value_proof_expect = (value_length + length_nonce1) * length_nonce2; xml_uint32 value_proof; in.read((char *)&value_proof, sizeof(value_proof)); if (in.gcount() != sizeof(value_proof)) { - return NULL; + return nullptr; } if (value_proof != value_proof_expect) { // Hey, we ran into garbage: the proof value didn't match our expected @@ -164,7 +169,7 @@ read_xml_node(istream &in, char *&buffer, xml_uint32 &buffer_length, } logfile << "\n"; logfile << "End garbage.\n"; - return NULL; + return nullptr; } if (value_length > buffer_length) { @@ -179,10 +184,10 @@ read_xml_node(istream &in, char *&buffer, xml_uint32 &buffer_length, // Read the node type. NodeType type = (NodeType)in.get(); if (type == NT_unknown) { - return NULL; + return nullptr; } - TiXmlNode *xnode = NULL; + TiXmlNode *xnode = nullptr; if (type == NT_element) { xnode = new TiXmlElement(value); } else if (type == NT_document) { @@ -196,7 +201,7 @@ read_xml_node(istream &in, char *&buffer, xml_uint32 &buffer_length, if (type == NT_element) { // Read the element attributes. TiXmlElement *xelement = xnode->ToElement(); - assert(xelement != NULL); + assert(xelement != nullptr); bool got_attrib = (bool)(in.get() != 0); while (got_attrib && in && !in.eof()) { @@ -205,7 +210,7 @@ read_xml_node(istream &in, char *&buffer, xml_uint32 &buffer_length, in.read((char *)&name_length, sizeof(name_length)); if (in.gcount() != sizeof(name_length)) { delete xnode; - return NULL; + return nullptr; } if (name_length > buffer_length) { @@ -221,7 +226,7 @@ read_xml_node(istream &in, char *&buffer, xml_uint32 &buffer_length, in.read((char *)&value_length, sizeof(value_length)); if (in.gcount() != sizeof(value_length)) { delete xnode; - return NULL; + return nullptr; } if (value_length > buffer_length) { @@ -245,7 +250,7 @@ read_xml_node(istream &in, char *&buffer, xml_uint32 &buffer_length, while (got_child && in && !in.eof()) { // We have a child. TiXmlNode *xchild = read_xml_node(in, buffer, buffer_length, logfile); - if (xchild != NULL) { + if (xchild != nullptr) { xnode->LinkEndChild(xchild); } @@ -317,12 +322,12 @@ read_xml(istream &in, ostream &logfile) { char *buffer = new char[buffer_length]; TiXmlNode *xnode = read_xml_node(in, buffer, buffer_length, logfile); delete[] buffer; - if (xnode == NULL) { - return NULL; + if (xnode == nullptr) { + return nullptr; } TiXmlDocument *doc = xnode->ToDocument(); - assert(doc != NULL); + assert(doc != nullptr); #else // standard ASCII read. @@ -330,7 +335,7 @@ read_xml(istream &in, ostream &logfile) { in >> *doc; if (in.fail() || in.eof()) { delete doc; - return NULL; + return nullptr; } #endif diff --git a/direct/src/plugin/binaryXml.h b/direct/src/plugin/binaryXml.h index 4bdd9d29cf..477c51e83f 100644 --- a/direct/src/plugin/binaryXml.h +++ b/direct/src/plugin/binaryXml.h @@ -18,14 +18,12 @@ #include "handleStream.h" #include -using namespace std; - // A pair of functions to input and output the TinyXml constructs on the // indicated streams. We could, of course, use the TinyXml output operators, // but this is a smidge more efficient and gives us more control. void init_xml(); -void write_xml(ostream &out, TiXmlDocument *doc, ostream &logfile); -TiXmlDocument *read_xml(istream &in, ostream &logfile); +void write_xml(std::ostream &out, TiXmlDocument *doc, std::ostream &logfile); +TiXmlDocument *read_xml(std::istream &in, std::ostream &logfile); #endif diff --git a/direct/src/plugin/fileSpec.I b/direct/src/plugin/fileSpec.I index e82e099fb8..22e6f26f81 100644 --- a/direct/src/plugin/fileSpec.I +++ b/direct/src/plugin/fileSpec.I @@ -15,7 +15,7 @@ * Returns the relative path to this file on disk, within the package root * directory. */ -inline const string &FileSpec:: +inline const std::string &FileSpec:: get_filename() const { return _filename; } @@ -25,15 +25,15 @@ get_filename() const { * directory. */ inline void FileSpec:: -set_filename(const string &filename) { +set_filename(const std::string &filename) { _filename = filename; } /** * Returns the full path to this file on disk. */ -inline string FileSpec:: -get_pathname(const string &package_dir) const { +inline std::string FileSpec:: +get_pathname(const std::string &package_dir) const { return package_dir + "/" + _filename; } diff --git a/direct/src/plugin/fileSpec.cxx b/direct/src/plugin/fileSpec.cxx index 58194c10f2..c291bfc14a 100644 --- a/direct/src/plugin/fileSpec.cxx +++ b/direct/src/plugin/fileSpec.cxx @@ -33,6 +33,11 @@ #endif +using std::istream; +using std::ostream; +using std::string; +using std::wstring; + /** * */ @@ -42,7 +47,7 @@ FileSpec() { _timestamp = 0; memset(_hash, 0, hash_size); _got_hash = false; - _actual_file = NULL; + _actual_file = nullptr; } /** @@ -56,7 +61,7 @@ FileSpec(const FileSpec ©) : _got_hash(copy._got_hash) { memcpy(_hash, copy._hash, hash_size); - _actual_file = NULL; + _actual_file = nullptr; } /** @@ -76,7 +81,7 @@ operator = (const FileSpec ©) { */ FileSpec:: ~FileSpec() { - if (_actual_file != NULL) { + if (_actual_file != nullptr) { delete _actual_file; } } @@ -87,25 +92,25 @@ FileSpec:: void FileSpec:: load_xml(TiXmlElement *xelement) { const char *filename = xelement->Attribute("filename"); - if (filename != NULL) { + if (filename != nullptr) { _filename = filename; } const char *size = xelement->Attribute("size"); - if (size != NULL) { + if (size != nullptr) { char *endptr; _size = strtoul(size, &endptr, 10); } const char *timestamp = xelement->Attribute("timestamp"); - if (timestamp != NULL) { + if (timestamp != nullptr) { char *endptr; _timestamp = strtoul(timestamp, &endptr, 10); } _got_hash = false; const char *hash = xelement->Attribute("hash"); - if (hash != NULL && strlen(hash) == (hash_size * 2)) { + if (hash != nullptr && strlen(hash) == (hash_size * 2)) { // Decode the hex hash string. _got_hash = decode_hex(_hash, hash, hash_size); } @@ -151,9 +156,9 @@ quick_verify(const string &package_dir) { */ bool FileSpec:: quick_verify_pathname(const string &pathname) { - if (_actual_file != NULL) { + if (_actual_file != nullptr) { delete _actual_file; - _actual_file = NULL; + _actual_file = nullptr; } int result = 1; @@ -221,9 +226,9 @@ quick_verify_pathname(const string &pathname) { */ bool FileSpec:: full_verify(const string &package_dir) { - if (_actual_file != NULL) { + if (_actual_file != nullptr) { delete _actual_file; - _actual_file = NULL; + _actual_file = nullptr; } string pathname = get_pathname(package_dir); @@ -281,7 +286,7 @@ full_verify(const string &package_dir) { */ const FileSpec *FileSpec:: force_get_actual_file(const string &pathname) { - if (_actual_file == NULL) { + if (_actual_file == nullptr) { #ifdef _WIN32 struct _stat st; wstring pathname_w; @@ -325,10 +330,10 @@ read_hash(const string &pathname) { #ifdef _WIN32 wstring pathname_w; if (string_to_wstring(pathname_w, pathname)) { - stream.open(pathname_w.c_str(), ios::in | ios::binary); + stream.open(pathname_w.c_str(), std::ios::in | std::ios::binary); } #else // _WIN32 - stream.open(pathname.c_str(), ios::in | ios::binary); + stream.open(pathname.c_str(), std::ios::in | std::ios::binary); #endif // _WIN32 if (!stream) { @@ -418,7 +423,7 @@ output_hash(ostream &out) const { bool FileSpec:: priv_check_hash(const string &pathname, void *stp) { const struct stat &st = *(const struct stat *)stp; - assert(_actual_file == NULL); + assert(_actual_file == nullptr); _actual_file = new FileSpec; _actual_file->_filename = pathname; _actual_file->_size = st.st_size; diff --git a/direct/src/plugin/fileSpec.h b/direct/src/plugin/fileSpec.h index 8dc39aebcf..3a661ab603 100644 --- a/direct/src/plugin/fileSpec.h +++ b/direct/src/plugin/fileSpec.h @@ -16,7 +16,6 @@ #include "get_tinyxml.h" #include -using namespace std; /** * This simple class is used both within the core API in this module, as well @@ -33,39 +32,39 @@ public: void load_xml(TiXmlElement *xelement); void store_xml(TiXmlElement *xelement); - inline const string &get_filename() const; - inline void set_filename(const string &filename); - inline string get_pathname(const string &package_dir) const; + inline const std::string &get_filename() const; + inline void set_filename(const std::string &filename); + inline std::string get_pathname(const std::string &package_dir) const; inline size_t get_size() const; inline time_t get_timestamp() const; inline bool has_hash() const; - bool quick_verify(const string &package_dir); - bool quick_verify_pathname(const string &pathname); - bool full_verify(const string &package_dir); + bool quick_verify(const std::string &package_dir); + bool quick_verify_pathname(const std::string &pathname); + bool full_verify(const std::string &package_dir); inline const FileSpec *get_actual_file() const; - const FileSpec *force_get_actual_file(const string &pathname); + const FileSpec *force_get_actual_file(const std::string &pathname); - bool check_hash(const string &pathname) const; - bool read_hash(const string &pathname); - bool read_hash_stream(istream &in); + bool check_hash(const std::string &pathname) const; + bool read_hash(const std::string &pathname); + bool read_hash_stream(std::istream &in); int compare_hash(const FileSpec &other) const; - void write(ostream &out) const; - void output_hash(ostream &out) const; + void write(std::ostream &out) const; + void output_hash(std::ostream &out) const; private: - bool priv_check_hash(const string &pathname, void *stp); + bool priv_check_hash(const std::string &pathname, void *stp); static inline int decode_hexdigit(char c); static inline char encode_hexdigit(int c); static bool decode_hex(unsigned char *dest, const char *source, size_t size); static void encode_hex(char *dest, const unsigned char *source, size_t size); - static void stream_hex(ostream &out, const unsigned char *source, size_t size); + static void stream_hex(std::ostream &out, const unsigned char *source, size_t size); enum { hash_size = 16 }; - string _filename; + std::string _filename; size_t _size; time_t _timestamp; unsigned char _hash[hash_size]; diff --git a/direct/src/plugin/find_root_dir.cxx b/direct/src/plugin/find_root_dir.cxx index 0cf4546a0e..7d20461aa9 100644 --- a/direct/src/plugin/find_root_dir.cxx +++ b/direct/src/plugin/find_root_dir.cxx @@ -27,6 +27,10 @@ #include #endif +using std::cerr; +using std::string; +using std::wstring; + #ifdef _WIN32 // From KnownFolders.h (part of Vista SDK): #define DEFINE_KNOWN_FOLDER(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ @@ -46,7 +50,7 @@ static wstring get_csidl_dir_w(int csidl) { static const int buffer_size = MAX_PATH; wchar_t buffer[buffer_size]; - if (SHGetSpecialFolderPathW(NULL, buffer, csidl, true)) { + if (SHGetSpecialFolderPathW(nullptr, buffer, csidl, true)) { wstring root = buffer; root += wstring(L"/Panda3D"); @@ -73,10 +77,10 @@ find_root_dir_default_w() { wstring root; bool is_protected = false; HMODULE ieframe = LoadLibrary("ieframe.dll"); - if (ieframe != NULL) { + if (ieframe != nullptr) { typedef HRESULT STDAPICALLTYPE IEIsProtectedModeProcess(BOOL *pbResult); IEIsProtectedModeProcess *func = (IEIsProtectedModeProcess *)GetProcAddress(ieframe, "IEIsProtectedModeProcess"); - if (func != NULL) { + if (func != nullptr) { BOOL result = false; HRESULT hr = (*func)(&result); if (hr == S_OK) { @@ -101,12 +105,12 @@ find_root_dir_default_w() { // instead of hard-linking it. HMODULE shell32 = LoadLibrary("shell32.dll"); - if (shell32 != NULL) { + if (shell32 != nullptr) { typedef HRESULT STDAPICALLTYPE SHGetKnownFolderPath(REFGUID rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath); SHGetKnownFolderPath *func = (SHGetKnownFolderPath *)GetProcAddress(shell32, "SHGetKnownFolderPath"); - if (func != NULL) { - LPWSTR cache_path = NULL; - HRESULT hr = (*func)(FOLDERID_LocalAppDataLow, 0, NULL, &cache_path); + if (func != nullptr) { + LPWSTR cache_path = nullptr; + HRESULT hr = (*func)(FOLDERID_LocalAppDataLow, 0, nullptr, &cache_path); if (SUCCEEDED(hr)) { root = cache_path; @@ -128,8 +132,8 @@ find_root_dir_default_w() { // cache folder. typedef HRESULT STDAPICALLTYPE IEGetWriteableFolderPath(REFGUID clsidFolderID, LPWSTR* lppwstrPath); IEGetWriteableFolderPath *func = (IEGetWriteableFolderPath *)GetProcAddress(ieframe, "IEGetWriteableFolderPath"); - if (func != NULL) { - LPWSTR cache_path = NULL; + if (func != nullptr) { + LPWSTR cache_path = nullptr; // Since we're here, we'll start by asking for LocalAppDataLow, even // though I know it doesn't work. @@ -218,9 +222,9 @@ find_root_dir_default() { string root; const passwd *pwdata = getpwuid(getuid()); - if (pwdata == NULL) { + if (pwdata == nullptr) { char *home = getenv("HOME"); - if (home == NULL) { + if (home == nullptr) { // Beh. Let's hope it never gets to this point. return "."; } else { @@ -260,13 +264,13 @@ find_root_dir_actual() { } TiXmlElement *xconfig = doc.FirstChildElement("config"); - if (xconfig == NULL) { + if (xconfig == nullptr) { // No element within config.xml. return root; } const char *new_root = xconfig->Attribute("root_dir"); - if (new_root == NULL || *new_root == '\0') { + if (new_root == nullptr || *new_root == '\0') { // No root_dir specified. return root; } @@ -295,7 +299,7 @@ find_root_dir() { wstring root_w; string_to_wstring(root_w, root); - DWORD length = GetShortPathNameW(root_w.c_str(), NULL, 0); + DWORD length = GetShortPathNameW(root_w.c_str(), nullptr, 0); wchar_t *short_name = new wchar_t[length]; GetShortPathNameW(root_w.c_str(), short_name, length); diff --git a/direct/src/plugin/find_root_dir.h b/direct/src/plugin/find_root_dir.h index cdbb25ec91..e76be59af3 100644 --- a/direct/src/plugin/find_root_dir.h +++ b/direct/src/plugin/find_root_dir.h @@ -16,12 +16,11 @@ #include #include -using namespace std; -string find_root_dir(); +std::string find_root_dir(); #ifdef __APPLE__ -string find_osx_root_dir(); +std::string find_osx_root_dir(); #endif // __APPLE__ #endif diff --git a/direct/src/plugin/find_root_dir_assist.mm b/direct/src/plugin/find_root_dir_assist.mm index e4eed157a6..f27693d147 100644 --- a/direct/src/plugin/find_root_dir_assist.mm +++ b/direct/src/plugin/find_root_dir_assist.mm @@ -70,7 +70,7 @@ get_osx_home_directory() { /** * */ -string +std::string find_osx_root_dir() { string result = call_NSSearchPathForDirectories(NSCachesDirectory, NSUserDomainMask); if (!result.empty()) { diff --git a/direct/src/plugin/handleStream.I b/direct/src/plugin/handleStream.I index 5003b98e82..60021cee96 100644 --- a/direct/src/plugin/handleStream.I +++ b/direct/src/plugin/handleStream.I @@ -15,7 +15,7 @@ * */ inline HandleStream:: -HandleStream() : iostream(&_buf) { +HandleStream() : std::iostream(&_buf) { } /** @@ -32,10 +32,10 @@ inline HandleStream:: */ inline void HandleStream:: open_read(FHandle handle) { - clear((ios::iostate)0); + clear((std::ios::iostatetate)0); _buf.open_read(handle); if (!_buf.is_open_read()) { - clear(ios::failbit); + clear(std::ios::failbit); } } @@ -45,10 +45,10 @@ open_read(FHandle handle) { */ inline void HandleStream:: open_write(FHandle handle) { - clear((ios::iostate)0); + clear((std::ios::iostatetate)0); _buf.open_write(handle); if (!_buf.is_open_write()) { - clear(ios::failbit); + clear(std::ios::failbit); } } diff --git a/direct/src/plugin/handleStream.h b/direct/src/plugin/handleStream.h index abe8b0dee3..b28dec5f6a 100644 --- a/direct/src/plugin/handleStream.h +++ b/direct/src/plugin/handleStream.h @@ -21,7 +21,7 @@ * Windows' HANDLE objects, or Posix file descriptors. This is necessary to * map low-level pipes into an iostream for tinyxml. */ -class HandleStream : public iostream { +class HandleStream : public std::iostream { public: inline HandleStream(); inline ~HandleStream(); diff --git a/direct/src/plugin/handleStreamBuf.cxx b/direct/src/plugin/handleStreamBuf.cxx index c3aa4dc76f..55e74977b5 100644 --- a/direct/src/plugin/handleStreamBuf.cxx +++ b/direct/src/plugin/handleStreamBuf.cxx @@ -28,6 +28,10 @@ #include #endif // !_WIN32 && !__APPLE__ && !__FreeBSD__ +using std::cerr; +using std::dec; +using std::hex; + static const size_t handle_buffer_size = 4096; /** @@ -120,10 +124,10 @@ close() { void HandleStreamBuf:: close_handle() { #ifdef _WIN32 - if (_handle != NULL) { + if (_handle != nullptr) { CloseHandle(_handle); } - _handle = NULL; + _handle = nullptr; #else if (_handle != -1) { ::close(_handle); @@ -256,7 +260,7 @@ read_chars(char *start, size_t length) { #ifdef _WIN32 // Windows case. DWORD bytes_read = 0; - BOOL success = ReadFile(_handle, start, length, &bytes_read, NULL); + BOOL success = ReadFile(_handle, start, length, &bytes_read, nullptr); if (!success) { DWORD error = GetLastError(); if (error != ERROR_HANDLE_EOF && error != ERROR_BROKEN_PIPE) { @@ -304,7 +308,7 @@ write_chars(const char *start, size_t length) { #ifdef _WIN32 // Windows case. DWORD bytes_written = 0; - BOOL success = WriteFile(_handle, start, length, &bytes_written, NULL); + BOOL success = WriteFile(_handle, start, length, &bytes_written, nullptr); if (!success) { assert(bytes_written <= length); DWORD error = GetLastError(); diff --git a/direct/src/plugin/handleStreamBuf.h b/direct/src/plugin/handleStreamBuf.h index 68486ec69f..da3448d4d3 100644 --- a/direct/src/plugin/handleStreamBuf.h +++ b/direct/src/plugin/handleStreamBuf.h @@ -18,12 +18,10 @@ #include "p3d_lock.h" #include -using namespace std; - /** * */ -class HandleStreamBuf : public streambuf { +class HandleStreamBuf : public std::streambuf { public: HandleStreamBuf(); virtual ~HandleStreamBuf(); diff --git a/direct/src/plugin/load_plugin.cxx b/direct/src/plugin/load_plugin.cxx index f5a730eacb..75def4fc10 100644 --- a/direct/src/plugin/load_plugin.cxx +++ b/direct/src/plugin/load_plugin.cxx @@ -24,6 +24,8 @@ #include #endif +using std::string; + #ifdef _WIN32 static const string dll_ext = ".dll"; #elif defined(__APPLE__) @@ -75,9 +77,9 @@ P3D_instance_feed_url_stream_func *P3D_instance_feed_url_stream_ptr; P3D_instance_handle_event_func *P3D_instance_handle_event_ptr; #ifdef _WIN32 -static HMODULE module = NULL; +static HMODULE module = nullptr; #else -static void *module = NULL; +static void *module = nullptr; #endif static bool plugin_loaded = false; @@ -132,18 +134,18 @@ load_plugin(const string &p3d_plugin_filename, const string &log_directory, const string &log_basename, bool trusted_environment, bool console_environment, const string &root_dir, const string &host_dir, - const string &start_dir, ostream &logfile) { + const string &start_dir, std::ostream &logfile) { if (plugin_loaded) { return true; } string filename = p3d_plugin_filename; #ifdef _WIN32 - assert(module == NULL); + assert(module == nullptr); if (filename.empty()) { // If no filename is supplied, look within our existing address space. - module = GetModuleHandle(NULL); + module = GetModuleHandle(nullptr); dso_needs_unload = false; } else { @@ -161,14 +163,14 @@ load_plugin(const string &p3d_plugin_filename, } SetErrorMode(0); - wstring filename_w; + std::wstring filename_w; if (string_to_wstring(filename_w, filename)) { module = LoadLibraryW(filename_w.c_str()); } dso_needs_unload = true; } - if (module == NULL) { + if (module == nullptr) { // Couldn't load the DLL. logfile << "Couldn't load " << filename << ", error = " @@ -180,16 +182,16 @@ load_plugin(const string &p3d_plugin_filename, #else // _WIN32 // Posix case. - assert(module == NULL); + assert(module == nullptr); if (filename.empty()) { - module = dlopen(NULL, RTLD_LAZY | RTLD_LOCAL); + module = dlopen(nullptr, RTLD_LAZY | RTLD_LOCAL); } else { module = dlopen(filename.c_str(), RTLD_LAZY | RTLD_LOCAL); } - if (module == NULL) { + if (module == nullptr) { // Couldn't load the .so. const char *message = dlerror(); - if (message == (char *)NULL) { + if (message == nullptr) { message = "No error"; } logfile << "Couldn't load " << filename << ": " << message << "\n"; @@ -273,48 +275,48 @@ init_plugin(const string &contents_filename, const string &host_url, const string &log_directory, const string &log_basename, bool trusted_environment, bool console_environment, const string &root_dir, const string &host_dir, - const string &start_dir, ostream &logfile) { + const string &start_dir, std::ostream &logfile) { // Ensure that all of the function pointers have been found. - if (P3D_initialize_ptr == NULL || - P3D_finalize_ptr == NULL || - P3D_set_plugin_version_ptr == NULL || - P3D_set_super_mirror_ptr == NULL || - P3D_new_instance_ptr == NULL || - P3D_instance_start_ptr == NULL || - P3D_instance_start_stream_ptr == NULL || - P3D_instance_finish_ptr == NULL || - P3D_instance_setup_window_ptr == NULL || + if (P3D_initialize_ptr == nullptr || + P3D_finalize_ptr == nullptr || + P3D_set_plugin_version_ptr == nullptr || + P3D_set_super_mirror_ptr == nullptr || + P3D_new_instance_ptr == nullptr || + P3D_instance_start_ptr == nullptr || + P3D_instance_start_stream_ptr == nullptr || + P3D_instance_finish_ptr == nullptr || + P3D_instance_setup_window_ptr == nullptr || - P3D_object_get_type_ptr == NULL || - P3D_object_get_bool_ptr == NULL || - P3D_object_get_int_ptr == NULL || - P3D_object_get_float_ptr == NULL || - P3D_object_get_string_ptr == NULL || - P3D_object_get_repr_ptr == NULL || - P3D_object_get_property_ptr == NULL || - P3D_object_set_property_ptr == NULL || - P3D_object_has_method_ptr == NULL || - P3D_object_call_ptr == NULL || - P3D_object_eval_ptr == NULL || - P3D_object_incref_ptr == NULL || - P3D_object_decref_ptr == NULL || + P3D_object_get_type_ptr == nullptr || + P3D_object_get_bool_ptr == nullptr || + P3D_object_get_int_ptr == nullptr || + P3D_object_get_float_ptr == nullptr || + P3D_object_get_string_ptr == nullptr || + P3D_object_get_repr_ptr == nullptr || + P3D_object_get_property_ptr == nullptr || + P3D_object_set_property_ptr == nullptr || + P3D_object_has_method_ptr == nullptr || + P3D_object_call_ptr == nullptr || + P3D_object_eval_ptr == nullptr || + P3D_object_incref_ptr == nullptr || + P3D_object_decref_ptr == nullptr || - P3D_make_class_definition_ptr == NULL || - P3D_new_undefined_object_ptr == NULL || - P3D_new_none_object_ptr == NULL || - P3D_new_bool_object_ptr == NULL || - P3D_new_int_object_ptr == NULL || - P3D_new_float_object_ptr == NULL || - P3D_new_string_object_ptr == NULL || - P3D_instance_get_panda_script_object_ptr == NULL || - P3D_instance_set_browser_script_object_ptr == NULL || + P3D_make_class_definition_ptr == nullptr || + P3D_new_undefined_object_ptr == nullptr || + P3D_new_none_object_ptr == nullptr || + P3D_new_bool_object_ptr == nullptr || + P3D_new_int_object_ptr == nullptr || + P3D_new_float_object_ptr == nullptr || + P3D_new_string_object_ptr == nullptr || + P3D_instance_get_panda_script_object_ptr == nullptr || + P3D_instance_set_browser_script_object_ptr == nullptr || - P3D_instance_get_request_ptr == NULL || - P3D_check_request_ptr == NULL || - P3D_request_finish_ptr == NULL || - P3D_instance_feed_url_stream_ptr == NULL || - P3D_instance_handle_event_ptr == NULL) { + P3D_instance_get_request_ptr == nullptr || + P3D_check_request_ptr == nullptr || + P3D_request_finish_ptr == nullptr || + P3D_instance_feed_url_stream_ptr == nullptr || + P3D_instance_handle_event_ptr == nullptr) { logfile << "Some function pointers not found:" @@ -392,7 +394,7 @@ init_plugin(const string &contents_filename, const string &host_url, * the pointers. */ void -unload_plugin(ostream &logfile) { +unload_plugin(std::ostream &logfile) { if (!plugin_loaded) { return; } @@ -411,55 +413,55 @@ unload_plugin(ostream &logfile) { static void unload_dso() { if (dso_needs_unload) { - assert(module != NULL); + assert(module != nullptr); #ifdef _WIN32 FreeLibrary(module); #else dlclose(module); #endif - module = NULL; + module = nullptr; dso_needs_unload = false; } - P3D_initialize_ptr = NULL; - P3D_finalize_ptr = NULL; - P3D_set_plugin_version_ptr = NULL; - P3D_set_super_mirror_ptr = NULL; - P3D_new_instance_ptr = NULL; - P3D_instance_start_ptr = NULL; - P3D_instance_start_stream_ptr = NULL; - P3D_instance_finish_ptr = NULL; - P3D_instance_setup_window_ptr = NULL; + P3D_initialize_ptr = nullptr; + P3D_finalize_ptr = nullptr; + P3D_set_plugin_version_ptr = nullptr; + P3D_set_super_mirror_ptr = nullptr; + P3D_new_instance_ptr = nullptr; + P3D_instance_start_ptr = nullptr; + P3D_instance_start_stream_ptr = nullptr; + P3D_instance_finish_ptr = nullptr; + P3D_instance_setup_window_ptr = nullptr; - P3D_object_get_type_ptr = NULL; - P3D_object_get_bool_ptr = NULL; - P3D_object_get_int_ptr = NULL; - P3D_object_get_float_ptr = NULL; - P3D_object_get_string_ptr = NULL; - P3D_object_get_repr_ptr = NULL; - P3D_object_get_property_ptr = NULL; - P3D_object_set_property_ptr = NULL; - P3D_object_has_method_ptr = NULL; - P3D_object_call_ptr = NULL; - P3D_object_eval_ptr = NULL; - P3D_object_incref_ptr = NULL; - P3D_object_decref_ptr = NULL; + P3D_object_get_type_ptr = nullptr; + P3D_object_get_bool_ptr = nullptr; + P3D_object_get_int_ptr = nullptr; + P3D_object_get_float_ptr = nullptr; + P3D_object_get_string_ptr = nullptr; + P3D_object_get_repr_ptr = nullptr; + P3D_object_get_property_ptr = nullptr; + P3D_object_set_property_ptr = nullptr; + P3D_object_has_method_ptr = nullptr; + P3D_object_call_ptr = nullptr; + P3D_object_eval_ptr = nullptr; + P3D_object_incref_ptr = nullptr; + P3D_object_decref_ptr = nullptr; - P3D_make_class_definition_ptr = NULL; - P3D_new_undefined_object_ptr = NULL; - P3D_new_none_object_ptr = NULL; - P3D_new_bool_object_ptr = NULL; - P3D_new_int_object_ptr = NULL; - P3D_new_float_object_ptr = NULL; - P3D_new_string_object_ptr = NULL; - P3D_instance_get_panda_script_object_ptr = NULL; - P3D_instance_set_browser_script_object_ptr = NULL; + P3D_make_class_definition_ptr = nullptr; + P3D_new_undefined_object_ptr = nullptr; + P3D_new_none_object_ptr = nullptr; + P3D_new_bool_object_ptr = nullptr; + P3D_new_int_object_ptr = nullptr; + P3D_new_float_object_ptr = nullptr; + P3D_new_string_object_ptr = nullptr; + P3D_instance_get_panda_script_object_ptr = nullptr; + P3D_instance_set_browser_script_object_ptr = nullptr; - P3D_instance_get_request_ptr = NULL; - P3D_check_request_ptr = NULL; - P3D_request_finish_ptr = NULL; - P3D_instance_feed_url_stream_ptr = NULL; - P3D_instance_handle_event_ptr = NULL; + P3D_instance_get_request_ptr = nullptr; + P3D_check_request_ptr = nullptr; + P3D_request_finish_ptr = nullptr; + P3D_instance_feed_url_stream_ptr = nullptr; + P3D_instance_handle_event_ptr = nullptr; plugin_loaded = false; } diff --git a/direct/src/plugin/load_plugin.h b/direct/src/plugin/load_plugin.h index b6a41a3f9c..2e462ed9cd 100644 --- a/direct/src/plugin/load_plugin.h +++ b/direct/src/plugin/load_plugin.h @@ -17,7 +17,6 @@ #include "p3d_plugin.h" #include -using namespace std; extern P3D_initialize_func *P3D_initialize_ptr; extern P3D_finalize_func *P3D_finalize_ptr; @@ -59,24 +58,24 @@ extern P3D_request_finish_func *P3D_request_finish_ptr; extern P3D_instance_feed_url_stream_func *P3D_instance_feed_url_stream_ptr; extern P3D_instance_handle_event_func *P3D_instance_handle_event_ptr; -string get_plugin_basename(); +std::string get_plugin_basename(); bool -load_plugin(const string &p3d_plugin_filename, - const string &contents_filename, const string &host_url, - P3D_verify_contents verify_contents, const string &platform, - const string &log_directory, const string &log_basename, +load_plugin(const std::string &p3d_plugin_filename, + const std::string &contents_filename, const std::string &host_url, + P3D_verify_contents verify_contents, const std::string &platform, + const std::string &log_directory, const std::string &log_basename, bool trusted_environment, bool console_environment, - const string &root_dir, const string &host_dir, - const string &start_dir, ostream &logfile); + const std::string &root_dir, const std::string &host_dir, + const std::string &start_dir, std::ostream &logfile); bool -init_plugin(const string &contents_filename, const string &host_url, - P3D_verify_contents verify_contents, const string &platform, - const string &log_directory, const string &log_basename, +init_plugin(const std::string &contents_filename, const std::string &host_url, + P3D_verify_contents verify_contents, const std::string &platform, + const std::string &log_directory, const std::string &log_basename, bool trusted_environment, bool console_environment, - const string &root_dir, const string &host_dir, - const string &start_dir, ostream &logfile); + const std::string &root_dir, const std::string &host_dir, + const std::string &start_dir, std::ostream &logfile); -void unload_plugin(ostream &logfile); +void unload_plugin(std::ostream &logfile); bool is_plugin_loaded(); #endif diff --git a/direct/src/plugin/mkdir_complete.cxx b/direct/src/plugin/mkdir_complete.cxx index 9422ea2e32..6689584198 100644 --- a/direct/src/plugin/mkdir_complete.cxx +++ b/direct/src/plugin/mkdir_complete.cxx @@ -26,6 +26,10 @@ #include #endif +using std::ostream; +using std::string; +using std::wstring; + /** * Returns the directory component of the indicated pathname, or the empty * string if there is no directory prefix. @@ -154,7 +158,7 @@ mkfile_complete(const string &filename, ostream &logfile) { */ bool mkdir_complete_w(const wstring &dirname, ostream &logfile) { - if (CreateDirectoryW(dirname.c_str(), NULL) != 0) { + if (CreateDirectoryW(dirname.c_str(), nullptr) != 0) { // Success! return true; } @@ -171,7 +175,7 @@ mkdir_complete_w(const wstring &dirname, ostream &logfile) { wstring parent = get_dirname_w(dirname); if (!parent.empty() && mkdir_complete_w(parent, logfile)) { // Parent successfully created. Try again to make the child. - if (CreateDirectoryW(dirname.c_str(), NULL) != 0) { + if (CreateDirectoryW(dirname.c_str(), nullptr) != 0) { // Got it! return true; } @@ -198,7 +202,7 @@ mkfile_complete_w(const wstring &filename, ostream &logfile) { HANDLE file = CreateFileW(filename.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) { // Try to make the parent directory first. wstring parent = get_dirname_w(filename); @@ -206,7 +210,7 @@ mkfile_complete_w(const wstring &filename, ostream &logfile) { // Parent successfully created. Try again to make the file. file = CreateFileW(filename.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); } if (file == INVALID_HANDLE_VALUE) { logfile diff --git a/direct/src/plugin/mkdir_complete.h b/direct/src/plugin/mkdir_complete.h index 9b9521a9bd..be79cf7e8e 100644 --- a/direct/src/plugin/mkdir_complete.h +++ b/direct/src/plugin/mkdir_complete.h @@ -16,14 +16,13 @@ #include #include -using namespace std; -bool mkdir_complete(const string &dirname, ostream &logfile); -bool mkfile_complete(const string &dirname, ostream &logfile); +bool mkdir_complete(const std::string &dirname, std::ostream &logfile); +bool mkfile_complete(const std::string &dirname, std::ostream &logfile); #ifdef _WIN32 -bool mkdir_complete_w(const wstring &dirname, ostream &logfile); -bool mkfile_complete_w(const wstring &dirname, ostream &logfile); +bool mkdir_complete_w(const std::wstring &dirname, std::ostream &logfile); +bool mkfile_complete_w(const std::wstring &dirname, std::ostream &logfile); #endif // _WIN32 #endif diff --git a/direct/src/plugin/p3dAuthSession.cxx b/direct/src/plugin/p3dAuthSession.cxx index 46678c19ad..e76bbe0a07 100644 --- a/direct/src/plugin/p3dAuthSession.cxx +++ b/direct/src/plugin/p3dAuthSession.cxx @@ -30,6 +30,8 @@ #include #endif +using std::string; + /** * */ @@ -53,7 +55,7 @@ P3DAuthSession(P3DInstance *inst) : _cert_filename = new P3DTemporaryFile(".crt"); string filename = _cert_filename->get_filename(); FILE *fp = fopen(filename.c_str(), "w"); - if (fp == NULL) { + if (fp == nullptr) { nout << "Couldn't write temporary file\n"; return; } @@ -88,7 +90,7 @@ P3DAuthSession:: ~P3DAuthSession() { shutdown(false); - if (_cert_filename != NULL) { + if (_cert_filename != nullptr) { delete _cert_filename; } } @@ -101,7 +103,7 @@ shutdown(bool send_message) { if (!send_message) { // If we're not to send the instance the shutdown message as a result of // this, then clear the _inst pointer now. - _inst = NULL; + _inst = nullptr; } if (_p3dcert_running) { @@ -119,7 +121,7 @@ shutdown(bool send_message) { struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 100000; - select(0, NULL, NULL, NULL, &tv); + select(0, nullptr, nullptr, nullptr, &tv); int status; waitpid(_p3dcert_pid, &status, WNOHANG); #endif // _WIN32 @@ -133,7 +135,7 @@ shutdown(bool send_message) { join_wait_thread(); // We're no longer bound to any particular instance. - _inst = NULL; + _inst = nullptr; } /** @@ -146,7 +148,7 @@ start_p3dcert() { return; } - if (_inst->_p3dcert_package == NULL) { + if (_inst->_p3dcert_package == nullptr) { nout << "Couldn't start Python: no p3dcert package.\n"; return; } @@ -175,14 +177,14 @@ start_p3dcert() { const wchar_t *keep[] = { L"TMP", L"TEMP", L"HOME", L"USER", L"SYSTEMROOT", L"USERPROFILE", L"COMSPEC", - NULL + nullptr }; - wstring env_w; + std::wstring env_w; - for (int ki = 0; keep[ki] != NULL; ++ki) { + for (int ki = 0; keep[ki] != nullptr; ++ki) { wchar_t *value = _wgetenv(keep[ki]); - if (value != NULL) { + if (value != nullptr) { env_w += keep[ki]; env_w += L"="; env_w += value; @@ -204,11 +206,11 @@ start_p3dcert() { #ifdef HAVE_X11 "DISPLAY", "XAUTHORITY", #endif - NULL + nullptr }; - for (int ki = 0; keep[ki] != NULL; ++ki) { + for (int ki = 0; keep[ki] != nullptr; ++ki) { char *value = getenv(keep[ki]); - if (value != NULL) { + if (value != nullptr) { _env += keep[ki]; _env += "="; _env += value; @@ -337,7 +339,7 @@ wt_thread_run() { // Notify the instance that we're done. P3DInstance *inst = _inst; - if (inst != NULL) { + if (inst != nullptr) { inst->auth_finished_sub_thread(); } @@ -369,7 +371,7 @@ win_create_process() { // Construct the command-line string, containing the quoted command-line // arguments. - ostringstream stream; + std::ostringstream stream; stream << "\"" << _p3dcert_exe << "\" \"" << _cert_filename->get_filename() << "\" \"" << _cert_dir << "\""; @@ -388,7 +390,7 @@ win_create_process() { // anyway. PROCESS_INFORMATION process_info; BOOL result = CreateProcess - (_p3dcert_exe.c_str(), command_line, NULL, NULL, TRUE, + (_p3dcert_exe.c_str(), command_line, nullptr, nullptr, TRUE, 0, (void *)_env.c_str(), start_dir_cstr, &startup_info, &process_info); bool started_program = (result != 0); @@ -432,7 +434,7 @@ posix_create_process() { } // build up an array of char strings for the environment. - vector ptrs; + std::vector ptrs; size_t p = 0; size_t zero = _env.find('\0', p); while (zero != string::npos) { @@ -440,7 +442,7 @@ posix_create_process() { p = zero + 1; zero = _env.find('\0', p); } - ptrs.push_back((char *)NULL); + ptrs.push_back(nullptr); execle(_p3dcert_exe.c_str(), _p3dcert_exe.c_str(), _cert_filename->get_filename().c_str(), _cert_dir.c_str(), diff --git a/direct/src/plugin/p3dAuthSession.h b/direct/src/plugin/p3dAuthSession.h index 3df7894279..f37f24d9e3 100644 --- a/direct/src/plugin/p3dAuthSession.h +++ b/direct/src/plugin/p3dAuthSession.h @@ -56,13 +56,13 @@ private: private: P3DInstance *_inst; - string _start_dir; + std::string _start_dir; // This information is passed to create_process(). P3DTemporaryFile *_cert_filename; - string _cert_dir; - string _p3dcert_exe; - string _env; + std::string _cert_dir; + std::string _p3dcert_exe; + std::string _env; #ifdef _WIN32 HANDLE _p3dcert_handle; diff --git a/direct/src/plugin/p3dBoolObject.cxx b/direct/src/plugin/p3dBoolObject.cxx index 87736ba216..7740c2f669 100644 --- a/direct/src/plugin/p3dBoolObject.cxx +++ b/direct/src/plugin/p3dBoolObject.cxx @@ -59,7 +59,7 @@ get_int() { * to a string. */ void P3DBoolObject:: -make_string(string &value) { +make_string(std::string &value) { if (_value) { value = "True"; } else { diff --git a/direct/src/plugin/p3dBoolObject.h b/direct/src/plugin/p3dBoolObject.h index 83a950cb76..85eb0a127c 100644 --- a/direct/src/plugin/p3dBoolObject.h +++ b/direct/src/plugin/p3dBoolObject.h @@ -29,7 +29,7 @@ public: virtual P3D_object_type get_type(); virtual bool get_bool(); virtual int get_int(); - virtual void make_string(string &value); + virtual void make_string(std::string &value); private: bool _value; diff --git a/direct/src/plugin/p3dCInstance.cxx b/direct/src/plugin/p3dCInstance.cxx index d6ecf259f1..0f77925b22 100644 --- a/direct/src/plugin/p3dCInstance.cxx +++ b/direct/src/plugin/p3dCInstance.cxx @@ -19,7 +19,7 @@ */ P3DCInstance:: P3DCInstance(TiXmlElement *xinstance) : - _func(NULL) + _func(nullptr) { xinstance->Attribute("instance_id", &_instance_id); } diff --git a/direct/src/plugin/p3dCert.cxx b/direct/src/plugin/p3dCert.cxx index bae39a3c76..e6868bdb80 100644 --- a/direct/src/plugin/p3dCert.cxx +++ b/direct/src/plugin/p3dCert.cxx @@ -46,6 +46,10 @@ #include #endif +using std::cerr; +using std::string; +using std::wstring; + static LanguageIndex li = LI_default; #if defined(_WIN32) @@ -55,10 +59,10 @@ static LanguageIndex detect_language() { typedef BOOL (*GUPL)(DWORD, PULONG, PZZWSTR, PULONG); GUPL pGetUserPreferredUILanguages = (GUPL)GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), TEXT("GetUserPreferredUILanguages")); - if (pGetUserPreferredUILanguages != NULL) { + if (pGetUserPreferredUILanguages != nullptr) { ULONG num_langs = 0; ULONG buffer_size = 0; - pGetUserPreferredUILanguages(8, &num_langs, NULL, &buffer_size); + pGetUserPreferredUILanguages(8, &num_langs, nullptr, &buffer_size); PZZWSTR buffer = (PZZWSTR)_alloca(buffer_size); if (pGetUserPreferredUILanguages(8, &num_langs, buffer, &buffer_size)) { for (ULONG i = 0; i < num_langs; ++i) { @@ -67,7 +71,7 @@ static LanguageIndex detect_language() { // It may be a two-letter code; match it in our list. for (int j = 0; j < LI_COUNT; ++j) { const char *lang_code = language_codes[j]; - if (lang_code != NULL && lang_code[0] == buffer[0] && + if (lang_code != nullptr && lang_code[0] == buffer[0] && lang_code[1] == buffer[1]) { return (LanguageIndex)j; } @@ -120,7 +124,7 @@ static LanguageIndex detect_language() { // See if we support this language. for (int j = 0; j < LI_COUNT; ++j) { const char *lang_code = language_codes[j]; - if (lang_code != NULL && strncasecmp(buffer, lang_code, 2) == 0) { + if (lang_code != nullptr && strncasecmp(buffer, lang_code, 2) == 0) { CFRelease(langs); return (LanguageIndex)j; } @@ -136,10 +140,10 @@ static LanguageIndex detect_language() { // First consult the LANGUAGE variable, which is a GNU extension that can // contain multiple languages in order of preference. const char *lang = getenv("LANGUAGE"); - while (lang != NULL && lang[0] != 0) { + while (lang != nullptr && lang[0] != 0) { size_t len; const char *next = strchr(lang, ':'); - if (next == NULL) { + if (next == nullptr) { len = strlen(lang); } else { len = (next - lang); @@ -150,7 +154,7 @@ static LanguageIndex detect_language() { // It may be a two-letter language code; match it in our list. for (int i = 0; i < LI_COUNT; ++i) { const char *lang_code = language_codes[i]; - if (lang_code != NULL && strncasecmp(lang, lang_code, 2) == 0) { + if (lang_code != nullptr && strncasecmp(lang, lang_code, 2) == 0) { return (LanguageIndex)i; } } @@ -161,14 +165,14 @@ static LanguageIndex detect_language() { // Fall back to the C locale functions. setlocale(LC_ALL, ""); - lang = setlocale(LC_MESSAGES, NULL); + lang = setlocale(LC_MESSAGES, nullptr); - if (lang == NULL || lang[0] == 0 || strcmp(lang, "C") == 0) { + if (lang == nullptr || lang[0] == 0 || strcmp(lang, "C") == 0) { // Try the LANG variable. lang = getenv("LANG"); } - if (lang == NULL || strlen(lang) < 2 || isalnum(lang[2])) { + if (lang == nullptr || strlen(lang) < 2 || isalnum(lang[2])) { // Couldn't extract a meaningful two-letter code. return LI_default; } @@ -176,7 +180,7 @@ static LanguageIndex detect_language() { // It may be a two-letter language code; match it in our list. for (int i = 0; i < LI_COUNT; ++i) { const char *lang_code = language_codes[i]; - if (lang_code != NULL && strncasecmp(lang, lang_code, 2) == 0) { + if (lang_code != nullptr && strncasecmp(lang, lang_code, 2) == 0) { return (LanguageIndex)i; } } @@ -192,7 +196,7 @@ wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdS LPWSTR *argv; int argc; argv = CommandLineToArgvW(pCmdLine, &argc); - if (argv == NULL || argc != 2) { + if (argv == nullptr || argc != 2) { cerr << "usage: p3dcert cert_filename cert_dir\n"; return 1; } @@ -243,10 +247,10 @@ AuthDialog(const string &cert_filename, const string &cert_dir) : Fl_Window(435, 242, new_application_title[li]), _cert_dir(cert_dir) { - _view_cert_dialog = NULL; + _view_cert_dialog = nullptr; - _cert = NULL; - _stack = NULL; + _cert = nullptr; + _stack = nullptr; _verify_result = -1; // Center the window on the screen. @@ -264,17 +268,17 @@ AuthDialog(const string &cert_filename, const string &cert_dir) : */ AuthDialog:: ~AuthDialog() { - if (_view_cert_dialog != NULL) { + if (_view_cert_dialog != nullptr) { _view_cert_dialog->hide(); } - if (_cert != NULL) { + if (_cert != nullptr) { X509_free(_cert); - _cert = NULL; + _cert = nullptr; } - if (_stack != NULL) { + if (_stack != nullptr) { sk_X509_free(_stack); - _stack = NULL; + _stack = nullptr; } } @@ -294,7 +298,7 @@ void AuthDialog:: view_cert_clicked(Fl_Widget *w, void *data) { AuthDialog *dlg = (AuthDialog *) data; - if (dlg->_view_cert_dialog != NULL) { + if (dlg->_view_cert_dialog != nullptr) { dlg->_view_cert_dialog->hide(); } dlg->hide(); @@ -317,7 +321,7 @@ cancel_clicked(Fl_Widget *w, void *data) { */ void AuthDialog:: approve_cert() { - assert(_cert != NULL); + assert(_cert != nullptr); // Make sure the directory exists. #ifdef _WIN32 @@ -332,7 +336,7 @@ approve_cert() { // Sure, there's a slight race condition right now: another process might // attempt to create the same filename. So what. - FILE *fp = NULL; + FILE *fp = nullptr; #ifdef _WIN32 wchar_t *buf = new wchar_t[buf_length]; @@ -366,7 +370,7 @@ approve_cert() { fp = fopen(buf, "w"); #endif // _WIN32 - if (fp != NULL) { + if (fp != nullptr) { PEM_write_X509(fp, _cert); fclose(fp); } @@ -386,14 +390,14 @@ void AuthDialog:: read_cert_file(const string &cert_filename) { #endif - FILE *fp = NULL; + FILE *fp = nullptr; #ifdef _WIN32 fp = _wfopen(cert_filename.c_str(), L"r"); #else // _WIN32 fp = fopen(cert_filename.c_str(), "r"); #endif // _WIN32 - if (fp == NULL) { + if (fp == nullptr) { #ifdef _WIN32 wcerr << L"Couldn't read " << cert_filename.c_str() << L"\n"; #else @@ -401,8 +405,8 @@ read_cert_file(const string &cert_filename) { #endif return; } - _cert = PEM_read_X509(fp, NULL, NULL, (void *)""); - if (_cert == NULL) { + _cert = PEM_read_X509(fp, nullptr, nullptr, (void *)""); + if (_cert == nullptr) { #ifdef _WIN32 wcerr << L"Could not read certificate in " << cert_filename.c_str() << L".\n"; #else @@ -413,11 +417,11 @@ read_cert_file(const string &cert_filename) { } // Build up a STACK of the remaining certificates in the file. - _stack = sk_X509_new(NULL); - X509 *c = PEM_read_X509(fp, NULL, NULL, (void *)""); - while (c != NULL) { + _stack = sk_X509_new(nullptr); + X509 *c = PEM_read_X509(fp, nullptr, nullptr, (void *)""); + while (c != nullptr) { sk_X509_push(_stack, c); - c = PEM_read_X509(fp, NULL, NULL, (void *)""); + c = PEM_read_X509(fp, nullptr, nullptr, (void *)""); } fclose(fp); @@ -429,7 +433,7 @@ read_cert_file(const string &cert_filename) { */ void AuthDialog:: get_friendly_name() { - if (_cert == NULL) { + if (_cert == nullptr) { _friendly_name.clear(); return; } @@ -447,15 +451,15 @@ get_friendly_name() { // A complex OpenSSL interface to extract out the name in utf-8. X509_NAME *xname = X509_get_subject_name(_cert); - if (xname != NULL) { + if (xname != nullptr) { int pos = X509_NAME_get_index_by_NID(xname, nid, -1); if (pos != -1) { // We just get the first common name. I guess it's possible to have // more than one; not sure what that means in this context. X509_NAME_ENTRY *xentry = X509_NAME_get_entry(xname, pos); - if (xentry != NULL) { + if (xentry != nullptr) { ASN1_STRING *data = X509_NAME_ENTRY_get_data(xentry); - if (data != NULL) { + if (data != nullptr) { // We use "print" to dump the output to a memory BIO. Is there an // easier way to decode the ASN1_STRING? Curse these incomplete // docs. @@ -480,7 +484,7 @@ get_friendly_name() { */ void AuthDialog:: verify_cert() { - if (_cert == NULL) { + if (_cert == nullptr) { _verify_result = -1; return; } @@ -535,11 +539,11 @@ load_certificates_from_der_ram(X509_STORE *store, bp = (unsigned char *)data; bp_end = bp + data_size; - X509 *x509 = d2i_X509(NULL, &bp, bp_end - bp); - while (x509 != NULL) { + X509 *x509 = d2i_X509(nullptr, &bp, bp_end - bp); + while (x509 != nullptr) { X509_STORE_add_cert(store, x509); ++count; - x509 = d2i_X509(NULL, &bp, bp_end - bp); + x509 = d2i_X509(nullptr, &bp, bp_end - bp); } return count; @@ -578,7 +582,7 @@ layout() { next_y += 180; short nbuttons = 1; - if (_cert != NULL) { + if (_cert != nullptr) { nbuttons++; if (_verify_result == 0) { nbuttons++; @@ -586,13 +590,13 @@ layout() { } short bx = (w() - nbuttons * BUTTON_WIDTH - (nbuttons - 1) * BUTTON_SPACE) / 2; - if (_verify_result == 0 && _cert != NULL) { + if (_verify_result == 0 && _cert != nullptr) { Fl_Return_Button *run_button = new Fl_Return_Button(bx, next_y, BUTTON_WIDTH, 25, run_title[li]); run_button->callback(this->run_clicked, this); bx += BUTTON_WIDTH + BUTTON_SPACE; } - if (_cert != NULL) { + if (_cert != nullptr) { Fl_Button *view_button = new Fl_Button(bx, next_y, BUTTON_WIDTH, 25, show_cert_title[li]); view_button->callback(this->view_cert_clicked, this); bx += BUTTON_WIDTH + BUTTON_SPACE; @@ -672,8 +676,8 @@ ViewCertDialog(AuthDialog *auth_dialog, X509 *cert) : */ ViewCertDialog:: ~ViewCertDialog() { - if (_auth_dialog != NULL) { - _auth_dialog->_view_cert_dialog = NULL; + if (_auth_dialog != nullptr) { + _auth_dialog->_view_cert_dialog = nullptr; } } @@ -683,7 +687,7 @@ ViewCertDialog:: void ViewCertDialog:: run_clicked(Fl_Widget *w, void *data) { ViewCertDialog *dlg = (ViewCertDialog *) data; - if (dlg->_auth_dialog != NULL){ + if (dlg->_auth_dialog != nullptr){ dlg->_auth_dialog->approve_cert(); } dlg->hide(); @@ -695,7 +699,7 @@ run_clicked(Fl_Widget *w, void *data) { void ViewCertDialog:: cancel_clicked(Fl_Widget *w, void *data) { ViewCertDialog *dlg = (ViewCertDialog *) data; - if (dlg->_auth_dialog != NULL){ + if (dlg->_auth_dialog != nullptr){ dlg->_auth_dialog->hide(); } dlg->hide(); @@ -707,7 +711,7 @@ cancel_clicked(Fl_Widget *w, void *data) { void ViewCertDialog:: layout() { // Format the certificate text for display in the dialog. - assert(_cert != NULL); + assert(_cert != nullptr); BIO *mbio = BIO_new(BIO_s_mem()); X509_print(mbio, _cert); diff --git a/direct/src/plugin/p3dCert.h b/direct/src/plugin/p3dCert.h index d5dbdd76a4..3c856c6ec3 100644 --- a/direct/src/plugin/p3dCert.h +++ b/direct/src/plugin/p3dCert.h @@ -25,7 +25,6 @@ #include #include #include -using namespace std; class ViewCertDialog; @@ -50,9 +49,9 @@ class ViewCertDialog; class AuthDialog : public Fl_Window { public: #ifdef _WIN32 - AuthDialog(const wstring &cert_filename, const wstring &cert_dir); + AuthDialog(const std::wstring &cert_filename, const std::wstring &cert_dir); #else - AuthDialog(const string &cert_filename, const string &cert_dir); + AuthDialog(const std::string &cert_filename, const std::string &cert_dir); #endif virtual ~AuthDialog(); @@ -64,9 +63,9 @@ public: private: #ifdef _WIN32 - void read_cert_file(const wstring &cert_filename); + void read_cert_file(const std::wstring &cert_filename); #else - void read_cert_file(const string &cert_filename); + void read_cert_file(const std::string &cert_filename); #endif void get_friendly_name(); void verify_cert(); @@ -81,9 +80,9 @@ public: private: #ifdef _WIN32 - wstring _cert_dir; + std::wstring _cert_dir; #else - string _cert_dir; + std::string _cert_dir; #endif X509 *_cert; STACK_OF(X509) *_stack; @@ -92,7 +91,7 @@ private: char _text[1024]; char _text_clean[2048]; - string _friendly_name; + std::string _friendly_name; int _verify_result; }; diff --git a/direct/src/plugin/p3dCert_wx.cxx b/direct/src/plugin/p3dCert_wx.cxx index ae373bb5ba..125732adda 100644 --- a/direct/src/plugin/p3dCert_wx.cxx +++ b/direct/src/plugin/p3dCert_wx.cxx @@ -20,6 +20,8 @@ #include "ca_bundle_data_src.c" +using std::cerr; + static const wxString self_signed_cert_text = _T("This Panda3D application uses a self-signed certificate. ") @@ -132,18 +134,18 @@ END_EVENT_TABLE() * */ AuthDialog:: -AuthDialog(const string &cert_filename, const string &cert_dir) : +AuthDialog(const std::string &cert_filename, const std::string &cert_dir) : // I hate stay-on-top dialogs, but if we don't set this flag, it doesn't // come to the foreground on OSX, and might be lost behind the browser // window. - wxDialog(NULL, wxID_ANY, _T("New Panda3D Application"), wxDefaultPosition, + wxDialog(nullptr, wxID_ANY, _T("New Panda3D Application"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxSTAY_ON_TOP), _cert_dir(cert_dir) { - _view_cert_dialog = NULL; + _view_cert_dialog = nullptr; - _cert = NULL; - _stack = NULL; + _cert = nullptr; + _stack = nullptr; _verify_result = -1; read_cert_file(cert_filename); @@ -157,17 +159,17 @@ AuthDialog(const string &cert_filename, const string &cert_dir) : */ AuthDialog:: ~AuthDialog() { - if (_view_cert_dialog != NULL) { + if (_view_cert_dialog != nullptr) { _view_cert_dialog->Destroy(); } - if (_cert != NULL) { + if (_cert != nullptr) { X509_free(_cert); - _cert = NULL; + _cert = nullptr; } - if (_stack != NULL) { + if (_stack != nullptr) { sk_X509_free(_stack); - _stack = NULL; + _stack = nullptr; } } @@ -184,7 +186,7 @@ run_clicked(wxCommandEvent &event) { */ void AuthDialog:: view_cert_clicked(wxCommandEvent &event) { - if (_view_cert_dialog != NULL) { + if (_view_cert_dialog != nullptr) { _view_cert_dialog->Destroy(); } Hide(); @@ -206,7 +208,7 @@ cancel_clicked(wxCommandEvent &event) { */ void AuthDialog:: approve_cert() { - assert(_cert != NULL); + assert(_cert != nullptr); // Make sure the directory exists. mkdir_complete(_cert_dir, cerr); @@ -216,7 +218,7 @@ approve_cert() { size_t buf_length = _cert_dir.length() + 100; char *buf = new char[buf_length]; #ifdef _WIN32 - wstring buf_w; + std::wstring buf_w; #endif // _WIN32 while (true) { @@ -243,13 +245,13 @@ approve_cert() { // Sure, there's a slight race condition right now: another process might // attempt to create the same filename. So what. - FILE *fp = NULL; + FILE *fp = nullptr; #ifdef _WIN32 fp = _wfopen(buf_w.c_str(), L"w"); #else // _WIN32 fp = fopen(buf, "w"); #endif // _WIN32 - if (fp != NULL) { + if (fp != nullptr) { PEM_write_X509(fp, _cert); fclose(fp); } @@ -262,10 +264,10 @@ approve_cert() { * line into _cert and _stack. */ void AuthDialog:: -read_cert_file(const string &cert_filename) { - FILE *fp = NULL; +read_cert_file(const std::string &cert_filename) { + FILE *fp = nullptr; #ifdef _WIN32 - wstring cert_filename_w; + std::wstring cert_filename_w; if (string_to_wstring(cert_filename_w, cert_filename)) { fp = _wfopen(cert_filename_w.c_str(), L"r"); } @@ -273,23 +275,23 @@ read_cert_file(const string &cert_filename) { fp = fopen(cert_filename.c_str(), "r"); #endif // _WIN32 - if (fp == NULL) { + if (fp == nullptr) { cerr << "Couldn't read " << cert_filename << "\n"; return; } - _cert = PEM_read_X509(fp, NULL, NULL, (void *)""); - if (_cert == NULL) { + _cert = PEM_read_X509(fp, nullptr, nullptr, (void *)""); + if (_cert == nullptr) { cerr << "Could not read certificate in " << cert_filename << ".\n"; fclose(fp); return; } // Build up a STACK of the remaining certificates in the file. - _stack = sk_X509_new(NULL); - X509 *c = PEM_read_X509(fp, NULL, NULL, (void *)""); - while (c != NULL) { + _stack = sk_X509_new(nullptr); + X509 *c = PEM_read_X509(fp, nullptr, nullptr, (void *)""); + while (c != nullptr) { sk_X509_push(_stack, c); - c = PEM_read_X509(fp, NULL, NULL, (void *)""); + c = PEM_read_X509(fp, nullptr, nullptr, (void *)""); } fclose(fp); @@ -301,7 +303,7 @@ read_cert_file(const string &cert_filename) { */ void AuthDialog:: get_friendly_name() { - if (_cert == NULL) { + if (_cert == nullptr) { _friendly_name.clear(); return; } @@ -319,15 +321,15 @@ get_friendly_name() { // A complex OpenSSL interface to extract out the name in utf-8. X509_NAME *xname = X509_get_subject_name(_cert); - if (xname != NULL) { + if (xname != nullptr) { int pos = X509_NAME_get_index_by_NID(xname, nid, -1); if (pos != -1) { // We just get the first common name. I guess it's possible to have // more than one; not sure what that means in this context. X509_NAME_ENTRY *xentry = X509_NAME_get_entry(xname, pos); - if (xentry != NULL) { + if (xentry != nullptr) { ASN1_STRING *data = X509_NAME_ENTRY_get_data(xentry); - if (data != NULL) { + if (data != nullptr) { // We use "print" to dump the output to a memory BIO. Is there an // easier way to decode the ASN1_STRING? Curse these incomplete // docs. @@ -352,7 +354,7 @@ get_friendly_name() { */ void AuthDialog:: verify_cert() { - if (_cert == NULL) { + if (_cert == nullptr) { _verify_result = -1; return; } @@ -407,11 +409,11 @@ load_certificates_from_der_ram(X509_STORE *store, bp = (unsigned char *)data; bp_end = bp + data_size; - X509 *x509 = d2i_X509(NULL, &bp, bp_end - bp); - while (x509 != NULL) { + X509 *x509 = d2i_X509(nullptr, &bp, bp_end - bp); + while (x509 != nullptr) { X509_STORE_add_cert(store, x509); ++count; - x509 = d2i_X509(NULL, &bp, bp_end - bp); + x509 = d2i_X509(nullptr, &bp, bp_end - bp); } return count; @@ -449,12 +451,12 @@ layout() { // Create the run cancel buttons. wxBoxSizer *bsizer = new wxBoxSizer(wxHORIZONTAL); - if (_verify_result == 0 && _cert != NULL) { + if (_verify_result == 0 && _cert != nullptr) { wxButton *run_button = new wxButton(panel, wxID_OK, _T("Run")); bsizer->Add(run_button, 0, wxALIGN_CENTER | wxALL, 5); } - if (_cert != NULL) { + if (_cert != nullptr) { wxButton *view_button = new wxButton(panel, VIEW_CERT_BUTTON, _T("View Certificate")); bsizer->Add(view_button, 0, wxALIGN_CENTER | wxALL, 5); } @@ -522,7 +524,7 @@ END_EVENT_TABLE() */ ViewCertDialog:: ViewCertDialog(AuthDialog *auth_dialog, X509 *cert) : -wxDialog(NULL, wxID_ANY, _T("View Certificate"), wxDefaultPosition, +wxDialog(nullptr, wxID_ANY, _T("View Certificate"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER), _auth_dialog(auth_dialog), _cert(cert) @@ -535,8 +537,8 @@ wxDialog(NULL, wxID_ANY, _T("View Certificate"), wxDefaultPosition, */ ViewCertDialog:: ~ViewCertDialog() { - if (_auth_dialog != NULL) { - _auth_dialog->_view_cert_dialog = NULL; + if (_auth_dialog != nullptr) { + _auth_dialog->_view_cert_dialog = nullptr; } } @@ -545,7 +547,7 @@ ViewCertDialog:: */ void ViewCertDialog:: run_clicked(wxCommandEvent &event) { - if (_auth_dialog != NULL){ + if (_auth_dialog != nullptr){ _auth_dialog->approve_cert(); } Destroy(); @@ -556,7 +558,7 @@ run_clicked(wxCommandEvent &event) { */ void ViewCertDialog:: cancel_clicked(wxCommandEvent &event) { - if (_auth_dialog != NULL){ + if (_auth_dialog != nullptr){ _auth_dialog->Destroy(); } Destroy(); @@ -568,7 +570,7 @@ cancel_clicked(wxCommandEvent &event) { void ViewCertDialog:: layout() { // Format the certificate text for display in the dialog. - assert(_cert != NULL); + assert(_cert != nullptr); BIO *mbio = BIO_new(BIO_s_mem()); X509_print(mbio, _cert); @@ -612,5 +614,5 @@ layout() { // Make sure the resulting window is at least a certain size. int width, height; GetSize(&width, &height); - SetSize(max(width, 600), max(height, 400)); + SetSize(std::max(width, 600), std::max(height, 400)); } diff --git a/direct/src/plugin/p3dCert_wx.h b/direct/src/plugin/p3dCert_wx.h index 05f0053b74..1ea8765a17 100644 --- a/direct/src/plugin/p3dCert_wx.h +++ b/direct/src/plugin/p3dCert_wx.h @@ -24,7 +24,6 @@ #include #include #include -using namespace std; class ViewCertDialog; @@ -48,8 +47,8 @@ public: virtual bool OnCmdLineParsed(wxCmdLineParser &parser); private: - string _cert_filename; - string _cert_dir; + std::string _cert_filename; + std::string _cert_dir; }; /** @@ -62,7 +61,7 @@ private: */ class AuthDialog : public wxDialog { public: - AuthDialog(const string &cert_filename, const string &cert_dir); + AuthDialog(const std::string &cert_filename, const std::string &cert_dir); virtual ~AuthDialog(); void run_clicked(wxCommandEvent &event); @@ -72,7 +71,7 @@ public: void approve_cert(); private: - void read_cert_file(const string &cert_filename); + void read_cert_file(const std::string &cert_filename); void get_friendly_name(); void verify_cert(); int load_certificates_from_der_ram(X509_STORE *store, @@ -88,7 +87,7 @@ private: // any class wishing to process wxWidgets events must use this macro DECLARE_EVENT_TABLE() - string _cert_dir; + std::string _cert_dir; X509 *_cert; STACK_OF(X509) *_stack; diff --git a/direct/src/plugin/p3dConcreteSequence.cxx b/direct/src/plugin/p3dConcreteSequence.cxx index 946afd05cd..ec4291cb7b 100644 --- a/direct/src/plugin/p3dConcreteSequence.cxx +++ b/direct/src/plugin/p3dConcreteSequence.cxx @@ -62,8 +62,8 @@ get_bool() { * to a string. */ void P3DConcreteSequence:: -make_string(string &value) { - ostringstream strm; +make_string(std::string &value) { + std::ostringstream strm; strm << "["; if (!_elements.empty()) { strm << *_elements[0]; @@ -81,12 +81,12 @@ make_string(string &value) { * new-reference P3D_object, or NULL on error. */ P3D_object *P3DConcreteSequence:: -get_property(const string &property) { +get_property(const std::string &property) { // We only understand integer "property" names. char *endptr; int index = strtoul(property.c_str(), &endptr, 10); if (*endptr != '\0') { - return NULL; + return nullptr; } return get_element(index); @@ -97,7 +97,7 @@ get_property(const string &property) { * object. Returns true on success, false on failure. */ bool P3DConcreteSequence:: -set_property(const string &property, P3D_object *value) { +set_property(const std::string &property, P3D_object *value) { // We only understand integer "property" names. char *endptr; int index = strtoul(property.c_str(), &endptr, 10); @@ -133,7 +133,7 @@ fill_xml(TiXmlElement *xvalue, P3DSession *session) { P3D_object **P3DConcreteSequence:: get_object_array() { if (_elements.empty()) { - return NULL; + return nullptr; } return &_elements[0]; } @@ -165,7 +165,7 @@ get_element(int n) const { return _elements[n]; } - return NULL; + return nullptr; } /** @@ -174,7 +174,7 @@ get_element(int n) const { */ bool P3DConcreteSequence:: set_element(int n, P3D_object *value) { - if (value == NULL) { + if (value == nullptr) { // Delete an element. if (n < 0 || n >= (int)_elements.size()) { // Invalid index. diff --git a/direct/src/plugin/p3dConcreteSequence.h b/direct/src/plugin/p3dConcreteSequence.h index e77b08b823..09b489c5ba 100644 --- a/direct/src/plugin/p3dConcreteSequence.h +++ b/direct/src/plugin/p3dConcreteSequence.h @@ -34,10 +34,10 @@ public: virtual P3D_object_type get_type(); virtual bool get_bool(); - virtual void make_string(string &value); + virtual void make_string(std::string &value); - virtual P3D_object *get_property(const string &property); - virtual bool set_property(const string &property, P3D_object *value); + virtual P3D_object *get_property(const std::string &property); + virtual bool set_property(const std::string &property, P3D_object *value); virtual bool fill_xml(TiXmlElement *xvalue, P3DSession *session); virtual P3D_object **get_object_array(); @@ -49,7 +49,7 @@ public: void append(P3D_object *value); private: - typedef vector Elements; + typedef std::vector Elements; Elements _elements; }; diff --git a/direct/src/plugin/p3dConcreteStruct.cxx b/direct/src/plugin/p3dConcreteStruct.cxx index f85119cd2d..fa9917d955 100644 --- a/direct/src/plugin/p3dConcreteStruct.cxx +++ b/direct/src/plugin/p3dConcreteStruct.cxx @@ -13,6 +13,8 @@ #include "p3dConcreteStruct.h" +using std::string; + /** * */ @@ -53,7 +55,7 @@ get_bool() { */ void P3DConcreteStruct:: make_string(string &value) { - ostringstream strm; + std::ostringstream strm; strm << "{"; if (!_elements.empty()) { Elements::iterator ei; @@ -82,7 +84,7 @@ get_property(const string &property) { return (*ei).second; } - return NULL; + return nullptr; } /** @@ -91,7 +93,7 @@ get_property(const string &property) { */ bool P3DConcreteStruct:: set_property(const string &property, P3D_object *value) { - if (value == NULL) { + if (value == nullptr) { // Delete an element. Elements::iterator ei = _elements.find(property); if (ei == _elements.end()) { @@ -105,7 +107,7 @@ set_property(const string &property, P3D_object *value) { } else { // Replace or insert an element. P3D_OBJECT_INCREF(value); - pair result = _elements.insert(Elements::value_type(property, value)); + std::pair result = _elements.insert(Elements::value_type(property, value)); if (!result.second) { // Replacing an element. Elements::iterator ei = result.first; @@ -139,7 +141,7 @@ has_method(const string &method_name) { P3D_object *P3DConcreteStruct:: call(const string &method_name, bool needs_response, P3D_object *params[], int num_params) { - P3D_object *result = NULL; + P3D_object *result = nullptr; if (method_name == "toString") { string value; @@ -147,9 +149,9 @@ call(const string &method_name, bool needs_response, result = P3D_new_string_object(value.data(), value.length()); } - if (result != NULL && !needs_response) { + if (result != nullptr && !needs_response) { P3D_OBJECT_DECREF(result); - result = NULL; + result = nullptr; } return result; diff --git a/direct/src/plugin/p3dConcreteStruct.h b/direct/src/plugin/p3dConcreteStruct.h index 565bb35ae3..cccd35bbeb 100644 --- a/direct/src/plugin/p3dConcreteStruct.h +++ b/direct/src/plugin/p3dConcreteStruct.h @@ -32,19 +32,19 @@ public: virtual P3D_object_type get_type(); virtual bool get_bool(); - virtual void make_string(string &value); + virtual void make_string(std::string &value); - virtual P3D_object *get_property(const string &property); - virtual bool set_property(const string &property, P3D_object *value); + virtual P3D_object *get_property(const std::string &property); + virtual bool set_property(const std::string &property, P3D_object *value); - virtual bool has_method(const string &method_name); - virtual P3D_object *call(const string &method_name, bool needs_response, + virtual bool has_method(const std::string &method_name); + virtual P3D_object *call(const std::string &method_name, bool needs_response, P3D_object *params[], int num_params); virtual bool fill_xml(TiXmlElement *xvalue, P3DSession *session); private: - typedef map Elements; + typedef std::map Elements; Elements _elements; }; diff --git a/direct/src/plugin/p3dConditionVar.cxx b/direct/src/plugin/p3dConditionVar.cxx index 341e8be905..22133c0781 100644 --- a/direct/src/plugin/p3dConditionVar.cxx +++ b/direct/src/plugin/p3dConditionVar.cxx @@ -28,7 +28,7 @@ P3DConditionVar() { InitializeCriticalSection(&_lock); // Create an auto-reset event. - _event_signal = CreateEvent(NULL, false, false, NULL); + _event_signal = CreateEvent(nullptr, false, false, nullptr); #else // _WIN32 pthread_mutexattr_t attr; @@ -38,7 +38,7 @@ P3DConditionVar() { pthread_mutexattr_destroy(&attr); assert(result == 0); - result = pthread_cond_init(&_cvar, NULL); + result = pthread_cond_init(&_cvar, nullptr); assert(result == 0); #endif // _WIN32 @@ -115,7 +115,7 @@ wait(double timeout) { #else // _WIN32 struct timeval now; - gettimeofday(&now, NULL); + gettimeofday(&now, nullptr); // Convert from timeval to timespec struct timespec ts; diff --git a/direct/src/plugin/p3dDownload.I b/direct/src/plugin/p3dDownload.I index e32370669c..c248948612 100644 --- a/direct/src/plugin/p3dDownload.I +++ b/direct/src/plugin/p3dDownload.I @@ -14,7 +14,7 @@ /** * Returns the URL that we are querying. */ -const string &P3DDownload:: +const std::string &P3DDownload:: get_url() const { return _url; } diff --git a/direct/src/plugin/p3dDownload.cxx b/direct/src/plugin/p3dDownload.cxx index 9b1af6ba7d..3b6a6cca7a 100644 --- a/direct/src/plugin/p3dDownload.cxx +++ b/direct/src/plugin/p3dDownload.cxx @@ -27,7 +27,7 @@ P3DDownload() { _canceled = false; _download_id = 0; - _instance = NULL; + _instance = nullptr; } /** @@ -46,7 +46,7 @@ P3DDownload(const P3DDownload ©) : _canceled = false; _download_id = 0; - _instance = NULL; + _instance = nullptr; } /** @@ -60,7 +60,7 @@ P3DDownload:: * Supplies the source URL for the download. */ void P3DDownload:: -set_url(const string &url) { +set_url(const std::string &url) { _url = url; } @@ -119,7 +119,7 @@ feed_url_stream(P3D_result_code result_code, _total_data += this_data_size; } - total_expected_data = max(total_expected_data, _total_data); + total_expected_data = std::max(total_expected_data, _total_data); if (total_expected_data > _total_expected_data) { // If the expected data grows during the download, we don't really know // how much we're getting. @@ -162,7 +162,7 @@ receive_data(const unsigned char *this_data, size_t this_data_size) { */ void P3DDownload:: download_progress() { - time_t now = time(NULL); + time_t now = time(nullptr); if (now - _last_reported_time > 10) { _last_reported_time = now; nout << "Downloading " << get_url() << ": "; diff --git a/direct/src/plugin/p3dDownload.h b/direct/src/plugin/p3dDownload.h index e36d5b19c5..ad2cd872a5 100644 --- a/direct/src/plugin/p3dDownload.h +++ b/direct/src/plugin/p3dDownload.h @@ -32,8 +32,8 @@ public: P3DDownload(const P3DDownload ©); virtual ~P3DDownload(); - void set_url(const string &url); - inline const string &get_url() const; + void set_url(const std::string &url); + inline const std::string &get_url() const; inline void set_instance(P3DInstance *instance); inline P3DInstance *get_instance() const; @@ -78,7 +78,7 @@ protected: private: bool _canceled; int _download_id; - string _url; + std::string _url; P3DInstance *_instance; }; diff --git a/direct/src/plugin/p3dFileDownload.I b/direct/src/plugin/p3dFileDownload.I index 187db8945d..af4e2b1ec8 100644 --- a/direct/src/plugin/p3dFileDownload.I +++ b/direct/src/plugin/p3dFileDownload.I @@ -14,7 +14,7 @@ /** * Returns the filename that we are downloading into. */ -const string &P3DFileDownload:: +const std::string &P3DFileDownload:: get_filename() const { return _filename; } diff --git a/direct/src/plugin/p3dFileDownload.cxx b/direct/src/plugin/p3dFileDownload.cxx index 2d1a85497e..a978c3640e 100644 --- a/direct/src/plugin/p3dFileDownload.cxx +++ b/direct/src/plugin/p3dFileDownload.cxx @@ -38,7 +38,7 @@ P3DFileDownload(const P3DFileDownload ©) : * success, false on failure. */ bool P3DFileDownload:: -set_filename(const string &filename) { +set_filename(const std::string &filename) { _filename = filename; return open_file(); @@ -57,12 +57,12 @@ open_file() { _file.clear(); #ifdef _WIN32 - wstring filename_w; + std::wstring filename_w; if (string_to_wstring(filename_w, _filename)) { - _file.open(filename_w.c_str(), ios::out | ios::trunc | ios::binary); + _file.open(filename_w.c_str(), std::ios::out | std::ios::trunc | std::ios::binary); } #else // _WIN32 - _file.open(_filename.c_str(), ios::out | ios::trunc | ios::binary); + _file.open(_filename.c_str(), std::ios::out | std::ios::trunc | std::ios::binary); #endif // _WIN32 if (!_file) { nout << "Failed to open " << _filename << " in write mode\n"; diff --git a/direct/src/plugin/p3dFileDownload.h b/direct/src/plugin/p3dFileDownload.h index f256706ac6..923f8ec0ec 100644 --- a/direct/src/plugin/p3dFileDownload.h +++ b/direct/src/plugin/p3dFileDownload.h @@ -28,8 +28,8 @@ public: P3DFileDownload(); P3DFileDownload(const P3DFileDownload ©); - bool set_filename(const string &filename); - inline const string &get_filename() const; + bool set_filename(const std::string &filename); + inline const std::string &get_filename() const; protected: virtual bool open_file(); @@ -42,7 +42,7 @@ protected: ofstream _file; private: - string _filename; + std::string _filename; }; #include "p3dFileDownload.I" diff --git a/direct/src/plugin/p3dFileParams.I b/direct/src/plugin/p3dFileParams.I index e7eb45788d..8565c47a90 100644 --- a/direct/src/plugin/p3dFileParams.I +++ b/direct/src/plugin/p3dFileParams.I @@ -14,7 +14,7 @@ /** * Returns the filename that was passed to set_p3d_filename(). */ -inline const string &P3DFileParams:: +inline const std::string &P3DFileParams:: get_p3d_filename() const { return _p3d_filename; } @@ -31,7 +31,7 @@ get_p3d_offset() const { /** * Returns the string that was passed to set_p3d_url(). */ -inline const string &P3DFileParams:: +inline const std::string &P3DFileParams:: get_p3d_url() const { return _p3d_url; } @@ -47,7 +47,7 @@ get_num_tokens() const { /** * Returns the keyword of the nth token. */ -inline const string &P3DFileParams:: +inline const std::string &P3DFileParams:: get_token_keyword(int n) const { assert(n >= 0 && n < (int)_tokens.size()); return _tokens[n]._keyword; @@ -56,7 +56,7 @@ get_token_keyword(int n) const { /** * Returns the value of the nth token. */ -inline const string &P3DFileParams:: +inline const std::string &P3DFileParams:: get_token_value(int n) const { assert(n >= 0 && n < (int)_tokens.size()); return _tokens[n]._value; diff --git a/direct/src/plugin/p3dFileParams.cxx b/direct/src/plugin/p3dFileParams.cxx index 128520d993..a32ede4b95 100644 --- a/direct/src/plugin/p3dFileParams.cxx +++ b/direct/src/plugin/p3dFileParams.cxx @@ -14,6 +14,8 @@ #include "p3dFileParams.h" #include +using std::string; + /** * */ @@ -90,13 +92,13 @@ set_tokens(const P3D_token tokens[], size_t num_tokens) { void P3DFileParams:: set_token(const char *keyword, const char *value) { Token token; - if (keyword != NULL) { + if (keyword != nullptr) { // Make the token lowercase, since HTML is case-insensitive but we're not. for (const char *p = keyword; *p; ++p) { token._keyword += tolower(*p); } } - if (value != NULL) { + if (value != nullptr) { token._value = value; } _tokens.push_back(token); @@ -111,7 +113,7 @@ set_args(int argc, const char *argv[]) { for (int i = 0; i < argc; ++i) { const char *arg = argv[i]; - if (arg == NULL) { + if (arg == nullptr) { arg = ""; } _args.push_back(arg); diff --git a/direct/src/plugin/p3dFileParams.h b/direct/src/plugin/p3dFileParams.h index 1cb54d1b3a..53b2630680 100644 --- a/direct/src/plugin/p3dFileParams.h +++ b/direct/src/plugin/p3dFileParams.h @@ -27,38 +27,38 @@ public: P3DFileParams(const P3DFileParams ©); void operator = (const P3DFileParams &other); - void set_p3d_filename(const string &p3d_filename); + void set_p3d_filename(const std::string &p3d_filename); void set_p3d_offset(const int &p3d_offset); - void set_p3d_url(const string &p3d_url); + void set_p3d_url(const std::string &p3d_url); void set_tokens(const P3D_token tokens[], size_t num_tokens); void set_token(const char *keyword, const char *value); void set_args(int argc, const char *argv[]); - inline const string &get_p3d_filename() const; + inline const std::string &get_p3d_filename() const; inline int get_p3d_offset() const; - inline const string &get_p3d_url() const; - string lookup_token(const string &keyword) const; - int lookup_token_int(const string &keyword) const; - bool has_token(const string &keyword) const; + inline const std::string &get_p3d_url() const; + std::string lookup_token(const std::string &keyword) const; + int lookup_token_int(const std::string &keyword) const; + bool has_token(const std::string &keyword) const; inline int get_num_tokens() const; - inline const string &get_token_keyword(int n) const; - inline const string &get_token_value(int n) const; + inline const std::string &get_token_keyword(int n) const; + inline const std::string &get_token_value(int n) const; TiXmlElement *make_xml(); private: class Token { public: - string _keyword; - string _value; + std::string _keyword; + std::string _value; }; - typedef vector Tokens; - typedef vector Args; + typedef std::vector Tokens; + typedef std::vector Args; - string _p3d_filename; + std::string _p3d_filename; int _p3d_offset; - string _p3d_url; + std::string _p3d_url; Tokens _tokens; Args _args; }; diff --git a/direct/src/plugin/p3dFloatObject.cxx b/direct/src/plugin/p3dFloatObject.cxx index 2581c44282..3262d45a54 100644 --- a/direct/src/plugin/p3dFloatObject.cxx +++ b/direct/src/plugin/p3dFloatObject.cxx @@ -67,8 +67,8 @@ get_float() { * to a string. */ void P3DFloatObject:: -make_string(string &value) { - ostringstream strm; +make_string(std::string &value) { + std::ostringstream strm; strm << _value; value = strm.str(); } diff --git a/direct/src/plugin/p3dFloatObject.h b/direct/src/plugin/p3dFloatObject.h index 1fbb79251b..13f7ba8358 100644 --- a/direct/src/plugin/p3dFloatObject.h +++ b/direct/src/plugin/p3dFloatObject.h @@ -30,7 +30,7 @@ public: virtual bool get_bool(); virtual int get_int(); virtual double get_float(); - virtual void make_string(string &value); + virtual void make_string(std::string &value); private: double _value; diff --git a/direct/src/plugin/p3dHost.I b/direct/src/plugin/p3dHost.I index f7e4640b66..9fb3672205 100644 --- a/direct/src/plugin/p3dHost.I +++ b/direct/src/plugin/p3dHost.I @@ -26,7 +26,7 @@ has_host_dir() const { * bootstrapped; if there is some danger of calling this early in the * initialization process, you should check has_host_dir() first. */ -inline const string &P3DHost:: +inline const std::string &P3DHost:: get_host_dir() const { assert(has_host_dir()); return _host_dir; @@ -36,7 +36,7 @@ get_host_dir() const { * Returns the root URL of this particular host, as passed from the package * file. This is a unique string that identifies each host. */ -inline const string &P3DHost:: +inline const std::string &P3DHost:: get_host_url() const { return _host_url; } @@ -48,7 +48,7 @@ get_host_url() const { * * Also see get_download_url_prefix(). */ -inline const string &P3DHost:: +inline const std::string &P3DHost:: get_host_url_prefix() const { return _host_url_prefix; } @@ -58,7 +58,7 @@ get_host_url_prefix() const { * the contents.xml file. This is often the same as get_host_url_prefix(), * but it may be different in the case of an https server for contents.xml. */ -inline const string &P3DHost:: +inline const std::string &P3DHost:: get_download_url_prefix() const { return _download_url_prefix; } @@ -68,7 +68,7 @@ get_download_url_prefix() const { * url if no descriptive name is provided. This will be available after * read_contents_file() has been called. */ -inline const string &P3DHost:: +inline const std::string &P3DHost:: get_descriptive_name() const { return _descriptive_name; } @@ -79,7 +79,7 @@ get_descriptive_name() const { */ inline bool P3DHost:: has_contents_file() const { - return (_xcontents != NULL); + return (_xcontents != nullptr); } /** @@ -101,6 +101,6 @@ get_contents_iseq() const { * contents.xml file (as provided by the server), false otherwise. */ inline bool P3DHost:: -check_contents_hash(const string &pathname) const { +check_contents_hash(const std::string &pathname) const { return _contents_spec.check_hash(pathname); } diff --git a/direct/src/plugin/p3dHost.cxx b/direct/src/plugin/p3dHost.cxx index 054dbe6166..991a66df3e 100644 --- a/direct/src/plugin/p3dHost.cxx +++ b/direct/src/plugin/p3dHost.cxx @@ -25,6 +25,11 @@ #include #endif +using std::ios; +using std::ostringstream; +using std::string; +using std::wstring; + /** * Use P3DInstanceManager::get_host() to construct a new P3DHost. */ @@ -42,7 +47,7 @@ P3DHost(const string &host_url, const string &host_dir) : _descriptive_name = _host_url; - _xcontents = NULL; + _xcontents = nullptr; _contents_expiration = 0; _contents_iseq = 0; } @@ -52,7 +57,7 @@ P3DHost(const string &host_url, const string &host_dir) : */ P3DHost:: ~P3DHost() { - if (_xcontents != NULL) { + if (_xcontents != nullptr) { delete _xcontents; } @@ -94,7 +99,7 @@ P3DHost:: */ P3DHost *P3DHost:: get_alt_host(const string &alt_host) { - assert(_xcontents != NULL); + assert(_xcontents != nullptr); AltHosts::iterator hi; hi = _alt_hosts.find(alt_host); @@ -118,8 +123,8 @@ has_current_contents_file(P3DInstanceManager *inst_mgr) const { return has_contents_file(); } - time_t now = time(NULL); - return now < _contents_expiration && (_xcontents != NULL); + time_t now = time(nullptr); + return now < _contents_expiration && (_xcontents != nullptr); } /** @@ -153,11 +158,11 @@ read_contents_file(const string &contents_filename, bool fresh_download) { } TiXmlElement *xcontents = doc.FirstChildElement("contents"); - if (xcontents == NULL) { + if (xcontents == nullptr) { return false; } - if (_xcontents != NULL) { + if (_xcontents != nullptr) { delete _xcontents; } _xcontents = (TiXmlElement *)xcontents->Clone(); @@ -169,7 +174,7 @@ read_contents_file(const string &contents_filename, bool fresh_download) { // Get the latest possible expiration time, based on the max_age indication. // Any expiration time later than this is in error. - time_t now = time(NULL); + time_t now = time(nullptr); _contents_expiration = now + (time_t)max_age; if (fresh_download) { @@ -177,7 +182,7 @@ read_contents_file(const string &contents_filename, bool fresh_download) { // Update the XML with the new download information. TiXmlElement *xorig = xcontents->FirstChildElement("orig"); - while (xorig != NULL) { + while (xorig != nullptr) { xcontents->RemoveChild(xorig); xorig = xcontents->FirstChildElement("orig"); } @@ -192,7 +197,7 @@ read_contents_file(const string &contents_filename, bool fresh_download) { // Read the download hash and expiration time from the XML. int expiration = 0; TiXmlElement *xorig = xcontents->FirstChildElement("orig"); - if (xorig != NULL) { + if (xorig != nullptr) { _contents_spec.load_xml(xorig); xorig->Attribute("expiration", &expiration); } @@ -200,26 +205,26 @@ read_contents_file(const string &contents_filename, bool fresh_download) { _contents_spec.read_hash(contents_filename); } - _contents_expiration = min(_contents_expiration, (time_t)expiration); + _contents_expiration = std::min(_contents_expiration, (time_t)expiration); } nout << "read contents.xml, max_age = " << max_age - << ", expires in " << max(_contents_expiration, now) - now + << ", expires in " << std::max(_contents_expiration, now) - now << " s\n"; TiXmlElement *xhost = _xcontents->FirstChildElement("host"); - if (xhost != NULL) { + if (xhost != nullptr) { const char *url = xhost->Attribute("url"); - if (url != NULL && _host_url == string(url)) { + if (url != nullptr && _host_url == string(url)) { // We're the primary host. This is the normal case. read_xhost(xhost); // Build up the list of alternate hosts. TiXmlElement *xalthost = xhost->FirstChildElement("alt_host"); - while (xalthost != NULL) { + while (xalthost != nullptr) { const char *keyword = xalthost->Attribute("keyword"); const char *url = xalthost->Attribute("url"); - if (keyword != NULL && url != NULL) { + if (keyword != nullptr && url != nullptr) { _alt_hosts[keyword] = url; } xalthost = xalthost->NextSiblingElement("alt_host"); @@ -228,9 +233,9 @@ read_contents_file(const string &contents_filename, bool fresh_download) { } else { // We're not the primary host; perhaps we're an alternate host. TiXmlElement *xalthost = xhost->FirstChildElement("alt_host"); - while (xalthost != NULL) { + while (xalthost != nullptr) { const char *url = xalthost->Attribute("url"); - if (url != NULL && _host_url == string(url)) { + if (url != nullptr && _host_url == string(url)) { // Yep, we're this alternate host. read_xhost(xalthost); break; @@ -288,12 +293,12 @@ read_contents_file(const string &contents_filename, bool fresh_download) { void P3DHost:: read_xhost(TiXmlElement *xhost) { const char *descriptive_name = xhost->Attribute("descriptive_name"); - if (descriptive_name != NULL && _descriptive_name.empty()) { + if (descriptive_name != nullptr && _descriptive_name.empty()) { _descriptive_name = descriptive_name; } const char *host_dir_basename = xhost->Attribute("host_dir"); - if (host_dir_basename == NULL) { + if (host_dir_basename == nullptr) { host_dir_basename = ""; } if (_host_dir.empty()) { @@ -303,7 +308,7 @@ read_xhost(TiXmlElement *xhost) { // Get the "download" URL, which is the source from which we download // everything other than the contents.xml file. const char *download_url = xhost->Attribute("download_url"); - if (download_url != NULL) { + if (download_url != nullptr) { _download_url_prefix = download_url; } if (!_download_url_prefix.empty()) { @@ -315,9 +320,9 @@ read_xhost(TiXmlElement *xhost) { } TiXmlElement *xmirror = xhost->FirstChildElement("mirror"); - while (xmirror != NULL) { + while (xmirror != nullptr) { const char *url = xmirror->Attribute("url"); - if (url != NULL) { + if (url != nullptr) { add_mirror(url); } xmirror = xmirror->NextSiblingElement("mirror"); @@ -338,7 +343,7 @@ get_package(const string &package_name, const string &package_version, const string &package_platform, const string &package_seq, const string &alt_host) { if (!alt_host.empty()) { - if (_xcontents != NULL) { + if (_xcontents != nullptr) { // If we're asking for an alt host and we've already read our // contents.xml file, then we already know all of our hosts, and we can // start the package off with the correct host immediately. @@ -355,7 +360,7 @@ get_package(const string &package_name, const string &package_version, string key = package_name + "_" + package_version; PlatformPackages &ppackages = _packages[alt_host][key]; PlatformPackages::iterator ppi; - P3DPackage *package = NULL; + P3DPackage *package = nullptr; // First, look for an exact match of the platform. for (ppi = ppackages.begin(); ppi != ppackages.end(); ++ppi) { @@ -366,7 +371,7 @@ get_package(const string &package_name, const string &package_version, } // If an exact match isn't found, look for a generic platform. - if (package == NULL) { + if (package == nullptr) { for (ppi = ppackages.begin(); ppi != ppackages.end(); ++ppi) { if ((*ppi)->get_package_platform().empty()) { package = *ppi; @@ -375,18 +380,18 @@ get_package(const string &package_name, const string &package_version, } } - if (package != NULL) { + if (package != nullptr) { if (package->get_failed()) { // If the package has previously failed, move it aside and try again // (maybe it just failed because the user interrupted it). nout << "Package " << key << " has previously failed; trying again.\n"; _failed_packages.push_back(package); ppackages.erase(ppi); - package = NULL; + package = nullptr; } } - if (package == NULL) { + if (package == nullptr) { package = new P3DPackage(this, package_name, package_version, package_platform, alt_host); ppackages.push_back(package); @@ -428,7 +433,7 @@ choose_suitable_platform(string &selected_platform, const string &package_name, const string &package_version, const string &package_platform) { - if (_xcontents == NULL) { + if (_xcontents == nullptr) { return false; } @@ -443,17 +448,17 @@ choose_suitable_platform(string &selected_platform, for (int pi = 0; pi < num_supported_platforms; ++pi) { string supported_platform = inst_mgr->get_supported_platform(pi); xpackage = _xcontents->FirstChildElement("package"); - while (xpackage != NULL) { + while (xpackage != nullptr) { const char *name = xpackage->Attribute("name"); const char *platform = xpackage->Attribute("platform"); const char *version = xpackage->Attribute("version"); - if (platform == NULL) { + if (platform == nullptr) { platform = ""; } - if (version == NULL) { + if (version == nullptr) { version = ""; } - if (name != NULL && + if (name != nullptr && package_name == name && supported_platform == platform && package_version == version) { @@ -470,17 +475,17 @@ choose_suitable_platform(string &selected_platform, // Now, we look for an exact match for the expected platform. xpackage = _xcontents->FirstChildElement("package"); - while (xpackage != NULL) { + while (xpackage != nullptr) { const char *name = xpackage->Attribute("name"); const char *platform = xpackage->Attribute("platform"); const char *version = xpackage->Attribute("version"); - if (platform == NULL) { + if (platform == nullptr) { platform = ""; } - if (version == NULL) { + if (version == nullptr) { version = ""; } - if (name != NULL && + if (name != nullptr && package_name == name && package_platform == platform && package_version == version) { @@ -496,17 +501,17 @@ choose_suitable_platform(string &selected_platform, // Look one more time, this time looking for a non-platform-specific // version. xpackage = _xcontents->FirstChildElement("package"); - while (xpackage != NULL) { + while (xpackage != nullptr) { const char *name = xpackage->Attribute("name"); const char *platform = xpackage->Attribute("platform"); const char *version = xpackage->Attribute("version"); - if (platform == NULL) { + if (platform == nullptr) { platform = ""; } - if (version == NULL) { + if (version == nullptr) { version = ""; } - if (name != NULL && + if (name != nullptr && package_name == name && *platform == '\0' && package_version == version) { @@ -535,7 +540,7 @@ get_package_desc_file(FileSpec &desc_file, // out const string &package_name, // in const string &package_version, // in const string &package_platform) { // in - if (_xcontents == NULL) { + if (_xcontents == nullptr) { return false; } @@ -545,22 +550,22 @@ get_package_desc_file(FileSpec &desc_file, // out // platform precisely, because we previously called // choose_suitable_platform(). TiXmlElement *xpackage = _xcontents->FirstChildElement("package"); - while (xpackage != NULL) { + while (xpackage != nullptr) { const char *name = xpackage->Attribute("name"); const char *platform = xpackage->Attribute("platform"); const char *version = xpackage->Attribute("version"); const char *seq = xpackage->Attribute("seq"); const char *solo = xpackage->Attribute("solo"); - if (platform == NULL) { + if (platform == nullptr) { platform = ""; } - if (version == NULL) { + if (version == nullptr) { version = ""; } - if (seq == NULL) { + if (seq == nullptr) { seq = ""; } - if (name != NULL && platform != NULL && + if (name != nullptr && platform != nullptr && package_name == name && package_platform == platform && package_version == version) { @@ -568,7 +573,7 @@ get_package_desc_file(FileSpec &desc_file, // out desc_file.load_xml(xpackage); package_seq = seq; package_solo = false; - if (solo != NULL) { + if (solo != nullptr) { package_solo = (atoi(solo) != 0); } return true; @@ -631,10 +636,10 @@ migrate_package_host(P3DPackage *package, const string &alt_host, P3DHost *new_h * elements in the list, adds only as many mirrors as we can get. */ void P3DHost:: -choose_random_mirrors(vector &result, int num_mirrors) { - vector selected; +choose_random_mirrors(std::vector &result, int num_mirrors) { + std::vector selected; - size_t num_to_select = min(_mirrors.size(), (size_t)num_mirrors); + size_t num_to_select = std::min(_mirrors.size(), (size_t)num_mirrors); while (num_to_select > 0) { size_t i = (size_t)(((double)rand() / (double)RAND_MAX) * _mirrors.size()); while (find(selected.begin(), selected.end(), i) != selected.end()) { @@ -846,7 +851,7 @@ copy_file(const string &from_filename, const string &to_filename) { char buffer[buffer_size]; in.read(buffer, buffer_size); - streamsize count = in.gcount(); + std::streamsize count = in.gcount(); while (count != 0) { out.write(buffer, count); if (out.fail()) { diff --git a/direct/src/plugin/p3dHost.h b/direct/src/plugin/p3dHost.h index adc66501c7..fd880ccde0 100644 --- a/direct/src/plugin/p3dHost.h +++ b/direct/src/plugin/p3dHost.h @@ -27,84 +27,84 @@ class P3DPackage; */ class P3DHost { private: - P3DHost(const string &host_url, const string &host_dir = ""); + P3DHost(const std::string &host_url, const std::string &host_dir = ""); ~P3DHost(); public: inline bool has_host_dir() const; - inline const string &get_host_dir() const; - inline const string &get_host_url() const; - inline const string &get_host_url_prefix() const; - inline const string &get_download_url_prefix() const; - inline const string &get_descriptive_name() const; + inline const std::string &get_host_dir() const; + inline const std::string &get_host_url() const; + inline const std::string &get_host_url_prefix() const; + inline const std::string &get_download_url_prefix() const; + inline const std::string &get_descriptive_name() const; - P3DHost *get_alt_host(const string &alt_host); + P3DHost *get_alt_host(const std::string &alt_host); inline bool has_contents_file() const; bool has_current_contents_file(P3DInstanceManager *inst_mgr) const; inline int get_contents_iseq() const; - inline bool check_contents_hash(const string &pathname) const; + inline bool check_contents_hash(const std::string &pathname) const; bool read_contents_file(); - bool read_contents_file(const string &contents_filename, bool fresh_download); + bool read_contents_file(const std::string &contents_filename, bool fresh_download); void read_xhost(TiXmlElement *xhost); - P3DPackage *get_package(const string &package_name, - const string &package_version, - const string &package_platform, - const string &package_seq, - const string &alt_host = ""); - bool choose_suitable_platform(string &selected_platform, + P3DPackage *get_package(const std::string &package_name, + const std::string &package_version, + const std::string &package_platform, + const std::string &package_seq, + const std::string &alt_host = ""); + bool choose_suitable_platform(std::string &selected_platform, bool &per_platform, - const string &package_name, - const string &package_version, - const string &package_platform); + const std::string &package_name, + const std::string &package_version, + const std::string &package_platform); bool get_package_desc_file(FileSpec &desc_file, - string &package_seq, + std::string &package_seq, bool &package_solo, - const string &package_name, - const string &package_version, - const string &package_platform); + const std::string &package_name, + const std::string &package_version, + const std::string &package_platform); - void forget_package(P3DPackage *package, const string &alt_host = ""); - void migrate_package_host(P3DPackage *package, const string &alt_host, P3DHost *new_host); + void forget_package(P3DPackage *package, const std::string &alt_host = ""); + void migrate_package_host(P3DPackage *package, const std::string &alt_host, P3DHost *new_host); - void choose_random_mirrors(vector &result, int num_mirrors); - void add_mirror(string mirror_url); + void choose_random_mirrors(std::vector &result, int num_mirrors); + void add_mirror(std::string mirror_url); void uninstall(); private: - void determine_host_dir(const string &host_dir_basename); + void determine_host_dir(const std::string &host_dir_basename); - static string standardize_filename(const string &filename); - static bool copy_file(const string &from_filename, const string &to_filename); - static bool save_xml_file(TiXmlDocument *doc, const string &to_filename); - static int compare_seq(const string &seq_a, const string &seq_b); + static std::string standardize_filename(const std::string &filename); + static bool copy_file(const std::string &from_filename, const std::string &to_filename); + static bool save_xml_file(TiXmlDocument *doc, const std::string &to_filename); + static int compare_seq(const std::string &seq_a, const std::string &seq_b); static int compare_seq_int(const char *&num_a, const char *&num_b); private: - string _host_dir; - string _host_url; - string _host_url_prefix; - string _download_url_prefix; - string _descriptive_name; + std::string _host_dir; + std::string _host_url; + std::string _host_url_prefix; + std::string _download_url_prefix; + std::string _descriptive_name; TiXmlElement *_xcontents; time_t _contents_expiration; int _contents_iseq; FileSpec _contents_spec; - typedef vector Mirrors; + typedef std::vector Mirrors; Mirrors _mirrors; - typedef map AltHosts; + typedef std::map AltHosts; AltHosts _alt_hosts; - typedef vector PlatformPackages; - typedef map PackageMap; - typedef map Packages; + typedef std::vector PlatformPackages; + typedef std::map PackageMap; + typedef std::map Packages; Packages _packages; - typedef vector FailedPackages; + typedef std::vector FailedPackages; FailedPackages _failed_packages; friend class P3DInstanceManager; diff --git a/direct/src/plugin/p3dInstance.I b/direct/src/plugin/p3dInstance.I index 4168f68ac8..63765832d3 100644 --- a/direct/src/plugin/p3dInstance.I +++ b/direct/src/plugin/p3dInstance.I @@ -42,7 +42,7 @@ get_instance_id() const { * is guaranteed to be unique for each unique session required for different * P3DInstances. */ -inline const string &P3DInstance:: +inline const std::string &P3DInstance:: get_session_key() const { return _session_key; } @@ -56,7 +56,7 @@ get_session_key() const { * Presumably all of the platform-specific packages that are downloaded * subsequently must be of the exact same platform. */ -inline const string &P3DInstance:: +inline const std::string &P3DInstance:: get_session_platform() const { return _session_platform; } @@ -105,7 +105,7 @@ get_matches_script_origin() const { */ inline bool P3DInstance:: is_started() const { - return (_session != NULL); + return (_session != nullptr); } /** @@ -123,7 +123,7 @@ is_failed() const { inline P3DInstance::ImageFile:: ImageFile() { _use_standard_image = true; - _temp_filename = NULL; + _temp_filename = nullptr; _image_placement = P3DSplashWindow::IP_none; } @@ -140,8 +140,8 @@ inline P3DInstance::ImageFile:: */ inline void P3DInstance::ImageFile:: cleanup() { - if (_temp_filename != NULL) { + if (_temp_filename != nullptr) { delete _temp_filename; - _temp_filename = NULL; + _temp_filename = nullptr; } } diff --git a/direct/src/plugin/p3dInstance.cxx b/direct/src/plugin/p3dInstance.cxx index 0eabdaafd5..220e28c667 100644 --- a/direct/src/plugin/p3dInstance.cxx +++ b/direct/src/plugin/p3dInstance.cxx @@ -34,6 +34,14 @@ #include #include +using std::max; +using std::min; +using std::ostream; +using std::ostringstream; +using std::stringstream; +using std::string; +using std::vector; + // Lifted from NSEvent.h (which is Objective-C). enum { NSAlphaShiftKeyMask = 1 << 16, @@ -99,22 +107,22 @@ P3DInstance(P3D_request_ready_func *func, int argc, const char *argv[], void *user_data) : _func(func) { - _dom_object = NULL; + _dom_object = nullptr; _main_object = new P3DMainObject; _main_object->set_instance(this); _user_data = user_data; _request_pending = false; _total_time_reports = 0; - _temp_p3d_filename = NULL; - _image_package = NULL; + _temp_p3d_filename = nullptr; + _image_package = nullptr; _current_background_image = IT_none; _current_button_image = IT_none; _got_fparams = false; _got_wparams = false; _p3d_trusted = false; - _xpackage = NULL; - _certlist_package = NULL; - _p3dcert_package = NULL; + _xpackage = nullptr; + _certlist_package = nullptr; + _p3dcert_package = nullptr; _fparams.set_tokens(tokens, num_tokens); _fparams.set_args(argc, argv); @@ -141,10 +149,10 @@ P3DInstance(P3D_request_ready_func *func, } _auth_button_clicked = false; _failed = false; - _session = NULL; - _auth_session = NULL; - _panda3d_package = NULL; - _splash_window = NULL; + _session = nullptr; + _auth_session = nullptr; + _panda3d_package = nullptr; + _splash_window = nullptr; _instance_window_opened = false; _instance_window_attached = false; _stuff_to_download = false; @@ -163,18 +171,18 @@ P3DInstance(P3D_request_ready_func *func, #ifdef __APPLE__ _shared_fd = -1; _shared_mmap_size = 0; - _swbuffer = NULL; - _reversed_buffer = NULL; - _buffer_data = NULL; - _data_provider = NULL; - _buffer_color_space = NULL; - _buffer_image = NULL; + _swbuffer = nullptr; + _reversed_buffer = nullptr; + _buffer_data = nullptr; + _data_provider = nullptr; + _buffer_color_space = nullptr; + _buffer_image = nullptr; // We have to start with _mouse_active true; firefox doesn't send activate // events. _mouse_active = true; _modifiers = 0; - _frame_timer = NULL; + _frame_timer = nullptr; #endif // __APPLE__ // Set some initial properties. @@ -219,7 +227,7 @@ P3DInstance(P3D_request_ready_func *func, time_t timestamp = inst_mgr->get_coreapi_timestamp(); _main_object->set_int_property("coreapiTimestamp", (int)timestamp); const char *timestamp_string = ctime(×tamp); - if (timestamp_string == NULL) { + if (timestamp_string == nullptr) { timestamp_string = ""; } _main_object->set_string_property("coreapiTimestampString", timestamp_string); @@ -239,7 +247,7 @@ P3DInstance(P3D_request_ready_func *func, // contents. P3DHost *host = inst_mgr->get_host(inst_mgr->get_host_url()); _image_package = host->get_package("images", "", "", ""); - if (_image_package != NULL) { + if (_image_package != nullptr) { _image_package->add_instance(this); } @@ -261,27 +269,27 @@ P3DInstance(P3D_request_ready_func *func, */ P3DInstance:: ~P3DInstance() { - assert(_session == NULL); + assert(_session == nullptr); cleanup(); - if (_dom_object != NULL) { + if (_dom_object != nullptr) { P3D_OBJECT_DECREF(_dom_object); - _dom_object = NULL; + _dom_object = nullptr; } - if (_main_object != NULL) { + if (_main_object != nullptr) { nout << "panda_script_object ref = " << _main_object->_ref_count << "\n"; - _main_object->set_instance(NULL); + _main_object->set_instance(nullptr); P3D_OBJECT_DECREF(_main_object); - _main_object = NULL; + _main_object = nullptr; } Downloads::iterator di; for (di = _downloads.begin(); di != _downloads.end(); ++di) { P3DDownload *download = (*di).second; if (download->get_instance() == this) { - download->set_instance(NULL); + download->set_instance(nullptr); } p3d_unref_delete(download); } @@ -300,10 +308,10 @@ void P3DInstance:: cleanup() { _failed = true; - if (_auth_session != NULL) { + if (_auth_session != nullptr) { _auth_session->shutdown(false); p3d_unref_delete(_auth_session); - _auth_session = NULL; + _auth_session = nullptr; } for (int i = 0; i < (int)IT_num_image_types; ++i) { @@ -316,47 +324,47 @@ cleanup() { (*pi)->remove_instance(this); } _packages.clear(); - if (_image_package != NULL) { + if (_image_package != nullptr) { _image_package->remove_instance(this); - _image_package = NULL; + _image_package = nullptr; } - if (_certlist_package != NULL) { + if (_certlist_package != nullptr) { _certlist_package->remove_instance(this); - _certlist_package = NULL; + _certlist_package = nullptr; } - if (_p3dcert_package != NULL) { + if (_p3dcert_package != nullptr) { _p3dcert_package->remove_instance(this); - _p3dcert_package = NULL; + _p3dcert_package = nullptr; } - if (_splash_window != NULL) { + if (_splash_window != nullptr) { delete _splash_window; - _splash_window = NULL; + _splash_window = nullptr; } - if (_temp_p3d_filename != NULL) { + if (_temp_p3d_filename != nullptr) { delete _temp_p3d_filename; - _temp_p3d_filename = NULL; + _temp_p3d_filename = nullptr; } - if (_xpackage != NULL) { + if (_xpackage != nullptr) { delete _xpackage; - _xpackage = NULL; + _xpackage = nullptr; } #ifdef __APPLE__ - if (_frame_timer != NULL) { + if (_frame_timer != nullptr) { CFRunLoopTimerInvalidate(_frame_timer); CFRelease(_frame_timer); - _frame_timer = NULL; + _frame_timer = nullptr; } free_swbuffer(); #endif - TiXmlDocument *doc = NULL; + TiXmlDocument *doc = nullptr; ACQUIRE_LOCK(_request_lock); RawRequests::iterator ri; for (ri = _raw_requests.begin(); ri != _raw_requests.end(); ++ri) { @@ -404,7 +412,7 @@ set_p3d_url(const string &p3d_url) { determine_p3d_basename(p3d_url); // Make a temporary file to receive the instance data. - assert(_temp_p3d_filename == NULL); + assert(_temp_p3d_filename == nullptr); _temp_p3d_filename = new P3DTemporaryFile(".p3d"); _stuff_to_download = true; @@ -416,7 +424,7 @@ set_p3d_url(const string &p3d_url) { #ifdef _WIN32 _start_dl_tick = GetTickCount(); #else - gettimeofday(&_start_dl_timeval, NULL); + gettimeofday(&_start_dl_timeval, nullptr); #endif _show_dl_instance_progress = false; @@ -445,7 +453,7 @@ make_p3d_stream(const string &p3d_url) { determine_p3d_basename(p3d_url); // Make a temporary file to receive the instance data. - assert(_temp_p3d_filename == NULL); + assert(_temp_p3d_filename == nullptr); _temp_p3d_filename = new P3DTemporaryFile(".p3d"); _stuff_to_download = true; @@ -457,7 +465,7 @@ make_p3d_stream(const string &p3d_url) { #ifdef _WIN32 _start_dl_tick = GetTickCount(); #else - gettimeofday(&_start_dl_timeval, NULL); + gettimeofday(&_start_dl_timeval, nullptr); #endif _show_dl_instance_progress = false; @@ -505,7 +513,7 @@ set_wparams(const P3DWindowParams &wparams) { if (_wparams.get_window_type() != P3D_WT_hidden) { // Update or create the splash window. - if (_splash_window != NULL) { + if (_splash_window != nullptr) { _splash_window->set_wparams(_wparams); } else { make_splash_window(); @@ -526,13 +534,13 @@ set_wparams(const P3DWindowParams &wparams) { int x_size = _wparams.get_win_width(); int y_size = _wparams.get_win_height(); if (x_size != 0 && y_size != 0) { - if (_swbuffer == NULL || _swbuffer->get_x_size() != x_size || + if (_swbuffer == nullptr || _swbuffer->get_x_size() != x_size || _swbuffer->get_y_size() != y_size) { // We need to open a new shared buffer. alloc_swbuffer(); } - if (_swbuffer == NULL) { + if (_swbuffer == nullptr) { nout << "Could not open swbuffer\n"; } } @@ -540,7 +548,7 @@ set_wparams(const P3DWindowParams &wparams) { } // Update the instance in the sub-process. - if (_session != NULL) { + if (_session != nullptr) { TiXmlDocument *doc = new TiXmlDocument; TiXmlElement *xcommand = new TiXmlElement("command"); xcommand->SetAttribute("cmd", "setup_window"); @@ -582,11 +590,11 @@ set_browser_script_object(P3D_object *browser_script_object) { if (browser_script_object != _dom_object) { P3D_OBJECT_XDECREF(_dom_object); _dom_object = browser_script_object; - if (_dom_object != NULL) { + if (_dom_object != nullptr) { P3D_OBJECT_INCREF(_dom_object); } - if (_session != NULL) { + if (_session != nullptr) { send_browser_script_object(); } } @@ -596,12 +604,12 @@ set_browser_script_object(P3D_object *browser_script_object) { _origin_protocol.clear(); _origin_hostname.clear(); _origin_port.clear(); - if (_dom_object != NULL) { + if (_dom_object != nullptr) { P3D_object *location = P3D_OBJECT_GET_PROPERTY(_dom_object, "location"); - if (location != NULL) { + if (location != nullptr) { P3D_object *protocol = P3D_OBJECT_GET_PROPERTY(location, "protocol"); - if (protocol != NULL) { - int size = P3D_OBJECT_GET_STRING(protocol, NULL, 0); + if (protocol != nullptr) { + int size = P3D_OBJECT_GET_STRING(protocol, nullptr, 0); char *buffer = new char[size]; P3D_OBJECT_GET_STRING(protocol, buffer, size); _origin_protocol = string(buffer, size); @@ -610,8 +618,8 @@ set_browser_script_object(P3D_object *browser_script_object) { } P3D_object *hostname = P3D_OBJECT_GET_PROPERTY(location, "hostname"); - if (hostname != NULL) { - int size = P3D_OBJECT_GET_STRING(hostname, NULL, 0); + if (hostname != nullptr) { + int size = P3D_OBJECT_GET_STRING(hostname, nullptr, 0); char *buffer = new char[size]; P3D_OBJECT_GET_STRING(hostname, buffer, size); _origin_hostname = string(buffer, size); @@ -620,8 +628,8 @@ set_browser_script_object(P3D_object *browser_script_object) { } P3D_object *port = P3D_OBJECT_GET_PROPERTY(location, "port"); - if (port != NULL) { - int size = P3D_OBJECT_GET_STRING(port, NULL, 0); + if (port != nullptr) { + int size = P3D_OBJECT_GET_STRING(port, nullptr, 0); char *buffer = new char[size]; P3D_OBJECT_GET_STRING(port, buffer, size); _origin_port = string(buffer, size); @@ -676,14 +684,14 @@ get_request() { if (_baked_requests.empty()) { // No requests ready. _request_pending = false; - return NULL; + return nullptr; } P3D_request *request = _baked_requests.front(); _baked_requests.pop_front(); _request_pending = !_baked_requests.empty(); - if (request != NULL) { + if (request != nullptr) { switch (request->_request_type) { case P3D_RT_notify: { @@ -691,7 +699,7 @@ get_request() { string message = request->_request._notify._message; string expression = _fparams.lookup_token(message); nout << "notify: " << message << " " << expression << "\n"; - if (!expression.empty() && _dom_object != NULL) { + if (!expression.empty() && _dom_object != nullptr) { P3D_object *result = P3D_OBJECT_EVAL(_dom_object, expression.c_str()); P3D_OBJECT_XDECREF(result); } @@ -702,13 +710,13 @@ get_request() { { // We also send an implicit message when Python requests itself to // shutdown. - _main_object->set_pyobj(NULL); + _main_object->set_pyobj(nullptr); _main_object->set_string_property("status", "stopped"); string message = "onpythonstop"; string expression = _fparams.lookup_token(message); nout << "notify: " << message << " " << expression << "\n"; - if (!expression.empty() && _dom_object != NULL) { + if (!expression.empty() && _dom_object != nullptr) { P3D_object *result = P3D_OBJECT_EVAL(_dom_object, expression.c_str()); P3D_OBJECT_XDECREF(result); } @@ -730,13 +738,13 @@ get_request() { const char *host_url = request->_request._forget_package._host_url; const char *package_name = request->_request._forget_package._package_name; const char *package_version = request->_request._forget_package._package_version; - if (package_version == NULL) { + if (package_version == nullptr) { package_version = ""; } P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); P3DHost *host = inst_mgr->get_host(host_url); - if (package_name != NULL) { + if (package_name != nullptr) { P3DPackage *package = host->get_package(package_name, package_version, _session_platform, ""); host->forget_package(package); } else { @@ -769,7 +777,7 @@ void P3DInstance:: bake_requests() { while (true) { // Get the latest request from the read thread. - TiXmlDocument *doc = NULL; + TiXmlDocument *doc = nullptr; ACQUIRE_LOCK(_request_lock); if (!_raw_requests.empty()) { doc = _raw_requests.front(); @@ -777,18 +785,18 @@ bake_requests() { } RELEASE_LOCK(_request_lock); - if (doc == NULL) { + if (doc == nullptr) { // No more requests to process right now. return; } // Now we've got a request in XML form; convert it to P3D_request form. TiXmlElement *xrequest = doc->FirstChildElement("request"); - assert(xrequest != (TiXmlElement *)NULL); + assert(xrequest != nullptr); P3D_request *request = make_p3d_request(xrequest); delete doc; - if (request != NULL) { + if (request != nullptr) { _baked_requests.push_back(request); } } @@ -812,7 +820,7 @@ add_raw_request(TiXmlDocument *doc) { // Tell the world we've got a new request. P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); inst_mgr->signal_request_ready(this); - if (_session != NULL) { + if (_session != nullptr) { _session->signal_request_ready(this); } } @@ -824,7 +832,7 @@ add_raw_request(TiXmlDocument *doc) { */ void P3DInstance:: add_baked_request(P3D_request *request) { - assert(request->_instance == NULL); + assert(request->_instance == nullptr); request->_instance = this; ref(); @@ -843,14 +851,14 @@ add_baked_request(P3D_request *request) { */ void P3DInstance:: finish_request(P3D_request *request, bool handled) { - assert(request != NULL); - if (request->_instance == NULL) { + assert(request != nullptr); + if (request->_instance == nullptr) { nout << "Ignoring empty request " << request << "\n"; return; } P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); - if (inst_mgr->validate_instance(request->_instance) == NULL) { + if (inst_mgr->validate_instance(request->_instance) == nullptr) { // nout << "Ignoring unknown request " << request << "\n"; return; } @@ -860,31 +868,31 @@ finish_request(P3D_request *request, bool handled) { break; case P3D_RT_get_url: - if (request->_request._get_url._url != NULL) { + if (request->_request._get_url._url != nullptr) { free((char *)request->_request._get_url._url); - request->_request._get_url._url = NULL; + request->_request._get_url._url = nullptr; } break; case P3D_RT_notify: - if (request->_request._notify._message != NULL) { + if (request->_request._notify._message != nullptr) { free((char *)request->_request._notify._message); - request->_request._notify._message = NULL; + request->_request._notify._message = nullptr; } break; case P3D_RT_forget_package: - if (request->_request._forget_package._host_url != NULL) { + if (request->_request._forget_package._host_url != nullptr) { free((char *)request->_request._forget_package._host_url); - request->_request._forget_package._host_url = NULL; + request->_request._forget_package._host_url = nullptr; } - if (request->_request._forget_package._package_name != NULL) { + if (request->_request._forget_package._package_name != nullptr) { free((char *)request->_request._forget_package._package_name); - request->_request._forget_package._package_name = NULL; + request->_request._forget_package._package_name = nullptr; } - if (request->_request._forget_package._package_version != NULL) { + if (request->_request._forget_package._package_version != nullptr) { free((char *)request->_request._forget_package._package_version); - request->_request._forget_package._package_version = NULL; + request->_request._forget_package._package_version = nullptr; } break; @@ -893,7 +901,7 @@ finish_request(P3D_request *request, bool handled) { } p3d_unref_delete(((P3DInstance *)request->_instance)); - request->_instance = NULL; + request->_instance = nullptr; delete request; } @@ -925,7 +933,7 @@ feed_url_stream(int unique_id, if (!download_ok || download->get_download_finished()) { // All done. if (download->get_instance() == this) { - download->set_instance(NULL); + download->set_instance(nullptr); } _downloads.erase(di); p3d_unref_delete(download); @@ -941,7 +949,7 @@ feed_url_stream(int unique_id, bool P3DInstance:: handle_event(const P3D_event_data &event) { bool retval = false; - if (_splash_window != NULL) { + if (_splash_window != nullptr) { if (_splash_window->handle_event(event)) { retval = true; } @@ -970,7 +978,7 @@ handle_event(const P3D_event_data &event) { */ const string &P3DInstance:: get_log_pathname() const { - if (_session != NULL) { + if (_session != nullptr) { return _session->_log_pathname; } return _log_pathname; @@ -1053,16 +1061,16 @@ remove_package(P3DPackage *package) { _downloading_packages.erase(pi); } if (package == _image_package) { - _image_package = NULL; + _image_package = nullptr; } if (package == _certlist_package) { - _certlist_package = NULL; + _certlist_package = nullptr; } if (package == _p3dcert_package) { - _p3dcert_package = NULL; + _p3dcert_package = nullptr; } if (package == _panda3d_package) { - _panda3d_package = NULL; + _panda3d_package = nullptr; } set_failed(); @@ -1170,7 +1178,7 @@ start_download(P3DDownload *download, bool add_request) { // is true in order to ask the plugin for the stream. if (add_request) { P3D_request *request = new P3D_request; - request->_instance = NULL; + request->_instance = nullptr; request->_request_type = P3D_RT_get_url; request->_request._get_url._url = strdup(download->get_url().c_str()); request->_request._get_url._unique_id = download_id; @@ -1227,7 +1235,7 @@ request_stop_main_thread() { if (add_request) { _requested_stop = true; P3D_request *request = new P3D_request; - request->_instance = NULL; + request->_instance = nullptr; request->_request_type = P3D_RT_stop; add_baked_request(request); } @@ -1240,7 +1248,7 @@ request_stop_main_thread() { void P3DInstance:: request_refresh() { P3D_request *request = new P3D_request; - request->_instance = NULL; + request->_instance = nullptr; request->_request_type = P3D_RT_refresh; add_baked_request(request); } @@ -1251,7 +1259,7 @@ request_refresh() { void P3DInstance:: request_callback(P3D_callback_func *func, void *data) { P3D_request *request = new P3D_request; - request->_instance = NULL; + request->_instance = nullptr; request->_request_type = P3D_RT_callback; request->_request._callback._func = func; request->_request._callback._data = data; @@ -1335,7 +1343,7 @@ splash_button_clicked_main_thread() { if (!_p3d_trusted) { auth_button_clicked(); - } else if (_session == NULL) { + } else if (_session == nullptr) { play_button_clicked(); } else { nout << "Ignoring click for already-started instance\n"; @@ -1349,10 +1357,10 @@ splash_button_clicked_main_thread() { void P3DInstance:: auth_button_clicked() { // Delete the previous session and create a new one. - if (_auth_session != NULL) { + if (_auth_session != nullptr) { _auth_session->shutdown(false); p3d_unref_delete(_auth_session); - _auth_session = NULL; + _auth_session = nullptr; } P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); @@ -1366,7 +1374,7 @@ auth_button_clicked() { */ void P3DInstance:: play_button_clicked() { - if (_session == NULL && _p3d_trusted) { + if (_session == nullptr && _p3d_trusted) { set_button_image(IT_none); if (!_download_started) { // Now we initiate the download. @@ -1472,7 +1480,7 @@ uninstall_host() { uninstall_packages(); // Collect the set of hosts referenced by this instance. - set hosts; + std::set hosts; Packages::const_iterator pi; for (pi = _packages.begin(); pi != _packages.end(); ++pi) { P3DPackage *package = (*pi); @@ -1484,7 +1492,7 @@ uninstall_host() { nout << "Uninstalling " << hosts.size() << " hosts\n"; // Uninstall all of them. - set::iterator hi; + std::set::iterator hi; for (hi = hosts.begin(); hi != hosts.end(); ++hi) { P3DHost *host = (*hi); host->uninstall(); @@ -1754,12 +1762,12 @@ check_p3d_signature() { } // Check the list of pre-approved certificates. - if (_certlist_package == NULL) { + if (_certlist_package == nullptr) { // We have to go download this package. P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); P3DHost *host = inst_mgr->get_host(inst_mgr->get_host_url()); _certlist_package = host->get_package("certlist", "", "", ""); - if (_certlist_package != NULL) { + if (_certlist_package != nullptr) { _certlist_package->add_instance(this); } @@ -1791,12 +1799,12 @@ mark_p3d_untrusted() { return; } - if (_p3dcert_package == NULL) { + if (_p3dcert_package == nullptr) { // We have to go download this package. P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); P3DHost *host = inst_mgr->get_host(inst_mgr->get_host_url()); _p3dcert_package = host->get_package("p3dcert", "", "", ""); - if (_p3dcert_package != NULL) { + if (_p3dcert_package != nullptr) { _p3dcert_package->add_instance(this); } @@ -1883,14 +1891,14 @@ scan_app_desc_file(TiXmlDocument *doc) { P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); TiXmlElement *xpackage = doc->FirstChildElement("package"); - if (xpackage == NULL) { + if (xpackage == nullptr) { return; } - assert(_xpackage == NULL); + assert(_xpackage == nullptr); _xpackage = (TiXmlElement *)xpackage->Clone(); TiXmlElement *xconfig = _xpackage->FirstChildElement("config"); - if (xconfig != NULL) { + if (xconfig != nullptr) { int hidden = 0; if (xconfig->QueryIntAttribute("hidden", &hidden) == TIXML_SUCCESS) { if (hidden != 0) { @@ -1899,27 +1907,27 @@ scan_app_desc_file(TiXmlDocument *doc) { } const char *log_basename = xconfig->Attribute("log_basename"); - if (log_basename != NULL) { + if (log_basename != nullptr) { _log_basename = log_basename; } const char *prc_name = xconfig->Attribute("prc_name"); - if (prc_name != NULL) { + if (prc_name != nullptr) { _prc_name = prc_name; } const char *start_dir = xconfig->Attribute("start_dir"); - if (start_dir != NULL) { + if (start_dir != nullptr) { _start_dir = start_dir; } const char *run_origin = xconfig->Attribute("run_origin"); - if (run_origin != NULL) { + if (run_origin != nullptr) { _matches_run_origin = check_matches_origin(run_origin); } const char *script_origin = xconfig->Attribute("script_origin"); - if (script_origin != NULL) { + if (script_origin != nullptr) { _matches_script_origin = check_matches_origin(script_origin); } @@ -1987,24 +1995,24 @@ scan_app_desc_file(TiXmlDocument *doc) { void P3DInstance:: add_panda3d_package() { assert(!_packages_specified); - assert(_panda3d_package == NULL); - if (_xpackage == NULL) { + assert(_panda3d_package == nullptr); + if (_xpackage == nullptr) { return; } P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); TiXmlElement *xrequires = _xpackage->FirstChildElement("requires"); - while (xrequires != NULL) { + while (xrequires != nullptr) { const char *name = xrequires->Attribute("name"); const char *host_url = xrequires->Attribute("host"); - if (name != NULL && host_url != NULL && strcmp(name, "panda3d") == 0) { + if (name != nullptr && host_url != nullptr && strcmp(name, "panda3d") == 0) { const char *version = xrequires->Attribute("version"); - if (version == NULL) { + if (version == nullptr) { version = ""; } const char *seq = xrequires->Attribute("seq"); - if (seq == NULL) { + if (seq == nullptr) { seq = ""; } P3DHost *host = inst_mgr->get_host(host_url); @@ -2026,23 +2034,23 @@ add_panda3d_package() { void P3DInstance:: add_packages() { assert(!_packages_specified); - if (_xpackage == NULL) { + if (_xpackage == nullptr) { return; } P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); TiXmlElement *xrequires = _xpackage->FirstChildElement("requires"); - while (xrequires != NULL) { + while (xrequires != nullptr) { const char *name = xrequires->Attribute("name"); const char *host_url = xrequires->Attribute("host"); - if (name != NULL && host_url != NULL) { + if (name != nullptr && host_url != nullptr) { const char *version = xrequires->Attribute("version"); - if (version == NULL) { + if (version == nullptr) { version = ""; } const char *seq = xrequires->Attribute("seq"); - if (seq == NULL) { + if (seq == nullptr) { seq = ""; } P3DHost *host = inst_mgr->get_host(host_url); @@ -2074,17 +2082,17 @@ add_packages() { string P3DInstance:: find_alt_host_url(const string &host_url, const string &alt_host) { TiXmlElement *xhost = _xpackage->FirstChildElement("host"); - while (xhost != NULL) { + while (xhost != nullptr) { const char *url = xhost->Attribute("url"); - if (url != NULL && host_url == url) { + if (url != nullptr && host_url == url) { // This matches the host. Now do we have a matching alt_host keyword // for this host? TiXmlElement *xalt_host = xhost->FirstChildElement("alt_host"); - while (xalt_host != NULL) { + while (xalt_host != nullptr) { const char *keyword = xalt_host->Attribute("keyword"); - if (keyword != NULL && alt_host == keyword) { + if (keyword != nullptr && alt_host == keyword) { const char *alt_host_url = xalt_host->Attribute("url"); - if (alt_host_url != NULL) { + if (alt_host_url != nullptr) { return alt_host_url; } } @@ -2110,9 +2118,9 @@ get_host_info(P3DHost *host) { assert(!host->has_contents_file()); TiXmlElement *xhost = _xpackage->FirstChildElement("host"); - while (xhost != NULL) { + while (xhost != nullptr) { const char *url = xhost->Attribute("url"); - if (url != NULL && host->get_host_url() == url) { + if (url != nullptr && host->get_host_url() == url) { // Found the entry for this particular host. host->read_xhost(xhost); return; @@ -2168,7 +2176,7 @@ send_browser_script_object() { TiXmlElement *xcommand = new TiXmlElement("command"); xcommand->SetAttribute("cmd", "pyobj"); xcommand->SetAttribute("op", "set_browser_script_object"); - if (_dom_object != NULL) { + if (_dom_object != nullptr) { xcommand->LinkEndChild(_session->p3dobj_to_xml(_dom_object)); } @@ -2184,16 +2192,16 @@ send_browser_script_object() { P3D_request *P3DInstance:: make_p3d_request(TiXmlElement *xrequest) { P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); - P3D_request *request = NULL; + P3D_request *request = nullptr; const char *rtype = xrequest->Attribute("rtype"); - if (rtype != NULL) { + if (rtype != nullptr) { if (strcmp(rtype, "notify") == 0) { const char *message = xrequest->Attribute("message"); - if (message != NULL) { + if (message != nullptr) { // A notify message from Python code. request = new P3D_request; - request->_instance = NULL; + request->_instance = nullptr; request->_request_type = P3D_RT_notify; request->_request._notify._message = strdup(message); handle_notify_request(message); @@ -2210,19 +2218,19 @@ make_p3d_request(TiXmlElement *xrequest) { int unique_id = 0; xrequest->Attribute("unique_id", &unique_id); - P3D_object *value = NULL; + P3D_object *value = nullptr; TiXmlElement *xvalue = xrequest->FirstChildElement("value"); - if (xvalue != NULL) { + if (xvalue != nullptr) { value = _session->xml_to_p3dobj(xvalue); } - if (value == NULL) { + if (value == nullptr) { value = inst_mgr->new_none_object(); } - if (operation != NULL && xobject != NULL) { + if (operation != nullptr && xobject != nullptr) { P3D_object *object = _session->xml_to_p3dobj(xobject); - if (property_name == NULL) { + if (property_name == nullptr) { property_name = ""; } @@ -2242,25 +2250,25 @@ make_p3d_request(TiXmlElement *xrequest) { } else if (strcmp(rtype, "stop") == 0) { // A stop request from Python code. This is kind of weird, but OK. request = new P3D_request; - request->_instance = NULL; + request->_instance = nullptr; request->_request_type = P3D_RT_stop; } else if (strcmp(rtype, "forget_package") == 0) { const char *host_url = xrequest->Attribute("host_url"); - if (host_url != NULL) { + if (host_url != nullptr) { // A Python-level request to remove a package from the cache. request = new P3D_request; - request->_instance = NULL; + request->_instance = nullptr; request->_request_type = P3D_RT_forget_package; request->_request._forget_package._host_url = strdup(host_url); - request->_request._forget_package._package_name = NULL; - request->_request._forget_package._package_version = NULL; + request->_request._forget_package._package_name = nullptr; + request->_request._forget_package._package_version = nullptr; const char *package_name = xrequest->Attribute("package_name"); const char *package_version = xrequest->Attribute("package_version"); - if (package_name != NULL) { + if (package_name != nullptr) { request->_request._forget_package._package_name = strdup(package_name); - if (package_version != NULL) { + if (package_version != nullptr) { request->_request._forget_package._package_version = strdup(package_version); } } @@ -2271,8 +2279,8 @@ make_p3d_request(TiXmlElement *xrequest) { } } - if (request != NULL) { - assert(request->_instance == NULL); + if (request != nullptr) { + assert(request->_instance == nullptr); request->_instance = this; ref(); } @@ -2298,19 +2306,19 @@ handle_notify_request(const string &message) { doc->LinkEndChild(xcommand); TiXmlDocument *response = _session->command_and_response(doc); - P3D_object *result = NULL; - if (response != NULL) { + P3D_object *result = nullptr; + if (response != nullptr) { TiXmlElement *xresponse = response->FirstChildElement("response"); - if (xresponse != NULL) { + if (xresponse != nullptr) { TiXmlElement *xvalue = xresponse->FirstChildElement("value"); - if (xvalue != NULL) { + if (xvalue != nullptr) { result = _session->xml_to_p3dobj(xvalue); } } delete response; } - if (result != NULL) { + if (result != nullptr) { if (_matches_script_origin) { // We only actually merge the objects if this web page is allowed to // call our scripting functions. @@ -2329,7 +2337,7 @@ handle_notify_request(const string &message) { // The process told us that it just successfully opened its window, for // the first time. Hide the splash window. _instance_window_opened = true; - if (_splash_window != NULL) { + if (_splash_window != nullptr) { _splash_window->set_visible(false); } @@ -2352,7 +2360,7 @@ handle_notify_request(const string &message) { // window opening and the first frame being drawn. _instance_window_attached = true; #ifndef __APPLE__ - if (_splash_window != NULL) { + if (_splash_window != nullptr) { _splash_window->set_visible(false); } #endif // __APPLE__ @@ -2360,12 +2368,12 @@ handle_notify_request(const string &message) { #ifdef __APPLE__ // Start a timer to update the frame repeatedly. This seems to be // steadier than waiting for nullEvent. - if (_frame_timer == NULL) { + if (_frame_timer == nullptr) { CFRunLoopTimerContext timer_context; memset(&timer_context, 0, sizeof(timer_context)); timer_context.info = this; _frame_timer = CFRunLoopTimerCreate - (NULL, 0, 1.0 / 60.0, 0, 0, timer_callback, &timer_context); + (nullptr, 0, 1.0 / 60.0, 0, 0, timer_callback, &timer_context); CFRunLoopRef run_loop = CFRunLoopGetCurrent(); CFRunLoopAddTimer(run_loop, _frame_timer, kCFRunLoopCommonModes); } @@ -2377,16 +2385,16 @@ handle_notify_request(const string &message) { _instance_window_opened = true; _instance_window_attached = false; set_background_image(IT_active); - if (_splash_window != NULL) { + if (_splash_window != nullptr) { _splash_window->set_visible(true); } #ifdef __APPLE__ // Stop the frame timer; we don't need it any more. - if (_frame_timer != NULL) { + if (_frame_timer != nullptr) { CFRunLoopTimerInvalidate(_frame_timer); CFRelease(_frame_timer); - _frame_timer = NULL; + _frame_timer = nullptr; } #endif // __APPLE__ @@ -2403,7 +2411,7 @@ handle_notify_request(const string &message) { auth_finished_main_thread(); } else if (message == "keyboardfocus") { - if (_splash_window != NULL) { + if (_splash_window != nullptr) { _splash_window->request_keyboard_focus(); } } @@ -2430,7 +2438,7 @@ handle_script_request(const string &operation, P3D_object *object, // We've got the property value; feed it back down to the subprocess. - if (result != NULL) { + if (result != nullptr) { xcommand->LinkEndChild(_session->p3dobj_to_xml(result)); P3D_OBJECT_DECREF(result); } @@ -2445,7 +2453,7 @@ handle_script_request(const string &operation, P3D_object *object, xcommand->LinkEndChild(xvalue); } else if (operation == "del_property") { - bool result = P3D_OBJECT_SET_PROPERTY(object, property_name.c_str(), true, NULL); + bool result = P3D_OBJECT_SET_PROPERTY(object, property_name.c_str(), true, nullptr); TiXmlElement *xvalue = new TiXmlElement("value"); xvalue->SetAttribute("type", "bool"); @@ -2476,20 +2484,20 @@ handle_script_request(const string &operation, P3D_object *object, P3D_OBJECT_CALL(object, property_name.c_str(), needs_response, values, num_values); - if (result != NULL) { + if (result != nullptr) { xcommand->LinkEndChild(_session->p3dobj_to_xml(result)); P3D_OBJECT_DECREF(result); } } else if (operation == "eval") { P3D_object *result; - int size = P3D_OBJECT_GET_STRING(value, NULL, 0); + int size = P3D_OBJECT_GET_STRING(value, nullptr, 0); char *buffer = new char[size + 1]; P3D_OBJECT_GET_STRING(value, buffer, size + 1); result = P3D_OBJECT_EVAL(object, buffer); delete[] buffer; - if (result != NULL) { + if (result != nullptr) { xcommand->LinkEndChild(_session->p3dobj_to_xml(result)); P3D_OBJECT_DECREF(result); } @@ -2544,7 +2552,7 @@ make_splash_window() { make_visible = true; } - if (_splash_window != NULL) { + if (_splash_window != nullptr) { // Already got one. _splash_window->set_visible(make_visible); return; @@ -2704,7 +2712,7 @@ make_splash_window() { _image_files[i]._filename.clear(); // Make a temporary file to receive the splash image. - assert(_image_files[i]._temp_filename == NULL); + assert(_image_files[i]._temp_filename == nullptr); _image_files[i]._temp_filename = new P3DTemporaryFile(".jpg"); // Start downloading the requested image. @@ -2753,7 +2761,7 @@ set_background_image(ImageType image_type) { } // Update the splash window. - if (_splash_window != NULL) { + if (_splash_window != nullptr) { _splash_window->set_image_filename(_image_files[_current_background_image]._filename, P3DSplashWindow::IP_background); } } @@ -2790,7 +2798,7 @@ set_button_image(ImageType image_type) { } // Update the splash window. - if (_splash_window != NULL) { + if (_splash_window != nullptr) { if (_current_button_image != IT_none) { _splash_window->set_image_filename(_image_files[_current_button_image]._filename, P3DSplashWindow::IP_button_ready); _splash_window->set_image_filename(_image_files[_current_button_image + 1]._filename, P3DSplashWindow::IP_button_rollover); @@ -2804,7 +2812,7 @@ set_button_image(ImageType image_type) { } else { // We're not changing the button graphic, but we might be re-activating // it. - if (_splash_window != NULL) { + if (_splash_window != nullptr) { if (_current_button_image != IT_none) { _splash_window->set_button_active(true); } else { @@ -2829,7 +2837,7 @@ report_package_info_ready(P3DPackage *package) { // If we're downloading one of the two cert packages, though, put up a // progress bar. make_splash_window(); - if (_splash_window != NULL) { + if (_splash_window != nullptr) { _splash_window->set_install_progress(0.0, true, 0); } if (package == _certlist_package) { @@ -2926,7 +2934,7 @@ ready_to_install() { #ifdef _WIN32 _start_dl_tick = GetTickCount(); #else - gettimeofday(&_start_dl_timeval, NULL); + gettimeofday(&_start_dl_timeval, nullptr); #endif nout << "Beginning install of " << _downloading_packages.size() @@ -2956,7 +2964,7 @@ ready_to_install() { _main_object->set_float_property("downloadProgress", progress); } - if (_splash_window != NULL) { + if (_splash_window != nullptr) { _splash_window->set_install_progress(progress, true, 0); } @@ -3030,7 +3038,7 @@ mark_download_complete() { } // Take down the download progress bar. - if (_splash_window != NULL) { + if (_splash_window != nullptr) { _splash_window->set_install_progress(0.0, true, 0); } set_install_label(""); @@ -3090,7 +3098,7 @@ report_instance_progress(double progress, bool is_progress_known, double elapsed = (double)(now - _start_dl_tick) * 0.001; #else struct timeval now; - gettimeofday(&now, NULL); + gettimeofday(&now, nullptr); double elapsed = (double)(now.tv_sec - _start_dl_timeval.tv_sec) + (double)(now.tv_usec - _start_dl_timeval.tv_usec) / 1000000.0; #endif @@ -3108,7 +3116,7 @@ report_instance_progress(double progress, bool is_progress_known, } } - if (_splash_window != NULL && _show_dl_instance_progress) { + if (_splash_window != nullptr && _show_dl_instance_progress) { _splash_window->set_install_progress(progress, is_progress_known, received_data); } _main_object->set_float_property("instanceDownloadProgress", progress); @@ -3125,7 +3133,7 @@ report_package_progress(P3DPackage *package, double progress) { } if (package == _certlist_package || package == _p3dcert_package) { // This gets its own progress bar. - if (_splash_window != NULL) { + if (_splash_window != nullptr) { _splash_window->set_install_progress(progress, true, 0); } return; @@ -3141,7 +3149,7 @@ report_package_progress(P3DPackage *package, double progress) { progress = (progress * package->get_download_size() + _total_downloaded + _prev_downloaded) / (_total_download_size + _prev_downloaded); progress = min(progress, 1.0); - if (_splash_window != NULL) { + if (_splash_window != nullptr) { _splash_window->set_install_progress(progress, true, 0); } _main_object->set_float_property("downloadProgress", progress); @@ -3155,7 +3163,7 @@ report_package_progress(P3DPackage *package, double progress) { double elapsed = (double)(now - _start_dl_tick) * 0.001; #else struct timeval now; - gettimeofday(&now, NULL); + gettimeofday(&now, nullptr); double elapsed = (double)(now.tv_sec - _start_dl_timeval.tv_sec) + (double)(now.tv_usec - _start_dl_timeval.tv_usec) / 1000000.0; #endif @@ -3213,7 +3221,7 @@ report_package_done(P3DPackage *package, bool success) { // files out of it and point them to the splash window. string package_dir = package->get_package_dir(); const TiXmlElement *xconfig = package->get_xconfig(); - if (xconfig == NULL) { + if (xconfig == nullptr) { nout << "No entry in image package\n"; return; } @@ -3225,7 +3233,7 @@ report_package_done(P3DPackage *package, bool success) { // filename. string token = string(_image_type_names[i]) + "_img"; const string *basename = xconfig->Attribute(token); - if (basename == NULL) { + if (basename == nullptr) { nout << "No entry in image package for " << token << "\n"; } else { string image_filename = package_dir + "/" + *basename; @@ -3233,7 +3241,7 @@ report_package_done(P3DPackage *package, bool success) { // If the image should be on the window now, and the window still // exists, put it up. - if (_splash_window != NULL && + if (_splash_window != nullptr && _image_files[i]._image_placement != P3DSplashWindow::IP_none) { P3DSplashWindow::ImagePlacement image_placement = _image_files[i]._image_placement; _splash_window->set_image_filename(image_filename, image_placement); @@ -3252,7 +3260,7 @@ report_package_done(P3DPackage *package, bool success) { package->mark_used(); // Take down the download progress. - if (_splash_window != NULL) { + if (_splash_window != nullptr) { _splash_window->set_install_progress(0.0, true, 0); } set_install_label(""); @@ -3270,7 +3278,7 @@ report_package_done(P3DPackage *package, bool success) { package->mark_used(); // Take down the download progress. - if (_splash_window != NULL) { + if (_splash_window != nullptr) { _splash_window->set_install_progress(0.0, true, 0); } set_install_label(""); @@ -3294,7 +3302,7 @@ report_package_done(P3DPackage *package, bool success) { void P3DInstance:: set_install_label(const string &install_label) { _install_label = install_label; - if (_splash_window != NULL) { + if (_splash_window != nullptr) { _splash_window->set_install_label(_install_label); } } @@ -3330,7 +3338,7 @@ paint_window() { */ bool P3DInstance:: get_framebuffer_osx_port() { - if (_swbuffer == NULL || !_instance_window_attached) { + if (_swbuffer == nullptr || !_instance_window_attached) { // We don't have a Panda3D window yet. return false; } @@ -3382,7 +3390,7 @@ get_framebuffer_osx_port() { _swbuffer->close_read_framebuffer(); - if (_splash_window != NULL && _splash_window->get_visible()) { + if (_splash_window != nullptr && _splash_window->get_visible()) { // If the splash window is up, time to hide it. We've just rendered a // real frame. _splash_window->set_visible(false); @@ -3404,7 +3412,7 @@ get_framebuffer_osx_port() { */ bool P3DInstance:: get_framebuffer_osx_cgcontext() { - if (_swbuffer == NULL || !_instance_window_attached) { + if (_swbuffer == nullptr || !_instance_window_attached) { // We don't have a Panda3D window yet. return false; } @@ -3420,7 +3428,7 @@ get_framebuffer_osx_cgcontext() { memcpy(_reversed_buffer, framebuffer, y_size * rowsize); _swbuffer->close_read_framebuffer(); - if (_splash_window != NULL && _splash_window->get_visible()) { + if (_splash_window != nullptr && _splash_window->get_visible()) { // If the splash window is up, time to hide it. We've just rendered a // real frame. _splash_window->set_visible(false); @@ -3466,7 +3474,7 @@ paint_window_osx_port() { const P3D_window_handle &handle = _wparams.get_parent_window(); assert(handle._window_handle_type == P3D_WHT_osx_port); GrafPtr out_port = handle._handle._osx_port._port; - GrafPtr port_save = NULL; + GrafPtr port_save = nullptr; Boolean port_changed = QDSwapPort(out_port, &port_save); // Make sure the clipping rectangle isn't in the way. Is there a better way @@ -3479,7 +3487,7 @@ paint_window_osx_port() { &src_rect, &ddrc_rect, srcCopy, 0); if (port_changed) { - QDSwapPort(port_save, NULL); + QDSwapPort(port_save, nullptr); } DisposeGWorld(pGWorld); @@ -3501,7 +3509,7 @@ paint_window_osx_cgcontext(CGContextRef context) { int x_size = min(_wparams.get_win_width(), _swbuffer->get_x_size()); int y_size = min(_wparams.get_win_height(), _swbuffer->get_y_size()); - if (_buffer_image != NULL) { + if (_buffer_image != nullptr) { CGRect region = { { 0, 0 }, { (CGFloat)x_size, (CGFloat)y_size } }; CGContextDrawImage(context, region, _buffer_image); } @@ -3526,20 +3534,20 @@ handle_event_osx_event_record(const P3D_event_data &event) { const P3D_window_handle &handle = _wparams.get_parent_window(); if (handle._window_handle_type == P3D_WHT_osx_port) { GrafPtr out_port = handle._handle._osx_port._port; - GrafPtr port_save = NULL; + GrafPtr port_save = nullptr; Boolean port_changed = QDSwapPort(out_port, &port_save); GlobalToLocal(&pt); if (port_changed) { - QDSwapPort(port_save, NULL); + QDSwapPort(port_save, nullptr); } } else { // First, convert the coordinates from screen coordinates to browser // window coordinates. WindowRef window = handle._handle._osx_cgcontext._window; CGPoint cgpt = { (CGFloat)pt.h, (CGFloat)pt.v }; - HIPointConvert(&cgpt, kHICoordSpaceScreenPixel, NULL, + HIPointConvert(&cgpt, kHICoordSpaceScreenPixel, nullptr, kHICoordSpaceWindow, window); // Then convert to plugin coordinates. @@ -3572,7 +3580,7 @@ handle_event_osx_event_record(const P3D_event_data &event) { case keyDown: case keyUp: case autoKey: - if (_swbuffer != NULL) { + if (_swbuffer != nullptr) { swb_event._source = SubprocessWindowBuffer::ES_keyboard; swb_event._code = er->message; if (er->what == keyUp) { @@ -3614,7 +3622,7 @@ handle_event_osx_event_record(const P3D_event_data &event) { } } - if (_swbuffer != NULL) { + if (_swbuffer != nullptr) { _swbuffer->add_event(swb_event); } #endif // __APPLE__ @@ -3709,7 +3717,7 @@ handle_event_osx_cocoa(const P3D_event_data &event) { swb_event._flags |= SubprocessWindowBuffer::EF_has_mouse; } - if (_swbuffer != NULL) { + if (_swbuffer != nullptr) { _swbuffer->add_event(swb_event); } #endif // __APPLE__ @@ -3773,7 +3781,7 @@ void P3DInstance:: send_notify(const string &message) { nout << "send_notify(" << message << ")\n"; P3D_request *request = new P3D_request; - request->_instance = NULL; + request->_instance = nullptr; request->_request_type = P3D_RT_notify; request->_request._notify._message = strdup(message.c_str()); add_baked_request(request); @@ -3793,12 +3801,12 @@ alloc_swbuffer() { _swbuffer = SubprocessWindowBuffer::new_buffer (_shared_fd, _shared_mmap_size, _shared_filename, x_size, y_size); - if (_swbuffer != NULL) { + if (_swbuffer != nullptr) { _reversed_buffer = new char[_swbuffer->get_framebuffer_size()]; memset(_reversed_buffer, 0, _swbuffer->get_row_size()); size_t rowsize = _swbuffer->get_row_size(); - _buffer_data = CFDataCreateWithBytesNoCopy(NULL, (const UInt8 *)_reversed_buffer, + _buffer_data = CFDataCreateWithBytesNoCopy(nullptr, (const UInt8 *)_reversed_buffer, y_size * rowsize, kCFAllocatorNull); _data_provider = CGDataProviderCreateWithCFData(_buffer_data); @@ -3806,7 +3814,7 @@ alloc_swbuffer() { _buffer_image = CGImageCreate(x_size, y_size, 8, 32, rowsize, _buffer_color_space, kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little, - _data_provider, NULL, false, kCGRenderingIntentDefault); + _data_provider, nullptr, false, kCGRenderingIntentDefault); } } @@ -3819,26 +3827,26 @@ alloc_swbuffer() { */ void P3DInstance:: free_swbuffer() { - if (_swbuffer != NULL) { + if (_swbuffer != nullptr) { SubprocessWindowBuffer::destroy_buffer(_shared_fd, _shared_mmap_size, _shared_filename, _swbuffer); - _swbuffer = NULL; + _swbuffer = nullptr; } - if (_reversed_buffer != NULL) { + if (_reversed_buffer != nullptr) { delete[] _reversed_buffer; - _reversed_buffer = NULL; + _reversed_buffer = nullptr; } - if (_buffer_image != NULL) { + if (_buffer_image != nullptr) { CGImageRelease(_buffer_image); CGColorSpaceRelease(_buffer_color_space); CGDataProviderRelease(_data_provider); CFRelease(_buffer_data); - _buffer_data = NULL; - _data_provider = NULL; - _buffer_color_space = NULL; - _buffer_image = NULL; + _buffer_data = nullptr; + _data_provider = nullptr; + _buffer_color_space = nullptr; + _buffer_image = nullptr; } } #endif // __APPLE__ @@ -3881,7 +3889,7 @@ download_finished(bool success) { // Put it onscreen if it's supposed to be onscreen now, and our splash // window still exists. - if (_inst->_splash_window != NULL && + if (_inst->_splash_window != nullptr && _inst->_image_files[_index]._image_placement != P3DSplashWindow::IP_none) { P3DSplashWindow::ImagePlacement image_placement = _inst->_image_files[_index]._image_placement; _inst->_splash_window->set_image_filename(get_filename(), image_placement); diff --git a/direct/src/plugin/p3dInstance.h b/direct/src/plugin/p3dInstance.h index 325e368003..7972ef7fbe 100644 --- a/direct/src/plugin/p3dInstance.h +++ b/direct/src/plugin/p3dInstance.h @@ -56,9 +56,9 @@ public: ~P3DInstance(); void cleanup(); - void set_p3d_url(const string &p3d_url); - void set_p3d_filename(const string &p3d_filename, const int &p3d_offset = 0); - int make_p3d_stream(const string &p3d_url); + void set_p3d_url(const std::string &p3d_url); + void set_p3d_filename(const std::string &p3d_filename, const int &p3d_offset = 0); + int make_p3d_stream(const std::string &p3d_url); inline const P3DFileParams &get_fparams() const; void set_wparams(const P3DWindowParams &wparams); @@ -84,16 +84,16 @@ public: bool handle_event(const P3D_event_data &event); inline int get_instance_id() const; - inline const string &get_session_key() const; - const string &get_log_pathname() const; - inline const string &get_session_platform() const; + inline const std::string &get_session_key() const; + const std::string &get_log_pathname() const; + inline const std::string &get_session_platform() const; inline P3DSession *get_session() const; inline P3D_request_ready_func *get_request_ready_func() const; - void add_package(const string &name, const string &version, - const string &seq, P3DHost *host); + void add_package(const std::string &name, const std::string &version, + const std::string &seq, P3DHost *host); void add_package(P3DPackage *package); void remove_package(P3DPackage *package); bool get_packages_info_ready() const; @@ -161,14 +161,14 @@ private: IT_num_image_types, // Not a real value }; - void priv_set_p3d_filename(const string &p3d_filename, const int &p3d_offset = -1); - void determine_p3d_basename(const string &p3d_url); + void priv_set_p3d_filename(const std::string &p3d_filename, const int &p3d_offset = -1); + void determine_p3d_basename(const std::string &p3d_url); - bool check_matches_origin(const string &origin_match); - bool check_matches_origin_one(const string &origin_match); - bool check_matches_hostname(const string &orig, const string &match); - void separate_components(vector &components, const string &str); - bool check_matches_component(const string &orig, const string &match); + bool check_matches_origin(const std::string &origin_match); + bool check_matches_origin_one(const std::string &origin_match); + bool check_matches_hostname(const std::string &orig, const std::string &match); + void separate_components(std::vector &components, const std::string &str); + bool check_matches_component(const std::string &orig, const std::string &match); void check_p3d_signature(); void mark_p3d_untrusted(); @@ -176,15 +176,15 @@ private: void scan_app_desc_file(TiXmlDocument *doc); void add_panda3d_package(); void add_packages(); - string find_alt_host_url(const string &host_url, const string &alt_host); + std::string find_alt_host_url(const std::string &host_url, const std::string &alt_host); void get_host_info(P3DHost *host); - string get_start_dir_suffix() const; + std::string get_start_dir_suffix() const; void send_browser_script_object(); P3D_request *make_p3d_request(TiXmlElement *xrequest); - void handle_notify_request(const string &message); - void handle_script_request(const string &operation, P3D_object *object, - const string &property_name, P3D_object *value, + void handle_notify_request(const std::string &message); + void handle_script_request(const std::string &operation, P3D_object *object, + const std::string &property_name, P3D_object *value, bool needs_response, int unique_id); void set_failed(); @@ -201,7 +201,7 @@ private: size_t received_data); void report_package_progress(P3DPackage *package, double progress); void report_package_done(P3DPackage *package, bool success); - void set_install_label(const string &install_label); + void set_install_label(const std::string &install_label); void paint_window(); @@ -217,7 +217,7 @@ private: void add_carbon_modifier_flags(unsigned int &swb_flags, int modifiers); void add_cocoa_modifier_flags(unsigned int &swb_flags, int modifiers); - void send_notify(const string &message); + void send_notify(const std::string &message); #ifdef __APPLE__ void alloc_swbuffer(); @@ -228,10 +228,10 @@ private: P3D_request_ready_func *_func; P3D_object *_dom_object; P3DMainObject *_main_object; - string _p3d_basename; - string _origin_protocol; - string _origin_hostname; - string _origin_port; + std::string _p3d_basename; + std::string _origin_protocol; + std::string _origin_hostname; + std::string _origin_port; // We need a list of previous time reports so we can average the predicted // download time over the past few seconds. @@ -240,7 +240,7 @@ private: double _total; double _report_time; }; - typedef deque TimeReports; + typedef std::deque TimeReports; TimeReports _time_reports; double _total_time_reports; @@ -258,7 +258,7 @@ private: bool _use_standard_image; P3DTemporaryFile *_temp_filename; - string _filename; + std::string _filename; P3DSplashWindow::ImagePlacement _image_placement; }; ImageFile _image_files[IT_num_image_types]; @@ -283,11 +283,11 @@ private: P3DPackage *_p3dcert_package; int _instance_id; - string _session_key; - string _log_basename; - string _session_platform; - string _prc_name; - string _start_dir; + std::string _session_key; + std::string _log_basename; + std::string _session_platform; + std::string _prc_name; + std::string _start_dir; bool _hidden; bool _matches_run_origin; bool _matches_script_origin; @@ -301,14 +301,14 @@ private: P3DSession *_session; P3DAuthSession *_auth_session; - string _log_pathname; + std::string _log_pathname; #ifdef __APPLE__ // On OSX, we have to get a copy of the framebuffer data back from the child // process, and draw it to the window, here in the parent process. Crazy! int _shared_fd; size_t _shared_mmap_size; - string _shared_filename; + std::string _shared_filename; SubprocessWindowBuffer *_swbuffer; char *_reversed_buffer; CFDataRef _buffer_data; @@ -323,7 +323,7 @@ private: #endif // __APPLE__ P3DSplashWindow *_splash_window; - string _install_label; + std::string _install_label; bool _instance_window_opened; bool _instance_window_attached; bool _stuff_to_download; @@ -341,7 +341,7 @@ private: // for more than a couple of seconds. bool _show_dl_instance_progress; - typedef vector Packages; + typedef std::vector Packages; Packages _packages; Packages _downloading_packages; int _download_package_index; @@ -357,19 +357,19 @@ private: // it's in the above vector also. P3DPackage *_panda3d_package; - typedef map Downloads; + typedef std::map Downloads; Downloads _downloads; // The _raw_requests queue might be filled up by the read thread, so we // protect it in a lock. LOCK _request_lock; - typedef deque RawRequests; + typedef std::deque RawRequests; RawRequests _raw_requests; bool _requested_stop; // The _baked_requests queue is only touched in the main thread; no lock // needed. - typedef deque BakedRequests; + typedef std::deque BakedRequests; BakedRequests _baked_requests; friend class P3DSession; diff --git a/direct/src/plugin/p3dInstanceManager.I b/direct/src/plugin/p3dInstanceManager.I index 90a13c810a..3241fea0cf 100644 --- a/direct/src/plugin/p3dInstanceManager.I +++ b/direct/src/plugin/p3dInstanceManager.I @@ -73,7 +73,7 @@ get_api_version() const { * PANDA_PACKAGE_HOST_URL, but it might be set to something different by the * -u parameter on the panda3d executable. */ -inline const string &P3DInstanceManager:: +inline const std::string &P3DInstanceManager:: get_host_url() const { return _host_url; } @@ -83,7 +83,7 @@ get_host_url() const { * downloaded and installed. This must be a writable directory or nothing * will work. */ -inline const string &P3DInstanceManager:: +inline const std::string &P3DInstanceManager:: get_root_dir() const { return _root_dir; } @@ -92,7 +92,7 @@ get_root_dir() const { * Returns the directory that the .p3d file should be mounted to and run from. * This is usually the "start" subdirectory of the root_dir. */ -inline const string &P3DInstanceManager:: +inline const std::string &P3DInstanceManager:: get_start_dir() const { return _start_dir; } @@ -102,7 +102,7 @@ get_start_dir() const { * running. This string will be used to determine the appropriate packages to * download. */ -inline const string &P3DInstanceManager:: +inline const std::string &P3DInstanceManager:: get_platform() const { return _platform; } @@ -112,7 +112,7 @@ get_platform() const { * written. This filename will end with a slash, so that full pathnames may * be made by concatenting directly with this string. */ -inline const string &P3DInstanceManager:: +inline const std::string &P3DInstanceManager:: get_temp_directory() const { return _temp_directory; } @@ -122,7 +122,7 @@ get_temp_directory() const { * written. This filename will end with a slash, so that full pathnames may * be made by concatenting directly with this string. */ -inline const string &P3DInstanceManager:: +inline const std::string &P3DInstanceManager:: get_log_directory() const { return _log_directory; } @@ -133,7 +133,7 @@ get_log_directory() const { * different from the session log file(s), which represent the output from a * particular Python session. */ -inline const string &P3DInstanceManager:: +inline const std::string &P3DInstanceManager:: get_log_pathname() const { return _log_pathname; } @@ -187,7 +187,7 @@ get_num_supported_platforms() const { * environment will support, in order of preference--preferred platforms * appear first in the list. */ -inline const string &P3DInstanceManager:: +inline const std::string &P3DInstanceManager:: get_supported_platform(int n) const { return _supported_platforms.at(n); } @@ -230,7 +230,7 @@ get_plugin_official_version() const { * Returns the "distributor" reported by the plugin. This should represent * the entity that built and hosted the plugin. */ -inline const string &P3DInstanceManager:: +inline const std::string &P3DInstanceManager:: get_plugin_distributor() const { return _plugin_distributor; } @@ -240,7 +240,7 @@ get_plugin_distributor() const { * the plugin). This is for reporting purposes only; see get_host_url() for * the URL to contact to actually download content. */ -inline const string &P3DInstanceManager:: +inline const std::string &P3DInstanceManager:: get_coreapi_host_url() const { return _coreapi_host_url; } @@ -261,7 +261,7 @@ get_coreapi_timestamp() const { * not provide a number here. If provided, this will be a string of dot- * separated integers. */ -inline const string &P3DInstanceManager:: +inline const std::string &P3DInstanceManager:: get_coreapi_set_ver() const { return _coreapi_set_ver; } @@ -269,7 +269,7 @@ get_coreapi_set_ver() const { /** * Returns the "super mirror" URL. See p3d_plugin.h. */ -inline const string &P3DInstanceManager:: +inline const std::string &P3DInstanceManager:: get_super_mirror() const { return _super_mirror_url; } diff --git a/direct/src/plugin/p3dInstanceManager.cxx b/direct/src/plugin/p3dInstanceManager.cxx index 46a194e289..93e2ffcfc2 100644 --- a/direct/src/plugin/p3dInstanceManager.cxx +++ b/direct/src/plugin/p3dInstanceManager.cxx @@ -50,8 +50,12 @@ #include +using std::string; +using std::vector; +using std::wstring; + static ofstream logfile; -ostream *nout_stream = &logfile; +std::ostream *nout_stream = &logfile; P3DInstanceManager *P3DInstanceManager::_global_ptr; @@ -86,11 +90,11 @@ P3DInstanceManager() { _true_object = new P3DBoolObject(true); _false_object = new P3DBoolObject(false); - _auth_session = NULL; + _auth_session = nullptr; // Seed the lame random number generator in rand(); we use it to select a // mirror for downloading. - srand((unsigned int)time(NULL)); + srand((unsigned int)time(nullptr)); #ifdef _WIN32 // Ensure the appropriate Windows common controls are available to this @@ -127,7 +131,7 @@ P3DInstanceManager:: #ifndef _WIN32 // Restore the original SIGPIPE handler. - sigaction(SIGPIPE, &_old_sigpipe, NULL); + sigaction(SIGPIPE, &_old_sigpipe, nullptr); #endif // _WIN32 // force-finish any remaining instances. @@ -139,9 +143,9 @@ P3DInstanceManager:: assert(_sessions.empty()); assert(_instances.empty()); - if (_auth_session != NULL) { + if (_auth_session != nullptr) { p3d_unref_delete(_auth_session); - _auth_session = NULL; + _auth_session = nullptr; } Hosts::iterator hi; @@ -239,7 +243,7 @@ initialize(int api_version, const string &contents_filename, int mib[2] = { CTL_HW, HW_MACHINE }; char machine[512]; size_t len = 511; - if (sysctl(mib, 2, (void *)machine, &len, NULL, 0) == 0) { + if (sysctl(mib, 2, (void *)machine, &len, nullptr, 0) == 0) { if (strcmp(machine, "x86_64") == 0) { _supported_platforms.push_back("osx_amd64"); } @@ -285,7 +289,7 @@ initialize(int api_version, const string &contents_filename, if (root_dir.empty()) { _root_dir = find_root_dir(); if (_root_dir.empty()) { - cerr << "Could not find root directory.\n"; + std::cerr << "Could not find root directory.\n"; return false; } } else { @@ -400,7 +404,7 @@ set_plugin_version(int major, int minor, int sequence, nout << "Core API version: " << _coreapi_set_ver << "\n"; const char *timestamp_string = ctime(&_coreapi_timestamp); - if (timestamp_string == NULL) { + if (timestamp_string == nullptr) { timestamp_string = ""; } nout << "Core API date: " << timestamp_string << "\n"; @@ -541,12 +545,12 @@ finish_instance(P3DInstance *inst) { */ P3DAuthSession *P3DInstanceManager:: authorize_instance(P3DInstance *inst) { - if (_auth_session != NULL) { + if (_auth_session != nullptr) { // We only want one auth_session window open at a time, to minimize user // confusion, so close any previous window. _auth_session->shutdown(true); p3d_unref_delete(_auth_session); - _auth_session = NULL; + _auth_session = nullptr; } _auth_session = new P3DAuthSession(inst); @@ -566,7 +570,7 @@ validate_instance(P3D_instance *instance) { return (*ii); } - return NULL; + return nullptr; } /** @@ -583,7 +587,7 @@ check_request() { } } - return NULL; + return nullptr; } /** @@ -600,7 +604,7 @@ wait_request(double timeout) { int stop_tick = int(GetTickCount() + timeout * 1000.0); #else struct timeval stop_time; - gettimeofday(&stop_time, NULL); + gettimeofday(&stop_time, nullptr); int seconds = (int)floor(timeout); stop_time.tv_sec += seconds; @@ -612,7 +616,7 @@ wait_request(double timeout) { #endif _request_ready.acquire(); - if (check_request() != (P3DInstance *)NULL) { + if (check_request() != nullptr) { _request_ready.release(); return; } @@ -633,7 +637,7 @@ wait_request(double timeout) { timeout = remaining_ticks * 0.001; #else struct timeval now; - gettimeofday(&now, NULL); + gettimeofday(&now, nullptr); struct timeval remaining; remaining.tv_sec = stop_time.tv_sec - now.tv_sec; @@ -649,7 +653,7 @@ wait_request(double timeout) { timeout = remaining.tv_sec + remaining.tv_usec * 0.001; #endif - if (check_request() != (P3DInstance *)NULL) { + if (check_request() != nullptr) { _request_ready.release(); return; } @@ -713,7 +717,7 @@ get_unique_id() { */ void P3DInstanceManager:: signal_request_ready(P3DInstance *inst) { - if (inst->get_request_ready_func() != NULL) { + if (inst->get_request_ready_func() != nullptr) { // This instance requires asynchronous notifications of requests. Thus, // we should tell the notify thread to wake up and make the callback. _notify_ready.acquire(); @@ -765,7 +769,7 @@ make_temp_filename(const string &extension) { if (tid == 0) { tid = 1; } - int hash = ((clock() + _next_temp_filename_counter) * ((time(NULL) * tid) >> 8)) & 0xffffff; + int hash = ((clock() + _next_temp_filename_counter) * ((time(nullptr) * tid) >> 8)) & 0xffffff; ++_next_temp_filename_counter; char hex_code[10]; sprintf(hex_code, "%06x", hash); @@ -847,8 +851,8 @@ find_cert(X509 *cert) { vector::iterator si; for (si = contents.begin(); si != contents.end(); ++si) { string filename = this_cert_dir + "/" + (*si); - X509 *x509 = NULL; - FILE *fp = NULL; + X509 *x509 = nullptr; + FILE *fp = nullptr; #ifdef _WIN32 wstring filename_w; if (string_to_wstring(filename_w, filename)) { @@ -857,12 +861,12 @@ find_cert(X509 *cert) { #else // _WIN32 fp = fopen(filename.c_str(), "r"); #endif // _WIN32 - if (fp != NULL) { - x509 = PEM_read_X509(fp, NULL, NULL, (void *)""); + if (fp != nullptr) { + x509 = PEM_read_X509(fp, nullptr, nullptr, (void *)""); fclose(fp); } - if (x509 != NULL) { + if (x509 != nullptr) { string der2 = cert_to_der(x509); // We might as well save this cert in the table for next time, even if // it's not the one we're looking for right now. @@ -896,8 +900,8 @@ read_certlist(P3DPackage *package) { string suffix = basename.substr(basename.length() - 4); if (suffix == ".pem" || suffix == ".crt") { string filename = package->get_package_dir() + "/" + basename; - X509 *x509 = NULL; - FILE *fp = NULL; + X509 *x509 = nullptr; + FILE *fp = nullptr; #ifdef _WIN32 wstring filename_w; if (string_to_wstring(filename_w, filename)) { @@ -906,12 +910,12 @@ read_certlist(P3DPackage *package) { #else // _WIN32 fp = fopen(filename.c_str(), "r"); #endif // _WIN32 - if (fp != NULL) { - x509 = PEM_read_X509(fp, NULL, NULL, (void *)""); + if (fp != nullptr) { + x509 = PEM_read_X509(fp, nullptr, nullptr, (void *)""); fclose(fp); } - if (x509 != NULL) { + if (x509 != nullptr) { string der2 = cert_to_der(x509); _approved_certs.insert(der2); } @@ -952,7 +956,7 @@ get_cert_dir(X509 *cert) { */ string P3DInstanceManager:: cert_to_der(X509 *cert) { - int buffer_size = i2d_X509(cert, NULL); + int buffer_size = i2d_X509(cert, nullptr); unsigned char *buffer = new unsigned char[buffer_size]; unsigned char *p = buffer; i2d_X509(cert, &p); @@ -1001,7 +1005,7 @@ uninstall_all() { */ P3DInstanceManager *P3DInstanceManager:: get_global_ptr() { - if (_global_ptr == NULL) { + if (_global_ptr == nullptr) { _global_ptr = new P3DInstanceManager; } return _global_ptr; @@ -1013,9 +1017,9 @@ get_global_ptr() { */ void P3DInstanceManager:: delete_global_ptr() { - if (_global_ptr != NULL) { + if (_global_ptr != nullptr) { delete _global_ptr; - _global_ptr = NULL; + _global_ptr = nullptr; } } @@ -1072,13 +1076,13 @@ scan_directory(const string &dirname, vector &contents) { size_t orig_size = contents.size(); DIR *root = opendir(dirname.c_str()); - if (root == (DIR *)NULL) { + if (root == nullptr) { return false; } struct dirent *d; d = readdir(root); - while (d != (struct dirent *)NULL) { + while (d != nullptr) { if (d->d_name[0] != '.') { contents.push_back(d->d_name); } @@ -1306,19 +1310,19 @@ append_safe_dir(string &root, const string &basename) { */ void P3DInstanceManager:: create_runtime_environment() { - mkdir_complete(_log_directory, cerr); + mkdir_complete(_log_directory, std::cerr); logfile.close(); logfile.clear(); #ifdef _WIN32 wstring log_pathname_w; string_to_wstring(log_pathname_w, _log_pathname); - logfile.open(log_pathname_w.c_str(), ios::out | ios::trunc); + logfile.open(log_pathname_w.c_str(), std::ios::out | std::ios::trunc); #else - logfile.open(_log_pathname.c_str(), ios::out | ios::trunc); + logfile.open(_log_pathname.c_str(), std::ios::out | std::ios::trunc); #endif // _WIN32 if (logfile) { - logfile.setf(ios::unitbuf); + logfile.setf(std::ios::unitbuf); nout_stream = &logfile; } @@ -1347,13 +1351,13 @@ create_runtime_environment() { // $TEMP or $TMP being defined specifically, and if they are, we'll use // GetTempPath(); otherwise, we'll fall back to SHGetSpecialFolderPath(). - if (getenv("TEMP") != NULL || getenv("TMP") != NULL) { + if (getenv("TEMP") != nullptr || getenv("TMP") != nullptr) { if (GetTempPathW(MAX_PATH, buffer_1) != 0) { temp_directory_w = buffer_1; } } if (temp_directory_w.empty()) { - if (SHGetSpecialFolderPathW(NULL, buffer_1, CSIDL_INTERNET_CACHE, true)) { + if (SHGetSpecialFolderPathW(nullptr, buffer_1, CSIDL_INTERNET_CACHE, true)) { temp_directory_w = buffer_1; // That just *might* return a non-writable folder, if we're in Protected @@ -1379,9 +1383,9 @@ create_runtime_environment() { } // Also insist that the temp directory is fully specified. - size_t needs_size_2 = GetFullPathNameW(temp_directory_w.c_str(), 0, NULL, NULL); + size_t needs_size_2 = GetFullPathNameW(temp_directory_w.c_str(), 0, nullptr, nullptr); wchar_t *buffer_2 = new wchar_t[needs_size_2]; - if (GetFullPathNameW(temp_directory_w.c_str(), needs_size_2, buffer_2, NULL) != 0) { + if (GetFullPathNameW(temp_directory_w.c_str(), needs_size_2, buffer_2, nullptr) != 0) { temp_directory_w = buffer_2; } delete[] buffer_2; @@ -1428,7 +1432,7 @@ create_runtime_environment() { struct sigaction ignore; memset(&ignore, 0, sizeof(ignore)); ignore.sa_handler = SIG_IGN; - sigaction(SIGINT, &ignore, NULL); + sigaction(SIGINT, &ignore, nullptr); } #endif @@ -1482,9 +1486,9 @@ nt_thread_run() { for (ni = instances.begin(); ni != instances.end(); ++ni) { // TODO: a race condition here when instances are deleted. P3DInstance *inst = (*ni); - assert(inst != NULL); + assert(inst != nullptr); P3D_request_ready_func *func = inst->get_request_ready_func(); - if (func != NULL) { + if (func != nullptr) { (*func)(inst); } } @@ -1505,7 +1509,7 @@ supports_win64() { LPFN_ISWOW64PROCESS _IsWow64Process; _IsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle("kernel32"), "IsWow64Process"); - if (_IsWow64Process != NULL) { + if (_IsWow64Process != nullptr) { if (!_IsWow64Process(GetCurrentProcess(), &is_win64)) { is_win64 = false; } diff --git a/direct/src/plugin/p3dInstanceManager.h b/direct/src/plugin/p3dInstanceManager.h index a148c760a2..f175e90aeb 100644 --- a/direct/src/plugin/p3dInstanceManager.h +++ b/direct/src/plugin/p3dInstanceManager.h @@ -47,17 +47,17 @@ private: ~P3DInstanceManager(); public: - bool initialize(int api_version, const string &contents_filename, - const string &host_url, + bool initialize(int api_version, const std::string &contents_filename, + const std::string &host_url, P3D_verify_contents verify_contents, - const string &platform, - const string &log_directory, - const string &log_basename, + const std::string &platform, + const std::string &log_directory, + const std::string &log_basename, bool trusted_environment, bool console_environment, - const string &root_dir = "", - const string &host_dir = "", - const string &start_dir = ""); + const std::string &root_dir = "", + const std::string &host_dir = "", + const std::string &start_dir = ""); inline bool is_initialized() const; inline void reconsider_runtime_environment(); @@ -65,35 +65,35 @@ public: inline void reset_verify_contents(); inline int get_api_version() const; - inline const string &get_host_url() const; - inline const string &get_root_dir() const; - inline const string &get_start_dir() const; - inline const string &get_platform() const; - inline const string &get_temp_directory() const; - inline const string &get_log_directory() const; - inline const string &get_log_pathname() const; + inline const std::string &get_host_url() const; + inline const std::string &get_root_dir() const; + inline const std::string &get_start_dir() const; + inline const std::string &get_platform() const; + inline const std::string &get_temp_directory() const; + inline const std::string &get_log_directory() const; + inline const std::string &get_log_pathname() const; inline bool get_trusted_environment() const; inline bool get_console_environment() const; inline int get_num_supported_platforms() const; - inline const string &get_supported_platform(int n) const; + inline const std::string &get_supported_platform(int n) const; void set_plugin_version(int major, int minor, int sequence, - bool official, const string &distributor, - const string &coreapi_host_url, + bool official, const std::string &distributor, + const std::string &coreapi_host_url, time_t coreapi_timestamp, - const string &coreapi_set_ver); + const std::string &coreapi_set_ver); inline int get_plugin_major_version() const; inline int get_plugin_minor_version() const; inline int get_plugin_sequence_version() const; inline bool get_plugin_official_version() const; - inline const string &get_plugin_distributor() const; - inline const string &get_coreapi_host_url() const; + inline const std::string &get_plugin_distributor() const; + inline const std::string &get_coreapi_host_url() const; inline time_t get_coreapi_timestamp() const; - inline const string &get_coreapi_set_ver() const; + inline const std::string &get_coreapi_set_ver() const; - void set_super_mirror(const string &super_mirror_url); - inline const string &get_super_mirror() const; + void set_super_mirror(const std::string &super_mirror_url); + inline const std::string &get_super_mirror() const; P3DInstance * create_instance(P3D_request_ready_func *func, @@ -101,8 +101,8 @@ public: int argc, const char *argv[], void *user_data); bool set_p3d_filename(P3DInstance *inst, bool is_local, - const string &p3d_filename, const int &p3d_offset); - int make_p3d_stream(P3DInstance *inst, const string &p3d_url); + const std::string &p3d_filename, const int &p3d_offset); + int make_p3d_stream(P3DInstance *inst, const std::string &p3d_url); bool start_instance(P3DInstance *inst); void finish_instance(P3DInstance *inst); P3DAuthSession *authorize_instance(P3DInstance *inst); @@ -112,7 +112,7 @@ public: P3DInstance *check_request(); void wait_request(double timeout); - P3DHost *get_host(const string &host_url); + P3DHost *get_host(const std::string &host_url); void forget_host(P3DHost *host); inline int get_num_instances() const; @@ -126,13 +126,13 @@ public: inline P3D_object *new_none_object(); inline P3D_object *new_bool_object(bool value); - string make_temp_filename(const string &extension); - void release_temp_filename(const string &filename); + std::string make_temp_filename(const std::string &extension); + void release_temp_filename(const std::string &filename); bool find_cert(X509 *cert); void read_certlist(P3DPackage *package); - string get_cert_dir(X509 *cert); - static string cert_to_der(X509 *cert); + std::string get_cert_dir(X509 *cert); + static std::string cert_to_der(X509 *cert); void uninstall_all(); @@ -140,19 +140,19 @@ public: static void delete_global_ptr(); static inline char encode_hexdigit(int c); - static bool scan_directory(const string &dirname, vector &contents); - static bool scan_directory_recursively(const string &dirname, - vector &filename_contents, - vector &dirname_contents, - const string &prefix = ""); - static void delete_directory_recursively(const string &root_dir); - static bool remove_file_from_list(vector &contents, const string &filename); + static bool scan_directory(const std::string &dirname, std::vector &contents); + static bool scan_directory_recursively(const std::string &dirname, + std::vector &filename_contents, + std::vector &dirname_contents, + const std::string &prefix = ""); + static void delete_directory_recursively(const std::string &root_dir); + static bool remove_file_from_list(std::vector &contents, const std::string &filename); - static void append_safe_dir(string &root, const string &basename); + static void append_safe_dir(std::string &root, const std::string &basename); private: void create_runtime_environment(); - static void append_safe_dir_component(string &root, const string &component); + static void append_safe_dir_component(std::string &root, const std::string &component); private: // The notify thread. This thread runs only for the purpose of generating @@ -168,30 +168,30 @@ private: bool _is_initialized; bool _created_runtime_environment; int _api_version; - string _host_url; - string _root_dir; - string _host_dir; - string _start_dir; - string _certs_dir; + std::string _host_url; + std::string _root_dir; + std::string _host_dir; + std::string _start_dir; + std::string _certs_dir; P3D_verify_contents _verify_contents; - string _platform; - string _log_directory; - string _log_basename; - string _log_pathname; - string _temp_directory; + std::string _platform; + std::string _log_directory; + std::string _log_basename; + std::string _log_pathname; + std::string _temp_directory; bool _trusted_environment; bool _console_environment; int _plugin_major_version; int _plugin_minor_version; int _plugin_sequence_version; bool _plugin_official_version; - string _plugin_distributor; - string _coreapi_host_url; + std::string _plugin_distributor; + std::string _coreapi_host_url; time_t _coreapi_timestamp; - string _coreapi_set_ver; - string _super_mirror_url; + std::string _coreapi_set_ver; + std::string _super_mirror_url; - typedef vector SupportedPlatforms; + typedef std::vector SupportedPlatforms; SupportedPlatforms _supported_platforms; P3D_object *_undefined_object; @@ -199,20 +199,20 @@ private: P3D_object *_true_object; P3D_object *_false_object; - typedef set ApprovedCerts; + typedef std::set ApprovedCerts; ApprovedCerts _approved_certs; - typedef set Instances; + typedef std::set Instances; Instances _instances; P3DAuthSession *_auth_session; - typedef map Sessions; + typedef std::map Sessions; Sessions _sessions; - typedef map Hosts; + typedef std::map Hosts; Hosts _hosts; - typedef set TempFilenames; + typedef std::set TempFilenames; TempFilenames _temp_filenames; int _next_temp_filename_counter; @@ -228,7 +228,7 @@ private: THREAD _notify_thread; // This queue of instances that need to send notifications is protected by // _notify_ready's mutex. - typedef vector NotifyInstances; + typedef std::vector NotifyInstances; NotifyInstances _notify_instances; P3DConditionVar _notify_ready; diff --git a/direct/src/plugin/p3dIntObject.cxx b/direct/src/plugin/p3dIntObject.cxx index 4fa4b14aaf..05ad970128 100644 --- a/direct/src/plugin/p3dIntObject.cxx +++ b/direct/src/plugin/p3dIntObject.cxx @@ -59,8 +59,8 @@ get_int() { * to a string. */ void P3DIntObject:: -make_string(string &value) { - ostringstream strm; +make_string(std::string &value) { + std::ostringstream strm; strm << _value; value = strm.str(); } diff --git a/direct/src/plugin/p3dIntObject.h b/direct/src/plugin/p3dIntObject.h index 899e422142..d77c0d689a 100644 --- a/direct/src/plugin/p3dIntObject.h +++ b/direct/src/plugin/p3dIntObject.h @@ -29,7 +29,7 @@ public: virtual P3D_object_type get_type(); virtual bool get_bool(); virtual int get_int(); - virtual void make_string(string &value); + virtual void make_string(std::string &value); private: int _value; diff --git a/direct/src/plugin/p3dMainObject.cxx b/direct/src/plugin/p3dMainObject.cxx index c905c8805b..2fd8dba33d 100644 --- a/direct/src/plugin/p3dMainObject.cxx +++ b/direct/src/plugin/p3dMainObject.cxx @@ -18,13 +18,18 @@ #include "p3dStringObject.h" #include "p3dInstanceManager.h" +using std::ios; +using std::max; +using std::streamsize; +using std::string; + /** * */ P3DMainObject:: P3DMainObject() : - _pyobj(NULL), - _inst(NULL), + _pyobj(nullptr), + _inst(nullptr), _unauth_play(false) { } @@ -34,7 +39,7 @@ P3DMainObject() : */ P3DMainObject:: ~P3DMainObject() { - set_pyobj(NULL); + set_pyobj(nullptr); // Clear the local properties. Properties::const_iterator pi; @@ -83,10 +88,10 @@ get_float() { */ void P3DMainObject:: make_string(string &value) { - if (_pyobj == NULL) { + if (_pyobj == nullptr) { value = "P3DMainObject"; } else { - int size = P3D_OBJECT_GET_STRING(_pyobj, NULL, 0); + int size = P3D_OBJECT_GET_STRING(_pyobj, nullptr, 0); char *buffer = new char[size]; P3D_OBJECT_GET_STRING(_pyobj, buffer, size); value = string(buffer, size); @@ -100,7 +105,7 @@ make_string(string &value) { */ P3D_object *P3DMainObject:: get_property(const string &property) { - if (_pyobj == NULL) { + if (_pyobj == nullptr) { // Without a pyobj, we just report whatever's been stored locally. Properties::const_iterator pi; pi = _properties.find(property); @@ -109,7 +114,7 @@ get_property(const string &property) { P3D_OBJECT_INCREF(result); return result; } - return NULL; + return nullptr; } // With a pyobj, we pass the query down to it. @@ -123,9 +128,9 @@ get_property(const string &property) { bool P3DMainObject:: set_property(const string &property, bool needs_response, P3D_object *value) { // First, we set the property locally. - if (value != NULL) { + if (value != nullptr) { Properties::iterator pi; - pi = _properties.insert(Properties::value_type(property, (P3D_object *)NULL)).first; + pi = _properties.insert(Properties::value_type(property, nullptr)).first; assert(pi != _properties.end()); P3D_object *orig_value = (*pi).second; if (orig_value != value) { @@ -144,7 +149,7 @@ set_property(const string &property, bool needs_response, P3D_object *value) { } } - if (_pyobj == NULL) { + if (_pyobj == nullptr) { // Without a pyobj, that's all we do. return true; } @@ -171,7 +176,7 @@ has_method(const string &method_name) { return true; } - if (_pyobj == NULL) { + if (_pyobj == nullptr) { // No methods until we get our pyobj. return false; } @@ -197,7 +202,7 @@ call(const string &method_name, bool needs_response, if (i != 0) { nout << ", "; } - int buffer_size = P3D_OBJECT_GET_REPR(params[i], NULL, 0); + int buffer_size = P3D_OBJECT_GET_REPR(params[i], nullptr, 0); char *buffer = new char[buffer_size]; P3D_OBJECT_GET_REPR(params[i], buffer, buffer_size); nout.write(buffer, buffer_size); @@ -217,9 +222,9 @@ call(const string &method_name, bool needs_response, return call_uninstall(params, num_params); } - if (_pyobj == NULL) { + if (_pyobj == nullptr) { // No methods until we get our pyobj. - return NULL; + return nullptr; } return P3D_OBJECT_CALL(_pyobj, method_name.c_str(), needs_response, @@ -231,7 +236,7 @@ call(const string &method_name, bool needs_response, * This is intended for developer assistance. */ void P3DMainObject:: -output(ostream &out) { +output(std::ostream &out) { out << "P3DMainObject"; } @@ -251,9 +256,9 @@ set_pyobj(P3D_object *pyobj) { // actually need to set the reference; instead, we clear anything we had // set. nout << "application shares main object\n"; - pyobj = NULL; + pyobj = nullptr; - } else if (pyobj != NULL) { + } else if (pyobj != nullptr) { // In the alternate case, the application has its own, separate // appRunner.main object. Thus, we do need to set the pointer. nout << "application has its own main object\n"; @@ -262,7 +267,7 @@ set_pyobj(P3D_object *pyobj) { if (_pyobj != pyobj) { P3D_OBJECT_XDECREF(_pyobj); _pyobj = pyobj; - if (_pyobj != NULL) { + if (_pyobj != nullptr) { P3D_OBJECT_INCREF(_pyobj); // Now that we have a pyobj, we have to transfer down all of the @@ -288,7 +293,7 @@ get_pyobj() const { */ void P3DMainObject:: apply_properties(P3D_object *pyobj) { - P3DPythonObject *p3dpyobj = NULL; + P3DPythonObject *p3dpyobj = nullptr; if (pyobj->_class == &P3DObject::_object_class) { p3dpyobj = ((P3DObject *)pyobj)->as_python_object(); } @@ -297,7 +302,7 @@ apply_properties(P3D_object *pyobj) { for (pi = _properties.begin(); pi != _properties.end(); ++pi) { const string &property_name = (*pi).first; P3D_object *value = (*pi).second; - if (p3dpyobj != NULL && P3D_OBJECT_GET_TYPE(value) != P3D_OT_object) { + if (p3dpyobj != nullptr && P3D_OBJECT_GET_TYPE(value) != P3D_OT_object) { // If we know we have an actual P3DPythonObject (we really expect this), // then we can call set_property_insecure() directly, because we want to // allow setting the initial properties even if Javascript has no @@ -317,7 +322,7 @@ apply_properties(P3D_object *pyobj) { */ void P3DMainObject:: set_instance(P3DInstance *inst) { - if (_inst != NULL) { + if (_inst != nullptr) { // Save the game log filename of the instance just before it goes away, in // case JavaScript asks for it later. _game_log_pathname = _inst->get_log_pathname(); @@ -341,7 +346,7 @@ set_instance(P3DInstance *inst) { P3D_object *P3DMainObject:: call_play(P3D_object *params[], int num_params) { P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); - if (_inst == NULL) { + if (_inst == nullptr) { return inst_mgr->new_bool_object(false); } @@ -372,7 +377,7 @@ call_play(P3D_object *params[], int num_params) { */ P3D_object *P3DMainObject:: call_read_game_log(P3D_object *params[], int num_params) { - if (_inst != NULL) { + if (_inst != nullptr) { string log_pathname = _inst->get_log_pathname(); return read_log(log_pathname, params, num_params); } @@ -413,7 +418,7 @@ call_read_log(P3D_object *params[], int num_params) { return inst_mgr->new_undefined_object(); } - int size = P3D_OBJECT_GET_STRING(params[0], NULL, 0); + int size = P3D_OBJECT_GET_STRING(params[0], nullptr, 0); char *buffer = new char[size]; P3D_OBJECT_GET_STRING(params[0], buffer, size); string log_filename = string(buffer, size); @@ -459,7 +464,7 @@ P3D_object *P3DMainObject:: read_log(const string &log_pathname, P3D_object *params[], int num_params) { P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); string log_directory = inst_mgr->get_log_directory(); - ostringstream log_data; + std::ostringstream log_data; // Check the first parameter, if any--if given, it specifies the last n // bytes to retrieve. @@ -512,7 +517,7 @@ read_log(const string &log_pathname, P3D_object *params[], int num_params) { } // Read matching files - vector all_logs; + std::vector all_logs; int log_matches_found = 0; string log_matching_pathname; inst_mgr->scan_directory(log_directory, all_logs); @@ -544,7 +549,7 @@ read_log(const string &log_pathname, P3D_object *params[], int num_params) { void P3DMainObject:: read_log_file(const string &log_pathname, size_t tail_bytes, size_t head_bytes, - ostringstream &log_data) { + std::ostringstream &log_data) { // Get leaf name string log_leafname = log_pathname; @@ -599,7 +604,7 @@ read_log_file(const string &log_pathname, size_t buffer_bytes = max(max(full_bytes, head_bytes), tail_bytes) + 1; nout << "allocating " << buffer_bytes << " bytes to read at a time from file of size " << file_size << ".\n"; char *buffer = new char[buffer_bytes]; - if (buffer == NULL) { + if (buffer == nullptr) { log_data << "== PandaLog-" << "Error allocating buffer"; log_data << " " << "(" << log_leafname << ")" << "\n"; return; @@ -659,7 +664,7 @@ read_log_file(const string &log_pathname, // cleanup delete[] buffer; - buffer = NULL; + buffer = nullptr; } /** @@ -673,7 +678,7 @@ call_uninstall(P3D_object *params[], int num_params) { // Get the first parameter, the uninstall mode. string mode; if (num_params > 0) { - int size = P3D_OBJECT_GET_STRING(params[0], NULL, 0); + int size = P3D_OBJECT_GET_STRING(params[0], nullptr, 0); char *buffer = new char[size]; P3D_OBJECT_GET_STRING(params[0], buffer, size); mode = string(buffer, size); @@ -686,7 +691,7 @@ call_uninstall(P3D_object *params[], int num_params) { return inst_mgr->new_bool_object(true); } - if (_inst != NULL) { + if (_inst != nullptr) { nout << "uninstall " << mode << " for " << _inst << "\n"; bool success = false; if (mode == "host") { diff --git a/direct/src/plugin/p3dMainObject.h b/direct/src/plugin/p3dMainObject.h index 7ed634c44c..fafad0ff16 100644 --- a/direct/src/plugin/p3dMainObject.h +++ b/direct/src/plugin/p3dMainObject.h @@ -45,17 +45,17 @@ public: virtual int get_int(); virtual double get_float(); - virtual void make_string(string &value); + virtual void make_string(std::string &value); - virtual P3D_object *get_property(const string &property); - virtual bool set_property(const string &property, bool needs_response, + virtual P3D_object *get_property(const std::string &property); + virtual bool set_property(const std::string &property, bool needs_response, P3D_object *value); - virtual bool has_method(const string &method_name); - virtual P3D_object *call(const string &method_name, bool needs_response, + virtual bool has_method(const std::string &method_name); + virtual P3D_object *call(const std::string &method_name, bool needs_response, P3D_object *params[], int num_params); - virtual void output(ostream &out); + virtual void output(std::ostream &out); void set_pyobj(P3D_object *pyobj); P3D_object *get_pyobj() const; @@ -68,11 +68,11 @@ private: P3D_object *call_read_game_log(P3D_object *params[], int num_params); P3D_object *call_read_system_log(P3D_object *params[], int num_params); P3D_object *call_read_log(P3D_object *params[], int num_params); - P3D_object *read_log(const string &log_pathname, + P3D_object *read_log(const std::string &log_pathname, P3D_object *params[], int num_params); - void read_log_file(const string &log_pathname, + void read_log_file(const std::string &log_pathname, size_t tail_bytes, size_t head_bytes, - ostringstream &log_data); + std::ostringstream &log_data); P3D_object *call_uninstall(P3D_object *params[], int num_params); private: @@ -80,12 +80,12 @@ private: P3DInstance *_inst; bool _unauth_play; - string _game_log_pathname; + std::string _game_log_pathname; // This map is used to store properties and retrieve until set_pyobj() is // called for the firs ttime. At that point, the properties stored here are // transferred down to the internal PyObject. - typedef map Properties; + typedef std::map Properties; Properties _properties; }; diff --git a/direct/src/plugin/p3dMultifileReader.I b/direct/src/plugin/p3dMultifileReader.I index eb072e0a3b..ff3daf31b8 100644 --- a/direct/src/plugin/p3dMultifileReader.I +++ b/direct/src/plugin/p3dMultifileReader.I @@ -48,7 +48,7 @@ read_uint32() { */ inline size_t P3DMultifileReader::Subfile:: get_last_byte_pos() const { - return max(_index_start + _index_length, _data_start + _data_length) - 1; + return std::max(_index_start + _index_length, _data_start + _data_length) - 1; } /** diff --git a/direct/src/plugin/p3dMultifileReader.cxx b/direct/src/plugin/p3dMultifileReader.cxx index 2ab529f887..e47400bdb6 100644 --- a/direct/src/plugin/p3dMultifileReader.cxx +++ b/direct/src/plugin/p3dMultifileReader.cxx @@ -23,6 +23,13 @@ #include #endif +using std::ios; +using std::max; +using std::min; +using std::streampos; +using std::streamsize; +using std::string; + // This sequence of bytes begins each Multifile to identify it as a Multifile. const char P3DMultifileReader::_header[] = "pmf\0\n\r"; const size_t P3DMultifileReader::_header_size = 6; @@ -88,7 +95,7 @@ extract_all(const string &to_dir, P3DPackage *package, for (si = _subfiles.begin(); si != _subfiles.end(); ++si) { const Subfile &s = (*si); FileSpec file; - if (package != NULL && !package->is_extractable(file, s._filename)) { + if (package != nullptr && !package->is_extractable(file, s._filename)) { continue; } @@ -99,7 +106,7 @@ extract_all(const string &to_dir, P3DPackage *package, ofstream out; #ifdef _WIN32 - wstring output_pathname_w; + std::wstring output_pathname_w; if (string_to_wstring(output_pathname_w, output_pathname)) { out.open(output_pathname_w.c_str(), ios::out | ios::binary); } @@ -127,7 +134,7 @@ extract_all(const string &to_dir, P3DPackage *package, // or something. chmod(output_pathname.c_str(), 0555); - if (step != NULL && package != NULL) { + if (step != nullptr && package != nullptr) { step->thread_add_bytes_done(s._data_length); } } @@ -140,7 +147,7 @@ extract_all(const string &to_dir, P3DPackage *package, * stream. Returns true on success, false on failure. */ bool P3DMultifileReader:: -extract_one(ostream &out, const string &filename) { +extract_one(std::ostream &out, const string &filename) { assert(_is_open); if (_in.fail()) { return false; @@ -202,7 +209,7 @@ read_header(const string &pathname) { _signatures.clear(); #ifdef _WIN32 - wstring pathname_w; + std::wstring pathname_w; if (string_to_wstring(pathname_w, pathname)) { _in.open(pathname_w.c_str(), ios::in | ios::binary); } @@ -341,7 +348,7 @@ read_index() { * Returns true on success, false on failure. */ bool P3DMultifileReader:: -extract_subfile(ostream &out, const Subfile &s) { +extract_subfile(std::ostream &out, const Subfile &s) { _in.seekg(s._data_start + _read_offset); static const streamsize buffer_size = 4096; @@ -409,7 +416,7 @@ check_signatures() { // Now convert each of the certificates to an X509 object, and store it in // our CertChain. CertChain chain; - EVP_PKEY *pkey = NULL; + EVP_PKEY *pkey = nullptr; if (buffer_size > 0) { #if OPENSSL_VERSION_NUMBER >= 0x00908000L // Beginning in 0.9.8, d2i_X509() accepted a const unsigned char **. @@ -420,13 +427,13 @@ check_signatures() { #endif bp = (unsigned char *)&buffer[0]; bp_end = bp + buffer_size; - X509 *x509 = d2i_X509(NULL, &bp, bp_end - bp); - while (num_certs > 0 && x509 != NULL) { + X509 *x509 = d2i_X509(nullptr, &bp, bp_end - bp); + while (num_certs > 0 && x509 != nullptr) { chain.push_back(CertRecord(x509)); --num_certs; - x509 = d2i_X509(NULL, &bp, bp_end - bp); + x509 = d2i_X509(nullptr, &bp, bp_end - bp); } - if (num_certs != 0 || x509 != NULL) { + if (num_certs != 0 || x509 != nullptr) { nout << "Extra data in signature record.\n"; } } @@ -437,7 +444,7 @@ check_signatures() { pkey = X509_get_pubkey(chain[0]._cert); } - if (pkey != NULL) { + if (pkey != nullptr) { EVP_MD_CTX *md_ctx; #if OPENSSL_VERSION_NUMBER >= 0x00907000L md_ctx = EVP_MD_CTX_create(); diff --git a/direct/src/plugin/p3dMultifileReader.h b/direct/src/plugin/p3dMultifileReader.h index 64a788c263..8f80a1f67c 100644 --- a/direct/src/plugin/p3dMultifileReader.h +++ b/direct/src/plugin/p3dMultifileReader.h @@ -27,14 +27,14 @@ class P3DMultifileReader { public: P3DMultifileReader(); - bool open_read(const string &pathname, const int &offset = 0); + bool open_read(const std::string &pathname, const int &offset = 0); inline bool is_open() const; void close(); - bool extract_all(const string &to_dir, P3DPackage *package, + bool extract_all(const std::string &to_dir, P3DPackage *package, P3DPackage::InstallStepThreaded *step); - bool extract_one(ostream &out, const string &filename); + bool extract_one(std::ostream &out, const std::string &filename); class CertRecord { public: @@ -43,16 +43,16 @@ public: inline ~CertRecord(); X509 *_cert; }; - typedef vector CertChain; + typedef std::vector CertChain; int get_num_signatures() const; const CertChain &get_signature(int n) const; private: class Subfile; - bool read_header(const string &pathname); + bool read_header(const std::string &pathname); bool read_index(); - bool extract_subfile(ostream &out, const Subfile &s); + bool extract_subfile(std::ostream &out, const Subfile &s); void check_signatures(); @@ -73,7 +73,7 @@ private: public: inline size_t get_last_byte_pos() const; - string _filename; + std::string _filename; size_t _index_start; size_t _index_length; size_t _data_start; @@ -85,12 +85,12 @@ private: bool _is_open; int _read_offset; - typedef vector Subfiles; + typedef std::vector Subfiles; Subfiles _subfiles; Subfiles _cert_special; size_t _last_data_byte; - typedef vector Certificates; + typedef std::vector Certificates; Certificates _signatures; static const char _header[]; diff --git a/direct/src/plugin/p3dNoneObject.cxx b/direct/src/plugin/p3dNoneObject.cxx index 0245b61174..2a1653a2b8 100644 --- a/direct/src/plugin/p3dNoneObject.cxx +++ b/direct/src/plugin/p3dNoneObject.cxx @@ -41,6 +41,6 @@ get_bool() { * to a string. */ void P3DNoneObject:: -make_string(string &value) { +make_string(std::string &value) { value = "None"; } diff --git a/direct/src/plugin/p3dNoneObject.h b/direct/src/plugin/p3dNoneObject.h index e0272f04cb..06fffe89f9 100644 --- a/direct/src/plugin/p3dNoneObject.h +++ b/direct/src/plugin/p3dNoneObject.h @@ -28,7 +28,7 @@ public: public: virtual P3D_object_type get_type(); virtual bool get_bool(); - virtual void make_string(string &value); + virtual void make_string(std::string &value); }; #endif diff --git a/direct/src/plugin/p3dObject.cxx b/direct/src/plugin/p3dObject.cxx index 5f17ee3e2e..f34f2d6d2d 100644 --- a/direct/src/plugin/p3dObject.cxx +++ b/direct/src/plugin/p3dObject.cxx @@ -19,6 +19,8 @@ #include "p3dInstanceManager.h" #include // strncpy +using std::string; + // The following functions are C-style wrappers around the below P3DObject // virtual methods; they are defined to allow us to create the C-style // P3D_class_definition method table to store in the P3D_object structure. @@ -77,7 +79,7 @@ static P3D_object * object_call(P3D_object *object, const char *method_name, bool needs_response, P3D_object *params[], int num_params) { - if (method_name == NULL) { + if (method_name == nullptr) { method_name = ""; } return ((P3DObject *)object)->call(method_name, needs_response, params, num_params); @@ -147,7 +149,7 @@ generic_get_repr(P3D_object *object, char *buffer, int buffer_length) { static P3D_object * generic_get_property(P3D_object *object, const char *property) { - return NULL; + return nullptr; } static bool @@ -164,12 +166,12 @@ generic_has_method(P3D_object *object, const char *method_name) { static P3D_object * generic_call(P3D_object *object, const char *method_name, bool needs_response, P3D_object *params[], int num_params) { - return NULL; + return nullptr; } static P3D_object * generic_eval(P3D_object *object, const char *expression) { - return NULL; + return nullptr; } P3D_class_definition P3DObject::_generic_class = { @@ -231,7 +233,7 @@ get_string(char *buffer, int buffer_length) { */ int P3DObject:: get_repr(char *buffer, int buffer_length) { - ostringstream strm; + std::ostringstream strm; output(strm); string result = strm.str(); strncpy(buffer, result.c_str(), buffer_length); @@ -244,7 +246,7 @@ get_repr(char *buffer, int buffer_length) { */ P3D_object *P3DObject:: get_property(const string &property) { - return NULL; + return nullptr; } /** @@ -275,7 +277,7 @@ has_method(const string &method_name) { P3D_object *P3DObject:: call(const string &method_name, bool needs_response, P3D_object *params[], int num_params) { - return NULL; + return nullptr; } /** @@ -284,7 +286,7 @@ call(const string &method_name, bool needs_response, */ P3D_object *P3DObject:: eval(const string &expression) { - return NULL; + return nullptr; } /** @@ -292,7 +294,7 @@ eval(const string &expression) { * This is intended for developer assistance. */ void P3DObject:: -output(ostream &out) { +output(std::ostream &out) { string value; make_string(value); out << value; @@ -317,7 +319,7 @@ fill_xml(TiXmlElement *xvalue, P3DSession *session) { */ P3D_object **P3DObject:: get_object_array() { - return NULL; + return nullptr; } /** @@ -335,7 +337,7 @@ get_object_array_size() { */ P3DPythonObject *P3DObject:: as_python_object() { - return NULL; + return nullptr; } /** @@ -345,7 +347,7 @@ as_python_object() { bool P3DObject:: get_bool_property(const string &property) { P3D_object *result = get_property(property); - if (result == NULL) { + if (result == nullptr) { return 0; } bool bresult = P3D_OBJECT_GET_BOOL(result); @@ -370,7 +372,7 @@ set_bool_property(const string &property, bool value) { int P3DObject:: get_int_property(const string &property) { P3D_object *result = get_property(property); - if (result == NULL) { + if (result == nullptr) { return 0; } int iresult = P3D_OBJECT_GET_INT(result); @@ -395,7 +397,7 @@ set_int_property(const string &property, int value) { double P3DObject:: get_float_property(const string &property) { P3D_object *result = get_property(property); - if (result == NULL) { + if (result == nullptr) { return 0.0; } double fresult = P3D_OBJECT_GET_FLOAT(result); @@ -421,11 +423,11 @@ set_float_property(const string &property, double value) { string P3DObject:: get_string_property(const string &property) { P3D_object *result = get_property(property); - if (result == NULL) { + if (result == nullptr) { return string(); } - int size = P3D_OBJECT_GET_STRING(result, NULL, 0); + int size = P3D_OBJECT_GET_STRING(result, nullptr, 0); char *buffer = new char[size]; P3D_OBJECT_GET_STRING(result, buffer, size); string sresult(buffer, size); diff --git a/direct/src/plugin/p3dObject.h b/direct/src/plugin/p3dObject.h index 0cedd291ad..8e69e5bec7 100644 --- a/direct/src/plugin/p3dObject.h +++ b/direct/src/plugin/p3dObject.h @@ -39,18 +39,18 @@ public: int get_string(char *buffer, int buffer_length); int get_repr(char *buffer, int buffer_length); - virtual void make_string(string &value)=0; + virtual void make_string(std::string &value)=0; - virtual P3D_object *get_property(const string &property); - virtual bool set_property(const string &property, bool needs_response, + virtual P3D_object *get_property(const std::string &property); + virtual bool set_property(const std::string &property, bool needs_response, P3D_object *value); - virtual bool has_method(const string &method_name); - virtual P3D_object *call(const string &method_name, bool needs_response, + virtual bool has_method(const std::string &method_name); + virtual P3D_object *call(const std::string &method_name, bool needs_response, P3D_object *params[], int num_params); - virtual P3D_object *eval(const string &expression); + virtual P3D_object *eval(const std::string &expression); - virtual void output(ostream &out); + virtual void output(std::ostream &out); virtual bool fill_xml(TiXmlElement *xvalue, P3DSession *session); virtual P3D_object **get_object_array(); virtual int get_object_array_size(); @@ -58,19 +58,19 @@ public: virtual P3DPythonObject *as_python_object(); // Convenience functions. - bool get_bool_property(const string &property); - void set_bool_property(const string &property, bool value); + bool get_bool_property(const std::string &property); + void set_bool_property(const std::string &property, bool value); - int get_int_property(const string &property); - void set_int_property(const string &property, int value); + int get_int_property(const std::string &property); + void set_int_property(const std::string &property, int value); - double get_float_property(const string &property); - void set_float_property(const string &property, double value); + double get_float_property(const std::string &property); + void set_float_property(const std::string &property, double value); - string get_string_property(const string &property); - void set_string_property(const string &property, const string &value); + std::string get_string_property(const std::string &property); + void set_string_property(const std::string &property, const std::string &value); - void set_undefined_property(const string &property); + void set_undefined_property(const std::string &property); public: static P3D_class_definition _object_class; @@ -83,7 +83,7 @@ public: // method to write the output simply. (For classes that inherit only from // P3D_object, we have to use the generic C method defined in // p3d_plugin_common.h, a little clumsier.) -inline ostream &operator << (ostream &out, P3DObject &value) { +inline std::ostream &operator << (std::ostream &out, P3DObject &value) { value.output(out); return out; } diff --git a/direct/src/plugin/p3dOsxSplashWindow.I b/direct/src/plugin/p3dOsxSplashWindow.I index 4778fd40cc..a9573dafa4 100644 --- a/direct/src/plugin/p3dOsxSplashWindow.I +++ b/direct/src/plugin/p3dOsxSplashWindow.I @@ -16,11 +16,11 @@ */ inline P3DOsxSplashWindow::OsxImageData:: OsxImageData() { - _raw_data = NULL; - _image = NULL; - _color_space = NULL; - _provider = NULL; - _data = NULL; + _raw_data = nullptr; + _image = nullptr; + _color_space = nullptr; + _provider = nullptr; + _data = nullptr; } /** diff --git a/direct/src/plugin/p3dOsxSplashWindow.cxx b/direct/src/plugin/p3dOsxSplashWindow.cxx index c8fc969679..4139a9629d 100644 --- a/direct/src/plugin/p3dOsxSplashWindow.cxx +++ b/direct/src/plugin/p3dOsxSplashWindow.cxx @@ -26,6 +26,8 @@ #endif #endif +using std::string; + /** * */ @@ -33,7 +35,7 @@ P3DOsxSplashWindow:: P3DOsxSplashWindow(P3DInstance *inst, bool make_visible) : P3DSplashWindow(inst, make_visible) { - _font_attribs = NULL; + _font_attribs = nullptr; _install_progress = 0; _progress_known = true; _received_data = 0; @@ -41,7 +43,7 @@ P3DOsxSplashWindow(P3DInstance *inst, bool make_visible) : // We have to start with _mouse_active true; firefox doesn't send activate // events. _mouse_active = true; - _toplevel_window = NULL; + _toplevel_window = nullptr; } /** @@ -49,13 +51,13 @@ P3DOsxSplashWindow(P3DInstance *inst, bool make_visible) : */ P3DOsxSplashWindow:: ~P3DOsxSplashWindow() { - if (_toplevel_window != NULL) { + if (_toplevel_window != nullptr) { SetWRefCon(_toplevel_window, 0); HideWindow(_toplevel_window); DisposeWindow(_toplevel_window); - _toplevel_window = NULL; + _toplevel_window = nullptr; } - if (_font_attribs != NULL) { + if (_font_attribs != nullptr) { CFRelease(_font_attribs); } } @@ -72,7 +74,7 @@ set_wparams(const P3DWindowParams &wparams) { if (_wparams.get_window_type() == P3D_WT_toplevel || _wparams.get_window_type() == P3D_WT_fullscreen) { // Creating a toplevel splash window. - if (_toplevel_window == NULL) { + if (_toplevel_window == nullptr) { Rect r; r.top = _wparams.get_win_y(); r.left = _wparams.get_win_x(); @@ -134,7 +136,7 @@ set_wparams(const P3DWindowParams &wparams) { CFTypeRef traits_values[1] = { symbolic_ref }; CFDictionaryRef traits = CFDictionaryCreate(kCFAllocatorDefault, (const void **)&traits_keys, (const void **)&traits_values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - CFStringRef family = CFStringCreateWithCString(NULL, _font_family.c_str(), kCFStringEncodingUTF8); + CFStringRef family = CFStringCreateWithCString(nullptr, _font_family.c_str(), kCFStringEncodingUTF8); CFStringRef attribs_keys[2] = { kCTFontFamilyNameAttribute, kCTFontTraitsAttribute }; CFTypeRef attribs_values[2] = { family, traits }; @@ -142,7 +144,7 @@ set_wparams(const P3DWindowParams &wparams) { // Create the font object. CTFontDescriptorRef font_desc = CTFontDescriptorCreateWithAttributes(attribs); - CTFontRef font = CTFontCreateWithFontDescriptor(font_desc, _font_size, NULL); + CTFontRef font = CTFontCreateWithFontDescriptor(font_desc, _font_size, nullptr); CFStringRef keys[1] = { kCTFontAttributeName }; CFTypeRef values[1] = { font }; @@ -164,7 +166,7 @@ void P3DOsxSplashWindow:: set_visible(bool visible) { P3DSplashWindow::set_visible(visible); - if (_toplevel_window != NULL) { + if (_toplevel_window != nullptr) { if (_visible) { ShowWindow(_toplevel_window); } else { @@ -266,7 +268,7 @@ refresh() { if (!_visible) { return; } - if (_toplevel_window != NULL) { + if (_toplevel_window != nullptr) { Rect r = { 0, 0, (short)_win_height, (short)_win_width }; InvalWindowRect(_toplevel_window, &r); @@ -284,13 +286,13 @@ paint_window() { return; } - if (_toplevel_window != NULL || + if (_toplevel_window != nullptr || _wparams.get_parent_window()._window_handle_type == P3D_WHT_osx_port) { // The old QuickDraw-style window handle. We use CreateCGContextForPort() // to map this to the new CoreGraphics-style. - GrafPtr out_port = NULL; - if (_toplevel_window != NULL) { + GrafPtr out_port = nullptr; + if (_toplevel_window != nullptr) { GetPort(&out_port); } else { @@ -394,13 +396,13 @@ handle_event_osx_event_record(const P3D_event_data &event) { const P3D_window_handle &handle = _wparams.get_parent_window(); if (handle._window_handle_type == P3D_WHT_osx_port) { GrafPtr out_port = handle._handle._osx_port._port; - GrafPtr port_save = NULL; + GrafPtr port_save = nullptr; Boolean port_changed = QDSwapPort(out_port, &port_save); GlobalToLocal(&pt); if (port_changed) { - QDSwapPort(port_save, NULL); + QDSwapPort(port_save, nullptr); } } else if (handle._window_handle_type == P3D_WHT_osx_cgcontext) { @@ -408,7 +410,7 @@ handle_event_osx_event_record(const P3D_event_data &event) { // window coordinates. WindowRef window = handle._handle._osx_cgcontext._window; CGPoint cgpt = { (CGFloat)pt.h, (CGFloat)pt.v }; - HIPointConvert(&cgpt, kHICoordSpaceScreenPixel, NULL, + HIPointConvert(&cgpt, kHICoordSpaceScreenPixel, nullptr, kHICoordSpaceWindow, window); // Then convert to plugin coordinates. @@ -536,7 +538,7 @@ load_image(OsxImageData &image, const string &image_filename) { } image._data = - CFDataCreateWithBytesNoCopy(NULL, (const UInt8 *)image._raw_data, + CFDataCreateWithBytesNoCopy(nullptr, (const UInt8 *)image._raw_data, image._height * new_row_stride, kCFAllocatorNull); image._provider = CGDataProviderCreateWithCFData(image._data); image._color_space = CGColorSpaceCreateDeviceRGB(); @@ -545,7 +547,7 @@ load_image(OsxImageData &image, const string &image_filename) { CGImageCreate(image._width, image._height, 8, 32, new_row_stride, image._color_space, kCGImageAlphaFirst | kCGBitmapByteOrder32Little, - image._provider, NULL, false, kCGRenderingIntentDefault); + image._provider, nullptr, false, kCGRenderingIntentDefault); } /** @@ -554,7 +556,7 @@ load_image(OsxImageData &image, const string &image_filename) { */ bool P3DOsxSplashWindow:: paint_image(CGContextRef context, const OsxImageData &image) { - if (image._image == NULL) { + if (image._image == nullptr) { return false; } @@ -580,7 +582,7 @@ paint_image(CGContextRef context, const OsxImageData &image) { // The bitmap is larger than the window; scale it down. double x_scale = (double)_win_width / (double)image._width; double y_scale = (double)_win_height / (double)image._height; - double scale = min(x_scale, y_scale); + double scale = std::min(x_scale, y_scale); int sc_width = (int)(image._width * scale); int sc_height = (int)(image._height * scale); @@ -675,8 +677,8 @@ paint_progress_bar(CGContextRef context) { CGContextSetTextMatrix(context, text_xform); // Now draw the install_label right above it. - CFStringRef string = CFStringCreateWithCString(NULL, _install_label.c_str(), kCFStringEncodingUTF8); - CFAttributedStringRef attr_string = CFAttributedStringCreate(NULL, string, _font_attribs); + CFStringRef string = CFStringCreateWithCString(nullptr, _install_label.c_str(), kCFStringEncodingUTF8); + CFAttributedStringRef attr_string = CFAttributedStringCreate(nullptr, string, _font_attribs); CTLineRef line = CTLineCreateWithAttributedString(attr_string); // Determine the placement based on the size of the text. @@ -716,11 +718,11 @@ OSStatus P3DOsxSplashWindow:: event_callback(EventHandlerCallRef my_handler, EventRef event) { OSStatus result = eventNotHandledErr; - WindowRef window = NULL; + WindowRef window = nullptr; UInt32 the_class = GetEventClass(event); UInt32 kind = GetEventKind(event); - GetEventParameter(event, kEventParamWindowRef, typeWindowRef, NULL, - sizeof(WindowRef), NULL, (void*) &window); + GetEventParameter(event, kEventParamWindowRef, typeWindowRef, nullptr, + sizeof(WindowRef), nullptr, (void*) &window); switch (the_class) { case kEventClassWindow: switch (kind) { @@ -773,17 +775,17 @@ event_callback(EventHandlerCallRef my_handler, EventRef event) { case kEventMouseDragged: { Point point; - GetEventParameter(event, kEventParamMouseLocation, typeQDPoint, NULL, - sizeof(Point), NULL, (void *)&point); + GetEventParameter(event, kEventParamMouseLocation, typeQDPoint, nullptr, + sizeof(Point), nullptr, (void *)&point); GrafPtr port; - assert(_toplevel_window != NULL); + assert(_toplevel_window != nullptr); port = GetWindowPort(_toplevel_window); - GrafPtr port_save = NULL; + GrafPtr port_save = nullptr; Boolean port_changed = QDSwapPort(port, &port_save); GlobalToLocal(&point); if (port_changed) { - QDSwapPort(port_save, NULL); + QDSwapPort(port_save, nullptr); } set_mouse_data(point.h, point.v, _mouse_down); @@ -800,25 +802,25 @@ event_callback(EventHandlerCallRef my_handler, EventRef event) { */ void P3DOsxSplashWindow::OsxImageData:: dump_image() { - if (_image != NULL) { + if (_image != nullptr) { CGImageRelease(_image); - _image = NULL; + _image = nullptr; } - if (_color_space != NULL) { + if (_color_space != nullptr) { CGColorSpaceRelease(_color_space); - _color_space = NULL; + _color_space = nullptr; } - if (_provider != NULL) { + if (_provider != nullptr) { CGDataProviderRelease(_provider); - _provider = NULL; + _provider = nullptr; } - if (_data != NULL) { + if (_data != nullptr) { CFRelease(_data); - _data = NULL; + _data = nullptr; } - if (_raw_data != NULL) { + if (_raw_data != nullptr) { delete[] _raw_data; - _raw_data = NULL; + _raw_data = nullptr; } } diff --git a/direct/src/plugin/p3dOsxSplashWindow.h b/direct/src/plugin/p3dOsxSplashWindow.h index 2a725412eb..9a2a6225bc 100644 --- a/direct/src/plugin/p3dOsxSplashWindow.h +++ b/direct/src/plugin/p3dOsxSplashWindow.h @@ -32,9 +32,9 @@ public: virtual void set_wparams(const P3DWindowParams &wparams); virtual void set_visible(bool visible); - virtual void set_image_filename(const string &image_filename, + virtual void set_image_filename(const std::string &image_filename, ImagePlacement image_placement); - virtual void set_install_label(const string &install_label); + virtual void set_install_label(const std::string &install_label); virtual void set_install_progress(double install_progress, bool is_progress_known, size_t received_data); @@ -50,7 +50,7 @@ private: bool handle_event_osx_cocoa(const P3D_event_data &event); class OsxImageData; - void load_image(OsxImageData &image, const string &image_filename); + void load_image(OsxImageData &image, const std::string &image_filename); bool paint_image(CGContextRef context, const OsxImageData &image); void paint_progress_bar(CGContextRef context); @@ -82,7 +82,7 @@ private: CFDictionaryRef _font_attribs; - string _install_label; + std::string _install_label; double _install_progress; bool _progress_known; size_t _received_data; diff --git a/direct/src/plugin/p3dPackage.I b/direct/src/plugin/p3dPackage.I index 2b5f40ff73..371491f5c2 100644 --- a/direct/src/plugin/p3dPackage.I +++ b/direct/src/plugin/p3dPackage.I @@ -60,7 +60,7 @@ get_host() const { /** * Returns the directory into which this package is installed. */ -inline const string &P3DPackage:: +inline const std::string &P3DPackage:: get_package_dir() const { return _package_dir; } @@ -71,7 +71,7 @@ get_package_dir() const { * will not contain spaces. See also get_package_display_name() for a name * suitable for displaying to the user. */ -inline const string &P3DPackage:: +inline const std::string &P3DPackage:: get_package_name() const { return _package_name; } @@ -79,7 +79,7 @@ get_package_name() const { /** * Returns the version string of this package. */ -inline const string &P3DPackage:: +inline const std::string &P3DPackage:: get_package_version() const { return _package_version; } @@ -87,7 +87,7 @@ get_package_version() const { /** * Returns the platform string of this package. */ -inline const string &P3DPackage:: +inline const std::string &P3DPackage:: get_package_platform() const { return _package_platform; } @@ -95,7 +95,7 @@ get_package_platform() const { /** * Returns the display_name name of this package, as set in the desc file. */ -inline const string &P3DPackage:: +inline const std::string &P3DPackage:: get_package_display_name() const { return _package_display_name; } @@ -114,7 +114,7 @@ get_xconfig() const { * package, the desc file itself represents the entire contents of the * package. */ -inline const string &P3DPackage:: +inline const std::string &P3DPackage:: get_desc_file_pathname() const { return _desc_file_pathname; } @@ -123,7 +123,7 @@ get_desc_file_pathname() const { * Returns the relative path, on the host, of the directory that contains the * desc file (and to which all of the paths in the desc file are relative). */ -inline const string &P3DPackage:: +inline const std::string &P3DPackage:: get_desc_file_dirname() const { return _desc_file_dirname; } @@ -132,7 +132,7 @@ get_desc_file_dirname() const { * Returns the full path to the package's uncompressed archive file. This is * only valid if get_ready() is true and the package is not a "solo" package. */ -inline string P3DPackage:: +inline std::string P3DPackage:: get_archive_file_pathname() const { return _uncompressed_archive.get_pathname(_package_dir); } @@ -154,7 +154,7 @@ get_progress() const { if (_bytes_needed == 0) { return 1.0; } - return min((double)_bytes_done / (double)_bytes_needed, 1.0); + return std::min((double)_bytes_done / (double)_bytes_needed, 1.0); } /** @@ -169,8 +169,8 @@ report_step_progress() { * */ inline P3DPackage::RequiredPackage:: -RequiredPackage(const string &package_name, const string &package_version, - const string &package_seq, P3DHost *host) : +RequiredPackage(const std::string &package_name, const std::string &package_version, + const std::string &package_seq, P3DHost *host) : _package_name(package_name), _package_version(package_version), _package_seq(package_seq), diff --git a/direct/src/plugin/p3dPackage.cxx b/direct/src/plugin/p3dPackage.cxx index 0560c0f6da..fad2dd97f2 100644 --- a/direct/src/plugin/p3dPackage.cxx +++ b/direct/src/plugin/p3dPackage.cxx @@ -29,6 +29,12 @@ #include // chmod() #endif +using std::ios; +using std::ostream; +using std::ostringstream; +using std::string; +using std::vector; + // Weight factors for computing download progress. This attempts to reflect // the relative time-per-byte of each of these operations. const double P3DPackage::_download_factor = 1.0; @@ -59,16 +65,16 @@ P3DPackage(P3DHost *host, const string &package_name, _host_contents_iseq = 0; - _xconfig = NULL; - _temp_contents_file = NULL; + _xconfig = nullptr; + _temp_contents_file = nullptr; _computed_plan_size = false; _info_ready = false; _allow_data_download = false; _ready = false; _failed = false; - _active_download = NULL; - _saved_download = NULL; + _active_download = nullptr; + _saved_download = nullptr; _updated = false; } @@ -89,24 +95,24 @@ P3DPackage:: } _instances.clear(); - if (_xconfig != NULL) { + if (_xconfig != nullptr) { delete _xconfig; - _xconfig = NULL; + _xconfig = nullptr; } // Cancel any pending download. - if (_active_download != NULL) { + if (_active_download != nullptr) { _active_download->cancel(); - set_active_download(NULL); + set_active_download(nullptr); } - if (_saved_download != NULL) { + if (_saved_download != nullptr) { _saved_download->cancel(); - set_saved_download(NULL); + set_saved_download(nullptr); } - if (_temp_contents_file != NULL) { + if (_temp_contents_file != nullptr) { delete _temp_contents_file; - _temp_contents_file = NULL; + _temp_contents_file = nullptr; } } @@ -192,9 +198,9 @@ remove_instance(P3DInstance *inst) { if (inst == _instances[0]) { // This was the primary instance. Cancel any pending download and move to // the next instance. - if (_active_download != NULL) { + if (_active_download != nullptr) { _active_download->cancel(); - set_active_download(NULL); + set_active_download(nullptr); } } @@ -226,12 +232,12 @@ mark_used() { } TiXmlElement *xusage = doc.FirstChildElement("usage"); - if (xusage == NULL) { + if (xusage == nullptr) { xusage = new TiXmlElement("usage"); doc.LinkEndChild(xusage); } - time_t now = time(NULL); + time_t now = time(nullptr); int count = 0; xusage->Attribute("count_runtime", &count); if (count == 0) { @@ -292,7 +298,7 @@ uninstall() { for (ii = _instances.begin(); ii != _instances.end(); ++ii) { P3DInstance *inst = (*ii); P3DSession *session = inst->get_session(); - if (session != NULL) { + if (session != nullptr) { nout << "Stopping session " << session << "\n"; session->shutdown(); } @@ -350,7 +356,7 @@ begin_info_download() { return; } - if (_active_download != NULL) { + if (_active_download != nullptr) { // In the middle of downloading. return; } @@ -387,9 +393,9 @@ download_contents_file() { // Download contents.xml to a temporary filename first, in case multiple // packages are downloading it simultaneously. - if (_temp_contents_file != NULL) { + if (_temp_contents_file != nullptr) { delete _temp_contents_file; - _temp_contents_file = NULL; + _temp_contents_file = nullptr; } _temp_contents_file = new P3DTemporaryFile(".xml"); @@ -404,7 +410,7 @@ void P3DPackage:: contents_file_download_finished(bool success) { P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); if (!_host->has_current_contents_file(inst_mgr)) { - if (!success || _temp_contents_file == NULL || + if (!success || _temp_contents_file == nullptr || !_host->read_contents_file(_temp_contents_file->get_filename(), true)) { if (_temp_contents_file) { @@ -429,7 +435,7 @@ contents_file_download_finished(bool success) { report_done(false); if (_temp_contents_file) { delete _temp_contents_file; - _temp_contents_file = NULL; + _temp_contents_file = nullptr; } return; } @@ -439,7 +445,7 @@ contents_file_download_finished(bool success) { // The file is correctly installed by now; we can remove the temporary file. if (_temp_contents_file) { delete _temp_contents_file; - _temp_contents_file = NULL; + _temp_contents_file = nullptr; } host_got_contents_file(); @@ -460,8 +466,8 @@ contents_file_download_finished(bool success) { */ void P3DPackage:: redownload_contents_file(P3DPackage::Download *download) { - assert(_active_download == NULL); - assert(_saved_download == NULL); + assert(_active_download == nullptr); + assert(_saved_download == nullptr); if (_host->get_contents_iseq() != _host_contents_iseq) { // If the contents_iseq number has changed, we don't even need to download @@ -479,9 +485,9 @@ redownload_contents_file(P3DPackage::Download *download) { set_saved_download(download); // Download contents.xml to a temporary filename first. - if (_temp_contents_file != NULL) { + if (_temp_contents_file != nullptr) { delete _temp_contents_file; - _temp_contents_file = NULL; + _temp_contents_file = nullptr; } _temp_contents_file = new P3DTemporaryFile(".xml"); @@ -521,14 +527,14 @@ contents_file_redownload_finished(bool success) { // We no longer need the temporary file. if (_temp_contents_file) { delete _temp_contents_file; - _temp_contents_file = NULL; + _temp_contents_file = nullptr; } if (contents_changed) { // OK, the contents.xml has changed; this means we have to restart the // whole download process from the beginning. nout << "Redownloading contents.xml made a difference.\n"; - set_saved_download(NULL); + set_saved_download(nullptr); host_got_contents_file(); } else { @@ -536,8 +542,8 @@ contents_file_redownload_finished(bool success) { // you to our regularly scheduled download. nout << "Redownloading contents.xml didn't help.\n"; Download *download = _saved_download; - _saved_download = NULL; - if (download == NULL) { + _saved_download = nullptr; + if (download == nullptr) { // But, if _saved_download was NULL (meaning NULL was passed to // redownload_contents_file(), above), it means that we were called from // download_desc_file(), and there's nothing more to do. We're just @@ -639,7 +645,7 @@ download_desc_file() { nout << "Couldn't find package " << _package_fullname << ", platform \"" << _package_platform << "\" in contents file.\n"; - redownload_contents_file(NULL); + redownload_contents_file(nullptr); return; } @@ -730,7 +736,7 @@ desc_file_download_finished(bool success) { void P3DPackage:: got_desc_file(TiXmlDocument *doc, bool freshly_downloaded) { TiXmlElement *xpackage = doc->FirstChildElement("package"); - if (xpackage == NULL) { + if (xpackage == nullptr) { nout << _package_name << " desc file contains no \n"; if (!freshly_downloaded) { download_desc_file(); @@ -752,9 +758,9 @@ got_desc_file(TiXmlDocument *doc, bool freshly_downloaded) { xpackage->Attribute("patch_version", &_patch_version); TiXmlElement *xconfig = xpackage->FirstChildElement("config"); - if (xconfig != NULL) { + if (xconfig != nullptr) { const char *display_name_cstr = xconfig->Attribute("display_name"); - if (display_name_cstr != NULL) { + if (display_name_cstr != nullptr) { _package_display_name = display_name_cstr; } @@ -767,7 +773,7 @@ got_desc_file(TiXmlDocument *doc, bool freshly_downloaded) { TiXmlElement *xcompressed_archive = xpackage->FirstChildElement("compressed_archive"); - if (xuncompressed_archive == NULL || xcompressed_archive == NULL) { + if (xuncompressed_archive == nullptr || xcompressed_archive == nullptr) { // The desc file didn't include the archive file itself, weird. if (!freshly_downloaded) { download_desc_file(); @@ -784,7 +790,7 @@ got_desc_file(TiXmlDocument *doc, bool freshly_downloaded) { _unpack_size = 0; _extracts.clear(); TiXmlElement *xextract = xpackage->FirstChildElement("extract"); - while (xextract != NULL) { + while (xextract != nullptr) { FileSpec file; file.load_xml(xextract); _extracts.push_back(file); @@ -797,16 +803,16 @@ got_desc_file(TiXmlDocument *doc, bool freshly_downloaded) { // Get the required packages. _requires.clear(); TiXmlElement *xrequires = xpackage->FirstChildElement("requires"); - while (xrequires != NULL) { + while (xrequires != nullptr) { const char *package_name = xrequires->Attribute("name"); const char *host_url = xrequires->Attribute("host"); - if (package_name != NULL && host_url != NULL) { + if (package_name != nullptr && host_url != nullptr) { const char *version = xrequires->Attribute("version"); - if (version == NULL) { + if (version == nullptr) { version = ""; } const char *seq = xrequires->Attribute("seq"); - if (seq == NULL) { + if (seq == nullptr) { seq = ""; } P3DHost *host = inst_mgr->get_host(host_url); @@ -969,14 +975,14 @@ build_install_plans(TiXmlDocument *doc) { // Maybe we've already read the md5 hash and we have it stored here. const FileSpec *on_disk_ptr = _uncompressed_archive.get_actual_file(); FileSpec on_disk; - if (on_disk_ptr == NULL) { + if (on_disk_ptr == nullptr) { // If not, we have to go read it now. if (on_disk.read_hash(_uncompressed_archive.get_pathname(_package_dir))) { on_disk_ptr = &on_disk; } } - if (on_disk_ptr != NULL) { + if (on_disk_ptr != nullptr) { P3DPatchFinder patch_finder; P3DPatchFinder::Patchfiles chain; if (patch_finder.get_patch_chain_to_current(chain, doc, *on_disk_ptr)) { @@ -1147,7 +1153,7 @@ void P3DPackage:: report_progress(P3DPackage::InstallStep *step) { if (_computed_plan_size) { double size = _total_plan_completed + _current_step_effort * step->get_progress(); - _download_progress = min(size / _total_plan_size, 1.0); + _download_progress = std::min(size / _total_plan_size, 1.0); Instances::iterator ii; for (ii = _instances.begin(); ii != _instances.end(); ++ii) { @@ -1218,7 +1224,7 @@ P3DPackage::Download *P3DPackage:: start_download(P3DPackage::DownloadType dtype, const string &urlbase, const string &pathname, const FileSpec &file_spec) { // Only one download should be active at a time - assert(_active_download == NULL); + assert(_active_download == nullptr); // This can't happen! If verify_contents is set to P3D_VC_never, we're not // allowed to download anything, so we shouldn't get here P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); @@ -1249,7 +1255,7 @@ start_download(P3DPackage::DownloadType dtype, const string &urlbase, } else { strm << _host->get_download_url_prefix(); } - strm << urlbase << "?" << time(NULL); + strm << urlbase << "?" << time(nullptr); string url = strm.str(); download->_try_urls.push_back(url); @@ -1315,11 +1321,11 @@ start_download(P3DPackage::DownloadType dtype, const string &urlbase, void P3DPackage:: set_active_download(Download *download) { if (_active_download != download) { - if (_active_download != NULL) { + if (_active_download != nullptr) { p3d_unref_delete(_active_download); } _active_download = download; - if (_active_download != NULL) { + if (_active_download != nullptr) { _active_download->ref(); } } @@ -1332,11 +1338,11 @@ set_active_download(Download *download) { void P3DPackage:: set_saved_download(Download *download) { if (_saved_download != download) { - if (_saved_download != NULL) { + if (_saved_download != nullptr) { p3d_unref_delete(_saved_download); } _saved_download = download; - if (_saved_download != NULL) { + if (_saved_download != nullptr) { _saved_download->ref(); } } @@ -1456,11 +1462,11 @@ download_finished(bool success) { if (get_ref_count() == 1) { // No one cares anymore. nout << "No one cares about " << get_url() << "\n"; - _package->set_active_download(NULL); + _package->set_active_download(nullptr); return; } - _package->set_active_download(NULL); + _package->set_active_download(nullptr); assert(get_ref_count() > 0); if (success && !_file_spec.get_filename().empty()) { @@ -1471,7 +1477,7 @@ download_finished(bool success) { nout << "expected: "; _file_spec.output_hash(nout); nout << "\n"; - if (_file_spec.get_actual_file() != (FileSpec *)NULL) { + if (_file_spec.get_actual_file() != nullptr) { nout << " got: "; _file_spec.get_actual_file()->output_hash(nout); nout << "\n"; @@ -1578,7 +1584,7 @@ InstallStepDownloadFile(P3DPackage *package, const FileSpec &file) : _pathname = _package->get_package_dir() + "/" + _file.get_filename(); - _download = NULL; + _download = nullptr; } /** @@ -1586,7 +1592,7 @@ InstallStepDownloadFile(P3DPackage *package, const FileSpec &file) : */ P3DPackage::InstallStepDownloadFile:: ~InstallStepDownloadFile() { - if (_download != NULL) { + if (_download != nullptr) { p3d_unref_delete(_download); } } @@ -1596,13 +1602,13 @@ P3DPackage::InstallStepDownloadFile:: */ P3DPackage::InstallToken P3DPackage::InstallStepDownloadFile:: do_step(bool download_finished) { - if (_download == NULL) { + if (_download == nullptr) { // First, we have to start the download going. - assert(_package->_active_download == NULL); + assert(_package->_active_download == nullptr); _download = _package->start_download(DT_install_step, _urlbase, _pathname, _file); - assert(_download != NULL); + assert(_download != nullptr); _download->ref(); } @@ -1632,7 +1638,7 @@ do_step(bool download_finished) { nout << "Restarting download of " << _urlbase << " on new instance\n"; p3d_unref_delete(_download); - _download = NULL; + _download = nullptr; return IT_continue; } else { @@ -1780,7 +1786,7 @@ thread_step() { ifstream source; #ifdef _WIN32 - wstring source_pathname_w; + std::wstring source_pathname_w; if (string_to_wstring(source_pathname_w, source_pathname)) { source.open(source_pathname_w.c_str(), ios::in | ios::binary); } @@ -1798,7 +1804,7 @@ thread_step() { ofstream target; #ifdef _WIN32 - wstring target_pathname_w; + std::wstring target_pathname_w; if (string_to_wstring(target_pathname_w, target_pathname)) { target.open(target_pathname_w.c_str(), ios::out | ios::binary); } @@ -1829,7 +1835,7 @@ thread_step() { int flush = 0; source.read(decompress_buffer, decompress_buffer_size); - streamsize read_count = source.gcount(); + std::streamsize read_count = source.gcount(); eof = (read_count == 0 || source.eof() || source.fail()); z.next_in = (Bytef *)decompress_buffer; @@ -1844,7 +1850,7 @@ thread_step() { while (true) { if (z.avail_in == 0 && !eof) { source.read(decompress_buffer, decompress_buffer_size); - streamsize read_count = source.gcount(); + std::streamsize read_count = source.gcount(); eof = (read_count == 0 || source.eof() || source.fail()); z.next_in = (Bytef *)decompress_buffer; diff --git a/direct/src/plugin/p3dPackage.h b/direct/src/plugin/p3dPackage.h index b65290f836..4d44282c67 100644 --- a/direct/src/plugin/p3dPackage.h +++ b/direct/src/plugin/p3dPackage.h @@ -38,10 +38,10 @@ class P3DTemporaryFile; class P3DPackage { private: P3DPackage(P3DHost *host, - const string &package_name, - const string &package_version, - const string &package_platform, - const string &alt_host); + const std::string &package_name, + const std::string &package_version, + const std::string &package_platform, + const std::string &alt_host); ~P3DPackage(); public: @@ -52,17 +52,17 @@ public: inline bool get_ready() const; inline bool get_failed() const; inline P3DHost *get_host() const; - inline const string &get_package_dir() const; - inline const string &get_package_name() const; - inline const string &get_package_version() const; - inline const string &get_package_platform() const; - inline const string &get_package_display_name() const; - string get_formatted_name() const; + inline const std::string &get_package_dir() const; + inline const std::string &get_package_name() const; + inline const std::string &get_package_version() const; + inline const std::string &get_package_platform() const; + inline const std::string &get_package_display_name() const; + std::string get_formatted_name() const; inline const TiXmlElement *get_xconfig() const; - inline const string &get_desc_file_pathname() const; - inline const string &get_desc_file_dirname() const; - inline string get_archive_file_pathname() const; + inline const std::string &get_desc_file_pathname() const; + inline const std::string &get_desc_file_dirname() const; + inline std::string get_archive_file_pathname() const; void add_instance(P3DInstance *inst); void remove_instance(P3DInstance *inst); @@ -73,7 +73,7 @@ public: TiXmlElement *make_xml(); private: - typedef vector Extracts; + typedef std::vector Extracts; enum DownloadType { DT_contents_file, @@ -82,7 +82,7 @@ private: DT_install_step, }; - typedef vector TryUrls; + typedef std::vector TryUrls; class Download : public P3DFileDownload { public: @@ -123,7 +123,7 @@ private: virtual ~InstallStep(); virtual InstallToken do_step(bool download_finished) = 0; - virtual void output(ostream &out) = 0; + virtual void output(std::ostream &out) = 0; inline double get_effort() const; inline double get_progress() const; @@ -141,10 +141,10 @@ private: virtual ~InstallStepDownloadFile(); virtual InstallToken do_step(bool download_finished); - virtual void output(ostream &out); + virtual void output(std::ostream &out); - string _urlbase; - string _pathname; + std::string _urlbase; + std::string _pathname; FileSpec _file; Download *_download; }; @@ -174,7 +174,7 @@ private: InstallStepUncompressFile(P3DPackage *package, const FileSpec &source, const FileSpec &target, bool verify_target); virtual InstallToken thread_step(); - virtual void output(ostream &out); + virtual void output(std::ostream &out); FileSpec _source; FileSpec _target; @@ -185,7 +185,7 @@ private: public: InstallStepUnpackArchive(P3DPackage *package, size_t unpack_size); virtual InstallToken thread_step(); - virtual void output(ostream &out); + virtual void output(std::ostream &out); }; class InstallStepApplyPatch : public InstallStepThreaded { @@ -195,13 +195,13 @@ private: const FileSpec &source, const FileSpec &target); virtual InstallToken thread_step(); - virtual void output(ostream &out); + virtual void output(std::ostream &out); P3DPatchfileReader _reader; }; - typedef deque InstallPlan; - typedef deque InstallPlans; + typedef std::deque InstallPlan; + typedef std::deque InstallPlans; InstallPlans _install_plans; bool _computed_plan_size; @@ -230,52 +230,52 @@ private: void report_progress(InstallStep *step); void report_info_ready(); void report_done(bool success); - Download *start_download(DownloadType dtype, const string &urlbase, - const string &pathname, const FileSpec &file_spec); + Download *start_download(DownloadType dtype, const std::string &urlbase, + const std::string &pathname, const FileSpec &file_spec); void set_active_download(Download *download); void set_saved_download(Download *download); - bool is_extractable(FileSpec &file, const string &filename) const; + bool is_extractable(FileSpec &file, const std::string &filename) const; bool instance_terminating(P3DInstance *instance); void set_fullname(); public: class RequiredPackage { public: - inline RequiredPackage(const string &package_name, - const string &package_version, - const string &package_seq, + inline RequiredPackage(const std::string &package_name, + const std::string &package_version, + const std::string &package_seq, P3DHost *host); - string _package_name; - string _package_version; - string _package_seq; + std::string _package_name; + std::string _package_version; + std::string _package_seq; P3DHost *_host; }; - typedef vector Requires; + typedef std::vector Requires; Requires _requires; private: P3DHost *_host; int _host_contents_iseq; - string _package_name; - string _package_version; - string _package_platform; + std::string _package_name; + std::string _package_version; + std::string _package_platform; bool _per_platform; int _patch_version; - string _alt_host; + std::string _alt_host; bool _package_solo; - string _package_display_name; - string _package_fullname; - string _package_dir; + std::string _package_display_name; + std::string _package_fullname; + std::string _package_dir; TiXmlElement *_xconfig; P3DTemporaryFile *_temp_contents_file; FileSpec _desc_file; - string _desc_file_dirname; - string _desc_file_basename; - string _desc_file_pathname; + std::string _desc_file_dirname; + std::string _desc_file_basename; + std::string _desc_file_pathname; bool _info_ready; bool _allow_data_download; @@ -284,7 +284,7 @@ private: Download *_active_download; Download *_saved_download; - typedef vector Instances; + typedef std::vector Instances; Instances _instances; FileSpec _compressed_archive; diff --git a/direct/src/plugin/p3dPatchFinder.cxx b/direct/src/plugin/p3dPatchFinder.cxx index c3e5b80c86..fbc109fe8c 100644 --- a/direct/src/plugin/p3dPatchFinder.cxx +++ b/direct/src/plugin/p3dPatchFinder.cxx @@ -13,6 +13,8 @@ #include "p3dPatchFinder.h" +using std::string; + /** * */ @@ -24,8 +26,8 @@ PackageVersion(const PackageVersionKey &key) : _host_url(key._host_url), _file(key._file) { - _package_current = NULL; - _package_base = NULL; + _package_current = nullptr; + _package_base = nullptr; } /** @@ -58,7 +60,7 @@ get_patch_chain(Patchfiles &chain, PackageVersion *start_pv, for (pi = _from_patches.begin(); pi != _from_patches.end(); ++pi) { Patchfile *patchfile = (*pi); PackageVersion *from_pv = patchfile->_from_pv; - assert(from_pv != NULL); + assert(from_pv != nullptr); Patchfiles this_chain; if (from_pv->get_patch_chain(this_chain, start_pv, already_visited)) { // There's a path through this patchfile. @@ -116,7 +118,7 @@ operator < (const PackageVersionKey &other) const { * */ void P3DPatchFinder::PackageVersionKey:: -output(ostream &out) const { +output(std::ostream &out) const { out << "(" << _package_name << ", " << _platform << ", " << _version << ", " << _host_url << ", "; _file.output_hash(out); @@ -129,8 +131,8 @@ output(ostream &out) const { P3DPatchFinder::Patchfile:: Patchfile(Package *package) : _package(package), - _from_pv(NULL), - _to_pv(NULL) + _from_pv(nullptr), + _to_pv(nullptr) { _package_name = package->_package_name; _platform = package->_platform; @@ -161,30 +163,30 @@ get_target_key() const { void P3DPatchFinder::Patchfile:: load_xml(TiXmlElement *xpatch) { const char *package_name_cstr = xpatch->Attribute("name"); - if (package_name_cstr != NULL && *package_name_cstr) { + if (package_name_cstr != nullptr && *package_name_cstr) { _package_name = package_name_cstr; } const char *platform_cstr = xpatch->Attribute("platform"); - if (platform_cstr != NULL && *platform_cstr) { + if (platform_cstr != nullptr && *platform_cstr) { _platform = platform_cstr; } const char *version_cstr = xpatch->Attribute("version"); - if (version_cstr != NULL && *version_cstr) { + if (version_cstr != nullptr && *version_cstr) { _version = version_cstr; } const char *host_url_cstr = xpatch->Attribute("host"); - if (host_url_cstr != NULL && *host_url_cstr) { + if (host_url_cstr != nullptr && *host_url_cstr) { _host_url = host_url_cstr; } _file.load_xml(xpatch); TiXmlElement *xsource = xpatch->FirstChildElement("source"); - if (xsource != NULL) { + if (xsource != nullptr) { _source_file.load_xml(xsource); } TiXmlElement *xtarget = xpatch->FirstChildElement("target"); - if (xtarget != NULL) { + if (xtarget != nullptr) { _target_file.load_xml(xtarget); } } @@ -194,8 +196,8 @@ load_xml(TiXmlElement *xpatch) { */ P3DPatchFinder::Package:: Package() { - _current_pv = NULL; - _base_pv = NULL; + _current_pv = nullptr; + _base_pv = nullptr; _got_base_file = false; } @@ -230,43 +232,43 @@ get_generic_key(const FileSpec &file) const { bool P3DPatchFinder::Package:: read_desc_file(TiXmlDocument *doc) { TiXmlElement *xpackage = doc->FirstChildElement("package"); - if (xpackage == NULL) { + if (xpackage == nullptr) { return false; } const char *package_name_cstr = xpackage->Attribute("name"); - if (package_name_cstr != NULL && *package_name_cstr) { + if (package_name_cstr != nullptr && *package_name_cstr) { _package_name = package_name_cstr; } const char *platform_cstr = xpackage->Attribute("platform"); - if (platform_cstr != NULL && *platform_cstr) { + if (platform_cstr != nullptr && *platform_cstr) { _platform = platform_cstr; } const char *version_cstr = xpackage->Attribute("version"); - if (version_cstr != NULL && *version_cstr) { + if (version_cstr != nullptr && *version_cstr) { _version = version_cstr; } const char *host_url_cstr = xpackage->Attribute("host"); - if (host_url_cstr != NULL && *host_url_cstr) { + if (host_url_cstr != nullptr && *host_url_cstr) { _host_url = host_url_cstr; } // Get the current version. TiXmlElement *xarchive = xpackage->FirstChildElement("uncompressed_archive"); - if (xarchive != NULL) { + if (xarchive != nullptr) { _current_file.load_xml(xarchive); } // Get the base_version--the bottom (oldest) of the patch chain. xarchive = xpackage->FirstChildElement("base_version"); - if (xarchive != NULL) { + if (xarchive != nullptr) { _base_file.load_xml(xarchive); _got_base_file = true; } _patches.clear(); TiXmlElement *xpatch = xpackage->FirstChildElement("patch"); - while (xpatch != NULL) { + while (xpatch != nullptr) { Patchfile *patchfile = new Patchfile(this); patchfile->load_xml(xpatch); _patches.push_back(patchfile); @@ -301,7 +303,7 @@ get_patch_chain_to_current(Patchfiles &chain, TiXmlDocument *doc, const FileSpec &file) { chain.clear(); Package *package = read_package_desc_file(doc); - if (package == NULL) { + if (package == nullptr) { return false; } @@ -309,7 +311,7 @@ get_patch_chain_to_current(Patchfiles &chain, TiXmlDocument *doc, PackageVersion *from_pv = get_package_version(package->get_generic_key(file)); PackageVersion *to_pv = package->_current_pv; - if (to_pv != NULL && from_pv != NULL) { + if (to_pv != nullptr && from_pv != nullptr) { return to_pv->get_patch_chain(chain, from_pv, PackageVersionsList()); } @@ -326,7 +328,7 @@ read_package_desc_file(TiXmlDocument *doc) { Package *package = new Package; if (!package->read_desc_file(doc)) { delete package; - return NULL; + return nullptr; } _packages.push_back(package); diff --git a/direct/src/plugin/p3dPatchFinder.h b/direct/src/plugin/p3dPatchFinder.h index d3ee7d02b7..f25145a8e3 100644 --- a/direct/src/plugin/p3dPatchFinder.h +++ b/direct/src/plugin/p3dPatchFinder.h @@ -34,26 +34,26 @@ public: class Patchfile; class PackageVersion; - typedef vector Patchfiles; - typedef vector PackageVersionsList; + typedef std::vector Patchfiles; + typedef std::vector PackageVersionsList; // This class is used to index into a map to locate PackageVersion objects, // below. class PackageVersionKey { public: - PackageVersionKey(const string &package_name, - const string &platform, - const string &version, - const string &host_url, + PackageVersionKey(const std::string &package_name, + const std::string &platform, + const std::string &version, + const std::string &host_url, const FileSpec &file); bool operator < (const PackageVersionKey &other) const; - void output(ostream &out) const; + void output(std::ostream &out) const; public: - string _package_name; - string _platform; - string _version; - string _host_url; + std::string _package_name; + std::string _platform; + std::string _version; + std::string _host_url; FileSpec _file; }; @@ -68,12 +68,12 @@ public: const PackageVersionsList &already_visited_in); public: - string _package_name; - string _platform; - string _version; - string _host_url; + std::string _package_name; + std::string _platform; + std::string _version; + std::string _host_url; FileSpec _file; - string _print_name; + std::string _print_name; // The Package object that produces this version if this is the current // form or the base form, respectively. @@ -98,10 +98,10 @@ public: public: Package *_package; - string _package_name; - string _platform; - string _version; - string _host_url; + std::string _package_name; + std::string _platform; + std::string _version; + std::string _host_url; // The patchfile itself FileSpec _file; @@ -132,10 +132,10 @@ public: bool read_desc_file(TiXmlDocument *doc); public: - string _package_name; - string _platform; - string _version; - string _host_url; + std::string _package_name; + std::string _platform; + std::string _version; + std::string _host_url; PackageVersion *_current_pv; PackageVersion *_base_pv; @@ -162,16 +162,16 @@ private: void record_patchfile(Patchfile *patchfile); private: - typedef map PackageVersions; + typedef std::map PackageVersions; PackageVersions _package_versions; - typedef vector Packages; + typedef std::vector Packages; Packages _packages; }; #include "p3dPatchFinder.I" -inline ostream &operator << (ostream &out, const P3DPatchFinder::PackageVersionKey &key) { +inline std::ostream &operator << (std::ostream &out, const P3DPatchFinder::PackageVersionKey &key) { key.output(out); return out; } diff --git a/direct/src/plugin/p3dPatchfileReader.cxx b/direct/src/plugin/p3dPatchfileReader.cxx index 255bed8477..14ede5e9f9 100644 --- a/direct/src/plugin/p3dPatchfileReader.cxx +++ b/direct/src/plugin/p3dPatchfileReader.cxx @@ -14,6 +14,9 @@ #include "p3dPatchfileReader.h" #include "wstring_encode.h" +using std::ios; +using std::string; + /** * */ @@ -55,7 +58,7 @@ open_read() { string patch_pathname = _patchfile.get_pathname(_package_dir); _patch_in.clear(); #ifdef _WIN32 - wstring patch_pathname_w; + std::wstring patch_pathname_w; if (string_to_wstring(patch_pathname_w, patch_pathname)) { _patch_in.open(patch_pathname_w.c_str(), ios::in | ios::binary); } @@ -66,7 +69,7 @@ open_read() { string source_pathname = _source.get_pathname(_package_dir); _source_in.clear(); #ifdef _WIN32 - wstring source_pathname_w; + std::wstring source_pathname_w; if (string_to_wstring(source_pathname_w, source_pathname)) { _source_in.open(source_pathname_w.c_str(), ios::in | ios::binary); } @@ -77,7 +80,7 @@ open_read() { mkfile_complete(_output_pathname, nout); _target_out.clear(); #ifdef _WIN32 - wstring output_pathname_w; + std::wstring output_pathname_w; if (string_to_wstring(output_pathname_w, _output_pathname)) { _target_out.open(output_pathname_w.c_str(), ios::in | ios::binary); } @@ -247,13 +250,13 @@ close() { * have enough bytes. */ bool P3DPatchfileReader:: -copy_bytes(istream &in, size_t copy_byte_count) { +copy_bytes(std::istream &in, size_t copy_byte_count) { static const size_t buffer_size = 8192; char buffer[buffer_size]; - streamsize read_size = min(copy_byte_count, buffer_size); + std::streamsize read_size = std::min(copy_byte_count, buffer_size); in.read(buffer, read_size); - streamsize count = in.gcount(); + std::streamsize count = in.gcount(); while (count != 0) { _target_out.write(buffer, count); _bytes_written += (size_t)count; @@ -267,7 +270,7 @@ copy_bytes(istream &in, size_t copy_byte_count) { copy_byte_count -= (size_t)count; count = 0; if (copy_byte_count != 0) { - read_size = min(copy_byte_count, buffer_size); + read_size = std::min(copy_byte_count, buffer_size); in.read(buffer, read_size); count = in.gcount(); } diff --git a/direct/src/plugin/p3dPatchfileReader.h b/direct/src/plugin/p3dPatchfileReader.h index 1ad097a5ba..1c9501f5d1 100644 --- a/direct/src/plugin/p3dPatchfileReader.h +++ b/direct/src/plugin/p3dPatchfileReader.h @@ -29,7 +29,7 @@ */ class P3DPatchfileReader { public: - P3DPatchfileReader(const string &package_dir, + P3DPatchfileReader(const std::string &package_dir, const FileSpec &patchfile, const FileSpec &source, const FileSpec &target); @@ -45,18 +45,18 @@ public: void close(); private: - bool copy_bytes(istream &in, size_t copy_byte_count); + bool copy_bytes(std::istream &in, size_t copy_byte_count); inline unsigned int read_uint16(); inline unsigned int read_uint32(); inline int read_int32(); private: - string _package_dir; + std::string _package_dir; FileSpec _patchfile; FileSpec _source; FileSpec _target; - string _output_pathname; + std::string _output_pathname; ifstream _patch_in; ifstream _source_in; ofstream _target_out; diff --git a/direct/src/plugin/p3dPythonMain.cxx b/direct/src/plugin/p3dPythonMain.cxx index 76cf92c7e4..b5d11e6052 100644 --- a/direct/src/plugin/p3dPythonMain.cxx +++ b/direct/src/plugin/p3dPythonMain.cxx @@ -18,7 +18,6 @@ #include #include #include // strrchr -using namespace std; #if defined(_WIN32) && defined(NON_CONSOLE) // On Windows, we may need to build p3dpythonw.exe, a non-console version of @@ -34,7 +33,7 @@ static char * parse_quoted_arg(char *&p) { char quote = *p; ++p; - string result; + std::string result; while (*p != '\0' && *p != quote) { // TODO: handle escape characters? Not sure if we need to. @@ -51,7 +50,7 @@ parse_quoted_arg(char *&p) { // beginning at p. Advances p to the first whitespace following the argument. static char * parse_unquoted_arg(char *&p) { - string result; + std::string result; while (*p != '\0' && !isspace(*p)) { result += *p; ++p; @@ -63,7 +62,7 @@ int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { char *command_line = GetCommandLine(); - vector argv; + std::vector argv; char *p = command_line; while (*p != '\0') { @@ -94,10 +93,10 @@ WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { int main(int argc, char *argv[]) { const char *program_name = argv[0]; - const char *archive_file = NULL; - const char *input_handle_str = NULL; - const char *output_handle_str = NULL; - const char *interactive_console_str = NULL; + const char *archive_file = nullptr; + const char *input_handle_str = nullptr; + const char *output_handle_str = nullptr; + const char *interactive_console_str = nullptr; if (argc > 1) { archive_file = argv[1]; @@ -112,14 +111,14 @@ main(int argc, char *argv[]) { interactive_console_str = argv[4]; } - if (archive_file == NULL || *archive_file == '\0') { - cerr << "No archive filename specified on command line.\n"; + if (archive_file == nullptr || *archive_file == '\0') { + std::cerr << "No archive filename specified on command line.\n"; return 1; } FHandle input_handle = invalid_fhandle; - if (input_handle_str != NULL && *input_handle_str) { - stringstream stream(input_handle_str); + if (input_handle_str != nullptr && *input_handle_str) { + std::stringstream stream(input_handle_str); stream >> input_handle; if (!stream) { input_handle = invalid_fhandle; @@ -127,8 +126,8 @@ main(int argc, char *argv[]) { } FHandle output_handle = invalid_fhandle; - if (output_handle_str != NULL && *output_handle_str) { - stringstream stream(output_handle_str); + if (output_handle_str != nullptr && *output_handle_str) { + std::stringstream stream(output_handle_str); stream >> output_handle; if (!stream) { output_handle = invalid_fhandle; @@ -136,8 +135,8 @@ main(int argc, char *argv[]) { } bool interactive_console = false; - if (interactive_console_str != NULL && *interactive_console_str) { - stringstream stream(interactive_console_str); + if (interactive_console_str != nullptr && *interactive_console_str) { + std::stringstream stream(interactive_console_str); int flag; stream >> flag; if (!stream.fail()) { @@ -146,9 +145,9 @@ main(int argc, char *argv[]) { } int status = run_p3dpython(program_name, archive_file, input_handle, - output_handle, NULL, interactive_console); + output_handle, nullptr, interactive_console); if (status != 0) { - cerr << "Failure on startup.\n"; + std::cerr << "Failure on startup.\n"; } return status; } diff --git a/direct/src/plugin/p3dPythonObject.cxx b/direct/src/plugin/p3dPythonObject.cxx index 3a771dbf72..58a2d0348f 100644 --- a/direct/src/plugin/p3dPythonObject.cxx +++ b/direct/src/plugin/p3dPythonObject.cxx @@ -13,6 +13,8 @@ #include "p3dPythonObject.h" +using std::string; + /** * */ @@ -51,8 +53,8 @@ bool P3DPythonObject:: get_bool() { bool bresult = 0; - P3D_object *result = call("__bool__", true, NULL, 0); - if (result != NULL) { + P3D_object *result = call("__bool__", true, nullptr, 0); + if (result != nullptr) { bresult = P3D_OBJECT_GET_BOOL(result); P3D_OBJECT_DECREF(result); } @@ -67,8 +69,8 @@ int P3DPythonObject:: get_int() { int iresult = 0; - P3D_object *result = call("__int__", true, NULL, 0); - if (result != NULL) { + P3D_object *result = call("__int__", true, nullptr, 0); + if (result != nullptr) { iresult = P3D_OBJECT_GET_INT(result); P3D_OBJECT_DECREF(result); } @@ -83,8 +85,8 @@ double P3DPythonObject:: get_float() { double fresult = 0.0; - P3D_object *result = call("__float__", true, NULL, 0); - if (result != NULL) { + P3D_object *result = call("__float__", true, nullptr, 0); + if (result != nullptr) { fresult = P3D_OBJECT_GET_FLOAT(result); P3D_OBJECT_DECREF(result); } @@ -98,9 +100,9 @@ get_float() { */ void P3DPythonObject:: make_string(string &value) { - P3D_object *result = call("__str__", true, NULL, 0); - if (result != NULL) { - int size = P3D_OBJECT_GET_STRING(result, NULL, 0); + P3D_object *result = call("__str__", true, nullptr, 0); + if (result != nullptr) { + int size = P3D_OBJECT_GET_STRING(result, nullptr, 0); char *buffer = new char[size]; P3D_OBJECT_GET_STRING(result, buffer, size); value = string(buffer, size); @@ -150,9 +152,9 @@ set_property_insecure(const string &property, bool needs_response, P3D_object *params[2]; params[0] = new P3DStringObject(property); - P3D_object *result = NULL; + P3D_object *result = nullptr; - if (value == NULL) { + if (value == nullptr) { // Delete an attribute. result = call_insecure("__del_property__", needs_response, params, 1); @@ -164,7 +166,7 @@ set_property_insecure(const string &property, bool needs_response, P3D_OBJECT_DECREF(params[0]); - if (result != NULL) { + if (result != nullptr) { bresult = P3D_OBJECT_GET_BOOL(result); P3D_OBJECT_DECREF(result); } @@ -178,7 +180,7 @@ set_property_insecure(const string &property, bool needs_response, bool P3DPythonObject:: has_method(const string &method_name) { // First, check the cache. - pair cresult = _has_method.insert(HasMethod::value_type(method_name, false)); + std::pair cresult = _has_method.insert(HasMethod::value_type(method_name, false)); HasMethod::iterator hi = cresult.first; if (!cresult.second) { // Already cached. @@ -193,7 +195,7 @@ has_method(const string &method_name) { P3D_object *result = call("__has_method__", true, params, 1); P3D_OBJECT_DECREF(params[0]); - if (result != NULL) { + if (result != nullptr) { bresult = P3D_OBJECT_GET_BOOL(result); P3D_OBJECT_DECREF(result); } @@ -219,7 +221,7 @@ call(const string &method_name, bool needs_response, P3D_object *params[], int num_params) { if (!_session->get_matches_script_origin()) { // If you can't be scripting us, you can't be calling methods. - return NULL; + return nullptr; } return call_insecure(method_name, needs_response, params, num_params); @@ -255,18 +257,18 @@ call_insecure(const string &method_name, bool needs_response, // NULL. if (!needs_response) { _session->send_command(doc); - return NULL; + return nullptr; } // If a response is requested, we have to send the command and wait for it. TiXmlDocument *response = _session->command_and_response(doc); - P3D_object *result = NULL; - if (response != NULL) { + P3D_object *result = nullptr; + if (response != nullptr) { TiXmlElement *xresponse = response->FirstChildElement("response"); - if (xresponse != NULL) { + if (xresponse != nullptr) { TiXmlElement *xvalue = xresponse->FirstChildElement("value"); - if (xvalue != NULL) { + if (xvalue != nullptr) { result = _session->xml_to_p3dobj(xvalue); } } @@ -281,10 +283,10 @@ call_insecure(const string &method_name, bool needs_response, * This is intended for developer assistance. */ void P3DPythonObject:: -output(ostream &out) { - P3D_object *result = call("__repr__", true, NULL, 0); +output(std::ostream &out) { + P3D_object *result = call("__repr__", true, nullptr, 0); out << "Python " << _object_id; - if (result != NULL) { + if (result != nullptr) { out << ": " << *result; P3D_OBJECT_DECREF(result); } diff --git a/direct/src/plugin/p3dPythonObject.h b/direct/src/plugin/p3dPythonObject.h index 980617257e..a4f9c5d7d0 100644 --- a/direct/src/plugin/p3dPythonObject.h +++ b/direct/src/plugin/p3dPythonObject.h @@ -35,20 +35,20 @@ public: virtual int get_int(); virtual double get_float(); - virtual void make_string(string &value); + virtual void make_string(std::string &value); - virtual P3D_object *get_property(const string &property); - virtual bool set_property(const string &property, bool needs_response, P3D_object *value); - bool set_property_insecure(const string &property, bool needs_response, + virtual P3D_object *get_property(const std::string &property); + virtual bool set_property(const std::string &property, bool needs_response, P3D_object *value); + bool set_property_insecure(const std::string &property, bool needs_response, P3D_object *value); - virtual bool has_method(const string &method_name); - virtual P3D_object *call(const string &method_name, bool needs_response, + virtual bool has_method(const std::string &method_name); + virtual P3D_object *call(const std::string &method_name, bool needs_response, P3D_object *params[], int num_params); - P3D_object *call_insecure(const string &method_name, bool needs_response, + P3D_object *call_insecure(const std::string &method_name, bool needs_response, P3D_object *params[], int num_params); - virtual void output(ostream &out); + virtual void output(std::ostream &out); virtual bool fill_xml(TiXmlElement *xvalue, P3DSession *session); virtual P3DPythonObject *as_python_object(); @@ -60,7 +60,7 @@ private: P3DSession *_session; int _object_id; - typedef map HasMethod; + typedef std::map HasMethod; HasMethod _has_method; }; diff --git a/direct/src/plugin/p3dPythonRun.cxx b/direct/src/plugin/p3dPythonRun.cxx index 542c47acb8..b9e4c5655e 100644 --- a/direct/src/plugin/p3dPythonRun.cxx +++ b/direct/src/plugin/p3dPythonRun.cxx @@ -20,6 +20,8 @@ #include "py_panda.h" +using std::string; + extern "C" { // This has been compiled-in by the build system, if all is well. extern struct _frozen _PyImport_FrozenModules[]; @@ -28,7 +30,7 @@ extern "C" { // There is only one P3DPythonRun object in any given process space. Makes // the statics easier to deal with, and we don't need multiple instances of // this thing. -P3DPythonRun *P3DPythonRun::_global_ptr = NULL; +P3DPythonRun *P3DPythonRun::_global_ptr = nullptr; TypeHandle P3DPythonRun::P3DWindowHandle::_type_handle; @@ -45,7 +47,7 @@ P3DPythonRun(const char *program_name, const char *archive_file, _read_thread_continue = false; _program_continue = true; _session_terminated = false; - _taskMgr = NULL; + _taskMgr = nullptr; INIT_LOCK(_commands_lock); INIT_THREAD(_read_thread); @@ -55,7 +57,7 @@ P3DPythonRun(const char *program_name, const char *archive_file, _interactive_console = interactive_console; - if (program_name != NULL) { + if (program_name != nullptr) { #if PY_MAJOR_VERSION >= 3 // Python 3 case: we have to convert it to a wstring. TextEncoder enc; @@ -66,7 +68,7 @@ P3DPythonRun(const char *program_name, const char *archive_file, _program_name = program_name; #endif } - if (archive_file != NULL) { + if (archive_file != nullptr) { _archive_file = Filename::from_os_specific(archive_file); } @@ -76,7 +78,7 @@ P3DPythonRun(const char *program_name, const char *archive_file, #else _py_argv[0] = (char *)_program_name.c_str(); #endif - _py_argv[1] = NULL; + _py_argv[1] = nullptr; #ifdef NDEBUG // In OPTIMIZE 4 compilation mode, run Python in optimized mode too. @@ -113,12 +115,12 @@ P3DPythonRun(const char *program_name, const char *archive_file, PySys_SetArgvEx(_py_argc, _py_argv, 0); // Open the error output before we do too much more. - if (log_pathname != NULL && *log_pathname != '\0') { + if (log_pathname != nullptr && *log_pathname != '\0') { Filename f = Filename::from_os_specific(log_pathname); f.set_text(); if (f.open_write(_error_log)) { // Set up the indicated error log as the Notify output. - _error_log.setf(ios::unitbuf); + _error_log.setf(std::ios::unitbuf); Notify::ptr()->set_ostream_ptr(&_error_log, false); } } @@ -155,7 +157,7 @@ P3DPythonRun:: // Restore the notify stream in case it tries to write to anything else // after our shutdown. - Notify::ptr()->set_ostream_ptr(&cerr, false); + Notify::ptr()->set_ostream_ptr(&std::cerr, false); } /** @@ -178,7 +180,7 @@ run_python() { // We could simply freeze it, but Python has a bug setting __path__ of // frozen modules properly. PyObject *panda3d_module = PyImport_AddModule("panda3d"); - if (panda3d_module == NULL) { + if (panda3d_module == nullptr) { nout << "Failed to add panda3d module:\n"; PyErr_Print(); return 1; @@ -192,7 +194,7 @@ run_python() { // Import the VFSImporter module that was frozen in. PyObject *vfsimporter_module = PyImport_ImportModule("direct.showbase.VFSImporter"); - if (vfsimporter_module == NULL) { + if (vfsimporter_module == nullptr) { nout << "Failed to import VFSImporter:\n"; PyErr_Print(); return 1; @@ -203,14 +205,14 @@ run_python() { // such that we can still find the other direct modules. Filename direct_dir(dir, "direct"); PyObject *direct_module = PyImport_AddModule("direct"); - if (direct_module != NULL) { + if (direct_module != nullptr) { dir_str = direct_dir.to_os_specific(); PyModule_AddObject(direct_module, "__path__", Py_BuildValue("[s#]", dir_str.data(), dir_str.length())); PyModule_AddStringConstant(direct_module, "__package__", "direct"); } PyObject *showbase_module = PyImport_AddModule("direct.showbase"); - if (showbase_module != NULL) { + if (showbase_module != nullptr) { Filename showbase_dir(direct_dir, "showbase"); dir_str = showbase_dir.to_os_specific(); PyModule_AddObject(showbase_module, "__path__", Py_BuildValue("[s#]", dir_str.data(), dir_str.length())); @@ -218,7 +220,7 @@ run_python() { } PyObject *stdpy_module = PyImport_AddModule("direct.stdpy"); - if (stdpy_module != NULL) { + if (stdpy_module != nullptr) { Filename stdpy_dir(direct_dir, "stdpy"); dir_str = stdpy_dir.to_os_specific(); PyModule_AddObject(stdpy_module, "__path__", Py_BuildValue("[s#]", dir_str.data(), dir_str.length())); @@ -229,7 +231,7 @@ run_python() { // bunch of encodings modules as part of the frozen bundle. Filename encodings_dir(dir, "encodings"); PyObject *encodings_module = PyImport_AddModule("encodings"); - if (encodings_module != NULL) { + if (encodings_module != nullptr) { dir_str = encodings_dir.to_os_specific(); PyModule_AddObject(encodings_module, "__path__", Py_BuildValue("[s#]", dir_str.data(), dir_str.length())); PyModule_AddStringConstant(encodings_module, "__package__", "encodings"); @@ -237,7 +239,7 @@ run_python() { // And register the VFSImporter. PyObject *result = PyObject_CallMethod(vfsimporter_module, (char *)"register", (char *)""); - if (result == NULL) { + if (result == nullptr) { nout << "Failed to call VFSImporter.register():\n"; PyErr_Print(); return 1; @@ -261,7 +263,7 @@ run_python() { // And finally, we can import the startup module. PyObject *app_runner_module = PyImport_ImportModule("direct.p3d.AppRunner"); - if (app_runner_module == NULL) { + if (app_runner_module == nullptr) { nout << "Failed to import direct.p3d.AppRunner\n"; PyErr_Print(); return 1; @@ -269,7 +271,7 @@ run_python() { // Get the pointers to the objects needed within the module. PyObject *app_runner_class = PyObject_GetAttrString(app_runner_module, "AppRunner"); - if (app_runner_class == NULL) { + if (app_runner_class == nullptr) { nout << "Failed to get AppRunner class\n"; PyErr_Print(); return 1; @@ -277,7 +279,7 @@ run_python() { // Construct an instance of AppRunner. _runner = PyObject_CallFunction(app_runner_class, (char *)""); - if (_runner == NULL) { + if (_runner == nullptr) { nout << "Failed to construct AppRunner instance\n"; PyErr_Print(); return 1; @@ -286,7 +288,7 @@ run_python() { // Import the JavaScript module. PyObject *javascript_module = PyImport_ImportModule("direct.p3d.JavaScript"); - if (javascript_module == NULL) { + if (javascript_module == nullptr) { nout << "Failed to import direct.p3d.JavaScript\n"; PyErr_Print(); return false; @@ -294,35 +296,35 @@ run_python() { // Get the UndefinedObject class. _undefined_object_class = PyObject_GetAttrString(javascript_module, "UndefinedObject"); - if (_undefined_object_class == NULL) { + if (_undefined_object_class == nullptr) { PyErr_Print(); return 1; } // And the "Undefined" instance. _undefined = PyObject_GetAttrString(javascript_module, "Undefined"); - if (_undefined == NULL) { + if (_undefined == nullptr) { PyErr_Print(); return 1; } // Get the ConcreteStruct class. _concrete_struct_class = PyObject_GetAttrString(javascript_module, "ConcreteStruct"); - if (_concrete_struct_class == NULL) { + if (_concrete_struct_class == nullptr) { PyErr_Print(); return 1; } // Get the BrowserObject class. _browser_object_class = PyObject_GetAttrString(javascript_module, "BrowserObject"); - if (_browser_object_class == NULL) { + if (_browser_object_class == nullptr) { PyErr_Print(); return 1; } // Get the global TaskManager. _taskMgr = PyObject_GetAttrString(app_runner_module, "taskMgr"); - if (_taskMgr == NULL) { + if (_taskMgr == nullptr) { PyErr_Print(); return 1; } @@ -337,28 +339,28 @@ run_python() { "Poll for communications from the parent process" }, { "request_func", P3DPythonRun::st_request_func, METH_VARARGS, "Send an asynchronous request to the plugin host" }, - { NULL, NULL, 0, NULL } /* Sentinel */ + { nullptr, nullptr, 0, nullptr } /* Sentinel */ }; #if PY_MAJOR_VERSION >= 3 static PyModuleDef p3dpython_module = { PyModuleDef_HEAD_INIT, "p3dpython", - NULL, + nullptr, -1, p3dpython_methods, - NULL, NULL, NULL, NULL + nullptr, nullptr, nullptr, nullptr }; PyObject *p3dpython = PyModule_Create(&p3dpython_module); #else PyObject *p3dpython = Py_InitModule("p3dpython", p3dpython_methods); #endif - if (p3dpython == NULL) { + if (p3dpython == nullptr) { PyErr_Print(); return 1; } PyObject *request_func = PyObject_GetAttrString(p3dpython, "request_func"); - if (request_func == NULL) { + if (request_func == nullptr) { PyErr_Print(); return 1; } @@ -366,7 +368,7 @@ run_python() { // Now pass that func pointer back to our AppRunner instance, so it can call // up to us. result = PyObject_CallMethod(_runner, (char *)"setRequestFunc", (char *)"N", request_func); - if (result == NULL) { + if (result == nullptr) { PyErr_Print(); return 1; } @@ -384,7 +386,7 @@ run_python() { chain->set_thread_priority(TP_low); PyObject *check_comm = PyObject_GetAttrString(p3dpython, "check_comm"); - if (check_comm == NULL) { + if (check_comm == nullptr) { PyErr_Print(); return 1; } @@ -392,7 +394,7 @@ run_python() { // Add it to the task manager. We do this instead of constructing a // PythonTask because linking p3dpython with core.pyd is problematic. result = PyObject_CallMethod(_taskMgr, (char *)"add", (char *)"Ns", check_comm, "check_comm"); - if (result == NULL) { + if (result == nullptr) { PyErr_Print(); return 1; } @@ -401,7 +403,7 @@ run_python() { // Finally, get lost in AppRunner.run() (which is really a call to // taskMgr.run()). PyObject *done = PyObject_CallMethod(_runner, (char *)"run", (char *)""); - if (done == NULL) { + if (done == nullptr) { int status = 1; // An uncaught application exception, and not handled by @@ -409,10 +411,10 @@ run_python() { // status that we should return. if (PyErr_ExceptionMatches(PyExc_SystemExit)) { PyObject *ptype, *ptraceback; - PyObject *value = NULL; + PyObject *value = nullptr; PyErr_Fetch(&ptype, &value, &ptraceback); - if (value != NULL && PyExceptionInstance_Check(value)) { + if (value != nullptr && PyExceptionInstance_Check(value)) { PyObject *code = PyObject_GetAttrString(value, "code"); if (code) { Py_DECREF(value); @@ -420,7 +422,7 @@ run_python() { } } - if (value == NULL || value == Py_None) { + if (value == nullptr || value == Py_None) { status = 0; #if PY_MAJOR_VERSION >= 3 } else if (PyLong_Check(value)) { @@ -510,13 +512,13 @@ void P3DPythonRun:: run_interactive_console() { #ifdef _WIN32 // Make sure that control-C support is enabled for the interpreter. - SetConsoleCtrlHandler(NULL, false); + SetConsoleCtrlHandler(nullptr, false); #endif // The "readline" module makes the Python prompt friendlier, with command // history and everything. Simply importing it is sufficient. PyObject *readline_module = PyImport_ImportModule("readline"); - if (readline_module == NULL) { + if (readline_module == nullptr) { // But, the module might not exist on certain platforms. If not, no // sweat. PyErr_Clear(); @@ -536,7 +538,7 @@ run_interactive_console() { void P3DPythonRun:: handle_command(TiXmlDocument *doc) { TiXmlElement *xcommand = doc->FirstChildElement("command"); - if (xcommand != NULL) { + if (xcommand != nullptr) { bool needs_response = false; int want_response_id; if (xcommand->QueryIntAttribute("want_response_id", &want_response_id) == TIXML_SUCCESS) { @@ -545,7 +547,7 @@ handle_command(TiXmlDocument *doc) { } const char *cmd = xcommand->Attribute("cmd"); - if (cmd != NULL) { + if (cmd != nullptr) { if (strcmp(cmd, "init") == 0) { assert(!needs_response); @@ -565,7 +567,7 @@ handle_command(TiXmlDocument *doc) { } else if (strcmp(cmd, "start_instance") == 0) { assert(!needs_response); TiXmlElement *xinstance = xcommand->FirstChildElement("instance"); - if (xinstance != (TiXmlElement *)NULL) { + if (xinstance != nullptr) { P3DCInstance *inst = new P3DCInstance(xinstance); start_instance(inst, xinstance); } @@ -581,7 +583,7 @@ handle_command(TiXmlDocument *doc) { assert(!needs_response); int instance_id; TiXmlElement *xwparams = xcommand->FirstChildElement("wparams"); - if (xwparams != (TiXmlElement *)NULL && + if (xwparams != nullptr && xcommand->QueryIntAttribute("instance_id", &instance_id) == TIXML_SUCCESS) { setup_window(instance_id, xwparams); } @@ -657,11 +659,11 @@ handle_pyobj_command(TiXmlElement *xcommand, bool needs_response, doc.LinkEndChild(xresponse); const char *op = xcommand->Attribute("op"); - if (op != NULL && !PyErr_Occurred()) { + if (op != nullptr && !PyErr_Occurred()) { if (strcmp(op, "get_panda_script_object") == 0) { // Get Panda's toplevel Python object. PyObject *obj = PyObject_CallMethod(_runner, (char*)"getPandaScriptObject", (char *)""); - if (obj != NULL) { + if (obj != nullptr) { xresponse->LinkEndChild(pyobj_to_xml(obj)); Py_DECREF(obj); } @@ -670,7 +672,7 @@ handle_pyobj_command(TiXmlElement *xcommand, bool needs_response, // Set the Browser's toplevel window object. PyObject *obj; TiXmlElement *xvalue = xcommand->FirstChildElement("value"); - if (xvalue != NULL) { + if (xvalue != nullptr) { obj = xml_to_pyobj(xvalue); } else { obj = Py_None; @@ -684,7 +686,7 @@ handle_pyobj_command(TiXmlElement *xcommand, bool needs_response, // Call the named method on the indicated object, or the object itself // if method_name isn't given. TiXmlElement *xobject = xcommand->FirstChildElement("object"); - if (xobject != NULL) { + if (xobject != nullptr) { PyObject *obj = xml_to_pyobj(xobject); const char *method_name = xcommand->Attribute("method_name"); @@ -693,7 +695,7 @@ handle_pyobj_command(TiXmlElement *xcommand, bool needs_response, PyObject *list = PyList_New(0); TiXmlElement *xchild = xcommand->FirstChildElement("value"); - while (xchild != NULL) { + while (xchild != nullptr) { PyObject *child = xml_to_pyobj(xchild); PyList_Append(list, child); Py_DECREF(child); @@ -705,8 +707,8 @@ handle_pyobj_command(TiXmlElement *xcommand, bool needs_response, Py_DECREF(list); // Now call the method. - PyObject *result = NULL; - if (method_name == NULL) { + PyObject *result = nullptr; + if (method_name == nullptr) { // No method name; call the object directly. result = PyObject_CallObject(obj, params); @@ -811,7 +813,7 @@ handle_pyobj_command(TiXmlElement *xcommand, bool needs_response, if (PyObject_HasAttrString(obj, property_name)) { result = PyObject_GetAttrString(obj, property_name); - if (result != NULL) { + if (result != nullptr) { success = true; } else { PyErr_Clear(); @@ -821,7 +823,7 @@ handle_pyobj_command(TiXmlElement *xcommand, bool needs_response, if (!success) { if (PyMapping_HasKeyString(obj, property_name)) { result = PyMapping_GetItemString(obj, property_name); - if (result != NULL) { + if (result != nullptr) { success = true; } else { PyErr_Clear(); @@ -830,7 +832,7 @@ handle_pyobj_command(TiXmlElement *xcommand, bool needs_response, } if (!success) { - result = NULL; + result = nullptr; } } @@ -859,7 +861,7 @@ handle_pyobj_command(TiXmlElement *xcommand, bool needs_response, } else { // Not a special-case name. Call the named method. PyObject *method = PyObject_GetAttrString(obj, (char *)method_name); - if (method != NULL) { + if (method != nullptr) { result = PyObject_CallObject(method, params); Py_DECREF(method); } @@ -867,7 +869,7 @@ handle_pyobj_command(TiXmlElement *xcommand, bool needs_response, Py_DECREF(params); // Feed the return value back through the XML pipe to the caller. - if (result != NULL) { + if (result != nullptr) { xresponse->LinkEndChild(pyobj_to_xml(result)); Py_DECREF(result); } else { @@ -948,10 +950,10 @@ wait_script_response(int response_id) { TiXmlDocument *doc = (*ci); TiXmlElement *xcommand = doc->FirstChildElement("command"); - if (xcommand != NULL) { + if (xcommand != nullptr) { const char *cmd = xcommand->Attribute("cmd"); - if ((cmd != NULL && strcmp(cmd, "script_response") == 0) || - xcommand->Attribute("want_response_id") != NULL) { + if ((cmd != nullptr && strcmp(cmd, "script_response") == 0) || + xcommand->Attribute("want_response_id") != nullptr) { // This is either a response, or it's a command that will want a // response itself. In either case we should handle it right away. @@ -960,7 +962,7 @@ wait_script_response(int response_id) { RELEASE_LOCK(_commands_lock); handle_command(doc); if (_session_terminated) { - return NULL; + return nullptr; } ACQUIRE_LOCK(_commands_lock); break; @@ -976,9 +978,9 @@ wait_script_response(int response_id) { TiXmlDocument *doc = (*ci); TiXmlElement *xcommand = doc->FirstChildElement("command"); - assert(xcommand != NULL); + assert(xcommand != nullptr); const char *cmd = xcommand->Attribute("cmd"); - assert(cmd != NULL && strcmp(cmd, "script_response") == 0); + assert(cmd != nullptr && strcmp(cmd, "script_response") == 0); int unique_id; if (xcommand->QueryIntAttribute("unique_id", &unique_id) == TIXML_SUCCESS) { @@ -995,7 +997,7 @@ wait_script_response(int response_id) { if (!_program_continue) { terminate_session(); - return NULL; + return nullptr; } #ifdef _WIN32 @@ -1005,7 +1007,7 @@ wait_script_response(int response_id) { // We appear to be best off with just a single PeekMessage() call here; // the full message pump seems to cause problems. MSG msg; - PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE | PM_NOYIELD); + PeekMessage(&msg, nullptr, 0, 0, PM_NOREMOVE | PM_NOYIELD); #endif // _WIN32 // nout << "."; @@ -1027,7 +1029,7 @@ py_request_func(PyObject *args) { const char *request_type; PyObject *extra_args; if (!PyArg_ParseTuple(args, "isO", &instance_id, &request_type, &extra_args)) { - return NULL; + return nullptr; } if (strcmp(request_type, "wait_script_response") == 0) { @@ -1035,20 +1037,20 @@ py_request_func(PyObject *args) { // means to wait for a particular script_response to come in on the wire. int response_id; if (!PyArg_ParseTuple(extra_args, "i", &response_id)) { - return NULL; + return nullptr; } TiXmlDocument *doc = wait_script_response(response_id); if (_session_terminated) { return Py_BuildValue(""); } - assert(doc != NULL); + assert(doc != nullptr); TiXmlElement *xcommand = doc->FirstChildElement("command"); - assert(xcommand != NULL); + assert(xcommand != nullptr); TiXmlElement *xvalue = xcommand->FirstChildElement("value"); - PyObject *value = NULL; - if (xvalue != NULL) { + PyObject *value = nullptr; + if (xvalue != nullptr) { value = xml_to_pyobj(xvalue); } else { // An absence of a element is an exception. We will return NULL @@ -1070,7 +1072,7 @@ py_request_func(PyObject *args) { // A general notification to be sent directly to the instance. const char *message; if (!PyArg_ParseTuple(extra_args, "s", &message)) { - return NULL; + return nullptr; } xrequest->SetAttribute("message", message); @@ -1087,7 +1089,7 @@ py_request_func(PyObject *args) { if (!PyArg_ParseTuple(extra_args, "sOsOii", &operation, &object, &property_name, &value, &needs_response, &unique_id)) { - return NULL; + return nullptr; } xrequest->SetAttribute("operation", operation); @@ -1106,7 +1108,7 @@ py_request_func(PyObject *args) { // Release a particular P3D_object that we were holding a reference to. int object_id; if (!PyArg_ParseTuple(extra_args, "i", &object_id)) { - return NULL; + return nullptr; } xrequest->SetAttribute("object_id", object_id); @@ -1119,7 +1121,7 @@ py_request_func(PyObject *args) { const char *package_name; const char *package_version; if (!PyArg_ParseTuple(extra_args, "sss", &host_url, &package_name, &package_version)) { - return NULL; + return nullptr; } xrequest->SetAttribute("host_url", host_url); @@ -1134,7 +1136,7 @@ py_request_func(PyObject *args) { } else { string message = string("Unsupported request type: ") + string(request_type); PyErr_SetString(PyExc_ValueError, message.c_str()); - return NULL; + return nullptr; } return Py_BuildValue(""); @@ -1185,18 +1187,18 @@ start_instance(P3DCInstance *inst, TiXmlElement *xinstance) { set_instance_info(inst, xinstance); TiXmlElement *xpackage = xinstance->FirstChildElement("package"); - while (xpackage != (TiXmlElement *)NULL) { + while (xpackage != nullptr) { add_package_info(inst, xpackage); xpackage = xpackage->NextSiblingElement("package"); } TiXmlElement *xfparams = xinstance->FirstChildElement("fparams"); - if (xfparams != (TiXmlElement *)NULL) { + if (xfparams != nullptr) { set_p3d_filename(inst, xfparams); } TiXmlElement *xwparams = xinstance->FirstChildElement("wparams"); - if (xwparams != (TiXmlElement *)NULL) { + if (xwparams != nullptr) { setup_window(inst, xwparams); } } @@ -1228,12 +1230,12 @@ terminate_instance(int id) { void P3DPythonRun:: set_instance_info(P3DCInstance *inst, TiXmlElement *xinstance) { const char *root_dir = xinstance->Attribute("root_dir"); - if (root_dir == NULL) { + if (root_dir == nullptr) { root_dir = ""; } const char *log_directory = xinstance->Attribute("log_directory"); - if (log_directory == NULL) { + if (log_directory == nullptr) { log_directory = ""; } @@ -1241,14 +1243,14 @@ set_instance_info(P3DCInstance *inst, TiXmlElement *xinstance) { xinstance->Attribute("verify_contents", &verify_contents); const char *super_mirror = xinstance->Attribute("super_mirror"); - if (super_mirror == NULL) { + if (super_mirror == nullptr) { super_mirror = ""; } // Get the initial "main" object, if specified. PyObject *main; TiXmlElement *xmain = xinstance->FirstChildElement("main"); - if (xmain != NULL) { + if (xmain != nullptr) { main = xml_to_pyobj(xmain); } else { main = Py_None; @@ -1262,7 +1264,7 @@ set_instance_info(P3DCInstance *inst, TiXmlElement *xinstance) { (_runner, (char *)"setInstanceInfo", (char *)"sssiNi", root_dir, log_directory, super_mirror, verify_contents, main, respect_per_platform); - if (result == NULL) { + if (result == nullptr) { PyErr_Print(); if (_interactive_console) { run_interactive_console(); @@ -1282,16 +1284,16 @@ add_package_info(P3DCInstance *inst, TiXmlElement *xpackage) { const char *version = xpackage->Attribute("version"); const char *host = xpackage->Attribute("host"); const char *host_dir = xpackage->Attribute("host_dir"); - if (name == NULL || host == NULL) { + if (name == nullptr || host == nullptr) { return; } - if (version == NULL) { + if (version == nullptr) { version = ""; } - if (platform == NULL) { + if (platform == nullptr) { platform = ""; } - if (host_dir == NULL) { + if (host_dir == nullptr) { host_dir = ""; } @@ -1299,7 +1301,7 @@ add_package_info(P3DCInstance *inst, TiXmlElement *xpackage) { (_runner, (char *)"addPackageInfo", (char *)"sssss", name, platform, version, host, host_dir); - if (result == NULL) { + if (result == nullptr) { PyErr_Print(); if (_interactive_console) { run_interactive_console(); @@ -1317,7 +1319,7 @@ void P3DPythonRun:: set_p3d_filename(P3DCInstance *inst, TiXmlElement *xfparams) { string p3d_filename; const char *p3d_filename_c = xfparams->Attribute("p3d_filename"); - if (p3d_filename_c != NULL) { + if (p3d_filename_c != nullptr) { p3d_filename = p3d_filename_c; } @@ -1326,21 +1328,21 @@ set_p3d_filename(P3DCInstance *inst, TiXmlElement *xfparams) { string p3d_url; const char *p3d_url_c = xfparams->Attribute("p3d_url"); - if (p3d_url_c != NULL) { + if (p3d_url_c != nullptr) { p3d_url = p3d_url_c; } PyObject *token_list = PyList_New(0); TiXmlElement *xtoken = xfparams->FirstChildElement("token"); - while (xtoken != NULL) { + while (xtoken != nullptr) { string keyword, value; const char *keyword_c = xtoken->Attribute("keyword"); - if (keyword_c != NULL) { + if (keyword_c != nullptr) { keyword = keyword_c; } const char *value_c = xtoken->Attribute("value"); - if (value_c != NULL) { + if (value_c != nullptr) { value = value_c; } @@ -1354,10 +1356,10 @@ set_p3d_filename(P3DCInstance *inst, TiXmlElement *xfparams) { PyObject *arg_list = PyList_New(0); TiXmlElement *xarg = xfparams->FirstChildElement("arg"); - while (xarg != NULL) { + while (xarg != nullptr) { string value; const char *value_c = xarg->Attribute("value"); - if (value_c != NULL) { + if (value_c != nullptr) { value = value_c; } @@ -1373,7 +1375,7 @@ set_p3d_filename(P3DCInstance *inst, TiXmlElement *xfparams) { token_list, arg_list, inst->get_instance_id(), _interactive_console, p3d_offset, p3d_url.c_str()); - if (result == NULL) { + if (result == nullptr) { PyErr_Print(); if (_interactive_console) { run_interactive_console(); @@ -1405,7 +1407,7 @@ void P3DPythonRun:: setup_window(P3DCInstance *inst, TiXmlElement *xwparams) { string window_type; const char *window_type_c = xwparams->Attribute("window_type"); - if (window_type_c != NULL) { + if (window_type_c != nullptr) { window_type = window_type_c; } @@ -1429,7 +1431,7 @@ setup_window(P3DCInstance *inst, TiXmlElement *xwparams) { // to go through this subprocess-window nonsense. const char *subprocess_window = xwparams->Attribute("subprocess_window"); - if (subprocess_window != NULL) { + if (subprocess_window != nullptr) { Filename filename = Filename::from_os_specific(subprocess_window); parent_window_handle = NativeWindowHandle::make_subprocess(filename); } @@ -1437,16 +1439,16 @@ setup_window(P3DCInstance *inst, TiXmlElement *xwparams) { #elif defined(HAVE_X11) // Use stringstream to decode the "long" attribute. const char *parent_cstr = xwparams->Attribute("parent_xwindow"); - if (parent_cstr != NULL) { + if (parent_cstr != nullptr) { long window; - istringstream strm(parent_cstr); + std::istringstream strm(parent_cstr); strm >> window; parent_window_handle = NativeWindowHandle::make_x11((X11_Window)window); } #endif PyObject *py_handle = Py_None; - if (parent_window_handle != NULL) { + if (parent_window_handle != nullptr) { // We have a valid parent WindowHandle, but replace it with a // P3DWindowHandle so we can get the callbacks. @@ -1467,7 +1469,7 @@ setup_window(P3DCInstance *inst, TiXmlElement *xwparams) { (_runner, (char *)"setupWindow", (char *)"siiiiN", window_type.c_str(), win_x, win_y, win_width, win_height, py_handle); - if (result == NULL) { + if (result == nullptr) { PyErr_Print(); if (_interactive_console) { run_interactive_console(); @@ -1489,7 +1491,7 @@ send_windows_message(int id, unsigned int msg, int wparam, int lparam) { } P3DCInstance *inst = (*ii).second; - if (inst->_parent_window_handle != (WindowHandle *)NULL) { + if (inst->_parent_window_handle != nullptr) { inst->_parent_window_handle->send_windows_message(msg, wparam, lparam); } } @@ -1507,9 +1509,9 @@ terminate_session() { _instances.clear(); if (!_session_terminated) { - if (_taskMgr != NULL) { + if (_taskMgr != nullptr) { PyObject *result = PyObject_CallMethod(_taskMgr, (char *)"stop", (char *)""); - if (result == NULL) { + if (result == nullptr) { PyErr_Print(); } else { Py_DECREF(result); @@ -1573,13 +1575,13 @@ pyobj_to_xml(PyObject *value) { // function for getting the UTF-8 encoded version. Py_ssize_t length = 0; char *buffer = PyUnicode_AsUTF8AndSize(value, &length); - if (buffer != NULL) { + if (buffer != nullptr) { string str(buffer, length); xvalue->SetAttribute("value", str); } #else PyObject *as_str = PyUnicode_AsUTF8String(value); - if (as_str != NULL) { + if (as_str != nullptr) { char *buffer; Py_ssize_t length; if (PyString_AsStringAndSize(as_str, &buffer, &length) != -1) { @@ -1594,13 +1596,13 @@ pyobj_to_xml(PyObject *value) { // using the standard encoding, then re-encoding it. xvalue->SetAttribute("type", "string"); - PyObject *ustr = PyUnicode_FromEncodedObject(value, NULL, NULL); - if (ustr == NULL) { + PyObject *ustr = PyUnicode_FromEncodedObject(value, nullptr, nullptr); + if (ustr == nullptr) { PyErr_Print(); return xvalue; } else { PyObject *as_str = PyUnicode_AsUTF8String(ustr); - if (as_str != NULL) { + if (as_str != nullptr) { char *buffer; Py_ssize_t length; if (PyString_AsStringAndSize(as_str, &buffer, &length) != -1) { @@ -1620,7 +1622,7 @@ pyobj_to_xml(PyObject *value) { Py_ssize_t length = PySequence_Length(value); for (Py_ssize_t i = 0; i < length; ++i) { PyObject *item = PySequence_GetItem(value, i); - if (item != NULL) { + if (item != nullptr) { xvalue->LinkEndChild(pyobj_to_xml(item)); Py_DECREF(item); } @@ -1631,7 +1633,7 @@ pyobj_to_xml(PyObject *value) { xvalue->SetAttribute("type", "concrete_struct"); PyObject *items = PyObject_CallMethod(value, (char *)"getConcreteProperties", (char *)""); - if (items == NULL) { + if (items == nullptr) { PyErr_Print(); return xvalue; } @@ -1639,11 +1641,11 @@ pyobj_to_xml(PyObject *value) { Py_ssize_t length = PySequence_Length(items); for (Py_ssize_t i = 0; i < length; ++i) { PyObject *item = PySequence_GetItem(items, i); - if (item != NULL) { + if (item != nullptr) { PyObject *a = PySequence_GetItem(item, 0); - if (a != NULL) { + if (a != nullptr) { PyObject *b = PySequence_GetItem(item, 1); - if (b != NULL) { + if (b != nullptr) { TiXmlElement *xitem = pyobj_to_xml(b); Py_DECREF(b); @@ -1664,7 +1666,7 @@ pyobj_to_xml(PyObject *value) { Py_ssize_t length; #if PY_MAJOR_VERSION >= 3 buffer = PyUnicode_AsUTF8AndSize(as_str, &length); - if (buffer != NULL) { + if (buffer != nullptr) { #else if (PyString_AsStringAndSize(as_str, &buffer, &length) != -1) { #endif @@ -1694,7 +1696,7 @@ pyobj_to_xml(PyObject *value) { // This is a BrowserObject, a reference to an object that actually exists // in the host namespace. So, pass up the appropriate object ID. PyObject *objectId = PyObject_GetAttrString(value, (char *)"_BrowserObject__objectId"); - if (objectId != NULL) { + if (objectId != nullptr) { int object_id = PyInt_AsLong(objectId); xvalue->SetAttribute("type", "browser"); xvalue->SetAttribute("object_id", object_id); @@ -1764,8 +1766,8 @@ xml_to_pyobj(TiXmlElement *xvalue) { // Using the string form here instead of the char * form, so we don't get // tripped up on embedded null characters. const string *value = xvalue->Attribute(string("value")); - if (value != NULL) { - return PyUnicode_DecodeUTF8(value->data(), value->length(), NULL); + if (value != nullptr) { + return PyUnicode_DecodeUTF8(value->data(), value->length(), nullptr); } } else if (strcmp(type, "undefined") == 0) { @@ -1785,9 +1787,9 @@ xml_to_pyobj(TiXmlElement *xvalue) { PyObject *list = PyList_New(0); TiXmlElement *xitem = xvalue->FirstChildElement("value"); - while (xitem != NULL) { + while (xitem != nullptr) { PyObject *item = xml_to_pyobj(xitem); - if (item != NULL) { + if (item != nullptr) { PyList_Append(list, item); Py_DECREF(item); } @@ -1802,13 +1804,13 @@ xml_to_pyobj(TiXmlElement *xvalue) { // Receive a concrete struct as a new ConcreteStruct instance. PyObject *obj = PyObject_CallFunction(_concrete_struct_class, (char *)""); - if (obj != NULL) { + if (obj != nullptr) { TiXmlElement *xitem = xvalue->FirstChildElement("value"); - while (xitem != NULL) { + while (xitem != nullptr) { const char *key = xitem->Attribute("key"); - if (key != NULL) { + if (key != nullptr) { PyObject *item = xml_to_pyobj(xitem); - if (item != NULL) { + if (item != nullptr) { PyObject_SetAttrString(obj, (char *)key, item); Py_DECREF(item); } @@ -1847,7 +1849,7 @@ void P3DPythonRun:: rt_thread_run() { while (_read_thread_continue) { TiXmlDocument *doc = read_xml(_pipe_read, nout); - if (doc == NULL) { + if (doc == nullptr) { // Some error on reading. Abort. _program_continue = false; return; @@ -1858,9 +1860,9 @@ rt_thread_run() { // Check for one special case: the "exit" command means we shut down the // read thread along with everything else. TiXmlElement *xcommand = doc->FirstChildElement("command"); - if (xcommand != NULL) { + if (xcommand != nullptr) { const char *cmd = xcommand->Attribute("cmd"); - if (cmd != NULL) { + if (cmd != nullptr) { if (strcmp(cmd, "exit") == 0) { _read_thread_continue = false; } diff --git a/direct/src/plugin/p3dPythonRun.h b/direct/src/plugin/p3dPythonRun.h index 17a8e35371..ee3fbc3d00 100644 --- a/direct/src/plugin/p3dPythonRun.h +++ b/direct/src/plugin/p3dPythonRun.h @@ -41,8 +41,6 @@ typedef int Py_ssize_t; #define PY_SSIZE_T_MIN INT_MIN #endif -using namespace std; - /** * This class is used to run, and communicate with, embedded Python in a sub- * process. It is compiled and launched as a separate executable from the @@ -156,10 +154,10 @@ private: int _py_argc; #if PY_MAJOR_VERSION >= 3 wchar_t *_py_argv[2]; - wstring _program_name; + std::wstring _program_name; #else char *_py_argv[2]; - string _program_name; + std::string _program_name; #endif bool _interactive_console; diff --git a/direct/src/plugin/p3dSession.I b/direct/src/plugin/p3dSession.I index 2ab1155788..010a81c172 100644 --- a/direct/src/plugin/p3dSession.I +++ b/direct/src/plugin/p3dSession.I @@ -15,7 +15,7 @@ * Returns a string that uniquely identifies this session. See * P3dInstance::get_session_key(). */ -inline const string &P3DSession:: +inline const std::string &P3DSession:: get_session_key() const { return _session_key; } @@ -25,7 +25,7 @@ get_session_key() const { * started and if it has a log file. Returns empty string if the session * never started or if it lacks a log file. */ -inline const string &P3DSession:: +inline const std::string &P3DSession:: get_log_pathname() const { return _log_pathname; } diff --git a/direct/src/plugin/p3dSession.cxx b/direct/src/plugin/p3dSession.cxx index 522936f61a..4a769ec9e1 100644 --- a/direct/src/plugin/p3dSession.cxx +++ b/direct/src/plugin/p3dSession.cxx @@ -43,6 +43,9 @@ #include #endif +using std::string; +using std::wstring; + /** * Creates a new session, corresponding to a new subprocess with its own copy * of Python. The initial parameters for the session are taken from the @@ -143,7 +146,7 @@ shutdown() { #else // _WIN32 // Wait for a certain amount of time for the process to stop by itself. struct timeval start; - gettimeofday(&start, NULL); + gettimeofday(&start, nullptr); int start_ms = start.tv_sec * 1000 + start.tv_usec / 1000; int status; @@ -155,7 +158,7 @@ shutdown() { } struct timeval now; - gettimeofday(&now, NULL); + gettimeofday(&now, nullptr); int now_ms = now.tv_sec * 1000 + now.tv_usec / 1000; int elapsed = now_ms - start_ms; @@ -171,7 +174,7 @@ shutdown() { struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 1; - select(0, NULL, NULL, NULL, &tv); + select(0, nullptr, nullptr, nullptr, &tv); result = waitpid(_p3dpython_pid, &status, WNOHANG); } _p3dpython_pid = -1; @@ -227,7 +230,7 @@ shutdown() { */ void P3DSession:: start_instance(P3DInstance *inst) { - assert(inst->_session == NULL); + assert(inst->_session == nullptr); assert(inst->get_session_key() == _session_key); if (_failed) { inst->set_failed(); @@ -279,7 +282,7 @@ terminate_instance(P3DInstance *inst) { if (inst->_session == this) { nout << "Assigning " << inst << "->log_pathname = " << _log_pathname << "\n"; inst->_log_pathname = _log_pathname; - inst->_session = NULL; + inst->_session = nullptr; _instances.erase(inst->get_instance_id()); } RELEASE_LOCK(_instances_lock); @@ -319,7 +322,7 @@ send_command(TiXmlDocument *command) { TiXmlDocument *P3DSession:: command_and_response(TiXmlDocument *command) { if (!_p3dpython_started) { - return NULL; + return nullptr; } P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); @@ -328,7 +331,7 @@ command_and_response(TiXmlDocument *command) { // Add the "want_response_id" attribute to the toplevel command, so the sub- // process knows we'll be waiting for its response. TiXmlElement *xcommand = command->FirstChildElement("command"); - assert(xcommand != NULL); + assert(xcommand != nullptr); xcommand->SetAttribute("want_response_id", response_id); write_xml(_pipe_write, command, nout); @@ -341,7 +344,7 @@ command_and_response(TiXmlDocument *command) { if (!_p3dpython_running) { // Hmm, looks like Python has gone away. _response_ready.release(); - return NULL; + return nullptr; } // Make sure we bake requests while we are waiting, to process recursive @@ -380,7 +383,7 @@ command_and_response(TiXmlDocument *command) { // coming and will block waiting for them. MSG msg; - PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE | PM_NOYIELD); + PeekMessage(&msg, nullptr, 0, 0, PM_NOREMOVE | PM_NOYIELD); // We wait with a timeout, so we can go back and spin the event loop some // more. On Windows, the timeout needs to be small, so we continue to @@ -444,16 +447,16 @@ xml_to_p3dobj(const TiXmlElement *xvalue) { // Using the string form here instead of the char * form, so we don't get // tripped up on embedded null characters. const string *value = xvalue->Attribute(string("value")); - if (value != NULL) { + if (value != nullptr) { return new P3DStringObject(*value); } } else if (strcmp(type, "concrete_sequence") == 0) { P3DConcreteSequence *obj = new P3DConcreteSequence; const TiXmlElement *xitem = xvalue->FirstChildElement("value"); - while (xitem != NULL) { + while (xitem != nullptr) { P3D_object *item = xml_to_p3dobj(xitem); - if (item != NULL) { + if (item != nullptr) { obj->append(item); P3D_OBJECT_DECREF(item); } @@ -464,11 +467,11 @@ xml_to_p3dobj(const TiXmlElement *xvalue) { } else if (strcmp(type, "concrete_struct") == 0) { P3DConcreteStruct *obj = new P3DConcreteStruct; const TiXmlElement *xitem = xvalue->FirstChildElement("value"); - while (xitem != NULL) { + while (xitem != nullptr) { const char *key = xitem->Attribute("key"); - if (key != NULL) { + if (key != nullptr) { P3D_object *item = xml_to_p3dobj(xitem); - if (item != NULL) { + if (item != nullptr) { obj->set_property(key, item); P3D_OBJECT_DECREF(item); } @@ -539,7 +542,7 @@ p3dobj_to_xml(P3D_object *obj) { case P3D_OT_string: { xvalue->SetAttribute("type", "string"); - int size = P3D_OBJECT_GET_STRING(obj, NULL, 0); + int size = P3D_OBJECT_GET_STRING(obj, nullptr, 0); char *buffer = new char[size]; P3D_OBJECT_GET_STRING(obj, buffer, size); xvalue->SetAttribute("value", string(buffer, size)); @@ -548,12 +551,12 @@ p3dobj_to_xml(P3D_object *obj) { break; case P3D_OT_object: - P3DObject *p3dobj = NULL; + P3DObject *p3dobj = nullptr; if (obj->_class == &P3DObject::_object_class) { p3dobj = (P3DObject *)obj; } - if (p3dobj != NULL && p3dobj->fill_xml(xvalue, this)) { + if (p3dobj != nullptr && p3dobj->fill_xml(xvalue, this)) { // This object has a specialized XML representation, valid for this // particular session. It has already been filled into xvalue. @@ -666,7 +669,7 @@ start_p3dpython(P3DInstance *inst) { return; } - if (inst->_panda3d_package == NULL) { + if (inst->_panda3d_package == nullptr) { nout << "Couldn't start Python: no panda3d dependency.\n"; set_failed(); return; @@ -787,22 +790,22 @@ start_p3dpython(P3DInstance *inst) { string p3dpythonw_exe = _p3dpython_exe + "w"; if (_p3dpython_exe.empty()) { // Allow package to override the name of the p3dpython executables. - const char *p3dpython_name_xconfig = NULL; - const char *p3dpythonw_name_xconfig = NULL; + const char *p3dpython_name_xconfig = nullptr; + const char *p3dpythonw_name_xconfig = nullptr; const TiXmlElement *panda3d_xconfig = inst->_panda3d_package->get_xconfig(); - if (panda3d_xconfig != NULL) { + if (panda3d_xconfig != nullptr) { p3dpython_name_xconfig = panda3d_xconfig->Attribute("p3dpython_name"); p3dpythonw_name_xconfig = panda3d_xconfig->Attribute("p3dpythonw_name"); } string p3dpython_name = "p3dpython"; - if (p3dpython_name_xconfig != NULL) { + if (p3dpython_name_xconfig != nullptr) { nout << "p3dpython_name from panda3d xconfig: " << p3dpython_name_xconfig << "\n"; p3dpython_name = p3dpython_name_xconfig; } string p3dpythonw_name = p3dpython_name + "w"; - if (p3dpythonw_name_xconfig != NULL) { + if (p3dpythonw_name_xconfig != nullptr) { nout << "p3dpythonw_name from panda3d xconfig: " << p3dpythonw_name_xconfig << "\n"; p3dpythonw_name = p3dpythonw_name_xconfig; } @@ -848,9 +851,9 @@ start_p3dpython(P3DInstance *inst) { #ifdef HAVE_X11 "DISPLAY", "XAUTHORITY", #endif - NULL + nullptr }; - for (int ki = 0; keep[ki] != NULL; ++ki) { + for (int ki = 0; keep[ki] != nullptr; ++ki) { string value; if (get_env(value, keep[ki])) { _env += keep[ki]; @@ -867,7 +870,7 @@ start_p3dpython(P3DInstance *inst) { "PATH", "LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH", "PYTHONPATH", "PYTHONHOME", "PRC_PATH", "PANDA_PRC_PATH", "TEMP", "CTPROJS", - NULL + nullptr }; #ifdef _WIN32 @@ -886,14 +889,14 @@ start_p3dpython(P3DInstance *inst) { #endif // _WIN32 char **ep; - for (ep = global_environ; *ep != NULL; ++ep) { + for (ep = global_environ; *ep != nullptr; ++ep) { string env = *ep; size_t equals = env.find('='); if (equals != string::npos) { string var = env.substr(0, equals); const char *varc = var.c_str(); bool found = false; - for (int i = 0; dont_keep[i] != NULL && !found; ++i) { + for (int i = 0; dont_keep[i] != nullptr && !found; ++i) { #ifdef _WIN32 found = (_stricmp(dont_keep[i], varc) == 0); #else @@ -1047,7 +1050,7 @@ start_p3dpython(P3DInstance *inst) { // Check if we want to keep copies of recent logs on disk. if (!log_basename.empty()) { // Get a list of all logs on disk - vector all_logs; + std::vector all_logs; string log_directory = inst_mgr->get_log_directory(); inst_mgr->scan_directory(log_directory, all_logs); @@ -1067,7 +1070,7 @@ start_p3dpython(P3DInstance *inst) { // Remove all but the most recent log_history timestamped logs string log_basename_dash = (log_basename + string("-")); string log_matching_pathname; - vector matching_logs; + std::vector matching_logs; for (int i=0; i<(int)all_logs.size(); ++i) { if ((all_logs[i].size() > 4) && (all_logs[i].find(log_basename_dash) == 0) && @@ -1088,9 +1091,9 @@ start_p3dpython(P3DInstance *inst) { #else tzset(); #endif - time_t log_time_seconds = time(NULL); + time_t log_time_seconds = time(nullptr); struct tm *log_time_local_p = localtime(&log_time_seconds); - if (log_time_local_p != NULL) { + if (log_time_local_p != nullptr) { struct tm log_time_local = *log_time_local_p; static const size_t buffer_size = 16; char buffer[buffer_size]; @@ -1121,7 +1124,7 @@ start_p3dpython(P3DInstance *inst) { HANDLE r_to, w_to, r_from, w_from; // Create the pipe to the process. - if (!CreatePipe(&r_to, &w_to, NULL, 0)) { + if (!CreatePipe(&r_to, &w_to, nullptr, 0)) { nout << "failed to create pipe\n"; set_failed(); } else { @@ -1131,7 +1134,7 @@ start_p3dpython(P3DInstance *inst) { } // Create the pipe from the process. - if (!CreatePipe(&r_from, &w_from, NULL, 0)) { + if (!CreatePipe(&r_from, &w_from, nullptr, 0)) { nout << "failed to create pipe\n"; set_failed(); } else { @@ -1311,7 +1314,7 @@ void P3DSession:: rt_thread_run() { while (_read_thread_continue) { TiXmlDocument *doc = read_xml(_pipe_read, nout); - if (doc == NULL) { + if (doc == nullptr) { // Some error on reading. Abort. rt_terminate(); _p3dpython_running = false; @@ -1335,7 +1338,7 @@ rt_thread_run() { void P3DSession:: rt_handle_request(TiXmlDocument *doc) { TiXmlElement *xresponse = doc->FirstChildElement("response"); - if (xresponse != (TiXmlElement *)NULL) { + if (xresponse != nullptr) { int response_id; if (xresponse->QueryIntAttribute("response_id", &response_id) == TIXML_SUCCESS) { // This is a response to a previous command-and-response. Send it to @@ -1350,7 +1353,7 @@ rt_handle_request(TiXmlDocument *doc) { } TiXmlElement *xrequest = doc->FirstChildElement("request"); - if (xrequest != (TiXmlElement *)NULL) { + if (xrequest != nullptr) { int instance_id; if (xrequest->QueryIntAttribute("instance_id", &instance_id) == TIXML_SUCCESS) { // Look up the particular instance this is related to. @@ -1360,13 +1363,13 @@ rt_handle_request(TiXmlDocument *doc) { if (ii != _instances.end()) { P3DInstance *inst = (*ii).second; inst->add_raw_request(doc); - doc = NULL; + doc = nullptr; } RELEASE_LOCK(_instances_lock); } } - if (doc != NULL) { + if (doc != nullptr) { delete doc; } } @@ -1418,7 +1421,7 @@ win_create_process() { HANDLE handle = CreateFileW (log_pathname_w.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - NULL, CREATE_ALWAYS, 0, NULL); + nullptr, CREATE_ALWAYS, 0, nullptr); if (handle != INVALID_HANDLE_VALUE) { error_handle = handle; SetHandleInformation(error_handle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); @@ -1447,7 +1450,7 @@ win_create_process() { const wchar_t *start_dir_cstr; wstring start_dir_w; if (_keep_user_env) { - start_dir_cstr = NULL; + start_dir_cstr = nullptr; nout << "Not changing working directory.\n"; } else { string_to_wstring(start_dir_w, _start_dir); @@ -1457,7 +1460,7 @@ win_create_process() { // Construct the command-line string, containing the quoted command-line // arguments. - ostringstream stream; + std::ostringstream stream; stream << "\"" << _p3dpython_exe << "\" \"" << _mf_filename << "\" \"" << _input_handle << "\" \"" << _output_handle << "\" \"" << _interactive_console << "\""; @@ -1479,7 +1482,7 @@ win_create_process() { PROCESS_INFORMATION process_info; BOOL result = CreateProcessW - (p3dpython_exe_w.c_str(), command_line, NULL, NULL, TRUE, + (p3dpython_exe_w.c_str(), command_line, nullptr, nullptr, TRUE, CREATE_UNICODE_ENVIRONMENT, (void *)env_w.c_str(), start_dir_cstr, &startup_info, &process_info); bool started_program = (result != 0); @@ -1569,7 +1572,7 @@ posix_create_process() { } // build up an array of char strings for the environment. - vector ptrs; + std::vector ptrs; size_t p = 0; size_t zero = _env.find('\0', p); while (zero != string::npos) { @@ -1577,13 +1580,13 @@ posix_create_process() { p = zero + 1; zero = _env.find('\0', p); } - ptrs.push_back((char *)NULL); + ptrs.push_back(nullptr); - stringstream input_handle_stream; + std::stringstream input_handle_stream; input_handle_stream << _input_handle; string input_handle_str = input_handle_stream.str(); - stringstream output_handle_stream; + std::stringstream output_handle_stream; output_handle_stream << _output_handle; string output_handle_str = output_handle_stream.str(); @@ -1605,7 +1608,7 @@ posix_create_process() { // program" message. Maybe I'll put in the more reliable test later. struct timeval start; - gettimeofday(&start, NULL); + gettimeofday(&start, nullptr); int start_ms = start.tv_sec * 1000 + start.tv_usec / 1000; int status; @@ -1617,7 +1620,7 @@ posix_create_process() { } struct timeval now; - gettimeofday(&now, NULL); + gettimeofday(&now, nullptr); int now_ms = now.tv_sec * 1000 + now.tv_usec / 1000; int elapsed = now_ms - start_ms; if (elapsed > 100) { @@ -1631,7 +1634,7 @@ posix_create_process() { struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 1; - select(0, NULL, NULL, NULL, &tv); + select(0, nullptr, nullptr, nullptr, &tv); result = waitpid(child, &status, WNOHANG); } @@ -1684,7 +1687,7 @@ p3dpython_thread_run() { _putenv(start); #else const char *equals = strchr(start, '='); - if (equals != NULL) { + if (equals != nullptr) { string variable(start, equals - start); setenv(variable.c_str(), equals + 1, true); } @@ -1703,7 +1706,7 @@ p3dpython_thread_run() { #endif SetErrorMode(0); HMODULE module = LoadLibrary(libp3dpython.c_str()); - if (module == NULL) { + if (module == nullptr) { // Couldn't load the DLL. nout << "Couldn't load " << libp3dpython << "\n"; return; @@ -1719,7 +1722,7 @@ p3dpython_thread_run() { libp3dpython += ".so"; #endif void *module = dlopen(libp3dpython.c_str(), RTLD_LAZY | RTLD_LOCAL); - if (module == NULL) { + if (module == nullptr) { // Couldn't load the .so. nout << "Couldn't load " << libp3dpython << "\n"; return; @@ -1730,7 +1733,7 @@ p3dpython_thread_run() { #endif // _WIN32 run_p3dpython_func *run_p3dpython = (run_p3dpython_func *)get_func(module, "run_p3dpython"); - if (run_p3dpython == NULL) { + if (run_p3dpython == nullptr) { nout << "Couldn't find run_p3dpython\n"; return; } @@ -1755,14 +1758,14 @@ get_env(string &value, const string &varname) { wstring varname_w; string_to_wstring(varname_w, varname); const wchar_t *vc = _wgetenv(varname_w.c_str()); - if (vc == NULL) { + if (vc == nullptr) { return false; } wstring_to_string(value, vc); return true; #else // _WIN32 const char *vc = getenv(varname.c_str()); - if (vc == NULL) { + if (vc == nullptr) { return false; } value = vc; diff --git a/direct/src/plugin/p3dSession.h b/direct/src/plugin/p3dSession.h index 88db279379..eca5702fd6 100644 --- a/direct/src/plugin/p3dSession.h +++ b/direct/src/plugin/p3dSession.h @@ -39,8 +39,8 @@ public: void shutdown(); - inline const string &get_session_key() const; - inline const string &get_log_pathname() const; + inline const std::string &get_session_key() const; + inline const std::string &get_log_pathname() const; inline bool get_matches_script_origin() const; void start_instance(P3DInstance *inst); @@ -67,7 +67,7 @@ private: void spawn_read_thread(); void join_read_thread(); - static void replace_slashes(string &str); + static void replace_slashes(std::string &str); private: // These methods run only within the read thread. @@ -87,42 +87,42 @@ private: THREAD_CALLBACK_DECLARATION(P3DSession, p3dpython_thread_run); void p3dpython_thread_run(); - static bool get_env(string &value, const string &varname); + static bool get_env(std::string &value, const std::string &varname); void write_env() const; private: int _session_id; - string _session_key; - string _log_pathname; - string _python_root_dir; - string _start_dir; + std::string _session_key; + std::string _log_pathname; + std::string _python_root_dir; + std::string _start_dir; bool _matches_script_origin; bool _keep_user_env; bool _failed; // This information is passed to create_process(), or to // p3dpython_thread_run(). - string _p3dpython_exe; - string _p3dpython_dll; - string _mf_filename; - string _env; + std::string _p3dpython_exe; + std::string _p3dpython_dll; + std::string _mf_filename; + std::string _env; FHandle _input_handle, _output_handle; bool _interactive_console; - typedef map Instances; + typedef std::map Instances; Instances _instances; LOCK _instances_lock; // Commands that are queued up to send down the pipe. Normally these only // accumulate before the python process has been started; after that, // commands are written to the pipe directly. - typedef vector Commands; + typedef std::vector Commands; Commands _commands; // This map keeps track of the P3D_object pointers we have delivered to the // child process. We have to keep each of these until the child process // tells us it's safe to delete them. - typedef map SentObjects; + typedef std::map SentObjects; SentObjects _sent_objects; P3DPackage *_panda3d; @@ -146,7 +146,7 @@ private: bool _p3dpython_running; // The _response_ready mutex protects this structure. - typedef map Responses; + typedef std::map Responses; Responses _responses; P3DConditionVar _response_ready; diff --git a/direct/src/plugin/p3dSplashWindow.cxx b/direct/src/plugin/p3dSplashWindow.cxx index dc17b5c95a..13bcc09ff2 100644 --- a/direct/src/plugin/p3dSplashWindow.cxx +++ b/direct/src/plugin/p3dSplashWindow.cxx @@ -20,6 +20,10 @@ #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" +using std::max; +using std::min; +using std::string; + // The number of pixels to move the block per byte downloaded, when we don't // know the actual file size we're downloading. const double P3DSplashWindow::_unknown_progress_rate = 1.0 / 4096; @@ -348,10 +352,10 @@ read_image_data(ImageData &image, string &data, unsigned char *imgdata = stbi_load(image_filename.c_str(), &image._width, &image._height, &image._num_channels, 0); - if (imgdata == NULL) { + if (imgdata == nullptr) { nout << "Couldn't read splash file image: " << image_filename << "\n"; const char *reason = stbi_failure_reason(); - if (reason != NULL) { + if (reason != nullptr) { nout << "stbi_failure_reason: " << reason << "\n"; } return false; @@ -492,7 +496,7 @@ set_mouse_data(int mouse_x, int mouse_y, bool mouse_down) { */ void P3DSplashWindow:: button_click_detected() { - assert(_inst != NULL); + assert(_inst != nullptr); nout << "Play button clicked by user\n"; _inst->splash_button_clicked_sub_thread(); } diff --git a/direct/src/plugin/p3dSplashWindow.h b/direct/src/plugin/p3dSplashWindow.h index 65c7301d7c..4f67b5c1c0 100644 --- a/direct/src/plugin/p3dSplashWindow.h +++ b/direct/src/plugin/p3dSplashWindow.h @@ -60,7 +60,7 @@ public: FW_black = 900 }; - virtual void set_image_filename(const string &image_filename, + virtual void set_image_filename(const std::string &image_filename, ImagePlacement image_placement); void set_fgcolor(int r, int g, int b); void set_bgcolor(int r, int g, int b); @@ -70,11 +70,11 @@ public: void set_bar_bottom(int bottom); void set_bar_width(int width, bool percent=false); void set_bar_height(int height, bool percent=false); - void set_font_family(const string &family); + void set_font_family(const std::string &family); void set_font_size(int size); void set_font_style(FontStyle style); void set_font_weight(int weight); - virtual void set_install_label(const string &install_label); + virtual void set_install_label(const std::string &install_label); virtual void set_install_progress(double install_progress, bool is_progress_known, size_t received_data); @@ -93,8 +93,8 @@ protected: int _width, _height, _num_channels; }; - bool read_image_data(ImageData &image, string &data, - const string &image_filename); + bool read_image_data(ImageData &image, std::string &data, + const std::string &image_filename); void get_bar_placement(int &bar_x, int &bar_y, int &bar_width, int &bar_height); void set_button_range(const ImageData &image); @@ -131,7 +131,7 @@ private: double _bar_width_ratio, _bar_height_ratio; protected: - string _font_family; + std::string _font_family; int _font_size; FontStyle _font_style; int _font_weight; diff --git a/direct/src/plugin/p3dStringObject.cxx b/direct/src/plugin/p3dStringObject.cxx index d0188a65af..8d87a2dc8c 100644 --- a/direct/src/plugin/p3dStringObject.cxx +++ b/direct/src/plugin/p3dStringObject.cxx @@ -17,7 +17,7 @@ * */ P3DStringObject:: -P3DStringObject(const string &value) : _value(value) { +P3DStringObject(const std::string &value) : _value(value) { } /** @@ -65,7 +65,7 @@ get_bool() { * to a string. */ void P3DStringObject:: -make_string(string &value) { +make_string(std::string &value) { value = _value; } @@ -74,9 +74,9 @@ make_string(string &value) { * This is intended for developer assistance. */ void P3DStringObject:: -output(ostream &out) { +output(std::ostream &out) { out << '"'; - for (string::const_iterator si = _value.begin(); si != _value.end(); ++si) { + for (std::string::const_iterator si = _value.begin(); si != _value.end(); ++si) { if (isprint(*si)) { switch (*si) { case '"': diff --git a/direct/src/plugin/p3dStringObject.h b/direct/src/plugin/p3dStringObject.h index 22366023f7..3e358e56b9 100644 --- a/direct/src/plugin/p3dStringObject.h +++ b/direct/src/plugin/p3dStringObject.h @@ -22,7 +22,7 @@ */ class P3DStringObject : public P3DObject { public: - P3DStringObject(const string &value); + P3DStringObject(const std::string &value); P3DStringObject(const char *data, size_t size); P3DStringObject(const P3DStringObject ©); @@ -31,12 +31,12 @@ public: virtual P3D_object_type get_type(); virtual bool get_bool(); - virtual void make_string(string &value); + virtual void make_string(std::string &value); - virtual void output(ostream &out); + virtual void output(std::ostream &out); private: - string _value; + std::string _value; }; #endif diff --git a/direct/src/plugin/p3dTemporaryFile.I b/direct/src/plugin/p3dTemporaryFile.I index 104fefa420..c1d8eeb7e2 100644 --- a/direct/src/plugin/p3dTemporaryFile.I +++ b/direct/src/plugin/p3dTemporaryFile.I @@ -14,7 +14,7 @@ /** * Returns the temporary filename. */ -inline const string &P3DTemporaryFile:: +inline const std::string &P3DTemporaryFile:: get_filename() const { return _filename; } diff --git a/direct/src/plugin/p3dTemporaryFile.cxx b/direct/src/plugin/p3dTemporaryFile.cxx index ca7abe701a..bb7c8ca7a1 100644 --- a/direct/src/plugin/p3dTemporaryFile.cxx +++ b/direct/src/plugin/p3dTemporaryFile.cxx @@ -18,7 +18,7 @@ * Constructs a new, unique temporary filename. */ P3DTemporaryFile:: -P3DTemporaryFile(const string &extension) { +P3DTemporaryFile(const std::string &extension) { P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); _filename = inst_mgr->make_temp_filename(extension); } diff --git a/direct/src/plugin/p3dTemporaryFile.h b/direct/src/plugin/p3dTemporaryFile.h index f4b87df247..57fb6cef5a 100644 --- a/direct/src/plugin/p3dTemporaryFile.h +++ b/direct/src/plugin/p3dTemporaryFile.h @@ -26,16 +26,16 @@ */ class P3DTemporaryFile { public: - P3DTemporaryFile(const string &extension); + P3DTemporaryFile(const std::string &extension); ~P3DTemporaryFile(); - inline const string &get_filename() const; + inline const std::string &get_filename() const; private: - string _filename; + std::string _filename; }; -inline ostream &operator << (ostream &out, P3DTemporaryFile &tfile) { +inline std::ostream &operator << (std::ostream &out, P3DTemporaryFile &tfile) { return out << tfile.get_filename(); } diff --git a/direct/src/plugin/p3dUndefinedObject.cxx b/direct/src/plugin/p3dUndefinedObject.cxx index 80cbb5897d..0ed227573f 100644 --- a/direct/src/plugin/p3dUndefinedObject.cxx +++ b/direct/src/plugin/p3dUndefinedObject.cxx @@ -41,6 +41,6 @@ get_bool() { * to a string. */ void P3DUndefinedObject:: -make_string(string &value) { +make_string(std::string &value) { value = "Undefined"; } diff --git a/direct/src/plugin/p3dUndefinedObject.h b/direct/src/plugin/p3dUndefinedObject.h index 9ab8189de6..3cba1d73b4 100644 --- a/direct/src/plugin/p3dUndefinedObject.h +++ b/direct/src/plugin/p3dUndefinedObject.h @@ -29,7 +29,7 @@ public: public: virtual P3D_object_type get_type(); virtual bool get_bool(); - virtual void make_string(string &value); + virtual void make_string(std::string &value); }; #endif diff --git a/direct/src/plugin/p3dWinSplashWindow.I b/direct/src/plugin/p3dWinSplashWindow.I index 20cafcc1bf..bae5fb0680 100644 --- a/direct/src/plugin/p3dWinSplashWindow.I +++ b/direct/src/plugin/p3dWinSplashWindow.I @@ -17,7 +17,7 @@ inline P3DWinSplashWindow::WinImageData:: WinImageData() { _filename_changed = false; - _bitmap = NULL; + _bitmap = nullptr; } /** diff --git a/direct/src/plugin/p3dWinSplashWindow.cxx b/direct/src/plugin/p3dWinSplashWindow.cxx index eb4d242430..256acb5eb8 100644 --- a/direct/src/plugin/p3dWinSplashWindow.cxx +++ b/direct/src/plugin/p3dWinSplashWindow.cxx @@ -28,14 +28,14 @@ P3DWinSplashWindow:: P3DWinSplashWindow(P3DInstance *inst, bool make_visible) : P3DSplashWindow(inst, make_visible) { - _thread = NULL; + _thread = nullptr; _thread_id = 0; - _hwnd = NULL; - _font = NULL; - _fg_brush = NULL; - _bg_brush = NULL; - _bar_brush = NULL; - _bar_bg_brush = NULL; + _hwnd = nullptr; + _font = nullptr; + _fg_brush = nullptr; + _bg_brush = nullptr; + _bar_brush = nullptr; + _bar_bg_brush = nullptr; _thread_running = false; _install_progress = 0.0; _progress_known = true; @@ -95,9 +95,9 @@ set_visible(bool visible) { * the splash window. */ void P3DWinSplashWindow:: -set_image_filename(const string &image_filename, ImagePlacement image_placement) { +set_image_filename(const std::string &image_filename, ImagePlacement image_placement) { nout << "image_filename = " << image_filename << ", thread_id = " << _thread_id << "\n"; - WinImageData *image = NULL; + WinImageData *image = nullptr; switch (image_placement) { case IP_background: image = &_background_image; @@ -116,7 +116,7 @@ set_image_filename(const string &image_filename, ImagePlacement image_placement) image = &_button_click_image; break; } - if (image != NULL) { + if (image != nullptr) { ACQUIRE_LOCK(_install_lock); if (image->_filename != image_filename) { image->_filename = image_filename; @@ -141,7 +141,7 @@ set_image_filename(const string &image_filename, ImagePlacement image_placement) * Specifies the text that is displayed above the install progress bar. */ void P3DWinSplashWindow:: -set_install_label(const string &install_label) { +set_install_label(const std::string &install_label) { ACQUIRE_LOCK(_install_lock); if (_install_label != install_label) { _install_label = install_label; @@ -211,13 +211,13 @@ request_keyboard_focus() { void P3DWinSplashWindow:: register_window_class() { if (!_registered_window_class) { - HINSTANCE application = GetModuleHandle(NULL); + HINSTANCE application = GetModuleHandle(nullptr); WNDCLASS wc; ZeroMemory(&wc, sizeof(WNDCLASS)); wc.lpfnWndProc = (WNDPROC)st_window_proc; wc.hInstance = application; - wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.hCursor = LoadCursor(nullptr, IDC_ARROW); wc.lpszClassName = "panda3d_splash"; if (!RegisterClass(&wc)) { @@ -234,7 +234,7 @@ register_window_class() { void P3DWinSplashWindow:: unregister_window_class() { if (_registered_window_class) { - HINSTANCE application = GetModuleHandle(NULL); + HINSTANCE application = GetModuleHandle(nullptr); if (!UnregisterClass("panda3d_splash", application)) { nout << "Could not unregister window class panda3d_splash\n"; @@ -261,8 +261,8 @@ void P3DWinSplashWindow:: start_thread() { _thread_continue = true; _thread_running = true; - _thread = CreateThread(NULL, 0, &win_thread_run, this, 0, &_thread_id); - if (_thread == NULL) { + _thread = CreateThread(nullptr, 0, &win_thread_run, this, 0, &_thread_id); + if (_thread == nullptr) { // Thread never got started. _thread_running = false; } @@ -280,17 +280,17 @@ stop_thread() { PostThreadMessage(_thread_id, WM_USER, 0, 0); } - if (_thread != NULL){ + if (_thread != nullptr){ // If the thread doesn't close right away, call PeekMessage() to check for // Windows messages that the thread might be waiting for. while (WaitForSingleObject(_thread, 200) == WAIT_TIMEOUT) { MSG msg; - PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE | PM_NOYIELD); + PeekMessage(&msg, nullptr, 0, 0, PM_NOREMOVE | PM_NOYIELD); nout << "Waiting for thread\n"; } CloseHandle(_thread); - _thread = NULL; + _thread = nullptr; // Now that the thread has exited, we can safely close its window. (We // couldn't close the window in the thread, because that would cause a @@ -310,7 +310,7 @@ thread_run() { int last_focus_seq = 0; MSG msg; int retval; - retval = GetMessage(&msg, NULL, 0, 0); + retval = GetMessage(&msg, nullptr, 0, 0); while (retval != 0 && _thread_continue) { if (retval == -1) { nout << "Error processing message queue.\n"; @@ -329,7 +329,7 @@ thread_run() { if (_drawn_label != _install_label) { // The label has changed. Redraw. _drawn_label = _install_label; - InvalidateRect(_hwnd, NULL, TRUE); + InvalidateRect(_hwnd, nullptr, TRUE); } // Also redraw when the progress bar changes. @@ -349,25 +349,25 @@ thread_run() { _drawn_progress = _install_progress; _drawn_progress_known = _progress_known; _drawn_received_data = _received_data; - InvalidateRect(_hwnd, NULL, TRUE); + InvalidateRect(_hwnd, nullptr, TRUE); } if (_drawn_bstate != _bstate) { // The button has changed state. Redraw it. _drawn_bstate = _bstate; - InvalidateRect(_hwnd, NULL, TRUE); + InvalidateRect(_hwnd, nullptr, TRUE); } if (_focus_seq != last_focus_seq) { last_focus_seq = _focus_seq; - if (SetFocus(_hwnd) == NULL && GetLastError() != 0) { + if (SetFocus(_hwnd) == nullptr && GetLastError() != 0) { nout << "SetFocus(" << _hwnd << ") failed: " << GetLastError() << "\n"; } } RELEASE_LOCK(_install_lock); - retval = GetMessage(&msg, NULL, 0, 0); + retval = GetMessage(&msg, nullptr, 0, 0); } // Tell our parent thread that we're done. @@ -392,7 +392,7 @@ win_thread_run(LPVOID data) { void P3DWinSplashWindow:: make_window() { register_window_class(); - HINSTANCE application = GetModuleHandle(NULL); + HINSTANCE application = GetModuleHandle(nullptr); int width = 320; int height = 240; @@ -420,7 +420,7 @@ make_window() { _hwnd = CreateWindow("panda3d_splash", "Panda3D", window_style, x, y, width, height, - parent_hwnd, NULL, application, 0); + parent_hwnd, nullptr, application, 0); if (!_hwnd) { nout << "Could not create embedded window!\n"; @@ -442,7 +442,7 @@ make_window() { x, y, win_rect.right - win_rect.left, win_rect.bottom - win_rect.top, - NULL, NULL, application, 0); + nullptr, nullptr, application, 0); if (!_hwnd) { nout << "Could not create toplevel window!\n"; return; @@ -463,7 +463,7 @@ make_window() { ANSI_CHARSET, OUT_OUTLINE_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, VARIABLE_PITCH, _font_family.c_str()); - if (_font == NULL) { + if (_font == nullptr) { nout << "CreateFont failed: " << GetLastError() << "\n"; _font = (HFONT)GetStockObject(ANSI_VAR_FONT); } @@ -490,10 +490,10 @@ update_image(WinImageData &image) { image.dump_image(); // Since we'll be displaying a new image, we need to refresh the window. - InvalidateRect(_hwnd, NULL, TRUE); + InvalidateRect(_hwnd, nullptr, TRUE); // Go read the image. - string data; + std::string data; if (!read_image_data(image, data, image._filename)) { return; } @@ -583,27 +583,27 @@ update_image(WinImageData &image) { */ void P3DWinSplashWindow:: close_window() { - if (_hwnd != NULL) { + if (_hwnd != nullptr) { ShowWindow(_hwnd, SW_HIDE); CloseWindow(_hwnd); - _hwnd = NULL; + _hwnd = nullptr; } - if (_fg_brush != NULL) { + if (_fg_brush != nullptr) { DeleteObject(_fg_brush); - _fg_brush = NULL; + _fg_brush = nullptr; } - if (_bg_brush != NULL) { + if (_bg_brush != nullptr) { DeleteObject(_bg_brush); - _bg_brush = NULL; + _bg_brush = nullptr; } - if (_bar_brush != NULL) { + if (_bar_brush != nullptr) { DeleteObject(_bar_brush); - _bar_brush = NULL; + _bar_brush = nullptr; } - if (_bar_bg_brush != NULL) { + if (_bar_bg_brush != nullptr) { DeleteObject(_bar_bg_brush); - _bar_bg_brush = NULL; + _bar_bg_brush = nullptr; } _background_image.dump_image(); @@ -677,7 +677,7 @@ paint_window(HDC dc) { */ bool P3DWinSplashWindow:: paint_image(HDC dc, const WinImageData &image, bool use_alpha) { - if (image._bitmap == NULL) { + if (image._bitmap == nullptr) { return false; } @@ -715,7 +715,7 @@ paint_image(HDC dc, const WinImageData &image, bool use_alpha) { // The bitmap is larger than the window; scale it down. double x_scale = (double)_win_width / (double)image._width; double y_scale = (double)_win_height / (double)image._height; - double scale = min(x_scale, y_scale); + double scale = std::min(x_scale, y_scale); int sc_width = (int)(image._width * scale); int sc_height = (int)(image._height * scale); @@ -738,7 +738,7 @@ paint_image(HDC dc, const WinImageData &image, bool use_alpha) { } } - SelectObject(mem_dc, NULL); + SelectObject(mem_dc, nullptr); DeleteDC(mem_dc); return true; @@ -831,7 +831,7 @@ window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { break; case WM_SIZE: - InvalidateRect(hwnd, NULL, FALSE); + InvalidateRect(hwnd, nullptr, FALSE); break; case WM_ERASEBKGND: @@ -869,7 +869,7 @@ window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { { int elapsed = GetTickCount() - _request_focus_tick; if (elapsed < 200) { - if (SetFocus(_hwnd) == NULL && GetLastError() != 0) { + if (SetFocus(_hwnd) == nullptr && GetLastError() != 0) { nout << "Secondary SetFocus failed: " << GetLastError() << "\n"; } } @@ -889,7 +889,7 @@ window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { case WM_KEYDOWN: case WM_SYSKEYUP: case WM_KEYUP: - if (_inst->get_session() != NULL) { + if (_inst->get_session() != nullptr) { _inst->get_session()->send_windows_message(_inst, msg, wparam, lparam); } break; @@ -904,7 +904,7 @@ window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { LRESULT P3DWinSplashWindow:: st_window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { LONG_PTR self = GetWindowLongPtr(hwnd, GWLP_USERDATA); - if (self == NULL) { + if (self == nullptr) { // We haven't assigned the pointer yet. return DefWindowProc(hwnd, msg, wparam, lparam); } @@ -917,9 +917,9 @@ st_window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { */ void P3DWinSplashWindow::WinImageData:: dump_image() { - if (_bitmap != NULL) { + if (_bitmap != nullptr) { DeleteObject(_bitmap); - _bitmap = NULL; + _bitmap = nullptr; } } diff --git a/direct/src/plugin/p3dWinSplashWindow.h b/direct/src/plugin/p3dWinSplashWindow.h index 852d794cb8..713157c921 100644 --- a/direct/src/plugin/p3dWinSplashWindow.h +++ b/direct/src/plugin/p3dWinSplashWindow.h @@ -34,9 +34,9 @@ public: virtual void set_wparams(const P3DWindowParams &wparams); virtual void set_visible(bool visible); - virtual void set_image_filename(const string &image_filename, + virtual void set_image_filename(const std::string &image_filename, ImagePlacement image_placement); - virtual void set_install_label(const string &install_label); + virtual void set_install_label(const std::string &install_label); virtual void set_install_progress(double install_progress, bool is_progress_known, size_t received_data); virtual void request_keyboard_focus(); @@ -75,7 +75,7 @@ private: inline ~WinImageData(); void dump_image(); - string _filename; + std::string _filename; bool _filename_changed; HBITMAP _bitmap; }; @@ -86,14 +86,14 @@ private: WinImageData _button_click_image; bool _got_install; - string _install_label; + std::string _install_label; double _install_progress; bool _progress_known; size_t _received_data; LOCK _install_lock; ButtonState _drawn_bstate; - string _drawn_label; + std::string _drawn_label; double _drawn_progress; bool _drawn_progress_known; size_t _drawn_received_data; diff --git a/direct/src/plugin/p3dWindowParams.cxx b/direct/src/plugin/p3dWindowParams.cxx index e6e9b750e4..29ed954823 100644 --- a/direct/src/plugin/p3dWindowParams.cxx +++ b/direct/src/plugin/p3dWindowParams.cxx @@ -78,7 +78,7 @@ make_xml(P3DInstance *inst) { // TinyXml doesn't support a "long" attribute. We'll use stringstream to // do it ourselves. { - ostringstream strm; + std::ostringstream strm; assert(_parent_window._window_handle_type == P3D_WHT_x11_window); strm << _parent_window._handle._x11_window._xwindow; xwparams->SetAttribute("parent_xwindow", strm.str()); diff --git a/direct/src/plugin/p3dX11SplashWindow.cxx b/direct/src/plugin/p3dX11SplashWindow.cxx index 8be0edb050..07e5fc4d99 100644 --- a/direct/src/plugin/p3dX11SplashWindow.cxx +++ b/direct/src/plugin/p3dX11SplashWindow.cxx @@ -24,6 +24,9 @@ #include #include +using std::string; +using std::vector; + /** * */ @@ -39,12 +42,12 @@ P3DX11SplashWindow(P3DInstance *inst, bool make_visible) : INIT_THREAD(_read_thread); // Init for subprocess - _composite_image = NULL; + _composite_image = nullptr; _needs_new_composite = false; _display = None; _window = None; _screen = 0; - _font = NULL; + _font = nullptr; _graphics_context = None; _bar_context = None; _bar_bg_context = None; @@ -285,7 +288,7 @@ stop_subprocess() { // Wait for a certain amount of time for the process to stop by itself. struct timeval start; - gettimeofday(&start, NULL); + gettimeofday(&start, nullptr); int start_ms = start.tv_sec * 1000 + start.tv_usec / 1000; int status; @@ -297,7 +300,7 @@ stop_subprocess() { } struct timeval now; - gettimeofday(&now, NULL); + gettimeofday(&now, nullptr); int now_ms = now.tv_sec * 1000 + now.tv_usec / 1000; int elapsed = now_ms - start_ms; @@ -313,7 +316,7 @@ stop_subprocess() { struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 1; - select(0, NULL, NULL, NULL, &tv); + select(0, nullptr, nullptr, nullptr, &tv); result = waitpid(_subprocess_pid, &status, WNOHANG); } @@ -406,7 +409,7 @@ void P3DX11SplashWindow:: rt_thread_run() { while (true) { TiXmlDocument *doc = read_xml(_pipe_read, nout); - if (doc == NULL) { + if (doc == nullptr) { // Some error on reading. The splash window must have gone away, e.g. // because the user explicitly closed it; tell the instance to exit. _inst->request_stop_sub_thread(); @@ -648,7 +651,7 @@ subprocess_run() { tv.tv_sec = 0; tv.tv_usec = 1000; // 1 usec is not enough. - int result = select(read_fd + 1, &fds, NULL, NULL, &tv); + int result = select(read_fd + 1, &fds, nullptr, nullptr, &tv); if (result > 0) { // There is some noise on the pipe, so read it. input_ready = true; @@ -668,7 +671,7 @@ subprocess_run() { struct timespec req; req.tv_sec = 0; req.tv_nsec = 50000000; // 50 ms - nanosleep(&req, NULL); + nanosleep(&req, nullptr); } close_window(); @@ -680,22 +683,22 @@ subprocess_run() { void P3DX11SplashWindow:: receive_command() { TiXmlDocument *doc = read_xml(_pipe_read, nout); - if (doc == NULL) { + if (doc == nullptr) { // Pipe closed or something. _subprocess_continue = false; return; } TiXmlElement *xcommand = doc->FirstChildElement("command"); - if (xcommand != NULL) { + if (xcommand != nullptr) { const char *cmd = xcommand->Attribute("cmd"); - if (cmd != NULL) { + if (cmd != nullptr) { if (strcmp(cmd, "exit") == 0) { _subprocess_continue = false; } else if (strcmp(cmd, "set_visible") == 0) { int visible = 0; - if (xcommand->Attribute("visible", &visible) != NULL) { + if (xcommand->Attribute("visible", &visible) != nullptr) { _visible = visible; if (_visible) { XMapWindow(_display, _window); @@ -707,10 +710,10 @@ receive_command() { } else if (strcmp(cmd, "set_image_filename") == 0) { const string *image_filename = xcommand->Attribute(string("image_filename")); int image_placement; - if (image_filename != NULL && + if (image_filename != nullptr && xcommand->QueryIntAttribute("image_placement", &image_placement) == TIXML_SUCCESS) { - X11ImageData *image = NULL; + X11ImageData *image = nullptr; switch ((ImagePlacement)image_placement) { case IP_background: image = &_background_image; @@ -732,7 +735,7 @@ receive_command() { case IP_none: break; } - if (image != NULL) { + if (image != nullptr) { if (image->_filename != *image_filename) { image->_filename = *image_filename; image->_filename_changed = true; @@ -742,7 +745,7 @@ receive_command() { } else if (strcmp(cmd, "set_install_label") == 0) { const char *str = xcommand->Attribute("install_label"); - if (str != NULL) { + if (str != nullptr) { if (_install_label != string(str)) { _install_label = str; } @@ -775,7 +778,7 @@ receive_command() { */ void P3DX11SplashWindow:: redraw() { - if (_composite_image == NULL) { + if (_composite_image == nullptr) { // Clear the whole window, if there's no image. XClearWindow(_display, _window); @@ -823,10 +826,10 @@ make_window() { // _display = (X11_Display*) _wparams.get_parent_window()._xdisplay; // _own_display = false; if (_display == 0) { - _display = XOpenDisplay(NULL); + _display = XOpenDisplay(nullptr); _own_display = true; // } - assert(_display != NULL); + assert(_display != nullptr); _screen = DefaultScreen(_display); int x = _wparams.get_win_x(); @@ -972,7 +975,7 @@ setup_gc() { _font_family.c_str(), weight_name, style, _font_size); _font = XLoadQueryFont(_display, font_name); - if (_font != NULL) { + if (_font != nullptr) { break; } nout << "Font " << font_name << " unavailable.\n"; @@ -984,14 +987,14 @@ setup_gc() { _font_family.c_str(), weight_name, style2, _font_size); _font = XLoadQueryFont(_display, font_name); - if (_font != NULL) { + if (_font != nullptr) { break; } nout << "Font " << font_name << " unavailable.\n"; } } - if (_font != NULL) { + if (_font != nullptr) { nout << "Loaded font " << font_name << "\n"; } else { nout << "Using fallback font 6x13.\n"; @@ -1054,9 +1057,9 @@ setup_gc() { */ void P3DX11SplashWindow:: close_window() { - if (_composite_image != NULL) { + if (_composite_image != nullptr) { XDestroyImage(_composite_image); - _composite_image = NULL; + _composite_image = nullptr; } if (_bar_context != None) { @@ -1136,9 +1139,9 @@ update_image(X11ImageData &image) { */ void P3DX11SplashWindow:: compose_image() { - if (_composite_image != NULL) { + if (_composite_image != nullptr) { XDestroyImage(_composite_image); - _composite_image = NULL; + _composite_image = nullptr; } _needs_new_composite = false; @@ -1284,7 +1287,7 @@ scale_image(vector &image0, int &image0_width, int &image0_height } else { // Yuck, the bad case - we need to scale it down. - double scale = min((double)_win_width / (double)image._width, + double scale = std::min((double)_win_width / (double)image._width, (double)_win_height / (double)image._height); image0_width = (int)(image._width * scale); image0_height = (int)(image._height * scale); @@ -1335,8 +1338,8 @@ compose_two_images(vector &image0, int &image0_width, int &image0 const vector &image1, int image1_width, int image1_height, const vector &image2, int image2_width, int image2_height) { // First, the resulting image size is the larger of the two. - image0_width = max(image1_width, image2_width); - image0_height = max(image1_height, image2_height); + image0_width = std::max(image1_width, image2_width); + image0_height = std::max(image1_height, image2_height); int new_row_stride = image0_width * 4; int new_data_length = image0_height * new_row_stride; diff --git a/direct/src/plugin/p3dX11SplashWindow.h b/direct/src/plugin/p3dX11SplashWindow.h index 892fc6e4cb..72c6ac00d0 100644 --- a/direct/src/plugin/p3dX11SplashWindow.h +++ b/direct/src/plugin/p3dX11SplashWindow.h @@ -34,9 +34,9 @@ public: virtual void set_wparams(const P3DWindowParams &wparams); virtual void set_visible(bool visible); - virtual void set_image_filename(const string &image_filename, + virtual void set_image_filename(const std::string &image_filename, ImagePlacement image_placement); - virtual void set_install_label(const string &install_label); + virtual void set_install_label(const std::string &install_label); virtual void set_install_progress(double install_progress, bool is_progress_known, size_t received_data); @@ -85,12 +85,12 @@ private: void update_image(X11ImageData &image); void compose_image(); - bool scale_image(vector &image0, int &image0_width, int &image0_height, + bool scale_image(std::vector &image0, int &image0_width, int &image0_height, X11ImageData &image); - void compose_two_images(vector &image0, int &image0_width, int &image0_height, - const vector &image1, int image1_width, int image1_height, - const vector &image2, int image2_width, int image2_height); + void compose_two_images(std::vector &image0, int &image0_width, int &image0_height, + const std::vector &image1, int image1_width, int image1_height, + const std::vector &image2, int image2_width, int image2_height); private: // Data members that are stored in the subprocess. @@ -99,9 +99,9 @@ private: inline X11ImageData(); inline ~X11ImageData(); - string _filename; + std::string _filename; bool _filename_changed; - string _data; + std::string _data; }; X11ImageData _background_image; @@ -116,12 +116,12 @@ private: bool _subprocess_continue; bool _own_display; - string _install_label; + std::string _install_label; double _install_progress; bool _progress_known; size_t _received_data; - string _label_text; + std::string _label_text; X11_Display *_display; int _screen; diff --git a/direct/src/plugin/p3d_lock.h b/direct/src/plugin/p3d_lock.h index ed923de304..7c11ca5bb4 100644 --- a/direct/src/plugin/p3d_lock.h +++ b/direct/src/plugin/p3d_lock.h @@ -44,15 +44,15 @@ public: // Threads. #define THREAD HANDLE -#define INIT_THREAD(thread) (thread) = NULL; +#define INIT_THREAD(thread) (thread) = nullptr; #define SPAWN_THREAD(thread, callback_function, this) \ - (thread) = CreateThread(NULL, 0, &win_ ## callback_function, (this), 0, NULL) + (thread) = CreateThread(nullptr, 0, &win_ ## callback_function, (this), 0, nullptr) #define JOIN_THREAD(thread) \ { \ - assert((thread) != NULL); \ + assert((thread) != nullptr); \ WaitForSingleObject((thread), INFINITE); \ CloseHandle((thread)); \ - (thread) = NULL; \ + (thread) = nullptr; \ } // Declare this macro within your class declaration. This implements the @@ -115,7 +115,7 @@ public: static void * \ posix_ ## callback_function(void *data) { \ ((class *)data)->callback_function(); \ - return NULL; \ + return nullptr; \ } #endif // _WIN32 diff --git a/direct/src/plugin/p3d_plugin.cxx b/direct/src/plugin/p3d_plugin.cxx index 8fc91c881e..7e6c01108b 100644 --- a/direct/src/plugin/p3d_plugin.cxx +++ b/direct/src/plugin/p3d_plugin.cxx @@ -61,35 +61,35 @@ P3D_initialize(int api_version, const char *contents_filename, } ACQUIRE_LOCK(_api_lock); - if (contents_filename == NULL){ + if (contents_filename == nullptr){ contents_filename = ""; } - if (host_url == NULL){ + if (host_url == nullptr){ host_url = ""; } - if (platform == NULL) { + if (platform == nullptr) { platform = ""; } - if (log_directory == NULL) { + if (log_directory == nullptr) { log_directory = ""; } - if (log_basename == NULL) { + if (log_basename == nullptr) { log_basename = ""; } - if (api_version < 12 || root_dir == NULL) { + if (api_version < 12 || root_dir == nullptr) { root_dir = ""; } - if (api_version < 16 || host_dir == NULL) { + if (api_version < 16 || host_dir == nullptr) { host_dir = ""; } - if (api_version < 17 || start_dir == NULL) { + if (api_version < 17 || start_dir == nullptr) { start_dir = ""; } @@ -116,10 +116,10 @@ P3D_set_plugin_version(int major, int minor, int sequence, const char *coreapi_timestamp_str, const char *coreapi_set_ver) { assert(P3DInstanceManager::get_global_ptr()->is_initialized()); - if (distributor == NULL) { + if (distributor == nullptr) { distributor = ""; } - if (coreapi_host_url == NULL) { + if (coreapi_host_url == nullptr) { coreapi_host_url = ""; } @@ -133,10 +133,10 @@ P3D_set_plugin_version(int major, int minor, int sequence, } else { // Passing a time_t causes problems with disagreements about word size, so // since version 15 we pass it as a string. - coreapi_timestamp = strtoul(coreapi_timestamp_str, NULL, 10); + coreapi_timestamp = strtoul(coreapi_timestamp_str, nullptr, 10); } - if (inst_mgr->get_api_version() < 14 || coreapi_set_ver == NULL) { + if (inst_mgr->get_api_version() < 14 || coreapi_set_ver == nullptr) { // Prior to version 14 this parameter was absent. coreapi_set_ver = ""; } @@ -150,7 +150,7 @@ P3D_set_plugin_version(int major, int minor, int sequence, void P3D_set_super_mirror(const char *super_mirror_url) { assert(P3DInstanceManager::get_global_ptr()->is_initialized()); - if (super_mirror_url == NULL) { + if (super_mirror_url == nullptr) { super_mirror_url = ""; } @@ -177,7 +177,7 @@ bool P3D_instance_start(P3D_instance *instance, bool is_local, const char *p3d_filename, int p3d_offset) { assert(P3DInstanceManager::get_global_ptr()->is_initialized()); - if (p3d_filename == NULL) { + if (p3d_filename == nullptr) { p3d_filename = ""; } ACQUIRE_LOCK(_api_lock); @@ -190,7 +190,7 @@ P3D_instance_start(P3D_instance *instance, bool is_local, P3DInstance *inst = inst_mgr->validate_instance(instance); bool result = false; - if (inst != NULL) { + if (inst != nullptr) { // We don't actually start it immediately; the instance will have to // download the p3d url and read it, reading the python version, before it // can start. @@ -204,14 +204,14 @@ P3D_instance_start(P3D_instance *instance, bool is_local, int P3D_instance_start_stream(P3D_instance *instance, const char *p3d_url) { assert(P3DInstanceManager::get_global_ptr()->is_initialized()); - if (p3d_url == NULL) { + if (p3d_url == nullptr) { p3d_url = ""; } ACQUIRE_LOCK(_api_lock); P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); P3DInstance *inst = inst_mgr->validate_instance(instance); int result = -1; - if (inst != NULL) { + if (inst != nullptr) { result = inst_mgr->make_p3d_stream(inst, p3d_url); } RELEASE_LOCK(_api_lock); @@ -224,7 +224,7 @@ P3D_instance_finish(P3D_instance *instance) { ACQUIRE_LOCK(_api_lock); P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); P3DInstance *inst = inst_mgr->validate_instance(instance); - if (inst != NULL) { + if (inst != nullptr) { inst_mgr->finish_instance(inst); } RELEASE_LOCK(_api_lock); @@ -243,7 +243,7 @@ P3D_instance_setup_window(P3D_instance *instance, ACQUIRE_LOCK(_api_lock); P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); P3DInstance *inst = inst_mgr->validate_instance(instance); - if (inst != NULL) { + if (inst != nullptr) { inst->set_wparams(wparams); } RELEASE_LOCK(_api_lock); @@ -356,7 +356,7 @@ P3D_object_eval(P3D_object *object, const char *expression) { void P3D_object_incref(P3D_object *object) { assert(P3DInstanceManager::get_global_ptr()->is_initialized()); - if (object != NULL) { + if (object != nullptr) { ACQUIRE_LOCK(_api_lock); P3D_OBJECT_INCREF(object); RELEASE_LOCK(_api_lock); @@ -366,7 +366,7 @@ P3D_object_incref(P3D_object *object) { void P3D_object_decref(P3D_object *object) { assert(P3DInstanceManager::get_global_ptr()->is_initialized()); - if (object != NULL) { + if (object != nullptr) { ACQUIRE_LOCK(_api_lock); P3D_OBJECT_DECREF(object); RELEASE_LOCK(_api_lock); @@ -448,7 +448,7 @@ P3D_new_string_object(const char *str, int length) { assert(P3DInstanceManager::get_global_ptr()->is_initialized()); ACQUIRE_LOCK(_api_lock); - P3D_object *result = new P3DStringObject(string(str, length)); + P3D_object *result = new P3DStringObject(std::string(str, length)); RELEASE_LOCK(_api_lock); return result; @@ -461,8 +461,8 @@ P3D_instance_get_panda_script_object(P3D_instance *instance) { P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); P3DInstance *inst = inst_mgr->validate_instance(instance); - P3D_object *result = NULL; - if (inst != NULL) { + P3D_object *result = nullptr; + if (inst != nullptr) { result = inst->get_panda_script_object(); } @@ -478,7 +478,7 @@ P3D_instance_set_browser_script_object(P3D_instance *instance, P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); P3DInstance *inst = inst_mgr->validate_instance(instance); - if (inst != NULL) { + if (inst != nullptr) { inst->set_browser_script_object(object); } @@ -493,8 +493,8 @@ P3D_instance_get_request(P3D_instance *instance) { P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); P3DInstance *inst = inst_mgr->validate_instance(instance); - P3D_request *result = NULL; - if (inst != NULL) { + P3D_request *result = nullptr; + if (inst != nullptr) { result = inst->get_request(); } @@ -509,7 +509,7 @@ P3D_check_request(double timeout) { P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); P3D_instance *inst = inst_mgr->check_request(); - if (inst != NULL || timeout <= 0.0) { + if (inst != nullptr || timeout <= 0.0) { RELEASE_LOCK(_api_lock); return inst; } @@ -518,7 +518,7 @@ P3D_check_request(double timeout) { int stop_tick = int(GetTickCount() + timeout * 1000.0); #else struct timeval stop_time; - gettimeofday(&stop_time, NULL); + gettimeofday(&stop_time, nullptr); int seconds = (int)floor(timeout); stop_time.tv_sec += seconds; @@ -535,7 +535,7 @@ P3D_check_request(double timeout) { ACQUIRE_LOCK(_api_lock); inst = inst_mgr->check_request(); - while (inst == NULL && inst_mgr->get_num_instances() != 0) { + while (inst == nullptr && inst_mgr->get_num_instances() != 0) { #ifdef _WIN32 int remaining_ticks = stop_tick - GetTickCount(); if (remaining_ticks <= 0) { @@ -544,7 +544,7 @@ P3D_check_request(double timeout) { timeout = remaining_ticks * 0.001; #else struct timeval now; - gettimeofday(&now, NULL); + gettimeofday(&now, nullptr); struct timeval remaining; remaining.tv_sec = stop_time.tv_sec - now.tv_sec; @@ -574,7 +574,7 @@ void P3D_request_finish(P3D_request *request, bool handled) { assert(P3DInstanceManager::get_global_ptr()->is_initialized()); ACQUIRE_LOCK(_api_lock); - if (request != (P3D_request *)NULL) { + if (request != nullptr) { P3DInstance::finish_request(request, handled); } RELEASE_LOCK(_api_lock); @@ -593,7 +593,7 @@ P3D_instance_feed_url_stream(P3D_instance *instance, int unique_id, P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); P3DInstance *inst = inst_mgr->validate_instance(instance); bool result = false; - if (inst != NULL) { + if (inst != nullptr) { result = inst-> feed_url_stream(unique_id, result_code, http_status_code, total_expected_data, @@ -613,7 +613,7 @@ P3D_instance_handle_event(P3D_instance *instance, P3DInstanceManager *inst_mgr = P3DInstanceManager::get_global_ptr(); P3DInstance *inst = inst_mgr->validate_instance(instance); bool result = false; - if (inst != NULL) { + if (inst != nullptr) { result = inst->handle_event(*event); } diff --git a/direct/src/plugin/p3d_plugin.h b/direct/src/plugin/p3d_plugin.h index 6df6e281fc..1d7866e05c 100644 --- a/direct/src/plugin/p3d_plugin.h +++ b/direct/src/plugin/p3d_plugin.h @@ -633,7 +633,7 @@ struct _P3D_object { #define P3D_OBJECT_INCREF(object) (++(object)->_ref_count) #define P3D_OBJECT_DECREF(object) { if (--(object)->_ref_count <= 0) { (object)->_class->_finish((object)); } } -#define P3D_OBJECT_XDECREF(object) { if ((object) != (P3D_object *)NULL) { P3D_OBJECT_DECREF(object); } } +#define P3D_OBJECT_XDECREF(object) { if ((object) != nullptr) { P3D_OBJECT_DECREF(object); } } /* End of method pointer definitions. The following function types are once again meant to define actual function pointers to be found diff --git a/direct/src/plugin/p3d_plugin_common.h b/direct/src/plugin/p3d_plugin_common.h index 244ac70925..6ddd0e057c 100644 --- a/direct/src/plugin/p3d_plugin_common.h +++ b/direct/src/plugin/p3d_plugin_common.h @@ -34,19 +34,17 @@ #include #include -using namespace std; - // Appears in p3dInstanceManager.cxx. -extern ostream *nout_stream; +extern std::ostream *nout_stream; #define nout (*nout_stream) // Appears in p3d_plugin.cxx. extern LOCK _api_lock; // A convenience function for formatting a generic P3D_object to an ostream. -inline ostream & -operator << (ostream &out, P3D_object &value) { - int size = P3D_OBJECT_GET_REPR(&value, NULL, 0); +inline std::ostream & +operator << (std::ostream &out, P3D_object &value) { + int size = P3D_OBJECT_GET_REPR(&value, nullptr, 0); char *buffer = new char[size]; P3D_OBJECT_GET_REPR(&value, buffer, size); out.write(buffer, size); diff --git a/direct/src/plugin/parse_color.cxx b/direct/src/plugin/parse_color.cxx index e3094e9d40..4a5f12b587 100644 --- a/direct/src/plugin/parse_color.cxx +++ b/direct/src/plugin/parse_color.cxx @@ -22,7 +22,7 @@ static bool parse_hexdigit(int &result, char digit); * in the range 0..255. On failure, r, g, b are undefined. */ bool -parse_color(int &r, int &g, int &b, const string &color) { +parse_color(int &r, int &g, int &b, const std::string &color) { if (color.empty() || color[0] != '#') { return false; } diff --git a/direct/src/plugin/parse_color.h b/direct/src/plugin/parse_color.h index cbbed95e03..794abf2055 100644 --- a/direct/src/plugin/parse_color.h +++ b/direct/src/plugin/parse_color.h @@ -15,8 +15,7 @@ #define PARSE_COLOR_H #include -using namespace std; -bool parse_color(int &r, int &g, int &b, const string &color); +bool parse_color(int &r, int &g, int &b, const std::string &color); #endif diff --git a/direct/src/plugin/run_p3dpython.cxx b/direct/src/plugin/run_p3dpython.cxx index abbaa92730..1a0432a2d4 100644 --- a/direct/src/plugin/run_p3dpython.cxx +++ b/direct/src/plugin/run_p3dpython.cxx @@ -28,6 +28,6 @@ run_p3dpython(const char *program_name, const char *archive_file, log_pathname, interactive_console); int result = P3DPythonRun::_global_ptr->run_python(); delete P3DPythonRun::_global_ptr; - P3DPythonRun::_global_ptr = NULL; + P3DPythonRun::_global_ptr = nullptr; return result; } diff --git a/direct/src/plugin/wstring_encode.cxx b/direct/src/plugin/wstring_encode.cxx index bda90a4270..e844d643bd 100644 --- a/direct/src/plugin/wstring_encode.cxx +++ b/direct/src/plugin/wstring_encode.cxx @@ -21,20 +21,19 @@ #include #endif // _WIN32 - #ifdef _WIN32 /** * Encodes std::wstring to std::string using UTF-8. */ bool -wstring_to_string(string &result, const wstring &source) { +wstring_to_string(std::string &result, const std::wstring &source) { bool success = false; int size = WideCharToMultiByte(CP_UTF8, 0, source.data(), source.length(), - NULL, 0, NULL, NULL); + nullptr, 0, nullptr, nullptr); if (size > 0) { char *buffer = new char[size]; int rc = WideCharToMultiByte(CP_UTF8, 0, source.data(), source.length(), - buffer, size, NULL, NULL); + buffer, size, nullptr, nullptr); if (rc != 0) { result.assign(buffer, size); success = true; @@ -51,10 +50,10 @@ wstring_to_string(string &result, const wstring &source) { * Decodes std::string to std::wstring using UTF-8. */ bool -string_to_wstring(wstring &result, const string &source) { +string_to_wstring(std::wstring &result, const std::string &source) { bool success = false; int size = MultiByteToWideChar(CP_UTF8, 0, source.data(), source.length(), - NULL, 0); + nullptr, 0); if (size > 0) { wchar_t *buffer = new wchar_t[size]; int rc = MultiByteToWideChar(CP_UTF8, 0, source.data(), source.length(), diff --git a/direct/src/plugin/wstring_encode.h b/direct/src/plugin/wstring_encode.h index 8f36f88209..b9641bd43d 100644 --- a/direct/src/plugin/wstring_encode.h +++ b/direct/src/plugin/wstring_encode.h @@ -15,19 +15,18 @@ #define WSTRING_ENCODE_H #include -using namespace std; // Presently, these two functions are implemented only for Windows, which is // the only place they are needed. (Only Windows requires wstrings for // filenames.) #ifdef _WIN32 -bool wstring_to_string(string &result, const wstring &source); -bool string_to_wstring(wstring &result, const string &source); +bool wstring_to_string(std::string &result, const std::wstring &source); +bool string_to_wstring(std::wstring &result, const std::string &source); // We declare this inline so it won't conflict with the similar function // defined in Panda's textEncoder.h. -inline ostream &operator << (ostream &out, const wstring &str) { - string result; +inline std::ostream &operator << (std::ostream &out, const std::wstring &str) { + std::string result; if (wstring_to_string(result, str)) { out << result; } diff --git a/direct/src/plugin/xml_helpers.cxx b/direct/src/plugin/xml_helpers.cxx index e08511f07a..9a997189da 100644 --- a/direct/src/plugin/xml_helpers.cxx +++ b/direct/src/plugin/xml_helpers.cxx @@ -21,10 +21,10 @@ * empty. */ bool -parse_bool_attrib(TiXmlElement *xelem, const string &attrib, +parse_bool_attrib(TiXmlElement *xelem, const std::string &attrib, bool default_value) { const char *value = xelem->Attribute(attrib.c_str()); - if (value == NULL || *value == '\0') { + if (value == nullptr || *value == '\0') { return default_value; } diff --git a/direct/src/plugin/xml_helpers.h b/direct/src/plugin/xml_helpers.h index ea540bcf7a..d64047f55a 100644 --- a/direct/src/plugin/xml_helpers.h +++ b/direct/src/plugin/xml_helpers.h @@ -16,7 +16,7 @@ #include "get_tinyxml.h" -bool parse_bool_attrib(TiXmlElement *xelem, const string &attrib, +bool parse_bool_attrib(TiXmlElement *xelem, const std::string &attrib, bool default_value); #endif diff --git a/direct/src/plugin_activex/PPDownloadRequest.h b/direct/src/plugin_activex/PPDownloadRequest.h index a9ad8f3b2d..26d5081fc7 100644 --- a/direct/src/plugin_activex/PPDownloadRequest.h +++ b/direct/src/plugin_activex/PPDownloadRequest.h @@ -30,19 +30,19 @@ public: }; PPDownloadRequest( PPInstance& instance, P3D_request* p3dRequest ) : - m_instance( instance ), m_p3dRequest( p3dRequest ), m_data( NULL ), + m_instance( instance ), m_p3dRequest( p3dRequest ), m_data( nullptr ), m_requestType( RequestType::P3DObject ), m_hFile( INVALID_HANDLE_VALUE ) { } PPDownloadRequest( PPInstance& instance, const std::string& fileName ) : - m_instance( instance ), m_p3dRequest( NULL ), m_fileName( fileName ), - m_data( NULL ), m_requestType( RequestType::File ), m_hFile( INVALID_HANDLE_VALUE ) + m_instance( instance ), m_p3dRequest( nullptr ), m_fileName( fileName ), + m_data( nullptr ), m_requestType( RequestType::File ), m_hFile( INVALID_HANDLE_VALUE ) { } PPDownloadRequest( PPInstance& instance, std::strstream* data ) : - m_instance( instance ), m_p3dRequest ( NULL ), m_data( data ), + m_instance( instance ), m_p3dRequest ( nullptr ), m_data( data ), m_requestType( RequestType::Data ), m_hFile( INVALID_HANDLE_VALUE ) { } diff --git a/direct/src/plugin_activex/PPInstance.h b/direct/src/plugin_activex/PPInstance.h index 1c80168aea..8b59b6a3ac 100644 --- a/direct/src/plugin_activex/PPInstance.h +++ b/direct/src/plugin_activex/PPInstance.h @@ -81,7 +81,7 @@ protected: bool HandleRequest( P3D_request *request ); static void HandleRequestGetUrl( void *data ); - static int compare_seq(const string &seq_a, const string &seq_b); + static int compare_seq(const std::string &seq_a, const std::string &seq_b); static int compare_seq_int(const char *&num_a, const char *&num_b); void set_failed(); @@ -100,7 +100,7 @@ protected: std::string _download_url_prefix; typedef std::vector Mirrors; Mirrors _mirrors; - string _coreapi_set_ver; + std::string _coreapi_set_ver; FileSpec _coreapi_dll; time_t _contents_expiration; bool _failed; diff --git a/direct/src/plugin_npapi/nppanda3d_common.h b/direct/src/plugin_npapi/nppanda3d_common.h index 512281ea3d..c1b7cd61af 100644 --- a/direct/src/plugin_npapi/nppanda3d_common.h +++ b/direct/src/plugin_npapi/nppanda3d_common.h @@ -30,13 +30,11 @@ #include #include -using namespace std; - // Appears in startup.cxx. -extern ostream *nout_stream; +extern std::ostream *nout_stream; #define nout (*nout_stream) -extern string global_root_dir; +extern std::string global_root_dir; extern bool has_plugin_thread_async_call; #ifdef _WIN32 diff --git a/direct/src/plugin_npapi/npruntime.h b/direct/src/plugin_npapi/npruntime.h index 6e89165045..2039225cbe 100644 --- a/direct/src/plugin_npapi/npruntime.h +++ b/direct/src/plugin_npapi/npruntime.h @@ -137,13 +137,13 @@ void NPN_ReleaseVariantValue(NPVariant *variant); #define VOID_TO_NPVARIANT(_v) \ NP_BEGIN_MACRO \ (_v).type = NPVariantType_Void; \ - (_v).value.objectValue = NULL; \ + (_v).value.objectValue = nullptr; \ NP_END_MACRO #define NULL_TO_NPVARIANT(_v) \ NP_BEGIN_MACRO \ (_v).type = NPVariantType_Null; \ - (_v).value.objectValue = NULL; \ + (_v).value.objectValue = nullptr; \ NP_END_MACRO #define BOOLEAN_TO_NPVARIANT(_val, _v) \ diff --git a/direct/src/plugin_npapi/ppBrowserObject.cxx b/direct/src/plugin_npapi/ppBrowserObject.cxx index 822f1f5657..17104b9e6c 100644 --- a/direct/src/plugin_npapi/ppBrowserObject.cxx +++ b/direct/src/plugin_npapi/ppBrowserObject.cxx @@ -16,6 +16,8 @@ #include #include // strncpy +using std::string; + // The following functions are C-style wrappers around the above // PPBrowserObject methods; they are defined to allow us to create the C-style // P3D_class_definition method table to store in the P3D_object structure. @@ -44,7 +46,7 @@ static P3D_object * object_call(P3D_object *object, const char *method_name, bool needs_response, P3D_object *params[], int num_params) { - if (method_name == NULL) { + if (method_name == nullptr) { method_name = ""; } P3D_object *response = ((const PPBrowserObject *)object)->call(method_name, params, num_params); @@ -52,7 +54,7 @@ object_call(P3D_object *object, const char *method_name, // No response was expected. Throw away the response we received, so we // can be consistent with defined semantics. P3D_OBJECT_XDECREF(response); - response = NULL; + response = nullptr; } return response; } @@ -105,7 +107,7 @@ PPBrowserObject:: */ int PPBrowserObject:: get_repr(char *buffer, int buffer_length) const { - ostringstream strm; + std::ostringstream strm; strm << "NPObject " << _npobj; string result = strm.str(); strncpy(buffer, result.c_str(), buffer_length); @@ -123,14 +125,14 @@ get_property(const string &property) const { if (!browser->hasproperty(_instance->get_npp_instance(), _npobj, property_name)) { // No such property. - return NULL; + return nullptr; } NPVariant result; if (!browser->getproperty(_instance->get_npp_instance(), _npobj, property_name, &result)) { // Failed to retrieve property. - return NULL; + return nullptr; } P3D_object *object = _instance->variant_to_p3dobj(&result); @@ -146,7 +148,7 @@ bool PPBrowserObject:: set_property(const string &property, bool needs_response, P3D_object *value) { NPIdentifier property_name = browser->getstringidentifier(property.c_str()); bool result; - if (value != NULL) { + if (value != nullptr) { // Set the property. NPVariant npvalue; _instance->p3dobj_to_variant(&npvalue, value); @@ -183,7 +185,7 @@ call(const string &method_name, P3D_object *params[], int num_params) const { npparams, num_params, &result)) { // Failed to invoke. delete[] npparams; - return NULL; + return nullptr; } } else { // Call the named method. @@ -193,7 +195,7 @@ call(const string &method_name, P3D_object *params[], int num_params) const { npparams, num_params, &result)) { // Failed to invoke. delete[] npparams; - return NULL; + return nullptr; } } @@ -215,7 +217,7 @@ eval(const string &expression) const { if (!browser->evaluate(_instance->get_npp_instance(), _npobj, &npexpr, &result)) { // Failed to eval. - return NULL; + return nullptr; } P3D_object *object = _instance->variant_to_p3dobj(&result); @@ -229,7 +231,7 @@ eval(const string &expression) const { */ void PPBrowserObject:: clear_class_definition() { - _browser_object_class = NULL; + _browser_object_class = nullptr; } /** @@ -238,7 +240,7 @@ clear_class_definition() { */ P3D_class_definition *PPBrowserObject:: get_class_definition() { - if (_browser_object_class == NULL) { + if (_browser_object_class == nullptr) { // Create a default class_definition object, and fill in the appropriate // pointers. _browser_object_class = P3D_make_class_definition_ptr(); diff --git a/direct/src/plugin_npapi/ppBrowserObject.h b/direct/src/plugin_npapi/ppBrowserObject.h index 8274ea8f34..3b0835b450 100644 --- a/direct/src/plugin_npapi/ppBrowserObject.h +++ b/direct/src/plugin_npapi/ppBrowserObject.h @@ -32,13 +32,13 @@ public: ~PPBrowserObject(); int get_repr(char *buffer, int buffer_length) const; - P3D_object *get_property(const string &property) const; - bool set_property(const string &property, bool needs_response, + P3D_object *get_property(const std::string &property) const; + bool set_property(const std::string &property, bool needs_response, P3D_object *value); - P3D_object *call(const string &method_name, + P3D_object *call(const std::string &method_name, P3D_object *params[], int num_params) const; - P3D_object *eval(const string &expression) const; + P3D_object *eval(const std::string &expression) const; static void clear_class_definition(); diff --git a/direct/src/plugin_npapi/ppInstance.I b/direct/src/plugin_npapi/ppInstance.I index 122b396912..1c929d849b 100644 --- a/direct/src/plugin_npapi/ppInstance.I +++ b/direct/src/plugin_npapi/ppInstance.I @@ -27,5 +27,5 @@ get_window() const { if (_got_window) { return &_window; } - return NULL; + return nullptr; } diff --git a/direct/src/plugin_npapi/ppInstance.cxx b/direct/src/plugin_npapi/ppInstance.cxx index 47aa5b3cd0..6a3d961e32 100644 --- a/direct/src/plugin_npapi/ppInstance.cxx +++ b/direct/src/plugin_npapi/ppInstance.cxx @@ -41,6 +41,12 @@ #include #endif // HAVE_X11 +using std::ios; +using std::ostream; +using std::ostringstream; +using std::string; +using std::vector; + PPInstance::FileDatas PPInstance::_file_datas; @@ -54,13 +60,13 @@ PPInstance(NPMIMEType pluginType, NPP instance, uint16_t mode, int16_t argc, char *argn[], char *argv[], NPSavedData *saved, P3D_window_handle_type window_handle_type, P3D_event_type event_type) { - _p3d_inst = NULL; + _p3d_inst = nullptr; _npp_instance = instance; _npp_mode = mode; _window_handle_type = window_handle_type; _event_type = event_type; - _script_object = NULL; + _script_object = nullptr; _contents_expiration = 0; _failed = false; _started = false; @@ -68,9 +74,9 @@ PPInstance(NPMIMEType pluginType, NPP instance, uint16_t mode, // Copy the tokens and save them within this object. _tokens.reserve(argc); for (int i = 0; i < argc; ++i) { - if (argn[i] != NULL) { + if (argn[i] != nullptr) { const char *v = argv[i]; - if (v == NULL) { + if (v == nullptr) { // Firefox might give us a NULL argv[i] in some cases. v = ""; } @@ -130,13 +136,13 @@ PPInstance(NPMIMEType pluginType, NPP instance, uint16_t mode, #ifdef HAVE_X11 _twirl_subprocess_pid = -1; #ifdef HAVE_GTK - _plug = NULL; + _plug = nullptr; #endif // HAVE_GTK #endif // HAVE_X11 #ifdef _WIN32 - _hwnd = NULL; - _bg_brush = NULL; + _hwnd = nullptr; + _bg_brush = nullptr; #endif // _WIN32 #ifndef _WIN32 @@ -144,7 +150,7 @@ PPInstance(NPMIMEType pluginType, NPP instance, uint16_t mode, // use this to measure elapsed time from the window parameters having been // received. struct timeval tv; - gettimeofday(&tv, (struct timezone *)NULL); + gettimeofday(&tv, nullptr); _init_sec = tv.tv_sec; _init_usec = tv.tv_usec; #endif // !_WIN32 @@ -155,16 +161,16 @@ PPInstance(NPMIMEType pluginType, NPP instance, uint16_t mode, // thread.) _run_loop_main = CFRunLoopGetCurrent(); CFRetain(_run_loop_main); - _request_timer = NULL; + _request_timer = nullptr; INIT_LOCK(_timer_lock); // Also set up a timer to twirl the icon until the instance loads. - _twirl_timer = NULL; + _twirl_timer = nullptr; CFRunLoopTimerContext timer_context; memset(&timer_context, 0, sizeof(timer_context)); timer_context.info = this; _twirl_timer = CFRunLoopTimerCreate - (NULL, 0, 0.1, 0, 0, st_twirl_timer_callback, &timer_context); + (nullptr, 0, 0.1, 0, 0, st_twirl_timer_callback, &timer_context); CFRunLoopAddTimer(_run_loop_main, _twirl_timer, kCFRunLoopCommonModes); #endif // __APPLE__ @@ -181,15 +187,15 @@ PPInstance:: cleanup_window(); #ifdef __APPLE__ - if (_twirl_timer != NULL) { + if (_twirl_timer != nullptr) { CFRunLoopTimerInvalidate(_twirl_timer); CFRelease(_twirl_timer); - _twirl_timer = NULL; + _twirl_timer = nullptr; } - if (_request_timer != NULL) { + if (_request_timer != nullptr) { CFRunLoopTimerInvalidate(_request_timer); CFRelease(_request_timer); - _request_timer = NULL; + _request_timer = nullptr; } _run_loop_main = CFRunLoopGetCurrent(); CFRelease(_run_loop_main); @@ -200,15 +206,15 @@ PPInstance:: osx_release_twirl_images(); #endif // MACOSX_HAS_EVENT_MODELS - if (_p3d_inst != NULL) { + if (_p3d_inst != nullptr) { P3D_instance_finish_ptr(_p3d_inst); - _p3d_inst = NULL; + _p3d_inst = nullptr; } assert(_streams.empty()); assert(_file_datas.empty()); - if (_script_object != NULL) { + if (_script_object != nullptr) { browser->releaseobject(_script_object); } @@ -259,7 +265,7 @@ begin() { string contents_filename = _root_dir + "/contents.xml"; if (read_contents_file(contents_filename, false)) { - if (time(NULL) < _contents_expiration) { + if (time(nullptr) < _contents_expiration) { // Got the file, and it's good. get_core_api(); success = true; @@ -276,7 +282,7 @@ begin() { // Append a uniquifying query string to the URL to force the download to // go all the way through any caches. We use the time in seconds; // that's unique enough. - strm << "?" << time(NULL); + strm << "?" << time(nullptr); url = strm.str(); PPDownloadRequest *req = new PPDownloadRequest(PPDownloadRequest::RT_contents_file); @@ -308,7 +314,7 @@ set_window(NPWindow *window) { if (!_got_window) { #ifdef _WIN32 - _orig_window_proc = NULL; + _orig_window_proc = nullptr; if (window->type == NPWindowTypeWindow) { // Save the window handle. _hwnd = (HWND)window->window; @@ -330,7 +336,7 @@ set_window(NPWindow *window) { // twirling icon, and also to catch events in case something slips // through. _init_time = GetTickCount(); - SetTimer(_hwnd, 1, 100, NULL); + SetTimer(_hwnd, 1, 100, nullptr); } #endif // _WIN32 #ifdef MACOSX_HAS_EVENT_MODELS @@ -342,9 +348,9 @@ set_window(NPWindow *window) { if (_use_xembed) { if (!_got_window || _window.window != window->window) { // The window has changed. Destroy the old GtkPlug. - if (_plug != NULL) { + if (_plug != nullptr) { gtk_widget_destroy(_plug); - _plug = NULL; + _plug = nullptr; } // Create a new GtkPlug to bind to the XEmbed socket. @@ -367,7 +373,7 @@ set_window(NPWindow *window) { #endif // HAVE_X11 if (!_failed) { - if (_p3d_inst == NULL) { + if (_p3d_inst == nullptr) { create_instance(); } else { send_window(); @@ -385,16 +391,16 @@ new_stream(NPMIMEType type, NPStream *stream, bool seekable, uint16_t *stype) { return NPERR_GENERIC_ERROR; } - if (stream->notifyData == NULL) { + if (stream->notifyData == nullptr) { // This is an unsolicited stream. Assume the first unsolicited stream we // receive is the instance data; any other unsolicited stream is an error. - if (!_got_instance_url && stream->url != NULL) { + if (!_got_instance_url && stream->url != nullptr) { _got_instance_url = true; _instance_url = stream->url; stream->notifyData = new PPDownloadRequest(PPDownloadRequest::RT_instance_data); - if (_p3d_inst != NULL) { + if (_p3d_inst != nullptr) { // If we already have an instance by the time we get this stream, // start sending the data to the instance (instead of having to mess // around with a temporary file). @@ -488,7 +494,7 @@ write_ready(NPStream *stream) { */ int PPInstance:: write_stream(NPStream *stream, int offset, int len, void *buffer) { - if (stream->notifyData == NULL) { + if (stream->notifyData == nullptr) { nout << "Unexpected write_stream on " << stream->url << "\n"; browser->destroystream(_npp_instance, stream, NPRES_USER_BREAK); return 0; @@ -523,7 +529,7 @@ write_stream(NPStream *stream, int offset, int len, void *buffer) { // Nowadays we solve this problem by writing the data to a temporary file // until the instance is ready for it. - if (_p3d_inst == NULL) { + if (_p3d_inst == nullptr) { // The instance isn't ready, so stuff it in a temporary file. if (!_p3d_temp_file.feed(stream->end, buffer, len)) { set_failed(); @@ -575,7 +581,7 @@ destroy_stream(NPStream *stream, NPReason reason) { _streams.erase(si); } - if (stream->notifyData == NULL) { + if (stream->notifyData == nullptr) { nout << "Unexpected destroy_stream on " << stream->url << "\n"; return NPERR_NO_ERROR; } @@ -595,14 +601,14 @@ destroy_stream(NPStream *stream, NPReason reason) { case PPDownloadRequest::RT_user: if (!req->_notified_done) { P3D_instance_feed_url_stream_ptr(_p3d_inst, req->_user_id, - result_code, 0, stream->end, NULL, 0); + result_code, 0, stream->end, nullptr, 0); req->_notified_done = true; } break; case PPDownloadRequest::RT_instance_data: if (!req->_notified_done) { - if (_p3d_inst == NULL) { + if (_p3d_inst == nullptr) { // The instance still isn't ready; just mark the data done. We'll // send the entire file to the instance when it is ready. _p3d_temp_file.finish(); @@ -614,7 +620,7 @@ destroy_stream(NPStream *stream, NPReason reason) { // The instance has (only just) been created. Tell it we've sent it // all the data it will get. P3D_instance_feed_url_stream_ptr(_p3d_inst, _p3d_instance_id, - result_code, 0, stream->end, NULL, 0); + result_code, 0, stream->end, nullptr, 0); } req->_notified_done = true; } @@ -655,7 +661,7 @@ destroy_stream(NPStream *stream, NPReason reason) { */ void PPInstance:: url_notify(const char *url, NPReason reason, void *notifyData) { - if (notifyData == NULL) { + if (notifyData == nullptr) { return; } @@ -675,7 +681,7 @@ url_notify(const char *url, NPReason reason, void *notifyData) { assert(reason != NPRES_DONE); P3D_instance_feed_url_stream_ptr(_p3d_inst, req->_user_id, - P3D_RC_generic_error, 0, 0, NULL, 0); + P3D_RC_generic_error, 0, 0, nullptr, 0); req->_notified_done = true; } break; @@ -739,7 +745,7 @@ url_notify(const char *url, NPReason reason, void *notifyData) { */ void PPInstance:: stream_as_file(NPStream *stream, const char *fname) { - if (stream->notifyData == NULL) { + if (stream->notifyData == nullptr) { nout << "Unexpected stream_as_file on " << stream->url << "\n"; return; } @@ -772,7 +778,7 @@ stream_as_file(NPStream *stream, const char *fname) { // the file that Safari tells us about appears to be a temporary file // that Safari's about to delete. In order to protect ourselves from // this, we need to temporarily copy the file somewhere else. - char *name = tempnam(NULL, "p3d_"); + char *name = tempnam(nullptr, "p3d_"); // We prefer just making a hard link; it's quick and easy. if (link(filename.c_str(), name) != 0) { @@ -802,7 +808,7 @@ stream_as_file(NPStream *stream, const char *fname) { */ bool PPInstance:: handle_request(P3D_request *request) { - if (_p3d_inst == NULL || _failed) { + if (_p3d_inst == nullptr || _failed) { return false; } assert(request->_instance == _p3d_inst); @@ -811,9 +817,9 @@ handle_request(P3D_request *request) { switch (request->_request_type) { case P3D_RT_stop: - if (_p3d_inst != NULL) { + if (_p3d_inst != nullptr) { P3D_instance_finish_ptr(_p3d_inst); - _p3d_inst = NULL; + _p3d_inst = nullptr; } cleanup_window(); // Guess the browser doesn't really care. @@ -911,7 +917,7 @@ handle_event(void *event) { #endif // MACOSX_HAS_EVENT_MODELS } - if (_p3d_inst != NULL) { + if (_p3d_inst != nullptr) { if (P3D_instance_handle_event_ptr(_p3d_inst, &edata)) { retval = true; } @@ -926,15 +932,15 @@ handle_event(void *event) { */ NPObject *PPInstance:: get_panda_script_object() { - if (_script_object != NULL) { + if (_script_object != nullptr) { // NPRuntime "steals" a reference to this object. browser->retainobject(_script_object); return _script_object; } - P3D_object *main = NULL; + P3D_object *main = nullptr; - if (_p3d_inst != NULL) { + if (_p3d_inst != nullptr) { main = P3D_instance_get_panda_script_object_ptr(_p3d_inst); } nout << "get_panda_script_object, main = " << main << "\n"; @@ -985,7 +991,7 @@ p3dobj_to_variant(NPVariant *result, P3D_object *object) { case P3D_OT_string: { - int size = P3D_OBJECT_GET_STRING(object, NULL, 0); + int size = P3D_OBJECT_GET_STRING(object, nullptr, 0); char *buffer = (char *)browser->memalloc(size); P3D_OBJECT_GET_STRING(object, buffer, size); STRINGN_TO_NPVARIANT(buffer, size, *result); @@ -1071,9 +1077,9 @@ void PPInstance:: find_host(TiXmlElement *xcontents) { string host_url = PANDA_PACKAGE_HOST_URL; TiXmlElement *xhost = xcontents->FirstChildElement("host"); - if (xhost != NULL) { + if (xhost != nullptr) { const char *url = xhost->Attribute("url"); - if (url != NULL && host_url == string(url)) { + if (url != nullptr && host_url == string(url)) { // We're the primary host. This is the normal case. read_xhost(xhost); return; @@ -1081,9 +1087,9 @@ find_host(TiXmlElement *xcontents) { } else { // We're not the primary host; perhaps we're an alternate host. TiXmlElement *xalthost = xhost->FirstChildElement("alt_host"); - while (xalthost != NULL) { + while (xalthost != nullptr) { const char *url = xalthost->Attribute("url"); - if (url != NULL && host_url == string(url)) { + if (url != nullptr && host_url == string(url)) { // Yep, we're this alternate host. read_xhost(xhost); return; @@ -1107,7 +1113,7 @@ read_xhost(TiXmlElement *xhost) { // Get the "download" URL, which is the source from which we download // everything other than the contents.xml file. const char *download_url = xhost->Attribute("download_url"); - if (download_url != NULL) { + if (download_url != nullptr) { _download_url_prefix = download_url; } else { _download_url_prefix = PANDA_PACKAGE_HOST_URL; @@ -1119,9 +1125,9 @@ read_xhost(TiXmlElement *xhost) { } TiXmlElement *xmirror = xhost->FirstChildElement("mirror"); - while (xmirror != NULL) { + while (xmirror != nullptr) { const char *url = xmirror->Attribute("url"); - if (url != NULL) { + if (url != nullptr) { add_mirror(url); } xmirror = xmirror->NextSiblingElement("mirror"); @@ -1154,7 +1160,7 @@ void PPInstance:: choose_random_mirrors(vector &result, int num_mirrors) { vector selected; - size_t num_to_select = min(_mirrors.size(), (size_t)num_mirrors); + size_t num_to_select = std::min(_mirrors.size(), (size_t)num_mirrors); while (num_to_select > 0) { size_t i = (size_t)(((double)rand() / (double)RAND_MAX) * _mirrors.size()); while (find(selected.begin(), selected.end(), i) != selected.end()) { @@ -1175,15 +1181,15 @@ choose_random_mirrors(vector &result, int num_mirrors) { void PPInstance:: request_ready(P3D_instance *instance) { PPInstance *inst = (PPInstance *)(instance->_user_data); - assert(inst != NULL); + assert(inst != nullptr); if (has_plugin_thread_async_call) { #ifdef HAS_PLUGIN_THREAD_ASYNC_CALL // Since we are running at least Gecko 1.9, and we have this very useful // function, let's use it to ask the browser to call us back in the main // thread. - assert((void *)browser->pluginthreadasynccall != (void *)NULL); - browser->pluginthreadasynccall(inst->_npp_instance, browser_sync_callback, NULL); + assert((void *)browser->pluginthreadasynccall != nullptr); + browser->pluginthreadasynccall(inst->_npp_instance, browser_sync_callback, nullptr); #endif // HAS_PLUGIN_THREAD_ASYNC_CALL } else { @@ -1195,7 +1201,7 @@ request_ready(P3D_instance *instance) { // Get the window handle for the window associated with this instance. const NPWindow *win = inst->get_window(); - if (win != NULL && win->type == NPWindowTypeWindow) { + if (win != nullptr && win->type == NPWindowTypeWindow) { PostMessage((HWND)(win->window), WM_USER, 0, 0); } #endif // _WIN32 @@ -1205,12 +1211,12 @@ request_ready(P3D_instance *instance) { // Only set a new timer if we don't have one already started. ACQUIRE_LOCK(inst->_timer_lock); - if (inst->_request_timer == NULL) { + if (inst->_request_timer == nullptr) { CFRunLoopTimerContext timer_context; memset(&timer_context, 0, sizeof(timer_context)); timer_context.info = inst; inst->_request_timer = CFRunLoopTimerCreate - (NULL, 0, 0, 0, 0, timer_callback, &timer_context); + (nullptr, 0, 0, 0, 0, timer_callback, &timer_context); CFRunLoopAddTimer(inst->_run_loop_main, inst->_request_timer, kCFRunLoopCommonModes); } RELEASE_LOCK(inst->_timer_lock); @@ -1232,7 +1238,7 @@ start_download(const string &url, PPDownloadRequest *req) { delete req; } else { // Otherwise, ask the browser to download it. - browser->geturlnotify(_npp_instance, url.c_str(), NULL, req); + browser->geturlnotify(_npp_instance, url.c_str(), nullptr, req); } } @@ -1283,19 +1289,19 @@ read_contents_file(const string &contents_filename, bool fresh_download) { bool found_core_package = false; TiXmlElement *xcontents = doc.FirstChildElement("contents"); - if (xcontents != NULL) { + if (xcontents != nullptr) { int max_age = P3D_CONTENTS_DEFAULT_MAX_AGE; xcontents->Attribute("max_age", &max_age); // Get the latest possible expiration time, based on the max_age // indication. Any expiration time later than this is in error. - time_t now = time(NULL); + time_t now = time(nullptr); _contents_expiration = now + (time_t)max_age; if (fresh_download) { // Update the XML with the new download information. TiXmlElement *xorig = xcontents->FirstChildElement("orig"); - while (xorig != NULL) { + while (xorig != nullptr) { xcontents->RemoveChild(xorig); xorig = xcontents->FirstChildElement("orig"); } @@ -1309,15 +1315,15 @@ read_contents_file(const string &contents_filename, bool fresh_download) { // Read the expiration time from the XML. int expiration = 0; TiXmlElement *xorig = xcontents->FirstChildElement("orig"); - if (xorig != NULL) { + if (xorig != nullptr) { xorig->Attribute("expiration", &expiration); } - _contents_expiration = min(_contents_expiration, (time_t)expiration); + _contents_expiration = std::min(_contents_expiration, (time_t)expiration); } nout << "read contents.xml, max_age = " << max_age - << ", expires in " << max(_contents_expiration, now) - now + << ", expires in " << std::max(_contents_expiration, now) - now << " s\n"; // Look for the entry; it might point us at a different download @@ -1327,14 +1333,14 @@ read_contents_file(const string &contents_filename, bool fresh_download) { // Now look for the core API package. _coreapi_set_ver = ""; TiXmlElement *xpackage = xcontents->FirstChildElement("package"); - while (xpackage != NULL) { + while (xpackage != nullptr) { const char *name = xpackage->Attribute("name"); - if (name != NULL && strcmp(name, "coreapi") == 0) { + if (name != nullptr && strcmp(name, "coreapi") == 0) { const char *platform = xpackage->Attribute("platform"); - if (platform != NULL && strcmp(platform, DTOOL_PLATFORM) == 0) { + if (platform != nullptr && strcmp(platform, DTOOL_PLATFORM) == 0) { _coreapi_dll.load_xml(xpackage); const char *set_ver = xpackage->Attribute("set_ver"); - if (set_ver != NULL) { + if (set_ver != nullptr) { _coreapi_set_ver = set_ver; } found_core_package = true; @@ -1491,7 +1497,7 @@ send_p3d_temp_file_data() { // If we'd already finished the stream earlier, tell the plugin. P3D_instance_feed_url_stream_ptr(_p3d_inst, _p3d_instance_id, P3D_RC_done, 0, _p3d_temp_file._total_size, - NULL, 0); + nullptr, 0); } _p3d_temp_file.cleanup(); } @@ -1515,7 +1521,7 @@ get_core_api() { // uniquifier, to break through any caches. ostringstream strm; strm << _download_url_prefix << _coreapi_dll.get_filename() - << "?" << time(NULL); + << "?" << time(nullptr); url = strm.str(); _core_urls.push_back(url); @@ -1566,7 +1572,7 @@ downloaded_plugin(const string &filename) { nout << "Expected:\n"; _coreapi_dll.write(nout); const FileSpec *actual = _coreapi_dll.force_get_actual_file(filename); - if (actual != NULL) { + if (actual != nullptr) { nout << "Found:\n"; actual->write(nout); } @@ -1671,10 +1677,10 @@ create_instance() { #ifdef __APPLE__ // We no longer need to twirl the icon. Stop the timer. - if (_twirl_timer != NULL) { + if (_twirl_timer != nullptr) { CFRunLoopTimerInvalidate(_twirl_timer); CFRelease(_twirl_timer); - _twirl_timer = NULL; + _twirl_timer = nullptr; } #endif // __APPLE__ @@ -1685,21 +1691,21 @@ create_instance() { // In the Windows case, we let the timer keep running, because it also // checks for wayward messages. - P3D_token *tokens = NULL; + P3D_token *tokens = nullptr; if (!_tokens.empty()) { tokens = &_tokens[0]; } _started = true; _p3d_inst = P3D_new_instance_ptr(request_ready, tokens, _tokens.size(), - 0, NULL, this); - if (_p3d_inst == NULL) { + 0, nullptr, this); + if (_p3d_inst == nullptr) { set_failed(); return; } // Now get the browser's toplevel DOM object (called the "window" object in // JavaScript), to pass to the plugin. - NPObject *window_object = NULL; + NPObject *window_object = nullptr; if (browser->getvalue(_npp_instance, NPNVWindowNPObject, &window_object) == NPERR_NO_ERROR) { PPBrowserObject *pobj = new PPBrowserObject(this, window_object); @@ -1709,7 +1715,7 @@ create_instance() { nout << "Couldn't get window_object\n"; } - if (_script_object != NULL) { + if (_script_object != nullptr) { // Now that we have a true instance, initialize our script_object with the // proper P3D_object pointer. P3D_object *main = P3D_instance_get_panda_script_object_ptr(_p3d_inst); @@ -1740,7 +1746,7 @@ create_instance() { */ void PPInstance:: send_window() { - assert(_p3d_inst != NULL); + assert(_p3d_inst != nullptr); int x = _window.x; int y = _window.y; @@ -1770,7 +1776,7 @@ send_window() { #endif } else if (_window_handle_type == P3D_WHT_osx_cgcontext) { NP_CGContext *context = (NP_CGContext *)_window.window; - if (context != NULL) { + if (context != nullptr) { parent_window._handle._osx_cgcontext._context = context->context; parent_window._handle._osx_cgcontext._window = (WindowRef)context->window; } @@ -1784,7 +1790,7 @@ send_window() { // If we're using XEmbed, pass the X11 Window pointer of our plug down // to Panda. (Hmm, it would be nice to pass the XID object and use this // system in general within Panda, but that's for the future, I think.) - assert(_plug != NULL); + assert(_plug != nullptr); parent_window._window_handle_type = P3D_WHT_x11_window; parent_window._handle._x11_window._xwindow = GDK_DRAWABLE_XID(_plug->window); #endif // HAVE_GTK @@ -1818,7 +1824,7 @@ send_window() { #endif } else if (_window_handle_type == P3D_WHT_osx_cgcontext) { NP_CGContext *context = (NP_CGContext *)_window.window; - if (context != NULL) { + if (context != nullptr) { parent_window._handle._osx_cgcontext._context = context->context; parent_window._handle._osx_cgcontext._window = (WindowRef)context->window; } @@ -1845,7 +1851,7 @@ send_window() { #endif P3D_window_type window_type = P3D_WT_embedded; - if (_window.window == NULL && _event_type != P3D_ET_osx_cocoa) { + if (_window.window == nullptr && _event_type != P3D_ET_osx_cocoa) { // No parent window: it must be a hidden window. window_type = P3D_WT_hidden; } else if (_window.width == 0 || _window.height == 0) { @@ -1870,16 +1876,16 @@ cleanup_window() { // Restore the parent window to its own window handler. HWND hwnd = (HWND)_window.window; SetWindowLongPtr(hwnd, GWLP_WNDPROC, _orig_window_proc); - InvalidateRect(hwnd, NULL, true); + InvalidateRect(hwnd, nullptr, true); - if (_bg_brush != NULL) { + if (_bg_brush != nullptr) { DeleteObject(_bg_brush); - _bg_brush = NULL; + _bg_brush = nullptr; } for (int step = 0; step < twirl_num_steps + 1; ++step) { - if (_twirl_bitmaps[step] != NULL) { + if (_twirl_bitmaps[step] != nullptr) { DeleteObject(_twirl_bitmaps[step]); - _twirl_bitmaps[step] = NULL; + _twirl_bitmaps[step] = nullptr; } } #endif // _WIN32 @@ -1888,9 +1894,9 @@ cleanup_window() { x11_stop_twirl_subprocess(); #ifdef HAVE_GTK - if (_plug != NULL) { + if (_plug != nullptr) { gtk_widget_destroy(_plug); - _plug = NULL; + _plug = nullptr; } #endif // HAVE_GTK #endif // HAVE_X11 @@ -2037,7 +2043,7 @@ set_failed() { if (!expression.empty()) { // Now attempt to evaluate the expression. - NPObject *window_object = NULL; + NPObject *window_object = nullptr; if (browser->getvalue(_npp_instance, NPNVWindowNPObject, &window_object) == NPERR_NO_ERROR) { NPString npexpr = { expression.c_str(), (uint32_t)expression.length() }; @@ -2054,9 +2060,9 @@ set_failed() { } } - if (_p3d_inst != NULL) { + if (_p3d_inst != nullptr) { P3D_instance_finish_ptr(_p3d_inst); - _p3d_inst = NULL; + _p3d_inst = nullptr; } cleanup_window(); } @@ -2073,11 +2079,11 @@ handle_request_loop() { } P3D_instance *p3d_inst = P3D_check_request_ptr(0.0); - while (p3d_inst != (P3D_instance *)NULL) { + while (p3d_inst != nullptr) { P3D_request *request = P3D_instance_get_request_ptr(p3d_inst); - if (request != (P3D_request *)NULL) { + if (request != nullptr) { PPInstance *inst = (PPInstance *)(p3d_inst->_user_data); - assert(inst != NULL); + assert(inst != nullptr); if (!inst->handle_request(request)) { // If handling the request is meant to yield control temporarily to // JavaScript (e.g. P3D_RT_callback), then do so now. @@ -2130,7 +2136,7 @@ browser_sync_callback(void *) { LONG PPInstance:: st_window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { LONG_PTR self = GetWindowLongPtr(hwnd, GWLP_USERDATA); - if (self == NULL) { + if (self == nullptr) { // We haven't assigned the pointer yet (!?) return DefWindowProc(hwnd, msg, wparam, lparam); } @@ -2174,7 +2180,7 @@ window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { case WM_TIMER: if (!_started) { - InvalidateRect(_hwnd, NULL, FALSE); + InvalidateRect(_hwnd, nullptr, FALSE); } break; @@ -2286,7 +2292,7 @@ win_paint_twirl(HWND hwnd, HDC dc) { BitBlt(bdc, left, top, twirl_width, twirl_height, mem_dc, 0, 0, SRCCOPY); - SelectObject(mem_dc, NULL); + SelectObject(mem_dc, nullptr); DeleteDC(mem_dc); } } @@ -2411,10 +2417,10 @@ copy_cocoa_event(P3DCocoaEvent *p3d_event, NPCocoaEvent *np_event, * returns result.c_str(). */ const wchar_t *PPInstance:: -make_ansi_string(wstring &result, NPNSString *ns_string) { +make_ansi_string(std::wstring &result, NPNSString *ns_string) { result.clear(); - if (ns_string != NULL) { + if (ns_string != nullptr) { // An NPNSString is really just an NSString, which is itself just a // CFString. CFStringRef cfstr = (CFStringRef)ns_string; @@ -2492,7 +2498,7 @@ osx_get_twirl_images() { image._raw_data = new_data; image._data = - CFDataCreateWithBytesNoCopy(NULL, (const UInt8 *)image._raw_data, + CFDataCreateWithBytesNoCopy(nullptr, (const UInt8 *)image._raw_data, twirl_size * 4, kCFAllocatorNull); image._provider = CGDataProviderCreateWithCFData(image._data); image._color_space = CGColorSpaceCreateDeviceRGB(); @@ -2501,7 +2507,7 @@ osx_get_twirl_images() { CGImageCreate(twirl_width, twirl_height, 8, 32, twirl_width * 4, image._color_space, kCGImageAlphaFirst | kCGBitmapByteOrder32Little, - image._provider, NULL, false, kCGRenderingIntentDefault); + image._provider, nullptr, false, kCGRenderingIntentDefault); } } #endif // MACOSX_HAS_EVENT_MODELS @@ -2520,25 +2526,25 @@ osx_release_twirl_images() { for (int step = 0; step < twirl_num_steps + 1; ++step) { OsxImageData &image = _twirl_images[step]; - if (image._image != NULL) { + if (image._image != nullptr) { CGImageRelease(image._image); - image._image = NULL; + image._image = nullptr; } - if (image._color_space != NULL) { + if (image._color_space != nullptr) { CGColorSpaceRelease(image._color_space); - image._color_space = NULL; + image._color_space = nullptr; } - if (image._provider != NULL) { + if (image._provider != nullptr) { CGDataProviderRelease(image._provider); - image._provider = NULL; + image._provider = nullptr; } - if (image._data != NULL) { + if (image._data != nullptr) { CFRelease(image._data); - image._data = NULL; + image._data = nullptr; } - if (image._raw_data != NULL) { + if (image._raw_data != nullptr) { delete[] image._raw_data; - image._raw_data = NULL; + image._raw_data = nullptr; } } } @@ -2571,7 +2577,7 @@ paint_twirl_osx_cgcontext(CGContextRef context) { } else { struct timeval tv; - gettimeofday(&tv, (struct timezone *)NULL); + gettimeofday(&tv, nullptr); double now = (double)(tv.tv_sec - _init_sec) + (double)(tv.tv_usec - _init_usec) / 1000000.0; // Don't draw the twirling icon until at least half a second has passed, @@ -2591,7 +2597,7 @@ paint_twirl_osx_cgcontext(CGContextRef context) { */ bool PPInstance:: osx_paint_image(CGContextRef context, const OsxImageData &image) { - if (image._image == NULL) { + if (image._image == nullptr) { return false; } @@ -2627,10 +2633,10 @@ void PPInstance:: timer_callback(CFRunLoopTimerRef timer, void *info) { PPInstance *self = (PPInstance *)info; ACQUIRE_LOCK(self->_timer_lock); - if (self->_request_timer != NULL) { + if (self->_request_timer != nullptr) { CFRunLoopTimerInvalidate(self->_request_timer); CFRelease(self->_request_timer); - self->_request_timer = NULL; + self->_request_timer = nullptr; } RELEASE_LOCK(self->_timer_lock); @@ -2744,14 +2750,14 @@ x11_twirl_subprocess_run() { struct timespec req; req.tv_sec = 0; req.tv_nsec = 500000000; // 500 ms - nanosleep(&req, NULL); + nanosleep(&req, nullptr); // We haven't been killed yet, so the plugin is still loading. Start // twirling. // First, embed a window. - X11_Display *display = XOpenDisplay(NULL); - assert(display != NULL); + X11_Display *display = XOpenDisplay(nullptr); + assert(display != nullptr); int screen = DefaultScreen(display); int depth = DefaultDepth(display, screen); @@ -2796,7 +2802,7 @@ x11_twirl_subprocess_run() { X11_Window parent = 0; if (_use_xembed) { #ifdef HAVE_GTK - assert(_plug != NULL); + assert(_plug != nullptr); parent = GDK_DRAWABLE_XID(_plug->window); #endif // HAVE_GTK } else { @@ -2874,7 +2880,7 @@ x11_twirl_subprocess_run() { // What step are we on now? struct timeval tv; - gettimeofday(&tv, (struct timezone *)NULL); + gettimeofday(&tv, nullptr); double now = (double)(tv.tv_sec - _init_sec) + (double)(tv.tv_usec - _init_usec) / 1000000.0; int step = ((int)(now * 10.0)) % twirl_num_steps; if (step != last_step) { @@ -2896,7 +2902,7 @@ x11_twirl_subprocess_run() { struct timespec req; req.tv_sec = 0; req.tv_nsec = 100000000; // 100 ms - nanosleep(&req, NULL); + nanosleep(&req, nullptr); } } #endif // HAVE_X11 @@ -2990,7 +2996,7 @@ thread_run() { struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 10000; - select(0, NULL, NULL, NULL, &tv); + select(0, nullptr, nullptr, nullptr, &tv); #endif } @@ -3002,7 +3008,7 @@ thread_run() { } P3D_instance_feed_url_stream_ptr - (_p3d_inst, _user_id, result, 0, _total_count, NULL, 0); + (_p3d_inst, _user_id, result, 0, _total_count, nullptr, 0); // All done. _thread_done = true; @@ -3041,7 +3047,7 @@ open() { _current_size = 0; _total_size = 0; - char *name = tempnam(NULL, "p3d_"); + char *name = tempnam(nullptr, "p3d_"); _filename = name; free(name); diff --git a/direct/src/plugin_npapi/ppInstance.h b/direct/src/plugin_npapi/ppInstance.h index 86fa9bbf93..f24ebb6443 100644 --- a/direct/src/plugin_npapi/ppInstance.h +++ b/direct/src/plugin_npapi/ppInstance.h @@ -74,38 +74,38 @@ public: void p3dobj_to_variant(NPVariant *result, P3D_object *object); P3D_object *variant_to_p3dobj(const NPVariant *variant); - static void output_np_variant(ostream &out, const NPVariant &result); + static void output_np_variant(std::ostream &out, const NPVariant &result); private: void find_host(TiXmlElement *xcontents); void read_xhost(TiXmlElement *xhost); - void add_mirror(string mirror_url); - void choose_random_mirrors(vector &result, int num_mirrors); + void add_mirror(std::string mirror_url); + void choose_random_mirrors(std::vector &result, int num_mirrors); static void request_ready(P3D_instance *instance); - void start_download(const string &url, PPDownloadRequest *req); - void downloaded_file(PPDownloadRequest *req, const string &filename); - static string get_filename_from_url(const string &url); - void feed_file(PPDownloadRequest *req, const string &filename); + void start_download(const std::string &url, PPDownloadRequest *req); + void downloaded_file(PPDownloadRequest *req, const std::string &filename); + static std::string get_filename_from_url(const std::string &url); + void feed_file(PPDownloadRequest *req, const std::string &filename); void open_p3d_temp_file(); void send_p3d_temp_file_data(); - void downloaded_contents_file(const string &filename); - bool read_contents_file(const string &contents_filename, bool fresh_download); + void downloaded_contents_file(const std::string &filename); + bool read_contents_file(const std::string &contents_filename, bool fresh_download); void get_core_api(); - void downloaded_plugin(const string &filename); + void downloaded_plugin(const std::string &filename); void do_load_plugin(); void create_instance(); void send_window(); void cleanup_window(); - bool copy_file(const string &from_filename, const string &to_filename); + bool copy_file(const std::string &from_filename, const std::string &to_filename); - string lookup_token(const string &keyword) const; - bool has_token(const string &keyword) const; - static int compare_seq(const string &seq_a, const string &seq_b); + std::string lookup_token(const std::string &keyword) const; + bool has_token(const std::string &keyword) const; + static int compare_seq(const std::string &seq_a, const std::string &seq_b); static int compare_seq_int(const char *&num_a, const char *&num_b); void set_failed(); @@ -123,15 +123,15 @@ private: class EventAuxData { public: - wstring _characters; - wstring _characters_im; - wstring _text; + std::wstring _characters; + std::wstring _characters_im; + std::wstring _text; }; #ifdef MACOSX_HAS_EVENT_MODELS static void copy_cocoa_event(P3DCocoaEvent *p3d_event, NPCocoaEvent *np_event, EventAuxData &aux_data); - static const wchar_t *make_ansi_string(wstring &result, NPNSString *ns_string); + static const wchar_t *make_ansi_string(std::wstring &result, NPNSString *ns_string); void handle_cocoa_event(const P3DCocoaEvent *p3d_event); void osx_get_twirl_images(); void osx_release_twirl_images(); @@ -157,24 +157,24 @@ private: unsigned int _npp_mode; P3D_window_handle_type _window_handle_type; P3D_event_type _event_type; - typedef vector Tokens; + typedef std::vector Tokens; Tokens _tokens; // Set from fgcolor & bgcolor. int _fgcolor_r, _fgcolor_b, _fgcolor_g; int _bgcolor_r, _bgcolor_b, _bgcolor_g; - string _root_dir; - string _standard_url_prefix; - string _download_url_prefix; - typedef vector Mirrors; + std::string _root_dir; + std::string _standard_url_prefix; + std::string _download_url_prefix; + typedef std::vector Mirrors; Mirrors _mirrors; // A list of URL's that we will attempt to download the core API from. - typedef vector CoreUrls; + typedef std::vector CoreUrls; CoreUrls _core_urls; - string _coreapi_set_ver; + std::string _coreapi_set_ver; FileSpec _coreapi_dll; time_t _contents_expiration; bool _failed; @@ -199,11 +199,11 @@ private: size_t _current_size; size_t _total_size; ofstream _stream; - string _filename; + std::string _filename; }; bool _got_instance_url; - string _instance_url; + std::string _instance_url; int _p3d_instance_id; StreamTempFile _p3d_temp_file; StreamTempFile _contents_temp_file; @@ -212,14 +212,14 @@ private: // We need to keep a list of the NPStream objects that the instance owns, // because Safari (at least) won't automatically delete all of the // outstanding streams when the instance is destroyed. - typedef vector Streams; + typedef std::vector Streams; Streams _streams; // This class is used for feeding local files (accessed via a "file:" url) // into the core API. class StreamingFileData { public: - StreamingFileData(PPDownloadRequest *req, const string &filename, + StreamingFileData(PPDownloadRequest *req, const std::string &filename, P3D_instance *p3d_inst); ~StreamingFileData(); @@ -235,7 +235,7 @@ private: P3D_instance *_p3d_inst; int _user_id; - string _filename; + std::string _filename; ifstream _file; size_t _file_size; size_t _total_count; @@ -243,7 +243,7 @@ private: THREAD _thread; }; - typedef vector FileDatas; + typedef std::vector FileDatas; static FileDatas _file_datas; bool _use_xembed; diff --git a/direct/src/plugin_npapi/ppPandaObject.I b/direct/src/plugin_npapi/ppPandaObject.I index 1f50908246..eafcfbd83c 100644 --- a/direct/src/plugin_npapi/ppPandaObject.I +++ b/direct/src/plugin_npapi/ppPandaObject.I @@ -18,7 +18,7 @@ */ inline P3D_object *PPPandaObject:: get_p3d_object() const { - if (_p3d_object != NULL) { + if (_p3d_object != nullptr) { P3D_OBJECT_INCREF(_p3d_object); } return _p3d_object; diff --git a/direct/src/plugin_npapi/ppPandaObject.cxx b/direct/src/plugin_npapi/ppPandaObject.cxx index c403868a41..e4e4854c3f 100644 --- a/direct/src/plugin_npapi/ppPandaObject.cxx +++ b/direct/src/plugin_npapi/ppPandaObject.cxx @@ -13,6 +13,8 @@ #include "ppPandaObject.h" +using std::string; + NPClass PPPandaObject::_object_class = { NP_CLASS_STRUCT_VERSION, &PPPandaObject::NPAllocate, @@ -52,7 +54,7 @@ make_new(PPInstance *inst, P3D_object *p3d_object) { */ void PPPandaObject:: set_p3d_object(P3D_object *p3d_object) { - if (p3d_object != NULL) { + if (p3d_object != nullptr) { P3D_OBJECT_INCREF(p3d_object); } P3D_OBJECT_XDECREF(_p3d_object); @@ -67,7 +69,7 @@ set_p3d_object(P3D_object *p3d_object) { void PPPandaObject:: construct(PPInstance *inst, P3D_object *p3d_object) { _instance = inst; - _p3d_object = NULL; + _p3d_object = nullptr; set_p3d_object(p3d_object); } @@ -76,8 +78,8 @@ construct(PPInstance *inst, P3D_object *p3d_object) { */ void PPPandaObject:: invalidate() { - _instance = NULL; - set_p3d_object(NULL); + _instance = nullptr; + set_p3d_object(nullptr); } /** @@ -87,7 +89,7 @@ bool PPPandaObject:: has_method(NPIdentifier name) { string method_name = identifier_to_string(name); // nout << this << ".has_method(" << method_name << ")\n"; - if (_p3d_object == NULL) { + if (_p3d_object == nullptr) { // Not powered up yet. return false; } @@ -114,7 +116,7 @@ invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { string method_name = identifier_to_string(name); // nout << this << ".invoke(" << method_name << ")\n"; - if (_p3d_object == NULL) { + if (_p3d_object == nullptr) { // Not powered up yet. return false; } @@ -132,7 +134,7 @@ invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, } delete[] p3dargs; - if (value == NULL) { + if (value == nullptr) { // No such method, or some problem with the parameters. return false; } @@ -151,7 +153,7 @@ bool PPPandaObject:: invoke_default(const NPVariant *args, uint32_t argCount, NPVariant *result) { // nout << this << ".invoke_default()\n"; - if (_p3d_object == NULL) { + if (_p3d_object == nullptr) { // Not powered up yet. return false; } @@ -169,7 +171,7 @@ invoke_default(const NPVariant *args, uint32_t argCount, } delete[] p3dargs; - if (value == NULL) { + if (value == nullptr) { // No such method, or some problem with the parameters. return false; } @@ -187,7 +189,7 @@ bool PPPandaObject:: has_property(NPIdentifier name) { string property_name = identifier_to_string(name); // nout << this << ".has_property(" << property_name << ")\n"; - if (_p3d_object == NULL) { + if (_p3d_object == nullptr) { // Not powered up yet. return false; } @@ -215,14 +217,14 @@ get_property(NPIdentifier name, NPVariant *result) { string property_name = identifier_to_string(name); // nout << this << ".get_property(" << property_name << ")\n"; - if (_p3d_object == NULL) { + if (_p3d_object == nullptr) { // Not powered up yet. VOID_TO_NPVARIANT(*result); return true; } P3D_object *value = P3D_OBJECT_GET_PROPERTY(_p3d_object, property_name.c_str()); - if (value == NULL) { + if (value == nullptr) { // No such property. VOID_TO_NPVARIANT(*result); return true; @@ -242,7 +244,7 @@ bool PPPandaObject:: set_property(NPIdentifier name, const NPVariant *value) { string property_name = identifier_to_string(name); // nout << this << ".set_property(" << property_name << ")\n"; - if (_p3d_object == NULL) { + if (_p3d_object == nullptr) { // Not powered up yet. return false; } @@ -262,13 +264,13 @@ bool PPPandaObject:: remove_property(NPIdentifier name) { string property_name = identifier_to_string(name); // nout << this << ".remove_property(" << property_name << ")\n"; - if (_p3d_object == NULL) { + if (_p3d_object == nullptr) { // Not powered up yet. return false; } bool result = P3D_OBJECT_SET_PROPERTY(_p3d_object, property_name.c_str(), - true, NULL); + true, nullptr); return result; } @@ -281,7 +283,7 @@ enumerate(NPIdentifier **value, uint32_t *count) { // nout << this << ".enumerate()\n"; TODO: Not implemented yet. // Note that the array of values must be allocated here with NPN_MemAlloc(). - *value = NULL; + *value = nullptr; *count = 0; return false; } @@ -294,7 +296,7 @@ string PPPandaObject:: identifier_to_string(NPIdentifier ident) { if (browser->identifierisstring(ident)) { NPUTF8 *result = browser->utf8fromidentifier(ident); - if (result != NULL) { + if (result != nullptr) { string strval(result); browser->memfree(result); return strval; @@ -304,7 +306,7 @@ identifier_to_string(NPIdentifier ident) { // Firefox does, but Safari doesn't appear to use integer identifiers and // just sends everything as a string identifier. So to make things // consistent internally, we also send everything as a string. - ostringstream strm; + std::ostringstream strm; strm << browser->intfromidentifier(ident); return strm.str(); } diff --git a/direct/src/plugin_npapi/ppPandaObject.h b/direct/src/plugin_npapi/ppPandaObject.h index 762f6a9c94..89a87d02af 100644 --- a/direct/src/plugin_npapi/ppPandaObject.h +++ b/direct/src/plugin_npapi/ppPandaObject.h @@ -49,7 +49,7 @@ private: bool enumerate(NPIdentifier **value, uint32_t *count); private: - static string identifier_to_string(NPIdentifier ident); + static std::string identifier_to_string(NPIdentifier ident); private: diff --git a/direct/src/plugin_npapi/ppToplevelObject.cxx b/direct/src/plugin_npapi/ppToplevelObject.cxx index a7f9c879e3..a3790d5039 100644 --- a/direct/src/plugin_npapi/ppToplevelObject.cxx +++ b/direct/src/plugin_npapi/ppToplevelObject.cxx @@ -52,7 +52,7 @@ make_new(PPInstance *inst) { */ void PPToplevelObject:: set_main(P3D_object *p3d_object) { - if (p3d_object != NULL) { + if (p3d_object != nullptr) { P3D_OBJECT_INCREF(p3d_object); } P3D_OBJECT_XDECREF(_main); @@ -67,7 +67,7 @@ set_main(P3D_object *p3d_object) { void PPToplevelObject:: construct(PPInstance *inst) { _instance = inst; - _main = NULL; + _main = nullptr; // Get our one property name as an identifier, so we can look for it. _main_id = browser->getstringidentifier("main"); @@ -78,8 +78,8 @@ construct(PPInstance *inst) { */ void PPToplevelObject:: invalidate() { - _instance = NULL; - set_main(NULL); + _instance = nullptr; + set_main(nullptr); } /** @@ -87,7 +87,7 @@ invalidate() { */ bool PPToplevelObject:: has_property(NPIdentifier name) { - if (_main == NULL) { + if (_main == nullptr) { // Not powered up yet. return false; } @@ -105,7 +105,7 @@ has_property(NPIdentifier name) { */ bool PPToplevelObject:: get_property(NPIdentifier name, NPVariant *result) { - if (_main == NULL) { + if (_main == nullptr) { // Not powered up yet. return false; } diff --git a/direct/src/plugin_npapi/startup.cxx b/direct/src/plugin_npapi/startup.cxx index 8d64c71dc7..315a21f8cc 100644 --- a/direct/src/plugin_npapi/startup.cxx +++ b/direct/src/plugin_npapi/startup.cxx @@ -23,8 +23,10 @@ #include #endif +using std::string; + static ofstream logfile; -ostream *nout_stream = &logfile; +std::ostream *nout_stream = &logfile; string global_root_dir; bool has_plugin_thread_async_call; @@ -62,7 +64,7 @@ open_logfile() { if (log_directory.empty()) { log_directory = global_root_dir + "/log"; } - mkdir_complete(log_directory, cerr); + mkdir_complete(log_directory, std::cerr); // Ensure that the log directory ends with a slash. if (!log_directory.empty() && log_directory[log_directory.size() - 1] != '/') { @@ -92,13 +94,13 @@ open_logfile() { logfile.close(); logfile.clear(); #ifdef _WIN32 - wstring log_pathname_w; + std::wstring log_pathname_w; string_to_wstring(log_pathname_w, log_pathname); - logfile.open(log_pathname_w.c_str(), ios::out | ios::trunc); + logfile.open(log_pathname_w.c_str(), std::ios::out | std::ios::trunc); #else - logfile.open(log_pathname.c_str(), ios::out | ios::trunc); + logfile.open(log_pathname.c_str(), std::ios::out | std::ios::trunc); #endif // _WIN32 - logfile.setf(ios::unitbuf); + logfile.setf(std::ios::unitbuf); } // If we didn't have a logfile name compiled in, we throw away log output @@ -127,7 +129,7 @@ NP_GetMIMEDescription(void) { */ NPError NP_GetValue(void*, NPPVariable variable, void* value) { - if (value == NULL) { + if (value == nullptr) { return NPERR_INVALID_PARAM; } @@ -175,7 +177,7 @@ NP_Initialize(NPNetscapeFuncs *browserFuncs, // On Unix, we have to use the pluginFuncs argument to pass our entry // points. #if !defined(_WIN32) && !defined(__APPLE__) - if (pluginFuncs != NULL) { + if (pluginFuncs != nullptr) { NP_GetEntryPoints(pluginFuncs); } #endif @@ -194,7 +196,7 @@ NP_Initialize(NPNetscapeFuncs *browserFuncs, #ifdef HAS_PLUGIN_THREAD_ASYNC_CALL // Check if the browser offers this very useful call. if (browser_major > 0 || browser_minor >= NPVERS_HAS_PLUGIN_THREAD_ASYNC_CALL) { - if ((void *)browser->pluginthreadasynccall == (void *)NULL) { + if ((void *)browser->pluginthreadasynccall == nullptr) { nout << "Browser should have PLUGIN_THREAD_ASYNC_CALL, but the pointer is NULL.\n"; has_plugin_thread_async_call = false; } else { @@ -205,7 +207,7 @@ NP_Initialize(NPNetscapeFuncs *browserFuncs, // Seed the lame random number generator in rand(); we use it to select a // mirror for downloading. - srand((unsigned int)time(NULL)); + srand((unsigned int)time(nullptr)); return NPERR_NO_ERROR; } @@ -370,11 +372,11 @@ NPP_Destroy(NPP instance, NPSavedData **save) { nout << "save = " << (void *)save << "\n"; // (*save) = NULL; PPInstance *inst = (PPInstance *)(instance->pdata); - assert(inst != NULL); + assert(inst != nullptr); inst->stop_outstanding_streams(); delete inst; - instance->pdata = NULL; + instance->pdata = nullptr; return NPERR_NO_ERROR; } @@ -392,7 +394,7 @@ NPP_SetWindow(NPP instance, NPWindow *window) { << "\n"; PPInstance *inst = (PPInstance *)(instance->pdata); - assert(inst != NULL); + assert(inst != nullptr); inst->set_window(window); return NPERR_NO_ERROR; @@ -414,7 +416,7 @@ NPP_NewStream(NPP instance, NPMIMEType type, NPStream *stream, << ", " << (PPInstance *)(instance->pdata) << "\n"; PPInstance::generic_browser_call(); PPInstance *inst = (PPInstance *)(instance->pdata); - assert(inst != NULL); + assert(inst != nullptr); return inst->new_stream(type, stream, seekable != 0, stype); } @@ -432,7 +434,7 @@ NPP_DestroyStream(NPP instance, NPStream *stream, NPReason reason) { PPInstance::generic_browser_call(); PPInstance *inst = (PPInstance *)(instance->pdata); - assert(inst != NULL); + assert(inst != nullptr); return inst->destroy_stream(stream, reason); } @@ -446,7 +448,7 @@ NPP_WriteReady_x(NPP instance, NPStream *stream) { // (PPInstance *)(instance->pdata) << "\n"; PPInstance::generic_browser_call(); PPInstance *inst = (PPInstance *)(instance->pdata); - assert(inst != NULL); + assert(inst != nullptr); return inst->write_ready(stream); } @@ -462,7 +464,7 @@ NPP_Write_x(NPP instance, NPStream *stream, int32_t offset, // " << instance << ", " << (PPInstance *)(instance->pdata) << "\n"; PPInstance::generic_browser_call(); PPInstance *inst = (PPInstance *)(instance->pdata); - assert(inst != NULL); + assert(inst != nullptr); return inst->write_stream(stream, offset, len, buffer); } @@ -481,7 +483,7 @@ NPP_StreamAsFile(NPP instance, NPStream *stream, const char *fname) { PPInstance::generic_browser_call(); PPInstance *inst = (PPInstance *)(instance->pdata); - assert(inst != NULL); + assert(inst != nullptr); inst->stream_as_file(stream, fname); } @@ -504,7 +506,7 @@ NPP_HandleEvent(NPP instance, void *event) { PPInstance::generic_browser_call(); PPInstance *inst = (PPInstance *)(instance->pdata); - assert(inst != NULL); + assert(inst != nullptr); return inst->handle_event(event); } @@ -522,7 +524,7 @@ NPP_URLNotify(NPP instance, const char *url, PPInstance::generic_browser_call(); PPInstance *inst = (PPInstance *)(instance->pdata); - assert(inst != NULL); + assert(inst != nullptr); inst->url_notify(url, reason, notifyData); } @@ -535,11 +537,11 @@ NPP_GetValue(NPP instance, NPPVariable variable, void *value) { nout << "GetValue " << variable << "\n"; PPInstance::generic_browser_call(); PPInstance *inst = (PPInstance *)(instance->pdata); - assert(inst != NULL); + assert(inst != nullptr); if (variable == NPPVpluginScriptableNPObject) { NPObject *obj = inst->get_panda_script_object(); - if (obj != NULL) { + if (obj != nullptr) { *(NPObject **)value = obj; return NPERR_NO_ERROR; } @@ -571,7 +573,7 @@ NPP_GetValue(NPP instance, NPPVariable variable, void *value) { return NPERR_NO_ERROR; } else { - return NP_GetValue(NULL, variable, value); + return NP_GetValue(nullptr, variable, value); } return NPERR_GENERIC_ERROR; diff --git a/direct/src/plugin_standalone/p3dEmbed.cxx b/direct/src/plugin_standalone/p3dEmbed.cxx index 87918f66f4..1d191e9c22 100644 --- a/direct/src/plugin_standalone/p3dEmbed.cxx +++ b/direct/src/plugin_standalone/p3dEmbed.cxx @@ -17,6 +17,9 @@ #include "load_plugin.h" #include "find_root_dir.h" +using std::cerr; +using std::string; + /** * */ @@ -36,7 +39,7 @@ P3DEmbed(bool console_environment) : Panda3DBase(console_environment) { * offset. */ int P3DEmbed:: -run_embedded(streampos read_offset, int argc, char *argv[]) { +run_embedded(std::streampos read_offset, int argc, char *argv[]) { // Check to see if we've actually got an application embedded. If we do, // read_offset will have been modified to contain a different value than the // one we compiled in, above. We test against read_offset + 1, because any @@ -46,8 +49,8 @@ run_embedded(streampos read_offset, int argc, char *argv[]) { // We also have to store this computation in a member variable, to work // around a compiler optimization that might otherwise remove the + 1 from // the test. - _read_offset_check = read_offset + (streampos)1; - if (_read_offset_check == (streampos)0xFF3D3D01) { + _read_offset_check = read_offset + (std::streampos)1; + if (_read_offset_check == (std::streampos)0xFF3D3D01) { cerr << "This program is not intended to be run directly.\nIt is used " "by pdeploy to construct an embedded Panda3D application.\n"; return 1; @@ -76,8 +79,8 @@ run_embedded(streampos read_offset, int argc, char *argv[]) { string curstr; bool havenull = false; P3D_token token; - token._keyword = NULL; - token._value = NULL; + token._keyword = nullptr; + token._value = nullptr; string keyword; string value; string root_dir; diff --git a/direct/src/plugin_standalone/p3dEmbed.h b/direct/src/plugin_standalone/p3dEmbed.h index 98a73ec8fc..7d1da92883 100644 --- a/direct/src/plugin_standalone/p3dEmbed.h +++ b/direct/src/plugin_standalone/p3dEmbed.h @@ -35,9 +35,9 @@ class P3DEmbed : public Panda3DBase { public: P3DEmbed(bool console_environment); - int run_embedded(streampos read_offset, int argc, char *argv[]); + int run_embedded(std::streampos read_offset, int argc, char *argv[]); - streampos _read_offset_check; + std::streampos _read_offset_check; }; #endif diff --git a/direct/src/plugin_standalone/panda3d.cxx b/direct/src/plugin_standalone/panda3d.cxx index 10876d2e64..d21933a441 100644 --- a/direct/src/plugin_standalone/panda3d.cxx +++ b/direct/src/plugin_standalone/panda3d.cxx @@ -29,6 +29,10 @@ #include #endif +using std::cerr; +using std::cout; +using std::string; + /** * */ @@ -144,12 +148,12 @@ run_command_line(int argc, char *argv[]) { // will be delivered to the subordinate Python process and return to a // command shell, and won't just kill the panda3d process. #ifdef _WIN32 - SetConsoleCtrlHandler(NULL, true); + SetConsoleCtrlHandler(nullptr, true); #else struct sigaction ignore; memset(&ignore, 0, sizeof(ignore)); ignore.sa_handler = SIG_IGN; - sigaction(SIGINT, &ignore, NULL); + sigaction(SIGINT, &ignore, nullptr); #endif // _WIN32 } break; @@ -348,7 +352,7 @@ get_plugin() { Filename contents_filename = Filename(Filename::from_os_specific(_root_dir), "contents.xml"); if (_verify_contents != P3D_VC_force) { if (read_contents_file(contents_filename, false)) { - if (_verify_contents == P3D_VC_none || time(NULL) < _contents_expiration) { + if (_verify_contents == P3D_VC_none || time(nullptr) < _contents_expiration) { // Got the file, and it's good. success = true; } @@ -410,12 +414,12 @@ download_contents_file(const Filename &contents_filename) { if (!success) { // Go download contents.xml from the actual host. - ostringstream strm; + std::ostringstream strm; strm << _host_url_prefix << "contents.xml"; // Append a uniquifying query string to the URL to force the download to // go all the way through any caches. We use the time in seconds; that's // unique enough. - strm << "?" << time(NULL); + strm << "?" << time(nullptr); string url = strm.str(); // We might as well explicitly request the cache to be disabled too, since @@ -468,19 +472,19 @@ read_contents_file(const Filename &contents_filename, bool fresh_download) { bool found_core_package = false; TiXmlElement *xcontents = doc.FirstChildElement("contents"); - if (xcontents != NULL) { + if (xcontents != nullptr) { int max_age = P3D_CONTENTS_DEFAULT_MAX_AGE; xcontents->Attribute("max_age", &max_age); // Get the latest possible expiration time, based on the max_age // indication. Any expiration time later than this is in error. - time_t now = time(NULL); + time_t now = time(nullptr); _contents_expiration = now + (time_t)max_age; if (fresh_download) { // Update the XML with the new download information. TiXmlElement *xorig = xcontents->FirstChildElement("orig"); - while (xorig != NULL) { + while (xorig != nullptr) { xcontents->RemoveChild(xorig); xorig = xcontents->FirstChildElement("orig"); } @@ -494,11 +498,11 @@ read_contents_file(const Filename &contents_filename, bool fresh_download) { // Read the expiration time from the XML. int expiration = 0; TiXmlElement *xorig = xcontents->FirstChildElement("orig"); - if (xorig != NULL) { + if (xorig != nullptr) { xorig->Attribute("expiration", &expiration); } - _contents_expiration = min(_contents_expiration, (time_t)expiration); + _contents_expiration = std::min(_contents_expiration, (time_t)expiration); } // Look for the entry; it might point us at a different download @@ -508,14 +512,14 @@ read_contents_file(const Filename &contents_filename, bool fresh_download) { // Now look for the core API package. _coreapi_set_ver = ""; TiXmlElement *xpackage = xcontents->FirstChildElement("package"); - while (xpackage != NULL) { + while (xpackage != nullptr) { const char *name = xpackage->Attribute("name"); - if (name != NULL && strcmp(name, "coreapi") == 0) { + if (name != nullptr && strcmp(name, "coreapi") == 0) { const char *platform = xpackage->Attribute("platform"); - if (platform != NULL && _coreapi_platform == string(platform)) { + if (platform != nullptr && _coreapi_platform == string(platform)) { _coreapi_dll.load_xml(xpackage); const char *set_ver = xpackage->Attribute("set_ver"); - if (set_ver != NULL) { + if (set_ver != nullptr) { _coreapi_set_ver = set_ver; } found_core_package = true; @@ -583,9 +587,9 @@ read_contents_file(const Filename &contents_filename, bool fresh_download) { void Panda3D:: find_host(TiXmlElement *xcontents) { TiXmlElement *xhost = xcontents->FirstChildElement("host"); - if (xhost != NULL) { + if (xhost != nullptr) { const char *url = xhost->Attribute("url"); - if (url != NULL && _host_url == string(url)) { + if (url != nullptr && _host_url == string(url)) { // We're the primary host. This is the normal case. read_xhost(xhost); return; @@ -593,9 +597,9 @@ find_host(TiXmlElement *xcontents) { } else { // We're not the primary host; perhaps we're an alternate host. TiXmlElement *xalthost = xhost->FirstChildElement("alt_host"); - while (xalthost != NULL) { + while (xalthost != nullptr) { const char *url = xalthost->Attribute("url"); - if (url != NULL && _host_url == string(url)) { + if (url != nullptr && _host_url == string(url)) { // Yep, we're this alternate host. read_xhost(xhost); return; @@ -619,11 +623,11 @@ read_xhost(TiXmlElement *xhost) { // Get the "download" URL, which is the source from which we download // everything other than the contents.xml file. const char *download_url = xhost->Attribute("download_url"); - if (download_url == NULL) { + if (download_url == nullptr) { download_url = xhost->Attribute("url"); } - if (download_url != NULL) { + if (download_url != nullptr) { _download_url_prefix = download_url; } else { _download_url_prefix = _host_url_prefix; @@ -635,9 +639,9 @@ read_xhost(TiXmlElement *xhost) { } TiXmlElement *xmirror = xhost->FirstChildElement("mirror"); - while (xmirror != NULL) { + while (xmirror != nullptr) { const char *url = xmirror->Attribute("url"); - if (url != NULL) { + if (url != nullptr) { add_mirror(url); } xmirror = xmirror->NextSiblingElement("mirror"); @@ -670,7 +674,7 @@ void Panda3D:: choose_random_mirrors(vector_string &result, int num_mirrors) { pvector selected; - size_t num_to_select = min(_mirrors.size(), (size_t)num_mirrors); + size_t num_to_select = std::min(_mirrors.size(), (size_t)num_mirrors); while (num_to_select > 0) { size_t i = (size_t)(((double)rand() / (double)RAND_MAX) * _mirrors.size()); while (find(selected.begin(), selected.end(), i) != selected.end()) { @@ -740,7 +744,7 @@ get_core_api() { #endif // Format the coreapi_timestamp as a string, for passing as a parameter. - ostringstream stream; + std::ostringstream stream; stream << _coreapi_dll.get_timestamp(); string coreapi_timestamp = stream.str(); @@ -765,9 +769,9 @@ download_core_api() { // Our last act of desperation: hit the original host, with a query // uniquifier, to break through any caches. - ostringstream strm; + std::ostringstream strm; strm << _download_url_prefix << _coreapi_dll.get_filename() - << "?" << time(NULL); + << "?" << time(nullptr); url = strm.str(); core_urls.push_back(url); diff --git a/direct/src/plugin_standalone/panda3d.h b/direct/src/plugin_standalone/panda3d.h index 8333177bb2..a9b647fc7d 100644 --- a/direct/src/plugin_standalone/panda3d.h +++ b/direct/src/plugin_standalone/panda3d.h @@ -43,7 +43,7 @@ protected: bool read_contents_file(const Filename &contents_filename, bool fresh_download); void find_host(TiXmlElement *xcontents); void read_xhost(TiXmlElement *xhost); - void add_mirror(string mirror_url); + void add_mirror(std::string mirror_url); void choose_random_mirrors(vector_string &result, int num_mirrors); bool get_core_api(); bool download_core_api(); @@ -51,14 +51,14 @@ protected: void usage(); protected: - string _super_mirror_url; - string _host_url_prefix; - string _download_url_prefix; - string _super_mirror_url_prefix; - typedef pvector Mirrors; + std::string _super_mirror_url; + std::string _host_url_prefix; + std::string _download_url_prefix; + std::string _super_mirror_url_prefix; + typedef pvector Mirrors; Mirrors _mirrors; - string _coreapi_set_ver; + std::string _coreapi_set_ver; FileSpec _coreapi_dll; }; diff --git a/direct/src/plugin_standalone/panda3dBase.cxx b/direct/src/plugin_standalone/panda3dBase.cxx index 0b3884f17c..cfdaeb1350 100644 --- a/direct/src/plugin_standalone/panda3dBase.cxx +++ b/direct/src/plugin_standalone/panda3dBase.cxx @@ -35,6 +35,9 @@ #include #include +using std::cerr; +using std::string; + // The amount of time in seconds to wait for new messages. static const double wait_cycle = 0.2; @@ -74,7 +77,7 @@ Panda3DBase(bool console_environment) { // Seed the lame random number generator in rand(); we use it to select a // mirror for downloading. - srand((unsigned int)time(NULL)); + srand((unsigned int)time(nullptr)); _prepend_filename_to_args = true; } @@ -90,7 +93,7 @@ run_main_loop() { // Wait for new messages from Windows, and new requests from the plugin. MSG msg; int retval; - retval = GetMessage(&msg, NULL, 0, 0); + retval = GetMessage(&msg, nullptr, 0, 0); while (retval != 0 && !time_to_exit()) { if (retval == -1) { cerr << "Error processing message queue.\n"; @@ -101,20 +104,20 @@ run_main_loop() { // Check for new requests from the Panda3D plugin. P3D_instance *inst = P3D_check_request_ptr(wait_cycle); - while (inst != (P3D_instance *)NULL) { + while (inst != nullptr) { P3D_request *request = P3D_instance_get_request_ptr(inst); - if (request != (P3D_request *)NULL) { + if (request != nullptr) { handle_request(request); } inst = P3D_check_request_ptr(wait_cycle); } while (!_url_getters.empty() && - !PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { + !PeekMessage(&msg, nullptr, 0, 0, PM_NOREMOVE)) { // If there are no Windows messages, check the download tasks. run_getters(); } - retval = GetMessage(&msg, NULL, 0, 0); + retval = GetMessage(&msg, nullptr, 0, 0); } // WM_QUIT has been received. Terminate all instances, and fall through. @@ -128,9 +131,9 @@ run_main_loop() { // Windows events. Instead, just wait for requests. while (!time_to_exit()) { P3D_instance *inst = P3D_check_request_ptr(wait_cycle); - if (inst != (P3D_instance *)NULL) { + if (inst != nullptr) { P3D_request *request = P3D_instance_get_request_ptr(inst); - if (request != (P3D_request *)NULL) { + if (request != nullptr) { handle_request(request); } } @@ -162,9 +165,9 @@ run_main_loop() { // Now wait while we process pending requests. while (!time_to_exit()) { P3D_instance *inst = P3D_check_request_ptr(wait_cycle); - if (inst != (P3D_instance *)NULL) { + if (inst != nullptr) { P3D_request *request = P3D_instance_get_request_ptr(inst); - if (request != (P3D_request *)NULL) { + if (request != nullptr) { handle_request(request); } } @@ -207,7 +210,7 @@ handle_request(P3D_request *request) { delete_instance(request->_instance); #ifdef _WIN32 // Post a silly message to spin the event loop. - PostMessage(NULL, WM_USER, 0, 0); + PostMessage(nullptr, WM_USER, 0, 0); #endif handled = true; break; @@ -267,7 +270,7 @@ void Panda3DBase:: make_parent_window() { WNDCLASS wc; - HINSTANCE application = GetModuleHandle(NULL); + HINSTANCE application = GetModuleHandle(nullptr); ZeroMemory(&wc, sizeof(WNDCLASS)); wc.lpfnWndProc = (WNDPROC)window_proc; wc.hInstance = application; @@ -287,7 +290,7 @@ make_parent_window() { HWND toplevel_window = CreateWindow("panda3d", "Panda3D", window_style, CW_USEDEFAULT, CW_USEDEFAULT, _win_width, _win_height, - NULL, NULL, application, 0); + nullptr, nullptr, application, 0); if (!toplevel_window) { cerr << "Could not create toplevel window!\n"; exit(1); @@ -364,7 +367,7 @@ create_instance(const string &p3d, bool start_instance, token._value = "1"; tokens.push_back(token); - P3D_token *tokens_p = NULL; + P3D_token *tokens_p = nullptr; size_t num_tokens = tokens.size(); if (!tokens.empty()) { tokens_p = &tokens[0]; @@ -379,10 +382,10 @@ create_instance(const string &p3d, bool start_instance, argv.push_back(args[i]); } - P3D_instance *inst = P3D_new_instance_ptr(NULL, tokens_p, num_tokens, - argv.size(), &argv[0], NULL); + P3D_instance *inst = P3D_new_instance_ptr(nullptr, tokens_p, num_tokens, + argv.size(), &argv[0], nullptr); - if (inst != NULL) { + if (inst != nullptr) { if (start_instance) { // We call start() first, to give the core API a chance to notice the // "hidden" attrib before we set the window parameters. @@ -436,18 +439,18 @@ read_p3d_info(const Filename &p3d_filename, int p3d_offset) { string p3d_info; mf->read_subfile(si, p3d_info); - istringstream strm(p3d_info); + std::istringstream strm(p3d_info); TiXmlDocument doc; strm >> doc; if (strm.fail() && !strm.eof()) { return false; } TiXmlElement *xpackage = doc.FirstChildElement("package"); - if (xpackage == NULL) { + if (xpackage == nullptr) { return false; } TiXmlElement *xconfig = xpackage->FirstChildElement("config"); - if (xconfig == NULL) { + if (xconfig == nullptr) { return false; } @@ -473,7 +476,7 @@ read_p3d_info(const Filename &p3d_filename, int p3d_offset) { bool Panda3DBase:: parse_token(const char *arg) { const char *equals = strchr(arg, '='); - if (equals == NULL) { + if (equals == nullptr) { return false; } @@ -624,12 +627,12 @@ report_downloading_package(P3D_instance *instance) { P3D_object *obj = P3D_instance_get_panda_script_object_ptr(instance); P3D_object *display_name = P3D_object_get_property_ptr(obj, "downloadPackageDisplayName"); - if (display_name == NULL) { + if (display_name == nullptr) { cerr << "Installing package.\n"; return; } - int name_length = P3D_object_get_string_ptr(display_name, NULL, 0); + int name_length = P3D_object_get_string_ptr(display_name, nullptr, 0); char *name = new char[name_length + 1]; P3D_object_get_string_ptr(display_name, name, name_length + 1); @@ -670,9 +673,9 @@ void Panda3DBase:: timer_callback(EventLoopTimerRef timer) { // Check for new requests from the Panda3D plugin. P3D_instance *inst = P3D_check_request_ptr(0.0); - while (inst != (P3D_instance *)NULL) { + while (inst != nullptr) { P3D_request *request = P3D_instance_get_request_ptr(inst); - if (request != (P3D_request *)NULL) { + if (request != nullptr) { handle_request(request); } inst = P3D_check_request_ptr(0.0); @@ -758,6 +761,6 @@ run() { P3D_instance_feed_url_stream_ptr (_instance, _unique_id, status, _channel->get_status_code(), - _bytes_sent, NULL, 0); + _bytes_sent, nullptr, 0); return false; } diff --git a/direct/src/plugin_standalone/panda3dBase.h b/direct/src/plugin_standalone/panda3dBase.h index fd277ce9ec..3b41aab07c 100644 --- a/direct/src/plugin_standalone/panda3dBase.h +++ b/direct/src/plugin_standalone/panda3dBase.h @@ -45,17 +45,17 @@ protected: void make_parent_window(); P3D_instance * - create_instance(const string &p3d, bool start_instance, + create_instance(const std::string &p3d, bool start_instance, char **args, int num_args, int p3d_offset = 0); void delete_instance(P3D_instance *instance); bool read_p3d_info(const Filename &p3d_filename, int p3d_offset = 0); bool parse_token(const char *arg); bool parse_int_pair(const char *arg, int &x, int &y); - string lookup_token(const string &keyword) const; - static int compare_seq(const string &seq_a, const string &seq_b); + std::string lookup_token(const std::string &keyword) const; + static int compare_seq(const std::string &seq_a, const std::string &seq_b); static int compare_seq_int(const char *&num_a, const char *&num_b); - static bool is_url(const string ¶m); + static bool is_url(const std::string ¶m); void report_downloading_package(P3D_instance *instance); void report_download_complete(P3D_instance *instance); @@ -68,14 +68,14 @@ protected: #endif protected: - string _host_url; - string _root_dir; - string _host_dir; - string _start_dir; - string _log_dirname; - string _log_basename; - string _this_platform; - string _coreapi_platform; + std::string _host_url; + std::string _root_dir; + std::string _host_dir; + std::string _start_dir; + std::string _log_dirname; + std::string _log_basename; + std::string _this_platform; + std::string _coreapi_platform; P3D_verify_contents _verify_contents; time_t _contents_expiration; @@ -101,7 +101,7 @@ protected: class URLGetter { public: URLGetter(P3D_instance *instance, int unique_id, - const URLSpec &url, const string &post_data); + const URLSpec &url, const std::string &post_data); bool run(); inline P3D_instance *get_instance(); @@ -110,7 +110,7 @@ protected: P3D_instance *_instance; int _unique_id; URLSpec _url; - string _post_data; + std::string _post_data; PT(HTTPChannel) _channel; Ramfile _rf; diff --git a/direct/src/plugin_standalone/panda3dMac.cxx b/direct/src/plugin_standalone/panda3dMac.cxx index 2b7ab47e8c..5a87c60d3e 100644 --- a/direct/src/plugin_standalone/panda3dMac.cxx +++ b/direct/src/plugin_standalone/panda3dMac.cxx @@ -16,7 +16,6 @@ #include #include -using namespace std; // Having a global Panda3DMac object just makes things easier. static Panda3DMac *this_prog; @@ -48,12 +47,12 @@ open_p3d_file(FSRef *ref) { UInt8 filename[buffer_size]; err = FSRefMakePath(ref, filename, buffer_size); if (err) { - cerr << "Couldn't get filename\n"; + std::cerr << "Couldn't get filename\n"; return; } // Create an instance. - create_instance((char *)filename, true, NULL, 0); + create_instance((char *)filename, true, nullptr, 0); } static pascal OSErr @@ -74,7 +73,7 @@ open_documents_handler(const AppleEvent *theAppleEvent, AppleEvent *reply, for (index = 1; index <= count; index++) { err = AEGetNthPtr(&docList, index, typeFSRef, - NULL, NULL, &theFSRef, sizeof(FSRef), NULL);// 5 + nullptr, nullptr, &theFSRef, sizeof(FSRef), nullptr);// 5 require_noerr(err, CantGetDocDescPtr); // Here's the file, do something with it. diff --git a/direct/src/plugin_standalone/panda3dWinMain.cxx b/direct/src/plugin_standalone/panda3dWinMain.cxx index dbf951da4c..ec7b8e630c 100644 --- a/direct/src/plugin_standalone/panda3dWinMain.cxx +++ b/direct/src/plugin_standalone/panda3dWinMain.cxx @@ -22,7 +22,7 @@ static char * parse_quoted_arg(char *&p) { char quote = *p; ++p; - string result; + std::string result; while (*p != '\0' && *p != quote) { // TODO: handle escape characters? Not sure if we need to. @@ -39,7 +39,7 @@ parse_quoted_arg(char *&p) { // beginning at p. Advances p to the first whitespace following the argument. static char * parse_unquoted_arg(char *&p) { - string result; + std::string result; while (*p != '\0' && !isspace(*p)) { result += *p; ++p; @@ -51,7 +51,7 @@ int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { char *command_line = GetCommandLine(); - vector argv; + std::vector argv; char *p = command_line; while (*p != '\0') { diff --git a/direct/src/showbase/Audio3DManager.py b/direct/src/showbase/Audio3DManager.py index 463d3b5bf0..4a67c9bc27 100644 --- a/direct/src/showbase/Audio3DManager.py +++ b/direct/src/showbase/Audio3DManager.py @@ -2,8 +2,8 @@ __all__ = ['Audio3DManager'] -from panda3d.core import Vec3, VBase3 -from direct.task import Task +from panda3d.core import Vec3, VBase3, WeakNodePath +from direct.task.TaskManagerGlobal import Task, taskMgr # class Audio3DManager: @@ -181,7 +181,8 @@ class Audio3DManager: def attachSoundToObject(self, sound, object): """ - Sound will come from the location of the object it is attached to + Sound will come from the location of the object it is attached to. + If the object is deleted, the sound will automatically be removed. """ # sound is an AudioSound # object is any Panda object with coordinates @@ -197,7 +198,7 @@ class Audio3DManager: del self.sound_dict[known_object] if object not in self.sound_dict: - self.sound_dict[object] = [] + self.sound_dict[WeakNodePath(object)] = [] self.sound_dict[object].append(sound) return 1 @@ -258,14 +259,18 @@ class Audio3DManager: if self.audio_manager.getActive()==0: return Task.cont - for known_object in list(self.sound_dict.keys()): - tracked_sound = 0 - while tracked_sound < len(self.sound_dict[known_object]): - sound = self.sound_dict[known_object][tracked_sound] - pos = known_object.getPos(self.root) + for known_object, sounds in list(self.sound_dict.items()): + node_path = known_object.getNodePath() + if not node_path: + # The node has been deleted. + del self.sound_dict[known_object] + continue + + pos = node_path.getPos(self.root) + + for sound in sounds: vel = self.getSoundVelocity(sound) sound.set3dAttributes(pos[0], pos[1], pos[2], vel[0], vel[1], vel[2]) - tracked_sound += 1 # Update the position of the listener based on the object # to which it is attached diff --git a/direct/src/showbase/showBase.cxx b/direct/src/showbase/showBase.cxx index 12aa08d4bd..f14d9610a4 100644 --- a/direct/src/showbase/showBase.cxx +++ b/direct/src/showbase/showBase.cxx @@ -34,6 +34,9 @@ TOGGLEKEYS g_StartupToggleKeys = {sizeof(TOGGLEKEYS), 0}; FILTERKEYS g_StartupFilterKeys = {sizeof(FILTERKEYS), 0}; #endif +using std::max; +using std::min; + #if !defined(CPPPARSER) && !defined(BUILDING_DIRECT_SHOWBASE) #error Buildsystem error: BUILDING_DIRECT_SHOWBASE not defined #endif @@ -201,7 +204,7 @@ add_grid_zone(unsigned int x, // zoneBase is the first zone in the grid (e.g. the upper left) // zoneResolution is the number of cells on each axsis. returns the next // available zoneBase (i.e. zoneBase+xZoneResolution*yZoneResolution) - cerr<<"adding grid zone with a zoneBase of "< 1.0 || y < 0.0 || y > 1.0) { return 0; } - cerr<<"resolution="<= (3, 0) and isinstance(pathname, bytes): + newpath = bytearray(drive) + for c in pathname: + if c == 42 or c == 63 or c == 91: + newpath += bytes((91, c, 93)) + else: + newpath.append(c) + return bytes(newpath) + else: + newpath = drive + for c in pathname: + if c == '*' or c == '?' or c == '[': + newpath += '[' + c + ']' + else: + newpath += c + return newpath diff --git a/dtool/src/cppparser/cppArrayType.cxx b/dtool/src/cppparser/cppArrayType.cxx index ce861c1d69..ea25b871cb 100644 --- a/dtool/src/cppparser/cppArrayType.cxx +++ b/dtool/src/cppparser/cppArrayType.cxx @@ -85,7 +85,7 @@ is_trivial() const { */ bool CPPArrayType:: is_default_constructible() const { - return _bounds != NULL && _element_type->is_default_constructible(); + return _bounds != nullptr && _element_type->is_default_constructible(); } /** @@ -93,7 +93,21 @@ is_default_constructible() const { */ bool CPPArrayType:: is_copy_constructible() const { - return false; + // This is technically not exactly true, but array data members do not + // prevent C++ implicit copy constructor generation rules, so we need to + // return true here. + // If this is a problem, we will need to create a separate method for the + // purpose of checking copyability as a data member. + return true; +} + +/** + * Returns true if the type is copy-assignable. + */ +bool CPPArrayType:: +is_copy_assignable() const { + // Same story as is_copy_constructible. + return true; } /** @@ -105,7 +119,7 @@ is_copy_constructible() const { bool CPPArrayType:: is_equivalent(const CPPType &other) const { const CPPArrayType *ot = ((CPPType *)&other)->as_array_type(); - if (ot == (CPPArrayType *)NULL) { + if (ot == nullptr) { return CPPType::is_equivalent(other); } @@ -128,7 +142,7 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, _element_type->substitute_decl(subst, current_scope, global_scope) ->as_type(); - if (_bounds != NULL) { + if (_bounds != nullptr) { rep->_bounds = _bounds->substitute_decl(subst, current_scope, global_scope) ->as_expression(); @@ -148,7 +162,7 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, * */ void CPPArrayType:: -output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { +output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const { /* _element_type->output(out, indent_level, scope, complete); out << "["; @@ -166,16 +180,16 @@ output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { * have special exceptions. */ void CPPArrayType:: -output_instance(ostream &out, int indent_level, CPPScope *scope, - bool complete, const string &prename, - const string &name) const { - ostringstream brackets; +output_instance(std::ostream &out, int indent_level, CPPScope *scope, + bool complete, const std::string &prename, + const std::string &name) const { + std::ostringstream brackets; brackets << "["; - if (_bounds != NULL) { + if (_bounds != nullptr) { brackets << *_bounds; } brackets << "]"; - string bracketsstr = brackets.str(); + std::string bracketsstr = brackets.str(); _element_type->output_instance(out, indent_level, scope, complete, prename, name + bracketsstr); @@ -204,13 +218,13 @@ as_array_type() { bool CPPArrayType:: is_equal(const CPPDeclaration *other) const { const CPPArrayType *ot = ((CPPDeclaration *)other)->as_array_type(); - assert(ot != NULL); + assert(ot != nullptr); - if (_bounds != NULL && ot->_bounds != NULL) { + if (_bounds != nullptr && ot->_bounds != nullptr) { if (*_bounds != *ot->_bounds) { return false; } - } else if ((_bounds == NULL) != (ot->_bounds == NULL)) { + } else if ((_bounds == nullptr) != (ot->_bounds == nullptr)) { return false; } @@ -225,13 +239,13 @@ is_equal(const CPPDeclaration *other) const { bool CPPArrayType:: is_less(const CPPDeclaration *other) const { const CPPArrayType *ot = ((CPPDeclaration *)other)->as_array_type(); - assert(ot != NULL); + assert(ot != nullptr); - if (_bounds != NULL && ot->_bounds != NULL) { + if (_bounds != nullptr && ot->_bounds != nullptr) { if (*_bounds != *ot->_bounds) { return *_bounds < *ot->_bounds; } - } else if ((_bounds == NULL) != (ot->_bounds == NULL)) { + } else if ((_bounds == nullptr) != (ot->_bounds == nullptr)) { return _bounds < ot->_bounds; } diff --git a/dtool/src/cppparser/cppArrayType.h b/dtool/src/cppparser/cppArrayType.h index 9e2489be72..7668950620 100644 --- a/dtool/src/cppparser/cppArrayType.h +++ b/dtool/src/cppparser/cppArrayType.h @@ -42,14 +42,15 @@ public: virtual bool is_trivial() const; virtual bool is_default_constructible() const; virtual bool is_copy_constructible() const; + virtual bool is_copy_assignable() const; virtual bool is_equivalent(const CPPType &other) const; - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; - virtual void output_instance(ostream &out, int indent_level, + virtual void output_instance(std::ostream &out, int indent_level, CPPScope *scope, - bool complete, const string &prename, - const string &name) const; + bool complete, const std::string &prename, + const std::string &name) const; virtual SubType get_subtype() const; diff --git a/dtool/src/cppparser/cppBison.cxx.prebuilt b/dtool/src/cppparser/cppBison.cxx.prebuilt index 2167d06578..4bff774461 100644 --- a/dtool/src/cppparser/cppBison.cxx.prebuilt +++ b/dtool/src/cppparser/cppBison.cxx.prebuilt @@ -97,6 +97,9 @@ #include "cppNamespace.h" #include "cppUsing.h" +using std::stringstream; +using std::string; + //////////////////////////////////////////////////////////////////// // Defining the interface to the parser. //////////////////////////////////////////////////////////////////// @@ -110,14 +113,13 @@ static CPPEnumType *current_enum = NULL; static int current_storage_class = 0; static CPPType *current_type = NULL; static CPPExpression *current_expr = NULL; -static CPPClosureType *current_closure = NULL; static int publish_nest_level = 0; static CPPVisibility publish_previous; static YYLTYPE publish_loc; -static vector last_scopes; -static vector last_storage_classes; -static vector last_structs; +static std::vector last_scopes; +static std::vector last_storage_classes; +static std::vector last_structs; int yyparse(); diff --git a/dtool/src/cppparser/cppBison.yxx b/dtool/src/cppparser/cppBison.yxx index 68f4f96706..5c2721eea7 100644 --- a/dtool/src/cppparser/cppBison.yxx +++ b/dtool/src/cppparser/cppBison.yxx @@ -32,27 +32,29 @@ #include "cppNamespace.h" #include "cppUsing.h" +using std::stringstream; +using std::string; + //////////////////////////////////////////////////////////////////// // Defining the interface to the parser. //////////////////////////////////////////////////////////////////// -CPPScope *current_scope = NULL; -CPPScope *global_scope = NULL; -CPPPreprocessor *current_lexer = NULL; +CPPScope *current_scope = nullptr; +CPPScope *global_scope = nullptr; +CPPPreprocessor *current_lexer = nullptr; -static CPPStructType *current_struct = NULL; -static CPPEnumType *current_enum = NULL; +static CPPStructType *current_struct = nullptr; +static CPPEnumType *current_enum = nullptr; static int current_storage_class = 0; -static CPPType *current_type = NULL; -static CPPExpression *current_expr = NULL; -static CPPClosureType *current_closure = NULL; +static CPPType *current_type = nullptr; +static CPPExpression *current_expr = nullptr; static int publish_nest_level = 0; static CPPVisibility publish_previous; static YYLTYPE publish_loc; -static vector last_scopes; -static vector last_storage_classes; -static vector last_structs; +static std::vector last_scopes; +static std::vector last_storage_classes; +static std::vector last_structs; int yyparse(); @@ -119,7 +121,7 @@ parse_const_expr(CPPPreprocessor *pp, CPPScope *new_current_scope, current_scope = new_current_scope; global_scope = new_global_scope; - current_expr = (CPPExpression *)NULL; + current_expr = nullptr; current_lexer = pp; yyparse(); @@ -143,7 +145,7 @@ parse_type(CPPPreprocessor *pp, CPPScope *new_current_scope, current_scope = new_current_scope; global_scope = new_global_scope; - current_type = (CPPType *)NULL; + current_type = nullptr; current_lexer = pp; yyparse(); @@ -160,7 +162,7 @@ parse_type(CPPPreprocessor *pp, CPPScope *new_current_scope, static void push_scope(CPPScope *new_scope) { last_scopes.push_back(current_scope); - if (new_scope != NULL) { + if (new_scope != nullptr) { current_scope = new_scope; } } @@ -653,7 +655,7 @@ declaration: CPPDeclaration *length_getter = $5->find_symbol(current_scope, global_scope, current_lexer); if (length_getter == nullptr || length_getter->get_subtype() != CPPDeclaration::ST_function_group) { yyerror("reference to non-existent or invalid length method: " + $5->get_fully_scoped_name(), @5); - length_getter = NULL; + length_getter = nullptr; } CPPDeclaration *getter = $7->find_symbol(current_scope, global_scope, current_lexer); @@ -689,7 +691,7 @@ declaration: CPPDeclaration *length_getter = $5->find_symbol(current_scope, global_scope, current_lexer); if (length_getter == nullptr || length_getter->get_subtype() != CPPDeclaration::ST_function_group) { yyerror("reference to non-existent or invalid length method: " + $5->get_fully_scoped_name(), @5); - length_getter = NULL; + length_getter = nullptr; } CPPDeclaration *getter = $7->find_symbol(current_scope, global_scope, current_lexer); @@ -891,18 +893,18 @@ declaration: | KW_MAKE_SEQ '(' name ',' IDENTIFIER ',' IDENTIFIER ')' ';' { CPPDeclaration *length_getter = $5->find_symbol(current_scope, global_scope, current_lexer); - if (length_getter == (CPPDeclaration *)NULL || length_getter->get_subtype() != CPPDeclaration::ST_function_group) { + if (length_getter == nullptr || length_getter->get_subtype() != CPPDeclaration::ST_function_group) { yyerror("reference to non-existent or invalid length method: " + $5->get_fully_scoped_name(), @5); - length_getter = NULL; + length_getter = nullptr; } CPPDeclaration *element_getter = $7->find_symbol(current_scope, global_scope, current_lexer); - if (element_getter == (CPPDeclaration *)NULL || element_getter->get_subtype() != CPPDeclaration::ST_function_group) { + if (element_getter == nullptr || element_getter->get_subtype() != CPPDeclaration::ST_function_group) { yyerror("reference to non-existent or invalid element method: " + $7->get_fully_scoped_name(), @5); - element_getter = NULL; + element_getter = nullptr; } - if (length_getter != (CPPDeclaration *)NULL && element_getter != (CPPDeclaration *)NULL) { + if (length_getter != nullptr && element_getter != nullptr) { CPPMakeSeq *make_seq = new CPPMakeSeq($3, length_getter->as_function_group(), element_getter->as_function_group(), @@ -1071,7 +1073,7 @@ type_like_declaration: } | storage_class constructor_prototype { - if ($2 != (CPPInstance *)NULL) { + if ($2 != nullptr) { // Push the scope so that the initializers can make use of things defined // in the class body. push_scope($2->get_scope(current_scope, global_scope)); @@ -1080,7 +1082,7 @@ type_like_declaration: } maybe_initialize_or_constructor_body { - if ($2 != (CPPInstance *)NULL) { + if ($2 != nullptr) { pop_scope(); current_scope->add_declaration($2, global_scope, current_lexer, @2); $2->set_initializer($4); @@ -1088,7 +1090,7 @@ type_like_declaration: } | storage_class function_prototype maybe_initialize_or_function_body { - if ($2 != (CPPInstance *)NULL) { + if ($2 != nullptr) { $2->_storage_class |= (current_storage_class | $1); current_scope->add_declaration($2, global_scope, current_lexer, @2); $2->set_initializer($3); @@ -1145,9 +1147,9 @@ typedef_declaration: } | storage_class function_prototype maybe_initialize_or_function_body { - if ($2 != (CPPDeclaration *)NULL) { + if ($2 != nullptr) { CPPInstance *inst = $2->as_instance(); - if (inst != (CPPInstance *)NULL) { + if (inst != nullptr) { inst->_storage_class |= (current_storage_class | $1); current_scope->add_declaration(inst, global_scope, current_lexer, @2); CPPTypedefType *typedef_type = new CPPTypedefType(inst->_type, inst->_ident, current_scope); @@ -1270,10 +1272,10 @@ function_prototype: { pop_scope(); CPPType *type = $1->find_type(current_scope, global_scope, false, current_lexer); - if (type == NULL) { + if (type == nullptr) { yyerror(string("internal error resolving type ") + $1->get_fully_scoped_name(), @1); } - assert(type != NULL); + assert(type != nullptr); CPPInstanceIdentifier *ii = $4; ii->add_modifier(IIT_pointer); @@ -1288,10 +1290,10 @@ function_prototype: { pop_scope(); CPPType *type = $1->find_type(current_scope, global_scope, false, current_lexer); - if (type == NULL) { + if (type == nullptr) { yyerror(string("internal error resolving type ") + $1->get_fully_scoped_name(), @1); } - assert(type != NULL); + assert(type != nullptr); CPPInstanceIdentifier *ii = $5; ii->add_scoped_pointer_modifier($3); @@ -1302,13 +1304,13 @@ function_prototype: /* Typecast operators */ | KW_OPERATOR type not_paren_formal_parameter_identifier '(' { - if ($1 != NULL) { + if ($1 != nullptr) { push_scope($1->get_scope(current_scope, global_scope)); } } function_parameter_list ')' function_post { - if ($1 != NULL) { + if ($1 != nullptr) { pop_scope(); } @@ -1323,7 +1325,7 @@ function_prototype: // the method's return type to determine the full type description. string name = "operator typecast " + $2->get_simple_name(); CPPIdentifier *ident = $1; - if (ident == NULL) { + if (ident == nullptr) { ident = new CPPIdentifier(name, @2); } else { ident->add_name(name); @@ -1333,18 +1335,18 @@ function_prototype: } | KW_OPERATOR KW_CONST type not_paren_formal_parameter_identifier '(' { - if ($1 != NULL) { + if ($1 != nullptr) { push_scope($1->get_scope(current_scope, global_scope)); } } function_parameter_list ')' function_post { - if ($1 != NULL) { + if ($1 != nullptr) { pop_scope(); } CPPIdentifier *ident = $1; - if (ident == NULL) { + if (ident == nullptr) { ident = new CPPIdentifier("operator typecast", @4); } else { ident->add_name("operator typecast"); @@ -1361,10 +1363,10 @@ function_prototype: { CPPDeclaration *decl = $1->find_symbol(current_scope, global_scope, current_lexer); - if (decl != (CPPDeclaration *)NULL) { + if (decl != nullptr) { $$ = decl->as_instance(); } else { - $$ = (CPPInstance *)NULL; + $$ = nullptr; } } ; @@ -1627,13 +1629,13 @@ template_nonempty_formal_parameters: template_formal_parameter { CPPTemplateScope *ts = current_scope->as_template_scope(); - assert(ts != NULL); + assert(ts != nullptr); ts->add_template_parameter($1); } | template_nonempty_formal_parameters ',' template_formal_parameter { CPPTemplateScope *ts = current_scope->as_template_scope(); - assert(ts != NULL); + assert(ts != nullptr); ts->add_template_parameter($3); } ; @@ -1646,7 +1648,7 @@ typename_keyword: template_formal_parameter: typename_keyword { - $$ = CPPType::new_type(new CPPClassTemplateParameter((CPPIdentifier *)NULL)); + $$ = CPPType::new_type(new CPPClassTemplateParameter(nullptr)); } | typename_keyword name { @@ -1658,7 +1660,7 @@ template_formal_parameter: } | typename_keyword ELLIPSIS { - CPPClassTemplateParameter *ctp = new CPPClassTemplateParameter((CPPIdentifier *)NULL); + CPPClassTemplateParameter *ctp = new CPPClassTemplateParameter(nullptr); ctp->_packed = true; $$ = CPPType::new_type(ctp); } @@ -1707,18 +1709,18 @@ template_formal_parameter_type: | TYPENAME_IDENTIFIER { $$ = $1->find_type(current_scope, global_scope, false, current_lexer); - if ($$ == NULL) { + if ($$ == nullptr) { yyerror(string("internal error resolving type ") + $1->get_fully_scoped_name(), @1); } - assert($$ != NULL); + assert($$ != nullptr); } | TYPEPACK_IDENTIFIER { $$ = $1->find_type(current_scope, global_scope, false, current_lexer); - if ($$ == NULL) { + if ($$ == nullptr) { yyerror(string("internal error resolving type ") + $1->get_fully_scoped_name(), @1); } - assert($$ != NULL); + assert($$ != nullptr); } ; @@ -1734,7 +1736,7 @@ instance_identifier: // ficticious name for the function; in other respects it's just // like a regular function. CPPIdentifier *ident = $1; - if (ident == NULL) { + if (ident == nullptr) { ident = new CPPIdentifier("operator "+$2, @2); } else { ident->_names.push_back("operator "+$2); @@ -1749,7 +1751,7 @@ instance_identifier: yyerror("expected empty string", @2); } CPPIdentifier *ident = $1; - if (ident == NULL) { + if (ident == nullptr) { ident = new CPPIdentifier("operator \"\" "+$3->get_simple_name(), @3); } else { ident->_names.push_back("operator \"\" "+$3->get_simple_name()); @@ -1833,7 +1835,7 @@ instance_identifier_and_maybe_trailing_return_type: // This is handled a bit awkwardly right now. Ideally it'd be wrapped // up in the instance_identifier rule, but then more needs to happen in // order to avoid shift/reduce conflicts. - if ($2 != NULL) { + if ($2 != nullptr) { $1->add_trailing_return_type($2); } $$ = $1; @@ -1850,7 +1852,7 @@ instance_identifier_and_maybe_trailing_return_type: maybe_trailing_return_type: empty { - $$ = NULL; + $$ = nullptr; } | POINTSAT predefined_type empty_instance_identifier { @@ -1867,7 +1869,7 @@ maybe_trailing_return_type: maybe_comma_identifier: empty { - $$ = NULL; + $$ = nullptr; } | ',' IDENTIFIER { @@ -1957,7 +1959,7 @@ formal_parameters: template_parameter_maybe_initialize: empty { - $$ = (CPPExpression *)NULL; + $$ = nullptr; } | '=' no_angle_bracket_const_expr { @@ -1968,7 +1970,7 @@ template_parameter_maybe_initialize: maybe_initialize: empty { - $$ = (CPPExpression *)NULL; + $$ = nullptr; } | '=' const_expr { @@ -1979,15 +1981,15 @@ maybe_initialize: maybe_initialize_or_constructor_body: ';' { - $$ = (CPPExpression *)NULL; + $$ = nullptr; } | '{' code '}' { - $$ = (CPPExpression *)NULL; + $$ = nullptr; } | ':' constructor_inits '{' code '}' { - $$ = (CPPExpression *)NULL; + $$ = nullptr; } | '=' KW_DEFAULT ';' { @@ -2002,11 +2004,11 @@ maybe_initialize_or_constructor_body: maybe_initialize_or_function_body: ';' { - $$ = (CPPExpression *)NULL; + $$ = nullptr; } | '{' code '}' { - $$ = (CPPExpression *)NULL; + $$ = nullptr; } | '=' const_expr ';' { @@ -2022,7 +2024,7 @@ maybe_initialize_or_function_body: } | '=' '{' structure_init '}' { - $$ = (CPPExpression *)NULL; + $$ = nullptr; } ; @@ -2107,7 +2109,7 @@ formal_parameter: not_paren_formal_parameter_identifier: empty { - $$ = new CPPInstanceIdentifier((CPPIdentifier *)NULL); + $$ = new CPPInstanceIdentifier(nullptr); } | name_no_final { @@ -2153,7 +2155,7 @@ not_paren_formal_parameter_identifier: formal_parameter_identifier: empty { - $$ = new CPPInstanceIdentifier((CPPIdentifier *)NULL); + $$ = new CPPInstanceIdentifier(nullptr); } | name_no_final { @@ -2210,7 +2212,7 @@ formal_parameter_identifier: parameter_pack_identifier: ELLIPSIS { - $$ = new CPPInstanceIdentifier((CPPIdentifier *)NULL); + $$ = new CPPInstanceIdentifier(nullptr); $$->_packed = true; } | ELLIPSIS name @@ -2269,11 +2271,11 @@ parameter_pack_identifier: not_paren_empty_instance_identifier: empty { - $$ = new CPPInstanceIdentifier((CPPIdentifier *)NULL); + $$ = new CPPInstanceIdentifier(nullptr); } | ELLIPSIS { - $$ = new CPPInstanceIdentifier((CPPIdentifier *)NULL); + $$ = new CPPInstanceIdentifier(nullptr); $$->_packed = true; } | ELLIPSIS name @@ -2321,11 +2323,11 @@ not_paren_empty_instance_identifier: empty_instance_identifier: empty { - $$ = new CPPInstanceIdentifier((CPPIdentifier *)NULL); + $$ = new CPPInstanceIdentifier(nullptr); } | ELLIPSIS { - $$ = new CPPInstanceIdentifier((CPPIdentifier *)NULL); + $$ = new CPPInstanceIdentifier(nullptr); $$->_packed = true; } | ELLIPSIS name @@ -2370,7 +2372,7 @@ empty_instance_identifier: } | '(' function_parameter_list ')' function_post maybe_trailing_return_type { - $$ = new CPPInstanceIdentifier((CPPIdentifier *)NULL); + $$ = new CPPInstanceIdentifier(nullptr); $$->add_modifier(IIT_paren); $$->add_func_modifier($2, $4, $5); } @@ -2405,10 +2407,10 @@ type: | TYPENAME_IDENTIFIER { $$ = $1->find_type(current_scope, global_scope, false, current_lexer); - if ($$ == NULL) { + if ($$ == nullptr) { yyerror(string("internal error resolving type ") + $1->get_fully_scoped_name(), @1); } - assert($$ != NULL); + assert($$ != nullptr); } | KW_TYPENAME name { @@ -2429,14 +2431,14 @@ type: | struct_keyword struct_attributes name { CPPType *type = $3->find_type(current_scope, global_scope, false, current_lexer); - if (type != NULL) { + if (type != nullptr) { $$ = type; } else { CPPExtensionType *et = CPPType::new_type(new CPPExtensionType($1, $3, current_scope, @1.file)) ->as_extension_type(); CPPScope *scope = $3->get_scope(current_scope, global_scope); - if (scope != NULL) { + if (scope != nullptr) { scope->define_extension_type(et); } $$ = et; @@ -2445,14 +2447,14 @@ type: | enum_keyword name_no_final ':' enum_element_type { CPPType *type = $2->find_type(current_scope, global_scope, false, current_lexer); - if (type != NULL) { + if (type != nullptr) { $$ = type; } else { CPPExtensionType *et = CPPType::new_type(new CPPExtensionType($1, $2, current_scope, @1.file)) ->as_extension_type(); CPPScope *scope = $2->get_scope(current_scope, global_scope); - if (scope != NULL) { + if (scope != nullptr) { scope->define_extension_type(et); } $$ = et; @@ -2461,7 +2463,7 @@ type: | KW_DECLTYPE '(' const_expr ')' { $$ = $3->determine_type(); - if ($$ == (CPPType *)NULL) { + if ($$ == nullptr) { stringstream str; str << *$3; yyerror("could not determine type of " + str.str(), @3); @@ -2474,7 +2476,7 @@ type: | KW_UNDERLYING_TYPE '(' full_type ')' { CPPEnumType *enum_type = $3->as_enum_type(); - if (enum_type == NULL) { + if (enum_type == nullptr) { yyerror("an enumeration type is required", @3); $$ = $3; } else { @@ -2491,10 +2493,10 @@ type_pack: TYPEPACK_IDENTIFIER { $$ = $1->find_type(current_scope, global_scope, false, current_lexer); - if ($$ == NULL) { + if ($$ == nullptr) { yyerror(string("internal error resolving type ") + $1->get_fully_scoped_name(), @1); } - assert($$ != NULL); + assert($$ != nullptr); } ; @@ -2506,10 +2508,10 @@ type_decl: | TYPENAME_IDENTIFIER { $$ = $1->find_type(current_scope, global_scope, false, current_lexer); - if ($$ == NULL) { + if ($$ == nullptr) { yyerror(string("internal error resolving type ") + $1->get_fully_scoped_name(), @1); } - assert($$ != NULL); + assert($$ != nullptr); } | KW_TYPENAME name { @@ -2530,14 +2532,14 @@ type_decl: | struct_keyword struct_attributes name { CPPType *type = $3->find_type(current_scope, global_scope, false, current_lexer); - if (type != NULL) { + if (type != nullptr) { $$ = type; } else { CPPExtensionType *et = CPPType::new_type(new CPPExtensionType($1, $3, current_scope, @1.file)) ->as_extension_type(); CPPScope *scope = $3->get_scope(current_scope, global_scope); - if (scope != NULL) { + if (scope != nullptr) { scope->define_extension_type(et); } $$ = et; @@ -2546,14 +2548,14 @@ type_decl: | enum_keyword name_no_final ':' enum_element_type { CPPType *type = $2->find_type(current_scope, global_scope, false, current_lexer); - if (type != NULL) { + if (type != nullptr) { $$ = type; } else { CPPExtensionType *et = CPPType::new_type(new CPPExtensionType($1, $2, current_scope, @1.file)) ->as_extension_type(); CPPScope *scope = $2->get_scope(current_scope, global_scope); - if (scope != NULL) { + if (scope != nullptr) { scope->define_extension_type(et); } $$ = et; @@ -2564,14 +2566,14 @@ type_decl: yywarning(string("C++ does not permit forward declaration of untyped enum ") + $2->get_fully_scoped_name(), @1); CPPType *type = $2->find_type(current_scope, global_scope, false, current_lexer); - if (type != NULL) { + if (type != nullptr) { $$ = type; } else { CPPExtensionType *et = CPPType::new_type(new CPPExtensionType($1, $2, current_scope, @1.file)) ->as_extension_type(); CPPScope *scope = $2->get_scope(current_scope, global_scope); - if (scope != NULL) { + if (scope != nullptr) { scope->define_extension_type(et); } $$ = et; @@ -2580,7 +2582,7 @@ type_decl: | KW_DECLTYPE '(' const_expr ')' { $$ = $3->determine_type(); - if ($$ == (CPPType *)NULL) { + if ($$ == nullptr) { stringstream str; str << *$3; yyerror("could not determine type of " + str.str(), @3); @@ -2593,7 +2595,7 @@ type_decl: | KW_UNDERLYING_TYPE '(' full_type ')' { CPPEnumType *enum_type = $3->as_enum_type(); - if (enum_type == NULL) { + if (enum_type == nullptr) { yyerror("an enumeration type is required", @3); $$ = $3; } else { @@ -2614,10 +2616,10 @@ predefined_type: | TYPENAME_IDENTIFIER { $$ = $1->find_type(current_scope, global_scope, false, current_lexer); - if ($$ == NULL) { + if ($$ == nullptr) { yyerror(string("internal error resolving type ") + $1->get_fully_scoped_name(), @1); } - assert($$ != NULL); + assert($$ != nullptr); } | KW_TYPENAME name { @@ -2626,14 +2628,14 @@ predefined_type: | struct_keyword struct_attributes name { CPPType *type = $3->find_type(current_scope, global_scope, false, current_lexer); - if (type != NULL) { + if (type != nullptr) { $$ = type; } else { CPPExtensionType *et = CPPType::new_type(new CPPExtensionType($1, $3, current_scope, @1.file)) ->as_extension_type(); CPPScope *scope = $3->get_scope(current_scope, global_scope); - if (scope != NULL) { + if (scope != nullptr) { scope->define_extension_type(et); } $$ = et; @@ -2642,14 +2644,14 @@ predefined_type: | enum_keyword name { CPPType *type = $2->find_type(current_scope, global_scope, false, current_lexer); - if (type != NULL) { + if (type != nullptr) { $$ = type; } else { CPPExtensionType *et = CPPType::new_type(new CPPExtensionType($1, $2, current_scope, @1.file)) ->as_extension_type(); CPPScope *scope = $2->get_scope(current_scope, global_scope); - if (scope != NULL) { + if (scope != nullptr) { scope->define_extension_type(et); } $$ = et; @@ -2658,7 +2660,7 @@ predefined_type: | KW_DECLTYPE '(' const_expr ')' { $$ = $3->determine_type(); - if ($$ == (CPPType *)NULL) { + if ($$ == nullptr) { stringstream str; str << *$3; yyerror("could not determine type of " + str.str(), @3); @@ -2667,7 +2669,7 @@ predefined_type: | KW_UNDERLYING_TYPE '(' full_type ')' { CPPEnumType *enum_type = $3->as_enum_type(); - if (enum_type == NULL) { + if (enum_type == nullptr) { yyerror("an enumeration type is required", @3); $$ = $3; } else { @@ -2728,7 +2730,7 @@ anonymous_struct: CPPScope *new_scope = new CPPScope(current_scope, CPPNameComponent("anon"), starting_vis); - CPPStructType *st = new CPPStructType($1, NULL, current_scope, + CPPStructType *st = new CPPStructType($1, nullptr, current_scope, new_scope, @1.file); new_scope->set_struct_type(st); @@ -2751,7 +2753,7 @@ named_struct: ($1 == CPPExtensionType::T_class) ? V_private : V_public; CPPScope *scope = $3->get_scope(current_scope, global_scope, current_lexer); - if (scope == NULL) { + if (scope == nullptr) { scope = current_scope; } CPPScope *new_scope = new CPPScope(scope, $3->_names.back(), @@ -2839,18 +2841,18 @@ enum: enum_decl '{' enum_body '}' { $$ = current_enum; - current_enum = NULL; + current_enum = nullptr; } ; enum_decl: enum_keyword ':' enum_element_type { - current_enum = new CPPEnumType($1, NULL, $3, current_scope, NULL, @1.file); + current_enum = new CPPEnumType($1, nullptr, $3, current_scope, nullptr, @1.file); } | enum_keyword { - current_enum = new CPPEnumType($1, NULL, current_scope, NULL, @1.file); + current_enum = new CPPEnumType($1, nullptr, current_scope, nullptr, @1.file); } | enum_keyword name_no_final ':' enum_element_type { @@ -2879,12 +2881,12 @@ enum_body_trailing_comma: empty | enum_body_trailing_comma name ',' { - assert(current_enum != NULL); - current_enum->add_element($2->get_simple_name(), NULL, current_lexer, @2); + assert(current_enum != nullptr); + current_enum->add_element($2->get_simple_name(), nullptr, current_lexer, @2); } | enum_body_trailing_comma name '=' const_expr ',' { - assert(current_enum != NULL); + assert(current_enum != nullptr); current_enum->add_element($2->get_simple_name(), $4, current_lexer, @2); }; @@ -2892,12 +2894,12 @@ enum_body: enum_body_trailing_comma | enum_body_trailing_comma name { - assert(current_enum != NULL); - current_enum->add_element($2->get_simple_name(), NULL, current_lexer, @2); + assert(current_enum != nullptr); + current_enum->add_element($2->get_simple_name(), nullptr, current_lexer, @2); } | enum_body_trailing_comma name '=' const_expr { - assert(current_enum != NULL); + assert(current_enum != nullptr); current_enum->add_element($2->get_simple_name(), $4, current_lexer, @2); } ; @@ -2936,11 +2938,11 @@ namespace_declaration: KW_NAMESPACE name '{' { CPPScope *scope = $2->find_scope(current_scope, global_scope, current_lexer); - if (scope == NULL) { + if (scope == nullptr) { // This must be a new namespace declaration. CPPScope *parent_scope = $2->get_scope(current_scope, global_scope, current_lexer); - if (parent_scope == NULL) { + if (parent_scope == nullptr) { parent_scope = current_scope; } scope = new CPPScope(parent_scope, $2->_names.back(), V_public); @@ -2958,11 +2960,11 @@ namespace_declaration: | KW_INLINE KW_NAMESPACE name '{' { CPPScope *scope = $3->find_scope(current_scope, global_scope, current_lexer); - if (scope == NULL) { + if (scope == nullptr) { // This must be a new namespace declaration. CPPScope *parent_scope = $3->get_scope(current_scope, global_scope, current_lexer); - if (parent_scope == NULL) { + if (parent_scope == nullptr) { parent_scope = current_scope; } scope = new CPPScope(parent_scope, $3->_names.back(), V_public); @@ -3166,7 +3168,7 @@ element: optional_const_expr: empty { - $$ = (CPPExpression *)NULL; + $$ = nullptr; } | const_expr { @@ -3177,7 +3179,7 @@ optional_const_expr: optional_const_expr_comma: empty { - $$ = (CPPExpression *)NULL; + $$ = nullptr; } | const_expr_comma { @@ -3228,7 +3230,7 @@ no_angle_bracket_const_expr: | KW_SIZEOF '(' IDENTIFIER ')' %prec UNARY { CPPDeclaration *arg = $3->find_symbol(current_scope, global_scope, current_lexer); - if (arg == (CPPDeclaration *)NULL) { + if (arg == nullptr) { yyerror("undefined sizeof argument: " + $3->get_fully_scoped_name(), @3); } else if (arg->get_subtype() == CPPDeclaration::ST_instance) { CPPInstance *inst = arg->as_instance(); @@ -3393,20 +3395,20 @@ const_expr: { // A constructor call. CPPType *type = $1->find_type(current_scope, global_scope, false, current_lexer); - if (type == NULL) { + if (type == nullptr) { yyerror(string("internal error resolving type ") + $1->get_fully_scoped_name(), @1); } - assert(type != NULL); + assert(type != nullptr); $$ = new CPPExpression(CPPExpression::construct_op(type, $3)); } | TYPENAME_IDENTIFIER '{' optional_const_expr_comma '}' { // Aggregate initialization. CPPType *type = $1->find_type(current_scope, global_scope, false, current_lexer); - if (type == NULL) { + if (type == nullptr) { yyerror(string("internal error resolving type ") + $1->get_fully_scoped_name(), @1); } - assert(type != NULL); + assert(type != nullptr); $$ = new CPPExpression(CPPExpression::aggregate_init_op(type, $3)); } | KW_INT '(' optional_const_expr_comma ')' @@ -3492,7 +3494,7 @@ const_expr: | KW_SIZEOF '(' IDENTIFIER ')' %prec UNARY { CPPDeclaration *arg = $3->find_symbol(current_scope, global_scope, current_lexer); - if (arg == (CPPDeclaration *)NULL) { + if (arg == nullptr) { yyerror("undefined sizeof argument: " + $3->get_fully_scoped_name(), @3); } else if (arg->get_subtype() == CPPDeclaration::ST_instance) { CPPInstance *inst = arg->as_instance(); @@ -3836,7 +3838,7 @@ formal_const_expr: | KW_SIZEOF '(' IDENTIFIER ')' %prec UNARY { CPPDeclaration *arg = $3->find_symbol(current_scope, global_scope, current_lexer); - if (arg == (CPPDeclaration *)NULL) { + if (arg == nullptr) { yyerror("undefined sizeof argument: " + $3->get_fully_scoped_name(), @3); } else if (arg->get_subtype() == CPPDeclaration::ST_instance) { CPPInstance *inst = arg->as_instance(); @@ -4124,7 +4126,7 @@ class_derivation_name: name { CPPType *type = $1->find_type(current_scope, global_scope, true); - if (type == NULL) { + if (type == nullptr) { type = CPPType::new_type(new CPPTBDType($1)); } $$ = type; diff --git a/dtool/src/cppparser/cppBisonDefs.h b/dtool/src/cppparser/cppBisonDefs.h index 1ae1caece8..9e8f71f9b1 100644 --- a/dtool/src/cppparser/cppBisonDefs.h +++ b/dtool/src/cppparser/cppBisonDefs.h @@ -27,8 +27,6 @@ #include "cppExtensionType.h" #include "cppFile.h" -using namespace std; - class CPPParser; class CPPExpression; class CPPPreprocessor; @@ -66,7 +64,7 @@ extern CPPPreprocessor *current_lexer; class cppyystype { public: - string str; + std::string str; union { unsigned long long integer; long double real; diff --git a/dtool/src/cppparser/cppClassTemplateParameter.cxx b/dtool/src/cppparser/cppClassTemplateParameter.cxx index 7ed9a94faf..7c85eb6c24 100644 --- a/dtool/src/cppparser/cppClassTemplateParameter.cxx +++ b/dtool/src/cppparser/cppClassTemplateParameter.cxx @@ -40,13 +40,13 @@ is_fully_specified() const { * */ void CPPClassTemplateParameter:: -output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { +output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const { if (complete) { out << "class"; if (_packed) { out << "..."; } - if (_ident != NULL) { + if (_ident != nullptr) { out << " "; _ident->output(out, scope); } @@ -83,7 +83,7 @@ as_class_template_parameter() { bool CPPClassTemplateParameter:: is_equal(const CPPDeclaration *other) const { const CPPClassTemplateParameter *ot = ((CPPDeclaration *)other)->as_class_template_parameter(); - assert(ot != NULL); + assert(ot != nullptr); if (_default_type != ot->_default_type) { return false; @@ -93,7 +93,7 @@ is_equal(const CPPDeclaration *other) const { return false; } - if (_ident == NULL || ot->_ident == NULL) { + if (_ident == nullptr || ot->_ident == nullptr) { return _ident == ot->_ident; } @@ -108,7 +108,7 @@ is_equal(const CPPDeclaration *other) const { bool CPPClassTemplateParameter:: is_less(const CPPDeclaration *other) const { const CPPClassTemplateParameter *ot = ((CPPDeclaration *)other)->as_class_template_parameter(); - assert(ot != NULL); + assert(ot != nullptr); if (_default_type != ot->_default_type) { return _default_type < ot->_default_type; @@ -118,7 +118,7 @@ is_less(const CPPDeclaration *other) const { return _packed < ot->_packed; } - if (_ident == NULL || ot->_ident == NULL) { + if (_ident == nullptr || ot->_ident == nullptr) { return _ident < ot->_ident; } diff --git a/dtool/src/cppparser/cppClassTemplateParameter.h b/dtool/src/cppparser/cppClassTemplateParameter.h index d936ca01ea..8ff6fe1538 100644 --- a/dtool/src/cppparser/cppClassTemplateParameter.h +++ b/dtool/src/cppparser/cppClassTemplateParameter.h @@ -26,10 +26,10 @@ class CPPIdentifier; class CPPClassTemplateParameter : public CPPType { public: CPPClassTemplateParameter(CPPIdentifier *ident, - CPPType *default_type = NULL); + CPPType *default_type = nullptr); virtual bool is_fully_specified() const; - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; virtual SubType get_subtype() const; diff --git a/dtool/src/cppparser/cppClosureType.cxx b/dtool/src/cppparser/cppClosureType.cxx index 30197057a6..1d12602c3b 100644 --- a/dtool/src/cppparser/cppClosureType.cxx +++ b/dtool/src/cppparser/cppClosureType.cxx @@ -20,7 +20,7 @@ */ CPPClosureType:: CPPClosureType(CaptureType default_capture) : - CPPFunctionType(NULL, NULL, 0), + CPPFunctionType(nullptr, nullptr, 0), _default_capture(default_capture) { } @@ -49,7 +49,7 @@ operator = (const CPPClosureType ©) { * Adds a new capture to the beginning of the capture list. */ void CPPClosureType:: -add_capture(string name, CaptureType type, CPPExpression *initializer) { +add_capture(std::string name, CaptureType type, CPPExpression *initializer) { if (type == CT_none) { if (name == "this") { type = CT_by_reference; @@ -58,8 +58,8 @@ add_capture(string name, CaptureType type, CPPExpression *initializer) { } } - Capture capture = {move(name), type, initializer}; - _captures.insert(_captures.begin(), move(capture)); + Capture capture = {std::move(name), type, initializer}; + _captures.insert(_captures.begin(), std::move(capture)); } /** @@ -100,7 +100,7 @@ is_destructible() const { * */ void CPPClosureType:: -output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { +output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const { out.put('['); bool have_capture = false; @@ -134,7 +134,7 @@ output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { } out << capture._name; - if (capture._initializer != NULL) { + if (capture._initializer != nullptr) { out << " = " << *capture._initializer; } @@ -142,7 +142,7 @@ output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { } out.put(']'); - if (_parameters != NULL) { + if (_parameters != nullptr) { out.put('('); _parameters->output(out, scope, true, -1); out.put(')'); @@ -152,7 +152,7 @@ output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { out << " noexcept"; } - if (_return_type != NULL) { + if (_return_type != nullptr) { out << " -> "; _return_type->output(out, indent_level, scope, false); } diff --git a/dtool/src/cppparser/cppClosureType.h b/dtool/src/cppparser/cppClosureType.h index 9c3533ad4a..9e11a2f124 100644 --- a/dtool/src/cppparser/cppClosureType.h +++ b/dtool/src/cppparser/cppClosureType.h @@ -35,16 +35,16 @@ public: void operator = (const CPPClosureType ©); struct Capture { - string _name; + std::string _name; CaptureType _type; CPPExpression *_initializer; }; - typedef vector Captures; + typedef std::vector Captures; Captures _captures; CaptureType _default_capture; - void add_capture(string name, CaptureType type, CPPExpression *initializer = NULL); + void add_capture(std::string name, CaptureType type, CPPExpression *initializer = nullptr); virtual bool is_fully_specified() const; @@ -52,7 +52,7 @@ public: virtual bool is_copy_constructible() const; virtual bool is_destructible() const; - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; virtual SubType get_subtype() const; virtual CPPClosureType *as_closure_type(); diff --git a/dtool/src/cppparser/cppCommentBlock.h b/dtool/src/cppparser/cppCommentBlock.h index d3e8ef0a02..e31b3b6278 100644 --- a/dtool/src/cppparser/cppCommentBlock.h +++ b/dtool/src/cppparser/cppCommentBlock.h @@ -33,9 +33,9 @@ public: int _col_number; int _last_line; bool _c_style; - string _comment; + std::string _comment; }; -typedef list CPPComments; +typedef std::list CPPComments; #endif diff --git a/dtool/src/cppparser/cppConstType.cxx b/dtool/src/cppparser/cppConstType.cxx index f1851b5233..139a25dc5c 100644 --- a/dtool/src/cppparser/cppConstType.cxx +++ b/dtool/src/cppparser/cppConstType.cxx @@ -160,7 +160,7 @@ is_convertible_to(const CPPType *other) const { bool CPPConstType:: is_equivalent(const CPPType &other) const { const CPPConstType *ot = ((CPPType *)&other)->as_const_type(); - if (ot == (CPPConstType *)NULL) { + if (ot == nullptr) { return CPPType::is_equivalent(other); } @@ -171,7 +171,7 @@ is_equivalent(const CPPType &other) const { * */ void CPPConstType:: -output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { +output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const { _wrapped_around->output(out, indent_level, scope, complete); out << " const"; } @@ -182,9 +182,9 @@ output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { * have special exceptions. */ void CPPConstType:: -output_instance(ostream &out, int indent_level, CPPScope *scope, - bool complete, const string &prename, - const string &name) const { +output_instance(std::ostream &out, int indent_level, CPPScope *scope, + bool complete, const std::string &prename, + const std::string &name) const { _wrapped_around->output_instance(out, indent_level, scope, complete, "const " + prename, name); } @@ -213,7 +213,7 @@ as_const_type() { bool CPPConstType:: is_equal(const CPPDeclaration *other) const { const CPPConstType *ot = ((CPPDeclaration *)other)->as_const_type(); - assert(ot != NULL); + assert(ot != nullptr); return _wrapped_around == ot->_wrapped_around; } @@ -226,7 +226,7 @@ is_equal(const CPPDeclaration *other) const { bool CPPConstType:: is_less(const CPPDeclaration *other) const { const CPPConstType *ot = ((CPPDeclaration *)other)->as_const_type(); - assert(ot != NULL); + assert(ot != nullptr); return _wrapped_around < ot->_wrapped_around; } diff --git a/dtool/src/cppparser/cppConstType.h b/dtool/src/cppparser/cppConstType.h index ef0943ca13..4f49a94c54 100644 --- a/dtool/src/cppparser/cppConstType.h +++ b/dtool/src/cppparser/cppConstType.h @@ -46,12 +46,12 @@ public: virtual bool is_convertible_to(const CPPType *other) const; virtual bool is_equivalent(const CPPType &other) const; - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; - virtual void output_instance(ostream &out, int indent_level, + virtual void output_instance(std::ostream &out, int indent_level, CPPScope *scope, - bool complete, const string &prename, - const string &name) const; + bool complete, const std::string &prename, + const std::string &name) const; virtual SubType get_subtype() const; diff --git a/dtool/src/cppparser/cppDeclaration.cxx b/dtool/src/cppparser/cppDeclaration.cxx index 3d2e5e68f5..0125ed4289 100644 --- a/dtool/src/cppparser/cppDeclaration.cxx +++ b/dtool/src/cppparser/cppDeclaration.cxx @@ -22,8 +22,8 @@ CPPDeclaration(const CPPFile &file) : _file(file) { _vis = V_unknown; - _template_scope = NULL; - _leading_comment = (CPPCommentBlock *)NULL; + _template_scope = nullptr; + _leading_comment = nullptr; } /** @@ -86,7 +86,7 @@ operator < (const CPPDeclaration &other) const { */ bool CPPDeclaration:: is_template() const { - return _template_scope != NULL; + return _template_scope != nullptr; } /** @@ -116,7 +116,7 @@ CPPDeclaration *CPPDeclaration:: instantiate(const CPPTemplateParameterList *, CPPScope *, CPPScope *, CPPPreprocessor *error_sink) const { - if (error_sink != NULL) { + if (error_sink != nullptr) { error_sink->warning("Ignoring template parameters"); } return (CPPDeclaration *)this; @@ -129,7 +129,7 @@ CPPDeclaration *CPPDeclaration:: substitute_decl(SubstDecl &subst, CPPScope *, CPPScope *) { SubstDecl::const_iterator si = subst.find(this); if (si != subst.end()) { - assert((*si).second != NULL); + assert((*si).second != nullptr); return (*si).second; } return this; @@ -140,7 +140,7 @@ substitute_decl(SubstDecl &subst, CPPScope *, CPPScope *) { */ CPPInstance *CPPDeclaration:: as_instance() { - return (CPPInstance *)NULL; + return nullptr; } /** @@ -148,7 +148,7 @@ as_instance() { */ CPPClassTemplateParameter *CPPDeclaration:: as_class_template_parameter() { - return (CPPClassTemplateParameter *)NULL; + return nullptr; } /** @@ -156,7 +156,7 @@ as_class_template_parameter() { */ CPPTypedefType *CPPDeclaration:: as_typedef_type() { - return (CPPTypedefType *)NULL; + return nullptr; } /** @@ -164,7 +164,7 @@ as_typedef_type() { */ CPPTypeDeclaration *CPPDeclaration:: as_type_declaration() { - return (CPPTypeDeclaration *)NULL; + return nullptr; } /** @@ -172,7 +172,7 @@ as_type_declaration() { */ CPPExpression *CPPDeclaration:: as_expression() { - return (CPPExpression *)NULL; + return nullptr; } /** @@ -180,7 +180,7 @@ as_expression() { */ CPPType *CPPDeclaration:: as_type() { - return (CPPType *)NULL; + return nullptr; } /** @@ -188,7 +188,7 @@ as_type() { */ CPPNamespace *CPPDeclaration:: as_namespace() { - return (CPPNamespace *)NULL; + return nullptr; } /** @@ -196,7 +196,7 @@ as_namespace() { */ CPPUsing *CPPDeclaration:: as_using() { - return (CPPUsing *)NULL; + return nullptr; } /** @@ -204,7 +204,7 @@ as_using() { */ CPPSimpleType *CPPDeclaration:: as_simple_type() { - return (CPPSimpleType *)NULL; + return nullptr; } /** @@ -212,7 +212,7 @@ as_simple_type() { */ CPPPointerType *CPPDeclaration:: as_pointer_type() { - return (CPPPointerType *)NULL; + return nullptr; } /** @@ -220,7 +220,7 @@ as_pointer_type() { */ CPPReferenceType *CPPDeclaration:: as_reference_type() { - return (CPPReferenceType *)NULL; + return nullptr; } /** @@ -228,7 +228,7 @@ as_reference_type() { */ CPPArrayType *CPPDeclaration:: as_array_type() { - return (CPPArrayType *)NULL; + return nullptr; } /** @@ -236,7 +236,7 @@ as_array_type() { */ CPPConstType *CPPDeclaration:: as_const_type() { - return (CPPConstType *)NULL; + return nullptr; } /** @@ -244,7 +244,7 @@ as_const_type() { */ CPPFunctionType *CPPDeclaration:: as_function_type() { - return (CPPFunctionType *)NULL; + return nullptr; } /** @@ -252,7 +252,7 @@ as_function_type() { */ CPPFunctionGroup *CPPDeclaration:: as_function_group() { - return (CPPFunctionGroup *)NULL; + return nullptr; } /** @@ -260,7 +260,7 @@ as_function_group() { */ CPPExtensionType *CPPDeclaration:: as_extension_type() { - return (CPPExtensionType *)NULL; + return nullptr; } /** @@ -268,7 +268,7 @@ as_extension_type() { */ CPPStructType *CPPDeclaration:: as_struct_type() { - return (CPPStructType *)NULL; + return nullptr; } /** @@ -276,7 +276,7 @@ as_struct_type() { */ CPPEnumType *CPPDeclaration:: as_enum_type() { - return (CPPEnumType *)NULL; + return nullptr; } /** @@ -284,7 +284,7 @@ as_enum_type() { */ CPPTBDType *CPPDeclaration:: as_tbd_type() { - return (CPPTBDType *)NULL; + return nullptr; } /** @@ -292,7 +292,7 @@ as_tbd_type() { */ CPPTypeProxy *CPPDeclaration:: as_type_proxy() { - return (CPPTypeProxy *)NULL; + return nullptr; } /** @@ -300,7 +300,7 @@ as_type_proxy() { */ CPPMakeProperty *CPPDeclaration:: as_make_property() { - return (CPPMakeProperty *)NULL; + return nullptr; } /** @@ -308,7 +308,7 @@ as_make_property() { */ CPPMakeSeq *CPPDeclaration:: as_make_seq() { - return (CPPMakeSeq *)NULL; + return nullptr; } /** @@ -316,7 +316,7 @@ as_make_seq() { */ CPPClosureType *CPPDeclaration:: as_closure_type() { - return (CPPClosureType *)NULL; + return nullptr; } /** @@ -338,18 +338,18 @@ is_less(const CPPDeclaration *other) const { } -ostream & -operator << (ostream &out, const CPPDeclaration::SubstDecl &subst) { +std::ostream & +operator << (std::ostream &out, const CPPDeclaration::SubstDecl &subst) { CPPDeclaration::SubstDecl::const_iterator it; for (it = subst.begin(); it != subst.end(); ++it) { out << " "; - if (it->first == NULL) { + if (it->first == nullptr) { out << "(null)"; } else { out << *(it->first); } out << " -> "; - if (it->second == NULL) { + if (it->second == nullptr) { out << "(null)"; } else { out << *(it->second); diff --git a/dtool/src/cppparser/cppDeclaration.h b/dtool/src/cppparser/cppDeclaration.h index 8acaf6e50c..967dc6b6ec 100644 --- a/dtool/src/cppparser/cppDeclaration.h +++ b/dtool/src/cppparser/cppDeclaration.h @@ -25,8 +25,6 @@ #include #include -using namespace std; - class CPPInstance; class CPPTemplateParameterList; class CPPTypedefType; @@ -105,17 +103,17 @@ public: virtual CPPDeclaration * instantiate(const CPPTemplateParameterList *actual_params, CPPScope *current_scope, CPPScope *global_scope, - CPPPreprocessor *error_sink = NULL) const; + CPPPreprocessor *error_sink = nullptr) const; - typedef map SubstDecl; + typedef std::map SubstDecl; virtual CPPDeclaration *substitute_decl(SubstDecl &subst, CPPScope *current_scope, CPPScope *global_scope); - typedef set Instantiations; + typedef std::set Instantiations; Instantiations _instantiations; - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const=0; virtual SubType get_subtype() const=0; @@ -224,13 +222,13 @@ protected: virtual bool is_less(const CPPDeclaration *other) const; }; -inline ostream & -operator << (ostream &out, const CPPDeclaration &decl) { - decl.output(out, 0, (CPPScope *)NULL, false); +inline std::ostream & +operator << (std::ostream &out, const CPPDeclaration &decl) { + decl.output(out, 0, nullptr, false); return out; } -ostream & -operator << (ostream &out, const CPPDeclaration::SubstDecl &decl); +std::ostream & +operator << (std::ostream &out, const CPPDeclaration::SubstDecl &decl); #endif diff --git a/dtool/src/cppparser/cppEnumType.cxx b/dtool/src/cppparser/cppEnumType.cxx index fbc3a7df53..11fcd5da3e 100644 --- a/dtool/src/cppparser/cppEnumType.cxx +++ b/dtool/src/cppparser/cppEnumType.cxx @@ -29,12 +29,12 @@ CPPEnumType(Type type, CPPIdentifier *ident, CPPScope *current_scope, CPPScope *scope, const CPPFile &file) : CPPExtensionType(type, ident, current_scope, file), _scope(scope), - _element_type(NULL), - _last_value(NULL) + _element_type(nullptr), + _last_value(nullptr) { _parent_scope = (type == T_enum) ? current_scope : scope; - if (ident != NULL) { + if (ident != nullptr) { ident->_native_scope = current_scope; } } @@ -48,10 +48,10 @@ CPPEnumType(Type type, CPPIdentifier *ident, CPPType *element_type, CPPExtensionType(type, ident, current_scope, file), _scope(scope), _element_type(element_type), - _last_value(NULL) + _last_value(nullptr) { _parent_scope = (type == T_enum) ? current_scope : scope; - if (ident != NULL) { + if (ident != nullptr) { ident->_native_scope = current_scope; } } @@ -69,11 +69,11 @@ is_scoped() const { */ CPPType *CPPEnumType:: get_underlying_type() { - if (_element_type == NULL) { + if (_element_type == nullptr) { // This enum is untyped. Use a suitable default, ie. 'int'. In the // future, we might want to check whether it fits in an int. - static CPPType *default_element_type = NULL; - if (default_element_type == NULL) { + static CPPType *default_element_type = nullptr; + if (default_element_type == nullptr) { default_element_type = CPPType::new_type(new CPPConstType(new CPPSimpleType(CPPSimpleType::T_int, 0))); } @@ -89,7 +89,7 @@ get_underlying_type() { * */ CPPInstance *CPPEnumType:: -add_element(const string &name, CPPExpression *value, CPPPreprocessor *preprocessor, const cppyyltype &pos) { +add_element(const std::string &name, CPPExpression *value, CPPPreprocessor *preprocessor, const cppyyltype &pos) { CPPIdentifier *ident = new CPPIdentifier(name); ident->_native_scope = _parent_scope; @@ -104,8 +104,8 @@ add_element(const string &name, CPPExpression *value, CPPPreprocessor *preproces inst->_storage_class |= CPPInstance::SC_constexpr; _elements.push_back(inst); - if (value == (CPPExpression *)NULL) { - if (_last_value == (CPPExpression *)NULL) { + if (value == nullptr) { + if (_last_value == nullptr) { // This is the first value, and should therefore be 0. static CPPExpression *const zero = new CPPExpression(0); value = zero; @@ -123,17 +123,17 @@ add_element(const string &name, CPPExpression *value, CPPPreprocessor *preproces inst->_initializer = value; _last_value = value; - if (preprocessor != (CPPPreprocessor *)NULL) { + if (preprocessor != nullptr) { // Same-line comment? CPPCommentBlock *comment = preprocessor->get_comment_on(pos.first_line, pos.file); - if (comment == (CPPCommentBlock *)NULL) { + if (comment == nullptr) { // Nope. Check for a comment before this line. comment = preprocessor->get_comment_before(pos.first_line, pos.file); - if (comment != NULL) { + if (comment != nullptr) { // This is a bit of a hack, but it prevents us from picking up a same- // line comment from the previous line. if (comment->_line_number != pos.first_line - 1 || @@ -148,12 +148,12 @@ add_element(const string &name, CPPExpression *value, CPPPreprocessor *preproces } // Add the value to the enum scope (as per C++11), assuming it's not anonymous. - if (_scope != NULL) { + if (_scope != nullptr) { _scope->add_enum_value(inst); } // Now add it to the containing scope as well if it's not an "enum class". - if (!is_scoped() && _parent_scope != NULL) { + if (!is_scoped() && _parent_scope != nullptr) { _parent_scope->add_enum_value(inst); } @@ -179,11 +179,11 @@ is_fully_specified() const { return false; } - if (_ident != NULL && !_ident->is_fully_specified()) { + if (_ident != nullptr && !_ident->is_fully_specified()) { return false; } - if (_element_type != NULL && !_element_type->is_fully_specified()) { + if (_element_type != nullptr && !_element_type->is_fully_specified()) { return false; } @@ -210,12 +210,12 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, CPPEnumType *rep = new CPPEnumType(*this); - if (_ident != NULL) { + if (_ident != nullptr) { rep->_ident = _ident->substitute_decl(subst, current_scope, global_scope); } - if (_element_type != NULL) { + if (_element_type != nullptr) { rep->_element_type = _element_type->substitute_decl(subst, current_scope, global_scope) ->as_type(); @@ -262,8 +262,8 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, * */ void CPPEnumType:: -output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { - if (!complete && _ident != NULL) { +output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const { + if (!complete && _ident != nullptr) { // If we have a name, use it. if (cppparser_output_class_keyword) { out << _type << " "; @@ -272,10 +272,10 @@ output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { } else { out << _type; - if (_ident != NULL) { + if (_ident != nullptr) { out << " " << _ident->get_local_name(scope); } - if (_element_type != NULL) { + if (_element_type != nullptr) { out << " : " << _element_type->get_local_name(scope); } @@ -283,7 +283,7 @@ output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { Elements::const_iterator ei; for (ei = _elements.begin(); ei != _elements.end(); ++ei) { indent(out, indent_level + 2) << (*ei)->get_local_name(); - if ((*ei)->_initializer != NULL) { + if ((*ei)->_initializer != nullptr) { out << " = " << *(*ei)->_initializer; } out << ",\n"; diff --git a/dtool/src/cppparser/cppEnumType.h b/dtool/src/cppparser/cppEnumType.h index a218feead4..678e1985c3 100644 --- a/dtool/src/cppparser/cppEnumType.h +++ b/dtool/src/cppparser/cppEnumType.h @@ -39,7 +39,7 @@ public: bool is_scoped() const; CPPType *get_underlying_type(); - CPPInstance *add_element(const string &name, CPPExpression *value, + CPPInstance *add_element(const std::string &name, CPPExpression *value, CPPPreprocessor *preprocessor, const cppyyltype &pos); virtual bool is_incomplete() const; @@ -49,7 +49,7 @@ public: CPPScope *current_scope, CPPScope *global_scope); - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; virtual SubType get_subtype() const; @@ -59,7 +59,7 @@ public: CPPScope *_scope; CPPType *_element_type; - typedef vector Elements; + typedef std::vector Elements; Elements _elements; CPPExpression *_last_value; }; diff --git a/dtool/src/cppparser/cppExpression.cxx b/dtool/src/cppparser/cppExpression.cxx index 139ac72d1b..2b2cc0bd50 100644 --- a/dtool/src/cppparser/cppExpression.cxx +++ b/dtool/src/cppparser/cppExpression.cxx @@ -31,6 +31,9 @@ #include +using std::cerr; +using std::string; + /** * */ @@ -131,7 +134,7 @@ as_pointer() const { default: cerr << "Invalid type\n"; assert(false); - return (void *)NULL; + return nullptr; } } @@ -148,7 +151,7 @@ as_boolean() const { return (_u._real != 0.0); case RT_pointer: - return (_u._pointer != NULL); + return (_u._pointer != nullptr); default: cerr << "Invalid type\n"; @@ -161,7 +164,7 @@ as_boolean() const { * */ void CPPExpression::Result:: -output(ostream &out) const { +output(std::ostream &out) const { switch (_type) { case RT_integer: out << _u._integer; @@ -250,15 +253,15 @@ CPPExpression(CPPIdentifier *ident, CPPScope *current_scope, CPPDeclaration *decl = ident->find_symbol(current_scope, global_scope); - if (decl != NULL) { + if (decl != nullptr) { CPPInstance *inst = decl->as_instance(); - if (inst != NULL) { + if (inst != nullptr) { _type = T_variable; _u._variable = inst; return; } CPPFunctionGroup *fgroup = decl->as_function_group(); - if (fgroup != NULL) { + if (fgroup != nullptr) { _type = T_function; _u._fgroup = fgroup; return; @@ -280,8 +283,8 @@ CPPExpression(int unary_operator, CPPExpression *op1) : _type = T_unary_operation; _u._op._operator = unary_operator; _u._op._op1 = op1; - _u._op._op2 = NULL; - _u._op._op3 = NULL; + _u._op._op2 = nullptr; + _u._op._op3 = nullptr; } /** @@ -295,7 +298,7 @@ CPPExpression(int binary_operator, CPPExpression *op1, CPPExpression *op2) : _u._op._operator = binary_operator; _u._op._op1 = op1; _u._op._op2 = op2; - _u._op._op3 = NULL; + _u._op._op3 = nullptr; } /** @@ -332,11 +335,11 @@ typecast_op(CPPType *type, CPPExpression *op1, Type cast_type) { CPPExpression CPPExpression:: construct_op(CPPType *type, CPPExpression *op1) { CPPExpression expr(0); - if (op1 == NULL) { + if (op1 == nullptr) { // A default constructor call--no parameters. expr._type = T_default_construct; expr._u._typecast._to = type; - expr._u._typecast._op1 = NULL; + expr._u._typecast._op1 = nullptr; } else { // A normal constructor call, with parameters. expr._type = T_construct; @@ -352,7 +355,7 @@ construct_op(CPPType *type, CPPExpression *op1) { CPPExpression CPPExpression:: aggregate_init_op(CPPType *type, CPPExpression *op1) { CPPExpression expr(0); - if (op1 == NULL) { + if (op1 == nullptr) { expr._type = T_empty_aggregate_init; } else { expr._type = T_aggregate_init; @@ -368,11 +371,11 @@ aggregate_init_op(CPPType *type, CPPExpression *op1) { CPPExpression CPPExpression:: new_op(CPPType *type, CPPExpression *op1) { CPPExpression expr(0); - if (op1 == NULL) { + if (op1 == nullptr) { // A default new operation--no parameters. expr._type = T_default_new; expr._u._typecast._to = type; - expr._u._typecast._op1 = NULL; + expr._u._typecast._op1 = nullptr; } else { // A normal new operation, with parameters. expr._type = T_new; @@ -427,7 +430,7 @@ sizeof_func(CPPType *type) { CPPExpression expr(0); expr._type = T_sizeof; expr._u._typecast._to = type; - expr._u._typecast._op1 = NULL; + expr._u._typecast._op1 = nullptr; return expr; } @@ -450,7 +453,7 @@ alignof_func(CPPType *type) { CPPExpression expr(0); expr._type = T_alignof; expr._u._typecast._to = type; - expr._u._typecast._op1 = NULL; + expr._u._typecast._op1 = nullptr; return expr; } @@ -509,7 +512,7 @@ raw_literal(const string &raw, CPPInstance *lit_op) { CPPExpression expr(0); expr._type = T_raw_literal; expr._str = raw; - expr._u._literal._value = (CPPExpression *)NULL; + expr._u._literal._value = nullptr; expr._u._literal._operator = lit_op; return expr; } @@ -553,7 +556,7 @@ evaluate() const { switch (_type) { case T_nullptr: - return Result((void *)0); + return Result(nullptr); case T_boolean: return Result((int)_u._boolean); @@ -572,15 +575,15 @@ evaluate() const { return Result(); case T_variable: - if (_u._variable->_type != NULL && - _u._variable->_initializer != NULL) { + if (_u._variable->_type != nullptr && + _u._variable->_initializer != nullptr) { // A constexpr variable, which is treated as const. if (_u._variable->_storage_class & CPPInstance::SC_constexpr) { return _u._variable->_initializer->evaluate(); } // A const variable. Fetch its assigned value. CPPConstType *const_type = _u._variable->_type->as_const_type(); - if (const_type != NULL) { + if (const_type != nullptr) { return _u._variable->_initializer->evaluate(); } } @@ -597,11 +600,11 @@ evaluate() const { case T_dynamic_cast: case T_const_cast: case T_reinterpret_cast: - assert(_u._typecast._op1 != NULL); + assert(_u._typecast._op1 != nullptr); r1 = _u._typecast._op1->evaluate(); if (r1._type != RT_error) { CPPSimpleType *stype = _u._typecast._to->as_simple_type(); - if (stype != NULL) { + if (stype != nullptr) { if (stype->_type == CPPSimpleType::T_bool) { return Result(r1.as_boolean()); @@ -630,18 +633,18 @@ evaluate() const { return Result(); case T_alignof: - if (_u._typecast._to != NULL) { + if (_u._typecast._to != nullptr) { // Check if the type is defined with an alignas. TODO: this should // probably be moved to a virtual getter on CPPType. CPPExtensionType *etype = _u._typecast._to->as_extension_type(); - if (etype != NULL && etype->_alignment != NULL) { + if (etype != nullptr && etype->_alignment != nullptr) { return etype->_alignment->evaluate(); } } return Result(); case T_binary_operation: - assert(_u._op._op2 != NULL); + assert(_u._op._op2 != nullptr); r2 = _u._op._op2->evaluate(); // The operators && and || are special cases: these are shirt-circuiting @@ -666,7 +669,7 @@ evaluate() const { // Fall through case T_unary_operation: - assert(_u._op._op1 != NULL); + assert(_u._op._op1 != nullptr); r1 = _u._op._op1->evaluate(); if (r1._type == RT_error) { // Here's one more special case: if the first operand is invalid, it @@ -854,39 +857,39 @@ evaluate() const { case KW_HAS_VIRTUAL_DESTRUCTOR: { CPPStructType *struct_type = _u._type_trait._type->as_struct_type(); - return Result(struct_type != NULL && struct_type->has_virtual_destructor()); + return Result(struct_type != nullptr && struct_type->has_virtual_destructor()); } case KW_IS_ABSTRACT: { CPPStructType *struct_type = _u._type_trait._type->as_struct_type(); - return Result(struct_type != NULL && struct_type->is_abstract()); + return Result(struct_type != nullptr && struct_type->is_abstract()); } case KW_IS_BASE_OF: { CPPStructType *struct_type1 = _u._type_trait._type->as_struct_type(); CPPStructType *struct_type2 = _u._type_trait._arg->as_struct_type(); - return Result(struct_type1 != NULL && struct_type2 != NULL && struct_type1->is_base_of(struct_type2)); + return Result(struct_type1 != nullptr && struct_type2 != nullptr && struct_type1->is_base_of(struct_type2)); } case KW_IS_CLASS: { CPPExtensionType *ext_type = _u._type_trait._type->as_extension_type(); - return Result(ext_type != NULL && ( + return Result(ext_type != nullptr && ( ext_type->_type == CPPExtensionType::T_class || ext_type->_type == CPPExtensionType::T_struct)); } case KW_IS_CONSTRUCTIBLE: - if (_u._type_trait._arg == NULL) { + if (_u._type_trait._arg == nullptr) { return Result(_u._type_trait._type->is_default_constructible()); } else { return Result(_u._type_trait._type->is_constructible(_u._type_trait._arg)); } case KW_IS_CONVERTIBLE_TO: - assert(_u._type_trait._arg != NULL); + assert(_u._type_trait._arg != nullptr); return Result(_u._type_trait._type->is_convertible_to(_u._type_trait._arg)); case KW_IS_DESTRUCTIBLE: @@ -895,7 +898,7 @@ evaluate() const { case KW_IS_EMPTY: { CPPStructType *struct_type = _u._type_trait._type->as_struct_type(); - return Result(struct_type != NULL && struct_type->is_empty()); + return Result(struct_type != nullptr && struct_type->is_empty()); } case KW_IS_ENUM: @@ -904,7 +907,7 @@ evaluate() const { case KW_IS_FINAL: { CPPStructType *struct_type = _u._type_trait._type->as_struct_type(); - return Result(struct_type != NULL && struct_type->is_final()); + return Result(struct_type != nullptr && struct_type->is_final()); } case KW_IS_FUNDAMENTAL: @@ -917,7 +920,7 @@ evaluate() const { case KW_IS_POLYMORPHIC: { CPPStructType *struct_type = _u._type_trait._type->as_struct_type(); - return Result(struct_type != NULL && struct_type->is_polymorphic()); + return Result(struct_type != nullptr && struct_type->is_polymorphic()); } case KW_IS_STANDARD_LAYOUT: @@ -929,7 +932,7 @@ evaluate() const { case KW_IS_UNION: { CPPExtensionType *ext_type = _u._type_trait._type->as_extension_type(); - return Result(ext_type != NULL && + return Result(ext_type != nullptr && ext_type->_type == CPPExtensionType::T_union); } @@ -952,8 +955,8 @@ evaluate() const { */ CPPType *CPPExpression:: determine_type() const { - CPPType *t1 = (CPPType *)NULL; - CPPType *t2 = (CPPType *)NULL; + CPPType *t1 = nullptr; + CPPType *t2 = nullptr; static CPPType *nullptr_type = CPPType::new_type(new CPPSimpleType(CPPSimpleType::T_nullptr)); @@ -1028,16 +1031,16 @@ determine_type() const { return _u._variable->_type; case T_function: - if (_u._fgroup->get_return_type() == (CPPType *)NULL) { + if (_u._fgroup->get_return_type() == nullptr) { // There are multiple functions by this name that have different return // types. We could attempt to differentiate them based on the parameter // list, but that's a lot of work. Let's just give up. - return (CPPType *)NULL; + return nullptr; } return _u._fgroup->_instances.front()->_type; case T_unknown_ident: - return (CPPType *)NULL; + return nullptr; case T_typecast: case T_static_cast: @@ -1064,12 +1067,12 @@ determine_type() const { case T_binary_operation: case T_trinary_operation: - assert(_u._op._op2 != NULL); + assert(_u._op._op2 != nullptr); t2 = _u._op._op2->determine_type(); // Fall through case T_unary_operation: - assert(_u._op._op1 != NULL); + assert(_u._op._op1 != nullptr); t1 = _u._op._op1->determine_type(); switch (_u._op._operator) { @@ -1081,7 +1084,7 @@ determine_type() const { case UNARY_MINUS: case UNARY_PLUS: - if (t1 != NULL) { + if (t1 != nullptr) { switch (t1->get_subtype()) { case CPPDeclaration::ST_array: // Decay into pointer. @@ -1107,11 +1110,11 @@ determine_type() const { return t1; } } - return NULL; + return nullptr; case UNARY_STAR: case '[': // Array element reference - if (t1 != NULL) { + if (t1 != nullptr) { if (t1->as_pointer_type()) { return t1->as_pointer_type()->_pointing_at; } @@ -1119,7 +1122,7 @@ determine_type() const { return t1->as_array_type()->_element_type; } } - return NULL; + return nullptr; case UNARY_REF: return t1; @@ -1128,9 +1131,9 @@ determine_type() const { case '/': case '+': case '-': - if (t1 == NULL) { + if (t1 == nullptr) { return t2; - } else if (t2 == NULL) { + } else if (t2 == nullptr) { return t1; } else if (t1->as_pointer_type()) { if (t2->as_pointer_type()) { @@ -1162,25 +1165,25 @@ determine_type() const { case '.': case POINTSAT: - return NULL; + return nullptr; case 'f': // Function evaluation - if (t1 != NULL) { + if (t1 != nullptr) { // Easy case, function with only a single overload. CPPFunctionType *ftype = t1->as_function_type(); - if (ftype != (CPPFunctionType *)NULL) { + if (ftype != nullptr) { return ftype->_return_type; } } else if (_u._op._op1->_type == T_function) { CPPFunctionGroup *fgroup = _u._op._op1->_u._fgroup; - if (_u._op._op2 == NULL) { + if (_u._op._op2 == nullptr) { // If we are passing no args, look for an overload that has takes no // args. for (auto it = fgroup->_instances.begin(); it != fgroup->_instances.end(); ++it) { CPPInstance *inst = *it; - if (inst != NULL && inst->_type != NULL) { + if (inst != nullptr && inst->_type != nullptr) { CPPFunctionType *type = inst->_type->as_function_type(); - if (type != NULL && type->accepts_num_parameters(0)) { + if (type != nullptr && type->accepts_num_parameters(0)) { return type->_return_type; } } @@ -1189,7 +1192,7 @@ determine_type() const { //TODO } } - return NULL; + return nullptr; case ',': return t2; @@ -1201,15 +1204,15 @@ determine_type() const { case T_literal: case T_raw_literal: - if (_u._literal._operator != NULL) { + if (_u._literal._operator != nullptr) { CPPType *type = _u._literal._operator->_type; CPPFunctionType *ftype = type->as_function_type(); - if (ftype != (CPPFunctionType *)NULL) { + if (ftype != nullptr) { return ftype->_return_type; } } - return NULL; + return nullptr; case T_typeid_type: case T_typeid_expr: @@ -1226,7 +1229,7 @@ determine_type() const { abort(); } - return NULL; // Compiler kludge; can't get here. + return nullptr; // Compiler kludge; can't get here. } /** @@ -1361,9 +1364,9 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, // See if we can define it now. decl = rep->_u._ident->find_symbol(current_scope, global_scope, subst); - if (decl != NULL) { + if (decl != nullptr) { CPPInstance *inst = decl->as_instance(); - if (inst != NULL) { + if (inst != nullptr) { rep->_type = T_variable; rep->_u._variable = inst; any_changed = true; @@ -1384,7 +1387,7 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, break; } CPPFunctionGroup *fgroup = decl->as_function_group(); - if (fgroup != NULL) { + if (fgroup != nullptr) { rep->_type = T_function; rep->_u._fgroup = fgroup; any_changed = true; @@ -1481,13 +1484,13 @@ bool CPPExpression:: is_tbd() const { switch (_type) { case T_variable: - if (_u._variable->_type != NULL && - _u._variable->_initializer != NULL) { + if (_u._variable->_type != nullptr && + _u._variable->_initializer != nullptr) { if (_u._variable->_storage_class & CPPInstance::SC_constexpr) { return false; } CPPConstType *const_type = _u._variable->_type->as_const_type(); - if (const_type != NULL) { + if (const_type != nullptr) { return false; } } @@ -1551,7 +1554,7 @@ is_tbd() const { * */ void CPPExpression:: -output(ostream &out, int indent_level, CPPScope *scope, bool) const { +output(std::ostream &out, int indent_level, CPPScope *scope, bool) const { switch (_type) { case T_nullptr: out << "nullptr"; @@ -1630,8 +1633,8 @@ output(ostream &out, int indent_level, CPPScope *scope, bool) const { if (isprint(*si)) { out << *si; } else { - out << '\\' << oct << setw(3) << setfill('0') << (int)(*si) - << dec << setw(0); + out << '\\' << std::oct << std::setw(3) << std::setfill('0') << (int)(*si) + << std::dec << std::setw(0); } } } @@ -1643,13 +1646,13 @@ output(ostream &out, int indent_level, CPPScope *scope, bool) const { // We can just refer to the variable by name, except if it's a private // constant, in which case we have to compute the value, since we may have // to use it in generated code. - if (_u._variable->_type != NULL && - _u._variable->_initializer != NULL && + if (_u._variable->_type != nullptr && + _u._variable->_initializer != nullptr && _u._variable->_vis > V_public) { // A constexpr or const variable. Fetch its assigned value. CPPConstType *const_type = _u._variable->_type->as_const_type(); if ((_u._variable->_storage_class & CPPInstance::SC_constexpr) != 0 || - const_type != NULL) { + const_type != nullptr) { _u._variable->_initializer->output(out, indent_level, scope, false); break; } @@ -1659,7 +1662,7 @@ output(ostream &out, int indent_level, CPPScope *scope, bool) const { case T_function: // Pick any instance; they all have the same name anyway. - if (!_u._fgroup->_instances.empty() && _u._fgroup->_instances[0]->_ident != NULL) { + if (!_u._fgroup->_instances.empty() && _u._fgroup->_instances[0]->_ident != nullptr) { _u._fgroup->_instances[0]->_ident->output(out, scope); } else { out << _u._fgroup->_name; @@ -1936,7 +1939,7 @@ output(ostream &out, int indent_level, CPPScope *scope, bool) const { case T_literal: _u._literal._value->output(out, indent_level, scope, false); - if (_u._literal._operator != NULL) { + if (_u._literal._operator != nullptr) { string name = _u._literal._operator->get_simple_name(); assert(name.substr(0, 12) == "operator \"\" "); out << name.substr(12); @@ -1945,7 +1948,7 @@ output(ostream &out, int indent_level, CPPScope *scope, bool) const { case T_raw_literal: out << _str; - if (_u._literal._operator != NULL) { + if (_u._literal._operator != nullptr) { string name = _u._literal._operator->get_simple_name(); assert(name.substr(0, 12) == "operator \"\" "); out << name.substr(12); @@ -2064,9 +2067,9 @@ elevate_type(CPPType *t1, CPPType *t2) { CPPSimpleType *st1 = t1->as_simple_type(); CPPSimpleType *st2 = t2->as_simple_type(); - if (st1 == NULL || st2 == NULL) { + if (st1 == nullptr || st2 == nullptr) { // Nothing we can do about this. Who knows? - return NULL; + return nullptr; } if (st1->_type == st2->_type) { @@ -2113,7 +2116,7 @@ elevate_type(CPPType *t1, CPPType *t2) { bool CPPExpression:: is_equal(const CPPDeclaration *other) const { const CPPExpression *ot = ((CPPDeclaration *)other)->as_expression(); - assert(ot != NULL); + assert(ot != nullptr); if (_type != ot->_type) { return false; @@ -2213,7 +2216,7 @@ is_equal(const CPPDeclaration *other) const { bool CPPExpression:: is_less(const CPPDeclaration *other) const { const CPPExpression *ot = ((CPPDeclaration *)other)->as_expression(); - assert(ot != NULL); + assert(ot != nullptr); if (_type != ot->_type) { return (int)_type < (int)ot->_type; diff --git a/dtool/src/cppparser/cppExpression.h b/dtool/src/cppparser/cppExpression.h index 3178d4d178..4482727f53 100644 --- a/dtool/src/cppparser/cppExpression.h +++ b/dtool/src/cppparser/cppExpression.h @@ -73,10 +73,10 @@ public: CPPExpression(bool value); CPPExpression(unsigned long long value); CPPExpression(int value); - CPPExpression(const string &value); + CPPExpression(const std::string &value); CPPExpression(long double value); CPPExpression(CPPIdentifier *ident, CPPScope *current_scope, - CPPScope *global_scope, CPPPreprocessor *error_sink = NULL); + CPPScope *global_scope, CPPPreprocessor *error_sink = nullptr); CPPExpression(int unary_operator, CPPExpression *op1); CPPExpression(int binary_operator, CPPExpression *op1, CPPExpression *op2); CPPExpression(int trinary_operator, CPPExpression *op1, CPPExpression *op2, CPPExpression *op3); @@ -84,10 +84,10 @@ public: static CPPExpression typecast_op(CPPType *type, CPPExpression *op1, Type cast_type = T_typecast); static CPPExpression construct_op(CPPType *type, CPPExpression *op1); static CPPExpression aggregate_init_op(CPPType *type, CPPExpression *op1); - static CPPExpression new_op(CPPType *type, CPPExpression *op1 = NULL); + static CPPExpression new_op(CPPType *type, CPPExpression *op1 = nullptr); static CPPExpression typeid_op(CPPType *type, CPPType *std_type_info); static CPPExpression typeid_op(CPPExpression *op1, CPPType *std_type_info); - static CPPExpression type_trait(int trait, CPPType *type, CPPType *arg = NULL); + static CPPExpression type_trait(int trait, CPPType *type, CPPType *arg = nullptr); static CPPExpression sizeof_func(CPPType *type); static CPPExpression sizeof_ellipsis_func(CPPIdentifier *ident); static CPPExpression alignof_func(CPPType *type); @@ -96,7 +96,7 @@ public: static CPPExpression literal(unsigned long long value, CPPInstance *lit_op); static CPPExpression literal(long double value, CPPInstance *lit_op); static CPPExpression literal(CPPExpression *value, CPPInstance *lit_op); - static CPPExpression raw_literal(const string &raw, CPPInstance *lit_op); + static CPPExpression raw_literal(const std::string &raw, CPPInstance *lit_op); static const CPPExpression &get_nullptr(); static const CPPExpression &get_default(); @@ -120,7 +120,7 @@ public: double as_real() const; void *as_pointer() const; bool as_boolean() const; - void output(ostream &out) const; + void output(std::ostream &out) const; ResultType _type; union { @@ -140,14 +140,14 @@ public: CPPScope *current_scope, CPPScope *global_scope); - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; virtual SubType get_subtype() const; virtual CPPExpression *as_expression(); Type _type; - string _str; + std::string _str; union { bool _boolean; unsigned long long _integer; @@ -191,8 +191,8 @@ protected: virtual bool is_less(const CPPDeclaration *other) const; }; -inline ostream & -operator << (ostream &out, const CPPExpression::Result &result) { +inline std::ostream & +operator << (std::ostream &out, const CPPExpression::Result &result) { result.output(out); return out; } diff --git a/dtool/src/cppparser/cppExpressionParser.cxx b/dtool/src/cppparser/cppExpressionParser.cxx index 2ab7b30771..ef5785eb5a 100644 --- a/dtool/src/cppparser/cppExpressionParser.cxx +++ b/dtool/src/cppparser/cppExpressionParser.cxx @@ -22,7 +22,7 @@ CPPExpressionParser(CPPScope *current_scope, CPPScope *global_scope) : _current_scope(current_scope), _global_scope(global_scope) { - _expr = NULL; + _expr = nullptr; } /** @@ -36,9 +36,9 @@ CPPExpressionParser:: * */ bool CPPExpressionParser:: -parse_expr(const string &expr) { +parse_expr(const std::string &expr) { if (!init_const_expr(expr)) { - cerr << "Unable to parse expression\n"; + std::cerr << "Unable to parse expression\n"; return false; } @@ -51,9 +51,9 @@ parse_expr(const string &expr) { * */ bool CPPExpressionParser:: -parse_expr(const string &expr, const CPPPreprocessor &filepos) { +parse_expr(const std::string &expr, const CPPPreprocessor &filepos) { if (!init_const_expr(expr)) { - cerr << "Unable to parse expression\n"; + std::cerr << "Unable to parse expression\n"; return false; } @@ -68,8 +68,8 @@ parse_expr(const string &expr, const CPPPreprocessor &filepos) { * */ void CPPExpressionParser:: -output(ostream &out) const { - if (_expr == NULL) { +output(std::ostream &out) const { + if (_expr == nullptr) { out << "(null expr)"; } else { out << *_expr; diff --git a/dtool/src/cppparser/cppExpressionParser.h b/dtool/src/cppparser/cppExpressionParser.h index f9ef78dafc..9a2cdf67a4 100644 --- a/dtool/src/cppparser/cppExpressionParser.h +++ b/dtool/src/cppparser/cppExpressionParser.h @@ -29,18 +29,18 @@ public: CPPExpressionParser(CPPScope *current_scope, CPPScope *global_scope); ~CPPExpressionParser(); - bool parse_expr(const string &expr); - bool parse_expr(const string &expr, const CPPPreprocessor &filepos); + bool parse_expr(const std::string &expr); + bool parse_expr(const std::string &expr, const CPPPreprocessor &filepos); - void output(ostream &out) const; + void output(std::ostream &out) const; CPPScope *_current_scope; CPPScope *_global_scope; CPPExpression *_expr; }; -inline ostream & -operator << (ostream &out, const CPPExpressionParser &ep) { +inline std::ostream & +operator << (std::ostream &out, const CPPExpressionParser &ep) { ep.output(out); return out; } diff --git a/dtool/src/cppparser/cppExtensionType.cxx b/dtool/src/cppparser/cppExtensionType.cxx index eba135eb64..b7d23cb667 100644 --- a/dtool/src/cppparser/cppExtensionType.cxx +++ b/dtool/src/cppparser/cppExtensionType.cxx @@ -26,9 +26,9 @@ CPPExtensionType(CPPExtensionType::Type type, const CPPFile &file) : CPPType(file), _type(type), _ident(ident), - _alignment(NULL) + _alignment(nullptr) { - if (_ident != NULL) { + if (_ident != nullptr) { _ident->_native_scope = current_scope; } } @@ -36,9 +36,9 @@ CPPExtensionType(CPPExtensionType::Type type, /** * */ -string CPPExtensionType:: +std::string CPPExtensionType:: get_simple_name() const { - if (_ident == NULL) { + if (_ident == nullptr) { return ""; } return _ident->get_simple_name(); @@ -47,9 +47,9 @@ get_simple_name() const { /** * */ -string CPPExtensionType:: +std::string CPPExtensionType:: get_local_name(CPPScope *scope) const { - if (_ident == NULL) { + if (_ident == nullptr) { return ""; } return _ident->get_local_name(scope); @@ -58,9 +58,9 @@ get_local_name(CPPScope *scope) const { /** * */ -string CPPExtensionType:: +std::string CPPExtensionType:: get_fully_scoped_name() const { - if (_ident == NULL) { + if (_ident == nullptr) { return ""; } return _ident->get_fully_scoped_name(); @@ -81,7 +81,7 @@ is_incomplete() const { */ bool CPPExtensionType:: is_tbd() const { - if (_ident != (CPPIdentifier *)NULL) { + if (_ident != nullptr) { return _ident->is_tbd(); } return false; @@ -110,7 +110,7 @@ bool CPPExtensionType:: is_constructible(const CPPType *given_type) const { if (_type == T_enum || _type == T_enum_class || _type == T_enum_struct) { const CPPExtensionType *other = ((CPPType *)given_type)->remove_reference()->remove_const()->as_extension_type(); - return other != NULL && is_equal(other); + return other != nullptr && is_equal(other); } return false; } @@ -151,7 +151,7 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, } CPPExtensionType *rep = new CPPExtensionType(*this); - if (_ident != NULL) { + if (_ident != nullptr) { rep->_ident = _ident->substitute_decl(subst, current_scope, global_scope); } @@ -172,7 +172,7 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, */ CPPType *CPPExtensionType:: resolve_type(CPPScope *current_scope, CPPScope *global_scope) { - if (_ident == NULL) { + if (_ident == nullptr) { // We can't resolve anonymous types. But that's OK, since they can't be // forward declared anyway. return this; @@ -180,7 +180,7 @@ resolve_type(CPPScope *current_scope, CPPScope *global_scope) { // Maybe it has been defined by now. CPPType *type = _ident->find_type(current_scope, global_scope); - if (type != NULL) { + if (type != nullptr) { return type; } return this; @@ -195,7 +195,7 @@ resolve_type(CPPScope *current_scope, CPPScope *global_scope) { bool CPPExtensionType:: is_equivalent(const CPPType &other) const { const CPPExtensionType *ot = ((CPPType *)&other)->as_extension_type(); - if (ot == (CPPExtensionType *)NULL) { + if (ot == nullptr) { return CPPType::is_equivalent(other); } @@ -209,8 +209,8 @@ is_equivalent(const CPPType &other) const { * */ void CPPExtensionType:: -output(ostream &out, int, CPPScope *scope, bool complete) const { - if (_ident != NULL) { +output(std::ostream &out, int, CPPScope *scope, bool complete) const { + if (_ident != nullptr) { // If we have a name, use it. if (complete || cppparser_output_class_keyword) { out << _type << " "; @@ -242,8 +242,8 @@ as_extension_type() { return this; } -ostream & -operator << (ostream &out, CPPExtensionType::Type type) { +std::ostream & +operator << (std::ostream &out, CPPExtensionType::Type type) { switch (type) { case CPPExtensionType::T_enum: return out << "enum"; diff --git a/dtool/src/cppparser/cppExtensionType.h b/dtool/src/cppparser/cppExtensionType.h index dca9cf8cb3..b47c084c88 100644 --- a/dtool/src/cppparser/cppExtensionType.h +++ b/dtool/src/cppparser/cppExtensionType.h @@ -41,9 +41,9 @@ public: CPPExtensionType(Type type, CPPIdentifier *ident, CPPScope *current_scope, const CPPFile &file); - virtual string get_simple_name() const; - virtual string get_local_name(CPPScope *scope = NULL) const; - virtual string get_fully_scoped_name() const; + virtual std::string get_simple_name() const; + virtual std::string get_local_name(CPPScope *scope = nullptr) const; + virtual std::string get_fully_scoped_name() const; virtual bool is_incomplete() const; virtual bool is_tbd() const; @@ -64,7 +64,7 @@ public: virtual bool is_equivalent(const CPPType &other) const; - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; virtual SubType get_subtype() const; @@ -75,6 +75,6 @@ public: CPPExpression *_alignment; }; -ostream &operator << (ostream &out, CPPExtensionType::Type type); +std::ostream &operator << (std::ostream &out, CPPExtensionType::Type type); #endif diff --git a/dtool/src/cppparser/cppFile.cxx b/dtool/src/cppparser/cppFile.cxx index a42602013f..ce9a61ffc5 100644 --- a/dtool/src/cppparser/cppFile.cxx +++ b/dtool/src/cppparser/cppFile.cxx @@ -15,6 +15,8 @@ #include +using std::string; + /** * */ diff --git a/dtool/src/cppparser/cppFile.h b/dtool/src/cppparser/cppFile.h index f3644fce3c..cd049e780f 100644 --- a/dtool/src/cppparser/cppFile.h +++ b/dtool/src/cppparser/cppFile.h @@ -59,7 +59,7 @@ public: mutable bool _pragma_once; }; -inline ostream &operator << (ostream &out, const CPPFile &file) { +inline std::ostream &operator << (std::ostream &out, const CPPFile &file) { return out << file._filename; } diff --git a/dtool/src/cppparser/cppFunctionGroup.cxx b/dtool/src/cppparser/cppFunctionGroup.cxx index 2243d14708..7904663d08 100644 --- a/dtool/src/cppparser/cppFunctionGroup.cxx +++ b/dtool/src/cppparser/cppFunctionGroup.cxx @@ -20,7 +20,7 @@ * */ CPPFunctionGroup:: -CPPFunctionGroup(const string &name) : +CPPFunctionGroup(const std::string &name) : CPPDeclaration(CPPFile()), _name(name) { @@ -40,7 +40,7 @@ CPPFunctionGroup:: */ CPPType *CPPFunctionGroup:: get_return_type() const { - CPPType *return_type = NULL; + CPPType *return_type = nullptr; if (!_instances.empty()) { Instances::const_iterator ii = _instances.begin(); @@ -48,7 +48,7 @@ get_return_type() const { ++ii; while (ii != _instances.end()) { if ((*ii)->_type->as_function_type()->_return_type != return_type) { - return (CPPType *)NULL; + return nullptr; } ++ii; } @@ -61,7 +61,7 @@ get_return_type() const { * */ void CPPFunctionGroup:: -output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { +output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const { if (!_instances.empty()) { Instances::const_iterator ii = _instances.begin(); (*ii)->output(out, indent_level, scope, complete); diff --git a/dtool/src/cppparser/cppFunctionGroup.h b/dtool/src/cppparser/cppFunctionGroup.h index c33eee3907..3fced8f4ab 100644 --- a/dtool/src/cppparser/cppFunctionGroup.h +++ b/dtool/src/cppparser/cppFunctionGroup.h @@ -28,20 +28,20 @@ class CPPInstance; */ class CPPFunctionGroup : public CPPDeclaration { public: - CPPFunctionGroup(const string &name); + CPPFunctionGroup(const std::string &name); ~CPPFunctionGroup(); CPPType *get_return_type() const; - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; virtual SubType get_subtype() const; virtual CPPFunctionGroup *as_function_group(); - typedef vector Instances; + typedef std::vector Instances; Instances _instances; - string _name; + std::string _name; }; #endif diff --git a/dtool/src/cppparser/cppFunctionType.cxx b/dtool/src/cppparser/cppFunctionType.cxx index 38eb3d98ba..27699d711b 100644 --- a/dtool/src/cppparser/cppFunctionType.cxx +++ b/dtool/src/cppparser/cppFunctionType.cxx @@ -16,6 +16,10 @@ #include "cppSimpleType.h" #include "cppInstance.h" +using std::ostream; +using std::ostringstream; +using std::string; + /** * */ @@ -27,16 +31,16 @@ CPPFunctionType(CPPType *return_type, CPPParameterList *parameters, _parameters(parameters), _flags(flags) { - _class_owner = NULL; + _class_owner = nullptr; // If the parameter list contains just the token "void", it means no // parameters. - if (_parameters != NULL && + if (_parameters != nullptr && _parameters->_parameters.size() == 1 && - _parameters->_parameters.front()->_type->as_simple_type() != NULL && + _parameters->_parameters.front()->_type->as_simple_type() != nullptr && _parameters->_parameters.front()->_type->as_simple_type()->_type == CPPSimpleType::T_void && - _parameters->_parameters.front()->_ident == NULL) { + _parameters->_parameters.front()->_ident == nullptr) { _parameters->_parameters.clear(); } } @@ -71,19 +75,21 @@ operator = (const CPPFunctionType ©) { */ bool CPPFunctionType:: accepts_num_parameters(int num_parameters) { - if (_parameters == NULL) { + assert(num_parameters >= 0); + if (_parameters == nullptr) { return (num_parameters == 0); } + size_t actual_num_parameters = _parameters->_parameters.size(); // If we passed too many parameters, it must have an ellipsis. - if (num_parameters > actual_num_parameters) { + if ((size_t)num_parameters > actual_num_parameters) { return _parameters->_includes_ellipsis; } // Make sure all superfluous parameters have a default value. - for (size_t i = num_parameters; i < actual_num_parameters; ++i) { + for (size_t i = (size_t)num_parameters; i < actual_num_parameters; ++i) { CPPInstance *param = _parameters->_parameters[i]; - if (param->_initializer == NULL) { + if (param->_initializer == nullptr) { return false; } } @@ -115,13 +121,13 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, } CPPFunctionType *rep = new CPPFunctionType(*this); - if (_return_type != NULL) { + if (_return_type != nullptr) { rep->_return_type = _return_type->substitute_decl(subst, current_scope, global_scope) ->as_type(); } - if (_parameters != NULL) { + if (_parameters != nullptr) { rep->_parameters = _parameters->substitute_decl(subst, current_scope, global_scope); } @@ -146,8 +152,8 @@ CPPType *CPPFunctionType:: resolve_type(CPPScope *current_scope, CPPScope *global_scope) { CPPType *rtype = _return_type->resolve_type(current_scope, global_scope); CPPParameterList *params; - if (_parameters == NULL) { - params = NULL; + if (_parameters == nullptr) { + params = nullptr; } else { params = _parameters->resolve_type(current_scope, global_scope); } @@ -171,7 +177,7 @@ is_tbd() const { if (_return_type->is_tbd()) { return true; } - return _parameters == NULL || _parameters->is_tbd(); + return _parameters == nullptr || _parameters->is_tbd(); } /** @@ -326,7 +332,7 @@ get_num_default_parameters() const { // The trick is just to count, beginning from the end and working towards // the front, the number of parameters that have some initializer. - if (_parameters == NULL) { + if (_parameters == nullptr) { return 0; } @@ -334,7 +340,7 @@ get_num_default_parameters() const { CPPParameterList::Parameters::const_reverse_iterator pi; int count = 0; for (pi = params.rbegin(); - pi != params.rend() && (*pi)->_initializer != (CPPExpression *)NULL; + pi != params.rend() && (*pi)->_initializer != nullptr; ++pi) { count++; } @@ -390,7 +396,7 @@ match_virtual_override(const CPPFunctionType &other) const { bool CPPFunctionType:: is_equal(const CPPDeclaration *other) const { const CPPFunctionType *ot = ((CPPDeclaration *)other)->as_function_type(); - assert(ot != NULL); + assert(ot != nullptr); if (_return_type != ot->_return_type) { return false; @@ -401,7 +407,7 @@ is_equal(const CPPDeclaration *other) const { if (_parameters == ot->_parameters) { return true; } - if (_parameters == NULL || ot->_parameters == NULL || + if (_parameters == nullptr || ot->_parameters == nullptr || *_parameters != *ot->_parameters) { return false; } @@ -416,7 +422,7 @@ is_equal(const CPPDeclaration *other) const { bool CPPFunctionType:: is_less(const CPPDeclaration *other) const { const CPPFunctionType *ot = ((CPPDeclaration *)other)->as_function_type(); - assert(ot != NULL); + assert(ot != nullptr); if (_return_type != ot->_return_type) { return _return_type < ot->_return_type; @@ -427,7 +433,7 @@ is_less(const CPPDeclaration *other) const { if (_parameters == ot->_parameters) { return 0; } - if (_parameters == NULL || ot->_parameters == NULL) { + if (_parameters == nullptr || ot->_parameters == nullptr) { return _parameters < ot->_parameters; } return *_parameters < *ot->_parameters; diff --git a/dtool/src/cppparser/cppFunctionType.h b/dtool/src/cppparser/cppFunctionType.h index b6bdff7ac6..83fc3ababd 100644 --- a/dtool/src/cppparser/cppFunctionType.h +++ b/dtool/src/cppparser/cppFunctionType.h @@ -69,18 +69,18 @@ public: virtual bool is_tbd() const; virtual bool is_trivial() const; - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; - void output(ostream &out, int indent_level, CPPScope *scope, + void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete, int num_default_parameters) const; - virtual void output_instance(ostream &out, int indent_level, + virtual void output_instance(std::ostream &out, int indent_level, CPPScope *scope, - bool complete, const string &prename, - const string &name) const; - void output_instance(ostream &out, int indent_level, + bool complete, const std::string &prename, + const std::string &name) const; + void output_instance(std::ostream &out, int indent_level, CPPScope *scope, - bool complete, const string &prename, - const string &name, + bool complete, const std::string &prename, + const std::string &name, int num_default_parameters) const; int get_num_default_parameters() const; diff --git a/dtool/src/cppparser/cppGlobals.cxx b/dtool/src/cppparser/cppGlobals.cxx index a435227203..f537ce8c42 100644 --- a/dtool/src/cppparser/cppGlobals.cxx +++ b/dtool/src/cppparser/cppGlobals.cxx @@ -13,4 +13,4 @@ #include "cppGlobals.h" -string cpp_longlong_keyword; +std::string cpp_longlong_keyword; diff --git a/dtool/src/cppparser/cppGlobals.h b/dtool/src/cppparser/cppGlobals.h index 9cf4e8711a..39755f18d7 100644 --- a/dtool/src/cppparser/cppGlobals.h +++ b/dtool/src/cppparser/cppGlobals.h @@ -20,7 +20,7 @@ // 64-bit integer, but don't recognize "long long int". To parse (and // generate) code for these compilers, set this string to the 64-bit integer // typename keyword. -extern string cpp_longlong_keyword; +extern std::string cpp_longlong_keyword; #endif diff --git a/dtool/src/cppparser/cppIdentifier.cxx b/dtool/src/cppparser/cppIdentifier.cxx index 940b2a5daf..43c937177b 100644 --- a/dtool/src/cppparser/cppIdentifier.cxx +++ b/dtool/src/cppparser/cppIdentifier.cxx @@ -19,6 +19,8 @@ #include "cppTBDType.h" #include "cppStructType.h" +using std::string; + /** * @@ -26,7 +28,7 @@ CPPIdentifier:: CPPIdentifier(const string &name, const CPPFile &file) { _names.push_back(CPPNameComponent(name)); - _native_scope = (CPPScope *)NULL; + _native_scope = nullptr; _loc.first_line = 0; _loc.first_column = 0; _loc.last_line = 0; @@ -40,7 +42,7 @@ CPPIdentifier(const string &name, const CPPFile &file) { CPPIdentifier:: CPPIdentifier(const CPPNameComponent &name, const CPPFile &file) { _names.push_back(name); - _native_scope = (CPPScope *)NULL; + _native_scope = nullptr; _loc.first_line = 0; _loc.first_column = 0; _loc.last_line = 0; @@ -54,7 +56,7 @@ CPPIdentifier(const CPPNameComponent &name, const CPPFile &file) { CPPIdentifier:: CPPIdentifier(const string &name, const cppyyltype &loc) : _loc(loc) { _names.push_back(CPPNameComponent(name)); - _native_scope = (CPPScope *)NULL; + _native_scope = nullptr; } /** @@ -63,7 +65,7 @@ CPPIdentifier(const string &name, const cppyyltype &loc) : _loc(loc) { CPPIdentifier:: CPPIdentifier(const CPPNameComponent &name, const cppyyltype &loc) : _loc(loc) { _names.push_back(name); - _native_scope = (CPPScope *)NULL; + _native_scope = nullptr; } /** @@ -150,7 +152,7 @@ get_local_name(CPPScope *scope) const { string result; - if (scope == NULL || (_native_scope == NULL && _names.size() == 1)) { + if (scope == nullptr || (_native_scope == nullptr && _names.size() == 1)) { result = _names.back().get_name_with_templ(scope); } else if (_names.front().empty()) { @@ -159,15 +161,15 @@ get_local_name(CPPScope *scope) const { } else { // Determine the scope of everything up until but not including the last // name. - CPPScope *my_scope = get_scope(scope, NULL); + CPPScope *my_scope = get_scope(scope, nullptr); // Strip off template scopes, since they don't add anything particularly // meaningful to the local name. - while (my_scope != NULL && my_scope->as_template_scope() != NULL) { + while (my_scope != nullptr && my_scope->as_template_scope() != nullptr) { my_scope = my_scope->get_parent_scope(); } - if (my_scope == NULL) { + if (my_scope == nullptr) { result = get_fully_scoped_name(); } else if (my_scope == scope) { return _names.back().get_name_with_templ(scope); @@ -240,7 +242,7 @@ get_scope(CPPScope *current_scope, CPPScope *global_scope, assert(!_names.empty()); CPPScope *scope = _native_scope; - if (scope == (CPPScope *)NULL) { + if (scope == nullptr) { scope = current_scope; } int i = 0; @@ -251,16 +253,16 @@ get_scope(CPPScope *current_scope, CPPScope *global_scope, i++; } - while (i + 1 < (int)_names.size() && scope != NULL) { - CPPScope *next_scope = scope->find_scope(_names[i].get_name()); - if (next_scope == (CPPScope *)NULL) { - if (error_sink != NULL) { + while (i + 1 < (int)_names.size() && scope != nullptr) { + CPPScope *next_scope = scope->find_scope(_names[i].get_name(), global_scope); + if (next_scope == nullptr) { + if (error_sink != nullptr) { error_sink->error("Symbol " + _names[i].get_name() + " is not a known scope in " + scope->get_fully_scoped_name(), _loc); } - return (CPPScope *)NULL; + return nullptr; } if (_names[i].has_templ()) { next_scope = next_scope->instantiate(_names[i].get_templ(), @@ -283,7 +285,7 @@ get_scope(CPPScope *current_scope, CPPScope *global_scope, assert(!_names.empty()); CPPScope *scope = _native_scope; - if (scope == (CPPScope *)NULL) { + if (scope == nullptr) { scope = current_scope; } int i = 0; @@ -294,17 +296,17 @@ get_scope(CPPScope *current_scope, CPPScope *global_scope, i++; } - while (i + 1 < (int)_names.size() && scope != NULL) { + while (i + 1 < (int)_names.size() && scope != nullptr) { CPPScope *next_scope = scope->find_scope(_names[i].get_name(), subst, global_scope); - if (next_scope == (CPPScope *)NULL) { - if (error_sink != NULL) { + if (next_scope == nullptr) { + if (error_sink != nullptr) { error_sink->error("Symbol " + _names[i].get_name() + " is not a known scope in " + scope->get_fully_scoped_name(), _loc); } - return (CPPScope *)NULL; + return nullptr; } if (_names[i].has_templ()) { next_scope = next_scope->instantiate(_names[i].get_templ(), @@ -330,11 +332,11 @@ find_type(CPPScope *current_scope, CPPScope *global_scope, bool force_instantiate, CPPPreprocessor *error_sink) const { CPPScope *scope = get_scope(current_scope, global_scope, error_sink); - if (scope == NULL) { - return NULL; + if (scope == nullptr) { + return nullptr; } - CPPType *type = NULL; + CPPType *type = nullptr; if (!_names.back().has_templ()) { type = scope->find_type(get_simple_name()); @@ -374,12 +376,12 @@ find_type(CPPScope *current_scope, CPPScope *global_scope, CPPDeclaration::SubstDecl &subst, CPPPreprocessor *error_sink) const { CPPScope *scope = get_scope(current_scope, global_scope, subst, error_sink); - if (scope == NULL) { - return NULL; + if (scope == nullptr) { + return nullptr; } CPPType *type = scope->find_type(get_simple_name(), subst, global_scope); - if (type != NULL && _names.back().has_templ()) { + if (type != nullptr && _names.back().has_templ()) { // This is a template type. if (is_fully_specified()) { @@ -388,9 +390,9 @@ find_type(CPPScope *current_scope, CPPScope *global_scope, type->instantiate(_names.back().get_templ(), current_scope, global_scope, error_sink); - assert(decl != NULL); + assert(decl != nullptr); CPPType *new_type = decl->as_type(); - assert(new_type != NULL); + assert(new_type != nullptr); if (new_type == type) { type = CPPType::new_type(new CPPTBDType((CPPIdentifier *)this)); } else { @@ -413,8 +415,8 @@ CPPDeclaration *CPPIdentifier:: find_symbol(CPPScope *current_scope, CPPScope *global_scope, CPPPreprocessor *error_sink) const { CPPScope *scope = get_scope(current_scope, global_scope, error_sink); - if (scope == NULL) { - return NULL; + if (scope == nullptr) { + return nullptr; } CPPDeclaration *sym; @@ -430,9 +432,9 @@ find_symbol(CPPScope *current_scope, CPPScope *global_scope, } else { sym = scope->find_template(get_simple_name()); - if (sym != NULL) { + if (sym != nullptr) { CPPType *type = sym->as_type(); - if (type != NULL && type->is_incomplete()) { + if (type != nullptr && type->is_incomplete()) { // We can't instantiate an incomplete type. sym = CPPType::new_type(new CPPTBDType((CPPIdentifier *)this)); } else { @@ -454,8 +456,8 @@ find_symbol(CPPScope *current_scope, CPPScope *global_scope, CPPDeclaration::SubstDecl &subst, CPPPreprocessor *error_sink) const { CPPScope *scope = get_scope(current_scope, global_scope, subst, error_sink); - if (scope == NULL) { - return NULL; + if (scope == nullptr) { + return nullptr; } CPPDeclaration *sym; @@ -472,9 +474,9 @@ find_symbol(CPPScope *current_scope, CPPScope *global_scope, } else { sym = scope->find_template(get_simple_name()); - if (sym != NULL) { + if (sym != nullptr) { CPPType *type = sym->as_type(); - if (type != NULL && type->is_incomplete()) { + if (type != nullptr && type->is_incomplete()) { // We can't instantiate an incomplete type. sym = CPPType::new_type(new CPPTBDType((CPPIdentifier *)this)); } else { @@ -495,8 +497,8 @@ CPPDeclaration *CPPIdentifier:: find_template(CPPScope *current_scope, CPPScope *global_scope, CPPPreprocessor *error_sink) const { CPPScope *scope = get_scope(current_scope, global_scope, error_sink); - if (scope == NULL) { - return NULL; + if (scope == nullptr) { + return nullptr; } return scope->find_template(get_simple_name()); } @@ -508,10 +510,10 @@ CPPScope *CPPIdentifier:: find_scope(CPPScope *current_scope, CPPScope *global_scope, CPPPreprocessor *error_sink) const { CPPScope *scope = get_scope(current_scope, global_scope, error_sink); - if (scope == NULL) { - return NULL; + if (scope == nullptr) { + return nullptr; } - return scope->find_scope(get_simple_name()); + return scope->find_scope(get_simple_name(), global_scope); } @@ -546,8 +548,8 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, * */ void CPPIdentifier:: -output(ostream &out, CPPScope *scope) const { - if (scope == NULL) { +output(std::ostream &out, CPPScope *scope) const { + if (scope == nullptr) { output_fully_scoped_name(out); } else { output_local_name(out, scope); @@ -559,19 +561,19 @@ output(ostream &out, CPPScope *scope) const { * */ void CPPIdentifier:: -output_local_name(ostream &out, CPPScope *scope) const { +output_local_name(std::ostream &out, CPPScope *scope) const { assert(!_names.empty()); - if (scope == NULL || (_native_scope == NULL && _names.size() == 1)) { + if (scope == nullptr || (_native_scope == nullptr && _names.size() == 1)) { out << _names.back(); } else if (_names.front().empty()) { output_fully_scoped_name(out); } else { // Determine the scope of everything up until but not including the last // name. - CPPScope *my_scope = get_scope(scope, NULL); + CPPScope *my_scope = get_scope(scope, nullptr); - if (my_scope == NULL) { + if (my_scope == nullptr) { output_fully_scoped_name(out); } else { out << my_scope->get_local_name(scope) << "::" << _names.back(); @@ -583,9 +585,9 @@ output_local_name(ostream &out, CPPScope *scope) const { * */ void CPPIdentifier:: -output_fully_scoped_name(ostream &out) const { - if (_native_scope != NULL) { - _native_scope->output(out, (CPPScope *)NULL); +output_fully_scoped_name(std::ostream &out) const { + if (_native_scope != nullptr) { + _native_scope->output(out, nullptr); out << "::"; } Names::const_iterator ni = _names.begin(); diff --git a/dtool/src/cppparser/cppIdentifier.h b/dtool/src/cppparser/cppIdentifier.h index abb6405fc6..8916320450 100644 --- a/dtool/src/cppparser/cppIdentifier.h +++ b/dtool/src/cppparser/cppIdentifier.h @@ -34,11 +34,11 @@ class CPPTemplateParameterList; */ class CPPIdentifier { public: - CPPIdentifier(const string &name, const CPPFile &file = CPPFile()); + CPPIdentifier(const std::string &name, const CPPFile &file = CPPFile()); CPPIdentifier(const CPPNameComponent &name, const CPPFile &file = CPPFile()); - CPPIdentifier(const string &name, const cppyyltype &loc); + CPPIdentifier(const std::string &name, const cppyyltype &loc); CPPIdentifier(const CPPNameComponent &name, const cppyyltype &loc); - void add_name(const string &name); + void add_name(const std::string &name); void add_name(const CPPNameComponent &name); bool operator == (const CPPIdentifier &other) const; @@ -47,56 +47,56 @@ public: bool is_scoped() const; - string get_simple_name() const; - string get_local_name(CPPScope *scope = NULL) const; - string get_fully_scoped_name() const; + std::string get_simple_name() const; + std::string get_local_name(CPPScope *scope = nullptr) const; + std::string get_fully_scoped_name() const; bool is_fully_specified() const; bool is_tbd() const; CPPScope *get_scope(CPPScope *current_scope, CPPScope *global_scope, - CPPPreprocessor *error_sink = NULL) const; + CPPPreprocessor *error_sink = nullptr) const; CPPScope *get_scope(CPPScope *current_scope, CPPScope *global_scope, CPPDeclaration::SubstDecl &subst, - CPPPreprocessor *error_sink = NULL) const; + CPPPreprocessor *error_sink = nullptr) const; CPPType *find_type(CPPScope *current_scope, CPPScope *global_scope, bool force_instantiate = false, - CPPPreprocessor *error_sink = NULL) const; + CPPPreprocessor *error_sink = nullptr) const; CPPType *find_type(CPPScope *current_scope, CPPScope *global_scope, CPPDeclaration::SubstDecl &subst, - CPPPreprocessor *error_sink = NULL) const; + CPPPreprocessor *error_sink = nullptr) const; CPPDeclaration *find_symbol(CPPScope *current_scope, CPPScope *global_scope, - CPPPreprocessor *error_sink = NULL) const; + CPPPreprocessor *error_sink = nullptr) const; CPPDeclaration *find_symbol(CPPScope *current_scope, CPPScope *global_scope, CPPDeclaration::SubstDecl &subst, - CPPPreprocessor *error_sink = NULL) const; + CPPPreprocessor *error_sink = nullptr) const; CPPDeclaration *find_template(CPPScope *current_scope, CPPScope *global_scope, - CPPPreprocessor *error_sink = NULL) const; + CPPPreprocessor *error_sink = nullptr) const; CPPScope *find_scope(CPPScope *current_scope, CPPScope *global_scope, - CPPPreprocessor *error_sink = NULL) const; + CPPPreprocessor *error_sink = nullptr) const; CPPIdentifier *substitute_decl(CPPDeclaration::SubstDecl &subst, CPPScope *current_scope, CPPScope *global_scope); - void output(ostream &out, CPPScope *scope) const; - void output_local_name(ostream &out, CPPScope *scope) const; - void output_fully_scoped_name(ostream &out) const; + void output(std::ostream &out, CPPScope *scope) const; + void output_local_name(std::ostream &out, CPPScope *scope) const; + void output_fully_scoped_name(std::ostream &out) const; - typedef vector Names; + typedef std::vector Names; Names _names; CPPScope *_native_scope; cppyyltype _loc; }; -inline ostream &operator << (ostream &out, const CPPIdentifier &identifier) { - identifier.output(out, (CPPScope *)NULL); +inline std::ostream &operator << (std::ostream &out, const CPPIdentifier &identifier) { + identifier.output(out, nullptr); return out; } diff --git a/dtool/src/cppparser/cppInstance.cxx b/dtool/src/cppparser/cppInstance.cxx index 0bfdcabde1..cb59e9a048 100644 --- a/dtool/src/cppparser/cppInstance.cxx +++ b/dtool/src/cppparser/cppInstance.cxx @@ -26,6 +26,8 @@ #include +using std::string; + /** * */ @@ -35,10 +37,10 @@ CPPInstance(CPPType *type, const string &name, int storage_class) : _type(type), _ident(new CPPIdentifier(name)), _storage_class(storage_class), - _alignment(NULL), + _alignment(nullptr), _bit_width(-1) { - _initializer = NULL; + _initializer = nullptr; } /** @@ -50,10 +52,10 @@ CPPInstance(CPPType *type, CPPIdentifier *ident, int storage_class) : _type(type), _ident(ident), _storage_class(storage_class), - _alignment(NULL), + _alignment(nullptr), _bit_width(-1) { - _initializer = NULL; + _initializer = nullptr; } /** @@ -65,17 +67,17 @@ CPPInstance:: CPPInstance(CPPType *type, CPPInstanceIdentifier *ii, int storage_class, const CPPFile &file) : CPPDeclaration(file), - _alignment(NULL) + _alignment(nullptr) { _type = ii->unroll_type(type); _ident = ii->_ident; - ii->_ident = NULL; + ii->_ident = nullptr; _storage_class = storage_class; - _initializer = NULL; + _initializer = nullptr; _bit_width = ii->_bit_width; CPPParameterList *params = ii->get_initializer(); - if (params != (CPPParameterList *)NULL) { + if (params != nullptr) { // In this case, the instance has a parameter-list initializer, e.g.: int // foo(0); We really should save this initializer in the instance object. // But we don't for now, since no one really cares about initializers @@ -102,7 +104,7 @@ CPPInstance(const CPPInstance ©) : _alignment(copy._alignment), _bit_width(copy._bit_width) { - assert(_type != NULL); + assert(_type != nullptr); } /** @@ -150,17 +152,17 @@ operator == (const CPPInstance &other) const { // We *do* care about the identifier. We need to differentiate types of // function variables, among possibly other things, based on the identifier. - if ((_ident == NULL && other._ident != NULL) || - (_ident != NULL && other._ident == NULL) || - (_ident != NULL && other._ident != NULL && *_ident != *other._ident)) + if ((_ident == nullptr && other._ident != nullptr) || + (_ident != nullptr && other._ident == nullptr) || + (_ident != nullptr && other._ident != nullptr && *_ident != *other._ident)) { return false; } // We similarly care about the initializer. - if ((_initializer == NULL && other._initializer != NULL) || - (_initializer != NULL && other._initializer == NULL) || - (_initializer != NULL && other._initializer != NULL && + if ((_initializer == nullptr && other._initializer != nullptr) || + (_initializer != nullptr && other._initializer == nullptr) || + (_initializer != nullptr && other._initializer != nullptr && *_initializer != *other._initializer)) { return false; @@ -194,23 +196,23 @@ operator < (const CPPInstance &other) const { // We *do* care about the identifier. We need to differentiate types of // function variables, among possibly other things, based on the identifier. - if ((_ident == NULL && other._ident != NULL) || - (_ident != NULL && other._ident == NULL) || - (_ident != NULL && other._ident != NULL && *_ident != *other._ident)) + if ((_ident == nullptr && other._ident != nullptr) || + (_ident != nullptr && other._ident == nullptr) || + (_ident != nullptr && other._ident != nullptr && *_ident != *other._ident)) { - if (_ident == NULL || other._ident == NULL) { + if (_ident == nullptr || other._ident == nullptr) { return _ident < other._ident; } return *_ident < *other._ident; } // We similarly care about the initializer. - if ((_initializer == NULL && other._initializer != NULL) || - (_initializer != NULL && other._initializer == NULL) || - (_initializer != NULL && other._initializer != NULL && + if ((_initializer == nullptr && other._initializer != nullptr) || + (_initializer != nullptr && other._initializer == nullptr) || + (_initializer != nullptr && other._initializer != nullptr && *_initializer != *other._initializer)) { - if (_initializer == NULL || other._initializer == NULL) { + if (_initializer == nullptr || other._initializer == nullptr) { return _initializer < other._initializer; } return *_initializer < *other._initializer; @@ -226,12 +228,12 @@ operator < (const CPPInstance &other) const { */ void CPPInstance:: set_initializer(CPPExpression *initializer) { - if (_type->as_function_type() != (CPPFunctionType *)NULL) { + if (_type->as_function_type() != nullptr) { // This is a function declaration. _storage_class &= ~(SC_pure_virtual | SC_defaulted | SC_deleted); - _initializer = (CPPExpression *)NULL; + _initializer = nullptr; - if (initializer != (CPPExpression *)NULL) { + if (initializer != nullptr) { if (initializer->_type == CPPExpression::T_integer) { // = 0 _storage_class |= SC_pure_virtual; @@ -270,7 +272,7 @@ set_alignment(CPPExpression *const_expr) { */ bool CPPInstance:: is_scoped() const { - if (_ident == NULL) { + if (_ident == nullptr) { return false; } else { return _ident->is_scoped(); @@ -283,7 +285,7 @@ is_scoped() const { CPPScope *CPPInstance:: get_scope(CPPScope *current_scope, CPPScope *global_scope, CPPPreprocessor *error_sink) const { - if (_ident == NULL) { + if (_ident == nullptr) { return current_scope; } else { return _ident->get_scope(current_scope, global_scope, error_sink); @@ -295,7 +297,7 @@ get_scope(CPPScope *current_scope, CPPScope *global_scope, */ string CPPInstance:: get_simple_name() const { - if (_ident == NULL) { + if (_ident == nullptr) { return ""; } else { return _ident->get_simple_name(); @@ -307,7 +309,7 @@ get_simple_name() const { */ string CPPInstance:: get_local_name(CPPScope *scope) const { - if (_ident == NULL) { + if (_ident == nullptr) { return ""; } else { return _ident->get_local_name(scope); @@ -319,7 +321,7 @@ get_local_name(CPPScope *scope) const { */ string CPPInstance:: get_fully_scoped_name() const { - if (_ident == NULL) { + if (_ident == nullptr) { return ""; } else { return _ident->get_fully_scoped_name(); @@ -334,12 +336,12 @@ get_fully_scoped_name() const { void CPPInstance:: check_for_constructor(CPPScope *current_scope, CPPScope *global_scope) { CPPScope *scope = get_scope(current_scope, global_scope); - if (scope == NULL) { + if (scope == nullptr) { scope = current_scope; } CPPFunctionType *func = _type->as_function_type(); - if (func != NULL) { + if (func != nullptr) { string method_name = get_local_name(scope); string class_name = scope->get_local_name(); @@ -359,7 +361,7 @@ check_for_constructor(CPPScope *current_scope, CPPScope *global_scope) { CPPType *param_type = params->_parameters[0]->_type; CPPReferenceType *ref_type = param_type->as_reference_type(); - if (ref_type != NULL) { + if (ref_type != nullptr) { param_type = ref_type->_pointing_at->remove_cv(); if (class_name == param_type->get_simple_name()) { @@ -404,7 +406,7 @@ instantiate(const CPPTemplateParameterList *actual_params, CPPPreprocessor *error_sink) const { if (!is_template()) { - if (error_sink != NULL) { + if (error_sink != nullptr) { error_sink->warning("Ignoring template parameters for instance " + _ident->get_local_name()); } @@ -434,7 +436,7 @@ instantiate(const CPPTemplateParameterList *actual_params, // change the name. inst = new CPPInstance(*this); } - assert(inst != NULL); + assert(inst != nullptr); inst->_ident = inst->_ident->substitute_decl(subst, current_scope, global_scope); if (inst->_ident == _ident) { inst->_ident = new CPPIdentifier(*inst->_ident); @@ -442,7 +444,7 @@ instantiate(const CPPTemplateParameterList *actual_params, inst->_ident->_names.back().set_templ (new CPPTemplateParameterList(*actual_params)); - inst->_template_scope = NULL; + inst->_template_scope = nullptr; ((CPPInstance *)this)->_instantiations.insert(Instantiations::value_type(actual_params, inst)); return inst; @@ -455,10 +457,10 @@ instantiate(const CPPTemplateParameterList *actual_params, */ bool CPPInstance:: is_fully_specified() const { - if (_ident != NULL && !_ident->is_fully_specified()) { + if (_ident != nullptr && !_ident->is_fully_specified()) { return false; } - if (_initializer != NULL && !_initializer->is_fully_specified()) { + if (_initializer != nullptr && !_initializer->is_fully_specified()) { return false; } return CPPDeclaration::is_fully_specified() && @@ -482,11 +484,11 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, _type->substitute_decl(subst, current_scope, global_scope); rep->_type = new_type->as_type(); - if (rep->_type == NULL) { + if (rep->_type == nullptr) { rep->_type = _type; } - if (_initializer != NULL) { + if (_initializer != nullptr) { rep->_initializer = _initializer->substitute_decl(subst, current_scope, global_scope) ->as_expression(); @@ -506,7 +508,7 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, * */ void CPPInstance:: -output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { +output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const { output(out, indent_level, scope, complete, -1); } @@ -515,9 +517,9 @@ output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { * function prototype. See CPPFunctionType::output(). */ void CPPInstance:: -output(ostream &out, int indent_level, CPPScope *scope, bool complete, +output(std::ostream &out, int indent_level, CPPScope *scope, bool complete, int num_default_parameters) const { - assert(_type != NULL); + assert(_type != nullptr); if (_type->is_parameter_expr()) { // In this case, the whole thing is really an expression, and not an @@ -532,7 +534,7 @@ output(ostream &out, int indent_level, CPPScope *scope, bool complete, indent(out, indent_level); } - if (_alignment != NULL) { + if (_alignment != nullptr) { out << "alignas(" << *_alignment << ") "; } @@ -571,7 +573,7 @@ output(ostream &out, int indent_level, CPPScope *scope, bool complete, } string name; - if (_ident != NULL) { + if (_ident != nullptr) { name = _ident->get_local_name(scope); } if (_storage_class & SC_parameter_pack) { @@ -600,7 +602,7 @@ output(ostream &out, int indent_level, CPPScope *scope, bool complete, if (_storage_class & SC_deleted) { out << " = delete"; } - if (_initializer != NULL) { + if (_initializer != nullptr) { out << " = " << *_initializer; } } diff --git a/dtool/src/cppparser/cppInstance.h b/dtool/src/cppparser/cppInstance.h index 675ba83507..0cfd4bea43 100644 --- a/dtool/src/cppparser/cppInstance.h +++ b/dtool/src/cppparser/cppInstance.h @@ -73,7 +73,7 @@ public: SC_parameter_pack = 0x40000, }; - CPPInstance(CPPType *type, const string &name, int storage_class = 0); + CPPInstance(CPPType *type, const std::string &name, int storage_class = 0); CPPInstance(CPPType *type, CPPIdentifier *ident, int storage_class = 0); CPPInstance(CPPType *type, CPPInstanceIdentifier *ii, int storage_class, const CPPFile &file); @@ -94,27 +94,27 @@ public: bool is_scoped() const; CPPScope *get_scope(CPPScope *current_scope, CPPScope *global_scope, - CPPPreprocessor *error_sink = NULL) const; + CPPPreprocessor *error_sink = nullptr) const; - string get_simple_name() const; - string get_local_name(CPPScope *scope = NULL) const; - string get_fully_scoped_name() const; + std::string get_simple_name() const; + std::string get_local_name(CPPScope *scope = nullptr) const; + std::string get_fully_scoped_name() const; void check_for_constructor(CPPScope *current_scope, CPPScope *global_scope); virtual CPPDeclaration * instantiate(const CPPTemplateParameterList *actual_params, CPPScope *current_scope, CPPScope *global_scope, - CPPPreprocessor *error_sink = NULL) const; + CPPPreprocessor *error_sink = nullptr) const; virtual bool is_fully_specified() const; virtual CPPDeclaration *substitute_decl(SubstDecl &subst, CPPScope *current_scope, CPPScope *global_scope); - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; - void output(ostream &out, int indent_level, CPPScope *scope, + void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete, int num_default_parameters) const; virtual SubType get_subtype() const; @@ -129,7 +129,7 @@ public: int _bit_width; private: - typedef map Instantiations; + typedef std::map Instantiations; Instantiations _instantiations; }; diff --git a/dtool/src/cppparser/cppInstanceIdentifier.cxx b/dtool/src/cppparser/cppInstanceIdentifier.cxx index fe723f552d..878d751285 100644 --- a/dtool/src/cppparser/cppInstanceIdentifier.cxx +++ b/dtool/src/cppparser/cppInstanceIdentifier.cxx @@ -27,10 +27,10 @@ CPPInstanceIdentifier::Modifier:: Modifier(CPPInstanceIdentifierType type) : _type(type), - _func_params(NULL), + _func_params(nullptr), _func_flags(0), - _scoping(NULL), - _expr(NULL) { + _scoping(nullptr), + _expr(nullptr) { } /** @@ -116,11 +116,11 @@ add_func_modifier(CPPParameterList *params, int flags, CPPType *trailing_return_ // check if the parameter list is empty. If it is, this is really a unary // operator, so set the unary_op flag. Operators () and [] are never // considered unary operators. - if (_ident != NULL && + if (_ident != nullptr && _ident->get_simple_name().substr(0, 9) == "operator ") { - if (_ident->get_simple_name() != string("operator ()") && - _ident->get_simple_name() != string("operator []")) { + if (_ident->get_simple_name() != std::string("operator ()") && + _ident->get_simple_name() != std::string("operator []")) { if (params->_parameters.empty()) { flags |= CPPFunctionType::F_unary_op; } @@ -129,7 +129,7 @@ add_func_modifier(CPPParameterList *params, int flags, CPPType *trailing_return_ flags |= CPPFunctionType::F_operator; } - if (trailing_return_type != NULL) { + if (trailing_return_type != nullptr) { // Remember whether trailing return type notation was used. flags |= CPPFunctionType::F_trailing_return_type; } @@ -153,7 +153,7 @@ add_array_modifier(CPPExpression *expr) { // Special case for operator new[] and delete[]. We're not really adding an // array modifier to them, but appending [] to the identifier. This is to // work around a parser ambiguity. - if (_ident != NULL && (_ident->get_simple_name() == "operator delete" || + if (_ident != nullptr && (_ident->get_simple_name() == "operator delete" || _ident->get_simple_name() == "operator new")) { _ident->_names.back().append_name("[]"); @@ -184,7 +184,7 @@ add_trailing_return_type(CPPType *type) { return; } } - cerr << "trailing return type can only be added to a function\n"; + std::cerr << "trailing return type can only be added to a function\n"; } /** @@ -206,7 +206,7 @@ get_initializer() const { } } - return NULL; + return nullptr; } /** @@ -215,7 +215,7 @@ get_initializer() const { CPPScope *CPPInstanceIdentifier:: get_scope(CPPScope *current_scope, CPPScope *global_scope, CPPPreprocessor *error_sink) const { - if (_ident == NULL) { + if (_ident == nullptr) { return current_scope; } else { return _ident->get_scope(current_scope, global_scope, error_sink); @@ -228,7 +228,7 @@ get_scope(CPPScope *current_scope, CPPScope *global_scope, CPPType *CPPInstanceIdentifier:: r_unroll_type(CPPType *start_type, CPPInstanceIdentifier::Modifiers::const_iterator mi) { - assert(start_type != NULL); + assert(start_type != nullptr); start_type = CPPType::new_type(start_type); @@ -239,7 +239,7 @@ r_unroll_type(CPPType *start_type, const Modifier &mod = (*mi); ++mi; - CPPType *result = NULL; + CPPType *result = nullptr; switch (mod._type) { case IIT_pointer: @@ -260,7 +260,7 @@ r_unroll_type(CPPType *start_type, { CPPType *type = r_unroll_type(start_type, mi); CPPFunctionType *ftype = type->as_function_type(); - if (ftype != NULL) { + if (ftype != nullptr) { ftype = new CPPFunctionType(*ftype); ftype->_class_owner = mod._scoping; ftype->_flags |= CPPFunctionType::F_method_pointer; @@ -291,12 +291,12 @@ r_unroll_type(CPPType *start_type, case IIT_func: { CPPType *return_type = r_unroll_type(start_type, mi); - if (mod._trailing_return_type != (CPPType *)NULL) { + if (mod._trailing_return_type != nullptr) { CPPSimpleType *simple_type = return_type->as_simple_type(); - if (simple_type != NULL && simple_type->_type == CPPSimpleType::T_auto) { + if (simple_type != nullptr && simple_type->_type == CPPSimpleType::T_auto) { return_type = mod._trailing_return_type; } else { - cerr << "function with trailing return type needs auto\n"; + std::cerr << "function with trailing return type needs auto\n"; } } result = new CPPFunctionType(return_type, mod._func_params, @@ -312,7 +312,7 @@ r_unroll_type(CPPType *start_type, break; default: - cerr << "Internal error--invalid CPPInstanceIdentifier\n"; + std::cerr << "Internal error--invalid CPPInstanceIdentifier\n"; abort(); } diff --git a/dtool/src/cppparser/cppInstanceIdentifier.h b/dtool/src/cppparser/cppInstanceIdentifier.h index 8433b30313..6a2951d9cb 100644 --- a/dtool/src/cppparser/cppInstanceIdentifier.h +++ b/dtool/src/cppparser/cppInstanceIdentifier.h @@ -19,8 +19,6 @@ #include #include -using namespace std; - class CPPIdentifier; class CPPParameterList; class CPPType; @@ -55,7 +53,7 @@ public: void add_modifier(CPPInstanceIdentifierType type); void add_func_modifier(CPPParameterList *params, int flags, - CPPType *trailing_return_type = NULL); + CPPType *trailing_return_type = nullptr); void add_scoped_pointer_modifier(CPPIdentifier *scoping); void add_array_modifier(CPPExpression *expr); void add_initializer_modifier(CPPParameterList *params); @@ -65,7 +63,7 @@ public: CPPParameterList *get_initializer() const; CPPScope *get_scope(CPPScope *current_scope, CPPScope *global_scope, - CPPPreprocessor *error_sink = NULL) const; + CPPPreprocessor *error_sink = nullptr) const; CPPIdentifier *_ident; @@ -85,7 +83,7 @@ public: CPPExpression *_expr; CPPType *_trailing_return_type; }; - typedef vector Modifiers; + typedef std::vector Modifiers; Modifiers _modifiers; // If not -1, indicates a bitfield diff --git a/dtool/src/cppparser/cppMakeProperty.cxx b/dtool/src/cppparser/cppMakeProperty.cxx index 02e4f21c60..1846092eaa 100644 --- a/dtool/src/cppparser/cppMakeProperty.cxx +++ b/dtool/src/cppparser/cppMakeProperty.cxx @@ -38,7 +38,7 @@ CPPMakeProperty(CPPIdentifier *ident, Type type, /** * */ -string CPPMakeProperty:: +std::string CPPMakeProperty:: get_simple_name() const { return _ident->get_simple_name(); } @@ -46,7 +46,7 @@ get_simple_name() const { /** * */ -string CPPMakeProperty:: +std::string CPPMakeProperty:: get_local_name(CPPScope *scope) const { return _ident->get_local_name(scope); } @@ -54,7 +54,7 @@ get_local_name(CPPScope *scope) const { /** * */ -string CPPMakeProperty:: +std::string CPPMakeProperty:: get_fully_scoped_name() const { return _ident->get_fully_scoped_name(); } @@ -63,42 +63,42 @@ get_fully_scoped_name() const { * */ void CPPMakeProperty:: -output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { - if (_length_function != NULL) { +output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const { + if (_length_function != nullptr) { out << "__make_seq_property"; } else { out << "__make_property"; } - if (_has_function != NULL) { + if (_has_function != nullptr) { out.put('2'); } out << "(" << _ident->get_local_name(scope); - if (_length_function != NULL) { + if (_length_function != nullptr) { out << ", " << _length_function->_name; } - if (_has_function != NULL) { + if (_has_function != nullptr) { out << ", " << _has_function->_name; } out << ", " << _get_function->_name; - if (_set_function != NULL) { + if (_set_function != nullptr) { out << ", " << _set_function->_name; } - if (_clear_function != NULL) { + if (_clear_function != nullptr) { out << ", " << _clear_function->_name; } - if (_del_function != NULL) { + if (_del_function != nullptr) { out << ", " << _del_function->_name; } - if (_insert_function != NULL) { + if (_insert_function != nullptr) { out << ", " << _insert_function->_name; } diff --git a/dtool/src/cppparser/cppMakeProperty.h b/dtool/src/cppparser/cppMakeProperty.h index cd364b30ec..2967ee3b09 100644 --- a/dtool/src/cppparser/cppMakeProperty.h +++ b/dtool/src/cppparser/cppMakeProperty.h @@ -91,11 +91,11 @@ public: CPPMakeProperty(CPPIdentifier *ident, Type type, CPPScope *current_scope, const CPPFile &file); - virtual string get_simple_name() const; - virtual string get_local_name(CPPScope *scope = NULL) const; - virtual string get_fully_scoped_name() const; + virtual std::string get_simple_name() const; + virtual std::string get_local_name(CPPScope *scope = nullptr) const; + virtual std::string get_fully_scoped_name() const; - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; virtual SubType get_subtype() const; diff --git a/dtool/src/cppparser/cppMakeSeq.cxx b/dtool/src/cppparser/cppMakeSeq.cxx index d9b5ac7fcd..b032d367bb 100644 --- a/dtool/src/cppparser/cppMakeSeq.cxx +++ b/dtool/src/cppparser/cppMakeSeq.cxx @@ -32,7 +32,7 @@ CPPMakeSeq(CPPIdentifier *ident, /** * */ -string CPPMakeSeq:: +std::string CPPMakeSeq:: get_simple_name() const { return _ident->get_simple_name(); } @@ -40,7 +40,7 @@ get_simple_name() const { /** * */ -string CPPMakeSeq:: +std::string CPPMakeSeq:: get_local_name(CPPScope *scope) const { return _ident->get_local_name(scope); } @@ -48,7 +48,7 @@ get_local_name(CPPScope *scope) const { /** * */ -string CPPMakeSeq:: +std::string CPPMakeSeq:: get_fully_scoped_name() const { return _ident->get_fully_scoped_name(); } @@ -57,7 +57,7 @@ get_fully_scoped_name() const { * */ void CPPMakeSeq:: -output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { +output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const { out << "__make_seq(" << _ident->get_local_name(scope) << ", " << _length_getter->_name << ", " << _element_getter->_name diff --git a/dtool/src/cppparser/cppMakeSeq.h b/dtool/src/cppparser/cppMakeSeq.h index 0e48dd0ef4..1db722d9bb 100644 --- a/dtool/src/cppparser/cppMakeSeq.h +++ b/dtool/src/cppparser/cppMakeSeq.h @@ -32,11 +32,11 @@ public: CPPFunctionGroup *element_getter, CPPScope *current_scope, const CPPFile &file); - virtual string get_simple_name() const; - virtual string get_local_name(CPPScope *scope = NULL) const; - virtual string get_fully_scoped_name() const; + virtual std::string get_simple_name() const; + virtual std::string get_local_name(CPPScope *scope = nullptr) const; + virtual std::string get_fully_scoped_name() const; - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; virtual SubType get_subtype() const; diff --git a/dtool/src/cppparser/cppManifest.cxx b/dtool/src/cppparser/cppManifest.cxx index bb8f315c39..2fc85783a7 100644 --- a/dtool/src/cppparser/cppManifest.cxx +++ b/dtool/src/cppparser/cppManifest.cxx @@ -16,6 +16,8 @@ #include +using std::string; + /** * */ @@ -41,7 +43,7 @@ CPPManifest:: CPPManifest(const string &args, const cppyyltype &loc) : _variadic_param(-1), _loc(loc), - _expr((CPPExpression *)NULL), + _expr(nullptr), _vis(V_public) { assert(!args.empty()); @@ -84,7 +86,7 @@ CPPManifest(const string &args, const cppyyltype &loc) : CPPManifest:: CPPManifest(const string ¯o, const string &definition) : _variadic_param(-1), - _expr((CPPExpression *)NULL), + _expr(nullptr), _vis(V_public) { _loc.first_line = 0; @@ -125,7 +127,7 @@ CPPManifest(const string ¯o, const string &definition) : */ CPPManifest:: ~CPPManifest() { - if (_expr != (CPPExpression *)NULL) { + if (_expr != nullptr) { delete _expr; } } @@ -242,17 +244,17 @@ expand(const vector_string &args) const { */ CPPType *CPPManifest:: determine_type() const { - if (_expr != (CPPExpression *)NULL) { + if (_expr != nullptr) { return _expr->determine_type(); } - return (CPPType *)NULL; + return nullptr; } /** * */ void CPPManifest:: -output(ostream &out) const { +output(std::ostream &out) const { out << _name; if (_has_parameters) { diff --git a/dtool/src/cppparser/cppManifest.h b/dtool/src/cppparser/cppManifest.h index dc5e7701a5..c397a3fb51 100644 --- a/dtool/src/cppparser/cppManifest.h +++ b/dtool/src/cppparser/cppManifest.h @@ -30,18 +30,18 @@ class CPPType; */ class CPPManifest { public: - CPPManifest(const string &args, const cppyyltype &loc); - CPPManifest(const string ¯o, const string &definition); + CPPManifest(const std::string &args, const cppyyltype &loc); + CPPManifest(const std::string ¯o, const std::string &definition); ~CPPManifest(); - static string stringify(const string &source); - string expand(const vector_string &args = vector_string()) const; + static std::string stringify(const std::string &source); + std::string expand(const vector_string &args = vector_string()) const; CPPType *determine_type() const; - void output(ostream &out) const; + void output(std::ostream &out) const; - string _name; + std::string _name; bool _has_parameters; int _num_parameters; int _variadic_param; @@ -54,25 +54,25 @@ public: CPPVisibility _vis; private: - void parse_parameters(const string &args, size_t &p, + void parse_parameters(const std::string &args, size_t &p, vector_string ¶meter_names); - void save_expansion(const string &exp, + void save_expansion(const std::string &exp, const vector_string ¶meter_names); class ExpansionNode { public: ExpansionNode(int parm_number, bool stringify, bool paste); - ExpansionNode(const string &str, bool paste = false); + ExpansionNode(const std::string &str, bool paste = false); int _parm_number; bool _stringify; bool _paste; - string _str; + std::string _str; }; - typedef vector Expansion; + typedef std::vector Expansion; Expansion _expansion; }; -inline ostream &operator << (ostream &out, const CPPManifest &manifest) { +inline std::ostream &operator << (std::ostream &out, const CPPManifest &manifest) { manifest.output(out); return out; } diff --git a/dtool/src/cppparser/cppNameComponent.cxx b/dtool/src/cppparser/cppNameComponent.cxx index 9287aaa89b..1c8e4df88b 100644 --- a/dtool/src/cppparser/cppNameComponent.cxx +++ b/dtool/src/cppparser/cppNameComponent.cxx @@ -14,6 +14,8 @@ #include "cppNameComponent.h" #include "cppTemplateParameterList.h" +using std::string; + /** * */ @@ -21,7 +23,7 @@ CPPNameComponent:: CPPNameComponent(const string &name) : _name(name) { - _templ = (CPPTemplateParameterList *)NULL; + _templ = nullptr; } /** @@ -32,10 +34,10 @@ operator == (const CPPNameComponent &other) const { if (_name != other._name) { return false; } - if (_templ == NULL && other._templ == NULL) { + if (_templ == nullptr && other._templ == nullptr) { return true; } - if (_templ == NULL || other._templ == NULL) { + if (_templ == nullptr || other._templ == nullptr) { return false; } if (*_templ != *other._templ) { @@ -61,10 +63,10 @@ operator < (const CPPNameComponent &other) const { if (_name != other._name) { return _name < other._name; } - if (_templ == NULL && other._templ == NULL) { + if (_templ == nullptr && other._templ == nullptr) { return false; } - if (_templ == NULL || other._templ == NULL) { + if (_templ == nullptr || other._templ == nullptr) { return _templ < other._templ; } return (*_templ) < (*other._templ); @@ -83,9 +85,9 @@ get_name() const { */ string CPPNameComponent:: get_name_with_templ(CPPScope *scope) const { - ostringstream strm; + std::ostringstream strm; strm << _name; - if (_templ != NULL) { + if (_templ != nullptr) { strm << "< "; _templ->output(strm, scope); strm << " >"; @@ -114,7 +116,7 @@ empty() const { */ bool CPPNameComponent:: has_templ() const { - return _templ != (CPPTemplateParameterList *)NULL; + return _templ != nullptr; } /** @@ -123,7 +125,7 @@ has_templ() const { */ bool CPPNameComponent:: is_tbd() const { - if (_templ != (CPPTemplateParameterList *)NULL) { + if (_templ != nullptr) { return _templ->is_tbd(); } return false; @@ -157,9 +159,9 @@ set_templ(CPPTemplateParameterList *templ) { * */ void CPPNameComponent:: -output(ostream &out) const { +output(std::ostream &out) const { out << _name; - if (_templ != NULL) { + if (_templ != nullptr) { out << "< " << *_templ << " >"; } } diff --git a/dtool/src/cppparser/cppNameComponent.h b/dtool/src/cppparser/cppNameComponent.h index e8f4a94ce4..a33de22a39 100644 --- a/dtool/src/cppparser/cppNameComponent.h +++ b/dtool/src/cppparser/cppNameComponent.h @@ -19,38 +19,36 @@ #include -using namespace std; - class CPPTemplateParameterList; class CPPScope; class CPPNameComponent { public: - CPPNameComponent(const string &name); + CPPNameComponent(const std::string &name); bool operator == (const CPPNameComponent &other) const; bool operator != (const CPPNameComponent &other) const; bool operator < (const CPPNameComponent &other) const; - string get_name() const; - string get_name_with_templ(CPPScope *scope = (CPPScope *)NULL) const; + std::string get_name() const; + std::string get_name_with_templ(CPPScope *scope = nullptr) const; CPPTemplateParameterList *get_templ() const; bool empty() const; bool has_templ() const; bool is_tbd() const; - void set_name(const string &name); - void append_name(const string &name); + void set_name(const std::string &name); + void append_name(const std::string &name); void set_templ(CPPTemplateParameterList *templ); - void output(ostream &out) const; + void output(std::ostream &out) const; private: - string _name; + std::string _name; CPPTemplateParameterList *_templ; }; -inline ostream &operator << (ostream &out, const CPPNameComponent &name) { +inline std::ostream &operator << (std::ostream &out, const CPPNameComponent &name) { name.output(out); return out; } diff --git a/dtool/src/cppparser/cppNamespace.cxx b/dtool/src/cppparser/cppNamespace.cxx index 36bad0a932..9a6f608f49 100644 --- a/dtool/src/cppparser/cppNamespace.cxx +++ b/dtool/src/cppparser/cppNamespace.cxx @@ -31,9 +31,9 @@ CPPNamespace(CPPIdentifier *ident, CPPScope *scope, const CPPFile &file) : /** * */ -string CPPNamespace:: +std::string CPPNamespace:: get_simple_name() const { - if (_ident == NULL) { + if (_ident == nullptr) { return ""; } return _ident->get_simple_name(); @@ -42,9 +42,9 @@ get_simple_name() const { /** * */ -string CPPNamespace:: +std::string CPPNamespace:: get_local_name(CPPScope *scope) const { - if (_ident == NULL) { + if (_ident == nullptr) { return ""; } return _ident->get_local_name(scope); @@ -53,9 +53,9 @@ get_local_name(CPPScope *scope) const { /** * */ -string CPPNamespace:: +std::string CPPNamespace:: get_fully_scoped_name() const { - if (_ident == NULL) { + if (_ident == nullptr) { return ""; } return _ident->get_fully_scoped_name(); @@ -73,16 +73,16 @@ get_scope() const { * */ void CPPNamespace:: -output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { +output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const { if (_is_inline) { out << "inline "; } - if (!complete && _ident != NULL) { + if (!complete && _ident != nullptr) { // If we have a name, use it. out << "namespace " << _ident->get_local_name(scope); } else { - if (_ident != NULL) { + if (_ident != nullptr) { out << "namespace " << _ident->get_local_name(scope) << " {\n"; } else { out << "namespace {\n"; diff --git a/dtool/src/cppparser/cppNamespace.h b/dtool/src/cppparser/cppNamespace.h index 81002b475f..ca4d1dcf04 100644 --- a/dtool/src/cppparser/cppNamespace.h +++ b/dtool/src/cppparser/cppNamespace.h @@ -29,12 +29,12 @@ public: CPPNamespace(CPPIdentifier *ident, CPPScope *scope, const CPPFile &file); - string get_simple_name() const; - string get_local_name(CPPScope *scope = NULL) const; - string get_fully_scoped_name() const; + std::string get_simple_name() const; + std::string get_local_name(CPPScope *scope = nullptr) const; + std::string get_fully_scoped_name() const; CPPScope *get_scope() const; - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; virtual SubType get_subtype() const; diff --git a/dtool/src/cppparser/cppParameterList.cxx b/dtool/src/cppparser/cppParameterList.cxx index 1d3c2b986d..4fc5198b6e 100644 --- a/dtool/src/cppparser/cppParameterList.cxx +++ b/dtool/src/cppparser/cppParameterList.cxx @@ -198,7 +198,7 @@ resolve_type(CPPScope *current_scope, CPPScope *global_scope) { * shown. */ void CPPParameterList:: -output(ostream &out, CPPScope *scope, bool parameter_names, +output(std::ostream &out, CPPScope *scope, bool parameter_names, int num_default_parameters) const { if (!_parameters.empty()) { for (int i = 0; i < (int)_parameters.size(); ++i) { @@ -213,7 +213,7 @@ output(ostream &out, CPPScope *scope, bool parameter_names, if (num_default_parameters >= 0 && i < (int)_parameters.size() - num_default_parameters) { // Don't show the default value for this parameter. - _parameters[i]->_initializer = (CPPExpression *)NULL; + _parameters[i]->_initializer = nullptr; } if (parameter_names) { diff --git a/dtool/src/cppparser/cppParameterList.h b/dtool/src/cppparser/cppParameterList.h index 93e00a822e..a5e5d327e9 100644 --- a/dtool/src/cppparser/cppParameterList.h +++ b/dtool/src/cppparser/cppParameterList.h @@ -49,17 +49,17 @@ public: // This vector contains a list of formal parameters, in order. A parameter // may have an empty identifer name. - typedef vector Parameters; + typedef std::vector Parameters; Parameters _parameters; bool _includes_ellipsis; - void output(ostream &out, CPPScope *scope, bool parameter_names, + void output(std::ostream &out, CPPScope *scope, bool parameter_names, int num_default_parameters = -1) const; }; -inline ostream & -operator << (ostream &out, const CPPParameterList &plist) { - plist.output(out, (CPPScope *)NULL, true); +inline std::ostream & +operator << (std::ostream &out, const CPPParameterList &plist) { + plist.output(out, nullptr, true); return out; } diff --git a/dtool/src/cppparser/cppParser.cxx b/dtool/src/cppparser/cppParser.cxx index 4b27a87d6d..f236a238c9 100644 --- a/dtool/src/cppparser/cppParser.cxx +++ b/dtool/src/cppparser/cppParser.cxx @@ -25,7 +25,7 @@ bool cppparser_output_class_keyword = false; * */ CPPParser:: -CPPParser() : CPPScope((CPPScope *)NULL, CPPNameComponent(""), V_public) { +CPPParser() : CPPScope(nullptr, CPPNameComponent(""), V_public) { } /** @@ -59,7 +59,7 @@ parse_file(const Filename &filename) { } if (!init_cpp(file)) { - cerr << "Unable to read " << filename << "\n"; + std::cerr << "Unable to read " << filename << "\n"; return false; } parse_cpp(this); @@ -72,7 +72,7 @@ parse_file(const Filename &filename) { * an expression. Returns NULL if the string is not a valid expression. */ CPPExpression *CPPParser:: -parse_expr(const string &expr) { +parse_expr(const std::string &expr) { YYLTYPE loc = {}; return CPPPreprocessor::parse_expr(expr, this, this, loc); } @@ -82,12 +82,12 @@ parse_expr(const string &expr) { * CPPType. Returns NULL if the string is not a valid type. */ CPPType *CPPParser:: -parse_type(const string &type) { +parse_type(const std::string &type) { CPPTypeParser ep(this, this); ep._verbose = 0; if (ep.parse_type(type, *this)) { return ep._type; } else { - return (CPPType *)NULL; + return nullptr; } } diff --git a/dtool/src/cppparser/cppParser.h b/dtool/src/cppparser/cppParser.h index f3b4405b7e..82ac2abd08 100644 --- a/dtool/src/cppparser/cppParser.h +++ b/dtool/src/cppparser/cppParser.h @@ -33,8 +33,8 @@ public: bool parse_file(const Filename &filename); - CPPExpression *parse_expr(const string &expr); - CPPType *parse_type(const string &type); + CPPExpression *parse_expr(const std::string &expr); + CPPType *parse_type(const std::string &type); }; /* diff --git a/dtool/src/cppparser/cppPointerType.cxx b/dtool/src/cppparser/cppPointerType.cxx index 4ae396e22d..bba2a82333 100644 --- a/dtool/src/cppparser/cppPointerType.cxx +++ b/dtool/src/cppparser/cppPointerType.cxx @@ -147,14 +147,14 @@ is_constructible(const CPPType *given_type) const { // Can initialize void pointer with any pointer. const CPPSimpleType *simple_type = a->as_simple_type(); - if (simple_type != NULL) { + if (simple_type != nullptr) { return simple_type->_type == CPPSimpleType::T_void; } // Can initialize from derived class pointer. const CPPStructType *a_struct = a->as_struct_type(); const CPPStructType *b_struct = b->as_struct_type(); - if (a_struct != NULL && b_struct != NULL) { + if (a_struct != nullptr && b_struct != nullptr) { return a_struct->is_base_of(b_struct); } @@ -194,7 +194,7 @@ is_copy_assignable() const { bool CPPPointerType:: is_equivalent(const CPPType &other) const { const CPPPointerType *ot = ((CPPType *)&other)->as_pointer_type(); - if (ot == (CPPPointerType *)NULL) { + if (ot == nullptr) { return CPPType::is_equivalent(other); } @@ -205,7 +205,7 @@ is_equivalent(const CPPType &other) const { * */ void CPPPointerType:: -output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { +output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const { /* CPPFunctionType *ftype = _pointing_at->as_function_type(); if (ftype != (CPPFunctionType *)NULL) { @@ -235,13 +235,13 @@ output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { * have special exceptions. */ void CPPPointerType:: -output_instance(ostream &out, int indent_level, CPPScope *scope, - bool complete, const string &prename, - const string &name) const { - string star = "*"; +output_instance(std::ostream &out, int indent_level, CPPScope *scope, + bool complete, const std::string &prename, + const std::string &name) const { + std::string star = "*"; CPPFunctionType *ftype = _pointing_at->as_function_type(); - if (ftype != NULL && + if (ftype != nullptr && ((ftype->_flags & CPPFunctionType::F_method_pointer) != 0)) { // We have to output pointers-to-method with a scoping before the '*'. star = ftype->_class_owner->get_fully_scoped_name() + "::*"; @@ -275,7 +275,7 @@ as_pointer_type() { bool CPPPointerType:: is_equal(const CPPDeclaration *other) const { const CPPPointerType *ot = ((CPPDeclaration *)other)->as_pointer_type(); - assert(ot != NULL); + assert(ot != nullptr); return _pointing_at == ot->_pointing_at; } @@ -288,7 +288,7 @@ is_equal(const CPPDeclaration *other) const { bool CPPPointerType:: is_less(const CPPDeclaration *other) const { const CPPPointerType *ot = ((CPPDeclaration *)other)->as_pointer_type(); - assert(ot != NULL); + assert(ot != nullptr); return _pointing_at < ot->_pointing_at; } diff --git a/dtool/src/cppparser/cppPointerType.h b/dtool/src/cppparser/cppPointerType.h index 3fce00b2f5..b5f42c57a2 100644 --- a/dtool/src/cppparser/cppPointerType.h +++ b/dtool/src/cppparser/cppPointerType.h @@ -44,12 +44,12 @@ public: virtual bool is_copy_assignable() const; virtual bool is_equivalent(const CPPType &other) const; - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; - virtual void output_instance(ostream &out, int indent_level, + virtual void output_instance(std::ostream &out, int indent_level, CPPScope *scope, - bool complete, const string &prename, - const string &name) const; + bool complete, const std::string &prename, + const std::string &name) const; virtual SubType get_subtype() const; diff --git a/dtool/src/cppparser/cppPreprocessor.cxx b/dtool/src/cppparser/cppPreprocessor.cxx index ecaecb98b6..24784a98c8 100644 --- a/dtool/src/cppparser/cppPreprocessor.cxx +++ b/dtool/src/cppparser/cppPreprocessor.cxx @@ -35,6 +35,9 @@ #include #include +using std::cerr; +using std::string; + // We manage our own visibility counter, in addition to that managed by // cppBison.y. We do this just so we can define manifests with the correct // visibility when they are declared. (Asking the parser for the current @@ -87,8 +90,8 @@ trim_blanks(const string &str) { */ CPPPreprocessor::InputFile:: InputFile() { - _in = NULL; - _ignore_manifest = NULL; + _in = nullptr; + _ignore_manifest = nullptr; _line_number = 0; _col_number = 0; _next_line_number = 1; @@ -101,7 +104,7 @@ InputFile() { */ CPPPreprocessor::InputFile:: ~InputFile() { - if (_in != NULL) { + if (_in != nullptr) { // For some reason--compiler bug in gcc 3.2?--explicitly deleting the // stream pointer does not call the appropriate global delete function; // instead apparently calling the system delete function. So we call the @@ -120,7 +123,7 @@ CPPPreprocessor::InputFile:: */ bool CPPPreprocessor::InputFile:: open(const CPPFile &file) { - assert(_in == NULL); + assert(_in == nullptr); _file = file; pifstream *in = new pifstream; @@ -134,10 +137,10 @@ open(const CPPFile &file) { */ bool CPPPreprocessor::InputFile:: connect_input(const string &input) { - assert(_in == NULL); + assert(_in == nullptr); _input = input; - _in = new istringstream(_input); + _in = new std::istringstream(_input); return !_in->fail(); } @@ -146,7 +149,7 @@ connect_input(const string &input) { */ int CPPPreprocessor::InputFile:: get() { - assert(_in != NULL); + assert(_in != nullptr); if (!_lock_position) { _line_number = _next_line_number; @@ -186,7 +189,7 @@ get() { */ int CPPPreprocessor::InputFile:: peek() { - assert(_in != NULL); + assert(_in != nullptr); int c = _in->peek(); @@ -344,7 +347,7 @@ get_next_token0() { // instantiation and call yacc recursively to parse the template // parameters. CPPDeclaration *decl = ident->find_template(current_scope, global_scope); - if (decl != NULL) { + if (decl != nullptr) { ident->_names.back().set_templ (nested_parse_template_instantiation(decl->get_template_scope())); token = internal_get_next_token(); @@ -402,7 +405,7 @@ get_next_token0() { // parameters. CPPDeclaration *decl = ident->find_template(current_scope, global_scope); - if (decl != NULL) { + if (decl != nullptr) { ident->_names.back().set_templ (nested_parse_template_instantiation(decl->get_template_scope())); token = internal_get_next_token(); @@ -417,7 +420,7 @@ get_next_token0() { int token_type = IDENTIFIER; CPPDeclaration *decl = ident->find_symbol(current_scope, global_scope); - if (decl != NULL && decl->as_type() != NULL) { + if (decl != nullptr && decl->as_type() != nullptr) { // We need to see type pack template parameters as a different type of // identifier to resolve a parser ambiguity. CPPClassTemplateParameter *ctp = decl->as_class_template_parameter(); @@ -567,12 +570,12 @@ show_line(const YYLTYPE &loc) { } // Seek to the offending line in the file. - ifstream stream; + std::ifstream stream; if (loc.file._filename.open_read(stream)) { int l = 0; string linestr; while (l < loc.first_line) { - getline(stream, linestr); + std::getline(stream, linestr); ++l; } @@ -642,19 +645,19 @@ get_comment_before(int line, CPPFile file) { } if (comment->_last_line < line) { - return (CPPCommentBlock *)NULL; + return nullptr; } } else { wrong_file_count++; if (wrong_file_count > 10) { - return (CPPCommentBlock *)NULL; + return nullptr; } } ++ci; } - return (CPPCommentBlock *)NULL; + return nullptr; } /** @@ -672,14 +675,14 @@ get_comment_on(int line, CPPFile file) { if (comment->_line_number == line) { return comment; } else if (comment->_line_number < line) { - return (CPPCommentBlock *)NULL; + return nullptr; } } ++ci; } - return (CPPCommentBlock *)NULL; + return nullptr; } /** @@ -887,7 +890,7 @@ parse_expr(const string &input_expr, CPPScope *current_scope, if (ep.parse_expr(expr, *this)) { return ep._expr; } else { - return (CPPExpression *)NULL; + return nullptr; } } @@ -1491,7 +1494,7 @@ handle_define_directive(const string &args, const YYLTYPE &loc) { } } - pair result = + std::pair result = _manifests.insert(Manifests::value_type(manifest->_name, manifest)); if (!result.second) { @@ -1555,7 +1558,7 @@ handle_if_directive(const string &args, const YYLTYPE &loc) { if (ep.parse_expr(expr, *this)) { CPPExpression::Result result = ep._expr->evaluate(); if (result._type == CPPExpression::RT_error) { - ostringstream strm; + std::ostringstream strm; strm << *ep._expr; warning("Ignoring invalid expression " + strm.str(), loc); } else { @@ -1579,7 +1582,6 @@ handle_if_directive(const string &args, const YYLTYPE &loc) { */ void CPPPreprocessor:: handle_include_directive(const string &args, const YYLTYPE &loc) { - bool okflag = false; Filename filename; Filename filename_as_referenced; bool angle_quotes = false; @@ -1599,7 +1601,6 @@ handle_include_directive(const string &args, const YYLTYPE &loc) { if (!expr.empty()) { if (expr[0] == '"' && expr[expr.size() - 1] == '"') { filename = expr.substr(1, expr.size() - 2); - okflag = true; if (_files.size() == 1) { // If we're currently processing a top-level file, record the include @@ -1614,7 +1615,6 @@ handle_include_directive(const string &args, const YYLTYPE &loc) { // same, as if they used quote marks. angle_quotes = true; } - okflag = true; if (_files.size() == 1) { // If we're currently processing a top-level file, record the include @@ -1677,7 +1677,7 @@ handle_pragma_directive(const string &args, const YYLTYPE &loc) { if (mi != _manifests.end()) { _manifest_stack[macro].push_back(mi->second); } else { - _manifest_stack[macro].push_back(NULL); + _manifest_stack[macro].push_back(nullptr); } } else if (sscanf(args.c_str(), "pop_macro ( \"%63[^\"]\" )", macro) == 1) { @@ -1686,7 +1686,7 @@ handle_pragma_directive(const string &args, const YYLTYPE &loc) { CPPManifest *manifest = stack.back(); stack.pop_back(); Manifests::iterator mi = _manifests.find(macro); - if (manifest == NULL) { + if (manifest == nullptr) { // It was undefined when it was pushed, so make it undefined again. if (mi != _manifests.end()) { _manifests.erase(mi); @@ -1969,7 +1969,7 @@ get_identifier(int c) { if (kw != 0) { YYSTYPE result; - result.u.identifier = (CPPIdentifier *)NULL; + result.u.identifier = nullptr; return CPPToken(kw, loc, name, result); } @@ -2022,24 +2022,24 @@ get_literal(int token, YYLTYPE loc, const string &str, const YYSTYPE &value) { CPPIdentifier *ident = new CPPIdentifier("operator \"\" " + suffix); CPPDeclaration *decl = ident->find_symbol(current_scope, global_scope, this); - if (decl == NULL || decl->get_subtype() != CPPDeclaration::ST_function_group) { + if (decl == nullptr || decl->get_subtype() != CPPDeclaration::ST_function_group) { error("unknown literal suffix " + suffix, loc); return CPPToken(token, loc, str, value); } // Find the overload with the appropriate signature. - CPPExpression *expr = NULL; - CPPInstance *instance = NULL; - CPPInstance *raw_instance = NULL; + CPPExpression *expr = nullptr; + CPPInstance *instance = nullptr; + CPPInstance *raw_instance = nullptr; CPPFunctionGroup *fgroup = decl->as_function_group(); CPPFunctionGroup::Instances::iterator it; for (it = fgroup->_instances.begin(); it != fgroup->_instances.end(); ++it) { - if ((*it)->_type == NULL) { + if ((*it)->_type == nullptr) { continue; } CPPFunctionType *ftype = (*it)->_type->as_function_type(); - if (ftype == NULL || ftype->_parameters == NULL) { + if (ftype == nullptr || ftype->_parameters == nullptr) { continue; } @@ -2052,7 +2052,7 @@ get_literal(int token, YYLTYPE loc, const string &str, const YYSTYPE &value) { } CPPInstance *param = params[0]; - if (param == NULL || param->_type == NULL) { + if (param == nullptr || param->_type == nullptr) { continue; } @@ -2086,11 +2086,11 @@ get_literal(int token, YYLTYPE loc, const string &str, const YYSTYPE &value) { } else if (type->get_subtype() == CPPDeclaration::ST_pointer) { // Must be a const pointer. Unwrap it. type = type->as_pointer_type()->_pointing_at; - if (type == NULL || type->get_subtype() != CPPDeclaration::ST_const) { + if (type == nullptr || type->get_subtype() != CPPDeclaration::ST_const) { continue; } type = type->as_const_type()->_wrapped_around; - if (type == NULL || type->get_subtype() != CPPDeclaration::ST_simple) { + if (type == nullptr || type->get_subtype() != CPPDeclaration::ST_simple) { continue; } @@ -2123,19 +2123,19 @@ get_literal(int token, YYLTYPE loc, const string &str, const YYSTYPE &value) { } YYSTYPE result; - if (instance != NULL) { + if (instance != nullptr) { result.u.expr = new CPPExpression(CPPExpression::literal(expr, instance)); return CPPToken(CUSTOM_LITERAL, loc, str, result); } - if ((token == REAL || token == INTEGER) && raw_instance != NULL) { + if ((token == REAL || token == INTEGER) && raw_instance != nullptr) { // For numeric constants, we can fall back to a raw literal operator. result.u.expr = new CPPExpression(CPPExpression::raw_literal(str, instance)); return CPPToken(CUSTOM_LITERAL, loc, str, result); } error(fgroup->_name + " has no suitable overload for literal of this type", loc); - result.u.expr = NULL; + result.u.expr = nullptr; return CPPToken(CUSTOM_LITERAL, loc, str, result); } @@ -2492,7 +2492,7 @@ get_number(int c) { loc.last_column = get_col_number(); YYSTYPE result; - result.u.integer = strtol(num.c_str(), (char **)NULL, 16); + result.u.integer = strtol(num.c_str(), nullptr, 16); return get_literal(INTEGER, loc, num, result); @@ -2511,7 +2511,7 @@ get_number(int c) { loc.last_column = get_col_number(); YYSTYPE result; - result.u.integer = strtol(bin.c_str(), (char **)NULL, 2); + result.u.integer = strtol(bin.c_str(), nullptr, 2); return get_literal(INTEGER, loc, bin, result); } @@ -2552,7 +2552,7 @@ get_number(int c) { loc.last_column = get_col_number(); YYSTYPE result; - result.u.real = pstrtod(num.c_str(), (char **)NULL); + result.u.real = (long double)pstrtod(num.c_str(), nullptr); return get_literal(REAL, loc, num, result); } @@ -2568,11 +2568,11 @@ get_number(int c) { // A leading zero implies an octal number. strtol() is supposed to be // able to make this distinction by itself, but we'll do it explicitly // just to be sure. - result.u.integer = strtol(num.c_str(), (char **)NULL, 8); + result.u.integer = strtol(num.c_str(), nullptr, 8); } else { // A decimal (base 10) integer. - result.u.integer = strtol(num.c_str(), (char **)NULL, 10); + result.u.integer = strtol(num.c_str(), nullptr, 10); } return get_literal(INTEGER, loc, num, result); @@ -2862,7 +2862,7 @@ bool CPPPreprocessor:: should_ignore_preprocessor() const { Files::const_iterator fi; for (fi = _files.begin(); fi != _files.end(); ++fi) { - if ((*fi)._ignore_manifest != NULL) { + if ((*fi)._ignore_manifest != nullptr) { return true; } } @@ -2960,7 +2960,7 @@ nested_parse_template_instantiation(CPPTemplateScope *scope) { indent(cerr, _files.size() * 2) << "Beginning nested parse\n"; #endif - assert(scope != NULL); + assert(scope != nullptr); State old_state = _state; int old_nesting = _paren_nesting; @@ -2994,7 +2994,7 @@ nested_parse_template_instantiation(CPPTemplateScope *scope) { // Parse a typename template parameter. _saved_tokens.push_back(CPPToken(START_TYPE)); CPPType *type = ::parse_type(this, current_scope, global_scope); - if (type == NULL) { + if (type == nullptr) { loc.last_line = get_line_number(); loc.last_column = get_col_number() - 1; warning("invalid type", loc); @@ -3011,7 +3011,7 @@ nested_parse_template_instantiation(CPPTemplateScope *scope) { // Parse a constant expression template parameter. _saved_tokens.push_back(CPPToken(START_CONST_EXPR)); CPPExpression *expr = parse_const_expr(this, current_scope, global_scope); - if (expr == NULL) { + if (expr == nullptr) { loc.last_line = get_line_number(); loc.last_column = get_col_number() - 1; warning("invalid expression", loc); diff --git a/dtool/src/cppparser/cppPreprocessor.h b/dtool/src/cppparser/cppPreprocessor.h index 02f3715339..3102386fee 100644 --- a/dtool/src/cppparser/cppPreprocessor.h +++ b/dtool/src/cppparser/cppPreprocessor.h @@ -57,10 +57,10 @@ public: int _token_index; #endif - void warning(const string &message); - void warning(const string &message, const YYLTYPE &loc); - void error(const string &message); - void error(const string &message, const YYLTYPE &loc); + void warning(const std::string &message); + void warning(const std::string &message, const YYLTYPE &loc); + void error(const std::string &message); + void error(const std::string &message, const YYLTYPE &loc); void show_line(const YYLTYPE &loc); CPPCommentBlock *get_comment_before(int line, CPPFile file); @@ -69,11 +69,11 @@ public: int get_warning_count() const; int get_error_count() const; - typedef map Manifests; + typedef std::map Manifests; Manifests _manifests; typedef pvector ManifestStack; - map _manifest_stack; + std::map _manifest_stack; pvector _quote_include_kind; DSearchPath _quote_include_path; @@ -82,14 +82,14 @@ public: CPPComments _comments; - typedef set ParsedFiles; + typedef std::set ParsedFiles; ParsedFiles _parsed_files; - typedef set Includes; + typedef std::set Includes; Includes _quote_includes; Includes _angle_includes; - set _explicit_files; + std::set _explicit_files; // This is normally true, to indicate that the preprocessor should decode // identifiers like foo::bar into a single IDENTIFIER, @@ -109,14 +109,14 @@ public: protected: bool init_cpp(const CPPFile &file); - bool init_const_expr(const string &expr); - bool init_type(const string &type); + bool init_const_expr(const std::string &expr); + bool init_type(const std::string &type); bool push_file(const CPPFile &file); - bool push_string(const string &input, bool lock_position); + bool push_string(const std::string &input, bool lock_position); - string expand_manifests(const string &input_expr, bool expand_undefined, + std::string expand_manifests(const std::string &input_expr, bool expand_undefined, const YYLTYPE &loc); - CPPExpression *parse_expr(const string &expr, CPPScope *current_scope, + CPPExpression *parse_expr(const std::string &expr, CPPScope *current_scope, CPPScope *global_scope, const YYLTYPE &loc); private: @@ -130,43 +130,43 @@ private: int skip_digit_separator(int c); int process_directive(int c); - int get_preprocessor_command(int c, string &command); - int get_preprocessor_args(int c, string &args); + int get_preprocessor_command(int c, std::string &command); + int get_preprocessor_args(int c, std::string &args); - void handle_define_directive(const string &args, const YYLTYPE &loc); - void handle_undef_directive(const string &args, const YYLTYPE &loc); - void handle_ifdef_directive(const string &args, const YYLTYPE &loc); - void handle_ifndef_directive(const string &args, const YYLTYPE &loc); - void handle_if_directive(const string &args, const YYLTYPE &loc); - void handle_include_directive(const string &args, const YYLTYPE &loc); - void handle_pragma_directive(const string &args, const YYLTYPE &loc); - void handle_error_directive(const string &args, const YYLTYPE &loc); + void handle_define_directive(const std::string &args, const YYLTYPE &loc); + void handle_undef_directive(const std::string &args, const YYLTYPE &loc); + void handle_ifdef_directive(const std::string &args, const YYLTYPE &loc); + void handle_ifndef_directive(const std::string &args, const YYLTYPE &loc); + void handle_if_directive(const std::string &args, const YYLTYPE &loc); + void handle_include_directive(const std::string &args, const YYLTYPE &loc); + void handle_pragma_directive(const std::string &args, const YYLTYPE &loc); + void handle_error_directive(const std::string &args, const YYLTYPE &loc); void skip_false_if_block(bool consider_elifs); - bool is_manifest_defined(const string &manifest_name); + bool is_manifest_defined(const std::string &manifest_name); bool find_include(Filename &filename, bool angle_quotes, CPPFile::Source &source); CPPToken get_quoted_char(int c); CPPToken get_quoted_string(int c); CPPToken get_identifier(int c); - CPPToken get_literal(int token, YYLTYPE loc, const string &str, + CPPToken get_literal(int token, YYLTYPE loc, const std::string &str, const YYSTYPE &result = YYSTYPE()); CPPToken expand_manifest(const CPPManifest *manifest); - void extract_manifest_args(const string &name, int num_args, + void extract_manifest_args(const std::string &name, int num_args, int va_arg, vector_string &args); - void expand_defined_function(string &expr, size_t q, size_t &p); - void expand_has_include_function(string &expr, size_t q, size_t &p, YYLTYPE loc); - void expand_manifest_inline(string &expr, size_t q, size_t &p, + void expand_defined_function(std::string &expr, size_t q, size_t &p); + void expand_has_include_function(std::string &expr, size_t q, size_t &p, YYLTYPE loc); + void expand_manifest_inline(std::string &expr, size_t q, size_t &p, const CPPManifest *manifest); - void extract_manifest_args_inline(const string &name, int num_args, + void extract_manifest_args_inline(const std::string &name, int num_args, int va_arg, vector_string &args, - const string &expr, size_t &p); + const std::string &expr, size_t &p); CPPToken get_number(int c); - static int check_keyword(const string &name); + static int check_keyword(const std::string &name); int scan_escape_sequence(int c); - string scan_quoted(int c); - string scan_raw(int c); + std::string scan_quoted(int c); + std::string scan_raw(int c); bool should_ignore_manifest(const CPPManifest *manifest) const; bool should_ignore_preprocessor() const; @@ -186,14 +186,14 @@ private: ~InputFile(); bool open(const CPPFile &file); - bool connect_input(const string &input); + bool connect_input(const std::string &input); int get(); int peek(); const CPPManifest *_ignore_manifest; CPPFile _file; - string _input; - istream *_in; + std::string _input; + std::istream *_in; int _line_number; int _col_number; int _next_line_number; @@ -204,7 +204,7 @@ private: // This must be a list and not a vector because we don't have a good copy // constructor defined for InputFile. - typedef list Files; + typedef std::list Files; Files _files; enum State { @@ -222,7 +222,7 @@ private: bool _last_cpp_comment; bool _save_comments; - vector _saved_tokens; + std::vector _saved_tokens; int _warning_count; int _error_count; diff --git a/dtool/src/cppparser/cppReferenceType.cxx b/dtool/src/cppparser/cppReferenceType.cxx index bbb1f1a50e..42526789a3 100644 --- a/dtool/src/cppparser/cppReferenceType.cxx +++ b/dtool/src/cppparser/cppReferenceType.cxx @@ -114,7 +114,7 @@ is_constructible(const CPPType *given_type) const { const CPPType *b; CPPReferenceType *ref_type = ((CPPType *)given_type)->as_reference_type(); - if (ref_type != NULL) { + if (ref_type != nullptr) { if (ref_type->_value_category == VC_rvalue) { return is_constructible(ref_type->_pointing_at); } @@ -159,7 +159,7 @@ is_constructible(const CPPType *given_type) const { // Can initialize from derived class pointer. const CPPStructType *a_struct = a->as_struct_type(); const CPPStructType *b_struct = b->as_struct_type(); - if (a_struct != NULL && b_struct != NULL) { + if (a_struct != nullptr && b_struct != nullptr) { return a_struct->is_base_of(b_struct); } @@ -199,7 +199,7 @@ is_destructible() const { bool CPPReferenceType:: is_equivalent(const CPPType &other) const { const CPPReferenceType *ot = ((CPPType *)&other)->as_reference_type(); - if (ot == (CPPReferenceType *)NULL) { + if (ot == nullptr) { return CPPType::is_equivalent(other); } @@ -210,7 +210,7 @@ is_equivalent(const CPPType &other) const { * */ void CPPReferenceType:: -output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { +output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const { /* _pointing_at->output(out, indent_level, scope, complete); out << " &"; @@ -224,9 +224,9 @@ output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { * have special exceptions. */ void CPPReferenceType:: -output_instance(ostream &out, int indent_level, CPPScope *scope, - bool complete, const string &prename, - const string &name) const { +output_instance(std::ostream &out, int indent_level, CPPScope *scope, + bool complete, const std::string &prename, + const std::string &name) const { if (_value_category == VC_rvalue) { _pointing_at->output_instance(out, indent_level, scope, complete, @@ -261,7 +261,7 @@ as_reference_type() { bool CPPReferenceType:: is_equal(const CPPDeclaration *other) const { const CPPReferenceType *ot = ((CPPDeclaration *)other)->as_reference_type(); - assert(ot != NULL); + assert(ot != nullptr); return (_pointing_at == ot->_pointing_at) && (_value_category == ot->_value_category); @@ -275,7 +275,7 @@ is_equal(const CPPDeclaration *other) const { bool CPPReferenceType:: is_less(const CPPDeclaration *other) const { const CPPReferenceType *ot = ((CPPDeclaration *)other)->as_reference_type(); - assert(ot != NULL); + assert(ot != nullptr); if (_value_category != ot->_value_category) { return (_value_category < ot->_value_category); diff --git a/dtool/src/cppparser/cppReferenceType.h b/dtool/src/cppparser/cppReferenceType.h index 89feba8d2c..273f645377 100644 --- a/dtool/src/cppparser/cppReferenceType.h +++ b/dtool/src/cppparser/cppReferenceType.h @@ -50,12 +50,12 @@ public: virtual bool is_destructible() const; virtual bool is_equivalent(const CPPType &other) const; - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; - virtual void output_instance(ostream &out, int indent_level, + virtual void output_instance(std::ostream &out, int indent_level, CPPScope *scope, - bool complete, const string &prename, - const string &name) const; + bool complete, const std::string &prename, + const std::string &name) const; virtual SubType get_subtype() const; diff --git a/dtool/src/cppparser/cppScope.cxx b/dtool/src/cppparser/cppScope.cxx index a873cfa3cf..af6404e4dd 100644 --- a/dtool/src/cppparser/cppScope.cxx +++ b/dtool/src/cppparser/cppScope.cxx @@ -33,6 +33,11 @@ #include "cppBisonDefs.h" #include "indent.h" +using std::ostream; +using std::ostringstream; +using std::pair; +using std::string; + /** * */ @@ -43,7 +48,7 @@ CPPScope(CPPScope *parent_scope, _parent_scope(parent_scope), _current_vis(starting_vis) { - _struct_type = NULL; + _struct_type = nullptr; _is_fully_specified = false; _fully_specified_known = false; _is_fully_specified_recursive_protect = false; @@ -111,7 +116,7 @@ add_declaration(CPPDeclaration *decl, CPPScope *global_scope, // that appeared preceding this particular declaration; they might be // relevant to the declaration. - if (decl->_leading_comment == (CPPCommentBlock *)NULL) { + if (decl->_leading_comment == nullptr) { decl->_leading_comment = preprocessor->get_comment_before(pos.first_line, pos.file); } @@ -151,13 +156,13 @@ define_typedef_type(CPPTypedefType *type, CPPPreprocessor *error_sink) { // We don't do redefinitions of typedefs. But we don't complain as long // as this is actually a typedef to the previous definition. if (other_type != type->_type && - (other_td == NULL || !other_td->_type->is_equivalent(*type->_type))) { + (other_td == nullptr || !other_td->_type->is_equivalent(*type->_type))) { - if (error_sink != NULL) { + if (error_sink != nullptr) { ostringstream errstr; - type->output(errstr, 0, NULL, false); + type->output(errstr, 0, nullptr, false); errstr << " has conflicting declaration as "; - other_type->output(errstr, 0, NULL, true); + other_type->output(errstr, 0, nullptr, true); error_sink->error(errstr.str(), type->_ident->_loc); error_sink->error("previous definition is here", other_td->_ident->_loc); @@ -185,7 +190,7 @@ define_typedef_type(CPPTypedefType *type, CPPPreprocessor *error_sink) { // incomplete, replace it. CPPDeclaration *old_templ = (*result.first).second; CPPType *old_templ_type = old_templ->as_type(); - if (old_templ_type == NULL || old_templ_type->is_incomplete()) { + if (old_templ_type == nullptr || old_templ_type->is_incomplete()) { // The previous template definition was incomplete, maybe a forward // reference; replace it with the good one. (*result.first).second = type; @@ -199,7 +204,7 @@ define_typedef_type(CPPTypedefType *type, CPPPreprocessor *error_sink) { */ void CPPScope:: define_extension_type(CPPExtensionType *type, CPPPreprocessor *error_sink) { - assert(type != NULL); + assert(type != nullptr); string name = type->get_local_name(this); if (name.empty()) { return; @@ -239,13 +244,13 @@ define_extension_type(CPPExtensionType *type, CPPPreprocessor *error_sink) { CPPExtensionType *other_ext = other_type->as_extension_type(); if (other_ext->_type != type->_type) { - if (error_sink != NULL) { + if (error_sink != nullptr) { ostringstream errstr; errstr << type->_type << " " << type->get_fully_scoped_name() << " was previously declared as " << other_ext->_type; error_sink->error(errstr.str(), type->_ident->_loc); - if (other_ext->_ident != NULL) { + if (other_ext->_ident != nullptr) { error_sink->error("previous declaration is here", other_ext->_ident->_loc); } @@ -258,20 +263,20 @@ define_extension_type(CPPExtensionType *type, CPPPreprocessor *error_sink) { // Error out if the declaration is different than the previous one. if (other_type != type && - (other_td == NULL || other_td->_type != type)) { + (other_td == nullptr || other_td->_type != type)) { - if (error_sink != NULL) { + if (error_sink != nullptr) { ostringstream errstr; if (!cppparser_output_class_keyword) { errstr << type->_type << " "; } - type->output(errstr, 0, NULL, false); + type->output(errstr, 0, nullptr, false); errstr << " has conflicting definition as "; - other_type->output(errstr, 0, NULL, true); + other_type->output(errstr, 0, nullptr, true); error_sink->error(errstr.str(), type->_ident->_loc); CPPExtensionType *other_ext = other_type->as_extension_type(); - if (other_ext != NULL && other_ext->_ident != NULL) { + if (other_ext != nullptr && other_ext->_ident != nullptr) { error_sink->error("previous definition is here", other_ext->_ident->_loc); } @@ -297,7 +302,7 @@ define_extension_type(CPPExtensionType *type, CPPPreprocessor *error_sink) { // incomplete, replace it. CPPDeclaration *old_templ = (*result.first).second; CPPType *old_templ_type = old_templ->as_type(); - if (old_templ_type == NULL || old_templ_type->is_incomplete()) { + if (old_templ_type == nullptr || old_templ_type->is_incomplete()) { // The previous template definition was incomplete, maybe a forward // reference; replace it with the good one. (*result.first).second = type; @@ -330,19 +335,19 @@ add_using(CPPUsing *using_decl, CPPScope *global_scope, if (using_decl->_full_namespace) { CPPScope *scope = using_decl->_ident->find_scope(this, global_scope); - if (scope != NULL) { + if (scope != nullptr) { _using.insert(scope); } else { - if (error_sink != NULL) { + if (error_sink != nullptr) { error_sink->warning("Attempt to use undefined namespace: " + using_decl->_ident->get_fully_scoped_name(), using_decl->_ident->_loc); } } } else { CPPDeclaration *decl = using_decl->_ident->find_symbol(this, global_scope); - if (decl != NULL) { + if (decl != nullptr) { handle_declaration(decl, global_scope, error_sink); } else { - if (error_sink != NULL) { + if (error_sink != nullptr) { error_sink->warning("Attempt to use unknown symbol: " + using_decl->_ident->get_fully_scoped_name(), using_decl->_ident->_loc); } } @@ -368,7 +373,7 @@ is_fully_specified() const { bool specified = true; - if (_parent_scope != NULL && !_parent_scope->is_fully_specified()) { + if (_parent_scope != nullptr && !_parent_scope->is_fully_specified()) { specified = false; } @@ -397,9 +402,9 @@ instantiate(const CPPTemplateParameterList *actual_params, CPPPreprocessor *error_sink) const { CPPScope *this_scope = (CPPScope *)this; - if (_parent_scope == NULL || - _parent_scope->as_template_scope() == NULL) { - if (error_sink != NULL) { + if (_parent_scope == nullptr || + _parent_scope->as_template_scope() == nullptr) { + if (error_sink != nullptr) { error_sink->warning("Ignoring template parameters for scope " + get_local_name()); } @@ -448,7 +453,7 @@ instantiate(const CPPTemplateParameterList *actual_params, ++pi) { CPPDeclaration *decl = (*pi); CPPClassTemplateParameter *ctp = decl->as_class_template_parameter(); - if (ctp != NULL) { + if (ctp != nullptr) { // CPPTypedefType *td = new CPPTypedefType(ctp, ctp->_ident); // scope->_typedefs.insert(Typedefs::value_type // (ctp->_ident->get_local_name(), td)); @@ -487,8 +492,8 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, CPPScope *rep = new CPPScope(current_scope, _name, V_public); bool anything_changed; - if (_parent_scope != NULL && - _parent_scope->as_template_scope() != NULL) { + if (_parent_scope != nullptr && + _parent_scope->as_template_scope() != nullptr) { // If the parent of this scope is a template scope--e.g. this scope has // template parameters--then we must first remove any of the template // parameters from the subst list. These will later get substituted @@ -529,31 +534,31 @@ find_type(const string &name, bool recurse) const { Using::const_iterator ui; for (ui = _using.begin(); ui != _using.end(); ++ui) { CPPType *type = (*ui)->find_type(name, false); - if (type != NULL) { + if (type != nullptr) { return type; } } - if (_struct_type != NULL) { + if (_struct_type != nullptr) { CPPStructType::Derivation::const_iterator di; for (di = _struct_type->_derivation.begin(); di != _struct_type->_derivation.end(); ++di) { CPPStructType *st = (*di)._base->as_struct_type(); - if (st != NULL) { + if (st != nullptr) { CPPType *type = st->_scope->find_type(name, false); - if (type != NULL) { + if (type != nullptr) { return type; } } } } - if (recurse && _parent_scope != NULL) { + if (recurse && _parent_scope != nullptr) { return _parent_scope->find_type(name); } - return NULL; + return nullptr; } /** @@ -573,97 +578,105 @@ find_type(const string &name, CPPDeclaration::SubstDecl &subst, Using::const_iterator ui; for (ui = _using.begin(); ui != _using.end(); ++ui) { CPPType *type = (*ui)->find_type(name, subst, global_scope, false); - if (type != NULL) { + if (type != nullptr) { return type; } } - if (_struct_type != NULL) { + if (_struct_type != nullptr) { CPPStructType::Derivation::const_iterator di; for (di = _struct_type->_derivation.begin(); di != _struct_type->_derivation.end(); ++di) { CPPStructType *st = (*di)._base->as_struct_type(); - if (st != NULL) { + if (st != nullptr) { CPPType *type = st->_scope->find_type(name, subst, global_scope, false); - if (type != NULL) { + if (type != nullptr) { return type; } } } } - if (recurse && _parent_scope != NULL) { + if (recurse && _parent_scope != nullptr) { return _parent_scope->find_type(name, subst, global_scope); } - return NULL; + return nullptr; } /** * */ CPPScope *CPPScope:: -find_scope(const string &name, bool recurse) const { +find_scope(const string &name, CPPScope *global_scope, bool recurse) const { Namespaces::const_iterator ni = _namespaces.find(name); if (ni != _namespaces.end()) { return (*ni).second->get_scope(); } - CPPType *type = (CPPType *)NULL; + CPPType *type = nullptr; Types::const_iterator ti; ti = _types.find(name); if (ti != _types.end()) { type = (*ti).second; - // Resolve if this is a typedef or const. + // Resolve if this is a typedef or const, or a TBD type. while (type->get_subtype() == CPPDeclaration::ST_const || - type->get_subtype() == CPPDeclaration::ST_typedef) { - if (type->as_typedef_type() != (CPPType *)NULL) { + type->get_subtype() == CPPDeclaration::ST_typedef || + type->get_subtype() == CPPDeclaration::ST_tbd) { + if (type->as_typedef_type() != nullptr) { type = type->as_typedef_type()->_type; - } else { + } else if (type->as_const_type() != nullptr) { type = type->as_const_type()->_wrapped_around; + } else { + CPPType *new_type = type->resolve_type((CPPScope *)this, global_scope); + if (new_type != type) { + type = new_type; + } else { + break; + } } } - } else if (_struct_type != NULL) { + } else if (_struct_type != nullptr) { CPPStructType::Derivation::const_iterator di; for (di = _struct_type->_derivation.begin(); di != _struct_type->_derivation.end(); ++di) { CPPStructType *st = (*di)._base->as_struct_type(); - if (st != NULL) { + if (st != nullptr) { type = st->_scope->find_type(name, false); } } } - if (type != NULL) { + if (type != nullptr) { CPPStructType *st = type->as_struct_type(); - if (st != NULL) { + if (st != nullptr) { return st->_scope; } CPPEnumType *et = type->as_enum_type(); - if (et != NULL) { + if (et != nullptr) { return et->_scope; } } Using::const_iterator ui; for (ui = _using.begin(); ui != _using.end(); ++ui) { - CPPScope *scope = (*ui)->find_scope(name, false); - if (scope != NULL) { + CPPScope *scope = (*ui)->find_scope(name, global_scope, false); + if (scope != nullptr) { return scope; } } - if (recurse && _parent_scope != NULL) { - return _parent_scope->find_scope(name); + if (recurse && _parent_scope != nullptr) { + return _parent_scope->find_scope(name, global_scope); } - return (CPPScope *)NULL; + return nullptr; } /** @@ -673,14 +686,14 @@ CPPScope *CPPScope:: find_scope(const string &name, CPPDeclaration::SubstDecl &subst, CPPScope *global_scope, bool recurse) const { CPPType *type = find_type(name, subst, global_scope, recurse); - if (type == NULL) { - return NULL; + if (type == nullptr) { + return nullptr; } // Resolve if this is a typedef or const. while (type->get_subtype() == CPPDeclaration::ST_const || type->get_subtype() == CPPDeclaration::ST_typedef) { - if (type->as_typedef_type() != (CPPType *)NULL) { + if (type->as_typedef_type() != nullptr) { type = type->as_typedef_type()->_type; } else { type = type->as_const_type()->_wrapped_around; @@ -688,16 +701,16 @@ find_scope(const string &name, CPPDeclaration::SubstDecl &subst, } CPPStructType *st = type->as_struct_type(); - if (st != NULL) { + if (st != nullptr) { return st->_scope; } CPPEnumType *et = type->as_enum_type(); - if (et != NULL) { + if (et != nullptr) { return et->_scope; } - return NULL; + return nullptr; } /** @@ -705,7 +718,7 @@ find_scope(const string &name, CPPDeclaration::SubstDecl &subst, */ CPPDeclaration *CPPScope:: find_symbol(const string &name, bool recurse) const { - if (_struct_type != NULL && name == get_simple_name()) { + if (_struct_type != nullptr && name == get_simple_name()) { return _struct_type; } @@ -735,31 +748,31 @@ find_symbol(const string &name, bool recurse) const { Using::const_iterator ui; for (ui = _using.begin(); ui != _using.end(); ++ui) { CPPDeclaration *decl = (*ui)->find_symbol(name, false); - if (decl != NULL) { + if (decl != nullptr) { return decl; } } - if (_struct_type != NULL) { + if (_struct_type != nullptr) { CPPStructType::Derivation::const_iterator di; for (di = _struct_type->_derivation.begin(); di != _struct_type->_derivation.end(); ++di) { CPPStructType *st = (*di)._base->as_struct_type(); - if (st != NULL) { + if (st != nullptr) { CPPDeclaration *decl = st->_scope->find_symbol(name, false); - if (decl != NULL) { + if (decl != nullptr) { return decl; } } } } - if (recurse && _parent_scope != NULL) { + if (recurse && _parent_scope != nullptr) { return _parent_scope->find_symbol(name); } - return NULL; + return nullptr; } /** @@ -776,31 +789,31 @@ find_template(const string &name, bool recurse) const { Using::const_iterator ui; for (ui = _using.begin(); ui != _using.end(); ++ui) { CPPDeclaration *decl = (*ui)->find_template(name, false); - if (decl != NULL) { + if (decl != nullptr) { return decl; } } - if (_struct_type != NULL) { + if (_struct_type != nullptr) { CPPStructType::Derivation::const_iterator di; for (di = _struct_type->_derivation.begin(); di != _struct_type->_derivation.end(); ++di) { CPPStructType *st = (*di)._base->as_struct_type(); - if (st != NULL) { + if (st != nullptr) { CPPDeclaration *decl = st->_scope->find_template(name, false); - if (decl != NULL) { + if (decl != nullptr) { return decl; } } } } - if (recurse && _parent_scope != NULL) { + if (recurse && _parent_scope != nullptr) { return _parent_scope->find_template(name); } - return NULL; + return nullptr; } /** @@ -827,7 +840,7 @@ get_local_name(CPPScope *scope) const { } */ - if (scope != NULL && _parent_scope != NULL/* && _parent_scope != scope*/) { + if (scope != nullptr && _parent_scope != nullptr/* && _parent_scope != scope*/) { string parent_scope_name = _parent_scope->get_local_name(scope); if (parent_scope_name.empty()) { return _name.get_name_with_templ(); @@ -851,7 +864,7 @@ get_fully_scoped_name() const { } */ - if (_parent_scope != NULL) { + if (_parent_scope != nullptr) { return _parent_scope->get_fully_scoped_name() + "::" + _name.get_name_with_templ(); } else { @@ -865,7 +878,7 @@ get_fully_scoped_name() const { void CPPScope:: output(ostream &out, CPPScope *scope) const { // out << get_local_name(scope); - if (_parent_scope != NULL && _parent_scope != scope) { + if (_parent_scope != nullptr && _parent_scope != scope) { _parent_scope->output(out, scope); out << "::"; } @@ -887,7 +900,7 @@ write(ostream &out, int indent_level, CPPScope *scope) const { } bool complete = false; - if (cd->as_type() != NULL || cd->as_namespace() != NULL) { + if (cd->as_type() != nullptr || cd->as_namespace() != nullptr) { complete = true; } @@ -906,10 +919,10 @@ get_template_scope() { if (as_template_scope()) { return as_template_scope(); } - if (_parent_scope != NULL) { + if (_parent_scope != nullptr) { return _parent_scope->get_template_scope(); } - return (CPPTemplateScope *)NULL; + return nullptr; } /** @@ -917,7 +930,7 @@ get_template_scope() { */ CPPTemplateScope *CPPScope:: as_template_scope() { - return (CPPTemplateScope *)NULL; + return nullptr; } /** @@ -933,9 +946,9 @@ copy_substitute_decl(CPPScope *to_scope, CPPDeclaration::SubstDecl &subst, CPPScope *global_scope) const { bool anything_changed = false; - if (_struct_type != NULL) { - CPPScope *native_scope = (CPPScope *)NULL; - if (_struct_type->_ident != (CPPIdentifier *)NULL) { + if (_struct_type != nullptr) { + CPPScope *native_scope = nullptr; + if (_struct_type->_ident != nullptr) { native_scope = _struct_type->_ident->_native_scope; } to_scope->_struct_type = @@ -975,9 +988,9 @@ copy_substitute_decl(CPPScope *to_scope, CPPDeclaration::SubstDecl &subst, CPPType *source_type = (*ei).second; CPPDeclaration *decl = source_type->substitute_decl(subst, to_scope, global_scope); - assert(decl != NULL); + assert(decl != nullptr); CPPType *new_type = decl->as_type(); - assert(new_type != NULL); + assert(new_type != nullptr); to_scope->_structs.insert(ExtensionTypes::value_type(name, new_type)); if (new_type != source_type) { anything_changed = true; @@ -988,9 +1001,9 @@ copy_substitute_decl(CPPScope *to_scope, CPPDeclaration::SubstDecl &subst, CPPType *source_type = (*ei).second; CPPDeclaration *decl = source_type->substitute_decl(subst, to_scope, global_scope); - assert(decl != NULL); + assert(decl != nullptr); CPPType *new_type = decl->as_type(); - assert(new_type != NULL); + assert(new_type != nullptr); to_scope->_classes.insert(ExtensionTypes::value_type(name, new_type)); if (new_type != source_type) { anything_changed = true; @@ -1001,9 +1014,9 @@ copy_substitute_decl(CPPScope *to_scope, CPPDeclaration::SubstDecl &subst, CPPType *source_type = (*ei).second; CPPDeclaration *decl = source_type->substitute_decl(subst, to_scope, global_scope); - assert(decl != NULL); + assert(decl != nullptr); CPPType *new_type = decl->as_type(); - assert(new_type != NULL); + assert(new_type != nullptr); to_scope->_unions.insert(ExtensionTypes::value_type(name, new_type)); if (new_type != source_type) { anything_changed = true; @@ -1014,9 +1027,9 @@ copy_substitute_decl(CPPScope *to_scope, CPPDeclaration::SubstDecl &subst, CPPType *source_type = (*ei).second; CPPDeclaration *decl = source_type->substitute_decl(subst, to_scope, global_scope); - assert(decl != NULL); + assert(decl != nullptr); CPPType *new_type = decl->as_type(); - assert(new_type != NULL); + assert(new_type != nullptr); to_scope->_enums.insert(ExtensionTypes::value_type(name, new_type)); if (new_type != source_type) { anything_changed = true; @@ -1028,7 +1041,7 @@ copy_substitute_decl(CPPScope *to_scope, CPPDeclaration::SubstDecl &subst, string name = fgroup->_name; CPPFunctionGroup *&to_fgroup = to_scope->_functions[name]; - if (to_fgroup == (CPPFunctionGroup *)NULL) { + if (to_fgroup == nullptr) { to_fgroup = new CPPFunctionGroup(name); } @@ -1095,30 +1108,30 @@ void CPPScope:: handle_declaration(CPPDeclaration *decl, CPPScope *global_scope, CPPPreprocessor *error_sink) { CPPTypedefType *def = decl->as_typedef_type(); - if (def != NULL) { + if (def != nullptr) { define_typedef_type(def, error_sink); CPPExtensionType *et = def->_type->as_extension_type(); - if (et != NULL) { + if (et != nullptr) { define_extension_type(et, error_sink); } return; } CPPTypeDeclaration *typedecl = decl->as_type_declaration(); - if (typedecl != (CPPTypeDeclaration *)NULL) { + if (typedecl != nullptr) { CPPExtensionType *et = typedecl->_type->as_extension_type(); - if (et != NULL) { + if (et != nullptr) { define_extension_type(et, error_sink); } return; } CPPInstance *inst = decl->as_instance(); - if (inst != NULL) { + if (inst != nullptr) { inst->check_for_constructor(this, global_scope); - if (inst->_ident != NULL) { + if (inst->_ident != nullptr) { // Not sure if this is the best place to assign this. However, this // fixes a bug with variables in expressions not having the proper // scoping prefix. ~rdb @@ -1153,7 +1166,7 @@ handle_declaration(CPPDeclaration *decl, CPPScope *global_scope, // Don't add a new template definition if we already had one by the // same name in another scope. - if (find_template(name) == NULL) { + if (find_template(name) == nullptr) { _templates.insert(Templates::value_type(name, inst)); } @@ -1170,7 +1183,7 @@ handle_declaration(CPPDeclaration *decl, CPPScope *global_scope, } CPPExtensionType *et = decl->as_extension_type(); - if (et != NULL) { + if (et != nullptr) { define_extension_type(et, error_sink); } } diff --git a/dtool/src/cppparser/cppScope.h b/dtool/src/cppparser/cppScope.h index dc8c7e0295..2631d6097a 100644 --- a/dtool/src/cppparser/cppScope.h +++ b/dtool/src/cppparser/cppScope.h @@ -25,8 +25,6 @@ #include #include -using namespace std; - class CPPType; class CPPDeclaration; class CPPExtensionType; @@ -63,46 +61,47 @@ public: const cppyyltype &pos); virtual void add_enum_value(CPPInstance *inst); virtual void define_typedef_type(CPPTypedefType *type, - CPPPreprocessor *error_sink = NULL); + CPPPreprocessor *error_sink = nullptr); virtual void define_extension_type(CPPExtensionType *type, - CPPPreprocessor *error_sink = NULL); + CPPPreprocessor *error_sink = nullptr); virtual void define_namespace(CPPNamespace *scope); virtual void add_using(CPPUsing *using_decl, CPPScope *global_scope, - CPPPreprocessor *error_sink = NULL); + CPPPreprocessor *error_sink = nullptr); virtual bool is_fully_specified() const; CPPScope * instantiate(const CPPTemplateParameterList *actual_params, CPPScope *current_scope, CPPScope *global_scope, - CPPPreprocessor *error_sink = NULL) const; + CPPPreprocessor *error_sink = nullptr) const; CPPScope * substitute_decl(CPPDeclaration::SubstDecl &subst, CPPScope *current_scope, CPPScope *global_scope) const; - CPPType *find_type(const string &name, bool recurse = true) const; - CPPType *find_type(const string &name, + CPPType *find_type(const std::string &name, bool recurse = true) const; + CPPType *find_type(const std::string &name, CPPDeclaration::SubstDecl &subst, CPPScope *global_scope, bool recurse = true) const; - CPPScope *find_scope(const string &name, bool recurse = true) const; - CPPScope *find_scope(const string &name, + CPPScope *find_scope(const std::string &name, CPPScope *global_scope, + bool recurse = true) const; + CPPScope *find_scope(const std::string &name, CPPDeclaration::SubstDecl &subst, CPPScope *global_scope, bool recurse = true) const; - CPPDeclaration *find_symbol(const string &name, + CPPDeclaration *find_symbol(const std::string &name, bool recurse = true) const; - CPPDeclaration *find_template(const string &name, + CPPDeclaration *find_template(const std::string &name, bool recurse = true) const; - virtual string get_simple_name() const; - virtual string get_local_name(CPPScope *scope = NULL) const; - virtual string get_fully_scoped_name() const; + virtual std::string get_simple_name() const; + virtual std::string get_local_name(CPPScope *scope = nullptr) const; + virtual std::string get_fully_scoped_name() const; - virtual void output(ostream &out, CPPScope *scope) const; - void write(ostream &out, int indent, CPPScope *scope) const; + virtual void output(std::ostream &out, CPPScope *scope) const; + void write(std::ostream &out, int indent, CPPScope *scope) const; CPPTemplateScope *get_template_scope(); virtual CPPTemplateScope *as_template_scope(); @@ -113,33 +112,33 @@ private: CPPScope *global_scope) const; void handle_declaration(CPPDeclaration *decl, CPPScope *global_scope, - CPPPreprocessor *error_sink = NULL); + CPPPreprocessor *error_sink = nullptr); public: - typedef vector Declarations; + typedef std::vector Declarations; Declarations _declarations; - typedef map ExtensionTypes; + typedef std::map ExtensionTypes; ExtensionTypes _structs; ExtensionTypes _classes; ExtensionTypes _unions; ExtensionTypes _enums; - typedef map Namespaces; + typedef std::map Namespaces; Namespaces _namespaces; - typedef map Types; + typedef std::map Types; Types _types; - typedef map Variables; + typedef std::map Variables; Variables _variables; Variables _enum_values; - typedef map Functions; + typedef std::map Functions; Functions _functions; - typedef map Templates; + typedef std::map Templates; Templates _templates; CPPNameComponent _name; - typedef set Using; + typedef std::set Using; Using _using; protected: @@ -148,7 +147,7 @@ protected: CPPVisibility _current_vis; private: - typedef map Instantiations; + typedef std::map Instantiations; Instantiations _instantiations; bool _is_fully_specified; @@ -157,9 +156,9 @@ private: bool _subst_decl_recursive_protect; }; -inline ostream & -operator << (ostream &out, const CPPScope &scope) { - scope.output(out, (CPPScope *)NULL); +inline std::ostream & +operator << (std::ostream &out, const CPPScope &scope) { + scope.output(out, nullptr); return out; } diff --git a/dtool/src/cppparser/cppSimpleType.cxx b/dtool/src/cppparser/cppSimpleType.cxx index 8107e7ee24..1ed364a175 100644 --- a/dtool/src/cppparser/cppSimpleType.cxx +++ b/dtool/src/cppparser/cppSimpleType.cxx @@ -74,7 +74,7 @@ is_constructible(const CPPType *given_type) const { given_type = ((CPPType *)given_type)->remove_reference()->remove_cv(); const CPPSimpleType *simple_type = given_type->as_simple_type(); - if (simple_type == NULL) { + if (simple_type == nullptr) { return given_type->is_enum() && is_arithmetic(); } else if (_type == T_nullptr) { return simple_type->_type == T_nullptr; @@ -133,7 +133,7 @@ is_parameter_expr() const { /** * */ -string CPPSimpleType:: +std::string CPPSimpleType:: get_preferred_name() const { // Simple types always prefer to use their native types. return get_local_name(); @@ -143,7 +143,7 @@ get_preferred_name() const { * */ void CPPSimpleType:: -output(ostream &out, int, CPPScope *, bool) const { +output(std::ostream &out, int, CPPScope *, bool) const { if (_flags & F_unsigned) { out << "unsigned "; } @@ -250,7 +250,7 @@ as_simple_type() { bool CPPSimpleType:: is_equal(const CPPDeclaration *other) const { const CPPSimpleType *ot = ((CPPDeclaration *)other)->as_simple_type(); - assert(ot != NULL); + assert(ot != nullptr); return _type == ot->_type && _flags == ot->_flags; } @@ -263,7 +263,7 @@ is_equal(const CPPDeclaration *other) const { bool CPPSimpleType:: is_less(const CPPDeclaration *other) const { const CPPSimpleType *ot = ((CPPDeclaration *)other)->as_simple_type(); - assert(ot != NULL); + assert(ot != nullptr); if (_type != ot->_type) { return _type < ot->_type; diff --git a/dtool/src/cppparser/cppSimpleType.h b/dtool/src/cppparser/cppSimpleType.h index 850353e9eb..a674374502 100644 --- a/dtool/src/cppparser/cppSimpleType.h +++ b/dtool/src/cppparser/cppSimpleType.h @@ -79,9 +79,9 @@ public: virtual bool is_destructible() const; virtual bool is_parameter_expr() const; - virtual string get_preferred_name() const; + virtual std::string get_preferred_name() const; - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; virtual SubType get_subtype() const; diff --git a/dtool/src/cppparser/cppStructType.cxx b/dtool/src/cppparser/cppStructType.cxx index fda8feaa2b..d0707c4404 100644 --- a/dtool/src/cppparser/cppStructType.cxx +++ b/dtool/src/cppparser/cppStructType.cxx @@ -28,7 +28,7 @@ * */ void CPPStructType::Base:: -output(ostream &out) const { +output(std::ostream &out) const { if (_is_virtual) { out << "virtual "; } @@ -82,15 +82,15 @@ operator = (const CPPStructType ©) { */ void CPPStructType:: append_derivation(CPPType *base, CPPVisibility vis, bool is_virtual) { - if (base != NULL) { + if (base != nullptr) { // Unwrap any typedefs, since we can't inherit from a typedef. CPPTypedefType *def = base->as_typedef_type(); - while (def != NULL) { + while (def != nullptr) { base = def->_type; def = base->as_typedef_type(); } - if (vis == V_unknown && base->as_extension_type() != NULL) { + if (vis == V_unknown && base->as_extension_type() != nullptr) { // Default visibility. if (base->as_extension_type()->_type == T_class) { vis = V_private; @@ -139,7 +139,7 @@ is_base_of(const CPPStructType *other) const { Derivation::const_iterator di; for (di = other->_derivation.begin(); di != other->_derivation.end(); ++di) { const CPPStructType *base = (*di)._base->as_struct_type(); - if (base != NULL && is_base_of(base)) { + if (base != nullptr && is_base_of(base)) { return true; } } @@ -165,7 +165,7 @@ is_empty() const { Derivation::const_iterator di; for (di = _derivation.begin(); di != _derivation.end(); ++di) { CPPStructType *base = (*di)._base->as_struct_type(); - if ((*di)._is_virtual || (base != NULL && !base->is_empty())) { + if ((*di)._is_virtual || (base != nullptr && !base->is_empty())) { return false; } } @@ -174,7 +174,7 @@ is_empty() const { CPPScope::Variables::const_iterator vi; for (vi = _scope->_variables.begin(); vi != _scope->_variables.end(); ++vi) { CPPInstance *instance = (*vi).second; - assert(instance != NULL); + assert(instance != nullptr); if (instance->_storage_class & CPPInstance::SC_static) { // Static members don't count. @@ -206,7 +206,7 @@ is_polymorphic() const { */ bool CPPStructType:: is_standard_layout() const { - assert(_scope != NULL); + assert(_scope != nullptr); CPPVisibility member_vis = V_unknown; @@ -214,7 +214,7 @@ is_standard_layout() const { CPPScope::Variables::const_iterator vi; for (vi = _scope->_variables.begin(); vi != _scope->_variables.end(); ++vi) { CPPInstance *instance = (*vi).second; - assert(instance != NULL); + assert(instance != nullptr); if (instance->_storage_class & CPPInstance::SC_static) { // Static members don't count. @@ -222,7 +222,7 @@ is_standard_layout() const { } // Finally, check if the data member itself is standard layout. - assert(instance->_type != NULL); + assert(instance->_type != nullptr); if (!instance->_type->is_standard_layout()) { return false; } @@ -230,7 +230,7 @@ is_standard_layout() const { if (member_vis == V_unknown) { // The first non-static data member may not be a base class. CPPStructType *struct_type = instance->_type->remove_cv()->as_struct_type(); - if (struct_type != NULL && struct_type->is_base_of(this)) { + if (struct_type != nullptr && struct_type->is_base_of(this)) { return false; } member_vis = instance->_vis; @@ -274,32 +274,32 @@ is_trivial() const { Derivation::const_iterator di; for (di = _derivation.begin(); di != _derivation.end(); ++di) { CPPStructType *base = (*di)._base->as_struct_type(); - if ((*di)._is_virtual || (base != NULL && !base->is_trivial())) { + if ((*di)._is_virtual || (base != nullptr && !base->is_trivial())) { return false; } } - assert(_scope != NULL); + assert(_scope != nullptr); // Make sure all members are trivial. CPPScope::Variables::const_iterator vi; for (vi = _scope->_variables.begin(); vi != _scope->_variables.end(); ++vi) { CPPInstance *instance = (*vi).second; - assert(instance != NULL); + assert(instance != nullptr); if (instance->_storage_class & CPPInstance::SC_static) { // Static members don't count. continue; } - if (instance->_initializer != NULL) { + if (instance->_initializer != nullptr) { // A member with an initializer means the default constructor would // assign a value. This means the type can't be trivial. return false; } // Finally, check if the data member itself is non-trivial. - assert(instance->_type != NULL); + assert(instance->_type != nullptr); if (!instance->_type->is_trivial()) { return false; } @@ -325,9 +325,9 @@ is_trivial() const { continue; } - assert(inst->_type != (CPPType *)NULL); + assert(inst->_type != nullptr); CPPFunctionType *ftype = inst->_type->as_function_type(); - assert(ftype != (CPPFunctionType *)NULL); + assert(ftype != nullptr); if (ftype->_flags & (CPPFunctionType::F_destructor | CPPFunctionType::F_move_constructor | @@ -370,7 +370,7 @@ is_constructible(const CPPType *given_type) const { CPPType *base_type = ((CPPType *)given_type)->remove_reference(); if (is_equivalent(*base_type->remove_cv())) { const CPPReferenceType *ref_type = given_type->as_reference_type(); - if (ref_type == NULL || + if (ref_type == nullptr || ref_type->_value_category == CPPReferenceType::VC_rvalue) { return is_move_constructible(V_public); } else { @@ -384,16 +384,16 @@ is_constructible(const CPPType *given_type) const { // Check for a different constructor. CPPFunctionGroup *fgroup = get_constructor(); - if (fgroup != (CPPFunctionGroup *)NULL) { + if (fgroup != nullptr) { CPPFunctionGroup::Instances::const_iterator ii; for (ii = fgroup->_instances.begin(); ii != fgroup->_instances.end(); ++ii) { CPPInstance *inst = (*ii); - assert(inst->_type != (CPPType *)NULL); + assert(inst->_type != nullptr); CPPFunctionType *ftype = inst->_type->as_function_type(); - assert(ftype != (CPPFunctionType *)NULL); + assert(ftype != nullptr); CPPParameterList *params = ftype->_parameters; if (params->_parameters.size() == 1 && !params->_includes_ellipsis) { @@ -464,7 +464,7 @@ is_default_constructible(CPPVisibility min_vis) const { } CPPInstance *constructor = get_default_constructor(); - if (constructor != (CPPInstance *)NULL) { + if (constructor != nullptr) { // It has a default constructor. if (constructor->_vis > min_vis) { // Inaccessible default constructor. @@ -480,7 +480,7 @@ is_default_constructible(CPPVisibility min_vis) const { } // Does it have constructors at all? If so, no implicit one is generated. - if (get_constructor() != (CPPFunctionGroup *)NULL) { + if (get_constructor() != nullptr) { return false; } @@ -489,7 +489,7 @@ is_default_constructible(CPPVisibility min_vis) const { Derivation::const_iterator di; for (di = _derivation.begin(); di != _derivation.end(); ++di) { CPPStructType *base = (*di)._base->as_struct_type(); - if (base != NULL) { + if (base != nullptr) { if (!base->is_default_constructible(V_protected)) { return false; } @@ -500,14 +500,14 @@ is_default_constructible(CPPVisibility min_vis) const { CPPScope::Variables::const_iterator vi; for (vi = _scope->_variables.begin(); vi != _scope->_variables.end(); ++vi) { CPPInstance *instance = (*vi).second; - assert(instance != NULL); + assert(instance != nullptr); if (instance->_storage_class & CPPInstance::SC_static) { // Static members don't count. continue; } - if (instance->_initializer != (CPPExpression *)NULL) { + if (instance->_initializer != nullptr) { // It has a default value. continue; } @@ -530,7 +530,7 @@ is_copy_constructible(CPPVisibility min_vis) const { } CPPInstance *constructor = get_copy_constructor(); - if (constructor != (CPPInstance *)NULL) { + if (constructor != nullptr) { // It has a copy constructor. if (constructor->_vis > min_vis) { // Inaccessible copy constructor. @@ -545,8 +545,15 @@ is_copy_constructible(CPPVisibility min_vis) const { return true; } + if (get_move_constructor() != nullptr || + get_move_assignment_operator() != nullptr) { + // A user-declared move constructor or move assignment operator means that + // the implicitly-declared copy constructor is deleted. + return false; + } + CPPInstance *destructor = get_destructor(); - if (destructor != (CPPInstance *)NULL) { + if (destructor != nullptr) { if (destructor->_vis > min_vis) { // Inaccessible destructor. return false; @@ -563,7 +570,7 @@ is_copy_constructible(CPPVisibility min_vis) const { Derivation::const_iterator di; for (di = _derivation.begin(); di != _derivation.end(); ++di) { CPPStructType *base = (*di)._base->as_struct_type(); - if (base != NULL) { + if (base != nullptr) { if (!base->is_copy_constructible(V_protected)) { return false; } @@ -574,7 +581,7 @@ is_copy_constructible(CPPVisibility min_vis) const { CPPScope::Variables::const_iterator vi; for (vi = _scope->_variables.begin(); vi != _scope->_variables.end(); ++vi) { CPPInstance *instance = (*vi).second; - assert(instance != NULL); + assert(instance != nullptr); if (instance->_storage_class & CPPInstance::SC_static) { // Static members don't count. @@ -595,7 +602,7 @@ is_copy_constructible(CPPVisibility min_vis) const { bool CPPStructType:: is_move_constructible(CPPVisibility min_vis) const { CPPInstance *constructor = get_move_constructor(); - if (constructor != (CPPInstance *)NULL) { + if (constructor != nullptr) { // It has a user-declared move constructor. if (constructor->_vis > min_vis) { // Inaccessible move constructor. @@ -624,7 +631,7 @@ is_move_constructible(CPPVisibility min_vis) const { bool CPPStructType:: is_copy_assignable(CPPVisibility min_vis) const { CPPInstance *assignment_operator = get_copy_assignment_operator(); - if (assignment_operator != (CPPInstance *)NULL) { + if (assignment_operator != nullptr) { // It has a copy assignment operator. if (assignment_operator->_vis > min_vis) { // Inaccessible copy assignment operator. @@ -653,7 +660,7 @@ is_copy_assignable(CPPVisibility min_vis) const { Derivation::const_iterator di; for (di = _derivation.begin(); di != _derivation.end(); ++di) { CPPStructType *base = (*di)._base->as_struct_type(); - if (base != NULL) { + if (base != nullptr) { if (!base->is_copy_assignable(V_protected)) { return false; } @@ -664,7 +671,7 @@ is_copy_assignable(CPPVisibility min_vis) const { CPPScope::Variables::const_iterator vi; for (vi = _scope->_variables.begin(); vi != _scope->_variables.end(); ++vi) { CPPInstance *instance = (*vi).second; - assert(instance != NULL); + assert(instance != nullptr); if (instance->_storage_class & CPPInstance::SC_static) { // Static members don't count. @@ -686,7 +693,7 @@ is_copy_assignable(CPPVisibility min_vis) const { bool CPPStructType:: is_move_assignable(CPPVisibility min_vis) const { CPPInstance *assignment_operator = get_move_assignment_operator(); - if (assignment_operator != (CPPInstance *)NULL) { + if (assignment_operator != nullptr) { // It has a user-declared move assignment_operator. if (assignment_operator->_vis > min_vis) { // Inaccessible move assignment_operator. @@ -715,7 +722,7 @@ bool CPPStructType:: is_destructible(CPPVisibility min_vis) const { // Do we have an explicit destructor? CPPInstance *destructor = get_destructor(); - if (destructor != (CPPInstance *)NULL) { + if (destructor != nullptr) { if (destructor->_vis > min_vis) { // Yes, but it's inaccessible. return false; @@ -733,18 +740,18 @@ is_destructible(CPPVisibility min_vis) const { Derivation::const_iterator di; for (di = _derivation.begin(); di != _derivation.end(); ++di) { CPPStructType *base = (*di)._base->as_struct_type(); - if (base != NULL && !base->is_destructible(V_protected)) { + if (base != nullptr && !base->is_destructible(V_protected)) { return false; } } - assert(_scope != NULL); + assert(_scope != nullptr); // Make sure all members are destructible. CPPScope::Variables::const_iterator vi; for (vi = _scope->_variables.begin(); vi != _scope->_variables.end(); ++vi) { CPPInstance *instance = (*vi).second; - assert(instance != NULL); + assert(instance != nullptr); if (instance->_storage_class & CPPInstance::SC_static) { // Static members don't count. @@ -752,7 +759,7 @@ is_destructible(CPPVisibility min_vis) const { } // If the data member is not destructible, no go. - assert(instance->_type != NULL); + assert(instance->_type != nullptr); if (!instance->_type->is_destructible()) { return false; } @@ -791,11 +798,11 @@ is_convertible_to(const CPPType *other) const { continue; } - assert(inst->_type != (CPPType *)NULL); + assert(inst->_type != nullptr); CPPFunctionType *ftype = inst->_type->as_function_type(); - assert(ftype != (CPPFunctionType *)NULL); + assert(ftype != nullptr); - if (ftype->_return_type != NULL && + if (ftype->_return_type != nullptr && (ftype->_flags & CPPFunctionType::F_operator_typecast) != 0) { // Yes, this is a typecast operator. Test using the return type. if (ftype->_return_type->is_convertible_to(other)) { @@ -809,7 +816,7 @@ is_convertible_to(const CPPType *other) const { Derivation::const_iterator di; for (di = _derivation.begin(); di != _derivation.end(); ++di) { CPPStructType *base = (*di)._base->as_struct_type(); - if (base != NULL && (*di)._vis <= V_public && !base->is_convertible_to(other)) { + if (base != nullptr && (*di)._vis <= V_public && !base->is_convertible_to(other)) { return true; } } @@ -845,7 +852,7 @@ check_virtual() const { bool CPPStructType:: has_virtual_destructor() const { CPPInstance *destructor = get_destructor(); - if (destructor != NULL) { + if (destructor != nullptr) { if (destructor->_storage_class & CPPInstance::SC_virtual) { return true; } @@ -854,7 +861,7 @@ has_virtual_destructor() const { Derivation::const_iterator di; for (di = _derivation.begin(); di != _derivation.end(); ++di) { CPPStructType *base = (*di)._base->as_struct_type(); - if (base != NULL && base->has_virtual_destructor()) { + if (base != nullptr && base->has_virtual_destructor()) { return true; } } @@ -869,7 +876,7 @@ has_virtual_destructor() const { */ bool CPPStructType:: is_fully_specified() const { - if (_scope != NULL && !_scope->is_fully_specified()) { + if (_scope != nullptr && !_scope->is_fully_specified()) { return false; } return CPPType::is_fully_specified(); @@ -895,7 +902,7 @@ get_constructor() const { if (fi != _scope->_functions.end()) { return fi->second; } else { - return (CPPFunctionGroup *)NULL; + return nullptr; } } @@ -906,8 +913,8 @@ get_constructor() const { CPPInstance *CPPStructType:: get_default_constructor() const { CPPFunctionGroup *fgroup = get_constructor(); - if (fgroup == (CPPFunctionGroup *)NULL) { - return (CPPInstance *)NULL; + if (fgroup == nullptr) { + return nullptr; } CPPFunctionGroup::Instances::const_iterator ii; @@ -915,19 +922,19 @@ get_default_constructor() const { ii != fgroup->_instances.end(); ++ii) { CPPInstance *inst = (*ii); - assert(inst->_type != (CPPType *)NULL); + assert(inst->_type != nullptr); CPPFunctionType *ftype = inst->_type->as_function_type(); - assert(ftype != (CPPFunctionType *)NULL); + assert(ftype != nullptr); if (ftype->_parameters->_parameters.size() == 0 || - ftype->_parameters->_parameters.front()->_initializer != NULL) { + ftype->_parameters->_parameters.front()->_initializer != nullptr) { // It takes 0 parameters (or all parameters have default values). return inst; } } - return (CPPInstance *)NULL; + return nullptr; } /** @@ -937,8 +944,8 @@ get_default_constructor() const { CPPInstance *CPPStructType:: get_copy_constructor() const { CPPFunctionGroup *fgroup = get_constructor(); - if (fgroup == (CPPFunctionGroup *)NULL) { - return (CPPInstance *)NULL; + if (fgroup == nullptr) { + return nullptr; } CPPFunctionGroup::Instances::const_iterator ii; @@ -946,17 +953,17 @@ get_copy_constructor() const { ii != fgroup->_instances.end(); ++ii) { CPPInstance *inst = (*ii); - assert(inst->_type != (CPPType *)NULL); + assert(inst->_type != nullptr); CPPFunctionType *ftype = inst->_type->as_function_type(); - assert(ftype != (CPPFunctionType *)NULL); + assert(ftype != nullptr); if ((ftype->_flags & CPPFunctionType::F_copy_constructor) != 0) { return inst; } } - return (CPPInstance *)NULL; + return nullptr; } /** @@ -966,8 +973,8 @@ get_copy_constructor() const { CPPInstance *CPPStructType:: get_move_constructor() const { CPPFunctionGroup *fgroup = get_constructor(); - if (fgroup == (CPPFunctionGroup *)NULL) { - return (CPPInstance *)NULL; + if (fgroup == nullptr) { + return nullptr; } CPPFunctionGroup::Instances::const_iterator ii; @@ -975,17 +982,17 @@ get_move_constructor() const { ii != fgroup->_instances.end(); ++ii) { CPPInstance *inst = (*ii); - assert(inst->_type != (CPPType *)NULL); + assert(inst->_type != nullptr); CPPFunctionType *ftype = inst->_type->as_function_type(); - assert(ftype != (CPPFunctionType *)NULL); + assert(ftype != nullptr); if ((ftype->_flags & CPPFunctionType::F_move_constructor) != 0) { return inst; } } - return (CPPInstance *)NULL; + return nullptr; } /** @@ -1000,7 +1007,7 @@ get_assignment_operator() const { if (fi != _scope->_functions.end()) { return fi->second; } else { - return (CPPFunctionGroup *)NULL; + return nullptr; } } @@ -1011,8 +1018,8 @@ get_assignment_operator() const { CPPInstance *CPPStructType:: get_copy_assignment_operator() const { CPPFunctionGroup *fgroup = get_assignment_operator(); - if (fgroup == (CPPFunctionGroup *)NULL) { - return (CPPInstance *)NULL; + if (fgroup == nullptr) { + return nullptr; } CPPFunctionGroup::Instances::const_iterator ii; @@ -1020,17 +1027,17 @@ get_copy_assignment_operator() const { ii != fgroup->_instances.end(); ++ii) { CPPInstance *inst = (*ii); - assert(inst->_type != (CPPType *)NULL); + assert(inst->_type != nullptr); CPPFunctionType *ftype = inst->_type->as_function_type(); - assert(ftype != (CPPFunctionType *)NULL); + assert(ftype != nullptr); if ((ftype->_flags & CPPFunctionType::F_copy_assignment_operator) != 0) { return inst; } } - return (CPPInstance *)NULL; + return nullptr; } /** @@ -1040,8 +1047,8 @@ get_copy_assignment_operator() const { CPPInstance *CPPStructType:: get_move_assignment_operator() const { CPPFunctionGroup *fgroup = get_assignment_operator(); - if (fgroup == (CPPFunctionGroup *)NULL) { - return (CPPInstance *)NULL; + if (fgroup == nullptr) { + return nullptr; } CPPFunctionGroup::Instances::const_iterator ii; @@ -1049,17 +1056,17 @@ get_move_assignment_operator() const { ii != fgroup->_instances.end(); ++ii) { CPPInstance *inst = (*ii); - assert(inst->_type != (CPPType *)NULL); + assert(inst->_type != nullptr); CPPFunctionType *ftype = inst->_type->as_function_type(); - assert(ftype != (CPPFunctionType *)NULL); + assert(ftype != nullptr); if ((ftype->_flags & CPPFunctionType::F_move_assignment_operator) != 0) { return inst; } } - return (CPPInstance *)NULL; + return nullptr; } /** @@ -1082,10 +1089,10 @@ get_destructor() const { ii != fgroup->_instances.end(); ++ii) { CPPInstance *inst = (*ii); - assert(inst->_type != (CPPType *)NULL); + assert(inst->_type != nullptr); CPPFunctionType *ftype = inst->_type->as_function_type(); - assert(ftype != (CPPFunctionType *)NULL); + assert(ftype != nullptr); if ((ftype->_flags & CPPFunctionType::F_destructor) != 0) { return inst; @@ -1094,7 +1101,7 @@ get_destructor() const { ++fi; } - return (CPPInstance *)NULL; + return nullptr; } /** @@ -1108,8 +1115,8 @@ instantiate(const CPPTemplateParameterList *actual_params, // I *think* this assertion is no longer valid. Who knows. // assert(!_incomplete); - if (_scope == NULL) { - if (error_sink != NULL) { + if (_scope == nullptr) { + if (error_sink != nullptr) { error_sink->warning("Ignoring template parameters for class " + get_local_name()); } @@ -1149,7 +1156,7 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, CPPScope *current_scope, CPPScope *global_scope) { SubstDecl::const_iterator si = subst.find(this); if (si != subst.end()) { - assert((*si).second != NULL); + assert((*si).second != nullptr); return (*si).second; } @@ -1163,19 +1170,19 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, // type which we'll define later. CPPTypeProxy *proxy = new CPPTypeProxy; _proxies.push_back(proxy); - assert(proxy != NULL); + assert(proxy != nullptr); return proxy; } _subst_decl_recursive_protect = true; CPPStructType *rep = new CPPStructType(*this); - if (_ident != NULL) { + if (_ident != nullptr) { rep->_ident = _ident->substitute_decl(subst, current_scope, global_scope); } - if (_scope != NULL) { + if (_scope != nullptr) { rep->_scope = _scope->substitute_decl(subst, current_scope, global_scope); if (rep->_scope != _scope) { @@ -1185,14 +1192,14 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, // parameters into our identifier. CPPScope *pscope = rep->_scope->get_parent_scope(); - if (pscope != (CPPScope *)NULL && + if (pscope != nullptr && pscope->_name.has_templ()) { // If the struct name didn't have an explicit template reference // before, now it does. - if (_ident != NULL && !_ident->_names.empty() && !_ident->_names.back().has_templ()) { + if (_ident != nullptr && !_ident->_names.empty() && !_ident->_names.back().has_templ()) { if (rep->is_template()) { - rep->_template_scope = (CPPTemplateScope *)NULL; + rep->_template_scope = nullptr; CPPNameComponent nc(get_simple_name()); nc.set_templ(pscope->_name.get_templ()); rep->_ident = new CPPIdentifier(nc, _file); @@ -1227,9 +1234,9 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, (*pi)->_actual_type = rep; } - assert(rep != NULL); + assert(rep != nullptr); rep = CPPType::new_type(rep)->as_struct_type(); - assert(rep != NULL); + assert(rep != nullptr); if (rep != this) { _instantiations.insert(rep); } @@ -1240,8 +1247,8 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, * */ void CPPStructType:: -output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { - if (!complete && _ident != NULL) { +output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const { + if (!complete && _ident != nullptr) { // If we have a name, use it. if (cppparser_output_class_keyword) { out << _type << " "; @@ -1258,7 +1265,7 @@ output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { get_template_scope()->_parameters.write_formal(out, scope); indent(out, indent_level); } - if (_ident != NULL) { + if (_ident != nullptr) { out << _type << " " << _ident->get_local_name(scope); } else { out << _type; @@ -1316,7 +1323,7 @@ get_virtual_funcs(VFunctions &funcs) const { for (di = _derivation.begin(); di != _derivation.end(); ++di) { VFunctions vf; CPPStructType *base = (*di)._base->as_struct_type(); - if (base != NULL) { + if (base != nullptr) { base->get_virtual_funcs(vf); funcs.splice(funcs.end(), vf); } @@ -1331,9 +1338,9 @@ get_virtual_funcs(VFunctions &funcs) const { ++vfnext; CPPInstance *inst = (*vfi); - assert(inst->_type != (CPPType *)NULL); + assert(inst->_type != nullptr); CPPFunctionType *base_ftype = inst->_type->as_function_type(); - assert(base_ftype != (CPPFunctionType *)NULL); + assert(base_ftype != nullptr); if (inst->_storage_class & CPPInstance::SC_deleted) { // Ignore deleted functions. @@ -1342,7 +1349,7 @@ get_virtual_funcs(VFunctions &funcs) const { // Match destructor-for-destructor; don't try to match destructors up by // name. CPPInstance *destructor = get_destructor(); - if (destructor != (CPPInstance *)NULL) { + if (destructor != nullptr) { // It's a match! This destructor is virtual. funcs.erase(vfi); destructor->_storage_class |= @@ -1351,7 +1358,7 @@ get_virtual_funcs(VFunctions &funcs) const { } else { // Non-destructors we can try to match up by name. - string fname = inst->get_local_name(); + std::string fname = inst->get_local_name(); CPPScope::Functions::const_iterator fi; fi = _scope->_functions.find(fname); @@ -1365,10 +1372,10 @@ get_virtual_funcs(VFunctions &funcs) const { ii != fgroup->_instances.end() && !match_found; ++ii) { CPPInstance *new_inst = (*ii); - assert(new_inst->_type != (CPPType *)NULL); + assert(new_inst->_type != nullptr); CPPFunctionType *new_ftype = new_inst->_type->as_function_type(); - assert(new_ftype != (CPPFunctionType *)NULL); + assert(new_ftype != nullptr); if (new_ftype->match_virtual_override(*base_ftype)) { // It's a match! We now know it's virtual. Erase this function diff --git a/dtool/src/cppparser/cppStructType.h b/dtool/src/cppparser/cppStructType.h index 9da8777a6c..57537b389e 100644 --- a/dtool/src/cppparser/cppStructType.h +++ b/dtool/src/cppparser/cppStructType.h @@ -80,13 +80,13 @@ public: virtual CPPDeclaration * instantiate(const CPPTemplateParameterList *actual_params, CPPScope *current_scope, CPPScope *global_scope, - CPPPreprocessor *error_sink = NULL) const; + CPPPreprocessor *error_sink = nullptr) const; virtual CPPDeclaration *substitute_decl(SubstDecl &subst, CPPScope *current_scope, CPPScope *global_scope); - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; virtual SubType get_subtype() const; @@ -98,17 +98,17 @@ public: class Base { public: - void output(ostream &out) const; + void output(std::ostream &out) const; CPPType *_base; CPPVisibility _vis; bool _is_virtual; }; - typedef vector Derivation; + typedef std::vector Derivation; Derivation _derivation; - typedef list VFunctions; + typedef std::list VFunctions; void get_virtual_funcs(VFunctions &funcs) const; void get_pure_virtual_funcs(VFunctions &funcs) const; @@ -117,11 +117,11 @@ protected: virtual bool is_less(const CPPDeclaration *other) const; bool _subst_decl_recursive_protect; - typedef vector Proxies; + typedef std::vector Proxies; Proxies _proxies; }; -inline ostream &operator << (ostream &out, const CPPStructType::Base &base) { +inline std::ostream &operator << (std::ostream &out, const CPPStructType::Base &base) { base.output(out); return out; } diff --git a/dtool/src/cppparser/cppTBDType.cxx b/dtool/src/cppparser/cppTBDType.cxx index 0b01c86817..5c583453ca 100644 --- a/dtool/src/cppparser/cppTBDType.cxx +++ b/dtool/src/cppparser/cppTBDType.cxx @@ -35,7 +35,7 @@ CPPTBDType(CPPIdentifier *ident) : CPPType *CPPTBDType:: resolve_type(CPPScope *current_scope, CPPScope *global_scope) { CPPType *type = _ident->find_type(current_scope, global_scope); - if (type != NULL) { + if (type != nullptr) { return type; } return this; @@ -56,7 +56,7 @@ is_tbd() const { * include any scoping operators or template parameters, so it may not be a * compilable reference to the type. */ -string CPPTBDType:: +std::string CPPTBDType:: get_simple_name() const { return _ident->get_simple_name(); } @@ -65,7 +65,7 @@ get_simple_name() const { * Returns the compilable, correct name for this type within the indicated * scope. If the scope is NULL, within the scope the type is declared in. */ -string CPPTBDType:: +std::string CPPTBDType:: get_local_name(CPPScope *scope) const { return _ident->get_local_name(scope); } @@ -74,7 +74,7 @@ get_local_name(CPPScope *scope) const { * Returns the compilable, correct name for the type, with completely explicit * scoping. */ -string CPPTBDType:: +std::string CPPTBDType:: get_fully_scoped_name() const { return _ident->get_fully_scoped_name(); } @@ -108,13 +108,13 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, } rep = CPPType::new_type(rep)->as_tbd_type(); - assert(rep != NULL); + assert(rep != nullptr); CPPType *result = rep; // Can we now define it as a real type? CPPType *type = rep->_ident->find_type(current_scope, global_scope, subst); - if (type != NULL) { + if (type != nullptr) { result = type; } @@ -128,7 +128,7 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, * */ void CPPTBDType:: -output(ostream &out, int, CPPScope *, bool) const { +output(std::ostream &out, int, CPPScope *, bool) const { out /* << "typename " */ << *_ident; } @@ -156,7 +156,7 @@ as_tbd_type() { bool CPPTBDType:: is_equal(const CPPDeclaration *other) const { const CPPTBDType *ot = ((CPPDeclaration *)other)->as_tbd_type(); - assert(ot != NULL); + assert(ot != nullptr); return (*_ident) == (*ot->_ident); } @@ -169,7 +169,7 @@ is_equal(const CPPDeclaration *other) const { bool CPPTBDType:: is_less(const CPPDeclaration *other) const { const CPPTBDType *ot = ((CPPDeclaration *)other)->as_tbd_type(); - assert(ot != NULL); + assert(ot != nullptr); return (*_ident) < (*ot->_ident); } diff --git a/dtool/src/cppparser/cppTBDType.h b/dtool/src/cppparser/cppTBDType.h index 6d35f053f4..beec68adeb 100644 --- a/dtool/src/cppparser/cppTBDType.h +++ b/dtool/src/cppparser/cppTBDType.h @@ -35,15 +35,15 @@ public: virtual bool is_tbd() const; - virtual string get_simple_name() const; - virtual string get_local_name(CPPScope *scope = NULL) const; - virtual string get_fully_scoped_name() const; + virtual std::string get_simple_name() const; + virtual std::string get_local_name(CPPScope *scope = nullptr) const; + virtual std::string get_fully_scoped_name() const; virtual CPPDeclaration *substitute_decl(SubstDecl &subst, CPPScope *current_scope, CPPScope *global_scope); - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; virtual SubType get_subtype() const; diff --git a/dtool/src/cppparser/cppTemplateParameterList.cxx b/dtool/src/cppparser/cppTemplateParameterList.cxx index 54d4ae544c..fd12967711 100644 --- a/dtool/src/cppparser/cppTemplateParameterList.cxx +++ b/dtool/src/cppparser/cppTemplateParameterList.cxx @@ -26,9 +26,9 @@ CPPTemplateParameterList() { /** * */ -string CPPTemplateParameterList:: +std::string CPPTemplateParameterList:: get_string() const { - ostringstream strname; + std::ostringstream strname; strname << "< " << *this << " >"; return strname.str(); } @@ -65,7 +65,7 @@ build_subst_decl(const CPPTemplateParameterList &formal_params, if (decl->as_instance()) { // A value template parameter. Its default is an expression. CPPInstance *inst = decl->as_instance(); - if (inst->_initializer != NULL) { + if (inst->_initializer != nullptr) { CPPDeclaration *decl = inst->_initializer->substitute_decl(subst, current_scope, global_scope); @@ -77,7 +77,7 @@ build_subst_decl(const CPPTemplateParameterList &formal_params, } else if (decl->as_class_template_parameter()) { // A class template parameter. CPPClassTemplateParameter *cparam = decl->as_class_template_parameter(); - if (cparam->_default_type != NULL) { + if (cparam->_default_type != nullptr) { CPPDeclaration *decl = cparam->_default_type->substitute_decl(subst, current_scope, global_scope); @@ -116,12 +116,12 @@ bool CPPTemplateParameterList:: is_tbd() const { for (int i = 0; i < (int)_parameters.size(); ++i) { CPPType *type = _parameters[i]->as_type(); - if (type != (CPPType *)NULL && - (type->is_tbd() || type->as_class_template_parameter() != NULL)) { + if (type != nullptr && + (type->is_tbd() || type->as_class_template_parameter() != nullptr)) { return true; } CPPExpression *expr = _parameters[i]->as_expression(); - if (expr != NULL && expr->is_tbd()) { + if (expr != nullptr && expr->is_tbd()) { return true; } } @@ -197,7 +197,7 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, * */ void CPPTemplateParameterList:: -output(ostream &out, CPPScope *scope) const { +output(std::ostream &out, CPPScope *scope) const { if (!_parameters.empty()) { Parameters::const_iterator pi = _parameters.begin(); (*pi)->output(out, 0, scope, false); @@ -217,7 +217,7 @@ output(ostream &out, CPPScope *scope) const { * trailing newline. */ void CPPTemplateParameterList:: -write_formal(ostream &out, CPPScope *scope) const { +write_formal(std::ostream &out, CPPScope *scope) const { out << "template<"; if (!_parameters.empty()) { Parameters::const_iterator pi = _parameters.begin(); diff --git a/dtool/src/cppparser/cppTemplateParameterList.h b/dtool/src/cppparser/cppTemplateParameterList.h index 712dd227cd..d47f8fdd9e 100644 --- a/dtool/src/cppparser/cppTemplateParameterList.h +++ b/dtool/src/cppparser/cppTemplateParameterList.h @@ -33,7 +33,7 @@ class CPPTemplateParameterList { public: CPPTemplateParameterList(); - string get_string() const; + std::string get_string() const; void build_subst_decl(const CPPTemplateParameterList &formal_params, CPPDeclaration::SubstDecl &subst, CPPScope *current_scope, CPPScope *global_scope) const; @@ -49,16 +49,16 @@ public: CPPScope *current_scope, CPPScope *global_scope); - void output(ostream &out, CPPScope *scope) const; - void write_formal(ostream &out, CPPScope *scope) const; + void output(std::ostream &out, CPPScope *scope) const; + void write_formal(std::ostream &out, CPPScope *scope) const; - typedef vector Parameters; + typedef std::vector Parameters; Parameters _parameters; }; -inline ostream & -operator << (ostream &out, const CPPTemplateParameterList &plist) { - plist.output(out, (CPPScope *)NULL); +inline std::ostream & +operator << (std::ostream &out, const CPPTemplateParameterList &plist) { + plist.output(out, nullptr); return out; } diff --git a/dtool/src/cppparser/cppTemplateScope.cxx b/dtool/src/cppparser/cppTemplateScope.cxx index 2960718205..a71c176005 100644 --- a/dtool/src/cppparser/cppTemplateScope.cxx +++ b/dtool/src/cppparser/cppTemplateScope.cxx @@ -17,6 +17,8 @@ #include "cppIdentifier.h" #include "cppTypedefType.h" +using std::string; + /** * */ @@ -35,7 +37,7 @@ add_declaration(CPPDeclaration *decl, CPPScope *global_scope, CPPPreprocessor *preprocessor, const cppyyltype &pos) { decl->_template_scope = this; - assert(_parent_scope != NULL); + assert(_parent_scope != nullptr); _parent_scope->add_declaration(decl, global_scope, preprocessor, pos); } @@ -45,7 +47,7 @@ add_declaration(CPPDeclaration *decl, CPPScope *global_scope, void CPPTemplateScope:: add_enum_value(CPPInstance *inst) { inst->_template_scope = this; - assert(_parent_scope != NULL); + assert(_parent_scope != nullptr); _parent_scope->add_enum_value(inst); } @@ -55,7 +57,7 @@ add_enum_value(CPPInstance *inst) { void CPPTemplateScope:: define_typedef_type(CPPTypedefType *type, CPPPreprocessor *error_sink) { type->_template_scope = this; - assert(_parent_scope != NULL); + assert(_parent_scope != nullptr); _parent_scope->define_typedef_type(type, error_sink); } @@ -65,7 +67,7 @@ define_typedef_type(CPPTypedefType *type, CPPPreprocessor *error_sink) { void CPPTemplateScope:: define_extension_type(CPPExtensionType *type, CPPPreprocessor *error_sink) { type->_template_scope = this; - assert(_parent_scope != NULL); + assert(_parent_scope != nullptr); _parent_scope->define_extension_type(type, error_sink); } @@ -74,7 +76,7 @@ define_extension_type(CPPExtensionType *type, CPPPreprocessor *error_sink) { */ void CPPTemplateScope:: define_namespace(CPPNamespace *scope) { - assert(_parent_scope != NULL); + assert(_parent_scope != nullptr); _parent_scope->define_namespace(scope); } @@ -84,7 +86,7 @@ define_namespace(CPPNamespace *scope) { void CPPTemplateScope:: add_using(CPPUsing *using_decl, CPPScope *global_scope, CPPPreprocessor *error_sink) { - assert(_parent_scope != NULL); + assert(_parent_scope != nullptr); _parent_scope->add_using(using_decl, global_scope, error_sink); } @@ -95,16 +97,16 @@ void CPPTemplateScope:: add_template_parameter(CPPDeclaration *param) { _parameters._parameters.push_back(param); CPPClassTemplateParameter *cl = param->as_class_template_parameter(); - if (cl != NULL) { + if (cl != nullptr) { // Create an implicit typedef for this class parameter. - if (cl->_ident != NULL) { + if (cl->_ident != nullptr) { string name = cl->_ident->get_local_name(); _types[name] = cl; } } CPPInstance *inst = param->as_instance(); - if (inst != NULL) { + if (inst != nullptr) { // Register the variable for this value parameter. string name = inst->get_local_name(); if (!name.empty()) { @@ -128,7 +130,7 @@ is_fully_specified() const { */ string CPPTemplateScope:: get_simple_name() const { - assert(_parent_scope != NULL); + assert(_parent_scope != nullptr); return _parent_scope->get_simple_name(); } @@ -137,7 +139,7 @@ get_simple_name() const { */ string CPPTemplateScope:: get_local_name(CPPScope *scope) const { - assert(_parent_scope != NULL); + assert(_parent_scope != nullptr); return _parent_scope->get_local_name(scope); } @@ -146,7 +148,7 @@ get_local_name(CPPScope *scope) const { */ string CPPTemplateScope:: get_fully_scoped_name() const { - assert(_parent_scope != NULL); + assert(_parent_scope != nullptr); return _parent_scope->get_fully_scoped_name(); } @@ -154,7 +156,7 @@ get_fully_scoped_name() const { * */ void CPPTemplateScope:: -output(ostream &out, CPPScope *scope) const { +output(std::ostream &out, CPPScope *scope) const { CPPScope::output(out, scope); out << "< "; _parameters.output(out, scope); diff --git a/dtool/src/cppparser/cppTemplateScope.h b/dtool/src/cppparser/cppTemplateScope.h index 91235ff0fe..8a30b686a5 100644 --- a/dtool/src/cppparser/cppTemplateScope.h +++ b/dtool/src/cppparser/cppTemplateScope.h @@ -35,20 +35,20 @@ public: const cppyyltype &pos); virtual void add_enum_value(CPPInstance *inst); virtual void define_typedef_type(CPPTypedefType *type, - CPPPreprocessor *error_sink = NULL); + CPPPreprocessor *error_sink = nullptr); virtual void define_extension_type(CPPExtensionType *type, - CPPPreprocessor *error_sink = NULL); + CPPPreprocessor *error_sink = nullptr); virtual void define_namespace(CPPNamespace *scope); virtual void add_using(CPPUsing *using_decl, CPPScope *global_scope, - CPPPreprocessor *error_sink = NULL); + CPPPreprocessor *error_sink = nullptr); virtual bool is_fully_specified() const; - virtual string get_simple_name() const; - virtual string get_local_name(CPPScope *scope = NULL) const; - virtual string get_fully_scoped_name() const; + virtual std::string get_simple_name() const; + virtual std::string get_local_name(CPPScope *scope = nullptr) const; + virtual std::string get_fully_scoped_name() const; - virtual void output(ostream &out, CPPScope *scope) const; + virtual void output(std::ostream &out, CPPScope *scope) const; virtual CPPTemplateScope *as_template_scope(); diff --git a/dtool/src/cppparser/cppToken.cxx b/dtool/src/cppparser/cppToken.cxx index d2e00982dc..5649d4a612 100644 --- a/dtool/src/cppparser/cppToken.cxx +++ b/dtool/src/cppparser/cppToken.cxx @@ -23,7 +23,7 @@ */ CPPToken:: CPPToken(int token, int line_number, int col_number, - const CPPFile &file, const string &str, + const CPPFile &file, const std::string &str, const YYSTYPE &lval) : _token(token), _lval(lval) { @@ -39,7 +39,7 @@ CPPToken(int token, int line_number, int col_number, * */ CPPToken:: -CPPToken(int token, const YYLTYPE &loc, const string &str, const YYSTYPE &val) : +CPPToken(int token, const YYLTYPE &loc, const std::string &str, const YYSTYPE &val) : _token(token), _lval(val), _lloc(loc) { _lval.str = str; @@ -90,7 +90,7 @@ is_eof() const { * */ void CPPToken:: -output(ostream &out) const { +output(std::ostream &out) const { switch (_token) { case REAL: out << "REAL " << _lval.u.real; @@ -357,7 +357,7 @@ output(ostream &out) const { break; case KW_OPERATOR: - if (_lval.u.identifier != NULL) { + if (_lval.u.identifier != nullptr) { out << *_lval.u.identifier << "::"; } out << "KW_OPERATOR"; diff --git a/dtool/src/cppparser/cppToken.h b/dtool/src/cppparser/cppToken.h index 0c14af3171..735ef0aac2 100644 --- a/dtool/src/cppparser/cppToken.h +++ b/dtool/src/cppparser/cppToken.h @@ -25,10 +25,10 @@ class CPPToken { public: CPPToken(int token, int line_number = 0, int col_number = 0, const CPPFile &file = CPPFile(""), - const string &str = string(), + const std::string &str = std::string(), const YYSTYPE &lval = YYSTYPE()); CPPToken(int token, const YYLTYPE &loc, - const string &str = string(), + const std::string &str = std::string(), const YYSTYPE &lval = YYSTYPE()); CPPToken(const CPPToken ©); void operator = (const CPPToken ©); @@ -36,14 +36,14 @@ public: static CPPToken eof(); bool is_eof() const; - void output(ostream &out) const; + void output(std::ostream &out) const; int _token; YYSTYPE _lval; YYLTYPE _lloc; }; -inline ostream &operator << (ostream &out, const CPPToken &token) { +inline std::ostream &operator << (std::ostream &out, const CPPToken &token) { token.output(out); return out; } diff --git a/dtool/src/cppparser/cppType.cxx b/dtool/src/cppparser/cppType.cxx index af3f511da4..eea6f47bf6 100644 --- a/dtool/src/cppparser/cppType.cxx +++ b/dtool/src/cppparser/cppType.cxx @@ -20,6 +20,8 @@ #include "cppExtensionType.h" #include +using std::string; + CPPType::Types CPPType::_types; CPPType::PreferredNames CPPType::_preferred_names; CPPType::AltNames CPPType::_alt_names; @@ -36,7 +38,7 @@ CPPType:: CPPType(const CPPFile &file) : CPPDeclaration(file) { - _declaration = (CPPTypeDeclaration *)NULL; + _declaration = nullptr; // This is set true by interrogate when the "forcetype" keyword is used. _forcetype = false; @@ -143,11 +145,11 @@ is_parameter_expr() const { bool CPPType:: is_enum() const { const CPPTypedefType *td_type = as_typedef_type(); - if (td_type != NULL) { + if (td_type != nullptr) { return td_type->_type->is_enum(); } const CPPExtensionType *ext_type = as_extension_type(); - if (ext_type != NULL) { + if (ext_type != nullptr) { return ext_type->_type == CPPExtensionType::T_enum || ext_type->_type == CPPExtensionType::T_enum_struct || ext_type->_type == CPPExtensionType::T_enum_class; @@ -161,7 +163,7 @@ is_enum() const { bool CPPType:: is_const() const { const CPPTypedefType *td_type = as_typedef_type(); - if (td_type != NULL) { + if (td_type != nullptr) { return td_type->_type->is_const(); } return get_subtype() == ST_const; @@ -173,7 +175,7 @@ is_const() const { bool CPPType:: is_reference() const { const CPPTypedefType *td_type = as_typedef_type(); - if (td_type != NULL) { + if (td_type != nullptr) { return td_type->_type->is_reference(); } return get_subtype() == ST_reference; @@ -186,11 +188,11 @@ is_reference() const { bool CPPType:: is_pointer() const { const CPPTypedefType *td_type = as_typedef_type(); - if (td_type != NULL) { + if (td_type != nullptr) { return td_type->_type->is_pointer(); } const CPPConstType *const_type = as_const_type(); - if (const_type != NULL) { + if (const_type != nullptr) { return const_type->_wrapped_around->is_pointer(); } return get_subtype() == ST_pointer; @@ -203,7 +205,7 @@ is_pointer() const { CPPType *CPPType:: remove_const() { const CPPTypedefType *td_type = as_typedef_type(); - if (td_type != NULL) { + if (td_type != nullptr) { CPPType *unwrapped = td_type->_type->remove_const(); if (unwrapped != td_type->_type) { return unwrapped; @@ -212,7 +214,7 @@ remove_const() { } } const CPPConstType *const_type = as_const_type(); - if (const_type != NULL) { + if (const_type != nullptr) { return const_type->_wrapped_around->remove_const(); } return this; @@ -224,7 +226,7 @@ remove_const() { CPPType *CPPType:: remove_reference() { const CPPTypedefType *td_type = as_typedef_type(); - if (td_type != NULL) { + if (td_type != nullptr) { CPPType *unwrapped = td_type->_type->remove_reference(); if (unwrapped != td_type->_type) { return unwrapped; @@ -233,7 +235,7 @@ remove_reference() { } } const CPPReferenceType *ref_type = as_reference_type(); - if (ref_type != NULL) { + if (ref_type != nullptr) { return ref_type->_pointing_at; } return this; @@ -306,7 +308,7 @@ get_simple_name() const { */ string CPPType:: get_local_name(CPPScope *scope) const { - ostringstream ostrm; + std::ostringstream ostrm; output(ostrm, 0, scope, false); return ostrm.str(); } @@ -419,7 +421,7 @@ is_convertible_to(const CPPType *other) const { * have special exceptions. */ void CPPType:: -output_instance(ostream &out, const string &name, CPPScope *scope) const { +output_instance(std::ostream &out, const string &name, CPPScope *scope) const { output_instance(out, 0, scope, false, "", name); } @@ -429,7 +431,7 @@ output_instance(ostream &out, const string &name, CPPScope *scope) const { * have special exceptions. */ void CPPType:: -output_instance(ostream &out, int indent_level, CPPScope *scope, +output_instance(std::ostream &out, int indent_level, CPPScope *scope, bool complete, const string &prename, const string &name) const { output(out, indent_level, scope, complete); @@ -454,7 +456,7 @@ as_type() { */ CPPType *CPPType:: new_type(CPPType *type) { - pair result = _types.insert(type); + std::pair result = _types.insert(type); if (result.second) { // The insertion has taken place; thus, this is the first time this type // has been declared. diff --git a/dtool/src/cppparser/cppType.h b/dtool/src/cppparser/cppType.h index a312f45d33..82f634080c 100644 --- a/dtool/src/cppparser/cppType.h +++ b/dtool/src/cppparser/cppType.h @@ -36,7 +36,7 @@ public: */ class CPPType : public CPPDeclaration { public: - typedef vector Typedefs; + typedef std::vector Typedefs; Typedefs _typedefs; CPPType(const CPPFile &file); @@ -68,46 +68,46 @@ public: CPPType *remove_pointer(); bool has_typedef_name() const; - string get_typedef_name(CPPScope *scope = NULL) const; + std::string get_typedef_name(CPPScope *scope = nullptr) const; - virtual string get_simple_name() const; - virtual string get_local_name(CPPScope *scope = NULL) const; - virtual string get_fully_scoped_name() const; - virtual string get_preferred_name() const; + virtual std::string get_simple_name() const; + virtual std::string get_local_name(CPPScope *scope = nullptr) const; + virtual std::string get_fully_scoped_name() const; + virtual std::string get_preferred_name() const; int get_num_alt_names() const; - string get_alt_name(int n) const; + std::string get_alt_name(int n) const; virtual bool is_incomplete() const; virtual bool is_convertible_to(const CPPType *other) const; virtual bool is_equivalent(const CPPType &other) const; - void output_instance(ostream &out, const string &name, + void output_instance(std::ostream &out, const std::string &name, CPPScope *scope) const; - virtual void output_instance(ostream &out, int indent_level, + virtual void output_instance(std::ostream &out, int indent_level, CPPScope *scope, - bool complete, const string &prename, - const string &name) const; + bool complete, const std::string &prename, + const std::string &name) const; virtual CPPType *as_type(); static CPPType *new_type(CPPType *type); - static void record_alt_name_for(const CPPType *type, const string &name); - static string get_preferred_name_for(const CPPType *type); + static void record_alt_name_for(const CPPType *type, const std::string &name); + static std::string get_preferred_name_for(const CPPType *type); CPPTypeDeclaration *_declaration; bool _forcetype; protected: - typedef set Types; + typedef std::set Types; static Types _types; - typedef map PreferredNames; + typedef std::map PreferredNames; static PreferredNames _preferred_names; - typedef vector Names; - typedef map AltNames; + typedef std::vector Names; + typedef std::map AltNames; static AltNames _alt_names; }; diff --git a/dtool/src/cppparser/cppTypeDeclaration.cxx b/dtool/src/cppparser/cppTypeDeclaration.cxx index 88509911b4..84b6075172 100644 --- a/dtool/src/cppparser/cppTypeDeclaration.cxx +++ b/dtool/src/cppparser/cppTypeDeclaration.cxx @@ -18,10 +18,10 @@ */ CPPTypeDeclaration:: CPPTypeDeclaration(CPPType *type) : - CPPInstance(type, (CPPIdentifier *)NULL) + CPPInstance(type, nullptr) { - assert(_type != NULL); - if (_type->_declaration == (CPPTypeDeclaration *)NULL) { + assert(_type != nullptr); + if (_type->_declaration == nullptr) { _type->_declaration = this; } } @@ -34,11 +34,11 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, CPPScope *current_scope, CPPScope *global_scope) { CPPDeclaration *decl = CPPInstance::substitute_decl(subst, current_scope, global_scope); - assert(decl != NULL); + assert(decl != nullptr); if (decl->as_type_declaration()) { return decl; } - assert(decl->as_instance() != NULL); + assert(decl->as_instance() != nullptr); return new CPPTypeDeclaration(decl->as_instance()->_type); } @@ -46,7 +46,7 @@ substitute_decl(CPPDeclaration::SubstDecl &subst, * */ void CPPTypeDeclaration:: -output(ostream &out, int indent_level, CPPScope *scope, bool) const { +output(std::ostream &out, int indent_level, CPPScope *scope, bool) const { _type->output(out, indent_level, scope, true); } diff --git a/dtool/src/cppparser/cppTypeDeclaration.h b/dtool/src/cppparser/cppTypeDeclaration.h index 9fb06debef..cd93ed0fdc 100644 --- a/dtool/src/cppparser/cppTypeDeclaration.h +++ b/dtool/src/cppparser/cppTypeDeclaration.h @@ -31,7 +31,7 @@ public: CPPScope *current_scope, CPPScope *global_scope); - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; virtual SubType get_subtype() const; diff --git a/dtool/src/cppparser/cppTypeParser.cxx b/dtool/src/cppparser/cppTypeParser.cxx index 815875dcf9..cdaa1d0288 100644 --- a/dtool/src/cppparser/cppTypeParser.cxx +++ b/dtool/src/cppparser/cppTypeParser.cxx @@ -22,7 +22,7 @@ CPPTypeParser(CPPScope *current_scope, CPPScope *global_scope) : _current_scope(current_scope), _global_scope(global_scope) { - _type = NULL; + _type = nullptr; } /** @@ -36,9 +36,9 @@ CPPTypeParser:: * */ bool CPPTypeParser:: -parse_type(const string &type) { +parse_type(const std::string &type) { if (!init_type(type)) { - cerr << "Unable to parse type\n"; + std::cerr << "Unable to parse type\n"; return false; } @@ -51,9 +51,9 @@ parse_type(const string &type) { * */ bool CPPTypeParser:: -parse_type(const string &type, const CPPPreprocessor &filepos) { +parse_type(const std::string &type, const CPPPreprocessor &filepos) { if (!init_type(type)) { - cerr << "Unable to parse type\n"; + std::cerr << "Unable to parse type\n"; return false; } @@ -68,8 +68,8 @@ parse_type(const string &type, const CPPPreprocessor &filepos) { * */ void CPPTypeParser:: -output(ostream &out) const { - if (_type == NULL) { +output(std::ostream &out) const { + if (_type == nullptr) { out << "(null type)"; } else { out << *_type; diff --git a/dtool/src/cppparser/cppTypeParser.h b/dtool/src/cppparser/cppTypeParser.h index af18e0e5b8..4064e84687 100644 --- a/dtool/src/cppparser/cppTypeParser.h +++ b/dtool/src/cppparser/cppTypeParser.h @@ -29,18 +29,18 @@ public: CPPTypeParser(CPPScope *current_scope, CPPScope *global_scope); ~CPPTypeParser(); - bool parse_type(const string &type); - bool parse_type(const string &type, const CPPPreprocessor &filepos); + bool parse_type(const std::string &type); + bool parse_type(const std::string &type, const CPPPreprocessor &filepos); - void output(ostream &out) const; + void output(std::ostream &out) const; CPPScope *_current_scope; CPPScope *_global_scope; CPPType *_type; }; -inline ostream & -operator << (ostream &out, const CPPTypeParser &ep) { +inline std::ostream & +operator << (std::ostream &out, const CPPTypeParser &ep) { ep.output(out); return out; } diff --git a/dtool/src/cppparser/cppTypeProxy.cxx b/dtool/src/cppparser/cppTypeProxy.cxx index 239ef04828..4843ac5b34 100644 --- a/dtool/src/cppparser/cppTypeProxy.cxx +++ b/dtool/src/cppparser/cppTypeProxy.cxx @@ -14,6 +14,8 @@ #include "cppTypeProxy.h" #include "cppFile.h" +using std::string; + /** * */ @@ -21,7 +23,7 @@ CPPTypeProxy:: CPPTypeProxy() : CPPType(CPPFile()) { - _actual_type = (CPPType *)NULL; + _actual_type = nullptr; } /** @@ -31,7 +33,7 @@ CPPTypeProxy() : */ CPPType *CPPTypeProxy:: resolve_type(CPPScope *, CPPScope *) { - if (_actual_type == (CPPType *)NULL) { + if (_actual_type == nullptr) { return this; } return _actual_type; @@ -44,7 +46,7 @@ resolve_type(CPPScope *, CPPScope *) { */ bool CPPTypeProxy:: is_tbd() const { - if (_actual_type == (CPPType *)NULL) { + if (_actual_type == nullptr) { return false; } return _actual_type->is_tbd(); @@ -57,7 +59,7 @@ is_tbd() const { */ bool CPPTypeProxy:: has_typedef_name() const { - if (_actual_type == (CPPType *)NULL) { + if (_actual_type == nullptr) { return false; } return _actual_type->has_typedef_name(); @@ -69,7 +71,7 @@ has_typedef_name() const { */ string CPPTypeProxy:: get_typedef_name(CPPScope *) const { - if (_actual_type == (CPPType *)NULL) { + if (_actual_type == nullptr) { return string(); } return _actual_type->get_typedef_name(); @@ -83,7 +85,7 @@ get_typedef_name(CPPScope *) const { */ string CPPTypeProxy:: get_simple_name() const { - if (_actual_type == (CPPType *)NULL) { + if (_actual_type == nullptr) { return "unknown"; } return _actual_type->get_simple_name(); @@ -95,7 +97,7 @@ get_simple_name() const { */ string CPPTypeProxy:: get_local_name(CPPScope *scope) const { - if (_actual_type == (CPPType *)NULL) { + if (_actual_type == nullptr) { return "unknown"; } return _actual_type->get_local_name(scope); @@ -107,7 +109,7 @@ get_local_name(CPPScope *scope) const { */ string CPPTypeProxy:: get_fully_scoped_name() const { - if (_actual_type == (CPPType *)NULL) { + if (_actual_type == nullptr) { return "unknown"; } return _actual_type->get_fully_scoped_name(); @@ -121,7 +123,7 @@ get_fully_scoped_name() const { */ string CPPTypeProxy:: get_preferred_name() const { - if (_actual_type == (CPPType *)NULL) { + if (_actual_type == nullptr) { return "unknown"; } return _actual_type->get_preferred_name(); @@ -132,7 +134,7 @@ get_preferred_name() const { */ bool CPPTypeProxy:: is_incomplete() const { - if (_actual_type == (CPPType *)NULL) { + if (_actual_type == nullptr) { return true; } return _actual_type->is_incomplete(); @@ -144,10 +146,10 @@ is_incomplete() const { * have special exceptions. */ void CPPTypeProxy:: -output_instance(ostream &out, int indent_level, CPPScope *scope, +output_instance(std::ostream &out, int indent_level, CPPScope *scope, bool complete, const string &prename, const string &name) const { - if (_actual_type == (CPPType *)NULL) { + if (_actual_type == nullptr) { out << "unknown " << prename << name; return; } @@ -159,8 +161,8 @@ output_instance(ostream &out, int indent_level, CPPScope *scope, * */ void CPPTypeProxy:: -output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { - if (_actual_type == (CPPType *)NULL) { +output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const { + if (_actual_type == nullptr) { out << "unknown"; return; } @@ -181,7 +183,7 @@ get_subtype() const { */ CPPType *CPPTypeProxy:: as_type() { - if (_actual_type == (CPPType *)NULL) { + if (_actual_type == nullptr) { return this; } return _actual_type; @@ -192,8 +194,8 @@ as_type() { */ CPPSimpleType *CPPTypeProxy:: as_simple_type() { - if (_actual_type == (CPPType *)NULL) { - return (CPPSimpleType *)NULL; + if (_actual_type == nullptr) { + return nullptr; } return _actual_type->as_simple_type(); } @@ -203,8 +205,8 @@ as_simple_type() { */ CPPPointerType *CPPTypeProxy:: as_pointer_type() { - if (_actual_type == (CPPType *)NULL) { - return (CPPPointerType *)NULL; + if (_actual_type == nullptr) { + return nullptr; } return _actual_type->as_pointer_type(); } @@ -214,8 +216,8 @@ as_pointer_type() { */ CPPReferenceType *CPPTypeProxy:: as_reference_type() { - if (_actual_type == (CPPType *)NULL) { - return (CPPReferenceType *)NULL; + if (_actual_type == nullptr) { + return nullptr; } return _actual_type->as_reference_type(); } @@ -225,8 +227,8 @@ as_reference_type() { */ CPPArrayType *CPPTypeProxy:: as_array_type() { - if (_actual_type == (CPPType *)NULL) { - return (CPPArrayType *)NULL; + if (_actual_type == nullptr) { + return nullptr; } return _actual_type->as_array_type(); } @@ -236,8 +238,8 @@ as_array_type() { */ CPPConstType *CPPTypeProxy:: as_const_type() { - if (_actual_type == (CPPType *)NULL) { - return (CPPConstType *)NULL; + if (_actual_type == nullptr) { + return nullptr; } return _actual_type->as_const_type(); } @@ -247,8 +249,8 @@ as_const_type() { */ CPPFunctionType *CPPTypeProxy:: as_function_type() { - if (_actual_type == (CPPType *)NULL) { - return (CPPFunctionType *)NULL; + if (_actual_type == nullptr) { + return nullptr; } return _actual_type->as_function_type(); } @@ -258,8 +260,8 @@ as_function_type() { */ CPPExtensionType *CPPTypeProxy:: as_extension_type() { - if (_actual_type == (CPPType *)NULL) { - return (CPPExtensionType *)NULL; + if (_actual_type == nullptr) { + return nullptr; } return _actual_type->as_extension_type(); } @@ -269,8 +271,8 @@ as_extension_type() { */ CPPStructType *CPPTypeProxy:: as_struct_type() { - if (_actual_type == (CPPType *)NULL) { - return (CPPStructType *)NULL; + if (_actual_type == nullptr) { + return nullptr; } return _actual_type->as_struct_type(); } @@ -280,8 +282,8 @@ as_struct_type() { */ CPPEnumType *CPPTypeProxy:: as_enum_type() { - if (_actual_type == (CPPType *)NULL) { - return (CPPEnumType *)NULL; + if (_actual_type == nullptr) { + return nullptr; } return _actual_type->as_enum_type(); } @@ -291,8 +293,8 @@ as_enum_type() { */ CPPTBDType *CPPTypeProxy:: as_tbd_type() { - if (_actual_type == (CPPType *)NULL) { - return (CPPTBDType *)NULL; + if (_actual_type == nullptr) { + return nullptr; } return _actual_type->as_tbd_type(); } @@ -302,8 +304,8 @@ as_tbd_type() { */ CPPTypedefType *CPPTypeProxy:: as_typedef_type() { - if (_actual_type == (CPPType *)NULL) { - return (CPPTypedefType *)NULL; + if (_actual_type == nullptr) { + return nullptr; } return _actual_type->as_typedef_type(); } diff --git a/dtool/src/cppparser/cppTypeProxy.h b/dtool/src/cppparser/cppTypeProxy.h index da87e99ca6..87d064a3b5 100644 --- a/dtool/src/cppparser/cppTypeProxy.h +++ b/dtool/src/cppparser/cppTypeProxy.h @@ -33,20 +33,20 @@ public: virtual bool is_tbd() const; bool has_typedef_name() const; - string get_typedef_name(CPPScope *scope = NULL) const; + std::string get_typedef_name(CPPScope *scope = nullptr) const; - virtual string get_simple_name() const; - virtual string get_local_name(CPPScope *scope = NULL) const; - virtual string get_fully_scoped_name() const; - virtual string get_preferred_name() const; + virtual std::string get_simple_name() const; + virtual std::string get_local_name(CPPScope *scope = nullptr) const; + virtual std::string get_fully_scoped_name() const; + virtual std::string get_preferred_name() const; virtual bool is_incomplete() const; - virtual void output_instance(ostream &out, int indent_level, + virtual void output_instance(std::ostream &out, int indent_level, CPPScope *scope, - bool complete, const string &prename, - const string &name) const; - virtual void output(ostream &out, int indent_level, CPPScope *scope, + bool complete, const std::string &prename, + const std::string &name) const; + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; virtual SubType get_subtype() const; diff --git a/dtool/src/cppparser/cppTypedefType.cxx b/dtool/src/cppparser/cppTypedefType.cxx index d965d5db48..6924fca4a0 100644 --- a/dtool/src/cppparser/cppTypedefType.cxx +++ b/dtool/src/cppparser/cppTypedefType.cxx @@ -17,6 +17,8 @@ #include "cppTemplateScope.h" #include "indent.h" +using std::string; + /** * */ @@ -27,7 +29,7 @@ CPPTypedefType(CPPType *type, const string &name, CPPScope *current_scope) : _ident(new CPPIdentifier(name)), _using(false) { - if (_ident != NULL) { + if (_ident != nullptr) { _ident->_native_scope = current_scope; } @@ -47,7 +49,7 @@ CPPTypedefType(CPPType *type, CPPIdentifier *ident, CPPScope *current_scope) : _ident(ident), _using(false) { - if (_ident != NULL) { + if (_ident != nullptr) { _ident->_native_scope = current_scope; } _subst_decl_recursive_protect = false; @@ -64,13 +66,13 @@ CPPTypedefType(CPPType *type, CPPInstanceIdentifier *ii, CPPType(file), _using(false) { - assert(ii != NULL); + assert(ii != nullptr); _type = ii->unroll_type(type); _ident = ii->_ident; - ii->_ident = NULL; + ii->_ident = nullptr; delete ii; - if (_ident != NULL) { + if (_ident != nullptr) { _ident->_native_scope = current_scope; } @@ -82,7 +84,7 @@ CPPTypedefType(CPPType *type, CPPInstanceIdentifier *ii, */ bool CPPTypedefType:: is_scoped() const { - if (_ident == NULL) { + if (_ident == nullptr) { return false; } else { return _ident->is_scoped(); @@ -95,7 +97,7 @@ is_scoped() const { CPPScope *CPPTypedefType:: get_scope(CPPScope *current_scope, CPPScope *global_scope, CPPPreprocessor *error_sink) const { - if (_ident == NULL) { + if (_ident == nullptr) { return current_scope; } else { return _ident->get_scope(current_scope, global_scope, error_sink); @@ -107,7 +109,7 @@ get_scope(CPPScope *current_scope, CPPScope *global_scope, */ string CPPTypedefType:: get_simple_name() const { - if (_ident == NULL) { + if (_ident == nullptr) { return ""; } return _ident->get_simple_name(); @@ -118,7 +120,7 @@ get_simple_name() const { */ string CPPTypedefType:: get_local_name(CPPScope *scope) const { - if (_ident == NULL) { + if (_ident == nullptr) { return ""; } return _ident->get_local_name(scope); @@ -129,7 +131,7 @@ get_local_name(CPPScope *scope) const { */ string CPPTypedefType:: get_fully_scoped_name() const { - if (_ident == NULL) { + if (_ident == nullptr) { return ""; } return _ident->get_fully_scoped_name(); @@ -151,7 +153,7 @@ is_incomplete() const { */ bool CPPTypedefType:: is_tbd() const { - if (_ident != NULL && _ident->is_tbd()) { + if (_ident != nullptr && _ident->is_tbd()) { return true; } return _type->is_tbd(); @@ -228,7 +230,7 @@ is_destructible() const { */ bool CPPTypedefType:: is_fully_specified() const { - if (_ident != NULL && !_ident->is_fully_specified()) { + if (_ident != nullptr && !_ident->is_fully_specified()) { return false; } return CPPDeclaration::is_fully_specified() && @@ -253,7 +255,7 @@ CPPDeclaration *CPPTypedefType:: substitute_decl(CPPDeclaration::SubstDecl &subst, CPPScope *current_scope, CPPScope *global_scope) { - if (_ident != NULL && _ident->get_scope(current_scope, global_scope) == global_scope) { + if (_ident != nullptr && _ident->get_scope(current_scope, global_scope) == global_scope) { // Hack... I know that size_t etc is supposed to work fine, so preserve // these top-level typedefs. CPPDeclaration *top = @@ -373,9 +375,9 @@ is_equivalent(const CPPType &other) const { * */ void CPPTypedefType:: -output(ostream &out, int indent_level, CPPScope *scope, bool complete) const { +output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const { string name; - if (_ident != NULL) { + if (_ident != nullptr) { name = _ident->get_local_name(scope); } @@ -420,7 +422,7 @@ as_typedef_type() { bool CPPTypedefType:: is_equal(const CPPDeclaration *other) const { const CPPTypedefType *ot = ((CPPDeclaration *)other)->as_typedef_type(); - assert(ot != NULL); + assert(ot != nullptr); return (*_type == *ot->_type) && (*_ident == *ot->_ident) && (_using == ot->_using); } diff --git a/dtool/src/cppparser/cppTypedefType.h b/dtool/src/cppparser/cppTypedefType.h index 04a9b05995..c8d7ffd6be 100644 --- a/dtool/src/cppparser/cppTypedefType.h +++ b/dtool/src/cppparser/cppTypedefType.h @@ -27,18 +27,18 @@ class CPPInstanceIdentifier; */ class CPPTypedefType : public CPPType { public: - CPPTypedefType(CPPType *type, const string &name, CPPScope *current_scope); + CPPTypedefType(CPPType *type, const std::string &name, CPPScope *current_scope); CPPTypedefType(CPPType *type, CPPIdentifier *ident, CPPScope *current_scope); CPPTypedefType(CPPType *type, CPPInstanceIdentifier *ii, CPPScope *current_scope, const CPPFile &file); bool is_scoped() const; CPPScope *get_scope(CPPScope *current_scope, CPPScope *global_scope, - CPPPreprocessor *error_sink = NULL) const; + CPPPreprocessor *error_sink = nullptr) const; - virtual string get_simple_name() const; - virtual string get_local_name(CPPScope *scope = NULL) const; - virtual string get_fully_scoped_name() const; + virtual std::string get_simple_name() const; + virtual std::string get_local_name(CPPScope *scope = nullptr) const; + virtual std::string get_fully_scoped_name() const; virtual bool is_incomplete() const; virtual bool is_tbd() const; @@ -56,7 +56,7 @@ public: virtual CPPDeclaration * instantiate(const CPPTemplateParameterList *actual_params, CPPScope *current_scope, CPPScope *global_scope, - CPPPreprocessor *error_sink = NULL) const; + CPPPreprocessor *error_sink = nullptr) const; virtual CPPDeclaration *substitute_decl(SubstDecl &subst, CPPScope *current_scope, @@ -68,7 +68,7 @@ public: virtual bool is_convertible_to(const CPPType *other) const; virtual bool is_equivalent(const CPPType &other) const; - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; virtual SubType get_subtype() const; @@ -83,7 +83,7 @@ protected: virtual bool is_less(const CPPDeclaration *other) const; bool _subst_decl_recursive_protect; - typedef vector Proxies; + typedef std::vector Proxies; Proxies _proxies; }; diff --git a/dtool/src/cppparser/cppUsing.cxx b/dtool/src/cppparser/cppUsing.cxx index 3611450de6..146f8f3f48 100644 --- a/dtool/src/cppparser/cppUsing.cxx +++ b/dtool/src/cppparser/cppUsing.cxx @@ -28,7 +28,7 @@ CPPUsing(CPPIdentifier *ident, bool full_namespace, const CPPFile &file) : * */ void CPPUsing:: -output(ostream &out, int, CPPScope *, bool) const { +output(std::ostream &out, int, CPPScope *, bool) const { out << "using "; if (_full_namespace) { out << "namespace "; diff --git a/dtool/src/cppparser/cppUsing.h b/dtool/src/cppparser/cppUsing.h index 0ec72c8ebf..13de9ce855 100644 --- a/dtool/src/cppparser/cppUsing.h +++ b/dtool/src/cppparser/cppUsing.h @@ -28,7 +28,7 @@ class CPPUsing : public CPPDeclaration { public: CPPUsing(CPPIdentifier *ident, bool full_namespace, const CPPFile &file); - virtual void output(ostream &out, int indent_level, CPPScope *scope, + virtual void output(std::ostream &out, int indent_level, CPPScope *scope, bool complete) const; virtual SubType get_subtype() const; diff --git a/dtool/src/cppparser/cppVisibility.cxx b/dtool/src/cppparser/cppVisibility.cxx index 6cee2a70f3..92273c00a3 100644 --- a/dtool/src/cppparser/cppVisibility.cxx +++ b/dtool/src/cppparser/cppVisibility.cxx @@ -13,8 +13,8 @@ #include "cppVisibility.h" -ostream & -operator << (ostream &out, CPPVisibility vis) { +std::ostream & +operator << (std::ostream &out, CPPVisibility vis) { switch (vis) { case V_published: return out << "__published"; diff --git a/dtool/src/cppparser/cppVisibility.h b/dtool/src/cppparser/cppVisibility.h index 07d3bfdcb5..7165aaecc1 100644 --- a/dtool/src/cppparser/cppVisibility.h +++ b/dtool/src/cppparser/cppVisibility.h @@ -24,6 +24,6 @@ enum CPPVisibility { V_unknown }; -ostream &operator << (ostream &out, CPPVisibility vis); +std::ostream &operator << (std::ostream &out, CPPVisibility vis); #endif diff --git a/dtool/src/dconfig/dconfig.I b/dtool/src/dconfig/dconfig.I index a49d57cd2c..e40db3c2b0 100644 --- a/dtool/src/dconfig/dconfig.I +++ b/dtool/src/dconfig/dconfig.I @@ -12,31 +12,31 @@ */ bool DConfig:: -GetBool(const string &sym, bool def) { +GetBool(const std::string &sym, bool def) { ConfigVariableBool var(sym, def, "DConfig", ConfigFlags::F_dconfig); return var.get_value(); } int DConfig:: -GetInt(const string &sym, int def) { +GetInt(const std::string &sym, int def) { ConfigVariableInt var(sym, def, "DConfig", ConfigFlags::F_dconfig); return var.get_value(); } float DConfig:: -GetFloat(const string &sym, float def) { - ConfigVariableDouble var(sym, def, "DConfig", ConfigFlags::F_dconfig); +GetFloat(const std::string &sym, float def) { + ConfigVariableDouble var(sym, (double)def, "DConfig", ConfigFlags::F_dconfig); return (float)var.get_value(); } double DConfig:: -GetDouble(const string &sym, double def) { +GetDouble(const std::string &sym, double def) { ConfigVariableDouble var(sym, def, "DConfig", ConfigFlags::F_dconfig); return var.get_value(); } -string DConfig:: -GetString(const string &sym, const string &def) { +std::string DConfig:: +GetString(const std::string &sym, const std::string &def) { ConfigVariableString var(sym, def, "DConfig", ConfigFlags::F_dconfig); return var.get_value(); } diff --git a/dtool/src/dconfig/dconfig.h b/dtool/src/dconfig/dconfig.h index ede79f596f..fca35685ed 100644 --- a/dtool/src/dconfig/dconfig.h +++ b/dtool/src/dconfig/dconfig.h @@ -32,11 +32,11 @@ */ class EXPCL_DTOOL_DCONFIG DConfig { PUBLISHED: - static INLINE bool GetBool(const string &sym, bool def = false); - static INLINE int GetInt(const string &sym, int def = 0); - static INLINE float GetFloat(const string &sym, float def = 0.); - static INLINE double GetDouble(const string &sym, double def = 0.); - static INLINE string GetString(const string &sym, const string &def = ""); + static INLINE bool GetBool(const std::string &sym, bool def = false); + static INLINE int GetInt(const std::string &sym, int def = 0); + static INLINE float GetFloat(const std::string &sym, float def = 0.); + static INLINE double GetDouble(const std::string &sym, double def = 0.); + static INLINE std::string GetString(const std::string &sym, const std::string &def = ""); }; #include "dconfig.I" diff --git a/dtool/src/dconfig/test_config.cxx b/dtool/src/dconfig/test_config.cxx index 40f27e7197..2374bd775e 100644 --- a/dtool/src/dconfig/test_config.cxx +++ b/dtool/src/dconfig/test_config.cxx @@ -13,6 +13,9 @@ #include "dconfig.h" +using std::cout; +using std::endl; + #define SNARF Configure(test); diff --git a/dtool/src/dconfig/test_expand.cxx b/dtool/src/dconfig/test_expand.cxx index 281e8b02ba..334bf2593d 100644 --- a/dtool/src/dconfig/test_expand.cxx +++ b/dtool/src/dconfig/test_expand.cxx @@ -14,6 +14,9 @@ #include "expand.h" #include +using std::cout; +using std::endl; + void TestExpandFunction() { std::string line; diff --git a/dtool/src/dconfig/test_pfstream.cxx b/dtool/src/dconfig/test_pfstream.cxx index 29874a97ac..9b211c2381 100644 --- a/dtool/src/dconfig/test_pfstream.cxx +++ b/dtool/src/dconfig/test_pfstream.cxx @@ -14,13 +14,13 @@ #include "pfstream.h" #include -void ReadIt(istream& ifs) { +void ReadIt(std::istream& ifs) { std::string line; while (!ifs.eof()) { std::getline(ifs, line); if (line.length() != 0) - cout << line << endl; + std::cout << line << std::endl; } } diff --git a/dtool/src/dconfig/test_searchpath.cxx b/dtool/src/dconfig/test_searchpath.cxx index edcb8a13cd..4abf1f71bd 100644 --- a/dtool/src/dconfig/test_searchpath.cxx +++ b/dtool/src/dconfig/test_searchpath.cxx @@ -15,6 +15,9 @@ // #include "expand.h" #include +using std::cout; +using std::endl; + void TestSearch() { std::string line, path; diff --git a/dtool/src/dtoolbase/atomicAdjustDummyImpl.I b/dtool/src/dtoolbase/atomicAdjustDummyImpl.I index a08d6ce130..54d6e6b860 100644 --- a/dtool/src/dtoolbase/atomicAdjustDummyImpl.I +++ b/dtool/src/dtoolbase/atomicAdjustDummyImpl.I @@ -30,10 +30,13 @@ dec(TVOLATILE AtomicAdjustDummyImpl::Integer &var) { /** * Atomically computes var += delta. It is legal for delta to be negative. + * Returns the result of the addition. */ -ALWAYS_INLINE void AtomicAdjustDummyImpl:: +ALWAYS_INLINE AtomicAdjustDummyImpl::Integer AtomicAdjustDummyImpl:: add(TVOLATILE AtomicAdjustDummyImpl::Integer &var, AtomicAdjustDummyImpl::Integer delta) { - var += delta; + Integer new_value = var + delta; + var = new_value; + return new_value; } /** diff --git a/dtool/src/dtoolbase/atomicAdjustDummyImpl.h b/dtool/src/dtoolbase/atomicAdjustDummyImpl.h index 120fbe195a..3257ae8dfd 100644 --- a/dtool/src/dtoolbase/atomicAdjustDummyImpl.h +++ b/dtool/src/dtoolbase/atomicAdjustDummyImpl.h @@ -31,7 +31,7 @@ public: ALWAYS_INLINE static void inc(TVOLATILE Integer &var); ALWAYS_INLINE static bool dec(TVOLATILE Integer &var); - ALWAYS_INLINE static void add(TVOLATILE Integer &var, Integer delta); + ALWAYS_INLINE static Integer add(TVOLATILE Integer &var, Integer delta); ALWAYS_INLINE static Integer set(TVOLATILE Integer &var, Integer new_value); ALWAYS_INLINE static Integer get(const TVOLATILE Integer &var); diff --git a/dtool/src/dtoolbase/atomicAdjustGccImpl.I b/dtool/src/dtoolbase/atomicAdjustGccImpl.I index 5becaaa4c0..682b14bed3 100644 --- a/dtool/src/dtoolbase/atomicAdjustGccImpl.I +++ b/dtool/src/dtoolbase/atomicAdjustGccImpl.I @@ -30,11 +30,12 @@ dec(TVOLATILE AtomicAdjustGccImpl::Integer &var) { /** * Atomically computes var += delta. It is legal for delta to be negative. + * Returns the result of the addition. */ -INLINE void AtomicAdjustGccImpl:: +INLINE AtomicAdjustGccImpl::Integer AtomicAdjustGccImpl:: add(TVOLATILE AtomicAdjustGccImpl::Integer &var, AtomicAdjustGccImpl::Integer delta) { - __atomic_fetch_add(&var, delta, __ATOMIC_SEQ_CST); + return __atomic_add_fetch(&var, delta, __ATOMIC_SEQ_CST); } /** diff --git a/dtool/src/dtoolbase/atomicAdjustGccImpl.h b/dtool/src/dtoolbase/atomicAdjustGccImpl.h index 7ae44037ff..57389c1349 100644 --- a/dtool/src/dtoolbase/atomicAdjustGccImpl.h +++ b/dtool/src/dtoolbase/atomicAdjustGccImpl.h @@ -35,7 +35,7 @@ public: INLINE static void inc(TVOLATILE Integer &var); INLINE static bool dec(TVOLATILE Integer &var); - INLINE static void add(TVOLATILE Integer &var, Integer delta); + INLINE static Integer add(TVOLATILE Integer &var, Integer delta); INLINE static Integer set(TVOLATILE Integer &var, Integer new_value); INLINE static Integer get(const TVOLATILE Integer &var); diff --git a/dtool/src/dtoolbase/atomicAdjustI386Impl.I b/dtool/src/dtoolbase/atomicAdjustI386Impl.I index 3841479b28..98208c8655 100644 --- a/dtool/src/dtoolbase/atomicAdjustI386Impl.I +++ b/dtool/src/dtoolbase/atomicAdjustI386Impl.I @@ -59,14 +59,18 @@ dec(TVOLATILE AtomicAdjustI386Impl::Integer &var) { /** * Atomically computes var += delta. It is legal for delta to be negative. + * Returns the result of the addition. */ -INLINE void AtomicAdjustI386Impl:: +INLINE AtomicAdjustI386Impl::Integer AtomicAdjustI386Impl:: add(TVOLATILE AtomicAdjustI386Impl::Integer &var, AtomicAdjustI386Impl::Integer delta) { assert((((size_t)&var) & (sizeof(Integer) - 1)) == 0); Integer orig_value = var; - while (compare_and_exchange(var, orig_value, orig_value + delta) != orig_value) { + Integer new_value = orig_value + delta; + while (compare_and_exchange(var, orig_value, new_value) != orig_value) { orig_value = var; + new_value = orig_value + delta; } + return new_value; } /** diff --git a/dtool/src/dtoolbase/atomicAdjustI386Impl.h b/dtool/src/dtoolbase/atomicAdjustI386Impl.h index eac5ce6a97..bcd1a62c61 100644 --- a/dtool/src/dtoolbase/atomicAdjustI386Impl.h +++ b/dtool/src/dtoolbase/atomicAdjustI386Impl.h @@ -34,7 +34,7 @@ public: INLINE static void inc(TVOLATILE Integer &var); INLINE static bool dec(TVOLATILE Integer &var); - INLINE static void add(TVOLATILE Integer &var, Integer delta); + INLINE static Integer add(TVOLATILE Integer &var, Integer delta); INLINE static Integer set(TVOLATILE Integer &var, Integer new_value); INLINE static Integer get(const TVOLATILE Integer &var); diff --git a/dtool/src/dtoolbase/atomicAdjustPosixImpl.I b/dtool/src/dtoolbase/atomicAdjustPosixImpl.I index ef3d43f053..09636c39c7 100644 --- a/dtool/src/dtoolbase/atomicAdjustPosixImpl.I +++ b/dtool/src/dtoolbase/atomicAdjustPosixImpl.I @@ -35,13 +35,16 @@ dec(TVOLATILE AtomicAdjustPosixImpl::Integer &var) { /** * Atomically computes var += delta. It is legal for delta to be negative. + * Returns the result of the addition. */ -INLINE void AtomicAdjustPosixImpl:: +INLINE AtomicAdjustPosixImpl::Integer AtomicAdjustPosixImpl:: add(TVOLATILE AtomicAdjustPosixImpl::Integer &var, AtomicAdjustPosixImpl::Integer delta) { pthread_mutex_lock(&_mutex); - var += delta; + Integer new_value = var + delta; + var = new_value; pthread_mutex_unlock(&_mutex); + return new_value; } /** diff --git a/dtool/src/dtoolbase/atomicAdjustPosixImpl.h b/dtool/src/dtoolbase/atomicAdjustPosixImpl.h index 3b98499129..8c2b2b5887 100644 --- a/dtool/src/dtoolbase/atomicAdjustPosixImpl.h +++ b/dtool/src/dtoolbase/atomicAdjustPosixImpl.h @@ -35,7 +35,7 @@ public: INLINE static void inc(TVOLATILE Integer &var); INLINE static bool dec(TVOLATILE Integer &var); - INLINE static void add(TVOLATILE Integer &var, Integer delta); + INLINE static Integer add(TVOLATILE Integer &var, Integer delta); INLINE static Integer set(TVOLATILE Integer &var, Integer new_value); INLINE static Integer get(const TVOLATILE Integer &var); diff --git a/dtool/src/dtoolbase/atomicAdjustWin32Impl.I b/dtool/src/dtoolbase/atomicAdjustWin32Impl.I index a0e213c638..851c9f05e2 100644 --- a/dtool/src/dtoolbase/atomicAdjustWin32Impl.I +++ b/dtool/src/dtoolbase/atomicAdjustWin32Impl.I @@ -40,17 +40,21 @@ dec(TVOLATILE AtomicAdjustWin32Impl::Integer &var) { /** * Atomically computes var += delta. It is legal for delta to be negative. + * Returns the result of the addition. */ -INLINE void AtomicAdjustWin32Impl:: +INLINE AtomicAdjustWin32Impl::Integer AtomicAdjustWin32Impl:: add(TVOLATILE AtomicAdjustWin32Impl::Integer &var, AtomicAdjustWin32Impl::Integer delta) { assert((((size_t)&var) & (sizeof(Integer) - 1)) == 0); #ifdef _WIN64 - InterlockedAdd64(&var, delta); + return InterlockedAdd64(&var, delta); #else - AtomicAdjustWin32Impl::Integer orig_value = var; - while (compare_and_exchange(var, orig_value, orig_value + delta) != orig_value) { + Integer orig_value = var; + Integer new_value = orig_value + delta; + while (compare_and_exchange(var, orig_value, new_value) != orig_value) { orig_value = var; + new_value = orig_value + delta; } + return new_value; #endif // _WIN64 } diff --git a/dtool/src/dtoolbase/atomicAdjustWin32Impl.h b/dtool/src/dtoolbase/atomicAdjustWin32Impl.h index 6f64d2a781..25f2e78066 100644 --- a/dtool/src/dtoolbase/atomicAdjustWin32Impl.h +++ b/dtool/src/dtoolbase/atomicAdjustWin32Impl.h @@ -44,7 +44,7 @@ public: ALWAYS_INLINE static void inc(TVOLATILE Integer &var); ALWAYS_INLINE static bool dec(TVOLATILE Integer &var); - INLINE static void add(TVOLATILE Integer &var, Integer delta); + INLINE static Integer add(TVOLATILE Integer &var, Integer delta); ALWAYS_INLINE static Integer set(TVOLATILE Integer &var, Integer new_value); ALWAYS_INLINE static Integer get(const TVOLATILE Integer &var); diff --git a/dtool/src/dtoolbase/deletedBufferChain.I b/dtool/src/dtoolbase/deletedBufferChain.I index 7f6a003f64..9eb17bd4fb 100644 --- a/dtool/src/dtoolbase/deletedBufferChain.I +++ b/dtool/src/dtoolbase/deletedBufferChain.I @@ -21,7 +21,7 @@ INLINE bool DeletedBufferChain:: validate(void *ptr) { TAU_PROFILE("bool DeletedBufferChain::validate(void *)", " ", TAU_USER); - if (ptr == (void *)NULL) { + if (ptr == nullptr) { return false; } diff --git a/dtool/src/dtoolbase/deletedBufferChain.cxx b/dtool/src/dtoolbase/deletedBufferChain.cxx index 27d7214d79..d009510ad3 100644 --- a/dtool/src/dtoolbase/deletedBufferChain.cxx +++ b/dtool/src/dtoolbase/deletedBufferChain.cxx @@ -20,11 +20,11 @@ */ DeletedBufferChain:: DeletedBufferChain(size_t buffer_size) { - _deleted_chain = NULL; + _deleted_chain = nullptr; _buffer_size = buffer_size; // We must allocate at least this much space for bookkeeping reasons. - _buffer_size = max(_buffer_size, sizeof(ObjectNode)); + _buffer_size = std::max(_buffer_size, sizeof(ObjectNode)); } /** @@ -43,11 +43,11 @@ allocate(size_t size, TypeHandle type_handle) { ObjectNode *obj; - _lock.acquire(); - if (_deleted_chain != (ObjectNode *)NULL) { + _lock.lock(); + if (_deleted_chain != nullptr) { obj = _deleted_chain; _deleted_chain = _deleted_chain->_next; - _lock.release(); + _lock.unlock(); #ifdef USE_DELETEDCHAINFLAG assert(obj->_flag == (AtomicAdjust::Integer)DCF_deleted); @@ -64,7 +64,7 @@ allocate(size_t size, TypeHandle type_handle) { return ptr; } - _lock.release(); + _lock.unlock(); // If we get here, the deleted_chain is empty; we have to allocate a new // object from the system pool. @@ -103,7 +103,7 @@ deallocate(void *ptr, TypeHandle type_handle) { #ifdef USE_DELETED_CHAIN // TAU_PROFILE("void DeletedBufferChain::deallocate(void *, TypeHandle)", " // ", TAU_USER); - assert(ptr != (void *)NULL); + assert(ptr != nullptr); #ifdef DO_MEMORY_USAGE const size_t alloc_size = _buffer_size + flag_reserved_bytes + MEMORY_HOOK_ALIGNMENT - 1; @@ -126,12 +126,12 @@ deallocate(void *ptr, TypeHandle type_handle) { assert(orig_flag == (AtomicAdjust::Integer)DCF_alive); #endif // USE_DELETEDCHAINFLAG - _lock.acquire(); + _lock.lock(); obj->_next = _deleted_chain; _deleted_chain = obj; - _lock.release(); + _lock.unlock(); #else // USE_DELETED_CHAIN PANDA_FREE_SINGLE(ptr); diff --git a/dtool/src/dtoolbase/deletedChain.h b/dtool/src/dtoolbase/deletedChain.h index a25be5d429..1915223450 100644 --- a/dtool/src/dtoolbase/deletedChain.h +++ b/dtool/src/dtoolbase/deletedChain.h @@ -122,11 +122,11 @@ public: #define ALLOC_DELETED_CHAIN(Type) \ inline static bool validate_ptr(const void *ptr) { \ - return (ptr != NULL); \ + return (ptr != nullptr); \ } #define ALLOC_DELETED_CHAIN_DECL(Type) \ inline static bool validate_ptr(const void *ptr) { \ - return (ptr != NULL); \ + return (ptr != nullptr); \ } #define ALLOC_DELETED_CHAIN_DEF(Type) diff --git a/dtool/src/dtoolbase/dtoolbase.cxx b/dtool/src/dtoolbase/dtoolbase.cxx index 64b7425057..10d1790ccf 100644 --- a/dtool/src/dtoolbase/dtoolbase.cxx +++ b/dtool/src/dtoolbase/dtoolbase.cxx @@ -36,7 +36,7 @@ MemoryHook *memory_hook; */ void init_memory_hook() { - if (memory_hook == NULL) { + if (memory_hook == nullptr) { memory_hook = new MemoryHook; } } diff --git a/dtool/src/dtoolbase/dtoolbase.h b/dtool/src/dtoolbase/dtoolbase.h index 3f8e07f998..f21e653695 100644 --- a/dtool/src/dtoolbase/dtoolbase.h +++ b/dtool/src/dtoolbase/dtoolbase.h @@ -60,6 +60,12 @@ #pragma warning (disable : 4577) #endif /* WIN32_VC */ +/* Windows likes to define min() and max() macros, which will conflict with + std::min() and std::max() respectively, unless we do this: */ +#ifdef WIN32 +#define NOMINMAX +#endif + #ifndef __has_builtin #define __has_builtin(x) 0 #endif @@ -73,10 +79,10 @@ // 'assume at least one of the cases is always true') #ifdef _DEBUG #define NODEFAULT default: assert(0); break; -#elif defined(_MSC_VER) -#define NODEFAULT default: __assume(0); // special VC keyword #elif __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) || __has_builtin(__builtin_unreachable) #define NODEFAULT default: __builtin_unreachable(); +#elif defined(_MSC_VER) +#define NODEFAULT default: __assume(0); // special VC keyword #else #define NODEFAULT #endif @@ -123,7 +129,7 @@ // This is a workaround for a glibc bug that is triggered by clang when // compiling with -ffast-math. -#ifdef __clang__ +#if defined(__clang__) && defined(__GLIBC__) #include #ifndef __extern_always_inline #define __extern_always_inline extern __always_inline @@ -198,10 +204,6 @@ typedef struct _object PyObject; #include #endif -#ifdef PHAVE_MINMAX_H -#include -#endif - #ifdef PHAVE_SYS_TIME_H #include #endif diff --git a/dtool/src/dtoolbase/dtoolbase_cc.h b/dtool/src/dtoolbase/dtoolbase_cc.h index 81968085bc..b4ce1d597c 100644 --- a/dtool/src/dtoolbase/dtoolbase_cc.h +++ b/dtool/src/dtoolbase/dtoolbase_cc.h @@ -19,6 +19,13 @@ #ifdef __cplusplus +// By including checkPandaVersion.h, we guarantee that runtime attempts to +// load any DLL will fail if they inadvertently link with the wrong version of +// dtool, which, transitively, means all DLLs must be from the same +// (ABI-compatible) version of Panda. + +#include "checkPandaVersion.h" + #ifdef USE_TAU // Tau provides this destructive version of stdbool.h that we must mask. #define __PDT_STDBOOL_H_ @@ -26,23 +33,14 @@ #ifdef CPPPARSER #include +#include #include - -using namespace std; +#include +#include #define INLINE inline #define ALWAYS_INLINE inline -#define TYPENAME typename -#define CONSTEXPR constexpr -#define ALWAYS_INLINE_CONSTEXPR constexpr -#define NOEXCEPT noexcept -#define FINAL final #define MOVE(x) x -#define DEFAULT_CTOR = default -#define DEFAULT_DTOR = default -#define DEFAULT_ASSIGN = default -#define DELETED = delete -#define DELETED_ASSIGN = delete #define EXPORT_TEMPLATE_CLASS(expcl, exptp, classname) @@ -80,31 +78,7 @@ typedef int ios_seekdir; #include #include - -#ifdef HAVE_NAMESPACE -using namespace std; -#endif - -#ifdef HAVE_TYPENAME -#define TYPENAME typename -#else -#define TYPENAME -#endif - -#ifndef HAVE_WCHAR_T -// Some C++ libraries (os x 3.1) don't define this. -typedef unsigned short wchar_t; -#endif - -#ifndef HAVE_WSTRING -// Some C++ libraries (gcc 2.95) don't define this. -typedef basic_string wstring; -#endif - -#ifndef HAVE_STREAMSIZE -// Some C++ libraries (Irix) don't define this. -typedef long streamsize; -#endif +#include #ifndef HAVE_IOS_TYPEDEFS typedef int ios_openmode; @@ -113,10 +87,10 @@ typedef int ios_iostate; // Old iostream libraries used ios::seek_dir instead of ios::seekdir. typedef ios::seek_dir ios_seekdir; #else -typedef ios::openmode ios_openmode; -typedef ios::fmtflags ios_fmtflags; -typedef ios::iostate ios_iostate; -typedef ios::seekdir ios_seekdir; +typedef std::ios::openmode ios_openmode; +typedef std::ios::fmtflags ios_fmtflags; +typedef std::ios::iostate ios_iostate; +typedef std::ios::seekdir ios_seekdir; #endif // Apple has an outdated libstdc++. Not all is lost, though, as we can fill @@ -124,18 +98,20 @@ typedef ios::seekdir ios_seekdir; #if defined(__GLIBCXX__) && __GLIBCXX__ <= 20070719 #include -using std::tr1::tuple; -using std::tr1::tie; +namespace std { + using std::tr1::tuple; + using std::tr1::tie; -typedef decltype(nullptr) nullptr_t; + typedef decltype(nullptr) nullptr_t; -template struct remove_reference {typedef T type;}; -template struct remove_reference {typedef T type;}; -template struct remove_reference{typedef T type;}; + template struct remove_reference {typedef T type;}; + template struct remove_reference {typedef T type;}; + template struct remove_reference{typedef T type;}; -template typename remove_reference::type &&move(T &&t) { - return static_cast::type&&>(t); -} + template typename remove_reference::type &&move(T &&t) { + return static_cast::type&&>(t); + } +}; #endif #ifdef _MSC_VER @@ -156,110 +132,12 @@ template typename remove_reference::type &&move(T &&t) { #endif // Determine the availability of C++11 features. -#if defined(__has_extension) // Clang magic. -# if __has_extension(cxx_constexpr) -# if !defined(__apple_build_version__) || __apple_build_version__ >= 5000000 -# define CONSTEXPR constexpr -# endif -# endif -# if __has_extension(cxx_noexcept) -# define NOEXCEPT noexcept -# endif -# if __has_extension(cxx_rvalue_references) && (__cplusplus >= 201103L) -# define USE_MOVE_SEMANTICS -# define MOVE(x) move(x) -# endif -# if __has_extension(cxx_override_control) && (__cplusplus >= 201103L) -# define FINAL final -# endif -# if __has_extension(cxx_defaulted_functions) -# define DEFAULT_CTOR = default -# define DEFAULT_DTOR = default -# define DEFAULT_ASSIGN = default -# endif -# if __has_extension(cxx_deleted_functions) -# define DELETED = delete -# endif -#elif defined(__GNUC__) // GCC - -// Starting at GCC 4.4 -# if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4) -# define DEFAULT_CTOR = default -# define DEFAULT_DTOR = default -# define DEFAULT_ASSIGN = default -# define DELETED = delete -# endif - -// Starting at GCC 4.6 -# if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) -# define CONSTEXPR constexpr -# define NOEXCEPT noexcept -# define USE_MOVE_SEMANTICS -# define MOVE(x) move(x) -# endif - -// Starting at GCC 4.7 -# if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7) -# define FINAL final -# endif - -// GCC defines several macros which we can query. List of all supported -// builtin macros: https://gcc.gnu.org/projects/cxx-status.html -# if !defined(CONSTEXPR) && __cpp_constexpr >= 200704 -# define CONSTEXPR constexpr -# endif - -#elif defined(_MSC_VER) && _MSC_VER >= 1900 // Visual Studio 2015 -# define CONSTEXPR constexpr -# define NOEXCEPT noexcept -# define USE_MOVE_SEMANTICS -# define FINAL final -# define MOVE(x) move(x) -#elif defined(_MSC_VER) && _MSC_VER >= 1600 // Visual Studio 2010 -# define NOEXCEPT throw() -# define USE_MOVE_SEMANTICS -# define FINAL sealed -# define MOVE(x) move(x) +#if defined(_MSC_VER) && _MSC_VER < 1900 // Visual Studio 2015 +#error Microsoft Visual C++ 2015 or later is required to compile Panda3D. #endif -#if defined(_MSC_VER) && _MSC_VER >= 1800 // Visual Studio 2013 -# define DEFAULT_CTOR = default -# define DEFAULT_DTOR = default -# define DEFAULT_ASSIGN = default -# define DELETED = delete -#endif - -// Fallbacks if features are not supported -#ifndef CONSTEXPR -# define CONSTEXPR INLINE -# define ALWAYS_INLINE_CONSTEXPR ALWAYS_INLINE -#else -# define ALWAYS_INLINE_CONSTEXPR ALWAYS_INLINE CONSTEXPR -#endif -#ifndef NOEXCEPT -# define NOEXCEPT -#endif -#ifndef MOVE -# define MOVE(x) x -#endif -#ifndef FINAL -# define FINAL -#endif -#ifndef DEFAULT_CTOR -# define DEFAULT_CTOR {} -#endif -#ifndef DEFAULT_DTOR -# define DEFAULT_DTOR {} -#endif -#ifndef DEFAULT_ASSIGN -# define DEFAULT_ASSIGN {return *this;} -#endif -#ifndef DELETED -# define DELETED {assert(false);} -# define DELETED_ASSIGN {assert(false);return *this;} -#else -# define DELETED_ASSIGN DELETED -#endif +// This is just to support code generated with older versions of interrogate. +#define MOVE(x) (std::move(x)) #ifndef LINK_ALL_STATIC diff --git a/dtool/src/dtoolbase/epvector.h b/dtool/src/dtoolbase/epvector.h index c3c650d015..e743ea4060 100644 --- a/dtool/src/dtoolbase/epvector.h +++ b/dtool/src/dtoolbase/epvector.h @@ -35,11 +35,11 @@ * kids. */ template -class epvector : public vector > { +class epvector : public std::vector > { public: typedef Eigen::aligned_allocator allocator; - typedef vector base_class; - typedef TYPENAME base_class::size_type size_type; + typedef std::vector base_class; + typedef typename base_class::size_type size_type; epvector(TypeHandle type_handle = pvector_type_handle) : base_class(allocator()) { } epvector(const epvector ©) : base_class(copy) { } diff --git a/dtool/src/dtoolbase/fakestringstream.h b/dtool/src/dtoolbase/fakestringstream.h index 6711eb8d2a..da2ba6880f 100644 --- a/dtool/src/dtoolbase/fakestringstream.h +++ b/dtool/src/dtoolbase/fakestringstream.h @@ -18,17 +18,13 @@ #include #include -#ifdef HAVE_NAMESPACE -using namespace std; -#endif - class fake_istream_buffer { public: fake_istream_buffer() { _len = 0; _str = ""; } - fake_istream_buffer(const string &source) { + fake_istream_buffer(const std::string &source) { _len = source.length(); if (_len == 0) { _str = ""; @@ -47,20 +43,20 @@ public: char *_str; }; -class istringstream : public fake_istream_buffer, public istrstream { +class std::istringstream : public fake_istream_buffer, public istrstream { public: - istringstream(const string &input) : + std::istringstream(const std::string &input) : fake_istream_buffer(input), istrstream(_str, _len) { } }; -class ostringstream : public ostrstream { +class std::ostringstream : public ostrstream { public: - string str() { + std::string str() { // We must capture the length before we take the str(). int length = pcount(); char *s = ostrstream::str(); - string result(s, length); + std::string result(s, length); delete[] s; return result; } @@ -71,9 +67,9 @@ public: stringstream() : strstream() { _owns_str = true; } - stringstream(const string &input) : + std::stringstream(const std::string &input) : fake_istream_buffer(input), - strstream(_str, _len, ios::in) + strstream(_str, _len, std::ios::in) { _owns_str = false; } diff --git a/dtool/src/dtoolbase/indent.I b/dtool/src/dtoolbase/indent.I index db990ebe1d..3e612a369b 100644 --- a/dtool/src/dtoolbase/indent.I +++ b/dtool/src/dtoolbase/indent.I @@ -19,9 +19,9 @@ */ template void -write_long_list(ostream &out, int indent_level, +write_long_list(std::ostream &out, int indent_level, InputIterator first, InputIterator last, - string first_prefix, string later_prefix, + std::string first_prefix, std::string later_prefix, int max_col) { if (later_prefix.empty()) { later_prefix = first_prefix; @@ -30,9 +30,9 @@ write_long_list(ostream &out, int indent_level, if (first != last) { // We have to use an intermediate strstream object so we can count the // number of characters the item will have when it is output. - ostringstream item; + std::ostringstream item; item << *first; - string str = item.str(); + std::string str = item.str(); indent(out, indent_level) << first_prefix << str; int col = indent_level + (int)(first_prefix.length() + str.length()); @@ -40,9 +40,9 @@ write_long_list(ostream &out, int indent_level, ++first; while (first != last) { - ostringstream item; + std::ostringstream item; item << *first; - string str = item.str(); + std::string str = item.str(); col += 1 + str.length(); if (col > max_col) { diff --git a/dtool/src/dtoolbase/indent.cxx b/dtool/src/dtoolbase/indent.cxx index bf33828d03..df66a47197 100644 --- a/dtool/src/dtoolbase/indent.cxx +++ b/dtool/src/dtoolbase/indent.cxx @@ -16,8 +16,8 @@ /** * */ -ostream & -indent(ostream &out, int indent_level) { +std::ostream & +indent(std::ostream &out, int indent_level) { for (int i = 0; i < indent_level; i++) { out << ' '; } diff --git a/dtool/src/dtoolbase/indent.h b/dtool/src/dtoolbase/indent.h index 93badf5e7d..c012ff1fe3 100644 --- a/dtool/src/dtoolbase/indent.h +++ b/dtool/src/dtoolbase/indent.h @@ -22,8 +22,8 @@ * stream itself. Useful for indenting a series of lines of text by a given * amount. */ -EXPCL_DTOOL_DTOOLBASE ostream & -indent(ostream &out, int indent_level); +EXPCL_DTOOL_DTOOLBASE std::ostream & +indent(std::ostream &out, int indent_level); /** * Writes a list of things to the indicated output stream, with a space @@ -33,10 +33,10 @@ indent(ostream &out, int indent_level); */ template void -write_long_list(ostream &out, int indent_level, +write_long_list(std::ostream &out, int indent_level, InputIterator ifirst, InputIterator ilast, - string first_prefix = "", - string later_prefix = "", + std::string first_prefix = "", + std::string later_prefix = "", int max_col = 72); #include "indent.I" diff --git a/dtool/src/dtoolbase/memoryHook.I b/dtool/src/dtoolbase/memoryHook.I index bd5a55af79..cc4f972f6b 100644 --- a/dtool/src/dtoolbase/memoryHook.I +++ b/dtool/src/dtoolbase/memoryHook.I @@ -34,15 +34,6 @@ dec_heap(size_t size) { #endif // DO_MEMORY_USAGE } -/** - * Returns the global memory alignment. This is the number of bytes at which - * each allocated memory pointer will be aligned. - */ -CONSTEXPR size_t MemoryHook:: -get_memory_alignment() { - return MEMORY_HOOK_ALIGNMENT; -} - /** * Returns the operating system page size. This is the minimum granularity * required for calls to mmap_alloc(). Also see round_up_to_page_size(). diff --git a/dtool/src/dtoolbase/memoryHook.cxx b/dtool/src/dtoolbase/memoryHook.cxx index 510b5b2688..24d5f11a11 100644 --- a/dtool/src/dtoolbase/memoryHook.cxx +++ b/dtool/src/dtoolbase/memoryHook.cxx @@ -37,6 +37,8 @@ #endif // WIN32 +using std::cerr; + // Ensure we made the right decisions about the alignment size. static_assert(MEMORY_HOOK_ALIGNMENT >= sizeof(size_t), "MEMORY_HOOK_ALIGNMENT should at least be sizeof(size_t)"); @@ -216,16 +218,16 @@ MemoryHook() { */ MemoryHook:: MemoryHook(const MemoryHook ©) : - _page_size(copy._page_size), _total_heap_single_size(copy._total_heap_single_size), _total_heap_array_size(copy._total_heap_array_size), _requested_heap_size(copy._requested_heap_size), _total_mmap_size(copy._total_mmap_size), - _max_heap_size(copy._max_heap_size) { + _max_heap_size(copy._max_heap_size), + _page_size(copy._page_size) { - copy._lock.acquire(); + copy._lock.lock(); _deleted_chains = copy._deleted_chains; - copy._lock.release(); + copy._lock.unlock(); } /** @@ -249,19 +251,19 @@ heap_alloc_single(size_t size) { size_t inflated_size = inflate_size(size); #ifdef MEMORY_HOOK_MALLOC_LOCK - _lock.acquire(); + _lock.lock(); void *alloc = call_malloc(inflated_size); - _lock.release(); + _lock.unlock(); #else void *alloc = call_malloc(inflated_size); #endif - while (alloc == (void *)NULL) { + while (alloc == nullptr) { alloc_fail(inflated_size); #ifdef MEMORY_HOOK_MALLOC_LOCK - _lock.acquire(); + _lock.lock(); alloc = call_malloc(inflated_size); - _lock.release(); + _lock.unlock(); #else alloc = call_malloc(inflated_size); #endif @@ -305,9 +307,9 @@ heap_free_single(void *ptr) { #endif // DO_MEMORY_USAGE #ifdef MEMORY_HOOK_MALLOC_LOCK - _lock.acquire(); + _lock.lock(); call_free(alloc); - _lock.release(); + _lock.unlock(); #else call_free(alloc); #endif @@ -326,19 +328,19 @@ heap_alloc_array(size_t size) { size_t inflated_size = inflate_size(size); #ifdef MEMORY_HOOK_MALLOC_LOCK - _lock.acquire(); + _lock.lock(); void *alloc = call_malloc(inflated_size); - _lock.release(); + _lock.unlock(); #else void *alloc = call_malloc(inflated_size); #endif - while (alloc == (void *)NULL) { + while (alloc == nullptr) { alloc_fail(inflated_size); #ifdef MEMORY_HOOK_MALLOC_LOCK - _lock.acquire(); + _lock.lock(); alloc = call_malloc(inflated_size); - _lock.release(); + _lock.unlock(); #else alloc = call_malloc(inflated_size); #endif @@ -380,23 +382,23 @@ heap_realloc_array(void *ptr, size_t size) { void *alloc1 = alloc; #ifdef MEMORY_HOOK_MALLOC_LOCK - _lock.acquire(); + _lock.lock(); alloc1 = call_realloc(alloc1, inflated_size); - _lock.release(); + _lock.unlock(); #else alloc1 = call_realloc(alloc1, inflated_size); #endif - while (alloc1 == (void *)NULL) { + while (alloc1 == nullptr) { alloc_fail(inflated_size); // Recover the original pointer. alloc1 = alloc; #ifdef MEMORY_HOOK_MALLOC_LOCK - _lock.acquire(); + _lock.lock(); alloc1 = call_realloc(alloc1, inflated_size); - _lock.release(); + _lock.unlock(); #else alloc1 = call_realloc(alloc1, inflated_size); #endif @@ -423,7 +425,7 @@ heap_realloc_array(void *ptr, size_t size) { size_t orig_delta = (char *)ptr - (char *)alloc; size_t new_delta = (char *)ptr1 - (char *)alloc1; if (orig_delta != new_delta) { - memmove((char *)alloc1 + new_delta, (char *)alloc1 + orig_delta, min(size, orig_size)); + memmove((char *)alloc1 + new_delta, (char *)alloc1 + orig_delta, std::min(size, orig_size)); } root[-2] = size; @@ -453,9 +455,9 @@ heap_free_array(void *ptr) { #endif // DO_MEMORY_USAGE #ifdef MEMORY_HOOK_MALLOC_LOCK - _lock.acquire(); + _lock.lock(); call_free(alloc); - _lock.release(); + _lock.unlock(); #else call_free(alloc); #endif @@ -478,11 +480,11 @@ heap_trim(size_t pad) { // Since malloc_trim() isn't standard C, we can't be sure it exists on a // given platform. But if we're using dlmalloc, we know we have // dlmalloc_trim. - _lock.acquire(); + _lock.lock(); if (dlmalloc_trim(pad)) { trimmed = true; } - _lock.release(); + _lock.unlock(); #endif #ifdef WIN32 @@ -517,16 +519,16 @@ mmap_alloc(size_t size, bool allow_exec) { #ifdef WIN32 // Windows case. - void *ptr = VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, + void *ptr = VirtualAlloc(nullptr, size, MEM_COMMIT | MEM_RESERVE, allow_exec ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE); - if (ptr == (void *)NULL) { + if (ptr == nullptr) { DWORD err = GetLastError(); cerr << "Couldn't allocate memory page of size " << size << ": "; PVOID buffer; DWORD length = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, err, 0, (LPTSTR)&buffer, 0, NULL); + nullptr, err, 0, (LPTSTR)&buffer, 0, nullptr); if (length != 0) { cerr << (char *)buffer << "\n"; } else { @@ -545,7 +547,7 @@ mmap_alloc(size_t size, bool allow_exec) { if (allow_exec) { prot |= PROT_EXEC; } - void *ptr = mmap(NULL, size, prot, MAP_PRIVATE | MAP_ANON, -1, 0); + void *ptr = mmap(nullptr, size, prot, MAP_PRIVATE | MAP_ANON, -1, 0); if (ptr == (void *)-1) { perror("mmap"); abort(); @@ -596,7 +598,7 @@ DeletedBufferChain *MemoryHook:: get_deleted_chain(size_t buffer_size) { DeletedBufferChain *chain; - _lock.acquire(); + _lock.lock(); DeletedChains::iterator dci = _deleted_chains.find(buffer_size); if (dci != _deleted_chains.end()) { chain = (*dci).second; @@ -606,7 +608,7 @@ get_deleted_chain(size_t buffer_size) { _deleted_chains.insert(DeletedChains::value_type(buffer_size, chain)); } - _lock.release(); + _lock.unlock(); return chain; } diff --git a/dtool/src/dtoolbase/memoryHook.h b/dtool/src/dtoolbase/memoryHook.h index 9472983d75..11d83439d3 100644 --- a/dtool/src/dtoolbase/memoryHook.h +++ b/dtool/src/dtoolbase/memoryHook.h @@ -52,7 +52,9 @@ public: bool heap_trim(size_t pad); - CONSTEXPR static size_t get_memory_alignment(); + constexpr static size_t get_memory_alignment() { + return MEMORY_HOOK_ALIGNMENT; + } virtual void *mmap_alloc(size_t size, bool allow_exec); virtual void mmap_free(void *ptr, size_t size); @@ -82,7 +84,7 @@ protected: private: size_t _page_size; - typedef map DeletedChains; + typedef std::map DeletedChains; DeletedChains _deleted_chains; mutable MutexImpl _lock; diff --git a/dtool/src/dtoolbase/mutexDummyImpl.I b/dtool/src/dtoolbase/mutexDummyImpl.I index 94afaa2cc5..26a4dd6242 100644 --- a/dtool/src/dtoolbase/mutexDummyImpl.I +++ b/dtool/src/dtoolbase/mutexDummyImpl.I @@ -15,14 +15,14 @@ * */ ALWAYS_INLINE void MutexDummyImpl:: -acquire() { +lock() { } /** * */ ALWAYS_INLINE bool MutexDummyImpl:: -try_acquire() { +try_lock() { return true; } @@ -30,5 +30,5 @@ try_acquire() { * */ ALWAYS_INLINE void MutexDummyImpl:: -release() { +unlock() { } diff --git a/dtool/src/dtoolbase/mutexDummyImpl.h b/dtool/src/dtoolbase/mutexDummyImpl.h index 772f3f8201..3474d443ed 100644 --- a/dtool/src/dtoolbase/mutexDummyImpl.h +++ b/dtool/src/dtoolbase/mutexDummyImpl.h @@ -23,16 +23,15 @@ */ class EXPCL_DTOOL_DTOOLBASE MutexDummyImpl { public: - CONSTEXPR MutexDummyImpl() DEFAULT_CTOR; + constexpr MutexDummyImpl() = default; + MutexDummyImpl(const MutexDummyImpl ©) = delete; -private: - MutexDummyImpl(const MutexDummyImpl ©) DELETED; - MutexDummyImpl &operator = (const MutexDummyImpl ©) DELETED_ASSIGN; + MutexDummyImpl &operator = (const MutexDummyImpl ©) = delete; public: - ALWAYS_INLINE void acquire(); - ALWAYS_INLINE bool try_acquire(); - ALWAYS_INLINE void release(); + ALWAYS_INLINE void lock(); + ALWAYS_INLINE bool try_lock(); + ALWAYS_INLINE void unlock(); }; #include "mutexDummyImpl.I" diff --git a/dtool/src/dtoolbase/mutexPosixImpl.I b/dtool/src/dtoolbase/mutexPosixImpl.I index 05acfae1c2..0bc338a2eb 100644 --- a/dtool/src/dtoolbase/mutexPosixImpl.I +++ b/dtool/src/dtoolbase/mutexPosixImpl.I @@ -14,8 +14,8 @@ /** * */ -CONSTEXPR MutexPosixImpl:: -MutexPosixImpl() NOEXCEPT : _lock(PTHREAD_MUTEX_INITIALIZER) { +constexpr MutexPosixImpl:: +MutexPosixImpl() noexcept : _lock(PTHREAD_MUTEX_INITIALIZER) { } /** @@ -32,8 +32,8 @@ INLINE MutexPosixImpl:: * */ INLINE void MutexPosixImpl:: -acquire() { - TAU_PROFILE("void MutexPosixImpl::acquire", " ", TAU_USER); +lock() { + TAU_PROFILE("void MutexPosixImpl::lock", " ", TAU_USER); int result = pthread_mutex_lock(&_lock); assert(result == 0); } @@ -42,8 +42,8 @@ acquire() { * */ INLINE bool MutexPosixImpl:: -try_acquire() { - TAU_PROFILE("bool MutexPosixImpl::try_acquire", " ", TAU_USER); +try_lock() { + TAU_PROFILE("bool MutexPosixImpl::try_lock", " ", TAU_USER); int result = pthread_mutex_trylock(&_lock); assert(result == 0 || result == EBUSY); return (result == 0); @@ -53,26 +53,18 @@ try_acquire() { * */ INLINE void MutexPosixImpl:: -release() { - TAU_PROFILE("void MutexPosixImpl::release", " ", TAU_USER); +unlock() { + TAU_PROFILE("void MutexPosixImpl::unlock", " ", TAU_USER); int result = pthread_mutex_unlock(&_lock); assert(result == 0); } -/** - * Returns the underlying Posix lock handle. - */ -INLINE pthread_mutex_t *MutexPosixImpl:: -get_posix_lock() { - return &_lock; -} - /** * */ #ifdef PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP -CONSTEXPR ReMutexPosixImpl:: -ReMutexPosixImpl() NOEXCEPT : _lock(PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP) { +constexpr ReMutexPosixImpl:: +ReMutexPosixImpl() noexcept : _lock(PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP) { } #else INLINE ReMutexPosixImpl:: @@ -101,8 +93,8 @@ INLINE ReMutexPosixImpl:: * */ INLINE void ReMutexPosixImpl:: -acquire() { - TAU_PROFILE("void ReMutexPosixImpl::acquire", " ", TAU_USER); +lock() { + TAU_PROFILE("void ReMutexPosixImpl::lock", " ", TAU_USER); int result = pthread_mutex_lock(&_lock); assert(result == 0); } @@ -111,8 +103,8 @@ acquire() { * */ INLINE bool ReMutexPosixImpl:: -try_acquire() { - TAU_PROFILE("bool ReMutexPosixImpl::try_acquire", " ", TAU_USER); +try_lock() { + TAU_PROFILE("bool ReMutexPosixImpl::try_lock", " ", TAU_USER); int result = pthread_mutex_trylock(&_lock); assert(result == 0 || result == EBUSY); return (result == 0); @@ -122,16 +114,8 @@ try_acquire() { * */ INLINE void ReMutexPosixImpl:: -release() { - TAU_PROFILE("void ReMutexPosixImpl::release", " ", TAU_USER); +unlock() { + TAU_PROFILE("void ReMutexPosixImpl::unlock", " ", TAU_USER); int result = pthread_mutex_unlock(&_lock); assert(result == 0); } - -/** - * Returns the underlying Posix lock handle. - */ -INLINE pthread_mutex_t *ReMutexPosixImpl:: -get_posix_lock() { - return &_lock; -} diff --git a/dtool/src/dtoolbase/mutexPosixImpl.h b/dtool/src/dtoolbase/mutexPosixImpl.h index 44b5ab193f..996001b114 100644 --- a/dtool/src/dtoolbase/mutexPosixImpl.h +++ b/dtool/src/dtoolbase/mutexPosixImpl.h @@ -28,19 +28,16 @@ */ class EXPCL_DTOOL_DTOOLBASE MutexPosixImpl { public: - CONSTEXPR MutexPosixImpl() NOEXCEPT; + constexpr MutexPosixImpl() noexcept; + MutexPosixImpl(const MutexPosixImpl ©) = delete; INLINE ~MutexPosixImpl(); -private: - MutexPosixImpl(const MutexPosixImpl ©) DELETED; - MutexPosixImpl &operator = (const MutexPosixImpl ©) DELETED_ASSIGN; + MutexPosixImpl &operator = (const MutexPosixImpl ©) = delete; public: - INLINE void acquire(); - INLINE bool try_acquire(); - INLINE void release(); - - INLINE pthread_mutex_t *get_posix_lock(); + INLINE void lock(); + INLINE bool try_lock(); + INLINE void unlock(); private: pthread_mutex_t _lock; @@ -53,22 +50,19 @@ private: class EXPCL_DTOOL_DTOOLBASE ReMutexPosixImpl { public: #ifdef PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP - CONSTEXPR ReMutexPosixImpl() NOEXCEPT; + constexpr ReMutexPosixImpl() noexcept; #else INLINE ReMutexPosixImpl(); #endif + ReMutexPosixImpl(const ReMutexPosixImpl ©) = delete; INLINE ~ReMutexPosixImpl(); -private: - ReMutexPosixImpl(const ReMutexPosixImpl ©) DELETED; - ReMutexPosixImpl &operator = (const ReMutexPosixImpl ©) DELETED; + ReMutexPosixImpl &operator = (const ReMutexPosixImpl ©) = delete; public: - INLINE void acquire(); - INLINE bool try_acquire(); - INLINE void release(); - - INLINE pthread_mutex_t *get_posix_lock(); + INLINE void lock(); + INLINE bool try_lock(); + INLINE void unlock(); private: pthread_mutex_t _lock; diff --git a/dtool/src/dtoolbase/mutexSpinlockImpl.I b/dtool/src/dtoolbase/mutexSpinlockImpl.I index 9fca1e9bf6..b3eb084181 100644 --- a/dtool/src/dtoolbase/mutexSpinlockImpl.I +++ b/dtool/src/dtoolbase/mutexSpinlockImpl.I @@ -14,7 +14,7 @@ /** * */ -CONSTEXPR MutexSpinlockImpl:: +constexpr MutexSpinlockImpl:: MutexSpinlockImpl() : _lock(0) { } @@ -22,8 +22,8 @@ MutexSpinlockImpl() : _lock(0) { * */ INLINE void MutexSpinlockImpl:: -acquire() { - if (!try_acquire()) { +lock() { + if (!try_lock()) { do_lock(); } } @@ -32,7 +32,7 @@ acquire() { * */ INLINE bool MutexSpinlockImpl:: -try_acquire() { +try_lock() { return (AtomicAdjust::compare_and_exchange(_lock, 0, 1) == 0); } @@ -40,6 +40,6 @@ try_acquire() { * */ INLINE void MutexSpinlockImpl:: -release() { +unlock() { AtomicAdjust::set(_lock, 0); } diff --git a/dtool/src/dtoolbase/mutexSpinlockImpl.h b/dtool/src/dtoolbase/mutexSpinlockImpl.h index 33514127f4..c7dfb72cf2 100644 --- a/dtool/src/dtoolbase/mutexSpinlockImpl.h +++ b/dtool/src/dtoolbase/mutexSpinlockImpl.h @@ -29,16 +29,15 @@ */ class EXPCL_DTOOL_DTOOLBASE MutexSpinlockImpl { public: - CONSTEXPR MutexSpinlockImpl(); + constexpr MutexSpinlockImpl(); + MutexSpinlockImpl(const MutexSpinlockImpl ©) = delete; -private: - MutexSpinlockImpl(const MutexSpinlockImpl ©) DELETED; - MutexSpinlockImpl &operator = (const MutexSpinlockImpl ©) DELETED_ASSIGN; + MutexSpinlockImpl &operator = (const MutexSpinlockImpl ©) = delete; public: - INLINE void acquire(); - INLINE bool try_acquire(); - INLINE void release(); + INLINE void lock(); + INLINE bool try_lock(); + INLINE void unlock(); private: void do_lock(); diff --git a/dtool/src/dtoolbase/mutexWin32Impl.I b/dtool/src/dtoolbase/mutexWin32Impl.I index cd9b3d1fb1..acbbd68b56 100644 --- a/dtool/src/dtoolbase/mutexWin32Impl.I +++ b/dtool/src/dtoolbase/mutexWin32Impl.I @@ -23,7 +23,7 @@ INLINE MutexWin32Impl:: * */ INLINE void MutexWin32Impl:: -acquire() { +lock() { EnterCriticalSection(&_lock); } @@ -31,7 +31,7 @@ acquire() { * */ INLINE bool MutexWin32Impl:: -try_acquire() { +try_lock() { return (TryEnterCriticalSection(&_lock) != 0); } @@ -39,6 +39,6 @@ try_acquire() { * */ INLINE void MutexWin32Impl:: -release() { +unlock() { LeaveCriticalSection(&_lock); } diff --git a/dtool/src/dtoolbase/mutexWin32Impl.h b/dtool/src/dtoolbase/mutexWin32Impl.h index 08fc6eab24..550d4944ab 100644 --- a/dtool/src/dtoolbase/mutexWin32Impl.h +++ b/dtool/src/dtoolbase/mutexWin32Impl.h @@ -29,16 +29,15 @@ class EXPCL_DTOOL_DTOOLBASE MutexWin32Impl { public: MutexWin32Impl(); + MutexWin32Impl(const MutexWin32Impl ©) = delete; INLINE ~MutexWin32Impl(); -private: - MutexWin32Impl(const MutexWin32Impl ©) DELETED; - MutexWin32Impl &operator = (const MutexWin32Impl ©) DELETED_ASSIGN; + MutexWin32Impl &operator = (const MutexWin32Impl ©) = delete; public: - INLINE void acquire(); - INLINE bool try_acquire(); - INLINE void release(); + INLINE void lock(); + INLINE bool try_lock(); + INLINE void unlock(); private: CRITICAL_SECTION _lock; diff --git a/dtool/src/dtoolbase/nearly_zero.h b/dtool/src/dtoolbase/nearly_zero.h index af71ad9419..0f31fdfb2e 100644 --- a/dtool/src/dtoolbase/nearly_zero.h +++ b/dtool/src/dtoolbase/nearly_zero.h @@ -24,17 +24,17 @@ // identifier, and then returning the value of that identifier, seems to lead // to compilation errors (at least in VC7) in which sometimes // IS_THRESHOLD_COMPEQ(a, a, get_nearly_zero_value(a)) != 0. -CONSTEXPR double +constexpr double get_nearly_zero_value(double) { return 1.0e-12; } -CONSTEXPR float +constexpr float get_nearly_zero_value(float) { return 1.0e-6f; } -CONSTEXPR int +constexpr int get_nearly_zero_value(int) { // This is a bit silly, but we should nevertheless define it in case it is // called for an integer type. diff --git a/dtool/src/dtoolbase/neverFreeMemory.I b/dtool/src/dtoolbase/neverFreeMemory.I index 2156209616..6e5216e993 100644 --- a/dtool/src/dtoolbase/neverFreeMemory.I +++ b/dtool/src/dtoolbase/neverFreeMemory.I @@ -48,9 +48,9 @@ get_total_used() { INLINE size_t NeverFreeMemory:: get_total_unused() { NeverFreeMemory *global_ptr = get_global_ptr(); - global_ptr->_lock.acquire(); + global_ptr->_lock.lock(); size_t total_unused = global_ptr->_total_alloc - global_ptr->_total_used; - global_ptr->_lock.release(); + global_ptr->_lock.unlock(); return total_unused; } @@ -59,7 +59,7 @@ get_total_unused() { */ INLINE NeverFreeMemory *NeverFreeMemory:: get_global_ptr() { - if (_global_ptr == (NeverFreeMemory *)NULL) { + if (_global_ptr == nullptr) { make_global_ptr(); } return _global_ptr; diff --git a/dtool/src/dtoolbase/neverFreeMemory.cxx b/dtool/src/dtoolbase/neverFreeMemory.cxx index fd10b683d8..bd7c1c1481 100644 --- a/dtool/src/dtoolbase/neverFreeMemory.cxx +++ b/dtool/src/dtoolbase/neverFreeMemory.cxx @@ -37,7 +37,7 @@ NeverFreeMemory() { */ void *NeverFreeMemory:: ns_alloc(size_t size) { - _lock.acquire(); + _lock.lock(); //NB: we no longer do alignment here. The only class that uses this is // DeletedBufferChain, and we can do the alignment potentially more @@ -46,7 +46,7 @@ ns_alloc(size_t size) { // Look for a page that has sufficient space remaining. - Pages::iterator pi = _pages.lower_bound(Page(NULL, size)); + Pages::iterator pi = _pages.lower_bound(Page(nullptr, size)); if (pi != _pages.end()) { // Here's a page with enough remaining space. Page page = (*pi); @@ -55,13 +55,13 @@ ns_alloc(size_t size) { if (page._remaining >= min_page_remaining_size) { _pages.insert(page); } - _lock.release(); + _lock.unlock(); return result; } // We have to allocate a new page. Allocate at least min_page_size bytes, // and then round that up to the next _page_size bytes. - size_t needed_size = max(size, min_page_size); + size_t needed_size = std::max(size, min_page_size); needed_size = memory_hook->round_up_to_page_size(needed_size); void *start = memory_hook->mmap_alloc(needed_size, false); _total_alloc += needed_size; @@ -71,7 +71,7 @@ ns_alloc(size_t size) { if (page._remaining >= min_page_remaining_size) { _pages.insert(page); } - _lock.release(); + _lock.unlock(); return result; } @@ -82,8 +82,8 @@ void NeverFreeMemory:: make_global_ptr() { NeverFreeMemory *ptr = new NeverFreeMemory; void *result = AtomicAdjust::compare_and_exchange_ptr - ((void * TVOLATILE &)_global_ptr, (void *)NULL, (void *)ptr); - if (result != NULL) { + ((void * TVOLATILE &)_global_ptr, nullptr, (void *)ptr); + if (result != nullptr) { // Someone else got there first. delete ptr; } diff --git a/dtool/src/dtoolbase/neverFreeMemory.h b/dtool/src/dtoolbase/neverFreeMemory.h index d3f0cf51a1..8396313015 100644 --- a/dtool/src/dtoolbase/neverFreeMemory.h +++ b/dtool/src/dtoolbase/neverFreeMemory.h @@ -57,7 +57,7 @@ private: size_t _remaining; }; - typedef set Pages; + typedef std::set Pages; Pages _pages; size_t _total_alloc; diff --git a/dtool/src/dtoolbase/pallocator.T b/dtool/src/dtoolbase/pallocator.T index e9bfd3f98e..ed8349debe 100644 --- a/dtool/src/dtoolbase/pallocator.T +++ b/dtool/src/dtoolbase/pallocator.T @@ -13,14 +13,14 @@ template INLINE pallocator_single:: -pallocator_single(TypeHandle type_handle) NOEXCEPT : +pallocator_single(TypeHandle type_handle) noexcept : _type_handle(type_handle) { } template INLINE Type *pallocator_single:: -allocate(TYPENAME pallocator_single::size_type n, TYPENAME allocator::const_pointer) { +allocate(typename pallocator_single::size_type n, typename std::allocator::const_pointer) { TAU_PROFILE("pallocator_single:allocate()", " ", TAU_USER); // This doesn't support allocating arrays. assert(n == 1); @@ -30,27 +30,27 @@ allocate(TYPENAME pallocator_single::size_type n, TYPENAME allocator template INLINE void pallocator_single:: -deallocate(TYPENAME pallocator_single::pointer p, TYPENAME pallocator_single::size_type) { +deallocate(typename pallocator_single::pointer p, typename pallocator_single::size_type) { TAU_PROFILE("pallocator_single:deallocate()", " ", TAU_USER); StaticDeletedChain::deallocate(p, _type_handle); } template INLINE pallocator_array:: -pallocator_array(TypeHandle type_handle) NOEXCEPT : +pallocator_array(TypeHandle type_handle) noexcept : _type_handle(type_handle) { } template INLINE Type *pallocator_array:: -allocate(TYPENAME pallocator_array::size_type n, TYPENAME allocator::const_pointer) { - return (TYPENAME pallocator_array::pointer) +allocate(typename pallocator_array::size_type n, typename std::allocator::const_pointer) { + return (typename pallocator_array::pointer) ASSUME_ALIGNED(_type_handle.allocate_array(n * sizeof(Type)), MEMORY_HOOK_ALIGNMENT); } template INLINE void pallocator_array:: -deallocate(TYPENAME pallocator_array::pointer p, TYPENAME pallocator_array::size_type) { +deallocate(typename pallocator_array::pointer p, typename pallocator_array::size_type) { _type_handle.deallocate_array((void *)p); } diff --git a/dtool/src/dtoolbase/pallocator.h b/dtool/src/dtoolbase/pallocator.h index 3c91b6cc7e..d61ca64ceb 100644 --- a/dtool/src/dtoolbase/pallocator.h +++ b/dtool/src/dtoolbase/pallocator.h @@ -36,30 +36,30 @@ // If we're not trying to make custom allocators (either we don't know what // kind of syntax this STL library wants, or we're compiling with OPTIMIZE 4), // then simply use the standard allocator. -#define pallocator_single allocator -#define pallocator_array allocator +#define pallocator_single std::allocator +#define pallocator_array std::allocator #else template -class pallocator_single : public allocator { +class pallocator_single : public std::allocator { public: // Nowadays we cannot implicitly inherit typedefs from base classes in a // template class; we must explicitly copy them here. - typedef TYPENAME allocator::pointer pointer; - typedef TYPENAME allocator::reference reference; - typedef TYPENAME allocator::const_pointer const_pointer; - typedef TYPENAME allocator::const_reference const_reference; - typedef TYPENAME allocator::size_type size_type; + typedef typename std::allocator::pointer pointer; + typedef typename std::allocator::reference reference; + typedef typename std::allocator::const_pointer const_pointer; + typedef typename std::allocator::const_reference const_reference; + typedef typename std::allocator::size_type size_type; - INLINE pallocator_single(TypeHandle type_handle) NOEXCEPT; + INLINE pallocator_single(TypeHandle type_handle) noexcept; // template member functions in VC++ can only be defined in-class. template - INLINE pallocator_single(const pallocator_single ©) NOEXCEPT : + INLINE pallocator_single(const pallocator_single ©) noexcept : _type_handle(copy._type_handle) { } - INLINE Type *allocate(size_type n, allocator::const_pointer hint = 0) + INLINE Type *allocate(size_type n, std::allocator::const_pointer hint = 0) RETURNS_ALIGNED(MEMORY_HOOK_ALIGNMENT); INLINE void deallocate(pointer p, size_type n); @@ -71,24 +71,24 @@ public: }; template -class pallocator_array : public allocator { +class pallocator_array : public std::allocator { public: // Nowadays we cannot implicitly inherit typedefs from base classes in a // template class; we must explicitly copy them here. - typedef TYPENAME allocator::pointer pointer; - typedef TYPENAME allocator::reference reference; - typedef TYPENAME allocator::const_pointer const_pointer; - typedef TYPENAME allocator::const_reference const_reference; - typedef TYPENAME allocator::size_type size_type; + typedef typename std::allocator::pointer pointer; + typedef typename std::allocator::reference reference; + typedef typename std::allocator::const_pointer const_pointer; + typedef typename std::allocator::const_reference const_reference; + typedef typename std::allocator::size_type size_type; - INLINE pallocator_array(TypeHandle type_handle = TypeHandle::none()) NOEXCEPT; + INLINE pallocator_array(TypeHandle type_handle = TypeHandle::none()) noexcept; // template member functions in VC++ can only be defined in-class. template - INLINE pallocator_array(const pallocator_array ©) NOEXCEPT : + INLINE pallocator_array(const pallocator_array ©) noexcept : _type_handle(copy._type_handle) { } - INLINE Type *allocate(size_type n, allocator::const_pointer hint = 0) + INLINE Type *allocate(size_type n, std::allocator::const_pointer hint = 0) RETURNS_ALIGNED(MEMORY_HOOK_ALIGNMENT); INLINE void deallocate(pointer p, size_type n); diff --git a/dtool/src/dtoolbase/pdeque.h b/dtool/src/dtoolbase/pdeque.h index 96cf319e77..e7e9f96c28 100644 --- a/dtool/src/dtoolbase/pdeque.h +++ b/dtool/src/dtoolbase/pdeque.h @@ -19,10 +19,11 @@ #include "register_type.h" #include + #if !defined(USE_STL_ALLOCATOR) || defined(CPPPARSER) // If we're not using custom allocators, just use the standard class // definition. -#define pdeque deque +#define pdeque std::deque #else @@ -32,13 +33,13 @@ * allocated memory. */ template -class pdeque : public deque > { +class pdeque : public std::deque > { public: typedef pallocator_array allocator; - typedef TYPENAME deque::size_type size_type; - pdeque(TypeHandle type_handle = pdeque_type_handle) : deque >(allocator(type_handle)) { } - pdeque(size_type n, TypeHandle type_handle = pdeque_type_handle) : deque >(n, Type(), allocator(type_handle)) { } - pdeque(size_type n, const Type &value, TypeHandle type_handle = pdeque_type_handle) : deque >(n, value, allocator(type_handle)) { } + typedef typename std::deque::size_type size_type; + pdeque(TypeHandle type_handle = pdeque_type_handle) : std::deque >(allocator(type_handle)) { } + pdeque(size_type n, TypeHandle type_handle = pdeque_type_handle) : std::deque >(n, Type(), allocator(type_handle)) { } + pdeque(size_type n, const Type &value, TypeHandle type_handle = pdeque_type_handle) : std::deque >(n, value, allocator(type_handle)) { } }; #endif // USE_STL_ALLOCATOR diff --git a/dtool/src/dtoolbase/pdtoa.cxx b/dtool/src/dtoolbase/pdtoa.cxx index 47aa2db50a..2b508654ba 100644 --- a/dtool/src/dtoolbase/pdtoa.cxx +++ b/dtool/src/dtoolbase/pdtoa.cxx @@ -259,7 +259,7 @@ inline static void DigitGen(const DiyFp& W, const DiyFp& Mp, uint64_t delta, cha *len = 0; while (kappa > 0) { - uint32_t d; + uint32_t d = 0; switch (kappa) { case 10: d = p1 / 1000000000; p1 %= 1000000000; break; case 9: d = p1 / 100000000; p1 %= 100000000; break; @@ -271,14 +271,7 @@ inline static void DigitGen(const DiyFp& W, const DiyFp& Mp, uint64_t delta, cha case 3: d = p1 / 100; p1 %= 100; break; case 2: d = p1 / 10; p1 %= 10; break; case 1: d = p1; p1 = 0; break; - default: -#if defined(_MSC_VER) - __assume(0); -#elif __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) - __builtin_unreachable(); -#else - d = 0; -#endif + NODEFAULT } if (d || *len) buffer[(*len)++] = '0' + static_cast(d); @@ -404,7 +397,7 @@ void pdtoa(double value, char *buffer) { #ifdef _MSC_VER if (copysign(1.0, value) < 0) { #else - if (signbit(value)) { + if (std::signbit(value)) { #endif *buffer++ = '-'; value = -value; diff --git a/dtool/src/dtoolbase/plist.h b/dtool/src/dtoolbase/plist.h index bbb9e55089..12d29880f3 100644 --- a/dtool/src/dtoolbase/plist.h +++ b/dtool/src/dtoolbase/plist.h @@ -22,7 +22,7 @@ #if !defined(USE_STL_ALLOCATOR) || defined(CPPPARSER) // If we're not using custom allocators, just use the standard class // definition. -#define plist list +#define plist std::list #else @@ -32,19 +32,19 @@ * allocated memory. */ template -class plist : public list > { +class plist : public std::list > { public: typedef pallocator_single allocator; - typedef list base_class; - typedef TYPENAME base_class::size_type size_type; + typedef std::list base_class; + typedef typename base_class::size_type size_type; plist(TypeHandle type_handle = plist_type_handle) : base_class(allocator(type_handle)) { } plist(size_type n, TypeHandle type_handle = plist_type_handle) : base_class(n, Type(), allocator(type_handle)) { } plist(size_type n, const Type &value, TypeHandle type_handle = plist_type_handle) : base_class(n, value, allocator(type_handle)) { } - typedef TYPENAME base_class::iterator iterator; - typedef TYPENAME base_class::const_iterator const_iterator; - typedef TYPENAME base_class::reverse_iterator reverse_iterator; - typedef TYPENAME base_class::const_reverse_iterator const_reverse_iterator; + typedef typename base_class::iterator iterator; + typedef typename base_class::const_iterator const_iterator; + typedef typename base_class::reverse_iterator reverse_iterator; + typedef typename base_class::const_reverse_iterator const_reverse_iterator; // This exists because libc++'s remove implementation has a bug with Panda's // allocator class. diff --git a/dtool/src/dtoolbase/pmap.h b/dtool/src/dtoolbase/pmap.h index e115191b45..6ddb38edee 100644 --- a/dtool/src/dtoolbase/pmap.h +++ b/dtool/src/dtoolbase/pmap.h @@ -27,8 +27,8 @@ #if !defined(USE_STL_ALLOCATOR) || defined(CPPPARSER) // If we're not using custom allocators, just use the standard class // definition. -#define pmap map -#define pmultimap multimap +#define pmap std::map +#define pmultimap std::multimap #ifdef HAVE_STL_HASH #define phash_map stdext::hash_map @@ -45,43 +45,43 @@ * purpose is to call the hooks for MemoryUsage to properly track STL- * allocated memory. */ -template > -class pmap : public map > > { +template > +class pmap : public std::map > > { public: - typedef pallocator_single > allocator; - typedef map base_class; + typedef pallocator_single > allocator; + typedef std::map base_class; pmap(TypeHandle type_handle = pmap_type_handle) : base_class(Compare(), allocator(type_handle)) { } pmap(const Compare &comp, TypeHandle type_handle = pmap_type_handle) : base_class(comp, allocator(type_handle)) { } #ifdef USE_TAU - TYPENAME base_class::mapped_type & - operator [] (const TYPENAME base_class::key_type &k) { + typename base_class::mapped_type & + operator [] (const typename base_class::key_type &k) { TAU_PROFILE("pmap::operator [] (const key_type &)", " ", TAU_USER); return base_class::operator [] (k); } - std::pair - insert(const TYPENAME base_class::value_type &x) { + std::pair + insert(const typename base_class::value_type &x) { TAU_PROFILE("pmap::insert(const value_type &)", " ", TAU_USER); return base_class::insert(x); } - TYPENAME base_class::iterator - insert(TYPENAME base_class::iterator position, - const TYPENAME base_class::value_type &x) { + typename base_class::iterator + insert(typename base_class::iterator position, + const typename base_class::value_type &x) { TAU_PROFILE("pmap::insert(iterator, const value_type &)", " ", TAU_USER); return base_class::insert(position, x); } void - erase(TYPENAME base_class::iterator position) { + erase(typename base_class::iterator position) { TAU_PROFILE("pmap::erase(iterator)", " ", TAU_USER); base_class::erase(position); } - TYPENAME base_class::size_type - erase(const TYPENAME base_class::key_type &x) { + typename base_class::size_type + erase(const typename base_class::key_type &x) { TAU_PROFILE("pmap::erase(const key_type &)", " ", TAU_USER); return base_class::erase(x); } @@ -92,14 +92,14 @@ public: base_class::clear(); } - TYPENAME base_class::iterator - find(const TYPENAME base_class::key_type &x) { + typename base_class::iterator + find(const typename base_class::key_type &x) { TAU_PROFILE("pmap::find(const key_type &)", " ", TAU_USER); return base_class::find(x); } - TYPENAME base_class::const_iterator - find(const TYPENAME base_class::key_type &x) const { + typename base_class::const_iterator + find(const typename base_class::key_type &x) const { TAU_PROFILE("pmap::find(const key_type &)", " ", TAU_USER); return base_class::find(x); } @@ -112,12 +112,12 @@ public: * purpose is to call the hooks for MemoryUsage to properly track STL- * allocated memory. */ -template > -class pmultimap : public multimap > > { +template > +class pmultimap : public std::multimap > > { public: - typedef pallocator_single > allocator; - pmultimap(TypeHandle type_handle = pmap_type_handle) : multimap(Compare(), allocator(type_handle)) { } - pmultimap(const Compare &comp, TypeHandle type_handle = pmap_type_handle) : multimap(comp, allocator(type_handle)) { } + typedef pallocator_single > allocator; + pmultimap(TypeHandle type_handle = pmap_type_handle) : std::multimap(Compare(), allocator(type_handle)) { } + pmultimap(const Compare &comp, TypeHandle type_handle = pmap_type_handle) : std::multimap(comp, allocator(type_handle)) { } }; #ifdef HAVE_STL_HASH @@ -126,11 +126,11 @@ public: * purpose is to call the hooks for MemoryUsage to properly track STL- * allocated memory. */ -template > > -class phash_map : public stdext::hash_map > > { +template > > +class phash_map : public stdext::hash_map > > { public: - phash_map() : stdext::hash_map > >() { } - phash_map(const Compare &comp) : stdext::hash_map > >(comp) { } + phash_map() : stdext::hash_map > >() { } + phash_map(const Compare &comp) : stdext::hash_map > >(comp) { } }; /** @@ -138,11 +138,11 @@ public: * main purpose is to call the hooks for MemoryUsage to properly track STL- * allocated memory. */ -template > > -class phash_multimap : public stdext::hash_multimap > > { +template > > +class phash_multimap : public stdext::hash_multimap > > { public: - phash_multimap() : stdext::hash_multimap > >() { } - phash_multimap(const Compare &comp) : stdext::hash_multimap > >(comp) { } + phash_multimap() : stdext::hash_multimap > >() { } + phash_multimap(const Compare &comp) : stdext::hash_multimap > >(comp) { } }; #else // HAVE_STL_HASH diff --git a/dtool/src/dtoolbase/pset.h b/dtool/src/dtoolbase/pset.h index b7990ad671..ff54486dfe 100644 --- a/dtool/src/dtoolbase/pset.h +++ b/dtool/src/dtoolbase/pset.h @@ -27,15 +27,15 @@ #if !defined(USE_STL_ALLOCATOR) || defined(CPPPARSER) // If we're not using custom allocators, just use the standard class // definition. -#define pset set -#define pmultiset multiset +#define pset std::set +#define pmultiset std::multiset #ifdef HAVE_STL_HASH #define phash_set stdext::hash_set #define phash_multiset stdext::hash_multiset #else // HAVE_STL_HASH -#define phash_set set -#define phash_multiset multiset +#define phash_set std::set +#define phash_multiset std::multiset #endif // HAVE_STL_HASH #else // USE_STL_ALLOCATOR @@ -45,36 +45,36 @@ * purpose is to call the hooks for MemoryUsage to properly track STL- * allocated memory. */ -template > -class pset : public set > { +template > +class pset : public std::set > { public: typedef pallocator_single allocator; - typedef set base_class; + typedef std::set base_class; pset(TypeHandle type_handle = pset_type_handle) : base_class(Compare(), allocator(type_handle)) { } pset(const Compare &comp, TypeHandle type_handle = pset_type_handle) : base_class(comp, type_handle) { } #ifdef USE_TAU - std::pair - insert(const TYPENAME base_class::value_type &x) { + std::pair + insert(const typename base_class::value_type &x) { TAU_PROFILE("pset::insert(const value_type &)", " ", TAU_USER); return base_class::insert(x); } - TYPENAME base_class::iterator - insert(TYPENAME base_class::iterator position, - const TYPENAME base_class::value_type &x) { + typename base_class::iterator + insert(typename base_class::iterator position, + const typename base_class::value_type &x) { TAU_PROFILE("pset::insert(iterator, const value_type &)", " ", TAU_USER); return base_class::insert(position, x); } void - erase(TYPENAME base_class::iterator position) { + erase(typename base_class::iterator position) { TAU_PROFILE("pset::erase(iterator)", " ", TAU_USER); base_class::erase(position); } - TYPENAME base_class::size_type - erase(const TYPENAME base_class::key_type &x) { + typename base_class::size_type + erase(const typename base_class::key_type &x) { TAU_PROFILE("pset::erase(const key_type &)", " ", TAU_USER); return base_class::erase(x); } @@ -85,14 +85,14 @@ public: base_class::clear(); } - TYPENAME base_class::iterator - find(const TYPENAME base_class::key_type &x) { + typename base_class::iterator + find(const typename base_class::key_type &x) { TAU_PROFILE("pset::find(x)", " ", TAU_USER); return base_class::find(x); } - TYPENAME base_class::const_iterator - find(const TYPENAME base_class::key_type &x) const { + typename base_class::const_iterator + find(const typename base_class::key_type &x) const { TAU_PROFILE("pset::find(x)", " ", TAU_USER); return base_class::find(x); } @@ -104,12 +104,12 @@ public: * purpose is to call the hooks for MemoryUsage to properly track STL- * allocated memory. */ -template > -class pmultiset : public multiset > { +template > +class pmultiset : public std::multiset > { public: typedef pallocator_single allocator; - pmultiset(TypeHandle type_handle = pset_type_handle) : multiset(Compare(), allocator(type_handle)) { } - pmultiset(const Compare &comp, TypeHandle type_handle = pset_type_handle) : multiset(comp, type_handle) { } + pmultiset(TypeHandle type_handle = pset_type_handle) : std::multiset(Compare(), allocator(type_handle)) { } + pmultiset(const Compare &comp, TypeHandle type_handle = pset_type_handle) : std::multiset(comp, type_handle) { } }; #ifdef HAVE_STL_HASH @@ -118,7 +118,7 @@ public: * purpose is to call the hooks for MemoryUsage to properly track STL- * allocated memory. */ -template > > +template > > class phash_set : public stdext::hash_set > { public: phash_set() : stdext::hash_set >() { } @@ -130,7 +130,7 @@ public: * main purpose is to call the hooks for MemoryUsage to properly track STL- * allocated memory. */ -template > > +template > > class phash_multiset : public stdext::hash_multiset > { public: phash_multiset() : stdext::hash_multiset >() { } diff --git a/dtool/src/dtoolbase/pstrtod.cxx b/dtool/src/dtoolbase/pstrtod.cxx index 5a27ab6212..933d342f2c 100644 --- a/dtool/src/dtoolbase/pstrtod.cxx +++ b/dtool/src/dtoolbase/pstrtod.cxx @@ -104,7 +104,7 @@ pstrtod(const char *nptr, char **endptr) { if (!found_digits) { // Not a valid float. - if (endptr != NULL) { + if (endptr != nullptr) { *endptr = (char *)nptr; } return 0.0; @@ -139,7 +139,7 @@ pstrtod(const char *nptr, char **endptr) { value = -value; } - if (endptr != NULL) { + if (endptr != nullptr) { *endptr = (char *)p; } return value; @@ -154,5 +154,5 @@ pstrtod(const char *nptr, char **endptr) { */ double patof(const char *str) { - return pstrtod(str, (char **)NULL); + return pstrtod(str, nullptr); } diff --git a/dtool/src/dtoolbase/ptmalloc2_smp_src.cxx b/dtool/src/dtoolbase/ptmalloc2_smp_src.cxx index 7ecfde41f1..8cb0c882c5 100644 --- a/dtool/src/dtoolbase/ptmalloc2_smp_src.cxx +++ b/dtool/src/dtoolbase/ptmalloc2_smp_src.cxx @@ -259,20 +259,20 @@ typedef pthread_mutex_t mutex_t; pthread_mutex_t is at least one int wide. */ #define mutex_init(m) \ - (__pthread_mutex_init != NULL \ - ? __pthread_mutex_init (m, NULL) : (*(int *)(m) = 0)) + (__pthread_mutex_init != nullptr \ + ? __pthread_mutex_init (m, nullptr) : (*(int *)(m) = 0)) #define mutex_lock(m) \ - (__pthread_mutex_lock != NULL \ + (__pthread_mutex_lock != nullptr \ ? __pthread_mutex_lock (m) : ((*(int *)(m) = 1), 0)) #define mutex_trylock(m) \ - (__pthread_mutex_trylock != NULL \ + (__pthread_mutex_trylock != nullptr \ ? __pthread_mutex_trylock (m) : (*(int *)(m) ? 1 : ((*(int *)(m) = 1), 0))) #define mutex_unlock(m) \ - (__pthread_mutex_unlock != NULL \ + (__pthread_mutex_unlock != nullptr \ ? __pthread_mutex_unlock (m) : (*(int*)(m) = 0)) #define thread_atfork(prepare, parent, child) \ - (__pthread_atfork != NULL ? __pthread_atfork(prepare, parent, child) : 0) + (__pthread_atfork != nullptr ? __pthread_atfork(prepare, parent, child) : 0) #elif defined(MUTEX_INITIALIZER) /* Assume hurd, with cthreads */ @@ -360,7 +360,7 @@ static inline int mutex_lock(mutex_t *m) { } else { tm.tv_sec = 0; tm.tv_nsec = 2000001; - nanosleep(&tm, NULL); + nanosleep(&tm, nullptr); cnt = 0; } } @@ -392,7 +392,7 @@ static inline int mutex_unlock(mutex_t *m) { typedef pthread_mutex_t mutex_t; #define MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER -#define mutex_init(m) pthread_mutex_init(m, NULL) +#define mutex_init(m) pthread_mutex_init(m, nullptr) #define mutex_lock(m) pthread_mutex_lock(m) #define mutex_trylock(m) pthread_mutex_trylock(m) #define mutex_unlock(m) pthread_mutex_unlock(m) @@ -438,7 +438,7 @@ typedef pthread_key_t tsd_key_t; typedef thread_t thread_id; #define MUTEX_INITIALIZER { 0 } -#define mutex_init(m) mutex_init(m, USYNC_THREAD, NULL) +#define mutex_init(m) mutex_init(m, USYNC_THREAD, nullptr) /* * Hack for thread-specific data on Solaris. We can't use thr_setspecific @@ -2040,7 +2040,7 @@ extern __malloc_ptr_t _int_memalign __MALLOC_P ((mstate __m, size_t __alignment, #define BOUNDED_N(ptr, sz) (ptr) #endif #ifndef RETURN_ADDRESS -#define RETURN_ADDRESS(X_) (NULL) +#define RETURN_ADDRESS(X_) (nullptr) #endif /* On some platforms we can compile internal, not exported functions better. @@ -3026,7 +3026,7 @@ int __malloc_initialized = -1; in the new arena. */ #define arena_get(ptr, size) do { \ - Void_t *vptr = NULL; \ + Void_t *vptr = nullptr; \ ptr = (mstate)tsd_getspecific(arena_key, vptr); \ if(ptr && !mutex_trylock(&ptr->mutex)) { \ THREAD_STAT(++(ptr->stat_lock_direct)); \ @@ -3088,7 +3088,7 @@ static Void_t* save_arena; static Void_t* malloc_atfork(size_t sz, const Void_t *caller) { - Void_t *vptr = NULL; + Void_t *vptr = nullptr; Void_t *victim; tsd_getspecific(arena_key, vptr); @@ -3115,7 +3115,7 @@ malloc_atfork(size_t sz, const Void_t *caller) static void free_atfork(Void_t* mem, const Void_t *caller) { - Void_t *vptr = NULL; + Void_t *vptr = nullptr; mstate ar_ptr; mchunkptr p; /* chunk corresponding to mem */ @@ -3232,9 +3232,9 @@ internal_function next_env_entry (char ***position) { char **current = *position; - char *result = NULL; + char *result = nullptr; - while (*current != NULL) + while (*current != nullptr) { if (__builtin_expect ((*current)[0] == 'M', 0) && (*current)[1] == 'A' @@ -3288,7 +3288,7 @@ ptmalloc_init __MALLOC_P((void)) __free_hook = free_starter; #ifdef _LIBC /* Initialize the pthreads interface. */ - if (__pthread_initialize != NULL) + if (__pthread_initialize != nullptr) __pthread_initialize(); #endif #endif /* !defined NO_THREADS */ @@ -3296,7 +3296,7 @@ ptmalloc_init __MALLOC_P((void)) main_arena.next = &main_arena; mutex_init(&list_lock); - tsd_key_create(&arena_key, NULL); + tsd_key_create(&arena_key, nullptr); tsd_setspecific(arena_key, (Void_t *)&main_arena); thread_atfork(ptmalloc_lock_all, ptmalloc_unlock_all, ptmalloc_unlock_all2); #ifndef NO_THREADS @@ -3305,12 +3305,12 @@ ptmalloc_init __MALLOC_P((void)) #endif #ifdef _LIBC secure = __libc_enable_secure; - s = NULL; + s = nullptr; { char **runp = _environ; char *envline; - while (__builtin_expect ((envline = next_env_entry (&runp)) != NULL, + while (__builtin_expect ((envline = next_env_entry (&runp)) != nullptr, 0)) { size_t len = strcspn (envline, "="); @@ -3367,7 +3367,7 @@ ptmalloc_init __MALLOC_P((void)) if(s[0]) mALLOPt(M_CHECK_ACTION, (int)(s[0] - '0')); __malloc_check_init(); } - if(__malloc_initialize_hook != NULL) + if(__malloc_initialize_hook != nullptr) (*__malloc_initialize_hook)(); __malloc_initialized = 1; } @@ -4103,7 +4103,7 @@ malloc_hook_ini(sz, caller) size_t sz; const __malloc_ptr_t caller; #endif { - __malloc_hook = NULL; + __malloc_hook = nullptr; ptmalloc_init(); return public_mALLOc(sz); } @@ -4116,8 +4116,8 @@ realloc_hook_ini(ptr, sz, caller) Void_t* ptr; size_t sz; const __malloc_ptr_t caller; #endif { - __malloc_hook = NULL; - __realloc_hook = NULL; + __malloc_hook = nullptr; + __realloc_hook = nullptr; ptmalloc_init(); return public_rEALLOc(ptr, sz); } @@ -4130,14 +4130,14 @@ memalign_hook_ini(alignment, sz, caller) size_t alignment; size_t sz; const __malloc_ptr_t caller; #endif { - __memalign_hook = NULL; + __memalign_hook = nullptr; ptmalloc_init(); return public_mEMALIGn(alignment, sz); } -void weak_variable (*__malloc_initialize_hook) __MALLOC_P ((void)) = NULL; +void weak_variable (*__malloc_initialize_hook) __MALLOC_P ((void)) = nullptr; void weak_variable (*__free_hook) __MALLOC_P ((__malloc_ptr_t __ptr, - const __malloc_ptr_t)) = NULL; + const __malloc_ptr_t)) = nullptr; __malloc_ptr_t weak_variable (*__malloc_hook) __MALLOC_P ((size_t __size, const __malloc_ptr_t)) = malloc_hook_ini; __malloc_ptr_t weak_variable (*__realloc_hook) @@ -4146,7 +4146,7 @@ __malloc_ptr_t weak_variable (*__realloc_hook) __malloc_ptr_t weak_variable (*__memalign_hook) __MALLOC_P ((size_t __alignment, size_t __size, const __malloc_ptr_t)) = memalign_hook_ini; -void weak_variable (*__after_morecore_hook) __MALLOC_P ((void)) = NULL; +void weak_variable (*__after_morecore_hook) __MALLOC_P ((void)) = nullptr; static int check_action = DEFAULT_CHECK_ACTION; @@ -4240,7 +4240,7 @@ mem2chunk_check(mem) Void_t* mem; unsigned char magic; p = mem2chunk(mem); - if(!aligned_OK(p)) return NULL; + if(!aligned_OK(p)) return nullptr; if( (char*)p>=mp_.sbrk_base && (char*)p<(mp_.sbrk_base+main_arena.system_mem) ) { /* Must be a chunk in conventional heap memory. */ @@ -4251,10 +4251,10 @@ mem2chunk_check(mem) Void_t* mem; ( !prev_inuse(p) && (p->prev_size&MALLOC_ALIGN_MASK || (long)prev_chunk(p)<(long)mp_.sbrk_base || next_chunk(prev_chunk(p))!=p) )) - return NULL; + return nullptr; magic = MAGICBYTE(p); for(sz += SIZE_SZ-1; (c = ((unsigned char*)p)[sz]) != magic; sz -= c) { - if(c<=0 || sz<(c+2*SIZE_SZ)) return NULL; + if(c<=0 || sz<(c+2*SIZE_SZ)) return nullptr; } ((unsigned char*)p)[sz] ^= 0xFF; } else { @@ -4271,10 +4271,10 @@ mem2chunk_check(mem) Void_t* mem; !chunk_is_mmapped(p) || (p->size & PREV_INUSE) || ( (((unsigned long)p - p->prev_size) & page_mask) != 0 ) || ( (sz = chunksize(p)), ((p->prev_size + sz) & page_mask) != 0 ) ) - return NULL; + return nullptr; magic = MAGICBYTE(p); for(sz -= 1; (c = ((unsigned char*)p)[sz]) != magic; sz -= c) { - if(c<=0 || sz<(c+2*SIZE_SZ)) return NULL; + if(c<=0 || sz<(c+2*SIZE_SZ)) return nullptr; } ((unsigned char*)p)[sz] ^= 0xFF; } @@ -4336,7 +4336,7 @@ malloc_check(sz, caller) size_t sz; const Void_t *caller; Void_t *victim; (void)mutex_lock(&main_arena.mutex); - victim = (top_check() >= 0) ? _int_malloc(&main_arena, sz+1) : NULL; + victim = (top_check() >= 0) ? _int_malloc(&main_arena, sz+1) : nullptr; (void)mutex_unlock(&main_arena.mutex); return mem2mem_check(victim, sz); } @@ -4387,7 +4387,7 @@ realloc_check(oldmem, bytes, caller) INTERNAL_SIZE_T nb, oldsize; Void_t* newmem = 0; - if (oldmem == 0) return malloc_check(bytes, NULL); + if (oldmem == 0) return malloc_check(bytes, nullptr); (void)mutex_lock(&main_arena.mutex); oldp = mem2chunk_check(oldmem); (void)mutex_unlock(&main_arena.mutex); @@ -4396,7 +4396,7 @@ realloc_check(oldmem, bytes, caller) fprintf(stderr, "realloc(): invalid pointer %p!\n", oldmem); if(check_action & 2) abort(); - return malloc_check(bytes, NULL); + return malloc_check(bytes, nullptr); } oldsize = chunksize(oldp); @@ -4460,13 +4460,13 @@ memalign_check(alignment, bytes, caller) INTERNAL_SIZE_T nb; Void_t* mem; - if (alignment <= MALLOC_ALIGNMENT) return malloc_check(bytes, NULL); + if (alignment <= MALLOC_ALIGNMENT) return malloc_check(bytes, nullptr); if (alignment < MINSIZE) alignment = MINSIZE; checked_request2size(bytes+1, nb); (void)mutex_lock(&main_arena.mutex); mem = (top_check() >= 0) ? _int_memalign(&main_arena, alignment, bytes+1) : - NULL; + nullptr; (void)mutex_unlock(&main_arena.mutex); return mem2mem_check(mem, bytes); } @@ -5367,7 +5367,7 @@ public_mALLOc(size_t bytes) __malloc_ptr_t (*hook) __MALLOC_P ((size_t, __const __malloc_ptr_t)) = __malloc_hook; - if (hook != NULL) + if (hook != nullptr) return (*hook)(bytes, RETURN_ADDRESS (0)); arena_get(ar_ptr, bytes); @@ -5407,7 +5407,7 @@ public_fREe(Void_t* mem) void (*hook) __MALLOC_P ((__malloc_ptr_t, __const __malloc_ptr_t)) = __free_hook; - if (hook != NULL) { + if (hook != nullptr) { (*hook)(mem, RETURN_ADDRESS (0)); return; } @@ -5454,11 +5454,11 @@ public_rEALLOc(Void_t* oldmem, size_t bytes) __malloc_ptr_t (*hook) __MALLOC_P ((__malloc_ptr_t, size_t, __const __malloc_ptr_t)) = __realloc_hook; - if (hook != NULL) + if (hook != nullptr) return (*hook)(oldmem, bytes, RETURN_ADDRESS (0)); #if REALLOC_ZERO_BYTES_FREES - if (bytes == 0 && oldmem != NULL) { public_fREe(oldmem); return 0; } + if (bytes == 0 && oldmem != nullptr) { public_fREe(oldmem); return 0; } #endif /* realloc of null is supposed to be same as malloc */ @@ -5523,7 +5523,7 @@ public_mEMALIGn(size_t alignment, size_t bytes) __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, size_t, __const __malloc_ptr_t)) = __memalign_hook; - if (hook != NULL) + if (hook != nullptr) return (*hook)(alignment, bytes, RETURN_ADDRESS (0)); /* If need less alignment than we give anyway, just relay to malloc */ @@ -5602,7 +5602,7 @@ public_cALLOc(size_t n, size_t elem_size) __malloc_ptr_t (*hook) __MALLOC_PMT ((size_t, __const __malloc_ptr_t)) = __malloc_hook; - if (hook != NULL) { + if (hook != nullptr) { sz = n * elem_size; mem = (*hook)(sz, RETURN_ADDRESS (0)); if(mem == 0) diff --git a/dtool/src/dtoolbase/pvector.h b/dtool/src/dtoolbase/pvector.h index 14bd542f37..4199506d13 100644 --- a/dtool/src/dtoolbase/pvector.h +++ b/dtool/src/dtoolbase/pvector.h @@ -28,7 +28,7 @@ #elif defined(CPPPARSER) // Simplified definition to speed up Interrogate parsing. template -class pvector : public vector { +class pvector : public std::vector { }; #else @@ -39,31 +39,28 @@ class pvector : public vector { * allocated memory. */ template -class pvector : public vector > { +class pvector : public std::vector > { public: typedef pallocator_array allocator; - typedef vector base_class; - typedef TYPENAME base_class::size_type size_type; + typedef std::vector base_class; + typedef typename base_class::size_type size_type; explicit pvector(TypeHandle type_handle = pvector_type_handle) : base_class(allocator(type_handle)) { } pvector(const pvector ©) : base_class(copy) { } + pvector(pvector &&from) noexcept : base_class(std::move(from)) {}; explicit pvector(size_type n, TypeHandle type_handle = pvector_type_handle) : base_class(n, Type(), allocator(type_handle)) { } explicit pvector(size_type n, const Type &value, TypeHandle type_handle = pvector_type_handle) : base_class(n, value, allocator(type_handle)) { } pvector(const Type *begin, const Type *end, TypeHandle type_handle = pvector_type_handle) : base_class(begin, end, allocator(type_handle)) { } -#ifdef USE_MOVE_SEMANTICS - pvector(pvector &&from) NOEXCEPT : base_class(move(from)) {}; - - pvector &operator =(pvector &&from) NOEXCEPT { - base_class::operator =(move(from)); - return *this; - } -#endif - pvector &operator =(const pvector ©) { base_class::operator =(copy); return *this; } + + pvector &operator =(pvector &&from) noexcept { + base_class::operator =(std::move(from)); + return *this; + } }; #endif // USE_STL_ALLOCATOR diff --git a/dtool/src/dtoolbase/register_type.I b/dtool/src/dtoolbase/register_type.I index 9d22794d20..0bd43e1501 100644 --- a/dtool/src/dtoolbase/register_type.I +++ b/dtool/src/dtoolbase/register_type.I @@ -19,18 +19,18 @@ * Register() and record_derivation() yourself. */ INLINE void -register_type(TypeHandle &type_handle, const string &name) { +register_type(TypeHandle &type_handle, const std::string &name) { TypeRegistry::ptr()->register_type(type_handle, name); } INLINE void -register_type(TypeHandle &type_handle, const string &name, +register_type(TypeHandle &type_handle, const std::string &name, TypeHandle parent1) { if (TypeRegistry::ptr()->register_type(type_handle, name)) { TypeRegistry::ptr()->record_derivation(type_handle, parent1); } } INLINE void -register_type(TypeHandle &type_handle, const string &name, +register_type(TypeHandle &type_handle, const std::string &name, TypeHandle parent1, TypeHandle parent2) { if (TypeRegistry::ptr()->register_type(type_handle, name)) { TypeRegistry::ptr()->record_derivation(type_handle, parent1); @@ -38,7 +38,7 @@ register_type(TypeHandle &type_handle, const string &name, } } INLINE void -register_type(TypeHandle &type_handle, const string &name, +register_type(TypeHandle &type_handle, const std::string &name, TypeHandle parent1, TypeHandle parent2, TypeHandle parent3) { if (TypeRegistry::ptr()->register_type(type_handle, name)) { @@ -48,7 +48,7 @@ register_type(TypeHandle &type_handle, const string &name, } } INLINE void -register_type(TypeHandle &type_handle, const string &name, +register_type(TypeHandle &type_handle, const std::string &name, TypeHandle parent1, TypeHandle parent2, TypeHandle parent3, TypeHandle parent4) { if (TypeRegistry::ptr()->register_type(type_handle, name)) { @@ -66,18 +66,18 @@ register_type(TypeHandle &type_handle, const string &name, * reference. */ INLINE TypeHandle -register_dynamic_type(const string &name) { +register_dynamic_type(const std::string &name) { return TypeRegistry::ptr()->register_dynamic_type(name); } INLINE TypeHandle -register_dynamic_type(const string &name, TypeHandle parent1) { +register_dynamic_type(const std::string &name, TypeHandle parent1) { TypeHandle type_handle = TypeRegistry::ptr()->register_dynamic_type(name); TypeRegistry::ptr()->record_derivation(type_handle, parent1); return type_handle; } INLINE TypeHandle -register_dynamic_type(const string &name, +register_dynamic_type(const std::string &name, TypeHandle parent1, TypeHandle parent2) { TypeHandle type_handle = TypeRegistry::ptr()->register_dynamic_type(name); @@ -86,7 +86,7 @@ register_dynamic_type(const string &name, return type_handle; } INLINE TypeHandle -register_dynamic_type(const string &name, +register_dynamic_type(const std::string &name, TypeHandle parent1, TypeHandle parent2, TypeHandle parent3) { TypeHandle type_handle = @@ -97,7 +97,7 @@ register_dynamic_type(const string &name, return type_handle; } INLINE TypeHandle -register_dynamic_type(const string &name, +register_dynamic_type(const std::string &name, TypeHandle parent1, TypeHandle parent2, TypeHandle parent3, TypeHandle parent4) { TypeHandle type_handle = diff --git a/dtool/src/dtoolbase/register_type.h b/dtool/src/dtoolbase/register_type.h index c6b27f2a94..a15cc9ddb1 100644 --- a/dtool/src/dtoolbase/register_type.h +++ b/dtool/src/dtoolbase/register_type.h @@ -27,23 +27,23 @@ * Register() and record_derivation() yourself. */ INLINE void -register_type(TypeHandle &type_handle, const string &name); +register_type(TypeHandle &type_handle, const std::string &name); INLINE void -register_type(TypeHandle &type_handle, const string &name, +register_type(TypeHandle &type_handle, const std::string &name, TypeHandle parent1); INLINE void -register_type(TypeHandle &type_handle, const string &name, +register_type(TypeHandle &type_handle, const std::string &name, TypeHandle parent1, TypeHandle parent2); INLINE void -register_type(TypeHandle &type_handle, const string &name, +register_type(TypeHandle &type_handle, const std::string &name, TypeHandle parent1, TypeHandle parent2, TypeHandle parent3); INLINE void -register_type(TypeHandle &type_handle, const string &name, +register_type(TypeHandle &type_handle, const std::string &name, TypeHandle parent1, TypeHandle parent2, TypeHandle parent3, TypeHandle parent4); @@ -55,22 +55,22 @@ register_type(TypeHandle &type_handle, const string &name, * reference. */ INLINE TypeHandle -register_dynamic_type(const string &name); +register_dynamic_type(const std::string &name); INLINE TypeHandle -register_dynamic_type(const string &name, TypeHandle parent1); +register_dynamic_type(const std::string &name, TypeHandle parent1); INLINE TypeHandle -register_dynamic_type(const string &name, +register_dynamic_type(const std::string &name, TypeHandle parent1, TypeHandle parent2); INLINE TypeHandle -register_dynamic_type(const string &name, +register_dynamic_type(const std::string &name, TypeHandle parent1, TypeHandle parent2, TypeHandle parent3); INLINE TypeHandle -register_dynamic_type(const string &name, +register_dynamic_type(const std::string &name, TypeHandle parent1, TypeHandle parent2, TypeHandle parent3, TypeHandle parent4); @@ -166,12 +166,12 @@ INLINE TypeHandle _get_type_handle(const float *) { } template<> -INLINE TypeHandle _get_type_handle(const string *) { +INLINE TypeHandle _get_type_handle(const std::string *) { return string_type_handle; } template<> -INLINE TypeHandle _get_type_handle(const wstring *) { +INLINE TypeHandle _get_type_handle(const std::wstring *) { return wstring_type_handle; } diff --git a/dtool/src/dtoolbase/stl_compares.h b/dtool/src/dtoolbase/stl_compares.h index 57d989337a..946eab9b64 100644 --- a/dtool/src/dtoolbase/stl_compares.h +++ b/dtool/src/dtoolbase/stl_compares.h @@ -24,7 +24,7 @@ #ifdef HAVE_STL_HASH #include // for hash_compare -template > +template > class stl_hash_compare : public stdext::hash_compare { public: INLINE bool is_equal(const Key &a, const Key &b) const { @@ -37,7 +37,7 @@ public: #include // for less // This is declared for the cases in which we don't have STL_HASH available. -template > +template > class stl_hash_compare : public Compare { public: INLINE size_t operator () (const Key &key) const { @@ -118,7 +118,7 @@ public: * size_t typecast operator). It is the same as the system-provided * hash_compare. */ -template > +template > class integer_hash : public stl_hash_compare { public: INLINE static size_t add_hash(size_t start, const Key &key); @@ -128,7 +128,7 @@ public: * This is the default hash_compare class, which assumes the Key is a pointer * value. It is the same as the system-provided hash_compare. */ -class pointer_hash : public stl_hash_compare > { +class pointer_hash : public stl_hash_compare > { public: INLINE static size_t add_hash(size_t start, const void *key); }; @@ -150,7 +150,7 @@ public: * This hash_compare class hashes a string. It assumes the Key is a string or * provides begin() and end() methods that iterate through Key::value_type. */ -template > +template > class sequence_hash : public stl_hash_compare { public: INLINE size_t operator () (const Key &key) const; @@ -164,7 +164,7 @@ public: * This hash_compare class hashes a class object. It assumes the Key provides * a method called get_hash() that returns a size_t. */ -template > +template > class method_hash : public stl_hash_compare { public: INLINE size_t operator () (const Key &key) const; @@ -208,8 +208,8 @@ typedef floating_point_hash float_hash; typedef floating_point_hash double_hash; typedef integer_hash int_hash; typedef integer_hash size_t_hash; -typedef sequence_hash string_hash; -typedef sequence_hash wstring_hash; +typedef sequence_hash string_hash; +typedef sequence_hash wstring_hash; template class indirect_less_hash : public indirect_method_hash > { diff --git a/dtool/src/dtoolbase/test_strtod.cxx b/dtool/src/dtoolbase/test_strtod.cxx index e2c10de958..1071a89273 100644 --- a/dtool/src/dtoolbase/test_strtod.cxx +++ b/dtool/src/dtoolbase/test_strtod.cxx @@ -24,11 +24,11 @@ main(int argc, char *argv[]) { #endif for (int i = 1; i < argc; ++i) { - char *endptr = NULL; + char *endptr = nullptr; double result = pstrtod(argv[i], &endptr); - cerr << "pstrtod - " << argv[i] << " : " << result << " : " << endptr << "\n"; + std::cerr << "pstrtod - " << argv[i] << " : " << result << " : " << endptr << "\n"; result = strtod(argv[i], &endptr); - cerr << "strtod - " << argv[i] << " : " << result << " : " << endptr << "\n"; + std::cerr << "strtod - " << argv[i] << " : " << result << " : " << endptr << "\n"; } return 0; diff --git a/dtool/src/dtoolbase/typeHandle.I b/dtool/src/dtoolbase/typeHandle.I index 3e9e53a9ae..134d85581a 100644 --- a/dtool/src/dtoolbase/typeHandle.I +++ b/dtool/src/dtoolbase/typeHandle.I @@ -84,7 +84,7 @@ get_hash() const { * owns this TypeHandle. It is only used in case the TypeHandle is * inadvertantly undefined. */ -INLINE string TypeHandle:: +INLINE std::string TypeHandle:: get_name(TypedObject *object) const { if ((*this) == TypeHandle::none()) { return "none"; @@ -187,18 +187,10 @@ get_index() const { * */ INLINE void TypeHandle:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_name(); } -/** - * Returns a special zero-valued TypeHandle that is used to indicate no type. - */ -CONSTEXPR TypeHandle TypeHandle:: -none() { - return TypeHandle(0); -} - /** * TypeHandle::none() evaluates to false, everything else evaluates to true. */ @@ -207,21 +199,10 @@ operator bool () const { return (_index != 0); } -/** - * Creates a TypeHandle from a type index without error checking, for use by - * internal functions. - * - * See TypeRegistry::find_type_by_id(). - */ -CONSTEXPR TypeHandle TypeHandle:: -from_index(int index) { - return TypeHandle(index); -} - /** * Private constructor for initializing a TypeHandle from an index, used by * none() and by from_index(). */ -CONSTEXPR TypeHandle:: +constexpr TypeHandle:: TypeHandle(int index) : _index(index) { } diff --git a/dtool/src/dtoolbase/typeHandle.cxx b/dtool/src/dtoolbase/typeHandle.cxx index ed85da8d03..1b96352723 100644 --- a/dtool/src/dtoolbase/typeHandle.cxx +++ b/dtool/src/dtoolbase/typeHandle.cxx @@ -30,8 +30,8 @@ get_memory_usage(MemoryClass memory_class) const { if ((*this) == TypeHandle::none()) { return 0; } else { - TypeRegistryNode *rnode = TypeRegistry::ptr()->look_up(*this, NULL); - assert(rnode != (TypeRegistryNode *)NULL); + TypeRegistryNode *rnode = TypeRegistry::ptr()->look_up(*this, nullptr); + assert(rnode != nullptr); return (size_t)AtomicAdjust::get(rnode->_memory_usage[memory_class]); } #endif // DO_MEMORY_USAGE @@ -49,13 +49,13 @@ inc_memory_usage(MemoryClass memory_class, size_t size) { assert((int)memory_class >= 0 && (int)memory_class < (int)MC_limit); #endif if ((*this) != TypeHandle::none()) { - TypeRegistryNode *rnode = TypeRegistry::ptr()->look_up(*this, NULL); - assert(rnode != (TypeRegistryNode *)NULL); + TypeRegistryNode *rnode = TypeRegistry::ptr()->look_up(*this, nullptr); + assert(rnode != nullptr); AtomicAdjust::add(rnode->_memory_usage[memory_class], (AtomicAdjust::Integer)size); // cerr << *this << ".inc(" << memory_class << ", " << size << ") -> " << // rnode->_memory_usage[memory_class] << "\n"; if (rnode->_memory_usage[memory_class] < 0) { - cerr << "Memory usage overflow for type " << rnode->_name << ".\n"; + std::cerr << "Memory usage overflow for type " << rnode->_name << ".\n"; abort(); } } @@ -73,8 +73,8 @@ dec_memory_usage(MemoryClass memory_class, size_t size) { assert((int)memory_class >= 0 && (int)memory_class < (int)MC_limit); #endif if ((*this) != TypeHandle::none()) { - TypeRegistryNode *rnode = TypeRegistry::ptr()->look_up(*this, NULL); - assert(rnode != (TypeRegistryNode *)NULL); + TypeRegistryNode *rnode = TypeRegistry::ptr()->look_up(*this, nullptr); + assert(rnode != nullptr); AtomicAdjust::add(rnode->_memory_usage[memory_class], -(AtomicAdjust::Integer)size); // cerr << *this << ".dec(" << memory_class << ", " << size << ") -> " << // rnode->_memory_usage[memory_class] << "\n"; @@ -98,11 +98,11 @@ allocate_array(size_t size) { #ifdef _DEBUG assert(size <= alloc_size); #endif - TypeRegistryNode *rnode = TypeRegistry::ptr()->look_up(*this, NULL); - assert(rnode != (TypeRegistryNode *)NULL); + TypeRegistryNode *rnode = TypeRegistry::ptr()->look_up(*this, nullptr); + assert(rnode != nullptr); AtomicAdjust::add(rnode->_memory_usage[MC_array], (AtomicAdjust::Integer)alloc_size); if (rnode->_memory_usage[MC_array] < 0) { - cerr << "Memory usage overflow for type " << rnode->_name << ".\n"; + std::cerr << "Memory usage overflow for type " << rnode->_name << ".\n"; abort(); } } @@ -125,8 +125,8 @@ reallocate_array(void *old_ptr, size_t size) { if ((*this) != TypeHandle::none()) { size_t new_size = MemoryHook::get_ptr_size(new_ptr); - TypeRegistryNode *rnode = TypeRegistry::ptr()->look_up(*this, NULL); - assert(rnode != (TypeRegistryNode *)NULL); + TypeRegistryNode *rnode = TypeRegistry::ptr()->look_up(*this, nullptr); + assert(rnode != nullptr); AtomicAdjust::add(rnode->_memory_usage[MC_array], (AtomicAdjust::Integer)new_size - (AtomicAdjust::Integer)old_size); assert(rnode->_memory_usage[MC_array] >= 0); } @@ -147,8 +147,8 @@ deallocate_array(void *ptr) { #ifdef DO_MEMORY_USAGE size_t alloc_size = MemoryHook::get_ptr_size(ptr); if ((*this) != TypeHandle::none()) { - TypeRegistryNode *rnode = TypeRegistry::ptr()->look_up(*this, NULL); - assert(rnode != (TypeRegistryNode *)NULL); + TypeRegistryNode *rnode = TypeRegistry::ptr()->look_up(*this, nullptr); + assert(rnode != nullptr); AtomicAdjust::add(rnode->_memory_usage[MC_array], -(AtomicAdjust::Integer)alloc_size); assert(rnode->_memory_usage[MC_array] >= 0); } @@ -175,8 +175,8 @@ get_best_parent_from_Set(const std::set< int > &legal_vals) const { return -1; } -ostream & -operator << (ostream &out, TypeHandle::MemoryClass mem_class) { +std::ostream & +operator << (std::ostream &out, TypeHandle::MemoryClass mem_class) { switch (mem_class) { case TypeHandle::MC_singleton: return out << "singleton"; diff --git a/dtool/src/dtoolbase/typeHandle.h b/dtool/src/dtoolbase/typeHandle.h index 3138d51e4b..da66074750 100644 --- a/dtool/src/dtoolbase/typeHandle.h +++ b/dtool/src/dtoolbase/typeHandle.h @@ -78,9 +78,9 @@ class TypedObject; * that ancestry of a particular type may be queried, and the type name may be * retrieved for run-time display. */ -class EXPCL_DTOOL_DTOOLBASE TypeHandle FINAL { +class EXPCL_DTOOL_DTOOLBASE TypeHandle final { PUBLISHED: - TypeHandle() NOEXCEPT DEFAULT_CTOR; + TypeHandle() noexcept = default; enum MemoryClass { MC_singleton, @@ -108,18 +108,18 @@ PUBLISHED: INLINE int compare_to(const TypeHandle &other) const; INLINE size_t get_hash() const; - INLINE string get_name(TypedObject *object = (TypedObject *)NULL) const; + INLINE std::string get_name(TypedObject *object = nullptr) const; INLINE bool is_derived_from(TypeHandle parent, - TypedObject *object = (TypedObject *)NULL) const; + TypedObject *object = nullptr) const; - INLINE int get_num_parent_classes(TypedObject *object = (TypedObject *)NULL) const; + INLINE int get_num_parent_classes(TypedObject *object = nullptr) const; INLINE TypeHandle get_parent_class(int index) const; - INLINE int get_num_child_classes(TypedObject *object = (TypedObject *)NULL) const; + INLINE int get_num_child_classes(TypedObject *object = nullptr) const; INLINE TypeHandle get_child_class(int index) const; INLINE TypeHandle get_parent_towards(TypeHandle ancestor, - TypedObject *object = (TypedObject *)NULL) const; + TypedObject *object = nullptr) const; int get_best_parent_from_Set(const std::set< int > &legal_vals) const; @@ -128,8 +128,8 @@ PUBLISHED: void dec_memory_usage(MemoryClass memory_class, size_t size); INLINE int get_index() const; - INLINE void output(ostream &out) const; - CONSTEXPR static TypeHandle none(); + INLINE void output(std::ostream &out) const; + constexpr static TypeHandle none() { return TypeHandle(0); } INLINE operator bool () const; MAKE_PROPERTY(index, get_index); @@ -142,10 +142,10 @@ public: void *reallocate_array(void *ptr, size_t size) RETURNS_ALIGNED(MEMORY_HOOK_ALIGNMENT); void deallocate_array(void *ptr); - CONSTEXPR static TypeHandle from_index(int index); + constexpr static TypeHandle from_index(int index) { return TypeHandle(index); } private: - CONSTEXPR TypeHandle(int index); + constexpr TypeHandle(int index); // Only kept temporarily for ABI compatibility. static TypeHandle _none; @@ -157,12 +157,12 @@ private: // It's handy to be able to output a TypeHandle directly, and see the type // name. -INLINE ostream &operator << (ostream &out, TypeHandle type) { +INLINE std::ostream &operator << (std::ostream &out, TypeHandle type) { type.output(out); return out; } -EXPCL_DTOOL_DTOOLBASE ostream &operator << (ostream &out, TypeHandle::MemoryClass mem_class); +EXPCL_DTOOL_DTOOLBASE std::ostream &operator << (std::ostream &out, TypeHandle::MemoryClass mem_class); // We must include typeRegistry at this point so we can call it from our // inline functions. This is a circular include that is strategically placed diff --git a/dtool/src/dtoolbase/typeRegistry.I b/dtool/src/dtoolbase/typeRegistry.I index e35f37c207..7d47c7f7f7 100644 --- a/dtool/src/dtoolbase/typeRegistry.I +++ b/dtool/src/dtoolbase/typeRegistry.I @@ -30,7 +30,7 @@ INLINE TypeRegistry *TypeRegistry:: ptr() { // It's OK that we don't acquire the lock, because we guarantee that this is // called at static init time. - if (_global_pointer == NULL) { + if (_global_pointer == nullptr) { init_global_pointer(); } return _global_pointer; @@ -41,7 +41,7 @@ ptr() { */ INLINE void TypeRegistry:: init_lock() { - if (_lock == (MutexImpl *)NULL) { + if (_lock == nullptr) { _lock = new MutexImpl; } } diff --git a/dtool/src/dtoolbase/typeRegistry.cxx b/dtool/src/dtoolbase/typeRegistry.cxx index 01b8ec498a..23cdb5ebfb 100644 --- a/dtool/src/dtoolbase/typeRegistry.cxx +++ b/dtool/src/dtoolbase/typeRegistry.cxx @@ -20,8 +20,13 @@ #include -MutexImpl *TypeRegistry::_lock = NULL; -TypeRegistry *TypeRegistry::_global_pointer = NULL; +using std::cerr; +using std::ostream; +using std::ostringstream; +using std::string; + +MutexImpl *TypeRegistry::_lock = nullptr; +TypeRegistry *TypeRegistry::_global_pointer = nullptr; /** * Creates a new Type of the given name and assigns a unique value to the @@ -32,15 +37,15 @@ TypeRegistry *TypeRegistry::_global_pointer = NULL; */ bool TypeRegistry:: register_type(TypeHandle &type_handle, const string &name) { - _lock->acquire(); + _lock->lock(); if (type_handle != TypeHandle::none()) { // Here's a type that was already registered. Just make sure everything's // still kosher. - TypeRegistryNode *rnode = look_up(type_handle, NULL); + TypeRegistryNode *rnode = look_up(type_handle, nullptr); if (&type_handle == &rnode->_ref) { // No problem. - _lock->release(); + _lock->unlock(); assert(rnode->_name == name); return false; } @@ -62,7 +67,7 @@ register_type(TypeHandle &type_handle, const string &name) { _derivations_fresh = false; type_handle = new_handle; - _lock->release(); + _lock->unlock(); return true; } TypeRegistryNode *rnode = (*ri).second; @@ -78,7 +83,7 @@ register_type(TypeHandle &type_handle, const string &name) { if (type_handle == rnode->_handle) { // No problem. - _lock->release(); + _lock->unlock(); return false; } // But wait--the type_handle has changed! We kept a reference to the @@ -87,7 +92,7 @@ register_type(TypeHandle &type_handle, const string &name) { // time, but now it's different! Bad juju. cerr << "Reregistering " << name << "\n"; type_handle = rnode->_handle; - _lock->release(); + _lock->unlock(); return false; } @@ -103,7 +108,7 @@ register_type(TypeHandle &type_handle, const string &name) { type_handle = rnode->_handle; } - _lock->release(); + _lock->unlock(); return false; } @@ -114,7 +119,7 @@ register_type(TypeHandle &type_handle, const string &name) { */ TypeHandle TypeRegistry:: register_dynamic_type(const string &name) { - _lock->acquire(); + _lock->lock(); NameRegistry::iterator ri; ri = _name_registry.find(name); @@ -134,14 +139,14 @@ register_dynamic_type(const string &name) { _name_registry[name] = rnode; _derivations_fresh = false; - _lock->release(); + _lock->unlock(); return *new_handle; } // Return the TypeHandle previously obtained. TypeRegistryNode *rnode = (*ri).second; TypeHandle handle = rnode->_handle; - _lock->release(); + _lock->unlock(); return handle; } @@ -152,12 +157,12 @@ register_dynamic_type(const string &name) { */ void TypeRegistry:: record_derivation(TypeHandle child, TypeHandle parent) { - _lock->acquire(); + _lock->lock(); - TypeRegistryNode *cnode = look_up(child, NULL); - assert(cnode != (TypeRegistryNode *)NULL); - TypeRegistryNode *pnode = look_up(parent, NULL); - assert(pnode != (TypeRegistryNode *)NULL); + TypeRegistryNode *cnode = look_up(child, nullptr); + assert(cnode != nullptr); + TypeRegistryNode *pnode = look_up(parent, nullptr); + assert(pnode != nullptr); // First, we'll just run through the list to make sure we hadn't already // made this connection. @@ -171,7 +176,7 @@ record_derivation(TypeHandle child, TypeHandle parent) { _derivations_fresh = false; } - _lock->release(); + _lock->unlock(); } /** @@ -182,15 +187,15 @@ record_derivation(TypeHandle child, TypeHandle parent) { */ void TypeRegistry:: record_alternate_name(TypeHandle type, const string &name) { - _lock->acquire(); + _lock->lock(); - TypeRegistryNode *rnode = look_up(type, (TypedObject *)NULL); - if (rnode != (TypeRegistryNode *)NULL) { + TypeRegistryNode *rnode = look_up(type, nullptr); + if (rnode != nullptr) { NameRegistry::iterator ri = _name_registry.insert(NameRegistry::value_type(name, rnode)).first; if ((*ri).second != rnode) { - _lock->release(); + _lock->unlock(); cerr << "Name " << name << " already assigned to TypeHandle " << rnode->_name << "; cannot reassign to " << type << "\n"; @@ -199,7 +204,7 @@ record_alternate_name(TypeHandle type, const string &name) { } - _lock->release(); + _lock->unlock(); } /** @@ -208,7 +213,7 @@ record_alternate_name(TypeHandle type, const string &name) { */ TypeHandle TypeRegistry:: find_type(const string &name) const { - _lock->acquire(); + _lock->lock(); TypeHandle handle = TypeHandle::none(); NameRegistry::const_iterator ri; @@ -216,7 +221,7 @@ find_type(const string &name) const { if (ri != _name_registry.end()) { handle = (*ri).second->_handle; } - _lock->release(); + _lock->unlock(); return handle; } @@ -248,11 +253,11 @@ find_type_by_id(int id) const { */ string TypeRegistry:: get_name(TypeHandle type, TypedObject *object) const { - _lock->acquire(); + _lock->lock(); TypeRegistryNode *rnode = look_up(type, object); - assert(rnode != (TypeRegistryNode *)NULL); + assert(rnode != nullptr); string name = rnode->_name; - _lock->release(); + _lock->unlock(); return name; } @@ -273,18 +278,18 @@ get_name(TypeHandle type, TypedObject *object) const { bool TypeRegistry:: is_derived_from(TypeHandle child, TypeHandle base, TypedObject *child_object) { - _lock->acquire(); + _lock->lock(); const TypeRegistryNode *child_node = look_up(child, child_object); - const TypeRegistryNode *base_node = look_up(base, (TypedObject *)NULL); + const TypeRegistryNode *base_node = look_up(base, nullptr); - assert(child_node != (TypeRegistryNode *)NULL); - assert(base_node != (TypeRegistryNode *)NULL); + assert(child_node != nullptr); + assert(base_node != nullptr); freshen_derivations(); bool result = TypeRegistryNode::is_derived_from(child_node, base_node); - _lock->release(); + _lock->unlock(); return result; } @@ -293,9 +298,9 @@ is_derived_from(TypeHandle child, TypeHandle base, */ int TypeRegistry:: get_num_typehandles() { - _lock->acquire(); + _lock->lock(); int num_types = (int)_handle_registry.size(); - _lock->release(); + _lock->unlock(); return num_types; } @@ -304,14 +309,14 @@ get_num_typehandles() { */ TypeHandle TypeRegistry:: get_typehandle(int n) { - _lock->acquire(); - TypeRegistryNode *rnode = NULL; + _lock->lock(); + TypeRegistryNode *rnode = nullptr; if (n >= 0 && n < (int)_handle_registry.size()) { rnode = _handle_registry[n]; } - _lock->release(); + _lock->unlock(); - if (rnode != (TypeRegistryNode *)NULL) { + if (rnode != nullptr) { return rnode->_handle; } @@ -324,10 +329,10 @@ get_typehandle(int n) { */ int TypeRegistry:: get_num_root_classes() { - _lock->acquire(); + _lock->lock(); freshen_derivations(); int num_roots = (int)_root_classes.size(); - _lock->release(); + _lock->unlock(); return num_roots; } @@ -336,7 +341,7 @@ get_num_root_classes() { */ TypeHandle TypeRegistry:: get_root_class(int n) { - _lock->acquire(); + _lock->lock(); freshen_derivations(); TypeHandle handle; if (n >= 0 && n < (int)_root_classes.size()) { @@ -344,7 +349,7 @@ get_root_class(int n) { } else { handle = TypeHandle::none(); } - _lock->release(); + _lock->unlock(); return handle; } @@ -362,11 +367,11 @@ get_root_class(int n) { */ int TypeRegistry:: get_num_parent_classes(TypeHandle child, TypedObject *child_object) const { - _lock->acquire(); + _lock->lock(); TypeRegistryNode *rnode = look_up(child, child_object); - assert(rnode != (TypeRegistryNode *)NULL); + assert(rnode != nullptr); int num_parents = (int)rnode->_parent_classes.size(); - _lock->release(); + _lock->unlock(); return num_parents; } @@ -376,16 +381,16 @@ get_num_parent_classes(TypeHandle child, TypedObject *child_object) const { */ TypeHandle TypeRegistry:: get_parent_class(TypeHandle child, int index) const { - _lock->acquire(); + _lock->lock(); TypeHandle handle; - TypeRegistryNode *rnode = look_up(child, (TypedObject *)NULL); - assert(rnode != (TypeRegistryNode *)NULL); + TypeRegistryNode *rnode = look_up(child, nullptr); + assert(rnode != nullptr); if (index >= 0 && index < (int)rnode->_parent_classes.size()) { handle = rnode->_parent_classes[index]->_handle; } else { handle = TypeHandle::none(); } - _lock->release(); + _lock->unlock(); return handle; } @@ -399,11 +404,11 @@ get_parent_class(TypeHandle child, int index) const { */ int TypeRegistry:: get_num_child_classes(TypeHandle child, TypedObject *child_object) const { - _lock->acquire(); + _lock->lock(); TypeRegistryNode *rnode = look_up(child, child_object); - assert(rnode != (TypeRegistryNode *)NULL); + assert(rnode != nullptr); int num_children = (int)rnode->_child_classes.size(); - _lock->release(); + _lock->unlock(); return num_children; } @@ -413,16 +418,16 @@ get_num_child_classes(TypeHandle child, TypedObject *child_object) const { */ TypeHandle TypeRegistry:: get_child_class(TypeHandle child, int index) const { - _lock->acquire(); + _lock->lock(); TypeHandle handle; - TypeRegistryNode *rnode = look_up(child, (TypedObject *)NULL); - assert(rnode != (TypeRegistryNode *)NULL); + TypeRegistryNode *rnode = look_up(child, nullptr); + assert(rnode != nullptr); if (index >= 0 && index < (int)rnode->_child_classes.size()) { handle = rnode->_child_classes[index]->_handle; } else { handle = TypeHandle::none(); } - _lock->release(); + _lock->unlock(); return handle; } @@ -439,15 +444,15 @@ get_child_class(TypeHandle child, int index) const { TypeHandle TypeRegistry:: get_parent_towards(TypeHandle child, TypeHandle base, TypedObject *child_object) { - _lock->acquire(); + _lock->lock(); TypeHandle handle; const TypeRegistryNode *child_node = look_up(child, child_object); - const TypeRegistryNode *base_node = look_up(base, NULL); - assert(child_node != (TypeRegistryNode *)NULL && - base_node != (TypeRegistryNode *)NULL); + const TypeRegistryNode *base_node = look_up(base, nullptr); + assert(child_node != nullptr && + base_node != nullptr); freshen_derivations(); handle = TypeRegistryNode::get_parent_towards(child_node, base_node); - _lock->release(); + _lock->unlock(); return handle; } @@ -462,18 +467,18 @@ get_parent_towards(TypeHandle child, TypeHandle base, void TypeRegistry:: reregister_types() { init_lock(); - _lock->acquire(); + _lock->lock(); HandleRegistry::iterator ri; TypeRegistry *reg = ptr(); for (ri = reg->_handle_registry.begin(); ri != reg->_handle_registry.end(); ++ri) { TypeRegistryNode *rnode = (*ri); - if (rnode != NULL && rnode->_handle != rnode->_ref) { + if (rnode != nullptr && rnode->_handle != rnode->_ref) { cerr << "Reregistering " << rnode->_name << "\n"; } } - _lock->release(); + _lock->unlock(); } @@ -483,9 +488,9 @@ reregister_types() { */ void TypeRegistry:: write(ostream &out) const { - _lock->acquire(); + _lock->lock(); do_write(out); - _lock->release(); + _lock->unlock(); } /** @@ -496,7 +501,7 @@ TypeRegistry() { // We'll start out our handle_registry with a default entry for the // TypeHandles whose index number is zero, and are therefore (probably) // uninitialized. - _handle_registry.push_back(NULL); + _handle_registry.push_back(nullptr); _derivations_fresh = false; @@ -537,7 +542,7 @@ rebuild_derivations() { hi != _handle_registry.end(); ++hi) { TypeRegistryNode *node = *hi; - if (node != (TypeRegistryNode *)NULL) { + if (node != nullptr) { node->clear_subtree(); } } @@ -548,7 +553,7 @@ rebuild_derivations() { hi != _handle_registry.end(); ++hi) { TypeRegistryNode *node = *hi; - if (node != NULL && node->_parent_classes.empty()) { + if (node != nullptr && node->_parent_classes.empty()) { _root_classes.push_back(node); // Also, for each root class, define a subtree. @@ -570,7 +575,7 @@ do_write(ostream &out) const { hi != _handle_registry.end(); ++hi) { const TypeRegistryNode *root = *hi; - if (root != NULL && root->_parent_classes.empty()) { + if (root != nullptr && root->_parent_classes.empty()) { write_node(out, 2, root); } } @@ -609,19 +614,19 @@ look_up_invalid(TypeHandle handle, TypedObject *object) const { if (handle._index == 0) { // The TypeHandle is unregistered. This is an error condition. - if (object != NULL) { + if (object != nullptr) { // But we're lucky enough to have a TypedObject pointer handy! Maybe we // can use it to resolve the error. We have to drop the lock while we // do this, so we don't get a recursive lock. - _lock->release(); + _lock->unlock(); handle = object->force_init_type(); - _lock->acquire(); + _lock->lock(); if (handle._index == 0) { // Strange. cerr << "Unable to force_init_type() on unregistered TypeHandle.\n"; - return NULL; + return nullptr; } // Now get the name for printing. We can't use TypeHandle:: get_name() @@ -629,7 +634,7 @@ look_up_invalid(TypeHandle handle, TypedObject *object) const { ostringstream name; if (handle._index > 0 && handle._index < (int)_handle_registry.size()) { TypeRegistryNode *rnode = _handle_registry[handle._index]; - if (rnode != (TypeRegistryNode *)NULL) { + if (rnode != nullptr) { name << rnode->_name; name << " (index " << handle._index << ")"; } else { @@ -650,7 +655,7 @@ look_up_invalid(TypeHandle handle, TypedObject *object) const { << "Attempt to reference unregistered TypeHandle. Type is of some\n" << "class derived from type " << name.str() << " that doesn't define\n" << "a good force_init_type() method.\n"; - return NULL; + return nullptr; } } else { @@ -660,7 +665,7 @@ look_up_invalid(TypeHandle handle, TypedObject *object) const { << "Attempt to reference unregistered TypeHandle!\n" << "Registered TypeHandles are:\n"; do_write(cerr); - return NULL; + return nullptr; } } @@ -669,7 +674,7 @@ look_up_invalid(TypeHandle handle, TypedObject *object) const { cerr << "Invalid TypeHandle index " << handle._index << "! Is memory corrupt?\n"; - return NULL; + return nullptr; } #endif // NDEBUG diff --git a/dtool/src/dtoolbase/typeRegistry.h b/dtool/src/dtoolbase/typeRegistry.h index 5c5c09ad4c..dc7df60541 100644 --- a/dtool/src/dtoolbase/typeRegistry.h +++ b/dtool/src/dtoolbase/typeRegistry.h @@ -38,18 +38,18 @@ public: // User code shouldn't generally need to call TypeRegistry::register_type() // or record_derivation() directly; instead, use the register_type // convenience function, defined in register_type.h. - bool register_type(TypeHandle &type_handle, const string &name); + bool register_type(TypeHandle &type_handle, const std::string &name); PUBLISHED: - TypeHandle register_dynamic_type(const string &name); + TypeHandle register_dynamic_type(const std::string &name); void record_derivation(TypeHandle child, TypeHandle parent); - void record_alternate_name(TypeHandle type, const string &name); + void record_alternate_name(TypeHandle type, const std::string &name); - TypeHandle find_type(const string &name) const; + TypeHandle find_type(const std::string &name) const; TypeHandle find_type_by_id(int id) const; - string get_name(TypeHandle type, TypedObject *object) const; + std::string get_name(TypeHandle type, TypedObject *object) const; bool is_derived_from(TypeHandle child, TypeHandle base, TypedObject *child_object); @@ -74,7 +74,7 @@ PUBLISHED: static void reregister_types(); - void write(ostream &out) const; + void write(std::ostream &out) const; // ptr() returns the pointer to the global TypeRegistry object. static INLINE TypeRegistry *ptr(); @@ -94,19 +94,19 @@ private: INLINE void freshen_derivations(); void rebuild_derivations(); - void do_write(ostream &out) const; - void write_node(ostream &out, int indent_level, + void do_write(std::ostream &out) const; + void write_node(std::ostream &out, int indent_level, const TypeRegistryNode *node) const; static INLINE void init_lock(); - typedef vector HandleRegistry; + typedef std::vector HandleRegistry; HandleRegistry _handle_registry; - typedef map NameRegistry; + typedef std::map NameRegistry; NameRegistry _name_registry; - typedef vector RootClasses; + typedef std::vector RootClasses; RootClasses _root_classes; bool _derivations_fresh; diff --git a/dtool/src/dtoolbase/typeRegistryNode.I b/dtool/src/dtoolbase/typeRegistryNode.I index c9298aae27..4328a47d79 100644 --- a/dtool/src/dtoolbase/typeRegistryNode.I +++ b/dtool/src/dtoolbase/typeRegistryNode.I @@ -16,7 +16,7 @@ */ INLINE TypeRegistryNode::Inherit:: Inherit() { - _top = (TypeRegistryNode *)NULL; + _top = nullptr; _mask = 0; _bits = 0; } diff --git a/dtool/src/dtoolbase/typeRegistryNode.cxx b/dtool/src/dtoolbase/typeRegistryNode.cxx index a88533a769..f809ddcc0b 100644 --- a/dtool/src/dtoolbase/typeRegistryNode.cxx +++ b/dtool/src/dtoolbase/typeRegistryNode.cxx @@ -22,7 +22,7 @@ bool TypeRegistryNode::_paranoid_inheritance = false; * */ TypeRegistryNode:: -TypeRegistryNode(TypeHandle handle, const string &name, TypeHandle &ref) : +TypeRegistryNode(TypeHandle handle, const std::string &name, TypeHandle &ref) : _handle(handle), _name(name), _ref(ref) { clear_subtree(); @@ -45,7 +45,7 @@ is_derived_from(const TypeRegistryNode *child, const TypeRegistryNode *base) { // additional work. (See r_build_subtrees()). if (child->_inherit._top == base->_inherit._top) { - assert(child->_inherit._top != (TypeRegistryNode *)NULL); + assert(child->_inherit._top != nullptr); bool derives = Inherit::is_derived_from(child->_inherit, base->_inherit); @@ -54,19 +54,19 @@ is_derived_from(const TypeRegistryNode *child, const TypeRegistryNode *base) { if (_paranoid_inheritance) { bool paranoid_derives = check_derived_from(child, base); if (derives != paranoid_derives) { - cerr + std::cerr << "Inheritance test for " << child->_name << " from " << base->_name << " failed!\n" << "Result: " << derives << " should have been: " << paranoid_derives << "\n" << "Classes are in the same single inheritance subtree, children of " << child->_inherit._top->_name << "\n" - << hex + << std::hex << child->_name << " has mask " << child->_inherit._mask << " and bits " << child->_inherit._bits << "\n" << base->_name << " has mask " << base->_inherit._mask << " and bits " << base->_inherit._bits << "\n" - << dec; + << std::dec; return paranoid_derives; } } @@ -118,7 +118,7 @@ is_derived_from(const TypeRegistryNode *child, const TypeRegistryNode *base) { if (_paranoid_inheritance) { bool paranoid_derives = check_derived_from(child, base); if (derives != paranoid_derives) { - cerr + std::cerr << "Inheritance test for " << child->_name << " from " << base->_name << " failed!\n" << "Result: " << derives << " should have been: " @@ -255,7 +255,7 @@ r_build_subtrees(TypeRegistryNode *top, int bit_count, if (_visit_count == (int)_parent_classes.size()) { // This is the last time we'll visit this node, so continue the // recursion now. - assert(_inherit._top == (TypeRegistryNode *)NULL); + assert(_inherit._top == nullptr); sort(_top_inheritance.begin(), _top_inheritance.end()); define_subtree(); } @@ -263,7 +263,7 @@ r_build_subtrees(TypeRegistryNode *top, int bit_count, } else { // This class singly inherits, so this had better be the only time this // function is called on it since clear_subtree(). - assert(_inherit._top == (TypeRegistryNode *)NULL); + assert(_inherit._top == nullptr); assert(bit_count < (int)(sizeof(SubtreeMaskType) * 8)); @@ -280,7 +280,7 @@ r_build_subtrees(TypeRegistryNode *top, int bit_count, // We need at least one bit, even if there is only one child, so we can // differentiate parent from child. - more_bits = max(more_bits, 1); + more_bits = std::max(more_bits, 1); assert(more_bits < (int)(sizeof(SubtreeMaskType) * 8)); diff --git a/dtool/src/dtoolbase/typeRegistryNode.h b/dtool/src/dtoolbase/typeRegistryNode.h index a8df5c339e..dd888cbf59 100644 --- a/dtool/src/dtoolbase/typeRegistryNode.h +++ b/dtool/src/dtoolbase/typeRegistryNode.h @@ -29,7 +29,7 @@ */ class EXPCL_DTOOL_DTOOLBASE TypeRegistryNode { public: - TypeRegistryNode(TypeHandle handle, const string &name, TypeHandle &ref); + TypeRegistryNode(TypeHandle handle, const std::string &name, TypeHandle &ref); static bool is_derived_from(const TypeRegistryNode *child, const TypeRegistryNode *base); @@ -41,9 +41,9 @@ public: void define_subtree(); TypeHandle _handle; - string _name; + std::string _name; TypeHandle &_ref; - typedef vector Classes; + typedef std::vector Classes; Classes _parent_classes; Classes _child_classes; @@ -72,7 +72,7 @@ private: SubtreeMaskType _mask; SubtreeMaskType _bits; }; - typedef vector TopInheritance; + typedef std::vector TopInheritance; void r_build_subtrees(TypeRegistryNode *top, int bit_count, SubtreeMaskType bits); diff --git a/dtool/src/dtoolbase/typedObject.cxx b/dtool/src/dtoolbase/typedObject.cxx index a397ef843e..73a2cfc9c2 100644 --- a/dtool/src/dtoolbase/typedObject.cxx +++ b/dtool/src/dtoolbase/typedObject.cxx @@ -31,7 +31,7 @@ get_type() const { // Normally, this function should never be called, because it is a pure // virtual function. If it is called, you probably called get_type() on a // recently-destructed object. - cerr + std::cerr << "TypedObject::get_type() called!\n"; return _type_handle; } diff --git a/dtool/src/dtoolbase/typedObject.h b/dtool/src/dtoolbase/typedObject.h index f3d6c193e3..dd60515f16 100644 --- a/dtool/src/dtoolbase/typedObject.h +++ b/dtool/src/dtoolbase/typedObject.h @@ -87,9 +87,9 @@ */ class EXPCL_DTOOL_DTOOLBASE TypedObject : public MemoryBase { public: - INLINE TypedObject() DEFAULT_CTOR; - INLINE TypedObject(const TypedObject ©) DEFAULT_CTOR; - INLINE TypedObject &operator = (const TypedObject ©) DEFAULT_ASSIGN; + INLINE TypedObject() = default; + INLINE TypedObject(const TypedObject ©) = default; + INLINE TypedObject &operator = (const TypedObject ©) = default; PUBLISHED: // A virtual destructor is just a good idea. diff --git a/dtool/src/dtoolutil/config_dtoolutil.N b/dtool/src/dtoolutil/config_dtoolutil.N index 2577aa3b24..2ccd2b4210 100644 --- a/dtool/src/dtoolutil/config_dtoolutil.N +++ b/dtool/src/dtoolutil/config_dtoolutil.N @@ -1,9 +1,10 @@ -forcetype ofstream -forcetype ifstream -forcetype fstream +forcetype std::ofstream +forcetype std::ifstream +forcetype std::fstream -forcetype ios_base -forcetype ios -forcetype istream -forcetype ostream -forcetype iostream +forcetype std::ios_base +forcetype std::basic_ios +forcetype std::ios +forcetype std::istream +forcetype std::ostream +forcetype std::iostream diff --git a/dtool/src/dtoolutil/config_dtoolutil.h b/dtool/src/dtoolutil/config_dtoolutil.h index 20e9784c55..2d297937be 100644 --- a/dtool/src/dtoolutil/config_dtoolutil.h +++ b/dtool/src/dtoolutil/config_dtoolutil.h @@ -19,4 +19,6 @@ // Include this so interrogate can find it. #include +extern EXPCL_DTOOL_DTOOLUTIL void init_libdtoolutil(); + #endif diff --git a/dtool/src/dtoolutil/dSearchPath.I b/dtool/src/dtoolutil/dSearchPath.I index 3a958915d6..66055a7466 100644 --- a/dtool/src/dtoolutil/dSearchPath.I +++ b/dtool/src/dtoolutil/dSearchPath.I @@ -48,8 +48,8 @@ find_all_files(const Filename &filename) const { * searches that. */ INLINE Filename DSearchPath:: -search_path(const Filename &filename, const string &path, - const string &separator) { +search_path(const Filename &filename, const std::string &path, + const std::string &separator) { DSearchPath search(path, separator); return search.find_file(filename); } diff --git a/dtool/src/dtoolutil/dSearchPath.cxx b/dtool/src/dtoolutil/dSearchPath.cxx index d0aec4c3ad..4a094f1d98 100644 --- a/dtool/src/dtoolutil/dSearchPath.cxx +++ b/dtool/src/dtoolutil/dSearchPath.cxx @@ -17,6 +17,9 @@ #include #include +using std::ostream; +using std::string; + /** * */ @@ -220,8 +223,8 @@ append_path(const string &path, const string &separator) { */ void DSearchPath:: append_path(const DSearchPath &path) { - copy(path._directories.begin(), path._directories.end(), - back_inserter(_directories)); + std::copy(path._directories.begin(), path._directories.end(), + std::back_inserter(_directories)); } /** @@ -232,8 +235,8 @@ void DSearchPath:: prepend_path(const DSearchPath &path) { if (!path._directories.empty()) { Directories new_directories = path._directories; - copy(_directories.begin(), _directories.end(), - back_inserter(new_directories)); + std::copy(_directories.begin(), _directories.end(), + std::back_inserter(new_directories)); _directories.swap(new_directories); } } diff --git a/dtool/src/dtoolutil/dSearchPath.h b/dtool/src/dtoolutil/dSearchPath.h index 85184df77c..8cb769c378 100644 --- a/dtool/src/dtoolutil/dSearchPath.h +++ b/dtool/src/dtoolutil/dSearchPath.h @@ -41,8 +41,8 @@ PUBLISHED: INLINE Filename operator [] (size_t n) const; INLINE size_t size() const; - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; public: void add_file(const Filename &file); @@ -53,7 +53,7 @@ PUBLISHED: }; DSearchPath(); - DSearchPath(const string &path, const string &separator = string()); + DSearchPath(const std::string &path, const std::string &separator = std::string()); DSearchPath(const Filename &directory); DSearchPath(const DSearchPath ©); void operator = (const DSearchPath ©); @@ -62,8 +62,8 @@ PUBLISHED: void clear(); void append_directory(const Filename &directory); void prepend_directory(const Filename &directory); - void append_path(const string &path, - const string &separator = string()); + void append_path(const std::string &path, + const std::string &separator = std::string()); void append_path(const DSearchPath &path); void prepend_path(const DSearchPath &path); @@ -78,18 +78,18 @@ PUBLISHED: INLINE Results find_all_files(const Filename &filename) const; INLINE static Filename - search_path(const Filename &filename, const string &path, - const string &separator = string()); + search_path(const Filename &filename, const std::string &path, + const std::string &separator = std::string()); - void output(ostream &out, const string &separator = string()) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out, const std::string &separator = std::string()) const; + void write(std::ostream &out, int indent_level = 0) const; private: typedef pvector Directories; Directories _directories; }; -INLINE ostream &operator << (ostream &out, const DSearchPath &sp) { +INLINE std::ostream &operator << (std::ostream &out, const DSearchPath &sp) { sp.output(out); return out; } diff --git a/dtool/src/dtoolutil/executionEnvironment.I b/dtool/src/dtoolutil/executionEnvironment.I index b1fe554a29..4639ab0a36 100644 --- a/dtool/src/dtoolutil/executionEnvironment.I +++ b/dtool/src/dtoolutil/executionEnvironment.I @@ -15,7 +15,7 @@ * Returns true if the indicated environment variable is defined. */ INLINE bool ExecutionEnvironment:: -has_environment_variable(const string &var) { +has_environment_variable(const std::string &var) { return get_ptr()->ns_has_environment_variable(var); } @@ -23,8 +23,8 @@ has_environment_variable(const string &var) { * Returns the definition of the indicated environment variable, or the empty * string if the variable is undefined. */ -INLINE string ExecutionEnvironment:: -get_environment_variable(const string &var) { +INLINE std::string ExecutionEnvironment:: +get_environment_variable(const std::string &var) { return get_ptr()->ns_get_environment_variable(var); } @@ -32,7 +32,7 @@ get_environment_variable(const string &var) { * Changes the definition of the indicated environment variable. */ INLINE void ExecutionEnvironment:: -set_environment_variable(const string &var, const string &value) { +set_environment_variable(const std::string &var, const std::string &value) { get_ptr()->ns_set_environment_variable(var, value); } @@ -43,7 +43,7 @@ set_environment_variable(const string &var, const string &value) { * will return this new value. */ INLINE void ExecutionEnvironment:: -shadow_environment_variable(const string &var, const string &value) { +shadow_environment_variable(const std::string &var, const std::string &value) { get_ptr()->ns_shadow_environment_variable(var, value); } @@ -52,7 +52,7 @@ shadow_environment_variable(const string &var, const string &value) { * and lets the actual value of the variable show again. */ INLINE void ExecutionEnvironment:: -clear_shadow(const string &var) { +clear_shadow(const std::string &var) { get_ptr()->ns_clear_shadow(var); } @@ -70,7 +70,7 @@ get_num_args() { * .. get_num_args()). The first parameter, n == 0, is the first actual * parameter, not the binary name. */ -INLINE string ExecutionEnvironment:: +INLINE std::string ExecutionEnvironment:: get_arg(size_t n) { return get_ptr()->ns_get_arg(n); } @@ -79,7 +79,7 @@ get_arg(size_t n) { * Returns the name of the binary executable that started this program, if it * can be determined. */ -INLINE string ExecutionEnvironment:: +INLINE std::string ExecutionEnvironment:: get_binary_name() { return get_ptr()->ns_get_binary_name(); } @@ -88,7 +88,7 @@ get_binary_name() { * Returns the name of the libdtool DLL that is used in this program, if it * can be determined. */ -INLINE string ExecutionEnvironment:: +INLINE std::string ExecutionEnvironment:: get_dtool_name() { return get_ptr()->ns_get_dtool_name(); } @@ -97,7 +97,7 @@ get_dtool_name() { * Do not use. */ INLINE void ExecutionEnvironment:: -set_binary_name(const string &name) { +set_binary_name(const std::string &name) { get_ptr()->_binary_name = name; } @@ -105,6 +105,6 @@ set_binary_name(const string &name) { * Do not use. */ INLINE void ExecutionEnvironment:: -set_dtool_name(const string &name) { +set_dtool_name(const std::string &name) { get_ptr()->_dtool_name = name; } diff --git a/dtool/src/dtoolutil/executionEnvironment.cxx b/dtool/src/dtoolutil/executionEnvironment.cxx index c4f2e5093e..4152a8c356 100644 --- a/dtool/src/dtoolutil/executionEnvironment.cxx +++ b/dtool/src/dtoolutil/executionEnvironment.cxx @@ -18,6 +18,9 @@ #include #include // for perror +using std::cerr; +using std::string; + #ifdef __APPLE__ #include // for realpath #endif // __APPLE__ @@ -86,7 +89,7 @@ extern int GLOBAL_ARGC; // safely access them at stat init time--at least, not in libc5. (It does seem // to work with glibc2, however.) -ExecutionEnvironment *ExecutionEnvironment::_global_ptr = NULL; +ExecutionEnvironment *ExecutionEnvironment::_global_ptr = nullptr; /** * You shouldn't need to construct one of these; there's only one and it @@ -162,13 +165,13 @@ get_cwd() { #ifdef WIN32_VC // getcwd() requires us to allocate a dynamic buffer and grow it on demand. static size_t bufsize = 1024; - static wchar_t *buffer = NULL; + static wchar_t *buffer = nullptr; - if (buffer == (wchar_t *)NULL) { + if (buffer == nullptr) { buffer = new wchar_t[bufsize]; } - while (_wgetcwd(buffer, bufsize) == (wchar_t *)NULL) { + while (_wgetcwd(buffer, bufsize) == nullptr) { if (errno != ERANGE) { perror("getcwd"); return string(); @@ -176,7 +179,7 @@ get_cwd() { delete[] buffer; bufsize = bufsize * 2; buffer = new wchar_t[bufsize]; - assert(buffer != (wchar_t *)NULL); + assert(buffer != nullptr); } Filename cwd = Filename::from_os_specific_w(buffer); @@ -185,13 +188,13 @@ get_cwd() { #else // WIN32_VC // getcwd() requires us to allocate a dynamic buffer and grow it on demand. static size_t bufsize = 1024; - static char *buffer = NULL; + static char *buffer = nullptr; - if (buffer == (char *)NULL) { + if (buffer == nullptr) { buffer = new char[bufsize]; } - while (getcwd(buffer, bufsize) == (char *)NULL) { + while (getcwd(buffer, bufsize) == nullptr) { if (errno != ERANGE) { perror("getcwd"); return string(); @@ -199,7 +202,7 @@ get_cwd() { delete[] buffer; bufsize = bufsize * 2; buffer = new char[bufsize]; - assert(buffer != (char *)NULL); + assert(buffer != nullptr); } Filename cwd = Filename::from_os_specific(buffer); @@ -217,7 +220,7 @@ ns_has_environment_variable(const string &var) const { #ifdef PREREAD_ENVIRONMENT return _variables.count(var) != 0; #else - return getenv(var.c_str()) != (char *)NULL; + return getenv(var.c_str()) != nullptr; #endif } @@ -257,7 +260,7 @@ ns_get_environment_variable(const string &var) const { #ifndef PREREAD_ENVIRONMENT const char *def = getenv(var.c_str()); - if (def != (char *)NULL) { + if (def != nullptr) { return def; } #endif @@ -327,13 +330,13 @@ ns_get_environment_variable(const string &var) const { { CSIDL_SYSTEMX86, "SYSTEMX86" }, { CSIDL_TEMPLATES, "TEMPLATES" }, { CSIDL_WINDOWS, "WINDOWS" }, - { 0, NULL }, + { 0, nullptr }, }; - for (int i = 0; csidl_table[i].name != NULL; ++i) { + for (int i = 0; csidl_table[i].name != nullptr; ++i) { if (strcmp(var.c_str(), csidl_table[i].name) == 0) { wchar_t buffer[MAX_PATH]; - if (SHGetSpecialFolderPathW(NULL, buffer, csidl_table[i].id, true)) { + if (SHGetSpecialFolderPathW(nullptr, buffer, csidl_table[i].id, true)) { Filename pathname = Filename::from_os_specific_w(buffer); return pathname.to_os_specific(); } @@ -399,7 +402,7 @@ ns_clear_shadow(const string &var) { #ifdef PREREAD_ENVIRONMENT // Now we have to replace the value in the table. const char *def = getenv(var.c_str()); - if (def != (char *)NULL) { + if (def != nullptr) { (*vi).second = def; } else { _variables.erase(vi); @@ -457,7 +460,7 @@ ns_get_dtool_name() const { */ ExecutionEnvironment *ExecutionEnvironment:: get_ptr() { - if (_global_ptr == (ExecutionEnvironment *)NULL) { + if (_global_ptr == nullptr) { _global_ptr = new ExecutionEnvironment; } return _global_ptr; @@ -554,7 +557,7 @@ read_args() { wchar_t buffer[buffer_size]; DWORD size = GetModuleFileNameW(dllhandle, buffer, buffer_size); if (size != 0) { - Filename tmp = Filename::from_os_specific_w(wstring(buffer, size)); + Filename tmp = Filename::from_os_specific_w(std::wstring(buffer, size)); tmp.make_true_case(); _dtool_name = tmp; } @@ -577,20 +580,20 @@ read_args() { } #endif -#if defined(IS_FREEBSD) || (defined(IS_LINUX) && !defined(__ANDROID__)) - // FreeBSD and Linux have a function to get the origin of a loaded library. +#if defined(RTLD_DI_ORIGIN) + // When building with glibc/uClibc, we typically have access to RTLD_DI_ORIGIN in Unix-like operating systems. char origin[PATH_MAX + 1]; if (_dtool_name.empty()) { void *dtool_handle = dlopen("libp3dtool.so." PANDA_ABI_VERSION_STR, RTLD_NOW | RTLD_NOLOAD); - if (dtool_handle != NULL && dlinfo(dtool_handle, RTLD_DI_ORIGIN, origin) != -1) { + if (dtool_handle != nullptr && dlinfo(dtool_handle, RTLD_DI_ORIGIN, origin) != -1) { _dtool_name = origin; _dtool_name += "/libp3dtool.so." PANDA_ABI_VERSION_STR; } else { // Try the version of libp3dtool.so without ABI suffix. dtool_handle = dlopen("libp3dtool.so", RTLD_NOW | RTLD_NOLOAD); - if (dtool_handle != NULL && dlinfo(dtool_handle, RTLD_DI_ORIGIN, origin) != -1) { + if (dtool_handle != nullptr && dlinfo(dtool_handle, RTLD_DI_ORIGIN, origin) != -1) { _dtool_name = origin; _dtool_name += "/libp3dtool.so"; } @@ -598,14 +601,18 @@ read_args() { } #endif -#if defined(IS_FREEBSD) - // On FreeBSD, we can use dlinfo to get the linked libraries. - +#if !defined(RTLD_DI_ORIGIN) && defined(RTLD_DI_LINKMAP) + // On platforms without RTLD_DI_ORIGIN, we can use dlinfo with RTLD_DI_LINKMAP to get the origin of a loaded library. if (_dtool_name.empty()) { - Link_map *map; - dlinfo(RTLD_SELF, RTLD_DI_LINKMAP, &map); + struct link_map *map; +#ifdef RTLD_SELF + void *self = RTLD_SELF; +#else + void *self = dlopen(NULL, RTLD_NOW | RTLD_NOLOAD); +#endif + dlinfo(self, RTLD_DI_LINKMAP, &map); - while (map != NULL) { + while (map != nullptr) { const char *tail = strrchr(map->l_name, '/'); const char *head = strchr(map->l_name, '/'); if (tail && head && (strcmp(tail, "/libp3dtool.so." PANDA_ABI_VERSION_STR) == 0 @@ -648,9 +655,9 @@ read_args() { if (_binary_name.empty()) { static const DWORD buffer_size = 1024; wchar_t buffer[buffer_size]; - DWORD size = GetModuleFileNameW(NULL, buffer, buffer_size); + DWORD size = GetModuleFileNameW(nullptr, buffer, buffer_size); if (size != 0) { - Filename tmp = Filename::from_os_specific_w(wstring(buffer, size)); + Filename tmp = Filename::from_os_specific_w(std::wstring(buffer, size)); tmp.make_true_case(); _binary_name = tmp; } @@ -677,7 +684,7 @@ read_args() { char buffer[4096]; int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1}; mib[3] = getpid(); - if (sysctl(mib, 4, (void*) buffer, &bufsize, NULL, 0) == -1) { + if (sysctl(mib, 4, (void*) buffer, &bufsize, nullptr, 0) == -1) { perror("sysctl"); } else { _binary_name = buffer; @@ -715,7 +722,7 @@ read_args() { int argc = 0; LPWSTR *wargv = CommandLineToArgvW(cmdline, &argc); - if (wargv == NULL) { + if (wargv == nullptr) { cerr << "CommandLineToArgvW failed; command-line arguments unavailable to config.\n"; } else { @@ -723,7 +730,7 @@ read_args() { encoder.set_encoding(Filename::get_filesystem_encoding()); for (int i = 0; i < argc; ++i) { - wstring wtext(wargv[i]); + std::wstring wtext(wargv[i]); encoder.set_wtext(wtext); if (i == 0) { @@ -745,16 +752,16 @@ read_args() { char buffer[4096]; int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ARGS, 0}; mib[3] = getpid(); - if (sysctl(mib, 4, (void*) buffer, &bufsize, NULL, 0) == -1) { + if (sysctl(mib, 4, (void*) buffer, &bufsize, nullptr, 0) == -1) { perror("sysctl"); } else { if (_binary_name.empty()) { _binary_name = buffer; } - int idx = strlen(buffer) + 1; + size_t idx = strlen(buffer) + 1; while (idx < bufsize) { _args.push_back((char*)(buffer + idx)); - int newidx = strlen(buffer + idx); + size_t newidx = strlen(buffer + idx); idx += newidx + 1; } } @@ -764,7 +771,7 @@ read_args() { // On Windows, __argv can be NULL when the main entry point is compiled in // Unicode mode (as is the case with Python 3) - if (GLOBAL_ARGV != NULL) { + if (GLOBAL_ARGV != nullptr) { if (_binary_name.empty() && argc > 0) { _binary_name = GLOBAL_ARGV[0]; // This really needs to be resolved against PATH. @@ -819,14 +826,14 @@ read_args() { if (!_binary_name.empty()) { char newpath [PATH_MAX + 1]; - if (realpath(_binary_name.c_str(), newpath) != NULL) { + if (realpath(_binary_name.c_str(), newpath) != nullptr) { _binary_name = newpath; } } if (!_dtool_name.empty()) { char newpath [PATH_MAX + 1]; - if (realpath(_dtool_name.c_str(), newpath) != NULL) { + if (realpath(_dtool_name.c_str(), newpath) != nullptr) { _dtool_name = newpath; } } diff --git a/dtool/src/dtoolutil/executionEnvironment.h b/dtool/src/dtoolutil/executionEnvironment.h index 7415f19642..0ff0814cdd 100644 --- a/dtool/src/dtoolutil/executionEnvironment.h +++ b/dtool/src/dtoolutil/executionEnvironment.h @@ -31,23 +31,23 @@ private: ExecutionEnvironment(); PUBLISHED: - INLINE static bool has_environment_variable(const string &var); - INLINE static string get_environment_variable(const string &var); - INLINE static void set_environment_variable(const string &var, const string &value); + INLINE static bool has_environment_variable(const std::string &var); + INLINE static std::string get_environment_variable(const std::string &var); + INLINE static void set_environment_variable(const std::string &var, const std::string &value); - INLINE static void shadow_environment_variable(const string &var, const string &value); - INLINE static void clear_shadow(const string &var); + INLINE static void shadow_environment_variable(const std::string &var, const std::string &value); + INLINE static void clear_shadow(const std::string &var); - static string expand_string(const string &str); + static std::string expand_string(const std::string &str); INLINE static size_t get_num_args(); - INLINE static string get_arg(size_t n); + INLINE static std::string get_arg(size_t n); - INLINE static string get_binary_name(); - INLINE static string get_dtool_name(); + INLINE static std::string get_binary_name(); + INLINE static std::string get_dtool_name(); - INLINE static void set_binary_name(const string &name); - INLINE static void set_dtool_name(const string &name); + INLINE static void set_binary_name(const std::string &name); + INLINE static void set_dtool_name(const std::string &name); static Filename get_cwd(); @@ -61,17 +61,17 @@ PUBLISHED: MAKE_PROPERTY(cwd, get_cwd); private: - bool ns_has_environment_variable(const string &var) const; - string ns_get_environment_variable(const string &var) const; - void ns_set_environment_variable(const string &var, const string &value); - void ns_shadow_environment_variable(const string &var, const string &value); - void ns_clear_shadow(const string &var); + bool ns_has_environment_variable(const std::string &var) const; + std::string ns_get_environment_variable(const std::string &var) const; + void ns_set_environment_variable(const std::string &var, const std::string &value); + void ns_shadow_environment_variable(const std::string &var, const std::string &value); + void ns_clear_shadow(const std::string &var); size_t ns_get_num_args() const; - string ns_get_arg(size_t n) const; + std::string ns_get_arg(size_t n) const; - string ns_get_binary_name() const; - string ns_get_dtool_name() const; + std::string ns_get_binary_name() const; + std::string ns_get_dtool_name() const; static ExecutionEnvironment *get_ptr(); @@ -79,14 +79,14 @@ private: void read_args(); private: - typedef map EnvironmentVariables; + typedef std::map EnvironmentVariables; EnvironmentVariables _variables; typedef vector_string CommandArguments; CommandArguments _args; - string _binary_name; - string _dtool_name; + std::string _binary_name; + std::string _dtool_name; static ExecutionEnvironment *_global_ptr; }; diff --git a/dtool/src/dtoolutil/filename.I b/dtool/src/dtoolutil/filename.I index 9bc23dfca3..b23947320f 100644 --- a/dtool/src/dtoolutil/filename.I +++ b/dtool/src/dtoolutil/filename.I @@ -15,7 +15,7 @@ * */ INLINE Filename:: -Filename(const string &filename) { +Filename(const std::string &filename) { _flags = 0; (*this) = filename; } @@ -24,7 +24,7 @@ Filename(const string &filename) { * */ INLINE Filename:: -Filename(const wstring &filename) { +Filename(const std::wstring &filename) { _flags = 0; (*this) = filename; } @@ -54,24 +54,20 @@ Filename(const Filename ©) : { } -#ifdef USE_MOVE_SEMANTICS /** * */ INLINE Filename:: -Filename(string &&filename) NOEXCEPT { - _flags = 0; - (*this) = move(filename); +Filename(std::string &&filename) noexcept : _flags(0) { + (*this) = std::move(filename); } -#endif // USE_MOVE_SEMANTICS -#ifdef USE_MOVE_SEMANTICS /** * */ INLINE Filename:: -Filename(Filename &&from) NOEXCEPT : - _filename(move(from._filename)), +Filename(Filename &&from) noexcept : + _filename(std::move(from._filename)), _dirname_end(from._dirname_end), _basename_start(from._basename_start), _basename_end(from._basename_end), @@ -81,7 +77,6 @@ Filename(Filename &&from) NOEXCEPT : _flags(from._flags) { } -#endif // USE_MOVE_SEMANTICS /** * Creates an empty Filename. @@ -90,10 +85,10 @@ INLINE Filename:: Filename() : _dirname_end(0), _basename_start(0), - _basename_end(string::npos), - _extension_start(string::npos), - _hash_start(string::npos), - _hash_end(string::npos), + _basename_end(std::string::npos), + _extension_start(std::string::npos), + _hash_start(std::string::npos), + _hash_end(std::string::npos), _flags(0) { } @@ -111,7 +106,7 @@ text_filename(const Filename &filename) { * */ INLINE Filename Filename:: -text_filename(const string &filename) { +text_filename(const std::string &filename) { Filename result(filename); result.set_text(); return result; @@ -131,7 +126,7 @@ binary_filename(const Filename &filename) { * */ INLINE Filename Filename:: -binary_filename(const string &filename) { +binary_filename(const std::string &filename) { Filename result(filename); result.set_binary(); return result; @@ -141,7 +136,7 @@ binary_filename(const string &filename) { * */ INLINE Filename Filename:: -dso_filename(const string &filename) { +dso_filename(const std::string &filename) { Filename result(filename); result.set_type(T_dso); return result; @@ -151,7 +146,7 @@ dso_filename(const string &filename) { * */ INLINE Filename Filename:: -executable_filename(const string &filename) { +executable_filename(const std::string &filename) { Filename result(filename); result.set_type(T_executable); return result; @@ -162,7 +157,7 @@ executable_filename(const string &filename) { * set_pattern(). */ INLINE Filename Filename:: -pattern_filename(const string &filename) { +pattern_filename(const std::string &filename) { Filename result(filename); result.set_pattern(true); return result; @@ -172,7 +167,7 @@ pattern_filename(const string &filename) { * */ INLINE Filename &Filename:: -operator = (const string &filename) { +operator = (const std::string &filename) { _filename = filename; locate_basename(); @@ -185,7 +180,7 @@ operator = (const string &filename) { * */ INLINE Filename &Filename:: -operator = (const wstring &filename) { +operator = (const std::wstring &filename) { TextEncoder encoder; encoder.set_encoding(get_filesystem_encoding()); encoder.set_wtext(filename); @@ -197,8 +192,8 @@ operator = (const wstring &filename) { */ INLINE Filename &Filename:: operator = (const char *filename) { - assert(filename != NULL); - return (*this) = string(filename); + assert(filename != nullptr); + return (*this) = std::string(filename); } /** @@ -217,28 +212,25 @@ operator = (const Filename ©) { return *this; } -#ifdef USE_MOVE_SEMANTICS /** * */ INLINE Filename &Filename:: -operator = (string &&filename) NOEXCEPT { - _filename = move(filename); +operator = (std::string &&filename) noexcept { + _filename = std::move(filename); locate_basename(); locate_extension(); locate_hash(); return *this; } -#endif // USE_MOVE_SEMANTICS -#ifdef USE_MOVE_SEMANTICS /** * */ INLINE Filename &Filename:: -operator = (Filename &&from) NOEXCEPT { - _filename = move(from._filename); +operator = (Filename &&from) noexcept { + _filename = std::move(from._filename); _dirname_end = from._dirname_end; _basename_start = from._basename_start; _basename_end = from._basename_end; @@ -248,13 +240,12 @@ operator = (Filename &&from) NOEXCEPT { _flags = from._flags; return *this; } -#endif // USE_MOVE_SEMANTICS /** * */ INLINE Filename:: -operator const string & () const { +operator const std::string & () const { return _filename; } @@ -294,7 +285,7 @@ operator [] (size_t n) const { /** * */ -INLINE string Filename:: +INLINE std::string Filename:: substr(size_t begin) const { return _filename.substr(begin); } @@ -302,7 +293,7 @@ substr(size_t begin) const { /** * */ -INLINE string Filename:: +INLINE std::string Filename:: substr(size_t begin, size_t end) const { return _filename.substr(begin, end); } @@ -313,7 +304,7 @@ substr(size_t begin, size_t end) const { * two parameters. */ INLINE void Filename:: -operator += (const string &other) { +operator += (const std::string &other) { _filename += other; locate_basename(); locate_extension(); @@ -324,7 +315,7 @@ operator += (const string &other) { * Returns a new Filename representing the concatenation of the two filenames. */ INLINE Filename Filename:: -operator + (const string &other) const { +operator + (const std::string &other) const { Filename a(*this); a += other; return a; @@ -343,7 +334,7 @@ operator / (const Filename &other) const { * Returns the entire filename: directory, basename, extension. This is the * same thing returned by the string typecast operator. */ -INLINE string Filename:: +INLINE std::string Filename:: get_fullpath() const { return _filename; } @@ -351,7 +342,7 @@ get_fullpath() const { /** * Returns the entire filename as a wide-character string. */ -INLINE wstring Filename:: +INLINE std::wstring Filename:: get_fullpath_w() const { TextEncoder encoder; encoder.set_encoding(get_filesystem_encoding()); @@ -363,7 +354,7 @@ get_fullpath_w() const { * Returns the directory part of the filename. This is everything in the * filename up to, but not including the rightmost slash. */ -INLINE string Filename:: +INLINE std::string Filename:: get_dirname() const { return _filename.substr(0, _dirname_end); } @@ -372,7 +363,7 @@ get_dirname() const { * Returns the basename part of the filename. This is everything in the * filename after the rightmost slash, including any extensions. */ -INLINE string Filename:: +INLINE std::string Filename:: get_basename() const { return _filename.substr(_basename_start); } @@ -382,7 +373,7 @@ get_basename() const { * Returns the full filename--directory and basename parts--except for the * extension. */ -INLINE string Filename:: +INLINE std::string Filename:: get_fullpath_wo_extension() const { return _filename.substr(0, _basename_end); } @@ -391,9 +382,9 @@ get_fullpath_wo_extension() const { /** * Returns the basename part of the filename, without the file extension. */ -INLINE string Filename:: +INLINE std::string Filename:: get_basename_wo_extension() const { - if (_basename_end == string::npos) { + if (_basename_end == std::string::npos) { return _filename.substr(_basename_start); } else { return _filename.substr(_basename_start, _basename_end - _basename_start); @@ -405,10 +396,10 @@ get_basename_wo_extension() const { * Returns the file extension. This is everything after the rightmost dot, if * there is one, or the empty string if there is not. */ -INLINE string Filename:: +INLINE std::string Filename:: get_extension() const { - if (_extension_start == string::npos) { - return string(); + if (_extension_start == std::string::npos) { + return std::string(); } else { return _filename.substr(_extension_start); } @@ -545,7 +536,7 @@ has_hash() const { * Returns the part of the filename beginning at the hash sequence (if any), * and continuing to the end of the filename. */ -INLINE string Filename:: +INLINE std::string Filename:: get_hash_to_end() const { return _filename.substr(_hash_start); } @@ -578,24 +569,24 @@ is_fully_qualified() const { * */ INLINE bool Filename:: -operator == (const string &other) const { - return (*(string *)this) == other; +operator == (const std::string &other) const { + return (*(std::string *)this) == other; } /** * */ INLINE bool Filename:: -operator != (const string &other) const { - return (*(string *)this) != other; +operator != (const std::string &other) const { + return (*(std::string *)this) != other; } /** * */ INLINE bool Filename:: -operator < (const string &other) const { - return (*(string *)this) < other; +operator < (const std::string &other) const { + return (*(std::string *)this) < other; } /** @@ -625,7 +616,7 @@ __nonzero__() const { * */ INLINE void Filename:: -output(ostream &out) const { +output(std::ostream &out) const { out << _filename; } diff --git a/dtool/src/dtoolutil/filename.cxx b/dtool/src/dtoolutil/filename.cxx index d2c566b557..da5657dd9d 100644 --- a/dtool/src/dtoolutil/filename.cxx +++ b/dtool/src/dtoolutil/filename.cxx @@ -48,11 +48,16 @@ #include #endif -#if defined(__ANDROID__) && !defined(HAVE_LOCKF) +#if defined(__ANDROID__) && !defined(PHAVE_LOCKF) // Needed for flock. #include #endif +using std::cerr; +using std::ios; +using std::string; +using std::wstring; + TextEncoder::Encoding Filename::_filesystem_encoding = TextEncoder::E_utf8; TVOLATILE AtomicAdjust::Pointer Filename::_home_directory; @@ -145,12 +150,12 @@ back_to_front_slash(const string &str) { static const string & get_panda_root() { - static string *panda_root = NULL; + static string *panda_root = nullptr; - if (panda_root == NULL) { + if (panda_root == nullptr) { panda_root = new string; const char *envvar = getenv("PANDA_ROOT"); - if (envvar != (const char *)NULL) { + if (envvar != nullptr) { (*panda_root) = front_to_back_slash(envvar); } @@ -430,7 +435,7 @@ temporary(const string &dirname, const string &prefix, const string &suffix, if (fdirname.empty()) { // If we are not given a dirname, use the system tempnam() function to // create a system-defined temporary filename. - char *name = tempnam(NULL, prefix.c_str()); + char *name = tempnam(nullptr, prefix.c_str()); Filename result = Filename::from_os_specific(name); free(name); result.set_type(type); @@ -446,7 +451,7 @@ temporary(const string &dirname, const string &prefix, const string &suffix, // We take the time of day and multiply it by the process time. This will // give us a very large number, of which we take the bottom 24 bits and // generate a 6-character hex code. - int hash = (clock() * time(NULL)) & 0xffffff; + int hash = (clock() * time(nullptr)) & 0xffffff; char hex_code[10]; #ifdef _WIN32 sprintf_s(hex_code, 10, "%06x", hash); @@ -467,12 +472,12 @@ temporary(const string &dirname, const string &prefix, const string &suffix, */ const Filename &Filename:: get_home_directory() { - if (AtomicAdjust::get_ptr(_home_directory) == NULL) { + if (AtomicAdjust::get_ptr(_home_directory) == nullptr) { Filename home_directory; // In all environments, check $HOME first. char *home = getenv("HOME"); - if (home != (char *)NULL) { + if (home != nullptr) { Filename dirname = from_os_specific(home); if (dirname.is_directory()) { if (dirname.make_canonical()) { @@ -486,7 +491,7 @@ get_home_directory() { wchar_t buffer[MAX_PATH]; // On Windows, fall back to the "My Documents" folder. - if (SHGetSpecialFolderPathW(NULL, buffer, CSIDL_PERSONAL, true)) { + if (SHGetSpecialFolderPathW(nullptr, buffer, CSIDL_PERSONAL, true)) { Filename dirname = from_os_specific_w(buffer); if (dirname.is_directory()) { if (dirname.make_canonical()) { @@ -517,9 +522,9 @@ get_home_directory() { } Filename *newdir = new Filename(home_directory); - if (AtomicAdjust::compare_and_exchange_ptr(_home_directory, NULL, newdir) != NULL) { + if (AtomicAdjust::compare_and_exchange_ptr(_home_directory, nullptr, newdir) != nullptr) { // Didn't store it. Must have been stored by someone else. - assert(_home_directory != NULL); + assert(_home_directory != nullptr); delete newdir; } } @@ -532,7 +537,7 @@ get_home_directory() { */ const Filename &Filename:: get_temp_directory() { - if (AtomicAdjust::get_ptr(_temp_directory) == NULL) { + if (AtomicAdjust::get_ptr(_temp_directory) == nullptr) { Filename temp_directory; #ifdef WIN32 @@ -565,9 +570,9 @@ get_temp_directory() { } Filename *newdir = new Filename(temp_directory); - if (AtomicAdjust::compare_and_exchange_ptr(_temp_directory, NULL, newdir) != NULL) { + if (AtomicAdjust::compare_and_exchange_ptr(_temp_directory, nullptr, newdir) != nullptr) { // Didn't store it. Must have been stored by someone else. - assert(_temp_directory != NULL); + assert(_temp_directory != nullptr); delete newdir; } } @@ -582,13 +587,13 @@ get_temp_directory() { */ const Filename &Filename:: get_user_appdata_directory() { - if (AtomicAdjust::get_ptr(_user_appdata_directory) == NULL) { + if (AtomicAdjust::get_ptr(_user_appdata_directory) == nullptr) { Filename user_appdata_directory; #ifdef WIN32 wchar_t buffer[MAX_PATH]; - if (SHGetSpecialFolderPathW(NULL, buffer, CSIDL_LOCAL_APPDATA, true)) { + if (SHGetSpecialFolderPathW(nullptr, buffer, CSIDL_LOCAL_APPDATA, true)) { Filename dirname = from_os_specific_w(buffer); if (dirname.is_directory()) { if (dirname.make_canonical()) { @@ -622,9 +627,9 @@ get_user_appdata_directory() { } Filename *newdir = new Filename(user_appdata_directory); - if (AtomicAdjust::compare_and_exchange_ptr(_user_appdata_directory, NULL, newdir) != NULL) { + if (AtomicAdjust::compare_and_exchange_ptr(_user_appdata_directory, nullptr, newdir) != nullptr) { // Didn't store it. Must have been stored by someone else. - assert(_user_appdata_directory != NULL); + assert(_user_appdata_directory != nullptr); delete newdir; } } @@ -638,13 +643,13 @@ get_user_appdata_directory() { */ const Filename &Filename:: get_common_appdata_directory() { - if (AtomicAdjust::get_ptr(_common_appdata_directory) == NULL) { + if (AtomicAdjust::get_ptr(_common_appdata_directory) == nullptr) { Filename common_appdata_directory; #ifdef WIN32 wchar_t buffer[MAX_PATH]; - if (SHGetSpecialFolderPathW(NULL, buffer, CSIDL_COMMON_APPDATA, true)) { + if (SHGetSpecialFolderPathW(nullptr, buffer, CSIDL_COMMON_APPDATA, true)) { Filename dirname = from_os_specific_w(buffer); if (dirname.is_directory()) { if (dirname.make_canonical()) { @@ -672,9 +677,9 @@ get_common_appdata_directory() { } Filename *newdir = new Filename(common_appdata_directory); - if (AtomicAdjust::compare_and_exchange_ptr(_common_appdata_directory, NULL, newdir) != NULL) { + if (AtomicAdjust::compare_and_exchange_ptr(_common_appdata_directory, nullptr, newdir) != nullptr) { // Didn't store it. Must have been stored by someone else. - assert(_common_appdata_directory != NULL); + assert(_common_appdata_directory != nullptr); delete newdir; } } @@ -832,9 +837,9 @@ get_filename_index(int index) const { Filename file(*this); if (_hash_end != _hash_start) { - ostringstream strm; + std::ostringstream strm; strm << _filename.substr(0, _hash_start) - << setw((int)(_hash_end - _hash_start)) << setfill('0') << index + << std::setw((int)(_hash_end - _hash_start)) << std::setfill('0') << index << _filename.substr(_hash_end); file.set_fullpath(strm.str()); } @@ -1017,7 +1022,7 @@ make_canonical() { #ifndef WIN32 // Use realpath in order to resolve symlinks properly char newpath [PATH_MAX + 1]; - if (realpath(c_str(), newpath) != NULL) { + if (realpath(c_str(), newpath) != nullptr) { Filename newpath_fn(newpath); newpath_fn._flags = _flags; (*this) = newpath_fn; @@ -1542,7 +1547,7 @@ get_access_timestamp() const { /** * Returns the size of the file in bytes, or 0 if there is an error. */ -streamsize Filename:: +std::streamsize Filename:: get_file_size() const { #ifdef WIN32_VC wstring os_specific = get_filename_index(0).to_os_specific_w(); @@ -1764,7 +1769,7 @@ scan_directory(vector_string &contents) const { dirname = _filename; } DIR *root = opendir(dirname.c_str()); - if (root == (DIR *)NULL) { + if (root == nullptr) { if (errno != ENOTDIR) { perror(dirname.c_str()); } @@ -1773,7 +1778,7 @@ scan_directory(vector_string &contents) const { struct dirent *d; d = readdir(root); - while (d != (struct dirent *)NULL) { + while (d != nullptr) { thread_consider_yield(); if (d->d_name[0] != '.') { contents.push_back(d->d_name); @@ -1814,7 +1819,7 @@ scan_directory(vector_string &contents) const { glob_t globbuf; - int r = glob(dirname.c_str(), GLOB_ERR, NULL, &globbuf); + int r = glob(dirname.c_str(), GLOB_ERR, nullptr, &globbuf); if (r != 0) { // Some error processing the match string. If our version of glob.h @@ -1834,7 +1839,7 @@ scan_directory(vector_string &contents) const { size_t offset = dirname.size() - 1; - for (int i = 0; globbuf.gl_pathv[i] != NULL; i++) { + for (int i = 0; globbuf.gl_pathv[i] != nullptr; i++) { contents.push_back(globbuf.gl_pathv[i] + offset); } globfree(&globbuf); @@ -1855,7 +1860,7 @@ scan_directory(vector_string &contents) const { * or set_binary(). */ bool Filename:: -open_read(ifstream &stream) const { +open_read(std::ifstream &stream) const { assert(!get_pattern()); assert(is_binary_or_text()); @@ -1891,7 +1896,7 @@ open_read(ifstream &stream) const { * if it already exists. Otherwise, the file is kept at its original length. */ bool Filename:: -open_write(ofstream &stream, bool truncate) const { +open_write(std::ofstream &stream, bool truncate) const { assert(!get_pattern()); assert(is_binary_or_text()); @@ -1921,15 +1926,10 @@ open_write(ofstream &stream, bool truncate) const { stream.clear(); #ifdef WIN32_VC wstring os_specific = to_os_specific_w(); - stream.open(os_specific.c_str(), open_mode); #else string os_specific = to_os_specific(); -#ifdef HAVE_OPEN_MASK - stream.open(os_specific.c_str(), open_mode, 0666); -#else - stream.open(os_specific.c_str(), open_mode); -#endif #endif // WIN32_VC + stream.open(os_specific.c_str(), open_mode); return (!stream.fail()); } @@ -1942,7 +1942,7 @@ open_write(ofstream &stream, bool truncate) const { * or set_binary(). */ bool Filename:: -open_append(ofstream &stream) const { +open_append(std::ofstream &stream) const { assert(!get_pattern()); assert(is_binary_or_text()); @@ -1958,15 +1958,10 @@ open_append(ofstream &stream) const { stream.clear(); #ifdef WIN32_VC wstring os_specific = to_os_specific_w(); - stream.open(os_specific.c_str(), open_mode); #else string os_specific = to_os_specific(); -#ifdef HAVE_OPEN_MASK - stream.open(os_specific.c_str(), open_mode, 0666); -#else - stream.open(os_specific.c_str(), open_mode); -#endif #endif // WIN32_VC + stream.open(os_specific.c_str(), open_mode); return (!stream.fail()); } @@ -1979,7 +1974,7 @@ open_append(ofstream &stream) const { * one of set_text() or set_binary(). */ bool Filename:: -open_read_write(fstream &stream, bool truncate) const { +open_read_write(std::fstream &stream, bool truncate) const { assert(!get_pattern()); assert(is_binary_or_text()); @@ -2005,15 +2000,10 @@ open_read_write(fstream &stream, bool truncate) const { stream.clear(); #ifdef WIN32_VC wstring os_specific = to_os_specific_w(); - stream.open(os_specific.c_str(), open_mode); #else string os_specific = to_os_specific(); -#ifdef HAVE_OPEN_MASK - stream.open(os_specific.c_str(), open_mode, 0666); -#else - stream.open(os_specific.c_str(), open_mode); -#endif #endif // WIN32_VC + stream.open(os_specific.c_str(), open_mode); return (!stream.fail()); } @@ -2026,7 +2016,7 @@ open_read_write(fstream &stream, bool truncate) const { * open_read() without first calling one of set_text() or set_binary(). */ bool Filename:: -open_read_append(fstream &stream) const { +open_read_append(std::fstream &stream) const { assert(!get_pattern()); assert(is_binary_or_text()); @@ -2042,15 +2032,10 @@ open_read_append(fstream &stream) const { stream.clear(); #ifdef WIN32_VC wstring os_specific = to_os_specific_w(); - stream.open(os_specific.c_str(), open_mode); #else string os_specific = to_os_specific(); -#ifdef HAVE_OPEN_MASK - stream.open(os_specific.c_str(), open_mode, 0666); -#else - stream.open(os_specific.c_str(), open_mode); -#endif #endif // WIN32_VC + stream.open(os_specific.c_str(), open_mode); return (!stream.fail()); } @@ -2125,11 +2110,7 @@ open_write(pofstream &stream, bool truncate) const { stream.clear(); string os_specific = to_os_specific(); -#ifdef HAVE_OPEN_MASK - stream.open(os_specific.c_str(), open_mode, 0666); -#else stream.open(os_specific.c_str(), open_mode); -#endif return (!stream.fail()); } @@ -2159,11 +2140,7 @@ open_append(pofstream &stream) const { stream.clear(); string os_specific = to_os_specific(); -#ifdef HAVE_OPEN_MASK - stream.open(os_specific.c_str(), open_mode, 0666); -#else stream.open(os_specific.c_str(), open_mode); -#endif return (!stream.fail()); } @@ -2203,11 +2180,7 @@ open_read_write(pfstream &stream, bool truncate) const { stream.clear(); string os_specific = to_os_specific(); -#ifdef HAVE_OPEN_MASK - stream.open(os_specific.c_str(), open_mode, 0666); -#else stream.open(os_specific.c_str(), open_mode); -#endif return (!stream.fail()); } @@ -2237,11 +2210,7 @@ open_read_append(pfstream &stream) const { stream.clear(); string os_specific = to_os_specific(); -#ifdef HAVE_OPEN_MASK - stream.open(os_specific.c_str(), open_mode, 0666); -#else stream.open(os_specific.c_str(), open_mode); -#endif return (!stream.fail()); } @@ -2262,7 +2231,7 @@ touch() const { wstring os_specific = to_os_specific_w(); HANDLE fhandle; fhandle = CreateFileW(os_specific.c_str(), GENERIC_WRITE, FILE_SHARE_WRITE, - NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (fhandle == INVALID_HANDLE_VALUE) { return false; } @@ -2276,7 +2245,7 @@ touch() const { return false; } - if (!SetFileTime(fhandle, NULL, NULL, &ftnow)) { + if (!SetFileTime(fhandle, nullptr, nullptr, &ftnow)) { CloseHandle(fhandle); return false; } @@ -2300,7 +2269,7 @@ touch() const { os_specific = result; } #endif // HAVE_CYGWIN - int result = utime(os_specific.c_str(), NULL); + int result = utime(os_specific.c_str(), nullptr); if (result < 0) { if (errno == ENOENT) { // So the file doesn't already exist; create it. @@ -2676,16 +2645,16 @@ atomic_compare_and_exchange_contents(string &orig_contents, #ifdef WIN32_VC wstring os_specific = to_os_specific_w(); HANDLE hfile = CreateFileW(os_specific.c_str(), GENERIC_READ | GENERIC_WRITE, - 0, NULL, OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL, NULL); + 0, nullptr, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); while (hfile == INVALID_HANDLE_VALUE) { DWORD error = GetLastError(); if (error == ERROR_SHARING_VIOLATION) { // If the file is locked by another process, yield and try again. Sleep(0); hfile = CreateFileW(os_specific.c_str(), GENERIC_READ | GENERIC_WRITE, - 0, NULL, OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL, NULL); + 0, nullptr, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); } else { cerr << "Couldn't open file: " << os_specific << ", error " << error << "\n"; @@ -2705,7 +2674,7 @@ atomic_compare_and_exchange_contents(string &orig_contents, orig_contents = string(); DWORD bytes_read; - if (!ReadFile(hfile, buf, buf_size, &bytes_read, NULL)) { + if (!ReadFile(hfile, buf, buf_size, &bytes_read, nullptr)) { cerr << "Error reading file: " << os_specific << ", error " << GetLastError() << "\n"; CloseHandle(hfile); @@ -2714,7 +2683,7 @@ atomic_compare_and_exchange_contents(string &orig_contents, while (bytes_read > 0) { orig_contents += string(buf, bytes_read); - if (!ReadFile(hfile, buf, buf_size, &bytes_read, NULL)) { + if (!ReadFile(hfile, buf, buf_size, &bytes_read, nullptr)) { cerr << "Error reading file: " << os_specific << ", error " << GetLastError() << "\n"; CloseHandle(hfile); @@ -2728,7 +2697,7 @@ atomic_compare_and_exchange_contents(string &orig_contents, SetFilePointer(hfile, 0, 0, FILE_BEGIN); DWORD bytes_written; if (!WriteFile(hfile, new_contents.data(), new_contents.size(), - &bytes_written, NULL)) { + &bytes_written, nullptr)) { cerr << "Error writing file: " << os_specific << ", error " << GetLastError() << "\n"; CloseHandle(hfile); @@ -2752,7 +2721,7 @@ atomic_compare_and_exchange_contents(string &orig_contents, orig_contents = string(); -#ifdef HAVE_LOCKF +#ifdef PHAVE_LOCKF if (lockf(fd, F_LOCK, 0) != 0) { #else if (flock(fd, LOCK_EX) != 0) { @@ -2812,16 +2781,16 @@ atomic_read_contents(string &contents) const { #ifdef WIN32_VC wstring os_specific = to_os_specific_w(); HANDLE hfile = CreateFileW(os_specific.c_str(), GENERIC_READ, - FILE_SHARE_READ, NULL, OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL, NULL); + FILE_SHARE_READ, nullptr, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); while (hfile == INVALID_HANDLE_VALUE) { DWORD error = GetLastError(); if (error == ERROR_SHARING_VIOLATION) { // If the file is locked by another process, yield and try again. Sleep(0); hfile = CreateFileW(os_specific.c_str(), GENERIC_READ, - FILE_SHARE_READ, NULL, OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL, NULL); + FILE_SHARE_READ, nullptr, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); } else { cerr << "Couldn't open file: " << os_specific << ", error " << error << "\n"; @@ -2835,7 +2804,7 @@ atomic_read_contents(string &contents) const { contents = string(); DWORD bytes_read; - if (!ReadFile(hfile, buf, buf_size, &bytes_read, NULL)) { + if (!ReadFile(hfile, buf, buf_size, &bytes_read, nullptr)) { cerr << "Error reading file: " << os_specific << ", error " << GetLastError() << "\n"; CloseHandle(hfile); @@ -2844,7 +2813,7 @@ atomic_read_contents(string &contents) const { while (bytes_read > 0) { contents += string(buf, bytes_read); - if (!ReadFile(hfile, buf, buf_size, &bytes_read, NULL)) { + if (!ReadFile(hfile, buf, buf_size, &bytes_read, nullptr)) { cerr << "Error reading file: " << os_specific << ", error " << GetLastError() << "\n"; CloseHandle(hfile); @@ -2868,7 +2837,7 @@ atomic_read_contents(string &contents) const { contents = string(); -#ifdef HAVE_LOCKF +#ifdef PHAVE_LOCKF if (lockf(fd, F_LOCK, 0) != 0) { #else if (flock(fd, LOCK_EX) != 0) { diff --git a/dtool/src/dtoolutil/filename.h b/dtool/src/dtoolutil/filename.h index 76ee5e0b39..66b38356a6 100644 --- a/dtool/src/dtoolutil/filename.h +++ b/dtool/src/dtoolutil/filename.h @@ -55,14 +55,11 @@ public: }; INLINE Filename(const char *filename); - INLINE Filename(const string &filename); - INLINE Filename(const wstring &filename); + INLINE Filename(const std::string &filename); + INLINE Filename(const std::wstring &filename); INLINE Filename(const Filename ©); - -#ifdef USE_MOVE_SEMANTICS - INLINE Filename(string &&filename) NOEXCEPT; - INLINE Filename(Filename &&from) NOEXCEPT; -#endif + INLINE Filename(std::string &&filename) noexcept; + INLINE Filename(Filename &&from) noexcept; PUBLISHED: INLINE Filename(); @@ -78,22 +75,22 @@ PUBLISHED: // or binary file. This is in lieu of calling set_text() or set_binary() or // set_type(). INLINE static Filename text_filename(const Filename &filename); - INLINE static Filename text_filename(const string &filename); + INLINE static Filename text_filename(const std::string &filename); INLINE static Filename binary_filename(const Filename &filename); - INLINE static Filename binary_filename(const string &filename); - INLINE static Filename dso_filename(const string &filename); - INLINE static Filename executable_filename(const string &filename); + INLINE static Filename binary_filename(const std::string &filename); + INLINE static Filename dso_filename(const std::string &filename); + INLINE static Filename executable_filename(const std::string &filename); - INLINE static Filename pattern_filename(const string &filename); + INLINE static Filename pattern_filename(const std::string &filename); - static Filename from_os_specific(const string &os_specific, + static Filename from_os_specific(const std::string &os_specific, Type type = T_general); - static Filename from_os_specific_w(const wstring &os_specific, + static Filename from_os_specific_w(const std::wstring &os_specific, Type type = T_general); - static Filename expand_from(const string &user_string, + static Filename expand_from(const std::string &user_string, Type type = T_general); - static Filename temporary(const string &dirname, const string &prefix, - const string &suffix = string(), + static Filename temporary(const std::string &dirname, const std::string &prefix, + const std::string &suffix = std::string(), Type type = T_general); static const Filename &get_home_directory(); @@ -102,18 +99,15 @@ PUBLISHED: static const Filename &get_common_appdata_directory(); // Assignment is via the = operator. - INLINE Filename &operator = (const string &filename); - INLINE Filename &operator = (const wstring &filename); + INLINE Filename &operator = (const std::string &filename); + INLINE Filename &operator = (const std::wstring &filename); INLINE Filename &operator = (const char *filename); INLINE Filename &operator = (const Filename ©); - -#ifdef USE_MOVE_SEMANTICS - INLINE Filename &operator = (string &&filename) NOEXCEPT; - INLINE Filename &operator = (Filename &&from) NOEXCEPT; -#endif + INLINE Filename &operator = (std::string &&filename) noexcept; + INLINE Filename &operator = (Filename &&from) noexcept; // And retrieval is by any of the classic string operations. - INLINE operator const string & () const; + INLINE operator const std::string & () const; INLINE const char *c_str() const; INLINE bool empty() const; INLINE size_t length() const; @@ -122,29 +116,29 @@ PUBLISHED: EXTENSION(PyObject *__repr__() const); EXTENSION(PyObject *__fspath__() const); - INLINE string substr(size_t begin) const; - INLINE string substr(size_t begin, size_t end) const; - INLINE void operator += (const string &other); - INLINE Filename operator + (const string &other) const; + INLINE std::string substr(size_t begin) const; + INLINE std::string substr(size_t begin, size_t end) const; + INLINE void operator += (const std::string &other); + INLINE Filename operator + (const std::string &other) const; INLINE Filename operator / (const Filename &other) const; // Or, you can use any of these. - INLINE string get_fullpath() const; - INLINE wstring get_fullpath_w() const; - INLINE string get_dirname() const; - INLINE string get_basename() const; - INLINE string get_fullpath_wo_extension() const; - INLINE string get_basename_wo_extension() const; - INLINE string get_extension() const; + INLINE std::string get_fullpath() const; + INLINE std::wstring get_fullpath_w() const; + INLINE std::string get_dirname() const; + INLINE std::string get_basename() const; + INLINE std::string get_fullpath_wo_extension() const; + INLINE std::string get_basename_wo_extension() const; + INLINE std::string get_extension() const; // You can also use any of these to reassign pieces of the filename. - void set_fullpath(const string &s); - void set_dirname(const string &s); - void set_basename(const string &s); - void set_fullpath_wo_extension(const string &s); - void set_basename_wo_extension(const string &s); - void set_extension(const string &s); + void set_fullpath(const std::string &s); + void set_dirname(const std::string &s); + void set_basename(const std::string &s); + void set_fullpath_wo_extension(const std::string &s); + void set_basename_wo_extension(const std::string &s); + void set_extension(const std::string &s); // Setting these flags appropriately is helpful when opening or searching // for a file; it helps the Filename resolve OS-specific conventions (for @@ -165,8 +159,8 @@ PUBLISHED: INLINE bool has_hash() const; Filename get_filename_index(int index) const; - INLINE string get_hash_to_end() const; - void set_hash_to_end(const string &s); + INLINE std::string get_hash_to_end() const; + void set_hash_to_end(const std::string &s); void extract_components(vector_string &components) const; void standardize(); @@ -181,11 +175,11 @@ PUBLISHED: bool make_canonical(); bool make_true_case(); - string to_os_specific() const; - wstring to_os_specific_w() const; - string to_os_generic() const; - string to_os_short_name() const; - string to_os_long_name() const; + std::string to_os_specific() const; + std::wstring to_os_specific_w() const; + std::string to_os_generic() const; + std::string to_os_short_name() const; + std::string to_os_long_name() const; bool exists() const; bool is_regular_file() const; @@ -197,10 +191,10 @@ PUBLISHED: bool other_missing_is_old = true) const; time_t get_timestamp() const; time_t get_access_timestamp() const; - streamsize get_file_size() const; + std::streamsize get_file_size() const; bool resolve_filename(const DSearchPath &searchpath, - const string &default_extension = string()); + const std::string &default_extension = std::string()); bool make_relative_to(Filename directory, bool allow_backups = true); int find_on_searchpath(const DSearchPath &searchpath); @@ -209,11 +203,11 @@ PUBLISHED: EXTENSION(PyObject *scan_directory() const); #endif - bool open_read(ifstream &stream) const; - bool open_write(ofstream &stream, bool truncate = true) const; - bool open_append(ofstream &stream) const; - bool open_read_write(fstream &stream, bool truncate = false) const; - bool open_read_append(fstream &stream) const; + bool open_read(std::ifstream &stream) const; + bool open_write(std::ofstream &stream, bool truncate = true) const; + bool open_append(std::ofstream &stream) const; + bool open_read_write(std::fstream &stream, bool truncate = false) const; + bool open_read_append(std::fstream &stream) const; #ifdef USE_PANDAFILESTREAM bool open_read(pifstream &stream) const; @@ -234,31 +228,31 @@ PUBLISHED: bool rmdir() const; // Comparison operators are handy. - INLINE bool operator == (const string &other) const; - INLINE bool operator != (const string &other) const; - INLINE bool operator < (const string &other) const; + INLINE bool operator == (const std::string &other) const; + INLINE bool operator != (const std::string &other) const; + INLINE bool operator < (const std::string &other) const; INLINE int compare_to(const Filename &other) const; INLINE bool __nonzero__() const; int get_hash() const; - INLINE void output(ostream &out) const; + INLINE void output(std::ostream &out) const; INLINE static void set_filesystem_encoding(TextEncoder::Encoding encoding); INLINE static TextEncoder::Encoding get_filesystem_encoding(); public: - bool atomic_compare_and_exchange_contents(string &orig_contents, const string &old_contents, const string &new_contents) const; - bool atomic_read_contents(string &contents) const; + bool atomic_compare_and_exchange_contents(std::string &orig_contents, const std::string &old_contents, const std::string &new_contents) const; + bool atomic_read_contents(std::string &contents) const; protected: void locate_basename(); void locate_extension(); void locate_hash(); - size_t get_common_prefix(const string &other) const; - static int count_slashes(const string &str); + size_t get_common_prefix(const std::string &other) const; + static int count_slashes(const std::string &str); bool r_make_canonical(const Filename &cwd); - string _filename; + std::string _filename; // We'll make these size_t instead of string::size_type to help out // cppParser. size_t _dirname_end; @@ -278,7 +272,7 @@ protected: #ifdef ANDROID public: - static string _internal_data_dir; + static std::string _internal_data_dir; #endif public: @@ -293,7 +287,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const Filename &n) { +INLINE std::ostream &operator << (std::ostream &out, const Filename &n) { n.output(out); return out; } diff --git a/dtool/src/dtoolutil/filename_assist.h b/dtool/src/dtoolutil/filename_assist.h index ff1c91402c..ad4f08ef1d 100644 --- a/dtool/src/dtoolutil/filename_assist.h +++ b/dtool/src/dtoolutil/filename_assist.h @@ -20,10 +20,10 @@ #ifdef IS_OSX -string get_osx_home_directory(); -string get_osx_temp_directory(); -string get_osx_user_appdata_directory(); -string get_osx_common_appdata_directory(); +std::string get_osx_home_directory(); +std::string get_osx_temp_directory(); +std::string get_osx_user_appdata_directory(); +std::string get_osx_common_appdata_directory(); #endif // IS_OSX diff --git a/dtool/src/dtoolutil/filename_assist.mm b/dtool/src/dtoolutil/filename_assist.mm index e27c4d1ece..3192fc58e2 100644 --- a/dtool/src/dtoolutil/filename_assist.mm +++ b/dtool/src/dtoolutil/filename_assist.mm @@ -22,6 +22,8 @@ #include #endif +using std::string; + /** * Copy the Objective-C string to a C++ string. */ diff --git a/dtool/src/dtoolutil/filename_ext.cxx b/dtool/src/dtoolutil/filename_ext.cxx index 3d71317786..e60bf83a90 100644 --- a/dtool/src/dtoolutil/filename_ext.cxx +++ b/dtool/src/dtoolutil/filename_ext.cxx @@ -13,6 +13,9 @@ #include "filename_ext.h" +using std::string; +using std::wstring; + #ifdef HAVE_PYTHON #ifndef CPPPARSER @@ -24,8 +27,8 @@ extern Dtool_PyTypedObject Dtool_Filename; */ void Extension:: __init__(PyObject *path) { - nassertv(path != NULL); - nassertv(_this != NULL); + nassertv(path != nullptr); + nassertv(_this != nullptr); Py_ssize_t length; @@ -64,12 +67,12 @@ __init__(PyObject *path) { #if PY_VERSION_HEX >= 0x03060000 // It must be an os.PathLike object. Check for an __fspath__ method. PyObject *fspath = PyObject_GetAttrString((PyObject *)Py_TYPE(path), "__fspath__"); - if (fspath == NULL) { + if (fspath == nullptr) { PyErr_Format(PyExc_TypeError, "expected str, bytes or os.PathLike object, not %s", Py_TYPE(path)->tp_name); return; } - path_str = PyObject_CallFunctionObjArgs(fspath, path, NULL); + path_str = PyObject_CallFunctionObjArgs(fspath, path, nullptr); Py_DECREF(fspath); #else // There is no standard path protocol before Python 3.6, but let's try and @@ -89,7 +92,7 @@ __init__(PyObject *path) { } #endif - if (path_str == NULL) { + if (path_str == nullptr) { return; } @@ -133,8 +136,8 @@ __reduce__(PyObject *self) const { // object whose constructor we should call (e.g. this), and the arguments // necessary to reconstruct this object. PyTypeObject *this_class = Py_TYPE(self); - if (this_class == NULL) { - return NULL; + if (this_class == nullptr) { + return nullptr; } PyObject *result = Py_BuildValue("(O(s))", this_class, _this->c_str()); diff --git a/dtool/src/dtoolutil/globPattern.I b/dtool/src/dtoolutil/globPattern.I index c5d48d4d28..f0ab3a6c0e 100644 --- a/dtool/src/dtoolutil/globPattern.I +++ b/dtool/src/dtoolutil/globPattern.I @@ -15,7 +15,7 @@ * */ INLINE GlobPattern:: -GlobPattern(const string &pattern) : _pattern(pattern) { +GlobPattern(const std::string &pattern) : _pattern(pattern) { _case_sensitive = true; } @@ -69,14 +69,14 @@ operator < (const GlobPattern &other) const { * Changes the pattern string that the GlobPattern object matches. */ INLINE void GlobPattern:: -set_pattern(const string &pattern) { +set_pattern(const std::string &pattern) { _pattern = pattern; } /** * Returns the pattern string that the GlobPattern object matches. */ -INLINE const string &GlobPattern:: +INLINE const std::string &GlobPattern:: get_pattern() const { return _pattern; } @@ -103,14 +103,14 @@ get_case_sensitive() const { * Specifies a set of characters that are not matched by * or ?. */ INLINE void GlobPattern:: -set_nomatch_chars(const string &nomatch_chars) { +set_nomatch_chars(const std::string &nomatch_chars) { _nomatch_chars = nomatch_chars; } /** * Returns the set of characters that are not matched by * or ?. */ -INLINE const string &GlobPattern:: +INLINE const std::string &GlobPattern:: get_nomatch_chars() const { return _nomatch_chars; } @@ -119,7 +119,7 @@ get_nomatch_chars() const { * Returns true if the candidate string matches the pattern, false otherwise. */ INLINE bool GlobPattern:: -matches(const string &candidate) const { +matches(const std::string &candidate) const { return matches_substr(_pattern.begin(), _pattern.end(), candidate.begin(), candidate.end()); } @@ -128,6 +128,6 @@ matches(const string &candidate) const { * */ INLINE void GlobPattern:: -output(ostream &out) const { +output(std::ostream &out) const { out << _pattern; } diff --git a/dtool/src/dtoolutil/globPattern.cxx b/dtool/src/dtoolutil/globPattern.cxx index 57a6afdb57..982fe3bb1d 100644 --- a/dtool/src/dtoolutil/globPattern.cxx +++ b/dtool/src/dtoolutil/globPattern.cxx @@ -14,6 +14,8 @@ #include "globPattern.h" #include +using std::string; + /** * Returns true if the pattern includes any special globbing characters, or * false if it is just a literal string. diff --git a/dtool/src/dtoolutil/globPattern.h b/dtool/src/dtoolutil/globPattern.h index 015bde38f9..27dfb67777 100644 --- a/dtool/src/dtoolutil/globPattern.h +++ b/dtool/src/dtoolutil/globPattern.h @@ -31,7 +31,7 @@ */ class EXPCL_DTOOL_DTOOLUTIL GlobPattern { PUBLISHED: - INLINE GlobPattern(const string &pattern = string()); + INLINE GlobPattern(const std::string &pattern = std::string()); INLINE GlobPattern(const GlobPattern ©); INLINE void operator = (const GlobPattern ©); @@ -39,48 +39,48 @@ PUBLISHED: INLINE bool operator != (const GlobPattern &other) const; INLINE bool operator < (const GlobPattern &other) const; - INLINE void set_pattern(const string &pattern); - INLINE const string &get_pattern() const; + INLINE void set_pattern(const std::string &pattern); + INLINE const std::string &get_pattern() const; MAKE_PROPERTY(pattern, get_pattern, set_pattern); INLINE void set_case_sensitive(bool case_sensitive); INLINE bool get_case_sensitive() const; MAKE_PROPERTY(case_sensitive, get_case_sensitive, set_case_sensitive); - INLINE void set_nomatch_chars(const string &nomatch_chars); - INLINE const string &get_nomatch_chars() const; + INLINE void set_nomatch_chars(const std::string &nomatch_chars); + INLINE const std::string &get_nomatch_chars() const; MAKE_PROPERTY(nomatch_chars, get_nomatch_chars, set_nomatch_chars); - INLINE bool matches(const string &candidate) const; + INLINE bool matches(const std::string &candidate) const; - INLINE void output(ostream &out) const; + INLINE void output(std::ostream &out) const; bool has_glob_characters() const; - string get_const_prefix() const; + std::string get_const_prefix() const; int match_files(vector_string &results, const Filename &cwd = Filename()) const; #ifdef HAVE_PYTHON EXTENSION(PyObject *match_files(const Filename &cwd = Filename()) const); #endif private: - bool matches_substr(string::const_iterator pi, - string::const_iterator pend, - string::const_iterator ci, - string::const_iterator cend) const; + bool matches_substr(std::string::const_iterator pi, + std::string::const_iterator pend, + std::string::const_iterator ci, + std::string::const_iterator cend) const; - bool matches_set(string::const_iterator &pi, - string::const_iterator pend, + bool matches_set(std::string::const_iterator &pi, + std::string::const_iterator pend, char ch) const; - int r_match_files(const Filename &prefix, const string &suffix, + int r_match_files(const Filename &prefix, const std::string &suffix, vector_string &results, const Filename &cwd); - string _pattern; + std::string _pattern; bool _case_sensitive; - string _nomatch_chars; + std::string _nomatch_chars; }; -INLINE ostream &operator << (ostream &out, const GlobPattern &glob) { +INLINE std::ostream &operator << (std::ostream &out, const GlobPattern &glob) { glob.output(out); return out; } diff --git a/dtool/src/dtoolutil/lineStream.I b/dtool/src/dtoolutil/lineStream.I index 67cab26cbe..8fcc880426 100644 --- a/dtool/src/dtoolutil/lineStream.I +++ b/dtool/src/dtoolutil/lineStream.I @@ -15,7 +15,7 @@ * */ INLINE LineStream:: -LineStream() : ostream(&_lsb) { +LineStream() : std::ostream(&_lsb) { } /** @@ -34,7 +34,7 @@ is_text_available() const { * has_newline() to determine whether or not there was an explicit newline * character written following this line. */ -INLINE string LineStream:: +INLINE std::string LineStream:: get_line() { return _lsb.get_line(); } diff --git a/dtool/src/dtoolutil/lineStream.h b/dtool/src/dtoolutil/lineStream.h index 7f9f5eff4a..845e6496ea 100644 --- a/dtool/src/dtoolutil/lineStream.h +++ b/dtool/src/dtoolutil/lineStream.h @@ -28,7 +28,7 @@ * otherwise affected when a line of text is extracted. More text can still * be written to it and continuously extracted. */ -class EXPCL_DTOOL_DTOOLUTIL LineStream : public ostream { +class EXPCL_DTOOL_DTOOLUTIL LineStream : public std::ostream { PUBLISHED: INLINE LineStream(); @@ -37,7 +37,7 @@ PUBLISHED: #endif INLINE bool is_text_available() const; - INLINE string get_line(); + INLINE std::string get_line(); INLINE bool has_newline() const; private: diff --git a/dtool/src/dtoolutil/lineStreamBuf.I b/dtool/src/dtoolutil/lineStreamBuf.I index 339248d2dd..2623afe787 100644 --- a/dtool/src/dtoolutil/lineStreamBuf.I +++ b/dtool/src/dtoolutil/lineStreamBuf.I @@ -34,6 +34,6 @@ has_newline() const { INLINE void LineStreamBuf:: write_chars(const char *start, size_t length) { if (length > 0) { - _data += string(start, length); + _data += std::string(start, length); } } diff --git a/dtool/src/dtoolutil/lineStreamBuf.cxx b/dtool/src/dtoolutil/lineStreamBuf.cxx index f2a795dab5..8ac3ed74f2 100644 --- a/dtool/src/dtoolutil/lineStreamBuf.cxx +++ b/dtool/src/dtoolutil/lineStreamBuf.cxx @@ -13,10 +13,7 @@ #include "lineStreamBuf.h" -#ifndef HAVE_STREAMSIZE -// Some compilers--notably SGI--don't define this for us. -typedef int streamsize; -#endif +using std::string; /** * @@ -29,8 +26,8 @@ LineStreamBuf() { // characters one at a time, since they're just getting stuffed into a // string. (Although the code is written portably enough to use a buffer // correctly, if we had one.) - setg(0, 0, 0); - setp(0, 0); + setg(nullptr, nullptr, nullptr); + setp(nullptr, nullptr); } /** @@ -70,7 +67,7 @@ get_line() { */ int LineStreamBuf:: sync() { - streamsize n = pptr() - pbase(); + std::streamsize n = pptr() - pbase(); write_chars(pbase(), n); pbump(-(int)n); // Reset pptr(). return 0; // EOF to indicate write full. @@ -82,7 +79,7 @@ sync() { */ int LineStreamBuf:: overflow(int ch) { - streamsize n = pptr() - pbase(); + std::streamsize n = pptr() - pbase(); if (n != 0 && sync() != 0) { return EOF; diff --git a/dtool/src/dtoolutil/lineStreamBuf.h b/dtool/src/dtoolutil/lineStreamBuf.h index 7718371a03..967d3f1636 100644 --- a/dtool/src/dtoolutil/lineStreamBuf.h +++ b/dtool/src/dtoolutil/lineStreamBuf.h @@ -23,13 +23,13 @@ * whose contents can be continuously extracted as a sequence of lines of * text. */ -class EXPCL_DTOOL_DTOOLUTIL LineStreamBuf : public streambuf { +class EXPCL_DTOOL_DTOOLUTIL LineStreamBuf : public std::streambuf { public: LineStreamBuf(); virtual ~LineStreamBuf(); INLINE bool is_text_available() const; - string get_line(); + std::string get_line(); INLINE bool has_newline() const; protected: @@ -39,7 +39,7 @@ protected: private: INLINE void write_chars(const char *start, size_t length); - string _data; + std::string _data; bool _has_newline; }; diff --git a/dtool/src/dtoolutil/load_dso.cxx b/dtool/src/dtoolutil/load_dso.cxx index ba63eee044..79d821b5fa 100644 --- a/dtool/src/dtoolutil/load_dso.cxx +++ b/dtool/src/dtoolutil/load_dso.cxx @@ -14,6 +14,8 @@ #include "load_dso.h" #include "executionEnvironment.h" +using std::string; + static Filename resolve_dso(const DSearchPath &path, const Filename &filename) { if (filename.is_local()) { if ((path.get_num_directories()==1)&&(path.get_directory(0)=="")) { @@ -45,9 +47,9 @@ void * load_dso(const DSearchPath &path, const Filename &filename) { Filename abspath = resolve_dso(path, filename); if (!abspath.is_regular_file()) { - return NULL; + return nullptr; } - wstring os_specific_w = abspath.to_os_specific_w(); + std::wstring os_specific_w = abspath.to_os_specific_w(); // Try using LoadLibraryEx, if possible. typedef HMODULE (WINAPI *tLoadLibraryEx)(LPCWSTR, HANDLE, DWORD); @@ -56,7 +58,7 @@ load_dso(const DSearchPath &path, const Filename &filename) { if (hLib) { pLoadLibraryEx = (tLoadLibraryEx)GetProcAddress(hLib, "LoadLibraryExW"); if (pLoadLibraryEx) { - return pLoadLibraryEx(os_specific_w.c_str(), NULL, LOAD_WITH_ALTERED_SEARCH_PATH); + return pLoadLibraryEx(os_specific_w.c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH); } } @@ -104,7 +106,7 @@ load_dso_error() { } // Some unknown error code. - ostringstream errmsg; + std::ostringstream errmsg; errmsg << "Unknown error " << last_error; return errmsg.str(); } @@ -130,7 +132,7 @@ void * load_dso(const DSearchPath &path, const Filename &filename) { Filename abspath = resolve_dso(path, filename); if (!abspath.is_regular_file()) { - return NULL; + return nullptr; } string os_specific = abspath.to_os_specific(); return dlopen(os_specific.c_str(), RTLD_NOW | RTLD_GLOBAL); @@ -144,7 +146,7 @@ unload_dso(void *dso_handle) { string load_dso_error() { const char *message = dlerror(); - if (message != (const char *)NULL) { + if (message != nullptr) { return std::string(message); } return "No error."; diff --git a/dtool/src/dtoolutil/load_dso.h b/dtool/src/dtoolutil/load_dso.h index 2c0a5d9d24..40d00e579a 100644 --- a/dtool/src/dtoolutil/load_dso.h +++ b/dtool/src/dtoolutil/load_dso.h @@ -31,11 +31,11 @@ unload_dso(void *dso_handle); // Returns the error message from the last failed load_dso() call. -EXPCL_DTOOL_DTOOLUTIL string +EXPCL_DTOOL_DTOOLUTIL std::string load_dso_error(); // Returns a function pointer or other symbol from a loaded library. EXPCL_DTOOL_DTOOLUTIL void * -get_dso_symbol(void *handle, const string &name); +get_dso_symbol(void *handle, const std::string &name); #endif diff --git a/dtool/src/dtoolutil/pandaFileStream.I b/dtool/src/dtoolutil/pandaFileStream.I index a30a5fdcc0..7ee64e9b4e 100644 --- a/dtool/src/dtoolutil/pandaFileStream.I +++ b/dtool/src/dtoolutil/pandaFileStream.I @@ -15,14 +15,14 @@ * */ INLINE IFileStream:: -IFileStream() : istream(&_buf) { +IFileStream() : std::istream(&_buf) { } /** * */ INLINE IFileStream:: -IFileStream(const char *filename, ios::openmode mode) : istream(&_buf) { +IFileStream(const char *filename, std::ios::openmode mode) : std::istream(&_buf) { open(filename, mode); } @@ -38,11 +38,11 @@ INLINE IFileStream:: * */ INLINE void IFileStream:: -open(const char *filename, ios::openmode mode) { +open(const char *filename, std::ios::openmode mode) { clear((ios_iostate)0); _buf.open(filename, mode); if (!_buf.is_open()) { - clear(ios::failbit); + clear(std::ios::failbit); } } @@ -55,11 +55,11 @@ open(const char *filename, ios::openmode mode) { * This function is the Windows-specific variant. */ void IFileStream:: -attach(const char *filename, HANDLE handle, ios::openmode mode) { +attach(const char *filename, HANDLE handle, std::ios::openmode mode) { clear((ios_iostate)0); _buf.attach(filename, handle, mode); if (!_buf.is_open()) { - clear(ios::failbit); + clear(std::ios::failbit); } } #endif // _WIN32 @@ -73,11 +73,11 @@ attach(const char *filename, HANDLE handle, ios::openmode mode) { * This function is the Posix-specific variant. */ void IFileStream:: -attach(const char *filename, int fd, ios::openmode mode) { +attach(const char *filename, int fd, std::ios::openmode mode) { clear((ios_iostate)0); _buf.attach(filename, fd, mode); if (!_buf.is_open()) { - clear(ios::failbit); + clear(std::ios::failbit); } } #endif // _WIN32 @@ -94,14 +94,14 @@ close() { * */ INLINE OFileStream:: -OFileStream() : ostream(&_buf) { +OFileStream() : std::ostream(&_buf) { } /** * */ INLINE OFileStream:: -OFileStream(const char *filename, ios::openmode mode) : ostream(&_buf) { +OFileStream(const char *filename, std::ios::openmode mode) : std::ostream(&_buf) { open(filename, mode); } @@ -117,11 +117,11 @@ INLINE OFileStream:: * */ INLINE void OFileStream:: -open(const char *filename, ios::openmode mode) { +open(const char *filename, std::ios::openmode mode) { clear((ios_iostate)0); _buf.open(filename, mode); if (!_buf.is_open()) { - clear(ios::failbit); + clear(std::ios::failbit); } } @@ -134,11 +134,11 @@ open(const char *filename, ios::openmode mode) { * This function is the Windows-specific variant. */ void OFileStream:: -attach(const char *filename, HANDLE handle, ios::openmode mode) { +attach(const char *filename, HANDLE handle, std::ios::openmode mode) { clear((ios_iostate)0); _buf.attach(filename, handle, mode); if (!_buf.is_open()) { - clear(ios::failbit); + clear(std::ios::failbit); } } #endif // _WIN32 @@ -152,11 +152,11 @@ attach(const char *filename, HANDLE handle, ios::openmode mode) { * This function is the Posix-specific variant. */ void OFileStream:: -attach(const char *filename, int fd, ios::openmode mode) { +attach(const char *filename, int fd, std::ios::openmode mode) { clear((ios_iostate)0); _buf.attach(filename, fd, mode); if (!_buf.is_open()) { - clear(ios::failbit); + clear(std::ios::failbit); } } #endif // _WIN32 @@ -173,14 +173,14 @@ close() { * */ INLINE FileStream:: -FileStream() : iostream(&_buf) { +FileStream() : std::iostream(&_buf) { } /** * */ INLINE FileStream:: -FileStream(const char *filename, ios::openmode mode) : iostream(&_buf) { +FileStream(const char *filename, std::ios::openmode mode) : std::iostream(&_buf) { open(filename, mode); } @@ -196,11 +196,11 @@ INLINE FileStream:: * */ INLINE void FileStream:: -open(const char *filename, ios::openmode mode) { +open(const char *filename, std::ios::openmode mode) { clear((ios_iostate)0); _buf.open(filename, mode); if (!_buf.is_open()) { - clear(ios::failbit); + clear(std::ios::failbit); } } @@ -213,11 +213,11 @@ open(const char *filename, ios::openmode mode) { * This function is the Windows-specific variant. */ void FileStream:: -attach(const char *filename, HANDLE handle, ios::openmode mode) { +attach(const char *filename, HANDLE handle, std::ios::openmode mode) { clear((ios_iostate)0); _buf.attach(filename, handle, mode); if (!_buf.is_open()) { - clear(ios::failbit); + clear(std::ios::failbit); } } #endif // _WIN32 @@ -231,11 +231,11 @@ attach(const char *filename, HANDLE handle, ios::openmode mode) { * This function is the Posix-specific variant. */ void FileStream:: -attach(const char *filename, int fd, ios::openmode mode) { +attach(const char *filename, int fd, std::ios::openmode mode) { clear((ios_iostate)0); _buf.attach(filename, fd, mode); if (!_buf.is_open()) { - clear(ios::failbit); + clear(std::ios::failbit); } } #endif // _WIN32 diff --git a/dtool/src/dtoolutil/pandaFileStream.h b/dtool/src/dtoolutil/pandaFileStream.h index 462e3ce160..4d565f8ac2 100644 --- a/dtool/src/dtoolutil/pandaFileStream.h +++ b/dtool/src/dtoolutil/pandaFileStream.h @@ -26,19 +26,19 @@ * simple-threading implementation (using this interface will block only the * current thread, rather than the entire process, on I/O waits). */ -class EXPCL_DTOOL_DTOOLUTIL IFileStream : public istream { +class EXPCL_DTOOL_DTOOLUTIL IFileStream : public std::istream { PUBLISHED: INLINE IFileStream(); - INLINE explicit IFileStream(const char *filename, ios::openmode mode = ios::in); + INLINE explicit IFileStream(const char *filename, std::ios::openmode mode = std::ios::in); INLINE ~IFileStream(); - INLINE void open(const char *filename, ios::openmode mode = ios::in); + INLINE void open(const char *filename, std::ios::openmode mode = std::ios::in); public: #ifdef _WIN32 - INLINE void attach(const char *filename, HANDLE handle, ios::openmode mode = ios::in); + INLINE void attach(const char *filename, HANDLE handle, std::ios::openmode mode = std::ios::in); #else - INLINE void attach(const char *filename, int fd, ios::openmode mode = ios::in); + INLINE void attach(const char *filename, int fd, std::ios::openmode mode = std::ios::in); #endif PUBLISHED: @@ -54,19 +54,19 @@ private: * simple-threading implementation (using this interface will block only the * current thread, rather than the entire process, on I/O waits). */ -class EXPCL_DTOOL_DTOOLUTIL OFileStream : public ostream { +class EXPCL_DTOOL_DTOOLUTIL OFileStream : public std::ostream { PUBLISHED: INLINE OFileStream(); - INLINE explicit OFileStream(const char *filename, ios::openmode mode = ios::out); + INLINE explicit OFileStream(const char *filename, std::ios::openmode mode = std::ios::out); INLINE ~OFileStream(); - INLINE void open(const char *filename, ios::openmode mode = ios::out); + INLINE void open(const char *filename, std::ios::openmode mode = std::ios::out); public: #ifdef _WIN32 - INLINE void attach(const char *filename, HANDLE handle, ios::openmode mode = ios::out); + INLINE void attach(const char *filename, HANDLE handle, std::ios::openmode mode = std::ios::out); #else - INLINE void attach(const char *filename, int fd, ios::openmode mode = ios::out); + INLINE void attach(const char *filename, int fd, std::ios::openmode mode = std::ios::out); #endif PUBLISHED: @@ -83,19 +83,19 @@ private: * will block only the current thread, rather than the entire process, on I/O * waits). */ -class EXPCL_DTOOL_DTOOLUTIL FileStream : public iostream { +class EXPCL_DTOOL_DTOOLUTIL FileStream : public std::iostream { PUBLISHED: INLINE FileStream(); - INLINE explicit FileStream(const char *filename, ios::openmode mode = ios::in); + INLINE explicit FileStream(const char *filename, std::ios::openmode mode = std::ios::in); INLINE ~FileStream(); - INLINE void open(const char *filename, ios::openmode mode = ios::in); + INLINE void open(const char *filename, std::ios::openmode mode = std::ios::in); public: #ifdef _WIN32 - INLINE void attach(const char *filename, HANDLE handle, ios::openmode mode); + INLINE void attach(const char *filename, HANDLE handle, std::ios::openmode mode); #else - INLINE void attach(const char *filename, int fd, ios::openmode mode); + INLINE void attach(const char *filename, int fd, std::ios::openmode mode); #endif PUBLISHED: diff --git a/dtool/src/dtoolutil/pandaFileStreamBuf.cxx b/dtool/src/dtoolutil/pandaFileStreamBuf.cxx index 037d421469..676f17e0e6 100644 --- a/dtool/src/dtoolutil/pandaFileStreamBuf.cxx +++ b/dtool/src/dtoolutil/pandaFileStreamBuf.cxx @@ -25,6 +25,16 @@ #include #endif // _WIN32 +using std::cerr; +using std::dec; +using std::hex; +using std::ios; +using std::istream; +using std::ostream; +using std::streamoff; +using std::streampos; +using std::string; + PandaFileStreamBuf::NewlineMode PandaFileStreamBuf::_newline_mode = NM_native; static const size_t file_buffer_size = 4096; @@ -41,7 +51,7 @@ PandaFileStreamBuf() { #ifdef _WIN32 // Windows case. - _handle = NULL; + _handle = nullptr; #else _fd = -1; #endif // _WIN32 @@ -130,9 +140,9 @@ open(const char *filename, ios::openmode mode) { TextEncoder encoder; encoder.set_encoding(Filename::get_filesystem_encoding()); encoder.set_text(_filename); - wstring wfilename = encoder.get_wtext(); + std::wstring wfilename = encoder.get_wtext(); _handle = CreateFileW(wfilename.c_str(), access, share_mode, - NULL, creation_disposition, flags, NULL); + nullptr, creation_disposition, flags, nullptr); if (_handle != INVALID_HANDLE_VALUE) { // The file was successfully opened and locked. _is_open = true; @@ -251,10 +261,10 @@ close() { sync(); #ifdef _WIN32 - if (_handle != NULL) { + if (_handle != nullptr) { CloseHandle(_handle); } - _handle = NULL; + _handle = nullptr; #else if (_fd != -1) { ::close(_fd); diff --git a/dtool/src/dtoolutil/pandaFileStreamBuf.h b/dtool/src/dtoolutil/pandaFileStreamBuf.h index 9ab6f84082..623aec6521 100644 --- a/dtool/src/dtoolutil/pandaFileStreamBuf.h +++ b/dtool/src/dtoolutil/pandaFileStreamBuf.h @@ -28,16 +28,16 @@ /** * The streambuf object that implements pifstream and pofstream. */ -class EXPCL_DTOOL_DTOOLUTIL PandaFileStreamBuf : public streambuf { +class EXPCL_DTOOL_DTOOLUTIL PandaFileStreamBuf : public std::streambuf { public: PandaFileStreamBuf(); virtual ~PandaFileStreamBuf(); - void open(const char *filename, ios::openmode mode); + void open(const char *filename, std::ios::openmode mode); #ifdef _WIN32 - void attach(const char *filename, HANDLE handle, ios::openmode mode); + void attach(const char *filename, HANDLE handle, std::ios::openmode mode); #else - void attach(const char *filename, int fd, ios::openmode mode); + void attach(const char *filename, int fd, std::ios::openmode mode); #endif bool is_open() const; @@ -53,8 +53,8 @@ public: static NewlineMode _newline_mode; protected: - virtual streampos seekoff(streamoff off, ios_seekdir dir, ios_openmode which); - virtual streampos seekpos(streampos pos, ios_openmode which); + virtual std::streampos seekoff(std::streamoff off, ios_seekdir dir, ios_openmode which); + virtual std::streampos seekpos(std::streampos pos, ios_openmode which); virtual int overflow(int c); virtual int sync(); @@ -78,9 +78,9 @@ private: const char *source, size_t source_length); private: - string _filename; + std::string _filename; bool _is_open; - ios::openmode _open_mode; + std::ios::openmode _open_mode; char _last_read_nl; @@ -91,15 +91,15 @@ private: #endif // _WIN32 char *_buffer; - streampos _ppos; - streampos _gpos; + std::streampos _ppos; + std::streampos _gpos; }; -EXPCL_DTOOL_DTOOLUTIL ostream & -operator << (ostream &out, PandaFileStreamBuf::NewlineMode newline_mode); +EXPCL_DTOOL_DTOOLUTIL std::ostream & +operator << (std::ostream &out, PandaFileStreamBuf::NewlineMode newline_mode); -EXPCL_DTOOL_DTOOLUTIL istream & -operator >> (istream &in, PandaFileStreamBuf::NewlineMode &newline_mode); +EXPCL_DTOOL_DTOOLUTIL std::istream & +operator >> (std::istream &in, PandaFileStreamBuf::NewlineMode &newline_mode); #endif // USE_PANDAFILESTREAM diff --git a/dtool/src/dtoolutil/pandaSystem.cxx b/dtool/src/dtoolutil/pandaSystem.cxx index 79e5aa7762..3d80d0f6b5 100644 --- a/dtool/src/dtoolutil/pandaSystem.cxx +++ b/dtool/src/dtoolutil/pandaSystem.cxx @@ -15,7 +15,9 @@ #include "pandaVersion.h" #include "dtool_platform.h" -PandaSystem *PandaSystem::_global_ptr = NULL; +using std::string; + +PandaSystem *PandaSystem::_global_ptr = nullptr; TypeHandle PandaSystem::_type_handle; /** @@ -220,7 +222,7 @@ string PandaSystem:: get_compiler() { #if defined(_MSC_VER) // MSVC defines this macro. It's an integer; we need to format it. - ostringstream strm; + std::ostringstream strm; strm << "MSC v." << _MSC_VER; // We also get this suite of macros that tells us what the build platform @@ -368,7 +370,7 @@ add_system(const string &system) { void PandaSystem:: set_system_tag(const string &system, const string &tag, const string &value) { - pair result; + std::pair result; result = _systems.insert(Systems::value_type(system, SystemTags(get_class_type()))); if (result.second) { _system_names_dirty = true; @@ -399,7 +401,7 @@ heap_trim(size_t pad) { * */ void PandaSystem:: -output(ostream &out) const { +output(std::ostream &out) const { out << "Panda version " << get_version_string(); } @@ -407,7 +409,7 @@ output(ostream &out) const { * */ void PandaSystem:: -write(ostream &out) const { +write(std::ostream &out) const { out << *this << "\n" << "compiled on " << get_build_date() << " by " << get_distributor() << "\n" @@ -432,7 +434,8 @@ write(ostream &out) const { */ PandaSystem *PandaSystem:: get_global_ptr() { - if (_global_ptr == (PandaSystem *)NULL) { + if (_global_ptr == nullptr) { + init_type(); _global_ptr = new PandaSystem; } diff --git a/dtool/src/dtoolutil/pandaSystem.h b/dtool/src/dtoolutil/pandaSystem.h index c5adae4898..712b61e834 100644 --- a/dtool/src/dtoolutil/pandaSystem.h +++ b/dtool/src/dtoolutil/pandaSystem.h @@ -29,10 +29,10 @@ protected: ~PandaSystem(); PUBLISHED: - static string get_version_string(); - static string get_package_version_string(); - static string get_package_host_url(); - static string get_p3d_coreapi_version_string(); + static std::string get_version_string(); + static std::string get_package_version_string(); + static std::string get_package_host_url(); + static std::string get_p3d_coreapi_version_string(); static int get_major_version(); static int get_minor_version(); @@ -41,12 +41,12 @@ PUBLISHED: static int get_memory_alignment(); - static string get_distributor(); - static string get_compiler(); - static string get_build_date(); - static string get_git_commit(); + static std::string get_distributor(); + static std::string get_compiler(); + static std::string get_build_date(); + static std::string get_git_commit(); - static string get_platform(); + static std::string get_platform(); MAKE_PROPERTY(version_string, get_version_string); MAKE_PROPERTY(major_version, get_major_version); @@ -63,41 +63,41 @@ PUBLISHED: MAKE_PROPERTY(platform, get_platform); - bool has_system(const string &system) const; + bool has_system(const std::string &system) const; size_t get_num_systems() const; - string get_system(size_t n) const; + std::string get_system(size_t n) const; MAKE_SEQ(get_systems, get_num_systems, get_system); MAKE_SEQ_PROPERTY(systems, get_num_systems, get_system); - string get_system_tag(const string &system, const string &tag) const; + std::string get_system_tag(const std::string &system, const std::string &tag) const; - void add_system(const string &system); - void set_system_tag(const string &system, const string &tag, - const string &value); + void add_system(const std::string &system); + void set_system_tag(const std::string &system, const std::string &tag, + const std::string &value); bool heap_trim(size_t pad); - void output(ostream &out) const; - void write(ostream &out) const; + void output(std::ostream &out) const; + void write(std::ostream &out) const; static PandaSystem *get_global_ptr(); private: void reset_system_names(); - void set_package_version_string(const string &package_version_string); - void set_package_host_url(const string &package_host_url); + void set_package_version_string(const std::string &package_version_string); + void set_package_host_url(const std::string &package_host_url); - typedef pmap SystemTags; - typedef pmap Systems; - typedef pvector SystemNames; + typedef pmap SystemTags; + typedef pmap Systems; + typedef pvector SystemNames; Systems _systems; SystemNames _system_names; bool _system_names_dirty; - string _package_version_string; - string _package_host_url; + std::string _package_version_string; + std::string _package_host_url; static PandaSystem *_global_ptr; @@ -115,7 +115,7 @@ private: friend class ConfigPageManager; }; -inline ostream &operator << (ostream &out, const PandaSystem &ps) { +inline std::ostream &operator << (std::ostream &out, const PandaSystem &ps) { ps.output(out); return out; } diff --git a/dtool/src/dtoolutil/panda_getopt_impl.cxx b/dtool/src/dtoolutil/panda_getopt_impl.cxx index fe1d630a32..030641a357 100644 --- a/dtool/src/dtoolutil/panda_getopt_impl.cxx +++ b/dtool/src/dtoolutil/panda_getopt_impl.cxx @@ -22,8 +22,9 @@ // If the system does lack one or the other of these functions, then we'll go // ahead and provide it instead. +using std::string; -char *optarg = NULL; +char *optarg = nullptr; int optind = 0; int opterr = 1; int optopt = 0; @@ -72,7 +73,7 @@ private: class Param { public: Param(size_t opt_index, size_t argv_index, - char short_option, char *argument = NULL); + char short_option, char *argument = nullptr); size_t _opt_index; size_t _argv_index; @@ -121,7 +122,7 @@ private: // This global pointer is used to differentiate between getopt() being called // the first time, vs. subsequent times. -static PandaGetopt *pgetopt = NULL; +static PandaGetopt *pgetopt = nullptr; /** * @@ -129,7 +130,7 @@ static PandaGetopt *pgetopt = NULL; PandaGetopt:: PandaGetopt(int argc, char *const argv[], const char *optstring, const struct option *longopts, bool allow_one_hyphen_long) { - assert(optstring != NULL); + assert(optstring != nullptr); _return_in_order = false; _require_order = false; @@ -154,7 +155,7 @@ PandaGetopt(int argc, char *const argv[], const char *optstring, ++optstring; _require_order = true; - } else if (getenv("POSIXLY_CORRECT") != NULL) { + } else if (getenv("POSIXLY_CORRECT") != nullptr) { // REQUIRE_ORDER. _require_order = true; @@ -210,13 +211,13 @@ process(int opterr, int *longindex, char *&optarg, int &optind, int &optopt) { optarg = param._argument; optind = (int)param._argv_index; - if (longindex != NULL) { + if (longindex != nullptr) { *longindex = option._longopts_index; } - if (option._option != NULL) { + if (option._option != nullptr) { // This was a long option. Check the special longopt handling parameters. - if (option._option->flag == NULL) { + if (option._option->flag == nullptr) { return option._option->val; } *(option._option->flag) = option._option->val; @@ -226,7 +227,7 @@ process(int opterr, int *longindex, char *&optarg, int &optind, int &optopt) { if (param._opt_index == 0 && opterr) { // This was an invalid character. optopt = param._short_option; - cerr << "Illegal option: -" << param._short_option << "\n"; + std::cerr << "Illegal option: -" << param._short_option << "\n"; return '?'; } @@ -298,9 +299,9 @@ scan_options(const char *optstring, const struct option *longopts) { _options.push_back(Option(short_option, has_arg)); } - if (longopts != NULL) { + if (longopts != nullptr) { int longopts_index = 0; - while (longopts[longopts_index].name != NULL) { + while (longopts[longopts_index].name != nullptr) { _options.push_back(Option(longopts, longopts_index)); ++longopts_index; } @@ -317,7 +318,7 @@ scan_args(int argc, char *const argv[]) { bool end_of_processing = false; while ((int)ai < argc) { - assert(argv[ai] != NULL); + assert(argv[ai] != nullptr); if (argv[ai][0] != '-' || end_of_processing) { // This is a non-option argument. @@ -342,8 +343,8 @@ scan_args(int argc, char *const argv[]) { } else { // An option argument. - char *option = NULL; - char *argument = NULL; + char *option = nullptr; + char *argument = nullptr; size_t opt_index = 0; bool is_long_option = false; bool has_argument = false; @@ -387,7 +388,7 @@ scan_args(int argc, char *const argv[]) { if (is_long_option) { char *equals = strchr(option, '='); - if (equals != NULL) { + if (equals != nullptr) { argument = equals + 1; has_argument = true; } @@ -416,7 +417,7 @@ scan_args(int argc, char *const argv[]) { // Now record the non-option arguments that followed the option arguments. while ((int)ai < argc) { - assert(argv[ai] != NULL); + assert(argv[ai] != nullptr); _arguments.push_back(argv[ai]); ++ai; } @@ -430,7 +431,7 @@ PandaGetopt::Option:: Option(char short_option, int has_arg) : _short_option(short_option), _has_arg(has_arg), - _option(NULL), + _option(nullptr), _longopts_index(-1) { } @@ -463,17 +464,17 @@ Param(size_t opt_index, size_t argv_index, char short_option, char *argument) : int getopt(int argc, char *const argv[], const char *optstring) { - if (pgetopt == NULL) { - pgetopt = new PandaGetopt(argc, argv, optstring, NULL, false); + if (pgetopt == nullptr) { + pgetopt = new PandaGetopt(argc, argv, optstring, nullptr, false); pgetopt->permute(argc, (char **)argv); } - return pgetopt->process(opterr, NULL, optarg, optind, optopt); + return pgetopt->process(opterr, nullptr, optarg, optind, optopt); } int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex) { - if (pgetopt == NULL) { + if (pgetopt == nullptr) { pgetopt = new PandaGetopt(argc, argv, optstring, longopts, false); pgetopt->permute(argc, (char **)argv); } @@ -483,7 +484,7 @@ getopt_long(int argc, char *const argv[], const char *optstring, int getopt_long_only(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex) { - if (pgetopt == NULL) { + if (pgetopt == nullptr) { pgetopt = new PandaGetopt(argc, argv, optstring, longopts, true); pgetopt->permute(argc, (char **)argv); } diff --git a/dtool/src/dtoolutil/pfstream.I b/dtool/src/dtoolutil/pfstream.I index c72a433453..4941f29ca2 100644 --- a/dtool/src/dtoolutil/pfstream.I +++ b/dtool/src/dtoolutil/pfstream.I @@ -12,7 +12,7 @@ */ INLINE IPipeStream::IPipeStream(const std::string cmd) - : istream(&_psb), _psb(PipeStreamBuf::Input) { + : std::istream(&_psb), _psb(PipeStreamBuf::Input) { _psb.command(cmd); } @@ -21,12 +21,12 @@ INLINE void IPipeStream::flush(void) { } INLINE IPipeStream::IPipeStream(void) - : istream(&_psb), _psb(PipeStreamBuf::Input) { - cerr << "should never call default constructor of IPipeStream" << endl; + : std::istream(&_psb), _psb(PipeStreamBuf::Input) { + std::cerr << "should never call default constructor of IPipeStream" << std::endl; } INLINE OPipeStream::OPipeStream(const std::string cmd) - : ostream(&_psb), _psb(PipeStreamBuf::Output) { + : std::ostream(&_psb), _psb(PipeStreamBuf::Output) { _psb.command(cmd); } @@ -35,6 +35,6 @@ INLINE void OPipeStream::flush(void) { } INLINE OPipeStream::OPipeStream(void) - : ostream(&_psb), _psb(PipeStreamBuf::Output) { - cerr << "should never call default constructor of OPipeStream" << endl; + : std::ostream(&_psb), _psb(PipeStreamBuf::Output) { + std::cerr << "should never call default constructor of OPipeStream" << std::endl; } diff --git a/dtool/src/dtoolutil/pfstream.h b/dtool/src/dtoolutil/pfstream.h index 6beccc16ca..e296655337 100644 --- a/dtool/src/dtoolutil/pfstream.h +++ b/dtool/src/dtoolutil/pfstream.h @@ -16,7 +16,7 @@ #include "pfstreamBuf.h" -class EXPCL_DTOOL_DTOOLUTIL IPipeStream : public istream { +class EXPCL_DTOOL_DTOOLUTIL IPipeStream : public std::istream { public: INLINE IPipeStream(const std::string); @@ -32,7 +32,7 @@ private: INLINE IPipeStream(); }; -class EXPCL_DTOOL_DTOOLUTIL OPipeStream : public ostream { +class EXPCL_DTOOL_DTOOLUTIL OPipeStream : public std::ostream { public: INLINE OPipeStream(const std::string); diff --git a/dtool/src/dtoolutil/pfstreamBuf.cxx b/dtool/src/dtoolutil/pfstreamBuf.cxx index a23d2f64df..a5585ee3cd 100644 --- a/dtool/src/dtoolutil/pfstreamBuf.cxx +++ b/dtool/src/dtoolutil/pfstreamBuf.cxx @@ -14,6 +14,10 @@ #include "pfstreamBuf.h" #include +using std::cerr; +using std::endl; +using std::string; + PipeStreamBuf::PipeStreamBuf(PipeStreamBuf::Direction dir) : _dir(dir) { @@ -56,7 +60,7 @@ void PipeStreamBuf::command(const string cmd) { int PipeStreamBuf::overflow(int c) { assert(is_open()); assert(_dir == Output); - streamsize n = pptr() - pbase(); + std::streamsize n = pptr() - pbase(); if (n != 0) { write_chars(pbase(), n, false); pbump(-n); // reset pptr() @@ -72,11 +76,11 @@ int PipeStreamBuf::overflow(int c) { int PipeStreamBuf::sync(void) { assert(is_open()); if (_dir == Output) { - streamsize n = pptr() - pbase(); + std::streamsize n = pptr() - pbase(); write_chars(pbase(), n, false); pbump(-n); } else { - streamsize n = egptr() - gptr(); + std::streamsize n = egptr() - gptr(); if (n != 0) { gbump(n); // flush all our stored input away #ifndef NDEBUG @@ -89,8 +93,8 @@ int PipeStreamBuf::sync(void) { int PipeStreamBuf::underflow(void) { assert(_dir == Input); - if ((eback() == (char*)0L) || (gptr() == (char*)0L) || - (egptr() == (char*)0L)) { + if ((eback() == nullptr) || (gptr() == nullptr) || + (egptr() == nullptr)) { // must be new-style iostream library char* buf = new char[4096]; char* ebuf = &(buf[4096]); @@ -162,7 +166,7 @@ void PipeStreamBuf::write_chars(const char* start, int length, bool flush) { */ void PipeStreamBuf:: init_pipe() { - _pipe = NULL; + _pipe = nullptr; } /** @@ -170,7 +174,7 @@ init_pipe() { */ bool PipeStreamBuf:: is_open() const { - return _pipe != NULL; + return _pipe != nullptr; } /** @@ -179,7 +183,7 @@ is_open() const { */ bool PipeStreamBuf:: eof_pipe() const { - return (_pipe == NULL) && feof(_pipe); + return (_pipe == nullptr) && feof(_pipe); } /** @@ -193,7 +197,7 @@ bool PipeStreamBuf:: open_pipe(const string &cmd) { const char *typ = (_dir == Output)?"w":"r"; _pipe = popen(cmd.c_str(), typ); - return (_pipe != NULL); + return (_pipe != nullptr); } /** @@ -201,9 +205,9 @@ open_pipe(const string &cmd) { */ void PipeStreamBuf:: close_pipe() { - if (_pipe != NULL) { + if (_pipe != nullptr) { fclose(_pipe); - _pipe = NULL; + _pipe = nullptr; } } @@ -289,7 +293,7 @@ open_pipe(const string &cmd) { SECURITY_ATTRIBUTES saAttr; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; - saAttr.lpSecurityDescriptor = NULL; + saAttr.lpSecurityDescriptor = nullptr; if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) { #ifndef NDEBUG cerr << "Unable to create output pipe\n"; @@ -391,7 +395,7 @@ read_pipe(char *data, size_t len) { return 0; } DWORD dwRead; - if (!ReadFile(_child_out, data, len, &dwRead, NULL)) { + if (!ReadFile(_child_out, data, len, &dwRead, nullptr)) { close_pipe(); return 0; } diff --git a/dtool/src/dtoolutil/pfstreamBuf.h b/dtool/src/dtoolutil/pfstreamBuf.h index ad0c132f0f..50875b2179 100644 --- a/dtool/src/dtoolutil/pfstreamBuf.h +++ b/dtool/src/dtoolutil/pfstreamBuf.h @@ -41,7 +41,7 @@ #endif // WIN_PIPE_CALLS -class EXPCL_DTOOL_DTOOLUTIL PipeStreamBuf : public streambuf { +class EXPCL_DTOOL_DTOOLUTIL PipeStreamBuf : public std::streambuf { public: enum Direction { Input, Output }; @@ -49,7 +49,7 @@ public: virtual ~PipeStreamBuf(void); void flush(); - void command(const string); + void command(const std::string); protected: virtual int overflow(int c); @@ -59,13 +59,13 @@ private: void init_pipe(); bool is_open() const; bool eof_pipe() const; - bool open_pipe(const string &cmd); + bool open_pipe(const std::string &cmd); void close_pipe(); size_t write_pipe(const char *data, size_t len); size_t read_pipe(char *data, size_t len); Direction _dir; - string _line_buffer; + std::string _line_buffer; #ifndef WIN_PIPE_CALLS FILE *_pipe; diff --git a/dtool/src/dtoolutil/stringDecoder.I b/dtool/src/dtoolutil/stringDecoder.I index 8ac51f52c6..f7a3b14701 100644 --- a/dtool/src/dtoolutil/stringDecoder.I +++ b/dtool/src/dtoolutil/stringDecoder.I @@ -15,7 +15,7 @@ * */ INLINE StringDecoder:: -StringDecoder(const string &input) : _input(input) { +StringDecoder(const std::string &input) : _input(input) { _p = 0; _eof = false; } @@ -46,12 +46,12 @@ test_eof() { * */ INLINE StringUtf8Decoder:: -StringUtf8Decoder(const string &input) : StringDecoder(input) { +StringUtf8Decoder(const std::string &input) : StringDecoder(input) { } /** * */ INLINE StringUnicodeDecoder:: -StringUnicodeDecoder(const string &input) : StringDecoder(input) { +StringUnicodeDecoder(const std::string &input) : StringDecoder(input) { } diff --git a/dtool/src/dtoolutil/stringDecoder.cxx b/dtool/src/dtoolutil/stringDecoder.cxx index ce73120543..e77e0c5e13 100644 --- a/dtool/src/dtoolutil/stringDecoder.cxx +++ b/dtool/src/dtoolutil/stringDecoder.cxx @@ -14,7 +14,7 @@ #include "stringDecoder.h" #include "config_dtoolutil.h" -ostream *StringDecoder::_notify_ptr = &cerr; +std::ostream *StringDecoder::_notify_ptr = &std::cerr; /** * @@ -41,7 +41,7 @@ get_next_character() { * notify. */ void StringDecoder:: -set_notify_ptr(ostream *notify_ptr) { +set_notify_ptr(std::ostream *notify_ptr) { _notify_ptr = notify_ptr; } @@ -49,7 +49,7 @@ set_notify_ptr(ostream *notify_ptr) { * Returns the ostream that is used to write error messages to. See * set_notify_ptr(). */ -ostream *StringDecoder:: +std::ostream *StringDecoder:: get_notify_ptr() { return _notify_ptr; } @@ -95,7 +95,7 @@ get_next_character() { // First byte of two. unsigned int two = 0; if (test_eof()) { - if (_notify_ptr != NULL) { + if (_notify_ptr != nullptr) { (*_notify_ptr) << "utf-8 encoded string '" << _input << "' ends abruptly.\n"; } @@ -108,7 +108,7 @@ get_next_character() { } else if ((result & 0xf0) == 0xe0) { // First byte of three. if (test_eof()) { - if (_notify_ptr != NULL) { + if (_notify_ptr != nullptr) { (*_notify_ptr) << "utf-8 encoded string '" << _input << "' ends abruptly.\n"; } @@ -116,7 +116,7 @@ get_next_character() { } unsigned int two = (unsigned char)_input[_p++]; if (test_eof()) { - if (_notify_ptr != NULL) { + if (_notify_ptr != nullptr) { (*_notify_ptr) << "utf-8 encoded string '" << _input << "' ends abruptly.\n"; } @@ -129,9 +129,9 @@ get_next_character() { // Otherwise--the high bit is set but it is not one of the introductory // utf-8 bytes--we have an error. - if (_notify_ptr != NULL) { + if (_notify_ptr != nullptr) { (*_notify_ptr) - << "Non utf-8 byte in string: 0x" << hex << result << dec + << "Non utf-8 byte in string: 0x" << std::hex << result << std::dec << ", string is '" << _input << "'\n"; } return -1; @@ -152,7 +152,7 @@ get_next_character() { unsigned int high = (unsigned char)_input[_p++]; if (test_eof()) { - if (_notify_ptr != NULL) { + if (_notify_ptr != nullptr) { (*_notify_ptr) << "Unicode-encoded string has odd number of bytes.\n"; } diff --git a/dtool/src/dtoolutil/stringDecoder.h b/dtool/src/dtoolutil/stringDecoder.h index 62c97cbe9e..c0b2534ee2 100644 --- a/dtool/src/dtoolutil/stringDecoder.h +++ b/dtool/src/dtoolutil/stringDecoder.h @@ -23,22 +23,22 @@ */ class EXPCL_DTOOL_DTOOLUTIL StringDecoder { public: - INLINE StringDecoder(const string &input); + INLINE StringDecoder(const std::string &input); virtual ~StringDecoder(); virtual int get_next_character(); INLINE bool is_eof(); - static void set_notify_ptr(ostream *ptr); - static ostream *get_notify_ptr(); + static void set_notify_ptr(std::ostream *ptr); + static std::ostream *get_notify_ptr(); protected: INLINE bool test_eof(); - string _input; + std::string _input; size_t _p; bool _eof; - static ostream *_notify_ptr; + static std::ostream *_notify_ptr; }; /** @@ -46,7 +46,7 @@ protected: */ class StringUtf8Decoder : public StringDecoder { public: - INLINE StringUtf8Decoder(const string &input); + INLINE StringUtf8Decoder(const std::string &input); virtual int get_next_character(); }; @@ -57,7 +57,7 @@ public: */ class StringUnicodeDecoder : public StringDecoder { public: - INLINE StringUnicodeDecoder(const string &input); + INLINE StringUnicodeDecoder(const std::string &input); virtual int get_next_character(); }; diff --git a/dtool/src/dtoolutil/string_utils.I b/dtool/src/dtoolutil/string_utils.I index e4e71766f8..1861e86ffa 100644 --- a/dtool/src/dtoolutil/string_utils.I +++ b/dtool/src/dtoolutil/string_utils.I @@ -12,38 +12,38 @@ */ template -INLINE string +INLINE std::string format_string(const Thing &thing) { - ostringstream str; + std::ostringstream str; str << thing; return str.str(); } -INLINE string -format_string(const string &value) { +INLINE std::string +format_string(const std::string &value) { return value; } -INLINE string +INLINE std::string format_string(bool value) { - return string(value ? "true" : "false"); + return std::string(value ? "true" : "false"); } -INLINE string +INLINE std::string format_string(float value) { char buffer[32]; - pdtoa(value, buffer); - return string(buffer); + pdtoa((double)value, buffer); + return std::string(buffer); } -INLINE string +INLINE std::string format_string(double value) { char buffer[32]; pdtoa(value, buffer); - return string(buffer); + return std::string(buffer); } -INLINE string +INLINE std::string format_string(unsigned int value) { char buffer[11]; char *p = buffer + 10; @@ -53,10 +53,10 @@ format_string(unsigned int value) { value /= 10; } while (value > 0); - return string(p); + return std::string(p); } -INLINE string +INLINE std::string format_string(int value) { char buffer[12]; char *p = buffer + 11; @@ -76,10 +76,10 @@ format_string(int value) { } while (value > 0); } - return string(p); + return std::string(p); } -INLINE string +INLINE std::string format_string(int64_t value) { char buffer[21]; char *p = buffer + 20; @@ -99,5 +99,5 @@ format_string(int64_t value) { } while (value > 0); } - return string(p); + return std::string(p); } diff --git a/dtool/src/dtoolutil/string_utils.cxx b/dtool/src/dtoolutil/string_utils.cxx index 600b07e7ed..50d5d53802 100644 --- a/dtool/src/dtoolutil/string_utils.cxx +++ b/dtool/src/dtoolutil/string_utils.cxx @@ -17,6 +17,9 @@ #include +using std::string; +using std::wstring; + // Case-insensitive string comparison, from Stroustrup's C++ third edition. // Works like strcmp(). int diff --git a/dtool/src/dtoolutil/string_utils.h b/dtool/src/dtoolutil/string_utils.h index 37f7679efe..01f7616fa9 100644 --- a/dtool/src/dtoolutil/string_utils.h +++ b/dtool/src/dtoolutil/string_utils.h @@ -22,58 +22,58 @@ // Case-insensitive string comparison, from Stroustrup's C++ third edition. // Works like strcmp(). -EXPCL_DTOOL_DTOOLUTIL int cmp_nocase(const string &s, const string &s2); +EXPCL_DTOOL_DTOOLUTIL int cmp_nocase(const std::string &s, const std::string &s2); // Similar, except it also accepts hyphen and underscore as equivalent. -EXPCL_DTOOL_DTOOLUTIL int cmp_nocase_uh(const string &s, const string &s2); +EXPCL_DTOOL_DTOOLUTIL int cmp_nocase_uh(const std::string &s, const std::string &s2); // Returns the string converted to lowercase. -EXPCL_DTOOL_DTOOLUTIL string downcase(const string &s); +EXPCL_DTOOL_DTOOLUTIL std::string downcase(const std::string &s); // Returns the string converted to uppercase. -EXPCL_DTOOL_DTOOLUTIL string upcase(const string &s); +EXPCL_DTOOL_DTOOLUTIL std::string upcase(const std::string &s); // Separates the string into words according to whitespace. -EXPCL_DTOOL_DTOOLUTIL int extract_words(const string &str, vector_string &words); -EXPCL_DTOOL_DTOOLUTIL int extract_words(const wstring &str, pvector &words); +EXPCL_DTOOL_DTOOLUTIL int extract_words(const std::string &str, vector_string &words); +EXPCL_DTOOL_DTOOLUTIL int extract_words(const std::wstring &str, pvector &words); // Separates the string into words according to the indicated delimiters. -EXPCL_DTOOL_DTOOLUTIL void tokenize(const string &str, vector_string &words, - const string &delimiters, +EXPCL_DTOOL_DTOOLUTIL void tokenize(const std::string &str, vector_string &words, + const std::string &delimiters, bool discard_repeated_delimiters = false); -EXPCL_DTOOL_DTOOLUTIL void tokenize(const wstring &str, pvector &words, - const wstring &delimiters, +EXPCL_DTOOL_DTOOLUTIL void tokenize(const std::wstring &str, pvector &words, + const std::wstring &delimiters, bool discard_repeated_delimiters = false); // Trims leading andor trailing whitespace from the string. -EXPCL_DTOOL_DTOOLUTIL string trim_left(const string &str); -EXPCL_DTOOL_DTOOLUTIL wstring trim_left(const wstring &str); -EXPCL_DTOOL_DTOOLUTIL string trim_right(const string &str); -EXPCL_DTOOL_DTOOLUTIL wstring trim_right(const wstring &str); -EXPCL_DTOOL_DTOOLUTIL string trim(const string &str); -EXPCL_DTOOL_DTOOLUTIL wstring trim(const wstring &str); +EXPCL_DTOOL_DTOOLUTIL std::string trim_left(const std::string &str); +EXPCL_DTOOL_DTOOLUTIL std::wstring trim_left(const std::wstring &str); +EXPCL_DTOOL_DTOOLUTIL std::string trim_right(const std::string &str); +EXPCL_DTOOL_DTOOLUTIL std::wstring trim_right(const std::wstring &str); +EXPCL_DTOOL_DTOOLUTIL std::string trim(const std::string &str); +EXPCL_DTOOL_DTOOLUTIL std::wstring trim(const std::wstring &str); // Functions to parse numeric values out of a string. -EXPCL_DTOOL_DTOOLUTIL int string_to_int(const string &str, string &tail); -EXPCL_DTOOL_DTOOLUTIL bool string_to_int(const string &str, int &result); -EXPCL_DTOOL_DTOOLUTIL double string_to_double(const string &str, string &tail); -EXPCL_DTOOL_DTOOLUTIL bool string_to_double(const string &str, double &result); -EXPCL_DTOOL_DTOOLUTIL bool string_to_float(const string &str, float &result); -EXPCL_DTOOL_DTOOLUTIL bool string_to_stdfloat(const string &str, PN_stdfloat &result); +EXPCL_DTOOL_DTOOLUTIL int string_to_int(const std::string &str, std::string &tail); +EXPCL_DTOOL_DTOOLUTIL bool string_to_int(const std::string &str, int &result); +EXPCL_DTOOL_DTOOLUTIL double string_to_double(const std::string &str, std::string &tail); +EXPCL_DTOOL_DTOOLUTIL bool string_to_double(const std::string &str, double &result); +EXPCL_DTOOL_DTOOLUTIL bool string_to_float(const std::string &str, float &result); +EXPCL_DTOOL_DTOOLUTIL bool string_to_stdfloat(const std::string &str, PN_stdfloat &result); // Convenience function to make a string from anything that has an ostream // operator. template -INLINE string format_string(const Thing &thing); +INLINE std::string format_string(const Thing &thing); // Fast specializations for some primitive types. -INLINE string format_string(const string &value); -INLINE string format_string(bool value); -INLINE string format_string(float value); -INLINE string format_string(double value); -INLINE string format_string(unsigned int value); -INLINE string format_string(int value); -INLINE string format_string(int64_t value); +INLINE std::string format_string(const std::string &value); +INLINE std::string format_string(bool value); +INLINE std::string format_string(float value); +INLINE std::string format_string(double value); +INLINE std::string format_string(unsigned int value); +INLINE std::string format_string(int value); +INLINE std::string format_string(int64_t value); #include "string_utils.I" diff --git a/dtool/src/dtoolutil/test_pfstream.cxx b/dtool/src/dtoolutil/test_pfstream.cxx index b088079723..93bebd6236 100644 --- a/dtool/src/dtoolutil/test_pfstream.cxx +++ b/dtool/src/dtoolutil/test_pfstream.cxx @@ -17,26 +17,26 @@ int main(int argc, char *argv[]) { if (argc < 2) { - cout << "test_pfstream command-line\n"; + std::cout << "test_pfstream command-line\n"; return (1); } // Build one command out of the arguments. - string cmd; + std::string cmd; cmd = argv[1]; for (int i = 2; i < argc; i++) { cmd += " "; cmd += argv[i]; } - cout << "Executing command:\n" << cmd << "\n"; + std::cout << "Executing command:\n" << cmd << "\n"; IPipeStream in(cmd); char c; c = in.get(); while (in && !in.fail() && !in.eof()) { - cout.put(toupper(c)); + std::cout.put(toupper(c)); c = in.get(); } diff --git a/dtool/src/dtoolutil/test_touch.cxx b/dtool/src/dtoolutil/test_touch.cxx index 722a94a85e..94a7d2782c 100644 --- a/dtool/src/dtoolutil/test_touch.cxx +++ b/dtool/src/dtoolutil/test_touch.cxx @@ -17,7 +17,7 @@ int main(int argc, char *argv[]) { if (argc < 2) { - cout << "test_touch filename [filename ... ]\n"; + std::cout << "test_touch filename [filename ... ]\n"; return (1); } diff --git a/dtool/src/dtoolutil/textEncoder.I b/dtool/src/dtoolutil/textEncoder.I index fb84aa316d..e07f489ab0 100644 --- a/dtool/src/dtoolutil/textEncoder.I +++ b/dtool/src/dtoolutil/textEncoder.I @@ -86,7 +86,7 @@ get_default_encoding() { * decoded version of the string. */ INLINE void TextEncoder:: -set_text(const string &text) { +set_text(const std::string &text) { if (!has_text() || _text != text) { _text = text; _flags = (_flags | F_got_text) & ~F_got_wtext; @@ -100,7 +100,7 @@ set_text(const string &text) { * whichever encoding is specified by set_encoding(). */ INLINE void TextEncoder:: -set_text(const string &text, TextEncoder::Encoding encoding) { +set_text(const std::string &text, TextEncoder::Encoding encoding) { set_wtext(decode_text(text, encoding)); } @@ -109,8 +109,8 @@ set_text(const string &text, TextEncoder::Encoding encoding) { */ INLINE void TextEncoder:: clear_text() { - _text = string(); - _wtext = wstring(); + _text = std::string(); + _wtext = std::wstring(); _flags |= (F_got_text | F_got_wtext); } @@ -129,7 +129,7 @@ has_text() const { /** * Returns the current text, as encoded via the current encoding system. */ -INLINE string TextEncoder:: +INLINE std::string TextEncoder:: get_text() const { if ((_flags & F_got_text) == 0) { ((TextEncoder *)this)->_text = encode_wtext(_wtext); @@ -141,7 +141,7 @@ get_text() const { /** * Returns the current text, as encoded via the indicated encoding system. */ -INLINE string TextEncoder:: +INLINE std::string TextEncoder:: get_text(TextEncoder::Encoding encoding) const { return encode_wtext(get_wtext(), encoding); } @@ -150,7 +150,7 @@ get_text(TextEncoder::Encoding encoding) const { * Appends the indicates string to the end of the stored text. */ INLINE void TextEncoder:: -append_text(const string &text) { +append_text(const std::string &text) { _text = get_text() + text; _flags = (_flags | F_got_text) & ~F_got_wtext; } @@ -161,7 +161,7 @@ append_text(const string &text) { */ INLINE void TextEncoder:: append_unicode_char(int character) { - _wtext = get_wtext() + wstring(1, (wchar_t)character); + _wtext = get_wtext() + std::wstring(1, (wchar_t)character); _flags = (_flags | F_got_wtext) & ~F_got_text; } @@ -207,7 +207,7 @@ set_unicode_char(size_t index, int character) { * Returns the nth char of the stored text, as a one-, two-, or three-byte * encoded string. */ -INLINE string TextEncoder:: +INLINE std::string TextEncoder:: get_encoded_char(size_t index) const { return get_encoded_char(index, get_encoding()); } @@ -216,9 +216,9 @@ get_encoded_char(size_t index) const { * Returns the nth char of the stored text, as a one-, two-, or three-byte * encoded string. */ -INLINE string TextEncoder:: +INLINE std::string TextEncoder:: get_encoded_char(size_t index, TextEncoder::Encoding encoding) const { - wstring wch(1, (wchar_t)get_unicode_char(index)); + std::wstring wch(1, (wchar_t)get_unicode_char(index)); return encode_wtext(wch, encoding); } @@ -235,7 +235,7 @@ get_encoded_char(size_t index, TextEncoder::Encoding encoding) const { * will be converted to ASCII, and the nonconvertible characters will remain * encoded in the encoding specified by set_encoding(). */ -INLINE string TextEncoder:: +INLINE std::string TextEncoder:: get_text_as_ascii() const { return encode_wtext(get_wtext_as_ascii()); } @@ -246,8 +246,8 @@ get_text_as_ascii() const { * and returns the newly encoded string. This does not change or affect any * properties on the TextEncoder itself. */ -INLINE string TextEncoder:: -reencode_text(const string &text, TextEncoder::Encoding from, +INLINE std::string TextEncoder:: +reencode_text(const std::string &text, TextEncoder::Encoding from, TextEncoder::Encoding to) { return encode_wtext(decode_text(text, from), to); } @@ -259,7 +259,7 @@ reencode_text(const string &text, TextEncoder::Encoding from, INLINE bool TextEncoder:: unicode_isalpha(int character) { const UnicodeLatinMap::Entry *entry = UnicodeLatinMap::look_up(character); - if (entry == (const UnicodeLatinMap::Entry *)NULL) { + if (entry == nullptr) { return false; } return entry->_char_type == UnicodeLatinMap::CT_upper || @@ -273,7 +273,7 @@ unicode_isalpha(int character) { INLINE bool TextEncoder:: unicode_isdigit(int character) { const UnicodeLatinMap::Entry *entry = UnicodeLatinMap::look_up(character); - if (entry == (const UnicodeLatinMap::Entry *)NULL) { + if (entry == nullptr) { // The digits aren't actually listed in the map. return (character >= '0' && character <= '9'); } @@ -288,7 +288,7 @@ unicode_isdigit(int character) { INLINE bool TextEncoder:: unicode_ispunct(int character) { const UnicodeLatinMap::Entry *entry = UnicodeLatinMap::look_up(character); - if (entry == (const UnicodeLatinMap::Entry *)NULL) { + if (entry == nullptr) { // Some punctuation marks aren't listed in the map. return (character >= 0 && character < 128 && ispunct(character)); } @@ -302,7 +302,7 @@ unicode_ispunct(int character) { INLINE bool TextEncoder:: unicode_isupper(int character) { const UnicodeLatinMap::Entry *entry = UnicodeLatinMap::look_up(character); - if (entry == (const UnicodeLatinMap::Entry *)NULL) { + if (entry == nullptr) { return false; } return entry->_char_type == UnicodeLatinMap::CT_upper; @@ -332,7 +332,7 @@ unicode_isspace(int character) { INLINE bool TextEncoder:: unicode_islower(int character) { const UnicodeLatinMap::Entry *entry = UnicodeLatinMap::look_up(character); - if (entry == (const UnicodeLatinMap::Entry *)NULL) { + if (entry == nullptr) { return false; } return entry->_char_type == UnicodeLatinMap::CT_lower; @@ -345,7 +345,7 @@ unicode_islower(int character) { INLINE int TextEncoder:: unicode_toupper(int character) { const UnicodeLatinMap::Entry *entry = UnicodeLatinMap::look_up(character); - if (entry == (const UnicodeLatinMap::Entry *)NULL) { + if (entry == nullptr) { return character; } return entry->_toupper_character; @@ -358,7 +358,7 @@ unicode_toupper(int character) { INLINE int TextEncoder:: unicode_tolower(int character) { const UnicodeLatinMap::Entry *entry = UnicodeLatinMap::look_up(character); - if (entry == (const UnicodeLatinMap::Entry *)NULL) { + if (entry == nullptr) { return character; } return entry->_tolower_character; @@ -368,8 +368,8 @@ unicode_tolower(int character) { * Converts the string to uppercase, assuming the string is encoded in the * default encoding. */ -INLINE string TextEncoder:: -upper(const string &source) { +INLINE std::string TextEncoder:: +upper(const std::string &source) { return upper(source, get_default_encoding()); } @@ -377,8 +377,8 @@ upper(const string &source) { * Converts the string to uppercase, assuming the string is encoded in the * indicated encoding. */ -INLINE string TextEncoder:: -upper(const string &source, TextEncoder::Encoding encoding) { +INLINE std::string TextEncoder:: +upper(const std::string &source, TextEncoder::Encoding encoding) { TextEncoder encoder; encoder.set_encoding(encoding); encoder.set_text(source); @@ -390,8 +390,8 @@ upper(const string &source, TextEncoder::Encoding encoding) { * Converts the string to lowercase, assuming the string is encoded in the * default encoding. */ -INLINE string TextEncoder:: -lower(const string &source) { +INLINE std::string TextEncoder:: +lower(const std::string &source) { return lower(source, get_default_encoding()); } @@ -399,8 +399,8 @@ lower(const string &source) { * Converts the string to lowercase, assuming the string is encoded in the * indicated encoding. */ -INLINE string TextEncoder:: -lower(const string &source, TextEncoder::Encoding encoding) { +INLINE std::string TextEncoder:: +lower(const std::string &source, TextEncoder::Encoding encoding) { TextEncoder encoder; encoder.set_encoding(encoding); encoder.set_text(source); @@ -414,7 +414,7 @@ lower(const string &source, TextEncoder::Encoding encoding) { * encoded version of the string. */ INLINE void TextEncoder:: -set_wtext(const wstring &wtext) { +set_wtext(const std::wstring &wtext) { if (!has_text() || _wtext != wtext) { _wtext = wtext; _flags = (_flags | F_got_wtext) & ~F_got_text; @@ -425,7 +425,7 @@ set_wtext(const wstring &wtext) { * Returns the text associated with the TextEncoder, as a wide-character * string. */ -INLINE const wstring &TextEncoder:: +INLINE const std::wstring &TextEncoder:: get_wtext() const { if ((_flags & F_got_wtext) == 0) { ((TextEncoder *)this)->_wtext = decode_text(_text); @@ -438,7 +438,7 @@ get_wtext() const { * Appends the indicates string to the end of the stored wide-character text. */ INLINE void TextEncoder:: -append_wtext(const wstring &wtext) { +append_wtext(const std::wstring &wtext) { _wtext = get_wtext() + wtext; _flags = (_flags | F_got_wtext) & ~F_got_text; } @@ -447,8 +447,8 @@ append_wtext(const wstring &wtext) { * Encodes a wide-text string into a single-char string, according to the * current encoding. */ -INLINE string TextEncoder:: -encode_wtext(const wstring &wtext) const { +INLINE std::string TextEncoder:: +encode_wtext(const std::wstring &wtext) const { return encode_wtext(wtext, _encoding); } @@ -456,16 +456,16 @@ encode_wtext(const wstring &wtext) const { * Returns the given wstring decoded to a single-byte string, via the current * encoding system. */ -INLINE wstring TextEncoder:: -decode_text(const string &text) const { +INLINE std::wstring TextEncoder:: +decode_text(const std::string &text) const { return decode_text(text, _encoding); } /** * Uses the current default encoding to output the wstring. */ -INLINE ostream & -operator << (ostream &out, const wstring &str) { +INLINE std::ostream & +operator << (std::ostream &out, const std::wstring &str) { TextEncoder encoder; encoder.set_wtext(str); out << encoder.get_text(); diff --git a/dtool/src/dtoolutil/textEncoder.cxx b/dtool/src/dtoolutil/textEncoder.cxx index f4f788845e..1e1cd4bc61 100644 --- a/dtool/src/dtoolutil/textEncoder.cxx +++ b/dtool/src/dtoolutil/textEncoder.cxx @@ -16,6 +16,11 @@ #include "unicodeLatinMap.h" #include "config_dtoolutil.h" +using std::istream; +using std::ostream; +using std::string; +using std::wstring; + TextEncoder::Encoding TextEncoder::_default_encoding = TextEncoder::E_iso8859; /** @@ -69,7 +74,7 @@ get_wtext_as_ascii() const { const UnicodeLatinMap::Entry *map_entry = UnicodeLatinMap::look_up(character); - if (map_entry != NULL && map_entry->_ascii_equiv != 0) { + if (map_entry != nullptr && map_entry->_ascii_equiv != 0) { result += (wchar_t)map_entry->_ascii_equiv; if (map_entry->_ascii_additional != 0) { result += (wchar_t)map_entry->_ascii_additional; @@ -117,7 +122,7 @@ encode_wchar(wchar_t ch, TextEncoder::Encoding encoding) { // an unusual accent mark). const UnicodeLatinMap::Entry *map_entry = UnicodeLatinMap::look_up(ch); - if (map_entry != NULL && map_entry->_ascii_equiv != 0) { + if (map_entry != nullptr && map_entry->_ascii_equiv != 0) { // Yes, it has an ascii equivalent. if (map_entry->_ascii_additional != 0) { // In fact, it has two of them. @@ -345,7 +350,7 @@ operator >> (istream &in, TextEncoder::Encoding &encoding) { encoding = TextEncoder::E_unicode; } else { ostream *notify_ptr = StringDecoder::get_notify_ptr(); - if (notify_ptr != (ostream *)NULL) { + if (notify_ptr != nullptr) { (*notify_ptr) << "Invalid TextEncoder::Encoding: " << word << "\n"; } diff --git a/dtool/src/dtoolutil/textEncoder.h b/dtool/src/dtoolutil/textEncoder.h index 3f57ed4c7f..a7eaf395ff 100644 --- a/dtool/src/dtoolutil/textEncoder.h +++ b/dtool/src/dtoolutil/textEncoder.h @@ -48,26 +48,26 @@ PUBLISHED: INLINE static Encoding get_default_encoding(); MAKE_PROPERTY(default_encoding, get_default_encoding, set_default_encoding); - INLINE void set_text(const string &text); - INLINE void set_text(const string &text, Encoding encoding); + INLINE void set_text(const std::string &text); + INLINE void set_text(const std::string &text, Encoding encoding); INLINE void clear_text(); INLINE bool has_text() const; void make_upper(); void make_lower(); - INLINE string get_text() const; - INLINE string get_text(Encoding encoding) const; - INLINE void append_text(const string &text); + INLINE std::string get_text() const; + INLINE std::string get_text(Encoding encoding) const; + INLINE void append_text(const std::string &text); INLINE void append_unicode_char(int character); INLINE size_t get_num_chars() const; INLINE int get_unicode_char(size_t index) const; INLINE void set_unicode_char(size_t index, int character); - INLINE string get_encoded_char(size_t index) const; - INLINE string get_encoded_char(size_t index, Encoding encoding) const; - INLINE string get_text_as_ascii() const; + INLINE std::string get_encoded_char(size_t index) const; + INLINE std::string get_encoded_char(size_t index, Encoding encoding) const; + INLINE std::string get_text_as_ascii() const; - INLINE static string reencode_text(const string &text, Encoding from, Encoding to); + INLINE static std::string reencode_text(const std::string &text, Encoding from, Encoding to); INLINE static bool unicode_isalpha(int character); INLINE static bool unicode_isdigit(int character); @@ -78,52 +78,52 @@ PUBLISHED: INLINE static int unicode_toupper(int character); INLINE static int unicode_tolower(int character); - INLINE static string upper(const string &source); - INLINE static string upper(const string &source, Encoding encoding); - INLINE static string lower(const string &source); - INLINE static string lower(const string &source, Encoding encoding); + INLINE static std::string upper(const std::string &source); + INLINE static std::string upper(const std::string &source, Encoding encoding); + INLINE static std::string lower(const std::string &source); + INLINE static std::string lower(const std::string &source, Encoding encoding); // Direct support for wide-character strings. Now publishable with the new // wstring support in interrogate. - INLINE void set_wtext(const wstring &wtext); - INLINE const wstring &get_wtext() const; - INLINE void append_wtext(const wstring &text); - wstring get_wtext_as_ascii() const; + INLINE void set_wtext(const std::wstring &wtext); + INLINE const std::wstring &get_wtext() const; + INLINE void append_wtext(const std::wstring &text); + std::wstring get_wtext_as_ascii() const; bool is_wtext() const; - static string encode_wchar(wchar_t ch, Encoding encoding); - INLINE string encode_wtext(const wstring &wtext) const; - static string encode_wtext(const wstring &wtext, Encoding encoding); - INLINE wstring decode_text(const string &text) const; - static wstring decode_text(const string &text, Encoding encoding); + static std::string encode_wchar(wchar_t ch, Encoding encoding); + INLINE std::string encode_wtext(const std::wstring &wtext) const; + static std::string encode_wtext(const std::wstring &wtext, Encoding encoding); + INLINE std::wstring decode_text(const std::string &text) const; + static std::wstring decode_text(const std::string &text, Encoding encoding); private: enum Flags { F_got_text = 0x0001, F_got_wtext = 0x0002, }; - static wstring decode_text_impl(StringDecoder &decoder); + static std::wstring decode_text_impl(StringDecoder &decoder); int _flags; Encoding _encoding; - string _text; - wstring _wtext; + std::string _text; + std::wstring _wtext; static Encoding _default_encoding; }; -EXPCL_DTOOL_DTOOLUTIL ostream & -operator << (ostream &out, TextEncoder::Encoding encoding); -EXPCL_DTOOL_DTOOLUTIL istream & -operator >> (istream &in, TextEncoder::Encoding &encoding); +EXPCL_DTOOL_DTOOLUTIL std::ostream & +operator << (std::ostream &out, TextEncoder::Encoding encoding); +EXPCL_DTOOL_DTOOLUTIL std::istream & +operator >> (std::istream &in, TextEncoder::Encoding &encoding); // We'll define the output operator for wstring here, too. Presumably this // will not be automatically defined by any system libraries. // This function is declared inline to minimize the risk of link conflicts // should another third-party module also define the same output operator. -INLINE EXPCL_DTOOL_DTOOLUTIL ostream & -operator << (ostream &out, const wstring &str); +INLINE EXPCL_DTOOL_DTOOLUTIL std::ostream & +operator << (std::ostream &out, const std::wstring &str); #include "textEncoder.I" diff --git a/dtool/src/dtoolutil/unicodeLatinMap.cxx b/dtool/src/dtoolutil/unicodeLatinMap.cxx index 3fc1e3cb1c..87c9cb5a7d 100644 --- a/dtool/src/dtoolutil/unicodeLatinMap.cxx +++ b/dtool/src/dtoolutil/unicodeLatinMap.cxx @@ -1392,7 +1392,7 @@ look_up(wchar_t character) { if (ci != _by_character->end()) { return (*ci).second; } - return NULL; + return nullptr; } } diff --git a/dtool/src/dtoolutil/win32ArgParser.cxx b/dtool/src/dtoolutil/win32ArgParser.cxx index 84ddb785a6..4faf6bff95 100644 --- a/dtool/src/dtoolutil/win32ArgParser.cxx +++ b/dtool/src/dtoolutil/win32ArgParser.cxx @@ -24,12 +24,14 @@ #include #include +using std::string; + /** * */ Win32ArgParser:: Win32ArgParser() : - _argv(NULL), + _argv(nullptr), _argc(0) { } @@ -50,12 +52,12 @@ void Win32ArgParser:: clear() { assert(_argc == (int)_args.size()); - if (_argv != NULL) { + if (_argv != nullptr) { for (int i = 0; i < _argc; ++i) { PANDA_FREE_ARRAY(_argv[i]); } PANDA_FREE_ARRAY(_argv); - _argv = NULL; + _argv = nullptr; } _argc = 0; @@ -80,7 +82,7 @@ set_command_line(const string &command_line) { } } - assert(_argc == 0 && _argv == NULL); + assert(_argc == 0 && _argv == nullptr); _argc = (int)_args.size(); _argv = (char **)PANDA_MALLOC_ARRAY(_argc * sizeof(char *)); for (int i = 0; i < _argc; ++i) { @@ -97,7 +99,7 @@ set_command_line(const string &command_line) { * starts parsing this into argc, argv. */ void Win32ArgParser:: -set_command_line(const wstring &command_line) { +set_command_line(const std::wstring &command_line) { TextEncoder encoder; encoder.set_encoding(Filename::get_filesystem_encoding()); encoder.set_wtext(command_line); @@ -146,7 +148,7 @@ do_glob() { // means to do it. string envvar = ExecutionEnvironment::get_environment_variable("PANDA_GLOB"); if (!envvar.empty()) { - istringstream strm(envvar); + std::istringstream strm(envvar); int value; strm >> value; if (!strm.fail()) { diff --git a/dtool/src/dtoolutil/win32ArgParser.h b/dtool/src/dtoolutil/win32ArgParser.h index b7d427a81f..b4cfdecbf9 100644 --- a/dtool/src/dtoolutil/win32ArgParser.h +++ b/dtool/src/dtoolutil/win32ArgParser.h @@ -37,8 +37,8 @@ public: void clear(); - void set_command_line(const string &command_line); - void set_command_line(const wstring &command_line); + void set_command_line(const std::string &command_line); + void set_command_line(const std::wstring &command_line); void set_system_command_line(); char **get_argv(); @@ -47,9 +47,9 @@ public: static bool do_glob(); private: - string parse_quoted_arg(const char *&p); + std::string parse_quoted_arg(const char *&p); void parse_unquoted_arg(const char *&p); - void save_arg(const string &arg); + void save_arg(const std::string &arg); typedef vector_string Args; Args _args; diff --git a/dtool/src/interrogate/functionRemap.cxx b/dtool/src/interrogate/functionRemap.cxx index 42a420644f..e7a2f828d9 100644 --- a/dtool/src/interrogate/functionRemap.cxx +++ b/dtool/src/interrogate/functionRemap.cxx @@ -32,6 +32,10 @@ #include "interrogateType.h" #include "pnotify.h" +using std::ostream; +using std::ostringstream; +using std::string; + /** * */ @@ -39,7 +43,7 @@ FunctionRemap:: FunctionRemap(const InterrogateType &itype, const InterrogateFunction &ifunc, CPPInstance *cppfunc, int num_default_parameters, InterfaceMaker *interface_maker) { - _return_type = (ParameterRemap *)NULL; + _return_type = nullptr; _void_return = true; _ForcedVoidReturn = false; _has_this = false; @@ -117,7 +121,7 @@ call_function(ostream &out, int indent_level, bool convert_result, if (_type == T_destructor) { // A destructor wrapper is just a wrapper around the delete operator. assert(!container.empty()); - assert(_cpptype != (CPPType *)NULL); + assert(_cpptype != nullptr); if (TypeManager::is_reference_count(_cpptype)) { // Except for a reference-count type object, in which case the @@ -279,7 +283,7 @@ call_function(ostream &out, int indent_level, bool convert_result, void FunctionRemap:: write_orig_prototype(ostream &out, int indent_level, bool local, int num_default_args) const { if (local) { - _cppfunc->output(out, indent_level, NULL, false, num_default_args); + _cppfunc->output(out, indent_level, nullptr, false, num_default_args); } else { _cppfunc->output(out, indent_level, &parser, false, num_default_args); } @@ -299,7 +303,7 @@ make_wrapper_entry(FunctionIndex function_index) { iwrapper._name = _wrapper_name; iwrapper._unique_name = _unique_name; - if (_cppfunc->_leading_comment != (CPPCommentBlock *)NULL) { + if (_cppfunc->_leading_comment != nullptr) { iwrapper._comment = InterrogateBuilder::trim_blanks(_cppfunc->_leading_comment->_comment); } @@ -395,7 +399,7 @@ get_call_str(const string &container, const vector_string &pexprs) const { // It's not possible to assign arrays in C++, we have to copy them. CPPArrayType *array_type = _parameters[_first_true_parameter]._remap->get_orig_type()->as_array_type(); - if (array_type != NULL) { + if (array_type != nullptr) { call << "std::copy(" << expr << ", " << expr << " + " << *array_type->_bounds << ", "; } else { call << expr << " = "; @@ -404,7 +408,7 @@ get_call_str(const string &container, const vector_string &pexprs) const { _parameters[_first_true_parameter]._remap->pass_parameter(call, get_parameter_expr(_first_true_parameter, pexprs)); - if (array_type != NULL) { + if (array_type != nullptr) { call << ')'; } @@ -439,7 +443,10 @@ get_call_str(const string &container, const vector_string &pexprs) const { call << ")." << _cppfunc->get_local_name(); } else { - call << _cppfunc->get_local_name(&parser); + if (_cpptype != nullptr) { + call << _cpptype->get_local_name(&parser); + } + call << "::" << _cppfunc->get_local_name(); } } call << "("; @@ -490,7 +497,7 @@ get_min_num_args() const { } for (; pi != _parameters.end(); ++pi) { ParameterRemap *param = (*pi)._remap; - if (param->get_default_value() != (CPPExpression *)NULL) { + if (param->get_default_value() != nullptr) { // We've reached the first parameter that takes a default value. break; } else { @@ -567,7 +574,7 @@ setup_properties(const InterrogateFunction &ifunc, InterfaceMaker *interface_mak string fname = _cppfunc->get_simple_name(); CPPType *rtype = _ftype->_return_type->resolve_type(&parser, _cppscope); - if (_cpptype != (CPPType *)NULL && + if (_cpptype != nullptr && ((_cppfunc->_storage_class & CPPInstance::SC_static) == 0) && _type != T_constructor) { @@ -609,10 +616,10 @@ setup_properties(const InterrogateFunction &ifunc, InterfaceMaker *interface_mak fname == "operator >>=") { _type = T_assignment_method; - } else if (fname == "operator []" && !_const_method && rtype != NULL) { + } else if (fname == "operator []" && !_const_method && rtype != nullptr) { // Check if this is an item-assignment operator. CPPReferenceType *reftype = rtype->as_reference_type(); - if (reftype != NULL && reftype->_pointing_at->as_const_type() == NULL) { + if (reftype != nullptr && reftype->_pointing_at->as_const_type() == nullptr) { // It returns a mutable reference. _type = T_item_assignment_operator; } @@ -638,7 +645,7 @@ setup_properties(const InterrogateFunction &ifunc, InterfaceMaker *interface_mak } param._remap = interface_maker->remap_parameter(_cpptype, type); - if (param._remap == (ParameterRemap *)NULL) { + if (param._remap == nullptr) { // If we can't handle one of the parameter types, we can't call the // function. if (fname == "__traverse__") { @@ -666,13 +673,13 @@ setup_properties(const InterrogateFunction &ifunc, InterfaceMaker *interface_mak // by the parser, but we know they actually return a new concrete // instance. - if (_cpptype == (CPPType *)NULL) { + if (_cpptype == nullptr) { nout << "Method " << *_cppfunc << " has no struct type\n"; return false; } _return_type = interface_maker->remap_parameter(_cpptype, _cpptype); - if (_return_type != (ParameterRemap *)NULL) { + if (_return_type != nullptr) { _void_return = false; } @@ -681,13 +688,13 @@ setup_properties(const InterrogateFunction &ifunc, InterfaceMaker *interface_mak // return *this, which is a semi-standard C++ convention anyway. We just // enforce it. - if (_cpptype == (CPPType *)NULL) { + if (_cpptype == nullptr) { nout << "Method " << *_cppfunc << " has no struct type\n"; return false; } else { CPPType *ref_type = CPPType::new_type(new CPPReferenceType(_cpptype)); _return_type = interface_maker->remap_parameter(_cpptype, ref_type); - if (_return_type != (ParameterRemap *)NULL) { + if (_return_type != nullptr) { _void_return = false; } } @@ -697,7 +704,7 @@ setup_properties(const InterrogateFunction &ifunc, InterfaceMaker *interface_mak // scripting languages, so we use this to denote item-access operators // that return a non-const reference. - if (_cpptype == (CPPType *)NULL) { + if (_cpptype == nullptr) { nout << "Method " << *_cppfunc << " has no struct type\n"; return false; } else { @@ -711,7 +718,7 @@ setup_properties(const InterrogateFunction &ifunc, InterfaceMaker *interface_mak param._name = "assign_val"; param._remap = interface_maker->remap_parameter(_cpptype, ref_type); - if (param._remap == NULL || !param._remap->is_valid()) { + if (param._remap == nullptr || !param._remap->is_valid()) { nout << "Invalid remap for assignment type of method " << *_cppfunc << "\n"; return false; } @@ -726,12 +733,12 @@ setup_properties(const InterrogateFunction &ifunc, InterfaceMaker *interface_mak } else { // The normal case. _return_type = interface_maker->remap_parameter(_cpptype, rtype); - if (_return_type != (ParameterRemap *)NULL) { + if (_return_type != nullptr) { _void_return = TypeManager::is_void(rtype); } } - if (_return_type == (ParameterRemap *)NULL || + if (_return_type == nullptr || !_return_type->is_valid()) { // If our return type isn't something we can deal with, treat the function // as if it returns NULL. @@ -739,7 +746,7 @@ setup_properties(const InterrogateFunction &ifunc, InterfaceMaker *interface_mak _ForcedVoidReturn = true; CPPType *void_type = TypeManager::get_void_type(); _return_type = interface_maker->remap_parameter(_cpptype, void_type); - assert(_return_type != (ParameterRemap *)NULL); + assert(_return_type != nullptr); } // Do we need to manage the return value? @@ -767,12 +774,12 @@ setup_properties(const InterrogateFunction &ifunc, InterfaceMaker *interface_mak } // Check for a special meaning by name and signature. - int first_param = 0; + size_t first_param = 0; if (_has_this) { first_param = 1; } - if (_parameters.size() > (size_t)first_param && _parameters[first_param]._name == "self" && + if (_parameters.size() > first_param && _parameters[first_param]._name == "self" && TypeManager::is_pointer_to_PyObject(_parameters[first_param]._remap->get_orig_type())) { // Here's a special case. If the first parameter of a nonstatic method // is a PyObject * called "self", then we will automatically fill it in @@ -782,10 +789,10 @@ setup_properties(const InterrogateFunction &ifunc, InterfaceMaker *interface_mak _flags |= F_explicit_self; } - if ((int)_parameters.size() == first_param) { + if (_parameters.size() == first_param) { _args_type = InterfaceMaker::AT_no_args; - } else if ((int)_parameters.size() == first_param + 1 && - _parameters[first_param]._remap->get_default_value() == NULL) { + } else if (_parameters.size() == first_param + 1 && + _parameters[first_param]._remap->get_default_value() == nullptr) { _args_type = InterfaceMaker::AT_single_arg; } else { _args_type = InterfaceMaker::AT_varargs; @@ -833,7 +840,7 @@ setup_properties(const InterrogateFunction &ifunc, InterfaceMaker *interface_mak } } else if (fname == "size" || fname == "__len__") { - if ((int)_parameters.size() == first_param && + if (_parameters.size() == first_param && TypeManager::is_integer(_return_type->get_new_type())) { // It receives no parameters, and returns an integer. _flags |= F_size; @@ -847,7 +854,7 @@ setup_properties(const InterrogateFunction &ifunc, InterfaceMaker *interface_mak } } else if (fname == "__iter__") { - if ((int)_parameters.size() == first_param && + if (_parameters.size() == first_param && TypeManager::is_pointer(_return_type->get_new_type())) { // It receives no parameters, and returns a pointer. _flags |= F_iter; @@ -870,7 +877,7 @@ setup_properties(const InterrogateFunction &ifunc, InterfaceMaker *interface_mak if (_args_type == InterfaceMaker::AT_varargs) { // Of course methods named "make" can still take kwargs, if they are // named. - for (int i = first_param; i < _parameters.size(); ++i) { + for (size_t i = first_param; i < _parameters.size(); ++i) { if (_parameters[i]._has_name) { _args_type = InterfaceMaker::AT_keyword_args; break; @@ -904,7 +911,7 @@ setup_properties(const InterrogateFunction &ifunc, InterfaceMaker *interface_mak if (_args_type == InterfaceMaker::AT_varargs) { // Every other method can take keyword arguments, if they take more // than one argument, and the arguments are named. - for (int i = first_param; i < _parameters.size(); ++i) { + for (size_t i = first_param; i < _parameters.size(); ++i) { if (_parameters[i]._has_name) { _args_type |= InterfaceMaker::AT_keyword_args; break; @@ -960,7 +967,7 @@ setup_properties(const InterrogateFunction &ifunc, InterfaceMaker *interface_mak // Constructors always take varargs, and possibly keyword args. _args_type = InterfaceMaker::AT_varargs; - for (int i = first_param; i < _parameters.size(); ++i) { + for (size_t i = first_param; i < _parameters.size(); ++i) { if (_parameters[i]._has_name) { _args_type = InterfaceMaker::AT_keyword_args; break; diff --git a/dtool/src/interrogate/functionRemap.h b/dtool/src/interrogate/functionRemap.h index b4b8aea6dd..61ce48bcb6 100644 --- a/dtool/src/interrogate/functionRemap.h +++ b/dtool/src/interrogate/functionRemap.h @@ -48,19 +48,19 @@ public: InterfaceMaker *interface_maker); ~FunctionRemap(); - string get_parameter_name(int n) const; - string call_function(ostream &out, int indent_level, - bool convert_result, const string &container) const; - string call_function(ostream &out, int indent_level, - bool convert_result, const string &container, + std::string get_parameter_name(int n) const; + std::string call_function(std::ostream &out, int indent_level, + bool convert_result, const std::string &container) const; + std::string call_function(std::ostream &out, int indent_level, + bool convert_result, const std::string &container, const vector_string &pexprs) const; - void write_orig_prototype(ostream &out, int indent_level, bool local=false, + void write_orig_prototype(std::ostream &out, int indent_level, bool local=false, int num_default_args=0) const; FunctionWrapperIndex make_wrapper_entry(FunctionIndex function_index); - string get_call_str(const string &container, const vector_string &pexprs) const; + std::string get_call_str(const std::string &container, const vector_string &pexprs) const; int get_min_num_args() const; int get_max_num_args() const; @@ -68,7 +68,7 @@ public: class Parameter { public: bool _has_name; - string _name; + std::string _name; ParameterRemap *_remap; }; @@ -103,7 +103,7 @@ public: F_explicit_args = 0x8000, }; - typedef vector Parameters; + typedef std::vector Parameters; Parameters _parameters; ParameterRemap *_return_type; @@ -118,12 +118,12 @@ public: Type _type; int _flags; int _args_type; - string _expression; - string _function_signature; - string _hash; - string _unique_name; - string _reported_name; - string _wrapper_name; + std::string _expression; + std::string _function_signature; + std::string _hash; + std::string _unique_name; + std::string _reported_name; + std::string _wrapper_name; FunctionWrapperIndex _wrapper_index; bool _return_value_needs_management; @@ -138,7 +138,7 @@ public: bool _is_valid; private: - string get_parameter_expr(size_t n, const vector_string &pexprs) const; + std::string get_parameter_expr(size_t n, const vector_string &pexprs) const; bool setup_properties(const InterrogateFunction &ifunc, InterfaceMaker *interface_maker); }; diff --git a/dtool/src/interrogate/functionWriter.cxx b/dtool/src/interrogate/functionWriter.cxx index 6a5c3e4e34..58937d3f3d 100644 --- a/dtool/src/interrogate/functionWriter.cxx +++ b/dtool/src/interrogate/functionWriter.cxx @@ -30,7 +30,7 @@ FunctionWriter:: /** * */ -const string &FunctionWriter:: +const std::string &FunctionWriter:: get_name() const { return _name; } @@ -42,7 +42,7 @@ int FunctionWriter:: compare_to(const FunctionWriter &other) const { // Lexicographical string comparison. - string::const_iterator n1, n2; + std::string::const_iterator n1, n2; n1 = _name.begin(); n2 = other._name.begin(); while (n1 != _name.end() && n2 != other._name.end()) { @@ -65,12 +65,12 @@ compare_to(const FunctionWriter &other) const { * Outputs the prototype for the function. */ void FunctionWriter:: -write_prototype(ostream &) { +write_prototype(std::ostream &) { } /** * Outputs the code for the function. */ void FunctionWriter:: -write_code(ostream &) { +write_code(std::ostream &) { } diff --git a/dtool/src/interrogate/functionWriter.h b/dtool/src/interrogate/functionWriter.h index 11d4c90252..da2930ae0e 100644 --- a/dtool/src/interrogate/functionWriter.h +++ b/dtool/src/interrogate/functionWriter.h @@ -26,14 +26,14 @@ public: FunctionWriter(); virtual ~FunctionWriter(); - const string &get_name() const; + const std::string &get_name() const; virtual int compare_to(const FunctionWriter &other) const; - virtual void write_prototype(ostream &out); - virtual void write_code(ostream &out); + virtual void write_prototype(std::ostream &out); + virtual void write_code(std::ostream &out); protected: - string _name; + std::string _name; }; #endif diff --git a/dtool/src/interrogate/functionWriterPtrFromPython.cxx b/dtool/src/interrogate/functionWriterPtrFromPython.cxx index d39d5f47dd..016d79cff7 100644 --- a/dtool/src/interrogate/functionWriterPtrFromPython.cxx +++ b/dtool/src/interrogate/functionWriterPtrFromPython.cxx @@ -43,7 +43,7 @@ FunctionWriterPtrFromPython:: * Outputs the prototype for the function. */ void FunctionWriterPtrFromPython:: -write_prototype(ostream &out) { +write_prototype(std::ostream &out) { CPPType *ppointer = new CPPPointerType(_pointer_type); out << "static int " << _name << "(PyObject *obj, "; @@ -57,20 +57,20 @@ write_prototype(ostream &out) { * Outputs the code for the function. */ void FunctionWriterPtrFromPython:: -write_code(ostream &out) { +write_code(std::ostream &out) { CPPType *ppointer = new CPPPointerType(_pointer_type); out << "static int\n" << _name << "(PyObject *obj, "; ppointer->output_instance(out, "addr", &parser); out << ") {\n" - << " if (obj != (PyObject *)NULL && PyInstance_Check(obj)) {\n" + << " if (obj != nullptr && PyInstance_Check(obj)) {\n" // << " PyClassObject *in_class = ((PyInstanceObject // *)obj)->in_class;\n" << " PyObject *in_dict = ((PyInstanceObject *)obj)->in_dict;\n" - << " if (in_dict != (PyObject *)NULL && PyDict_Check(in_dict)) {\n" + << " if (in_dict != nullptr && PyDict_Check(in_dict)) {\n" << " PyObject *thisobj = PyDict_GetItemString(in_dict, \"this\");\n" - << " if (thisobj != (PyObject *)NULL && PyLong_Check(thisobj)) {\n" + << " if (thisobj != nullptr && PyLong_Check(thisobj)) {\n" << " (*addr) = (" << _pointer_type->get_local_name(&parser) << ")PyLong_AsVoidPtr(thisobj);\n" << " return 1;\n" diff --git a/dtool/src/interrogate/functionWriterPtrFromPython.h b/dtool/src/interrogate/functionWriterPtrFromPython.h index 36f59fa955..ca74f1dfdc 100644 --- a/dtool/src/interrogate/functionWriterPtrFromPython.h +++ b/dtool/src/interrogate/functionWriterPtrFromPython.h @@ -28,8 +28,8 @@ public: FunctionWriterPtrFromPython(CPPType *type); virtual ~FunctionWriterPtrFromPython(); - virtual void write_prototype(ostream &out); - virtual void write_code(ostream &out); + virtual void write_prototype(std::ostream &out); + virtual void write_code(std::ostream &out); CPPType *get_type() const; CPPType *get_pointer_type() const; diff --git a/dtool/src/interrogate/functionWriterPtrToPython.cxx b/dtool/src/interrogate/functionWriterPtrToPython.cxx index 23a8304528..e2486dae7c 100644 --- a/dtool/src/interrogate/functionWriterPtrToPython.cxx +++ b/dtool/src/interrogate/functionWriterPtrToPython.cxx @@ -44,7 +44,7 @@ FunctionWriterPtrToPython:: * Outputs the prototype for the function. */ void FunctionWriterPtrToPython:: -write_prototype(ostream &out) { +write_prototype(std::ostream &out) { out << "static PyObject *" << _name << "("; _pointer_type->output_instance(out, "addr", &parser); out << ", int caller_manages);\n"; @@ -54,16 +54,16 @@ write_prototype(ostream &out) { * Outputs the code for the function. */ void FunctionWriterPtrToPython:: -write_code(ostream &out) { - string classobj_func = InterfaceMakerPythonObj::get_builder_name(_type); +write_code(std::ostream &out) { + std::string classobj_func = InterfaceMakerPythonObj::get_builder_name(_type); out << "static PyObject *\n" << _name << "("; _pointer_type->output_instance(out, "addr", &parser); out << ", int caller_manages) {\n" << " PyObject *" << classobj_func << "();\n" << " PyObject *classobj = " << classobj_func << "();\n" - << " PyInstanceObject *instance = (PyInstanceObject *)PyInstance_New(classobj, (PyObject *)NULL, (PyObject *)NULL);\n" - << " if (instance != (PyInstanceObject *)NULL) {\n" + << " PyInstanceObject *instance = (PyInstanceObject *)PyInstance_New(classobj, nullptr, nullptr);\n" + << " if (instance != nullptr) {\n" << " PyObject *thisptr = PyLong_FromVoidPtr((void*)addr);\n" << " PyDict_SetItemString(instance->in_dict, \"this\", thisptr);\n" << " }\n" diff --git a/dtool/src/interrogate/functionWriterPtrToPython.h b/dtool/src/interrogate/functionWriterPtrToPython.h index d36e025da1..f563d4fccb 100644 --- a/dtool/src/interrogate/functionWriterPtrToPython.h +++ b/dtool/src/interrogate/functionWriterPtrToPython.h @@ -27,8 +27,8 @@ public: FunctionWriterPtrToPython(CPPType *type); virtual ~FunctionWriterPtrToPython(); - virtual void write_prototype(ostream &out); - virtual void write_code(ostream &out); + virtual void write_prototype(std::ostream &out); + virtual void write_code(std::ostream &out); CPPType *get_pointer_type() const; private: diff --git a/dtool/src/interrogate/functionWriters.cxx b/dtool/src/interrogate/functionWriters.cxx index 93ee5945fc..2d1d167b2d 100644 --- a/dtool/src/interrogate/functionWriters.cxx +++ b/dtool/src/interrogate/functionWriters.cxx @@ -41,7 +41,7 @@ FunctionWriters:: */ FunctionWriter *FunctionWriters:: add_writer(FunctionWriter *writer) { - pair result = _writers.insert(writer); + std::pair result = _writers.insert(writer); if (!result.second) { // Already there; delete the pointer. delete writer; @@ -55,7 +55,7 @@ add_writer(FunctionWriter *writer) { * Generates prototypes for all of the functions. */ void FunctionWriters:: -write_prototypes(ostream &out) { +write_prototypes(std::ostream &out) { Writers::iterator wi; for (wi = _writers.begin(); wi != _writers.end(); ++wi) { FunctionWriter *writer = (*wi); @@ -67,7 +67,7 @@ write_prototypes(ostream &out) { * Generates all of the functions. */ void FunctionWriters:: -write_code(ostream &out) { +write_code(std::ostream &out) { Writers::iterator wi; for (wi = _writers.begin(); wi != _writers.end(); ++wi) { FunctionWriter *writer = (*wi); diff --git a/dtool/src/interrogate/functionWriters.h b/dtool/src/interrogate/functionWriters.h index 0db121de10..2da07ecd9c 100644 --- a/dtool/src/interrogate/functionWriters.h +++ b/dtool/src/interrogate/functionWriters.h @@ -31,8 +31,8 @@ public: FunctionWriter *add_writer(FunctionWriter *writer); - void write_prototypes(ostream &out); - void write_code(ostream &out); + void write_prototypes(std::ostream &out); + void write_code(std::ostream &out); protected: class IndirectCompareTo { @@ -42,7 +42,7 @@ protected: } }; - typedef set Writers; + typedef std::set Writers; Writers _writers; }; diff --git a/dtool/src/interrogate/interfaceMaker.cxx b/dtool/src/interrogate/interfaceMaker.cxx index 218affd565..0d4d56dfc1 100644 --- a/dtool/src/interrogate/interfaceMaker.cxx +++ b/dtool/src/interrogate/interfaceMaker.cxx @@ -39,6 +39,10 @@ #include "cppStructType.h" #include "pnotify.h" +using std::ostream; +using std::ostringstream; +using std::string; + InterrogateType dummy_type; /** @@ -315,7 +319,7 @@ write_module(ostream &, ostream *out_h, InterrogateModuleDef *) { */ ParameterRemap *InterfaceMaker:: remap_parameter(CPPType *struct_type, CPPType *param_type) { - nassertr(param_type != NULL, NULL); + nassertr(param_type != nullptr, nullptr); if (convert_strings) { if (TypeManager::is_char_pointer(param_type)) { @@ -328,7 +332,7 @@ remap_parameter(CPPType *struct_type, CPPType *param_type) { // If we're exporting a method of basic_string itself, don't convert // basic_string's to atomic strings. - if (struct_type == (CPPType *)NULL || + if (struct_type == nullptr || !(TypeManager::is_basic_string_char(struct_type) || TypeManager::is_basic_string_wchar(struct_type))) { if (TypeManager::is_basic_string_char(param_type)) { @@ -359,11 +363,11 @@ remap_parameter(CPPType *struct_type, CPPType *param_type) { CPPType *pt_type = TypeManager::unwrap(param_type); if (TypeManager::is_basic_string_char(pt_type) || TypeManager::is_basic_string_wchar(pt_type)) { - return (ParameterRemap *)NULL; + return nullptr; } } } - if (struct_type == (CPPType *)NULL || + if (struct_type == nullptr || !TypeManager::is_vector_unsigned_char(struct_type)) { if (TypeManager::is_vector_unsigned_char(param_type)) { if (TypeManager::is_reference(param_type)) { @@ -385,7 +389,7 @@ remap_parameter(CPPType *struct_type, CPPType *param_type) { // Don't convert PointerTo<>'s to pointers for methods of the PointerTo // itself! - if (struct_type == (CPPType *)NULL || + if (struct_type == nullptr || !(pt_type->get_local_name(&parser) == struct_type->get_local_name(&parser))) { return new ParameterRemapPTToPointer(param_type); } @@ -417,7 +421,7 @@ remap_parameter(CPPType *struct_type, CPPType *param_type) { } else { // Here's something we have a problem with. - return (ParameterRemap *)NULL; + return nullptr; } } @@ -460,7 +464,7 @@ wrap_global_functions() { * added to the end. */ void InterfaceMaker:: -get_function_remaps(vector &remaps) { +get_function_remaps(std::vector &remaps) { FunctionsByIndex::iterator fi; for (fi = _functions.begin(); fi != _functions.end(); ++fi) { Function *func = (*fi).second; @@ -512,7 +516,7 @@ make_function_remap(const InterrogateType &itype, // No such FunctionRemap is valid. Return NULL. delete remap; - return (FunctionRemap *)NULL; + return nullptr; } /** @@ -576,7 +580,7 @@ record_function(const InterrogateType &itype, FunctionIndex func_index) { // printf(" Function Name = %s\n", ifunc.get_name().c_str()); // Now get all the valid FunctionRemaps for the function. - if (ifunc._instances != (InterrogateFunction::Instances *)NULL) { + if (ifunc._instances != nullptr) { InterrogateFunction::Instances::const_iterator ii; for (ii = ifunc._instances->begin(); ii != ifunc._instances->end(); ++ii) { CPPInstance *cppfunc = (*ii).second; @@ -591,7 +595,7 @@ record_function(const InterrogateType &itype, FunctionIndex func_index) { pi != parameters->_parameters.rend(); ++pi) { CPPInstance *param = (*pi); - if (param->_initializer != (CPPExpression *)NULL) { + if (param->_initializer != nullptr) { // This parameter has a default value. max_default_parameters++; } else { @@ -610,7 +614,7 @@ record_function(const InterrogateType &itype, FunctionIndex func_index) { num_default_parameters++) { FunctionRemap *remap = make_function_remap(itype, ifunc, cppfunc, num_default_parameters); - if (remap != (FunctionRemap *)NULL) { + if (remap != nullptr) { func->_remaps.push_back(remap); @@ -654,7 +658,7 @@ InterfaceMaker::Object *InterfaceMaker:: record_object(TypeIndex type_index) { if (type_index == 0) { // An invalid type. - return (Object *)NULL; + return nullptr; } Objects::iterator oi = _objects.find(type_index); @@ -665,7 +669,6 @@ record_object(TypeIndex type_index) { InterrogateDatabase *idb = InterrogateDatabase::get_ptr(); const InterrogateType &itype = idb->get_type(type_index); - assert(&itype != NULL); Object *object = new Object(itype); bool inserted = _objects.insert(Objects::value_type(type_index, object)).second; @@ -756,8 +759,7 @@ manage_return_value(ostream &out, int indent_level, out << " = " << return_expr << ";\n"; indent(out, indent_level) - << "if (" << return_expr << " != (" - << remap->_return_type->get_new_type()->get_local_name(&parser) << ")NULL) {\n"; + << "if (" << return_expr << " != nullptr) {\n"; indent(out, indent_level + 2) << "(" << return_expr << ")->ref();\n"; indent(out, indent_level) @@ -814,8 +816,7 @@ output_ref(ostream &out, int indent_level, FunctionRemap *remap, // attempt to ref it. indent(out, indent_level) - << "if (" << varname << " != (" - << remap->_return_type->get_new_type()->get_local_name(&parser) << ")NULL) {\n"; + << "if (" << varname << " != nullptr) {\n"; indent(out, indent_level + 2) << varname << "->ref();\n"; indent(out, indent_level) @@ -848,8 +849,7 @@ output_unref(ostream &out, int indent_level, FunctionRemap *remap, // attempt to ref it. indent(out, indent_level) - << "if (" << varname << " != (" - << remap->_return_type->get_new_type()->get_local_name(&parser) << ")NULL) {\n"; + << "if (" << varname << " != nullptr) {\n"; if (TypeManager::is_pointer_to_base(remap->_return_type->get_temporary_type())) { // We're sure the reference count won't reach zero since we have it @@ -885,7 +885,7 @@ hash_function_signature(FunctionRemap *remap) { return; } - if ((*hi).second != (FunctionRemap *)NULL && + if ((*hi).second != nullptr && (*hi).second->_function_signature == remap->_function_signature) { // The same function signature has already appeared. This shouldn't // happen. @@ -897,9 +897,9 @@ hash_function_signature(FunctionRemap *remap) { } // We have a conflict. Extend both strings to resolve the ambiguity. - if ((*hi).second != (FunctionRemap *)NULL) { + if ((*hi).second != nullptr) { FunctionRemap *other_remap = (*hi).second; - (*hi).second = (FunctionRemap *)NULL; + (*hi).second = nullptr; other_remap->_hash += InterrogateBuilder::hash_string(other_remap->_function_signature, 11); bool inserted = _wrappers_by_hash.insert diff --git a/dtool/src/interrogate/interfaceMaker.h b/dtool/src/interrogate/interfaceMaker.h index f6b4730609..e439105ea1 100644 --- a/dtool/src/interrogate/interfaceMaker.h +++ b/dtool/src/interrogate/interfaceMaker.h @@ -51,12 +51,12 @@ public: virtual void generate_wrappers(); - virtual void write_includes(ostream &out); - virtual void write_prototypes(ostream &out, ostream *out_h); - virtual void write_functions(ostream &out); - virtual void write_module_support(ostream &out, ostream *out_h, InterrogateModuleDef *def) {}; + virtual void write_includes(std::ostream &out); + virtual void write_prototypes(std::ostream &out, std::ostream *out_h); + virtual void write_functions(std::ostream &out); + virtual void write_module_support(std::ostream &out, std::ostream *out_h, InterrogateModuleDef *def) {}; - virtual void write_module(ostream &out, ostream *out_h, InterrogateModuleDef *def); + virtual void write_module(std::ostream &out, std::ostream *out_h, InterrogateModuleDef *def); virtual ParameterRemap *remap_parameter(CPPType *struct_type, CPPType *param_type); @@ -64,9 +64,9 @@ public: virtual bool separate_overloading(); virtual bool wrap_global_functions(); - void get_function_remaps(vector &remaps); + void get_function_remaps(std::vector &remaps); - static ostream &indent(ostream &out, int indent_level); + static std::ostream &indent(std::ostream &out, int indent_level); public: // This contains information about the number of arguments that the wrapping @@ -92,42 +92,42 @@ public: class Function { public: - Function(const string &name, + Function(const std::string &name, const InterrogateType &itype, const InterrogateFunction &ifunc); ~Function(); - string _name; + std::string _name; const InterrogateType &_itype; const InterrogateFunction &_ifunc; - typedef vector Remaps; + typedef std::vector Remaps; Remaps _remaps; bool _has_this; int _flags; ArgsType _args_type; }; - typedef map FunctionsByIndex; - typedef vector Functions; + typedef std::map FunctionsByIndex; + typedef std::vector Functions; FunctionsByIndex _functions; class MakeSeq { public: - MakeSeq(const string &name, const InterrogateMakeSeq &imake_seq); + MakeSeq(const std::string &name, const InterrogateMakeSeq &imake_seq); const InterrogateMakeSeq &_imake_seq; - string _name; + std::string _name; Function *_length_getter; Function *_element_getter; }; - typedef vector MakeSeqs; + typedef std::vector MakeSeqs; class Property { public: Property(const InterrogateElement &ielement); const InterrogateElement &_ielement; - vector _getter_remaps; - vector _setter_remaps; + std::vector _getter_remaps; + std::vector _setter_remaps; Function *_length_function; Function *_has_function; Function *_clear_function; @@ -136,7 +136,7 @@ public: Function *_getkey_function; bool _has_this; }; - typedef vector Properties; + typedef std::vector Properties; class Object { public: @@ -144,7 +144,7 @@ public: ~Object(); void check_protocols(); - bool is_static_method(const string &name); + bool is_static_method(const std::string &name); const InterrogateType &_itype; Functions _constructors; @@ -162,10 +162,10 @@ public: }; int _protocol_types; }; - typedef map Objects; + typedef std::map Objects; Objects _objects; - typedef map WrappersByHash; + typedef std::map WrappersByHash; WrappersByHash _wrappers_by_hash; virtual FunctionRemap * @@ -173,12 +173,12 @@ public: const InterrogateFunction &ifunc, CPPInstance *cppfunc, int num_default_parameters); - virtual string + virtual std::string get_wrapper_name(const InterrogateType &itype, const InterrogateFunction &ifunc, FunctionIndex func_index); - virtual string get_wrapper_prefix(); - virtual string get_unique_prefix(); + virtual std::string get_wrapper_prefix(); + virtual std::string get_unique_prefix(); Function * record_function(const InterrogateType &itype, FunctionIndex func_index); @@ -192,19 +192,19 @@ public: void hash_function_signature(FunctionRemap *remap); - string - manage_return_value(ostream &out, int indent_level, - FunctionRemap *remap, const string &return_expr) const; + std::string + manage_return_value(std::ostream &out, int indent_level, + FunctionRemap *remap, const std::string &return_expr) const; void - delete_return_value(ostream &out, int indent_level, - FunctionRemap *remap, const string &return_expr) const; + delete_return_value(std::ostream &out, int indent_level, + FunctionRemap *remap, const std::string &return_expr) const; - void output_ref(ostream &out, int indent_level, FunctionRemap *remap, - const string &varname) const; - void output_unref(ostream &out, int indent_level, FunctionRemap *remap, - const string &varname) const; - void write_spam_message(ostream &out, FunctionRemap *remap) const; + void output_ref(std::ostream &out, int indent_level, FunctionRemap *remap, + const std::string &varname) const; + void output_unref(std::ostream &out, int indent_level, FunctionRemap *remap, + const std::string &varname) const; + void write_spam_message(std::ostream &out, FunctionRemap *remap) const; protected: InterrogateModuleDef *_def; diff --git a/dtool/src/interrogate/interfaceMakerC.cxx b/dtool/src/interrogate/interfaceMakerC.cxx index 966e9c058d..64b36fc366 100644 --- a/dtool/src/interrogate/interfaceMakerC.cxx +++ b/dtool/src/interrogate/interfaceMakerC.cxx @@ -24,6 +24,8 @@ #include "interrogateFunction.h" #include "cppFunctionType.h" +using std::ostream; + /** * */ @@ -115,7 +117,7 @@ synthesize_this_parameter() { /** * Returns the prefix string used to generate wrapper function names. */ -string InterfaceMakerC:: +std::string InterfaceMakerC:: get_wrapper_prefix() { return "_inC"; } @@ -124,7 +126,7 @@ get_wrapper_prefix() { * Returns the prefix string used to generate unique symbolic names, which are * not necessarily C-callable function names. */ -string InterfaceMakerC:: +std::string InterfaceMakerC:: get_unique_prefix() { return "c"; } @@ -206,7 +208,7 @@ write_function_instance(ostream &out, InterfaceMaker::Function *func, write_spam_message(out, remap); } - string return_expr = + std::string return_expr = remap->call_function(out, 2, true, "param0"); return_expr = manage_return_value(out, 2, remap, return_expr); if (!return_expr.empty()) { diff --git a/dtool/src/interrogate/interfaceMakerC.h b/dtool/src/interrogate/interfaceMakerC.h index 5eaf276815..91c8ef68bf 100644 --- a/dtool/src/interrogate/interfaceMakerC.h +++ b/dtool/src/interrogate/interfaceMakerC.h @@ -30,27 +30,27 @@ public: InterfaceMakerC(InterrogateModuleDef *def); virtual ~InterfaceMakerC(); - virtual void write_prototypes(ostream &out,ostream *out_h); - virtual void write_functions(ostream &out); + virtual void write_prototypes(std::ostream &out,std::ostream *out_h); + virtual void write_functions(std::ostream &out); virtual ParameterRemap *remap_parameter(CPPType *struct_type, CPPType *param_type); virtual bool synthesize_this_parameter(); protected: - virtual string get_wrapper_prefix(); - virtual string get_unique_prefix(); + virtual std::string get_wrapper_prefix(); + virtual std::string get_unique_prefix(); virtual void record_function_wrapper(InterrogateFunction &ifunc, FunctionWrapperIndex wrapper_index); private: - void write_prototype_for(ostream &out, Function *func); - void write_function_for(ostream &out, Function *func); - void write_function_instance(ostream &out, Function *func, + void write_prototype_for(std::ostream &out, Function *func); + void write_function_for(std::ostream &out, Function *func); + void write_function_instance(std::ostream &out, Function *func, FunctionRemap *remap); - void write_function_header(ostream &out, Function *func, + void write_function_header(std::ostream &out, Function *func, FunctionRemap *remap, bool newline); }; diff --git a/dtool/src/interrogate/interfaceMakerPython.cxx b/dtool/src/interrogate/interfaceMakerPython.cxx index 37125a7e64..cfd82edf19 100644 --- a/dtool/src/interrogate/interfaceMakerPython.cxx +++ b/dtool/src/interrogate/interfaceMakerPython.cxx @@ -28,7 +28,7 @@ InterfaceMakerPython(InterrogateModuleDef *def) : * particular interface to the indicated output stream. */ void InterfaceMakerPython:: -write_includes(ostream &out) { +write_includes(std::ostream &out) { InterfaceMaker::write_includes(out); out << "#undef _POSIX_C_SOURCE\n" << "#undef _XOPEN_SOURCE\n" @@ -45,7 +45,7 @@ write_includes(ostream &out) { * was executing, and report this failure back to Python. */ void InterfaceMakerPython:: -test_assert(ostream &out, int indent_level) const { +test_assert(std::ostream &out, int indent_level) const { if (watch_asserts) { out << "#ifndef NDEBUG\n"; indent(out, indent_level) @@ -57,13 +57,13 @@ test_assert(ostream &out, int indent_level) const { indent(out, indent_level + 2) << "notify->clear_assert_failed();\n"; indent(out, indent_level + 2) - << "return (PyObject *)NULL;\n"; + << "return nullptr;\n"; indent(out, indent_level) << "}\n"; indent(out, indent_level) << "if (PyErr_Occurred()) {\n"; indent(out, indent_level + 2) - << "return (PyObject *)NULL;\n"; + << "return nullptr;\n"; indent(out, indent_level) << "}\n"; out << "#endif\n"; diff --git a/dtool/src/interrogate/interfaceMakerPython.h b/dtool/src/interrogate/interfaceMakerPython.h index 2d9bb84376..612e9ced17 100644 --- a/dtool/src/interrogate/interfaceMakerPython.h +++ b/dtool/src/interrogate/interfaceMakerPython.h @@ -30,10 +30,10 @@ protected: InterfaceMakerPython(InterrogateModuleDef *def); public: - virtual void write_includes(ostream &out); + virtual void write_includes(std::ostream &out); protected: - virtual void test_assert(ostream &out, int indent_level) const; + virtual void test_assert(std::ostream &out, int indent_level) const; }; #endif diff --git a/dtool/src/interrogate/interfaceMakerPythonNative.cxx b/dtool/src/interrogate/interfaceMakerPythonNative.cxx index 5ae2d3fca9..3134fcb2eb 100644 --- a/dtool/src/interrogate/interfaceMakerPythonNative.cxx +++ b/dtool/src/interrogate/interfaceMakerPythonNative.cxx @@ -39,7 +39,17 @@ #include #include -extern InterrogateType dummy_type; +using std::dec; +using std::hex; +using std::max; +using std::min; +using std::oct; +using std::ostream; +using std::ostringstream; +using std::set; +using std::string; + +extern InterrogateType dummy_type; extern std::string EXPORT_IMPORT_PREFIX; #define CLASS_PREFIX "Dtool_" @@ -100,12 +110,7 @@ RenameSet methodRenameDictionary[] = { { "__deepcopy__" , "__deepcopy__", 0 }, { "print" , "Cprint", 0 }, { "CInterval.set_t", "_priv__cSetT", 0 }, - { NULL, NULL, -1 } -}; - -RenameSet classRenameDictionary[] = { - // No longer used, now empty. - { NULL, NULL, -1 } + { nullptr, nullptr, -1 } }; const char *pythonKeywords[] = { @@ -141,12 +146,12 @@ const char *pythonKeywords[] = { "while", "with", "yield", - NULL + nullptr }; std::string checkKeyword(std::string &cppName) { - for (int x = 0; pythonKeywords[x] != NULL; x++) { + for (int x = 0; pythonKeywords[x] != nullptr; x++) { if (cppName == pythonKeywords[x]) { return std::string("_") + cppName; } @@ -193,12 +198,6 @@ classNameFromCppName(const std::string &cppName, bool mangle) { } } - for (int x = 0; classRenameDictionary[x]._from != NULL; x++) { - if (cppName == classRenameDictionary[x]._from) { - className = classRenameDictionary[x]._to; - } - } - if (className.empty()) { std::string text = "** ERROR ** Renaming class: " + cppName + " to empty string"; printf("%s", text.c_str()); @@ -247,21 +246,12 @@ methodNameFromCppName(const std::string &cppName, const std::string &className, } } - for (int x = 0; methodRenameDictionary[x]._from != NULL; x++) { + for (int x = 0; methodRenameDictionary[x]._from != nullptr; x++) { if (origName == methodRenameDictionary[x]._from) { methodName = methodRenameDictionary[x]._to; } } - if (className.size() > 0) { - string lookup_name = className + '.' + cppName; - for (int x = 0; classRenameDictionary[x]._from != NULL; x++) { - if (lookup_name == methodRenameDictionary[x]._from) { - methodName = methodRenameDictionary[x]._to; - } - } - } - // # Mangle names that happen to be python keywords so they are not anymore methodName = checkKeyword(methodName); return methodName; @@ -296,7 +286,7 @@ std::string methodNameFromCppName(FunctionRemap *remap, const std::string &class bool InterfaceMakerPythonNative:: get_slotted_function_def(Object *obj, Function *func, FunctionRemap *remap, SlottedFunctionDef &def) { - if (obj == NULL) { + if (obj == nullptr) { // Only methods may be slotted. return false; } @@ -679,19 +669,14 @@ write_function_slot(ostream &out, int indent_level, const SlottedFunctions &slot void InterfaceMakerPythonNative:: get_valid_child_classes(std::map &answer, CPPStructType *inclass, const std::string &upcast_seed, bool can_downcast) { - if (inclass == NULL) { + if (inclass == nullptr) { return; } - CPPStructType::Derivation::const_iterator bi; - for (bi = inclass->_derivation.begin(); - bi != inclass->_derivation.end(); - ++bi) { - - const CPPStructType::Base &base = (*bi); + for (const CPPStructType::Base &base : inclass->_derivation) { // if (base._vis <= V_public) can_downcast = false; CPPStructType *base_type = TypeManager::resolve_type(base._base)->as_struct_type(); - if (base_type != NULL) { + if (base_type != nullptr) { std::string scoped_name = base_type->get_local_name(&parser); if (answer.find(scoped_name) == answer.end()) { @@ -722,7 +707,7 @@ get_valid_child_classes(std::map &answer, CPPStructTyp void InterfaceMakerPythonNative:: write_python_instance(ostream &out, int indent_level, const string &return_expr, bool owns_memory, const InterrogateType &itype, bool is_const) { - out << boolalpha; + out << std::boolalpha; if (!isExportThisRun(itype._cpptype)) { _external_imports.insert(TypeManager::resolve_type(itype._cpptype)); @@ -738,7 +723,7 @@ write_python_instance(ostream &out, int indent_level, const string &return_expr, // will be grabbing the type index (which would obviously crash when // called on a NULL pointer), so we do it here. indent(out, indent_level) - << "if (" << return_expr << " == NULL) {\n"; + << "if (" << return_expr << " == nullptr) {\n"; indent(out, indent_level) << " Py_INCREF(Py_None);\n"; indent(out, indent_level) @@ -751,7 +736,7 @@ write_python_instance(ostream &out, int indent_level, const string &return_expr, indent(out, indent_level) << " ReferenceCount *rc = " << return_expr << "->as_reference_count();\n"; indent(out, indent_level) - << " bool is_refcount = (rc != (ReferenceCount *)NULL);\n"; + << " bool is_refcount = (rc != nullptr);\n"; indent(out, indent_level) << " if (is_refcount) {\n"; indent(out, indent_level) @@ -806,16 +791,15 @@ void InterfaceMakerPythonNative:: write_prototypes(ostream &out_code, ostream *out_h) { Functions::iterator fi; - if (out_h != NULL) { + if (out_h != nullptr) { *out_h << "#include \"py_panda.h\"\n\n"; } /* - for (fi = _functions.begin(); fi != _functions.end(); ++fi) - { - Function *func = (*fi); - if (!func->_itype.is_global() && is_function_legal(func)) - write_prototype_for (out_code, func); + for (Function *func : _functions) { + if (!func->_itype.is_global() && is_function_legal(func)) { + write_prototype_for(out_code, func); + } } */ @@ -831,6 +815,11 @@ write_prototypes(ostream &out_code, ostream *out_h) { // _external_imports.insert(object->_itype._cpptype); } } + } else if (object->_itype.is_scoped_enum() && isExportThisRun(object->_itype._cpptype)) { + // Forward declare where we will put the scoped enum type. + string class_name = object->_itype._cpptype->get_local_name(&parser); + string safe_name = make_safe_name(class_name); + out_code << "static PyTypeObject *Dtool_Ptr_" << safe_name << " = nullptr;\n"; } } @@ -838,8 +827,7 @@ write_prototypes(ostream &out_code, ostream *out_h) { out_code << " * Extern declarations for imported classes\n"; out_code << " */\n"; - for (std::set::iterator ii = _external_imports.begin(); ii != _external_imports.end(); ii++) { - CPPType *type = (*ii); + for (CPPType *type : _external_imports) { string class_name = type->get_local_name(&parser); string safe_name = make_safe_name(class_name); @@ -862,24 +850,24 @@ write_prototypes(ostream &out_code, ostream *out_h) { if (TypeManager::is_reference_count(type)) { out_code << "inline static bool Dtool_ConstCoerce_" << safe_name << "(PyObject *args, CPT(" << class_name << ") &coerced) {\n" - << " nassertr(Dtool_Ptr_" << safe_name << " != NULL, false);\n" - << " nassertr(Dtool_Ptr_" << safe_name << "->_Dtool_ConstCoerce != NULL, false);\n" + << " nassertr(Dtool_Ptr_" << safe_name << " != nullptr, false);\n" + << " nassertr(Dtool_Ptr_" << safe_name << "->_Dtool_ConstCoerce != nullptr, false);\n" << " return ((bool (*)(PyObject *, CPT(" << class_name << ") &))Dtool_Ptr_" << safe_name << "->_Dtool_ConstCoerce)(args, coerced);\n" << "}\n"; if (has_coerce > 1) { out_code << "inline static bool Dtool_Coerce_" << safe_name << "(PyObject *args, PT(" << class_name << ") &coerced) {\n" - << " nassertr(Dtool_Ptr_" << safe_name << " != NULL, false);\n" - << " nassertr(Dtool_Ptr_" << safe_name << "->_Dtool_Coerce != NULL, false);\n" + << " nassertr(Dtool_Ptr_" << safe_name << " != nullptr, false);\n" + << " nassertr(Dtool_Ptr_" << safe_name << "->_Dtool_Coerce != nullptr, false);\n" << " return ((bool (*)(PyObject *, PT(" << class_name << ") &))Dtool_Ptr_" << safe_name << "->_Dtool_Coerce)(args, coerced);\n" << "}\n"; } } else { out_code << "inline static " << class_name << " *Dtool_Coerce_" << safe_name << "(PyObject *args, " << class_name << " &coerced) {\n" - << " nassertr(Dtool_Ptr_" << safe_name << " != NULL, NULL);\n" - << " nassertr(Dtool_Ptr_" << safe_name << "->_Dtool_Coerce != NULL, NULL);\n" + << " nassertr(Dtool_Ptr_" << safe_name << " != nullptr, nullptr);\n" + << " nassertr(Dtool_Ptr_" << safe_name << "->_Dtool_Coerce != nullptr, nullptr);\n" << " return ((" << class_name << " *(*)(PyObject *, " << class_name << " &))Dtool_Ptr_" << safe_name << "->_Dtool_Coerce)(args, coerced);\n" << "}\n"; } @@ -936,15 +924,13 @@ write_prototypes_class(ostream &out_code, ostream *out_h, Object *obj) { out_code << " */\n"; /* - for (fi = obj->_methods.begin(); fi != obj->_methods.end(); ++fi) { - Function *func = (*fi); + for (Function *func : obj->_methods) { write_prototype_for(out_code, func); } */ /* - for (fi = obj->_constructors.begin(); fi != obj->_constructors.end(); ++fi) { - Function *func = (*fi); + for (Function *func : obj->_constructors) { std::string fname = "int Dtool_Init_" + ClassName + "(PyObject *self, PyObject *args, PyObject *kwds)"; write_prototype_for_name(out_code, obj, func, fname); } @@ -966,7 +952,7 @@ write_functions(ostream &out) { for (fi = _functions.begin(); fi != _functions.end(); ++fi) { Function *func = (*fi).second; if (!func->_itype.is_global() && is_function_legal(func)) { - write_function_for_top(out, NULL, func); + write_function_for_top(out, nullptr, func); } } @@ -1003,9 +989,6 @@ write_functions(ostream &out) { */ void InterfaceMakerPythonNative:: write_class_details(ostream &out, Object *obj) { - Functions::iterator fi; - Function::Remaps::const_iterator ri; - // std::string cClassName = obj->_itype.get_scoped_name(); std::string ClassName = make_safe_name(obj->_itype.get_scoped_name()); std::string cClassName = obj->_itype.get_true_name(); @@ -1015,8 +998,7 @@ write_class_details(ostream &out, Object *obj) { out << " */\n"; // First write out all the wrapper functions for the methods. - for (fi = obj->_methods.begin(); fi != obj->_methods.end(); ++fi) { - Function *func = (*fi); + for (Function *func : obj->_methods) { if (func) { // Write the definition of the generic wrapper function for this // function. @@ -1025,18 +1007,13 @@ write_class_details(ostream &out, Object *obj) { } // Now write out generated getters and setters for the properties. - Properties::const_iterator pit; - for (pit = obj->_properties.begin(); pit != obj->_properties.end(); ++pit) { - Property *property = (*pit); - + for (Property *property : obj->_properties) { write_getset(out, obj, property); } // Write the constructors. std::string fname = "static int Dtool_Init_" + ClassName + "(PyObject *self, PyObject *args, PyObject *kwds)"; - for (fi = obj->_constructors.begin(); fi != obj->_constructors.end(); ++fi) { - Function *func = (*fi); - + for (Function *func : obj->_constructors) { string expected_params; write_function_for_name(out, obj, func->_remaps, fname, expected_params, true, AT_keyword_args, RF_int); } @@ -1062,17 +1039,16 @@ write_class_details(ostream &out, Object *obj) { } // Write make seqs: generated methods that return a sequence of items. - MakeSeqs::iterator msi; - for (msi = obj->_make_seqs.begin(); msi != obj->_make_seqs.end(); ++msi) { - if (is_function_legal((*msi)->_length_getter) && - is_function_legal((*msi)->_element_getter)) { - write_make_seq(out, obj, ClassName, cClassName, *msi); + for (MakeSeq *make_seq : obj->_make_seqs) { + if (is_function_legal(make_seq->_length_getter) && + is_function_legal(make_seq->_element_getter)) { + write_make_seq(out, obj, ClassName, cClassName, make_seq); } else { - if (!is_function_legal((*msi)->_length_getter)) { - cerr << "illegal length function for MAKE_SEQ: " << (*msi)->_length_getter->_name << "\n"; + if (!is_function_legal(make_seq->_length_getter)) { + std::cerr << "illegal length function for MAKE_SEQ: " << make_seq->_length_getter->_name << "\n"; } - if (!is_function_legal((*msi)->_element_getter)) { - cerr << "illegal element function for MAKE_SEQ: " << (*msi)->_element_getter->_name << "\n"; + if (!is_function_legal(make_seq->_element_getter)) { + std::cerr << "illegal element function for MAKE_SEQ: " << make_seq->_element_getter->_name << "\n"; } } } @@ -1096,8 +1072,8 @@ write_class_details(ostream &out, Object *obj) { out << "static void *Dtool_UpcastInterface_" << ClassName << "(PyObject *self, Dtool_PyTypedObject *requested_type) {\n"; out << " Dtool_PyTypedObject *type = DtoolInstance_TYPE(self);\n"; out << " if (type != &Dtool_" << ClassName << ") {\n"; - out << " printf(\"" << ClassName << " ** Bad Source Type-- Requesting Conversion from %s to %s\\n\", Py_TYPE(self)->tp_name, requested_type->_PyType.tp_name); fflush(NULL);\n";; - out << " return NULL;\n"; + out << " printf(\"" << ClassName << " ** Bad Source Type-- Requesting Conversion from %s to %s\\n\", Py_TYPE(self)->tp_name, requested_type->_PyType.tp_name); fflush(nullptr);\n";; + out << " return nullptr;\n"; out << " }\n"; out << "\n"; out << " " << cClassName << " *local_this = (" << cClassName << " *)DtoolInstance_VOID_PTR(self);\n"; @@ -1113,12 +1089,12 @@ write_class_details(ostream &out, Object *obj) { } } - out << " return NULL;\n"; + out << " return nullptr;\n"; out << "}\n\n"; out << "static void *Dtool_DowncastInterface_" << ClassName << "(void *from_this, Dtool_PyTypedObject *from_type) {\n"; - out << " if (from_this == NULL || from_type == NULL) {\n"; - out << " return NULL;\n"; + out << " if (from_this == nullptr || from_type == nullptr) {\n"; + out << " return nullptr;\n"; out << " }\n"; out << " if (from_type == Dtool_Ptr_" << ClassName << ") {\n"; out << " return from_this;\n"; @@ -1131,7 +1107,7 @@ write_class_details(ostream &out, Object *obj) { out << " }\n"; } } - out << " return (void *) NULL;\n"; + out << " return nullptr;\n"; out << "}\n\n"; } } @@ -1187,7 +1163,7 @@ write_class_declarations(ostream &out, ostream *out_h, Object *obj) { out << "\n"; - if (out_h != NULL) { + if (out_h != nullptr) { *out_h << "extern \"C\" " << EXPORT_IMPORT_PREFIX << " struct Dtool_PyTypedObject Dtool_" << class_name << ";\n"; } } @@ -1225,7 +1201,7 @@ write_sub_module(ostream &out, Object *obj) { _external_imports.insert(TypeManager::resolve_type(wrapped_itype._cpptype)); class_ptr = "Dtool_Ptr_" + class_name; - out << " assert(" << class_ptr << " != NULL);\n"; + out << " assert(" << class_ptr << " != nullptr);\n"; } else { class_ptr = "&Dtool_" + class_name; @@ -1307,11 +1283,11 @@ write_module_support(ostream &out, ostream *out_h, InterrogateModuleDef *def) { out << "#ifndef LINK_ALL_STATIC\n"; out << " // Resolve externally imported types.\n"; - for (std::set::iterator ii = _external_imports.begin(); ii != _external_imports.end(); ++ii) { - string class_name = (*ii)->get_local_name(&parser); + for (CPPType *type : _external_imports) { + string class_name = type->get_local_name(&parser); string safe_name = make_safe_name(class_name); - if (has_get_class_type_function(*ii)) { + if (has_get_class_type_function(type)) { out << " Dtool_Ptr_" << safe_name << " = LookupRuntimeTypedClass(" << class_name << "::get_class_type());\n"; } else { out << " Dtool_Ptr_" << safe_name << " = LookupNamedClass(\"" << class_name << "\");\n"; @@ -1330,28 +1306,36 @@ write_module_support(ostream &out, ostream *out_h, InterrogateModuleDef *def) { int enum_count = object->_itype.number_of_enum_values(); if (object->_itype.is_scoped_enum()) { - // Convert as Python 3.4 enum. + // Convert as Python 3.4-style enum. + string class_name = object->_itype._cpptype->get_local_name(&parser); + string safe_name = make_safe_name(class_name); + CPPType *underlying_type = TypeManager::unwrap_const(object->_itype._cpptype->as_enum_type()->get_underlying_type()); string cast_to = underlying_type->get_local_name(&parser); - out << "#if PY_VERSION_HEX >= 0x03040000\n\n"; out << " // enum class " << object->_itype.get_scoped_name() << "\n"; out << " {\n"; out << " PyObject *members = PyTuple_New(" << enum_count << ");\n"; out << " PyObject *member;\n"; for (int xx = 0; xx < enum_count; xx++) { out << " member = PyTuple_New(2);\n" - " PyTuple_SET_ITEM(member, 0, PyUnicode_FromString(\"" + "#if PY_MAJOR_VERSION >= 3\n" + " PyTuple_SET_ITEM(member, 0, PyUnicode_FromString(\"" << object->_itype.get_enum_value_name(xx) << "\"));\n" + "#else\n" + " PyTuple_SET_ITEM(member, 0, PyString_FromString(\"" + << object->_itype.get_enum_value_name(xx) << "\"));\n" + "#endif\n" " PyTuple_SET_ITEM(member, 1, Dtool_WrapValue((" << cast_to << ")" << object->_itype.get_scoped_name() << "::" << object->_itype.get_enum_value_name(xx) << "));\n" " PyTuple_SET_ITEM(members, " << xx << ", member);\n"; } + out << " Dtool_Ptr_" << safe_name << " = Dtool_EnumType_Create(\"" + << object->_itype.get_name() << "\", members, \"" + << _def->module_name << "\");\n"; out << " PyModule_AddObject(module, \"" << object->_itype.get_name() - << "\", Dtool_EnumType_Create(\"" << object->_itype.get_name() - << "\", members, \"" << _def->module_name << "\"));\n"; + << "\", (PyObject *)Dtool_Ptr_" << safe_name << ");\n"; out << " }\n"; - out << "#endif\n"; } else { out << " // enum " << object->_itype.get_scoped_name() << "\n"; for (int xx = 0; xx < enum_count; xx++) { @@ -1459,13 +1443,13 @@ write_module_support(ostream &out, ostream *out_h, InterrogateModuleDef *def) { if (force_base_functions) { out << " // Support Function For Dtool_types ... for now in each module ??\n"; out << " {\"Dtool_BorrowThisReference\", &Dtool_BorrowThisReference, METH_VARARGS, \"Used to borrow 'this' pointer (to, from)\\nAssumes no ownership.\"},\n"; - out << " {\"Dtool_AddToDictionary\", &Dtool_AddToDictionary, METH_VARARGS, \"Used to add items into a tp_dict\"},\n"; + //out << " {\"Dtool_AddToDictionary\", &Dtool_AddToDictionary, METH_VARARGS, \"Used to add items into a tp_dict\"},\n"; } - out << " {NULL, NULL, 0, NULL}\n" << "};\n\n"; + out << " {nullptr, nullptr, 0, nullptr}\n" << "};\n\n"; out << "struct LibraryDef " << def->library_name << "_moddef = {python_simple_funcs};\n"; - if (out_h != NULL) { + if (out_h != nullptr) { *out_h << "extern struct LibraryDef " << def->library_name << "_moddef;\n"; } } @@ -1486,10 +1470,10 @@ write_module(ostream &out, ostream *out_h, InterrogateModuleDef *def) { << "static struct PyModuleDef python_native_module = {\n" << " PyModuleDef_HEAD_INIT,\n" << " \"" << def->module_name << "\",\n" - << " NULL,\n" + << " nullptr,\n" << " -1,\n" - << " NULL,\n" - << " NULL, NULL, NULL, NULL\n" + << " nullptr,\n" + << " nullptr, nullptr, nullptr, nullptr\n" << "};\n" << "\n" << "#ifdef _WIN32\n" @@ -1501,7 +1485,7 @@ write_module(ostream &out, ostream *out_h, InterrogateModuleDef *def) { << "#endif\n" << "\n" << "PyObject *PyInit_" << def->module_name << "() {\n" - << " LibraryDef *refs[] = {&" << def->library_name << "_moddef, NULL};\n" + << " LibraryDef *refs[] = {&" << def->library_name << "_moddef, nullptr};\n" << " PyObject *module = Dtool_PyModuleInitHelper(refs, &python_native_module);\n" << " Dtool_" << def->library_name << "_BuildInstants(module);\n" << " return module;\n" @@ -1518,7 +1502,7 @@ write_module(ostream &out, ostream *out_h, InterrogateModuleDef *def) { << "#endif\n" << "\n" << "void init" << def->module_name << "() {\n" - << " LibraryDef *refs[] = {&" << def->library_name << "_moddef, NULL};\n" + << " LibraryDef *refs[] = {&" << def->library_name << "_moddef, nullptr};\n" << " PyObject *module = Dtool_PyModuleInitHelper(refs, \"" << def->module_name << "\");\n" << " Dtool_" << def->library_name << "_BuildInstants(module);\n" << "}\n" @@ -1546,7 +1530,7 @@ write_module_class(ostream &out, Object *obj) { } Object *nested_obj = _objects[nested_index]; - assert(nested_obj != (Object *)NULL); + assert(nested_obj != nullptr); if (nested_obj->_itype.is_class() || nested_obj->_itype.is_struct()) { write_module_class(out, nested_obj); @@ -1565,7 +1549,6 @@ write_module_class(ostream &out, Object *obj) { is_runtime_typed = true; } - Functions::iterator fi; out << "/**\n"; out << " * Python method tables for " << ClassName << " (" << export_class_name << ")\n" ; out << " */\n"; @@ -1576,8 +1559,7 @@ write_module_class(ostream &out, Object *obj) { bool got_copy = false; bool got_deepcopy = false; - for (fi = obj->_methods.begin(); fi != obj->_methods.end(); ++fi) { - Function *func = (*fi); + for (Function *func : obj->_methods) { if (func->_name == "__copy__") { got_copy = true; } else if (func->_name == "__deepcopy__") { @@ -1614,9 +1596,7 @@ write_module_class(ostream &out, Object *obj) { bool has_nonslotted = false; - Function::Remaps::const_iterator ri; - for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri) { - FunctionRemap *remap = (*ri); + for (FunctionRemap *remap : func->_remaps) { if (!is_remap_legal(remap)) { continue; } @@ -1694,23 +1674,21 @@ write_module_class(ostream &out, Object *obj) { if (obj->_protocol_types & Object::PT_make_copy) { if (!got_copy) { - out << " {\"__copy__\", ©_from_make_copy, METH_NOARGS, NULL},\n"; + out << " {\"__copy__\", ©_from_make_copy, METH_NOARGS, nullptr},\n"; got_copy = true; } } else if (obj->_protocol_types & Object::PT_copy_constructor) { if (!got_copy) { - out << " {\"__copy__\", ©_from_copy_constructor, METH_NOARGS, NULL},\n"; + out << " {\"__copy__\", ©_from_copy_constructor, METH_NOARGS, nullptr},\n"; got_copy = true; } } if (got_copy && !got_deepcopy) { - out << " {\"__deepcopy__\", &map_deepcopy_to_copy, METH_VARARGS, NULL},\n"; + out << " {\"__deepcopy__\", &map_deepcopy_to_copy, METH_VARARGS, nullptr},\n"; } - MakeSeqs::iterator msi; - for (msi = obj->_make_seqs.begin(); msi != obj->_make_seqs.end(); ++msi) { - MakeSeq *make_seq = (*msi); + for (MakeSeq *make_seq : obj->_make_seqs) { if (!is_function_legal(make_seq->_length_getter) || !is_function_legal(make_seq->_element_getter)) { continue; @@ -1727,14 +1705,14 @@ write_module_class(ostream &out, Object *obj) { string name1 = methodNameFromCppName(seq_name, export_class_name, false); string name2 = methodNameFromCppName(seq_name, export_class_name, true); out << " {\"" << name1 - << "\", (PyCFunction) &" << make_seq->_name << ", " << flags << ", NULL},\n"; + << "\", (PyCFunction) &" << make_seq->_name << ", " << flags << ", nullptr},\n"; if (name1 != name2) { out << " { \"" << name2 - << "\", (PyCFunction) &" << make_seq->_name << ", " << flags << ", NULL},\n"; + << "\", (PyCFunction) &" << make_seq->_name << ", " << flags << ", nullptr},\n"; } } - out << " {NULL, NULL, 0, NULL}\n" + out << " {nullptr, nullptr, 0, nullptr}\n" << "};\n\n"; int num_derivations = obj->_itype.number_of_derivations(); @@ -1792,9 +1770,9 @@ write_module_class(ostream &out, Object *obj) { out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n"; out << "//////////////////\n"; out << "static PyObject *" << def._wrapper_name << "(PyObject *self) {\n"; - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n"; - out << " return NULL;\n"; + out << " return nullptr;\n"; out << " }\n\n"; int return_flags = RF_pyobject | RF_err_null; @@ -1812,7 +1790,7 @@ write_module_class(ostream &out, Object *obj) { output_quoted(out, 6, expected_params); out << ");\n"; out << " }\n"; - out << " return NULL;\n"; + out << " return nullptr;\n"; out << "}\n\n"; } break; @@ -1833,19 +1811,19 @@ write_module_class(ostream &out, Object *obj) { out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n"; out << "//////////////////\n"; out << "static PyObject *" << def._wrapper_name << "(PyObject *self, PyObject *arg) {\n"; - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; if (rfi->second._wrapper_type != WT_one_param) { // WT_binary_operator means we must return NotImplemented, instead // of raising an exception, if the this pointer doesn't match. // This is for things like __sub__, which Python likes to call on // the wrong-type objects. out << " DTOOL_Call_ExtractThisPointerForType(self, &Dtool_" << ClassName << ", (void **)&local_this);\n"; - out << " if (local_this == NULL) {\n"; + out << " if (local_this == nullptr) {\n"; out << " Py_INCREF(Py_NotImplemented);\n"; out << " return Py_NotImplemented;\n"; } else { out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n"; - out << " return NULL;\n"; + out << " return nullptr;\n"; } out << " }\n"; @@ -1862,7 +1840,7 @@ write_module_class(ostream &out, Object *obj) { output_quoted(out, 6, expected_params); out << ");\n"; out << " }\n"; - out << " return NULL;\n"; + out << " return nullptr;\n"; } out << "}\n\n"; } @@ -1876,7 +1854,7 @@ write_module_class(ostream &out, Object *obj) { out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n"; out << "//////////////////\n"; out << "static int " << def._wrapper_name << "(PyObject *self, PyObject *arg, PyObject *arg2) {\n"; - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n"; out << " return -1;\n"; out << " }\n\n"; @@ -1886,10 +1864,7 @@ write_module_class(ostream &out, Object *obj) { // This function handles both delattr and setattr. Fish out the // remaps for both types. - set::const_iterator ri; - for (ri = def._remaps.begin(); ri != def._remaps.end(); ++ri) { - FunctionRemap *remap = (*ri); - + for (FunctionRemap *remap : def._remaps) { if (remap->_cppfunc->get_simple_name() == "__delattr__" && remap->_parameters.size() == 2) { delattr_remaps.insert(remap); @@ -1899,7 +1874,7 @@ write_module_class(ostream &out, Object *obj) { } out << " // Determine whether to call __setattr__ or __delattr__.\n"; - out << " if (arg2 != (PyObject *)NULL) { // __setattr__\n"; + out << " if (arg2 != nullptr) { // __setattr__\n"; if (!setattr_remaps.empty()) { out << " PyObject *args = PyTuple_Pack(2, arg, arg2);\n"; @@ -1956,17 +1931,17 @@ write_module_class(ostream &out, Object *obj) { out << "//////////////////\n"; out << "static PyObject *" << def._wrapper_name << "(PyObject *self, PyObject *arg) {\n"; out << " PyObject *res = PyObject_GenericGetAttr(self, arg);\n"; - out << " if (res != NULL) {\n"; + out << " if (res != nullptr) {\n"; out << " return res;\n"; out << " }\n"; out << " if (_PyErr_OCCURRED() != PyExc_AttributeError) {\n"; - out << " return NULL;\n"; + out << " return nullptr;\n"; out << " }\n"; out << " PyErr_Clear();\n\n"; - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n"; - out << " return NULL;\n"; + out << " return nullptr;\n"; out << " }\n\n"; string expected_params; @@ -1975,7 +1950,7 @@ write_module_class(ostream &out, Object *obj) { RF_pyobject | RF_err_null, true); // out << " PyErr_Clear();\n"; - out << " return NULL;\n"; + out << " return nullptr;\n"; out << "}\n\n"; } break; @@ -1988,9 +1963,9 @@ write_module_class(ostream &out, Object *obj) { out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n"; out << "//////////////////\n"; out << "static PyObject *" << def._wrapper_name << "(PyObject *self, Py_ssize_t index) {\n"; - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n"; - out << " return NULL;\n"; + out << " return nullptr;\n"; out << " }\n\n"; // This is a getitem or setitem of a sequence type. This means we @@ -1999,7 +1974,7 @@ write_module_class(ostream &out, Object *obj) { // assumption that Python makes). out << " if (index < 0 || index >= (Py_ssize_t) local_this->size()) {\n"; out << " PyErr_SetString(PyExc_IndexError, \"" << ClassName << " index out of range\");\n"; - out << " return NULL;\n"; + out << " return nullptr;\n"; out << " }\n"; string expected_params; @@ -2011,7 +1986,7 @@ write_module_class(ostream &out, Object *obj) { output_quoted(out, 6, expected_params); out << ");\n"; out << " }\n"; - out << " return NULL;\n"; + out << " return nullptr;\n"; out << "}\n\n"; } break; @@ -2024,7 +1999,7 @@ write_module_class(ostream &out, Object *obj) { out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n"; out << "//////////////////\n"; out << "static int " << def._wrapper_name << "(PyObject *self, Py_ssize_t index, PyObject *arg) {\n"; - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n"; out << " return -1;\n"; out << " }\n\n"; @@ -2039,10 +2014,7 @@ write_module_class(ostream &out, Object *obj) { // This function handles both delitem and setitem. Fish out the // remaps for either one. - set::const_iterator ri; - for (ri = def._remaps.begin(); ri != def._remaps.end(); ++ri) { - FunctionRemap *remap = (*ri); - + for (FunctionRemap *remap : def._remaps) { if (remap->_flags & FunctionRemap::F_setitem_int) { setitem_remaps.insert(remap); @@ -2052,7 +2024,7 @@ write_module_class(ostream &out, Object *obj) { } string expected_params; - out << " if (arg != (PyObject *)NULL) { // __setitem__\n"; + out << " if (arg != nullptr) { // __setitem__\n"; write_function_forset(out, setitem_remaps, 2, 2, expected_params, 4, true, true, AT_single_arg, RF_int, false, true, "index"); out << " } else { // __delitem__\n"; @@ -2078,7 +2050,7 @@ write_module_class(ostream &out, Object *obj) { out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n"; out << "//////////////////\n"; out << "static Py_ssize_t " << def._wrapper_name << "(PyObject *self) {\n"; - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n"; out << " return -1;\n"; out << " }\n\n"; @@ -2098,7 +2070,7 @@ write_module_class(ostream &out, Object *obj) { out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n"; out << "//////////////////\n"; out << "static int " << def._wrapper_name << "(PyObject *self, PyObject *arg, PyObject *arg2) {\n"; - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n"; out << " return -1;\n"; out << " }\n\n"; @@ -2108,10 +2080,7 @@ write_module_class(ostream &out, Object *obj) { // This function handles both delitem and setitem. Fish out the // remaps for either one. - set::const_iterator ri; - for (ri = def._remaps.begin(); ri != def._remaps.end(); ++ri) { - FunctionRemap *remap = (*ri); - + for (FunctionRemap *remap : def._remaps) { if (remap->_flags & FunctionRemap::F_setitem) { setitem_remaps.insert(remap); @@ -2121,7 +2090,7 @@ write_module_class(ostream &out, Object *obj) { } string expected_params; - out << " if (arg2 != (PyObject *)NULL) { // __setitem__\n"; + out << " if (arg2 != nullptr) { // __setitem__\n"; out << " PyObject *args = PyTuple_Pack(2, arg, arg2);\n"; write_function_forset(out, setitem_remaps, 2, 2, expected_params, 4, true, true, AT_varargs, RF_int | RF_decref_args, false); @@ -2155,7 +2124,7 @@ write_module_class(ostream &out, Object *obj) { const char *container = ""; if (remap->_has_this) { - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n"; out << " return -1;\n"; out << " }\n\n"; @@ -2183,21 +2152,19 @@ write_module_class(ostream &out, Object *obj) { out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n"; out << "//////////////////\n"; out << "static int " << def._wrapper_name << "(PyObject *self, Py_buffer *buffer, int flags) {\n"; - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n"; out << " return -1;\n"; out << " }\n\n"; vector_string params_const(1); vector_string params_nonconst(1); - FunctionRemap *remap_const = NULL; - FunctionRemap *remap_nonconst = NULL; + FunctionRemap *remap_const = nullptr; + FunctionRemap *remap_nonconst = nullptr; // Iterate through the remaps to find the one that matches our // parameters. - set::const_iterator ri; - for (ri = def._remaps.begin(); ri != def._remaps.end(); ++ri) { - FunctionRemap *remap = (*ri); + for (FunctionRemap *remap : def._remaps) { if (remap->_const_method) { if ((remap->_flags & FunctionRemap::F_explicit_self) == 0) { params_const.push_back("self"); @@ -2219,20 +2186,20 @@ write_module_class(ostream &out, Object *obj) { // because the function may depend on it to decide whether to // provide a writable buffer or a readonly buffer. const string const_this = "(const " + cClassName + " *)local_this"; - if (remap_const != NULL && remap_nonconst != NULL) { + if (remap_const != nullptr && remap_nonconst != nullptr) { out << " if (!DtoolInstance_IS_CONST(self)) {\n"; out << " return " << remap_nonconst->call_function(out, 4, false, "local_this", params_nonconst) << ";\n"; out << " } else {\n"; out << " return " << remap_const->call_function(out, 4, false, const_this, params_const) << ";\n"; out << " }\n"; - } else if (remap_nonconst != NULL) { + } else if (remap_nonconst != nullptr) { out << " if (!DtoolInstance_IS_CONST(self)) {\n"; out << " return " << remap_nonconst->call_function(out, 4, false, "local_this", params_nonconst) << ";\n"; out << " } else {\n"; out << " Dtool_Raise_TypeError(\"Cannot call " << ClassName << ".__getbuffer__() on a const object.\");\n"; out << " return -1;\n"; out << " }\n"; - } else if (remap_const != NULL) { + } else if (remap_const != nullptr) { out << " return " << remap_const->call_function(out, 4, false, const_this, params_const) << ";\n"; } else { nout << ClassName << "::__getbuffer__ does not match the required signature.\n"; @@ -2252,21 +2219,19 @@ write_module_class(ostream &out, Object *obj) { out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n"; out << "//////////////////\n"; out << "static void " << def._wrapper_name << "(PyObject *self, Py_buffer *buffer) {\n"; - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n"; out << " return;\n"; out << " }\n\n"; vector_string params_const(1); vector_string params_nonconst(1); - FunctionRemap *remap_const = NULL; - FunctionRemap *remap_nonconst = NULL; + FunctionRemap *remap_const = nullptr; + FunctionRemap *remap_nonconst = nullptr; // Iterate through the remaps to find the one that matches our // parameters. - set::const_iterator ri; - for (ri = def._remaps.begin(); ri != def._remaps.end(); ++ri) { - FunctionRemap *remap = (*ri); + for (FunctionRemap *remap : def._remaps) { if (remap->_const_method) { if ((remap->_flags & FunctionRemap::F_explicit_self) == 0) { params_const.push_back("self"); @@ -2284,7 +2249,7 @@ write_module_class(ostream &out, Object *obj) { string return_expr; const string const_this = "(const " + cClassName + " *)local_this"; - if (remap_const != NULL && remap_nonconst != NULL) { + if (remap_const != nullptr && remap_nonconst != nullptr) { out << " if (!DtoolInstance_IS_CONST(self)) {\n"; return_expr = remap_nonconst->call_function(out, 4, false, "local_this", params_nonconst); if (!return_expr.empty()) { @@ -2298,7 +2263,7 @@ write_module_class(ostream &out, Object *obj) { } out << " }\n"; - } else if (remap_nonconst != NULL) { + } else if (remap_nonconst != nullptr) { // Doesn't matter if there's no const version. We *have* to call // it or else we could leak memory. return_expr = remap_nonconst->call_function(out, 2, false, "local_this", params_nonconst); @@ -2306,7 +2271,7 @@ write_module_class(ostream &out, Object *obj) { out << " " << return_expr << ";\n"; } - } else if (remap_const != NULL) { + } else if (remap_const != nullptr) { return_expr = remap_const->call_function(out, 2, false, const_this, params_const); if (!return_expr.empty()) { out << " " << return_expr << ";\n"; @@ -2336,9 +2301,9 @@ write_module_class(ostream &out, Object *obj) { out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n"; out << "//////////////////\n"; out << "static PyObject *" << def._wrapper_name << "(PyObject *self, PyObject *arg, PyObject *arg2) {\n"; - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " DTOOL_Call_ExtractThisPointerForType(self, &Dtool_" << ClassName << ", (void **)&local_this);\n"; - out << " if (local_this == NULL) {\n"; + out << " if (local_this == nullptr) {\n"; // WT_ternary_operator means we must return NotImplemented, instead // of raising an exception, if the this pointer doesn't match. This // is for things like __pow__, which Python likes to call on the @@ -2350,10 +2315,7 @@ write_module_class(ostream &out, Object *obj) { set one_param_remaps; set two_param_remaps; - set::const_iterator ri; - for (ri = def._remaps.begin(); ri != def._remaps.end(); ++ri) { - FunctionRemap *remap = (*ri); - + for (FunctionRemap *remap : def._remaps) { if (remap->_parameters.size() == 2) { one_param_remaps.insert(remap); @@ -2364,7 +2326,7 @@ write_module_class(ostream &out, Object *obj) { string expected_params; - out << " if (arg2 != (PyObject *)NULL && arg2 != Py_None) {\n"; + out << " if (arg2 != nullptr && arg2 != Py_None) {\n"; out << " PyObject *args = PyTuple_Pack(2, arg, arg2);\n"; write_function_forset(out, two_param_remaps, 2, 2, expected_params, 4, true, true, AT_varargs, RF_pyobject | RF_err_null | RF_decref_args, true); @@ -2379,7 +2341,7 @@ write_module_class(ostream &out, Object *obj) { output_quoted(out, 6, expected_params); out << ");\n"; out << " }\n"; - out << " return NULL;\n"; + out << " return nullptr;\n"; out << "}\n\n"; } break; @@ -2399,9 +2361,9 @@ write_module_class(ostream &out, Object *obj) { const char *container = ""; if (remap->_has_this) { - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " DTOOL_Call_ExtractThisPointerForType(self, &Dtool_" << ClassName << ", (void **) &local_this);\n"; - out << " if (local_this == NULL) {\n"; + out << " if (local_this == nullptr) {\n"; out << " return 0;\n"; out << " }\n\n"; container = "local_this"; @@ -2424,7 +2386,7 @@ write_module_class(ostream &out, Object *obj) { out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n"; out << "//////////////////\n"; out << "static int " << def._wrapper_name << "(PyObject *self, PyObject *arg) {\n"; - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n"; out << " return -1;\n"; out << " }\n\n"; @@ -2451,7 +2413,7 @@ write_module_class(ostream &out, Object *obj) { out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n"; out << "//////////////////\n"; out << "static Py_hash_t " << def._wrapper_name << "(PyObject *self) {\n"; - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n"; out << " return -1;\n"; out << " }\n\n"; @@ -2467,7 +2429,7 @@ write_module_class(ostream &out, Object *obj) { // Nothing special about the wrapper function: just write it normally. string fname = "static PyObject *" + def._wrapper_name + "(PyObject *self, PyObject *args, PyObject *kwds)\n"; - vector remaps; + std::vector remaps; remaps.insert(remaps.end(), def._remaps.begin(), def._remaps.end()); string expected_params; write_function_for_name(out, obj, remaps, fname, expected_params, true, AT_keyword_args, RF_pyobject | RF_err_null); @@ -2489,11 +2451,11 @@ write_module_class(ostream &out, Object *obj) { out << "// " << ClassName << "\n"; out << "//////////////////\n"; out << "static PyObject *Dtool_Repr_" << ClassName << "(PyObject *self) {\n"; - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n"; - out << " return NULL;\n"; + out << " return nullptr;\n"; out << " }\n\n"; - out << " ostringstream os;\n"; + out << " std::ostringstream os;\n"; if (need_repr == 3) { out << " invoke_extension(local_this).python_repr(os, \"" << classNameFromCppName(ClassName, false) << "\");\n"; @@ -2519,11 +2481,11 @@ write_module_class(ostream &out, Object *obj) { out << "// " << ClassName << "\n"; out << "//////////////////\n"; out << "static PyObject *Dtool_Str_" << ClassName << "(PyObject *self) {\n"; - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n"; - out << " return NULL;\n"; + out << " return nullptr;\n"; out << " }\n\n"; - out << " ostringstream os;\n"; + out << " std::ostringstream os;\n"; if (need_str == 2) { out << " local_this->write(os, 0);\n"; } else { @@ -2536,49 +2498,52 @@ write_module_class(ostream &out, Object *obj) { } } - if (NeedsARichCompareFunction(obj->_itype)) { + if (NeedsARichCompareFunction(obj->_itype) || slots.count("tp_compare")) { out << "//////////////////\n"; out << "// A rich comparison function\n"; out << "// " << ClassName << "\n"; out << "//////////////////\n"; out << "static PyObject *Dtool_RichCompare_" << ClassName << "(PyObject *self, PyObject *arg, int op) {\n"; - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n"; - out << " return NULL;\n"; + out << " return nullptr;\n"; out << " }\n\n"; - out << " switch (op) {\n"; - for (fi = obj->_methods.begin(); fi != obj->_methods.end(); ++fi) { + for (Function *func : obj->_methods) { std::set remaps; - Function *func = (*fi); if (!func) { continue; } // We only accept comparison operators that take one parameter (besides // 'this'). - Function::Remaps::const_iterator ri; - for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri) { - FunctionRemap *remap = (*ri); + for (FunctionRemap *remap : func->_remaps) { if (is_remap_legal(remap) && remap->_has_this && (remap->_args_type == AT_single_arg)) { remaps.insert(remap); } } const string &fname = func->_ifunc.get_name(); + const char *op_type; if (fname == "operator <") { - out << " case Py_LT:\n"; + op_type = "Py_LT"; } else if (fname == "operator <=") { - out << " case Py_LE:\n"; + op_type = "Py_LE"; } else if (fname == "operator ==") { - out << " case Py_EQ:\n"; + op_type = "Py_EQ"; } else if (fname == "operator !=") { - out << " case Py_NE:\n"; + op_type = "Py_NE"; } else if (fname == "operator >") { - out << " case Py_GT:\n"; + op_type = "Py_GT"; } else if (fname == "operator >=") { - out << " case Py_GE:\n"; + op_type = "Py_GE"; } else { continue; } + if (!has_local_richcompare) { + out << " switch (op) {\n"; + has_local_richcompare = true; + } + out << " case " << op_type << ":\n"; + out << " {\n"; string expected_params; @@ -2587,28 +2552,28 @@ write_module_class(ostream &out, Object *obj) { out << " break;\n"; out << " }\n"; - has_local_richcompare = true; } - out << " }\n\n"; - - out << " if (_PyErr_OCCURRED()) {\n"; - out << " PyErr_Clear();\n"; - out << " }\n\n"; + if (has_local_richcompare) { + // End of switch block + out << " }\n\n"; + out << " if (_PyErr_OCCURRED()) {\n"; + out << " PyErr_Clear();\n"; + out << " }\n\n"; + } if (slots.count("tp_compare")) { // A lot of Panda code depends on comparisons being done via the // compare_to function, which is mapped to the tp_compare slot, which // Python 3 no longer has. So, we'll write code to fall back to that if // no matching comparison operator was found. - out << "#if PY_MAJOR_VERSION >= 3\n"; out << " // All is not lost; we still have the compare_to function to fall back onto.\n"; out << " int cmpval = " << slots["tp_compare"]._wrapper_name << "(self, arg);\n"; out << " if (cmpval == -1 && _PyErr_OCCURRED()) {\n"; out << " if (PyErr_ExceptionMatches(PyExc_TypeError)) {\n"; out << " PyErr_Clear();\n"; out << " } else {\n"; - out << " return (PyObject *)NULL;\n"; + out << " return nullptr;\n"; out << " }\n"; out << " }\n"; out << " switch (op) {\n"; @@ -2625,7 +2590,7 @@ write_module_class(ostream &out, Object *obj) { out << " case Py_GE:\n"; out << " return PyBool_FromLong(cmpval >= 0);\n"; out << " }\n"; - out << "#endif\n\n"; + has_local_richcompare = true; } out << " Py_INCREF(Py_NotImplemented);\n"; @@ -2638,23 +2603,23 @@ write_module_class(ostream &out, Object *obj) { if (obj->_properties.size() > 0) { // Write out the array of properties, telling Python which getter and // setter to call when they are assigned or queried in Python code. - out << "static PyGetSetDef Dtool_Properties_" << ClassName << "[] = {\n"; - - Properties::const_iterator pit; - for (pit = obj->_properties.begin(); pit != obj->_properties.end(); ++pit) { - Property *property = (*pit); + for (Property *property : obj->_properties) { const InterrogateElement &ielem = property->_ielement; if (!property->_has_this || property->_getter_remaps.empty()) { continue; } + if (num_getset == 0) { + out << "static PyGetSetDef Dtool_Properties_" << ClassName << "[] = {\n"; + } + ++num_getset; string name1 = methodNameFromCppName(ielem.get_name(), "", false); // string name2 = methodNameFromCppName(ielem.get_name(), "", true); string getter = "&Dtool_" + ClassName + "_" + ielem.get_name() + "_Getter"; - string setter = "NULL"; + string setter = "nullptr"; if (!ielem.is_sequence() && !ielem.is_mapping() && !property->_setter_remaps.empty()) { setter = "&Dtool_" + ClassName + "_" + ielem.get_name() + "_Setter"; } @@ -2666,11 +2631,11 @@ write_module_class(ostream &out, Object *obj) { output_quoted(out, 4, ielem.get_comment()); out << ",\n "; } else { - out << ", NULL, "; + out << ", nullptr, "; } // Extra void* argument; we don't make use of it. - out << "NULL},\n"; + out << "nullptr},\n"; /*if (name1 != name2 && name1 != "__dict__") { // Add alternative spelling. @@ -2681,8 +2646,10 @@ write_module_class(ostream &out, Object *obj) { }*/ } - out << " {NULL},\n"; - out << "};\n\n"; + if (num_getset != 0) { + out << " {nullptr},\n"; + out << "};\n\n"; + } } // These fields are inherited together. We should either write all of them @@ -2720,7 +2687,7 @@ write_module_class(ostream &out, Object *obj) { write_function_slot(out, 2, slots, "nb_coerce"); out << "#endif\n"; write_function_slot(out, 2, slots, "nb_int"); - out << " 0, // nb_long\n"; // removed in Python 3 + out << " nullptr, // nb_long\n"; // removed in Python 3 write_function_slot(out, 2, slots, "nb_float"); out << "#if PY_MAJOR_VERSION < 3\n"; write_function_slot(out, 2, slots, "nb_oct"); @@ -2767,9 +2734,9 @@ write_module_class(ostream &out, Object *obj) { write_function_slot(out, 2, slots, "sq_concat"); write_function_slot(out, 2, slots, "sq_repeat"); write_function_slot(out, 2, slots, "sq_item"); - out << " 0, // sq_slice\n"; // removed in Python 3 + out << " nullptr, // sq_slice\n"; // removed in Python 3 write_function_slot(out, 2, slots, "sq_ass_item"); - out << " 0, // sq_ass_slice\n"; // removed in Python 3 + out << " nullptr, // sq_ass_slice\n"; // removed in Python 3 write_function_slot(out, 2, slots, "sq_contains"); write_function_slot(out, 2, slots, "sq_inplace_concat"); @@ -2819,7 +2786,7 @@ write_module_class(ostream &out, Object *obj) { // Output the actual PyTypeObject definition. out << "struct Dtool_PyTypedObject Dtool_" << ClassName << " = {\n"; out << " {\n"; - out << " PyVarObject_HEAD_INIT(NULL, 0)\n"; + out << " PyVarObject_HEAD_INIT(nullptr, 0)\n"; // const char *tp_name; out << " \"" << _def->module_name << "." << export_class_name << "\",\n"; // Py_ssize_t tp_basicsize; @@ -2841,16 +2808,16 @@ write_module_class(ostream &out, Object *obj) { if (have_async) { out << " &Dtool_AsyncMethods_" << ClassName << ",\n"; } else { - out << " 0, // tp_as_async\n"; + out << " nullptr, // tp_as_async\n"; } out << "#elif PY_MAJOR_VERSION >= 3\n"; - out << " 0, // tp_reserved\n"; + out << " nullptr, // tp_reserved\n"; out << "#else\n"; if (has_hash_compare) { write_function_slot(out, 4, slots, "tp_compare", - "&DTOOL_PyObject_ComparePointers"); + "&DtoolInstance_ComparePointers"); } else { - out << " 0, // tp_compare\n"; + out << " nullptr, // tp_compare\n"; } out << "#endif\n"; @@ -2867,20 +2834,20 @@ write_module_class(ostream &out, Object *obj) { if (has_parent_class || (obj->_protocol_types & Object::PT_sequence) != 0) { out << " &Dtool_SequenceMethods_" << ClassName << ",\n"; } else { - out << " 0, // tp_as_sequence\n"; + out << " nullptr, // tp_as_sequence\n"; } // PyMappingMethods *tp_as_mapping; if (has_parent_class || (obj->_protocol_types & Object::PT_mapping) != 0) { out << " &Dtool_MappingMethods_" << ClassName << ",\n"; } else { - out << " 0, // tp_as_mapping\n"; + out << " nullptr, // tp_as_mapping\n"; } // hashfunc tp_hash; if (has_hash_compare) { - write_function_slot(out, 4, slots, "tp_hash", "&DTOOL_PyObject_HashPointer"); + write_function_slot(out, 4, slots, "tp_hash", "&DtoolInstance_HashPointer"); } else { - out << " 0, // tp_hash\n"; + out << " nullptr, // tp_hash\n"; } // ternaryfunc tp_call; @@ -2904,7 +2871,7 @@ write_module_class(ostream &out, Object *obj) { if (has_parent_class || has_local_getbuffer) { out << " &Dtool_BufferProcs_" << ClassName << ",\n"; } else { - out << " 0, // tp_as_buffer\n"; + out << " nullptr, // tp_as_buffer\n"; } string gcflag; @@ -2932,15 +2899,15 @@ write_module_class(ostream &out, Object *obj) { out << ",\n"; out << "#endif\n"; } else { - out << " 0, // tp_doc\n"; + out << " nullptr, // tp_doc\n"; } // traverseproc tp_traverse; - out << " 0, // tp_traverse\n"; + out << " nullptr, // tp_traverse\n"; //write_function_slot(out, 4, slots, "tp_traverse"); // inquiry tp_clear; - out << " 0, // tp_clear\n"; + out << " nullptr, // tp_clear\n"; //write_function_slot(out, 4, slots, "tp_clear"); // richcmpfunc tp_richcompare; @@ -2949,12 +2916,12 @@ write_module_class(ostream &out, Object *obj) { } else if (has_hash_compare) { // All hashable types need to be comparable. out << "#if PY_MAJOR_VERSION >= 3\n"; - out << " &DTOOL_PyObject_RichCompare,\n"; + out << " &DtoolInstance_RichComparePointers,\n"; out << "#else\n"; - out << " 0, // tp_richcompare\n"; + out << " nullptr, // tp_richcompare\n"; out << "#endif\n"; } else { - out << " 0, // tp_richcompare\n"; + out << " nullptr, // tp_richcompare\n"; } // Py_ssize_t tp_weaklistoffset; @@ -2968,19 +2935,19 @@ write_module_class(ostream &out, Object *obj) { // struct PyMethodDef *tp_methods; out << " Dtool_Methods_" << ClassName << ",\n"; // struct PyMemberDef *tp_members; - out << " 0, // tp_members\n"; + out << " nullptr, // tp_members\n"; // struct PyGetSetDef *tp_getset; if (num_getset > 0) { out << " Dtool_Properties_" << ClassName << ",\n"; } else { - out << " 0, // tp_getset\n"; + out << " nullptr, // tp_getset\n"; } // struct _typeobject *tp_base; - out << " 0, // tp_base\n"; + out << " nullptr, // tp_base\n"; // PyObject *tp_dict; - out << " 0, // tp_dict\n"; + out << " nullptr, // tp_dict\n"; // descrgetfunc tp_descr_get; write_function_slot(out, 4, slots, "tp_descr_get"); // descrsetfunc tp_descr_set; @@ -3000,26 +2967,26 @@ write_module_class(ostream &out, Object *obj) { out << " PyObject_Del,\n"; } // inquiry tp_is_gc; - out << " 0, // tp_is_gc\n"; + out << " nullptr, // tp_is_gc\n"; // PyObject *tp_bases; - out << " 0, // tp_bases\n"; + out << " nullptr, // tp_bases\n"; // PyObject *tp_mro; - out << " 0, // tp_mro\n"; + out << " nullptr, // tp_mro\n"; // PyObject *tp_cache; - out << " 0, // tp_cache\n"; + out << " nullptr, // tp_cache\n"; // PyObject *tp_subclasses; - out << " 0, // tp_subclasses\n"; + out << " nullptr, // tp_subclasses\n"; // PyObject *tp_weaklist; - out << " 0, // tp_weaklist\n"; + out << " nullptr, // tp_weaklist\n"; // destructor tp_del; - out << " 0, // tp_del\n"; + out << " nullptr, // tp_del\n"; // unsigned int tp_version_tag out << "#if PY_VERSION_HEX >= 0x02060000\n"; out << " 0, // tp_version_tag\n"; out << "#endif\n"; // destructor tp_finalize out << "#if PY_VERSION_HEX >= 0x03040000\n"; - out << " 0, // tp_finalize\n"; + out << " nullptr, // tp_finalize\n"; out << "#endif\n"; out << " },\n"; @@ -3037,15 +3004,15 @@ write_module_class(ostream &out, Object *obj) { if (has_coerce > 1) { out << " (CoerceFunction)Dtool_Coerce_" << ClassName << ",\n"; } else { - out << " (CoerceFunction)0,\n"; + out << " nullptr,\n"; } } else { - out << " (CoerceFunction)0,\n"; + out << " nullptr,\n"; out << " (CoerceFunction)Dtool_Coerce_" << ClassName << ",\n"; } } else { - out << " (CoerceFunction)0,\n"; - out << " (CoerceFunction)0,\n"; + out << " nullptr,\n"; + out << " nullptr,\n"; } out << "};\n\n"; @@ -3060,19 +3027,19 @@ write_module_class(ostream &out, Object *obj) { out << " // Dependent objects\n"; if (bases.size() > 0) { string baseargs; - for (vector::iterator bi = bases.begin(); bi != bases.end(); ++bi) { - string safe_name = make_safe_name((*bi)->get_local_name(&parser)); + for (CPPType *base : bases) { + string safe_name = make_safe_name(base->get_local_name(&parser)); - if (isExportThisRun(*bi)) { + if (isExportThisRun(base)) { baseargs += ", (PyTypeObject *)&Dtool_" + safe_name; - out << " Dtool_PyModuleClassInit_" << safe_name << "(NULL);\n"; + out << " Dtool_PyModuleClassInit_" << safe_name << "(nullptr);\n"; } else { baseargs += ", (PyTypeObject *)Dtool_Ptr_" + safe_name; - out << " assert(Dtool_Ptr_" << safe_name << " != NULL);\n" - << " assert(Dtool_Ptr_" << safe_name << "->_Dtool_ModuleClassInit != NULL);\n" - << " Dtool_Ptr_" << safe_name << "->_Dtool_ModuleClassInit(NULL);\n"; + out << " assert(Dtool_Ptr_" << safe_name << " != nullptr);\n" + << " assert(Dtool_Ptr_" << safe_name << "->_Dtool_ModuleClassInit != nullptr);\n" + << " Dtool_Ptr_" << safe_name << "->_Dtool_ModuleClassInit(nullptr);\n"; } } @@ -3091,7 +3058,7 @@ write_module_class(ostream &out, Object *obj) { continue; } Object *nested_obj = _objects[nested_index]; - assert(nested_obj != (Object *)NULL); + assert(nested_obj != nullptr); if (nested_obj->_itype.is_class() || nested_obj->_itype.is_struct()) { num_dict_items += 2; @@ -3123,13 +3090,13 @@ write_module_class(ostream &out, Object *obj) { } Object *nested_obj = _objects[nested_index]; - assert(nested_obj != (Object *)NULL); + assert(nested_obj != nullptr); if (nested_obj->_itype.is_class() || nested_obj->_itype.is_struct()) { std::string ClassName1 = make_safe_name(nested_obj->_itype.get_scoped_name()); std::string ClassName2 = make_safe_name(nested_obj->_itype.get_name()); out << " // Nested Object " << ClassName1 << ";\n"; - out << " Dtool_PyModuleClassInit_" << ClassName1 << "(NULL);\n"; + out << " Dtool_PyModuleClassInit_" << ClassName1 << "(nullptr);\n"; string name1 = classNameFromCppName(ClassName2, false); string name2 = classNameFromCppName(ClassName2, true); out << " PyDict_SetItemString(dict, \"" << name1 << "\", (PyObject *)&Dtool_" << ClassName1 << ");\n"; @@ -3158,29 +3125,37 @@ write_module_class(ostream &out, Object *obj) { // support recently. } else if (nested_obj->_itype.is_scoped_enum()) { - // Convert enum class as Python 3.4 enum. + // Convert enum class as Python 3.4-style enum. + string class_name = nested_obj->_itype._cpptype->get_local_name(&parser); + string safe_name = make_safe_name(class_name); + int enum_count = nested_obj->_itype.number_of_enum_values(); CPPType *underlying_type = TypeManager::unwrap_const(nested_obj->_itype._cpptype->as_enum_type()->get_underlying_type()); string cast_to = underlying_type->get_local_name(&parser); - out << "#if PY_VERSION_HEX >= 0x03040000\n\n"; out << " // enum class " << nested_obj->_itype.get_scoped_name() << ";\n"; out << " {\n"; out << " PyObject *members = PyTuple_New(" << enum_count << ");\n"; out << " PyObject *member;\n"; for (int xx = 0; xx < enum_count; xx++) { out << " member = PyTuple_New(2);\n" + "#if PY_MAJOR_VERSION >= 3\n" " PyTuple_SET_ITEM(member, 0, PyUnicode_FromString(\"" << nested_obj->_itype.get_enum_value_name(xx) << "\"));\n" + "#else\n" + " PyTuple_SET_ITEM(member, 0, PyString_FromString(\"" + << nested_obj->_itype.get_enum_value_name(xx) << "\"));\n" + "#endif\n" " PyTuple_SET_ITEM(member, 1, Dtool_WrapValue((" << cast_to << ")" << nested_obj->_itype.get_scoped_name() << "::" << nested_obj->_itype.get_enum_value_name(xx) << "));\n" " PyTuple_SET_ITEM(members, " << xx << ", member);\n"; } + out << " Dtool_Ptr_" << safe_name << " = Dtool_EnumType_Create(\"" + << nested_obj->_itype.get_name() << "\", members, \"" + << _def->module_name << "\");\n"; out << " PyDict_SetItemString(dict, \"" << nested_obj->_itype.get_name() - << "\", Dtool_EnumType_Create(\"" << nested_obj->_itype.get_name() - << "\", members, \"" << _def->module_name << "\"));\n"; + << "\", (PyObject *)Dtool_Ptr_" << safe_name << ");\n"; out << " }\n"; - out << "#endif\n"; } else if (nested_obj->_itype.is_enum()) { out << " // enum " << nested_obj->_itype.get_scoped_name() << ";\n"; @@ -3207,9 +3182,7 @@ write_module_class(ostream &out, Object *obj) { } // Also add the static properties, which can't be added via getset. - Properties::const_iterator pit; - for (pit = obj->_properties.begin(); pit != obj->_properties.end(); ++pit) { - Property *property = (*pit); + for (Property *property : obj->_properties) { const InterrogateElement &ielem = property->_ielement; if (property->_has_this || property->_getter_remaps.empty()) { continue; @@ -3219,7 +3192,7 @@ write_module_class(ostream &out, Object *obj) { // string name2 = methodNameFromCppName(ielem.get_name(), "", true); string getter = "&Dtool_" + ClassName + "_" + ielem.get_name() + "_Getter"; - string setter = "NULL"; + string setter = "nullptr"; if (!ielem.is_sequence() && !ielem.is_mapping() && !property->_setter_remaps.empty()) { setter = "&Dtool_" + ClassName + "_" + ielem.get_name() + "_Setter"; } @@ -3231,11 +3204,11 @@ write_module_class(ostream &out, Object *obj) { output_quoted(out, 4, ielem.get_comment()); out << ",\n "; } else { - out << ", NULL, "; + out << ", nullptr, "; } // Extra void* argument; we don't make use of it. - out << "NULL};\n"; + out << "nullptr};\n"; out << " PyDict_SetItemString(dict, \"" << name1 << "\", Dtool_NewStaticProperty(&Dtool_" << ClassName << "._PyType, &def_" << name1 << "));\n"; /* Alternative spelling: @@ -3354,9 +3327,7 @@ write_function_for_top(ostream &out, InterfaceMaker::Object *obj, InterfaceMaker // should even write it. bool has_remaps = false; - Function::Remaps::const_iterator ri; - for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri) { - FunctionRemap *remap = (*ri); + for (FunctionRemap *remap : func->_remaps) { if (!is_remap_legal(remap)) { continue; } @@ -3439,7 +3410,7 @@ write_function_for_top(ostream &out, InterfaceMaker::Object *obj, InterfaceMaker output_quoted(out, 2, comment.str()); out << ";\n"; out << "#else\n"; - out << "static const char *" << func->_name << "_comment = NULL;\n"; + out << "static const char *" << func->_name << "_comment = nullptr;\n"; out << "#endif\n\n"; } @@ -3460,7 +3431,7 @@ write_function_for_name(ostream &out, Object *obj, bool has_this = false; Function::Remaps::const_iterator ri; - FunctionRemap *remap = NULL; + FunctionRemap *remap = nullptr; int max_required_args = 0; bool all_nonconst = true; bool has_keywords = false; @@ -3512,7 +3483,7 @@ write_function_for_name(ostream &out, Object *obj, // string class_name = remap->_cpptype->get_simple_name(); // Extract pointer from 'self' parameter. - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; if (all_nonconst) { // All remaps are non-const. Also check that this object isn't const. @@ -3536,7 +3507,7 @@ write_function_for_name(ostream &out, Object *obj, if (args_type == AT_keyword_args && !has_keywords) { // We don't actually take keyword arguments. Make sure we didn't get any. - out << " if (kwds != NULL && PyDict_Size(kwds) > 0) {\n"; + out << " if (kwds != nullptr && PyDict_Size(kwds) > 0) {\n"; out << "#ifdef NDEBUG\n"; error_raise_return(out, 4, return_flags, "TypeError", "function takes no keyword arguments"); out << "#else\n"; @@ -3562,7 +3533,7 @@ write_function_for_name(ostream &out, Object *obj, switch (args_type) { case AT_keyword_args: indent(out, 2) << "int parameter_count = (int)PyTuple_Size(args);\n"; - indent(out, 2) << "if (kwds != NULL) {\n"; + indent(out, 2) << "if (kwds != nullptr) {\n"; indent(out, 2) << " parameter_count += (int)PyDict_Size(kwds);\n"; indent(out, 2) << "}\n"; break; @@ -3608,8 +3579,8 @@ write_function_for_name(ostream &out, Object *obj, std::set::iterator sii; for (sii = mii->second.begin(); sii != mii->second.end(); ++sii) { remap = (*sii); - int first_param = remap->_has_this ? 1 : 0; - for (int i = first_param; i < remap->_parameters.size(); ++i) { + size_t first_param = remap->_has_this ? 1u : 0u; + for (size_t i = first_param; i < remap->_parameters.size(); ++i) { if (remap->_parameters[i]._has_name) { strip_keyword_args = false; break; @@ -3621,7 +3592,7 @@ write_function_for_name(ostream &out, Object *obj, if (strip_keyword_args) { // None of the remaps take any keyword arguments, so let's check that // we take none. This saves some checks later on. - indent(out, 4) << "if (kwds == NULL || PyDict_GET_SIZE(kwds) == 0) {\n"; + indent(out, 4) << "if (kwds == nullptr || PyDict_GET_SIZE(kwds) == 0) {\n"; if (min_args == 1 && min_args == 1) { indent(out, 4) << " PyObject *arg = PyTuple_GET_ITEM(args, 0);\n"; write_function_forset(out, mii->second, min_args, max_args, expected_params, 6, @@ -3708,7 +3679,7 @@ write_function_for_name(ostream &out, Object *obj, case AT_keyword_args: out << " if (!Dtool_CheckNoArgs(args, kwds)) {\n"; out << " int parameter_count = (int)PyTuple_Size(args);\n"; - out << " if (kwds != NULL) {\n"; + out << " if (kwds != nullptr) {\n"; out << " parameter_count += (int)PyDict_Size(kwds);\n"; out << " }\n"; break; @@ -3740,7 +3711,7 @@ write_function_for_name(ostream &out, Object *obj, // Check this to be sure, as we handle the case of only 1 keyword arg in // write_function_forset (not using ParseTupleAndKeywords). out << " int parameter_count = (int)PyTuple_Size(args);\n" - " if (kwds != NULL) {\n" + " if (kwds != nullptr) {\n" " parameter_count += (int)PyDict_Size(kwds);\n" " }\n" " if (parameter_count != 1) {\n" @@ -3805,18 +3776,12 @@ void InterfaceMakerPythonNative:: write_coerce_constructor(ostream &out, Object *obj, bool is_const) { std::map > map_sets; std::map >::iterator mii; - std::set::iterator sii; int max_required_args = 0; - Functions::iterator fi; - Function::Remaps::const_iterator ri; - // Go through the methods and find appropriate static make() functions. - for (fi = obj->_methods.begin(); fi != obj->_methods.end(); ++fi) { - Function *func = (*fi); - for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri) { - FunctionRemap *remap = (*ri); + for (Function *func : obj->_methods) { + for (FunctionRemap *remap : func->_remaps) { if (is_remap_legal(remap) && remap->_flags & FunctionRemap::F_coerce_constructor) { nassertd(!remap->_has_this) continue; @@ -3850,10 +3815,8 @@ write_coerce_constructor(ostream &out, Object *obj, bool is_const) { // Now go through the constructors that are suitable for coercion. This // excludes copy constructors and ones marked "explicit". - for (fi = obj->_constructors.begin(); fi != obj->_constructors.end(); ++fi) { - Function *func = (*fi); - for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri) { - FunctionRemap *remap = (*ri); + for (Function *func : obj->_constructors) { + for (FunctionRemap *remap : func->_remaps) { if (is_remap_legal(remap) && remap->_flags & FunctionRemap::F_coerce_constructor) { nassertd(!remap->_has_this) continue; @@ -4237,8 +4200,8 @@ int get_type_sort(CPPType *type) { // The Core sort function for remap calling orders.. bool RemapCompareLess(FunctionRemap *in1, FunctionRemap *in2) { - assert(in1 != NULL); - assert(in2 != NULL); + assert(in1 != nullptr); + assert(in2 != nullptr); if (in1->_const_method != in2->_const_method) { // Non-const methods should come first. @@ -4322,7 +4285,7 @@ write_function_forset(ostream &out, return; } - FunctionRemap *remap = NULL; + FunctionRemap *remap = nullptr; std::set::iterator sii; bool all_nonconst = false; @@ -4735,7 +4698,7 @@ write_function_instance(ostream &out, FunctionRemap *remap, extra_convert << "#if PY_VERSION_HEX >= 0x03030000\n" - << "wchar_t *" << param_name << "_str = PyUnicode_AsWideCharString(" << param_name << ", NULL);\n" + << "wchar_t *" << param_name << "_str = PyUnicode_AsWideCharString(" << param_name << ", nullptr);\n" << "#else" << "Py_ssize_t " << param_name << "_len = PyUnicode_GET_SIZE(" << param_name << ");\n" << "wchar_t *" << param_name << "_str = (wchar_t *)alloca(sizeof(wchar_t) * (" + param_name + "_len + 1));\n" @@ -4825,7 +4788,7 @@ write_function_instance(ostream &out, FunctionRemap *remap, << default_value->_str.size() << ";\n"; } } else { - indent(out, indent_level) << "const char *" << param_name << "_str = NULL;\n"; + indent(out, indent_level) << "const char *" << param_name << "_str = nullptr;\n"; indent(out, indent_level) << "Py_ssize_t " << param_name << "_len;\n"; } @@ -4837,11 +4800,11 @@ write_function_instance(ostream &out, FunctionRemap *remap, out << "#else\n"; // NB. PyString_AsStringAndSize also accepts a PyUnicode. indent(out, indent_level) << "if (PyString_AsStringAndSize(arg, (char **)&" << param_name << "_str, &" << param_name << "_len) == -1) {\n"; - indent(out, indent_level + 2) << param_name << "_str = NULL;\n"; + indent(out, indent_level + 2) << param_name << "_str = nullptr;\n"; indent(out, indent_level) << "}\n"; out << "#endif\n"; - extra_param_check << " && " << param_name << "_str != NULL"; + extra_param_check << " && " << param_name << "_str != nullptr"; } else { format_specifiers += "s#"; parameter_list += ", &" + param_name @@ -4860,7 +4823,7 @@ write_function_instance(ostream &out, FunctionRemap *remap, only_pyobjects = false; } else if (TypeManager::is_vector_unsigned_char(type)) { - indent(out, indent_level) << "unsigned char *" << param_name << "_str = NULL;\n"; + indent(out, indent_level) << "unsigned char *" << param_name << "_str = nullptr;\n"; indent(out, indent_level) << "Py_ssize_t " << param_name << "_len;\n"; if (args_type == AT_single_arg) { @@ -4879,6 +4842,46 @@ write_function_instance(ostream &out, FunctionRemap *remap, clear_error = true; only_pyobjects = false; + } else if (TypeManager::is_scoped_enum(type)) { + if (args_type == AT_single_arg) { + param_name = "arg"; + } else { + indent(out, indent_level) << "PyObject *" << param_name; + if (default_value != nullptr) { + out << " = nullptr"; + } + out << ";\n"; + format_specifiers += "O"; + parameter_list += ", &" + param_name; + } + + CPPEnumType *enum_type = (CPPEnumType *)TypeManager::unwrap(type); + CPPType *underlying_type = enum_type->get_underlying_type(); + underlying_type = TypeManager::unwrap_const(underlying_type); + + //indent(out, indent_level); + //underlying_type->output_instance(out, param_name + "_val", &parser); + //out << default_expr << ";\n"; + extra_convert << "long " << param_name << "_val"; + + if (default_value != nullptr) { + extra_convert << " = (long)"; + default_value->output(extra_convert, 0, &parser, false); + extra_convert << + ";\nif (" << param_name << " != nullptr) {\n" + " " << param_name << "_val = Dtool_EnumValue_AsLong(" + param_name + ");\n" + "}"; + } else { + extra_convert + << ";\n" + << param_name << "_val = Dtool_EnumValue_AsLong(" + param_name + ");\n"; + } + + pexpr_string = "(" + enum_type->get_local_name(&parser) + ")" + param_name + "_val"; + expected_params += classNameFromCppName(enum_type->get_simple_name(), false); + extra_param_check << " && " << param_name << "_val != -1"; + clear_error = true; + } else if (TypeManager::is_bool(type)) { if (args_type == AT_single_arg) { param_name = "arg"; @@ -5036,7 +5039,7 @@ write_function_instance(ostream &out, FunctionRemap *remap, "value %ld out of range for unsigned byte", param_name); } else { - extra_convert << "if (" << param_name << " < CHAR_MIN || " << param_name << " > CHAR_MAX) {\n"; + extra_convert << "if (" << param_name << " < SCHAR_MIN || " << param_name << " > SCHAR_MAX) {\n"; error_raise_return(extra_convert, 2, return_flags, "OverflowError", "value %ld out of range for signed byte", param_name); @@ -5285,23 +5288,23 @@ write_function_instance(ostream &out, FunctionRemap *remap, // Unravel the type to determine its properties. int array_len = -1; bool is_const = true; - CPPSimpleType *simple = NULL; + CPPSimpleType *simple = nullptr; CPPType *unwrap = TypeManager::unwrap_const_reference(type); - if (unwrap != NULL) { + if (unwrap != nullptr) { CPPArrayType *array_type = unwrap->as_array_type(); CPPPointerType *pointer_type = unwrap->as_pointer_type(); - if (array_type != NULL) { - if (array_type->_bounds != NULL) { + if (array_type != nullptr) { + if (array_type->_bounds != nullptr) { array_len = array_type->_bounds->evaluate().as_integer(); } unwrap = array_type->_element_type; - } else if (pointer_type != NULL) { + } else if (pointer_type != nullptr) { unwrap = pointer_type->_pointing_at; } CPPConstType *const_type = unwrap->as_const_type(); - if (const_type != NULL) { + if (const_type != nullptr) { unwrap = const_type->_wrapped_around; } else { is_const = false; @@ -5407,7 +5410,7 @@ write_function_instance(ostream &out, FunctionRemap *remap, } else { indent(out, indent_level) << "PyObject *" << param_name; if (is_optional) { - out << " = NULL"; + out << " = nullptr"; } out << ";\n"; format_specifiers += "O"; @@ -5449,6 +5452,9 @@ write_function_instance(ostream &out, FunctionRemap *remap, if (TypeManager::is_reference_count(obj_type)) { // We use a PointerTo to handle the management here. It's cleaner // that way. + if (default_expr == " = 0" || default_expr == " = nullptr") { + default_expr.clear(); + } if (TypeManager::is_const_pointer_to_anything(type)) { extra_convert << "CPT(" << class_name << ") " << param_name << "_this" @@ -5479,16 +5485,16 @@ write_function_instance(ostream &out, FunctionRemap *remap, if (is_optional && maybe_none) { extra_convert << default_expr << ";\n" - << "if (" << param_name << " != NULL && " << param_name << " != Py_None) {\n" + << "if (" << param_name << " != nullptr && " << param_name << " != Py_None) {\n" << " " << param_name << "_this"; } else if (is_optional) { extra_convert << default_expr << ";\n" - << "if (" << param_name << " != NULL) {\n" + << "if (" << param_name << " != nullptr) {\n" << " " << param_name << "_this"; } else if (maybe_none) { extra_convert - << " = NULL;\n" + << " = nullptr;\n" << "if (" << param_name << " != Py_None) {\n" << " " << param_name << "_this"; } @@ -5500,7 +5506,7 @@ write_function_instance(ostream &out, FunctionRemap *remap, extra_convert << "}\n"; } - coerce_call = "(" + param_name + "_this != NULL)"; + coerce_call = "(" + param_name + "_this != nullptr)"; pexpr_string = param_name + "_this"; } @@ -5508,9 +5514,9 @@ write_function_instance(ostream &out, FunctionRemap *remap, if (report_errors) { // We were asked to report any errors. Let's do it. if (is_optional && maybe_none) { - extra_convert << "if (" << param_name << " != NULL && " << param_name << " != Py_None && !" << coerce_call << ") {\n"; + extra_convert << "if (" << param_name << " != nullptr && " << param_name << " != Py_None && !" << coerce_call << ") {\n"; } else if (is_optional) { - extra_convert << "if (" << param_name << " != NULL && !" << coerce_call << ") {\n"; + extra_convert << "if (" << param_name << " != nullptr && !" << coerce_call << ") {\n"; } else if (maybe_none) { extra_convert << "if (" << param_name << " != Py_None && !" << coerce_call << ") {\n"; } else { @@ -5536,10 +5542,10 @@ write_function_instance(ostream &out, FunctionRemap *remap, extra_convert << "}\n"; } else if (is_optional && maybe_none) { - extra_param_check << " && (" << param_name << " == NULL || " << param_name << " == Py_None || " << coerce_call << ")"; + extra_param_check << " && (" << param_name << " == nullptr || " << param_name << " == Py_None || " << coerce_call << ")"; } else if (is_optional) { - extra_param_check << " && (" << param_name << " == NULL || " << coerce_call << ")"; + extra_param_check << " && (" << param_name << " == nullptr || " << coerce_call << ")"; } else if (maybe_none) { extra_param_check << " && (" << param_name << " == Py_None || " << coerce_call << ")"; @@ -5553,16 +5559,16 @@ write_function_instance(ostream &out, FunctionRemap *remap, if (is_optional && maybe_none) { extra_convert << default_expr << ";\n" - << "if (" << param_name << " != NULL && " << param_name << " != Py_None) {\n" + << "if (" << param_name << " != nullptr && " << param_name << " != Py_None) {\n" << " " << param_name << "_this"; } else if (is_optional) { extra_convert << default_expr << ";\n" - << "if (" << param_name << " != NULL) {\n" + << "if (" << param_name << " != nullptr) {\n" << " " << param_name << "_this"; } else if (maybe_none) { extra_convert - << " = NULL;\n" + << " = nullptr;\n" << "if (" << param_name << " != Py_None) {\n" << " " << param_name << "_this"; } @@ -5570,7 +5576,7 @@ write_function_instance(ostream &out, FunctionRemap *remap, // This function does the same thing in this case and is slightly // simpler. But maybe we should just reorganize these functions // entirely? - extra_convert << " = NULL;\n"; + extra_convert << " = nullptr;\n"; int indent_level = (is_optional || maybe_none) ? 2 : 0; indent(extra_convert, indent_level) << "DtoolInstance_GetPointer(" << param_name @@ -5578,7 +5584,7 @@ write_function_instance(ostream &out, FunctionRemap *remap, << ", *Dtool_Ptr_" << make_safe_name(class_name) << ");\n"; } else { - extra_convert << boolalpha + extra_convert << std::boolalpha << " = (" << class_name << " *)" << "DTOOL_Call_GetPointerThisClass(" << param_name << ", Dtool_Ptr_" << make_safe_name(class_name) @@ -5589,15 +5595,15 @@ write_function_instance(ostream &out, FunctionRemap *remap, if (is_optional && maybe_none) { extra_convert << "}\n"; - extra_param_check << " && (" << param_name << " == NULL || " << param_name << " == Py_None || " << param_name << "_this != NULL)"; + extra_param_check << " && (" << param_name << " == nullptr || " << param_name << " == Py_None || " << param_name << "_this != nullptr)"; } else if (is_optional) { extra_convert << "}\n"; - extra_param_check << " && (" << param_name << " == NULL || " << param_name << "_this != NULL)"; + extra_param_check << " && (" << param_name << " == nullptr || " << param_name << "_this != nullptr)"; } else if (maybe_none) { extra_convert << "}\n"; - extra_param_check << " && (" << param_name << " == Py_None || " << param_name << "_this != NULL)"; + extra_param_check << " && (" << param_name << " == Py_None || " << param_name << "_this != nullptr)"; } else { - extra_param_check << " && " << param_name << "_this != NULL"; + extra_param_check << " && " << param_name << "_this != nullptr"; } pexpr_string = param_name + "_this"; @@ -5657,7 +5663,7 @@ write_function_instance(ostream &out, FunctionRemap *remap, // We have to use the more expensive PyArg_ParseTupleAndKeywords. clear_error = true; indent(out, indent_level) - << "static const char *keyword_list[] = {" << keyword_list << ", NULL};\n"; + << "static const char *keyword_list[] = {" << keyword_list << ", nullptr};\n"; indent(out, indent_level) << "if (PyArg_ParseTupleAndKeywords(args, kwds, \"" << format_specifiers << ":" << method_name @@ -5681,7 +5687,7 @@ write_function_instance(ostream &out, FunctionRemap *remap, } else { clear_error = true; indent(out, indent_level) - << "if ((kwds == NULL || PyDict_Size(kwds) == 0) && PyArg_UnpackTuple(args, \"" + << "if ((kwds == nullptr || PyDict_Size(kwds) == 0) && PyArg_UnpackTuple(args, \"" << methodNameFromCppName(remap, "", false) << "\", " << min_num_args << ", " << max_num_args << parameter_list << ")) {\n"; @@ -5690,7 +5696,7 @@ write_function_instance(ostream &out, FunctionRemap *remap, } else { clear_error = true; indent(out, indent_level) - << "if ((kwds == NULL || PyDict_Size(kwds) == 0) && PyArg_ParseTuple(args, \"" + << "if ((kwds == nullptr || PyDict_Size(kwds) == 0) && PyArg_ParseTuple(args, \"" << format_specifiers << ":" << method_name << "\"" << parameter_list << ")) {\n"; } @@ -5787,14 +5793,14 @@ write_function_instance(ostream &out, FunctionRemap *remap, << "PyObject *self = Dtool_new_" << make_safe_name(itype.get_scoped_name()) << "(&" << CLASS_PREFIX << make_safe_name(itype.get_scoped_name()) - << "._PyType, NULL, NULL);\n"; + << "._PyType, nullptr, nullptr);\n"; extra_cleanup << "PyObject_Del(self);\n"; } else { // XXX rdb: this isn't needed, is it, because tp_new already initializes // the instance? indent(out, indent_level) - << "DTool_PyInit_Finalize(self, NULL, &" + << "DTool_PyInit_Finalize(self, nullptr, &" << CLASS_PREFIX << make_safe_name(itype.get_scoped_name()) << ", false, false);\n"; } @@ -5887,7 +5893,7 @@ write_function_instance(ostream &out, FunctionRemap *remap, if (manage_return) { // If a constructor returns NULL, that means allocation failed. if (remap->_return_type->return_value_needs_management()) { - indent(out, indent_level) << "if (return_value == NULL) {\n"; + indent(out, indent_level) << "if (return_value == nullptr) {\n"; if ((return_flags & ~RF_pyobject) == RF_err_null) { // PyErr_NoMemory returns NULL, so allow tail call elimination. indent(out, indent_level) << " return PyErr_NoMemory();\n"; @@ -5988,7 +5994,7 @@ write_function_instance(ostream &out, FunctionRemap *remap, indent(out, indent_level) << " // TypeError raised; continue to next overload type.\n"; indent(out, indent_level) - << "} else if (exception != (PyObject *)NULL) {\n"; + << "} else if (exception != nullptr) {\n"; } if (manage_return) { @@ -6089,8 +6095,8 @@ write_function_instance(ostream &out, FunctionRemap *remap, indent(out, indent_level) << "return Py_None;\n"; } else if (return_flags & RF_preserve_null) { - indent(out, indent_level) << "if (" << return_expr << " == NULL) {\n"; - indent(out, indent_level) << " return NULL;\n"; + indent(out, indent_level) << "if (" << return_expr << " == nullptr) {\n"; + indent(out, indent_level) << " return nullptr;\n"; indent(out, indent_level) << "} else {\n"; pack_return_value(out, indent_level + 2, remap, return_expr, return_flags); indent(out, indent_level) << "}\n"; @@ -6202,7 +6208,7 @@ error_return(ostream &out, int indent_level, int return_flags) { indent(out, indent_level) << "return Py_NotImplemented;\n"; } else if (return_flags & RF_err_null) { - indent(out, indent_level) << "return NULL;\n"; + indent(out, indent_level) << "return nullptr;\n"; } else if (return_flags & RF_err_false) { indent(out, indent_level) << "return false;\n"; @@ -6275,7 +6281,24 @@ pack_return_value(ostream &out, int indent_level, FunctionRemap *remap, CPPType *orig_type = return_type->get_orig_type(); CPPType *type = return_type->get_new_type(); - if (return_type->new_type_is_atomic_string() || + if (TypeManager::is_scoped_enum(type)) { + InterrogateDatabase *idb = InterrogateDatabase::get_ptr(); + TypeIndex type_index = builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(orig_type)), false); + const InterrogateType &itype = idb->get_type(type_index); + string safe_name = make_safe_name(itype.get_scoped_name()); + + indent(out, indent_level) + << "return PyObject_CallFunction((PyObject *)Dtool_Ptr_" << safe_name; + + CPPType *underlying_type = ((CPPEnumType *)itype._cpptype)->get_underlying_type(); + if (TypeManager::is_unsigned_integer(underlying_type)) { + out << ", \"k\", (unsigned long)"; + } else { + out << ", \"l\", (long)"; + } + out << "(" << return_expr << "));\n"; + + } else if (return_type->new_type_is_atomic_string() || TypeManager::is_simple(type) || TypeManager::is_char_pointer(type) || TypeManager::is_wchar_pointer(type) || @@ -6302,7 +6325,7 @@ pack_return_value(ostream &out, int indent_level, FunctionRemap *remap, indent(out, indent_level); type->output_instance(out, "return_ptr", &parser); out << " = " << return_expr << ";\n"; - indent(out, indent_level) << "return_value.cheat() = NULL;\n"; + indent(out, indent_level) << "return_value.cheat() = nullptr;\n"; return_expr = "return_ptr"; } @@ -6361,9 +6384,9 @@ write_make_seq(ostream &out, Object *obj, const std::string &ClassName, if (make_seq->_length_getter->_has_this) { out << - " " << cClassName << " *local_this = NULL;\n" + " " << cClassName << " *local_this = nullptr;\n" " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n" - " return NULL;\n" + " return nullptr;\n" " }\n" " Py_ssize_t count = (Py_ssize_t)" << remap->get_call_str("local_this", pexprs) << ";\n"; } else { @@ -6389,7 +6412,7 @@ write_make_seq(ostream &out, Object *obj, const std::string &ClassName, switch (elem_getter->_args_type) { case AT_keyword_args: out << " PyTuple_SET_ITEM(&args, 0, index);\n" - " PyObject *value = " << elem_getter->_name << "(self, (PyObject *)&args, NULL);\n"; + " PyObject *value = " << elem_getter->_name << "(self, (PyObject *)&args, nullptr);\n"; break; case AT_varargs: @@ -6402,7 +6425,7 @@ write_make_seq(ostream &out, Object *obj, const std::string &ClassName, break; default: - out << " PyObject *value = " << elem_getter->_name << "(self, NULL);\n"; + out << " PyObject *value = " << elem_getter->_name << "(self, nullptr);\n"; break; } @@ -6419,7 +6442,7 @@ write_make_seq(ostream &out, Object *obj, const std::string &ClassName, out << " if (Dtool_CheckErrorOccurred()) {\n" " Py_DECREF(tuple);\n" - " return NULL;\n" + " return nullptr;\n" " }\n" " return tuple;\n" "}\n" @@ -6452,7 +6475,7 @@ write_getset(ostream &out, Object *obj, Property *property) { "static Py_ssize_t Dtool_" + ClassName + "_" + ielem.get_name() + "_Len(PyObject *self) {\n"; if (property->_length_function->_has_this) { out << - " " << cClassName << " *local_this = NULL;\n" + " " << cClassName << " *local_this = nullptr;\n" " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n" " return -1;\n" " }\n" @@ -6477,9 +6500,9 @@ write_getset(ostream &out, Object *obj, Property *property) { if (property->_has_this) { out << - " " << cClassName << " *local_this = NULL;\n" + " " << cClassName << " *local_this = nullptr;\n" " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n" - " return NULL;\n" + " return nullptr;\n" " }\n"; } @@ -6488,7 +6511,7 @@ write_getset(ostream &out, Object *obj, Property *property) { out << " if (index < 0 || index >= (Py_ssize_t)" << len_remap->get_call_str("local_this", pexprs) << ") {\n"; out << " PyErr_SetString(PyExc_IndexError, \"" << ClassName << "." << ielem.get_name() << "[] index out of range\");\n"; - out << " return NULL;\n"; + out << " return nullptr;\n"; out << " }\n"; /*if (property->_has_function != NULL) { @@ -6501,11 +6524,7 @@ write_getset(ostream &out, Object *obj, Property *property) { std::set remaps; // Extract only the getters that take one integral argument. - Function::Remaps::iterator it; - for (it = property->_getter_remaps.begin(); - it != property->_getter_remaps.end(); - ++it) { - FunctionRemap *remap = *it; + for (FunctionRemap *remap : property->_getter_remaps) { int min_num_args = remap->get_min_num_args(); int max_num_args = remap->get_max_num_args(); if (min_num_args <= 1 && max_num_args >= 1 && @@ -6529,7 +6548,7 @@ write_getset(ostream &out, Object *obj, Property *property) { if (!property->_setter_remaps.empty()) { out << "static int Dtool_" + ClassName + "_" + ielem.get_name() + "_Sequence_Setitem(PyObject *self, Py_ssize_t index, PyObject *arg) {\n"; if (property->_has_this) { - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " if (!Dtool_Call_ExtractThisPointer_NonConst(self, Dtool_" << ClassName << ", (void **)&local_this, \"" << classNameFromCppName(cClassName, false) << "." << ielem.get_name() << "\")) {\n"; out << " return -1;\n"; @@ -6542,8 +6561,8 @@ write_getset(ostream &out, Object *obj, Property *property) { out << " return -1;\n"; out << " }\n"; - out << " if (arg == (PyObject *)NULL) {\n"; - if (property->_deleter != NULL) { + out << " if (arg == nullptr) {\n"; + if (property->_deleter != nullptr) { if (property->_deleter->_has_this) { out << " local_this->" << property->_deleter->_ifunc.get_name() << "(index);\n"; } else { @@ -6556,7 +6575,7 @@ write_getset(ostream &out, Object *obj, Property *property) { } out << " }\n"; - if (property->_clear_function != NULL) { + if (property->_clear_function != nullptr) { out << " if (arg == Py_None) {\n"; if (property->_clear_function->_has_this) { out << " local_this->" << property->_clear_function->_ifunc.get_name() << "(index);\n"; @@ -6570,11 +6589,7 @@ write_getset(ostream &out, Object *obj, Property *property) { std::set remaps; // Extract only the setters that take two arguments. - Function::Remaps::iterator it; - for (it = property->_setter_remaps.begin(); - it != property->_setter_remaps.end(); - ++it) { - FunctionRemap *remap = *it; + for (FunctionRemap *remap : property->_setter_remaps) { int min_num_args = remap->get_min_num_args(); int max_num_args = remap->get_max_num_args(); if (min_num_args <= 2 && max_num_args >= 2 && @@ -6601,10 +6616,10 @@ write_getset(ostream &out, Object *obj, Property *property) { if (property->_inserter != nullptr) { out << "static PyObject *Dtool_" + ClassName + "_" + ielem.get_name() + "_Sequence_insert(PyObject *self, size_t index, PyObject *arg) {\n"; if (property->_has_this) { - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " if (!Dtool_Call_ExtractThisPointer_NonConst(self, Dtool_" << ClassName << ", (void **)&local_this, \"" << classNameFromCppName(cClassName, false) << "." << ielem.get_name() << "\")) {\n"; - out << " return NULL;\n"; + out << " return nullptr;\n"; out << " }\n\n"; } @@ -6622,7 +6637,7 @@ write_getset(ostream &out, Object *obj, Property *property) { output_quoted(out, 6, expected_params); out << ");\n"; out << " }\n"; - out << " return NULL;\n"; + out << " return nullptr;\n"; out << "}\n\n"; } } @@ -6651,13 +6666,13 @@ write_getset(ostream &out, Object *obj, Property *property) { if (property->_has_this) { out << - " " << cClassName << " *local_this = NULL;\n" + " " << cClassName << " *local_this = nullptr;\n" " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n" - " return NULL;\n" + " return nullptr;\n" " }\n"; } - if (property->_has_function != NULL) { + if (property->_has_function != nullptr) { std::set remaps; remaps.insert(property->_has_function->_remaps.begin(), property->_has_function->_remaps.end()); @@ -6672,11 +6687,7 @@ write_getset(ostream &out, Object *obj, Property *property) { std::set remaps; // Extract only the getters that take one argument. Fish out the ones // already taken by the sequence getter. - Function::Remaps::iterator it; - for (it = property->_getter_remaps.begin(); - it != property->_getter_remaps.end(); - ++it) { - FunctionRemap *remap = *it; + for (FunctionRemap *remap : property->_getter_remaps) { int min_num_args = remap->get_min_num_args(); int max_num_args = remap->get_max_num_args(); if (min_num_args <= 1 && max_num_args >= 1 && @@ -6694,7 +6705,7 @@ write_getset(ostream &out, Object *obj, Property *property) { output_quoted(out, 6, expected_params); out << ");\n" " }\n" - " return NULL;\n" + " return nullptr;\n" "}\n\n"; // Write out a setitem if this is not a read-only property. @@ -6707,18 +6718,18 @@ write_getset(ostream &out, Object *obj, Property *property) { if (property->_has_this) { out << - " " << cClassName << " *local_this = NULL;\n" + " " << cClassName << " *local_this = nullptr;\n" " if (!Dtool_Call_ExtractThisPointer_NonConst(self, Dtool_" << ClassName << ", (void **)&local_this, \"" << classNameFromCppName(cClassName, false) << "." << ielem.get_name() << "\")) {\n" " return -1;\n" " }\n\n"; } - out << " if (value == (PyObject *)NULL) {\n"; - if (property->_deleter != NULL) { + out << " if (value == nullptr) {\n"; + if (property->_deleter != nullptr) { out << " PyObject *arg = key;\n"; - if (property->_has_function != NULL) { + if (property->_has_function != nullptr) { std::set remaps; remaps.insert(property->_has_function->_remaps.begin(), property->_has_function->_remaps.end()); @@ -6745,7 +6756,7 @@ write_getset(ostream &out, Object *obj, Property *property) { } out << " }\n"; - if (property->_clear_function != NULL) { + if (property->_clear_function != nullptr) { out << " if (value == Py_None) {\n" << " local_this->" << property->_clear_function->_ifunc.get_name() << "(key);\n" << " return 0;\n" @@ -6787,9 +6798,9 @@ write_getset(ostream &out, Object *obj, Property *property) { if (property->_has_this) { out << - " " << cClassName << " *local_this = NULL;\n" + " " << cClassName << " *local_this = nullptr;\n" " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n" - " return NULL;\n" + " return nullptr;\n" " }\n"; } @@ -6798,18 +6809,14 @@ write_getset(ostream &out, Object *obj, Property *property) { out << " if (index < 0 || index >= (Py_ssize_t)" << len_remap->get_call_str("local_this", pexprs) << ") {\n"; out << " PyErr_SetString(PyExc_IndexError, \"" << ClassName << "." << ielem.get_name() << "[] index out of range\");\n"; - out << " return NULL;\n"; + out << " return nullptr;\n"; out << " }\n"; } std::set remaps; // Extract only the getters that take one integral argument. - Function::Remaps::iterator it; - for (it = property->_getkey_function->_remaps.begin(); - it != property->_getkey_function->_remaps.end(); - ++it) { - FunctionRemap *remap = *it; + for (FunctionRemap *remap : property->_getkey_function->_remaps) { int min_num_args = remap->get_min_num_args(); int max_num_args = remap->get_max_num_args(); if (min_num_args <= 1 && max_num_args >= 1 && @@ -6836,14 +6843,14 @@ write_getset(ostream &out, Object *obj, Property *property) { if (ielem.is_mapping()) { out << "static PyObject *Dtool_" + ClassName + "_" + ielem.get_name() + "_Getter(PyObject *self, void *) {\n"; if (property->_has_this) { - out << " nassertr(self != NULL, NULL);\n"; + out << " nassertr(self != nullptr, nullptr);\n"; } if (property->_setter_remaps.empty()) { out << " Dtool_MappingWrapper *wrap = Dtool_NewMappingWrapper(self, \"" << ClassName << "." << ielem.get_name() << "\");\n"; } else { out << " Dtool_MappingWrapper *wrap = Dtool_NewMutableMappingWrapper(self, \"" << ClassName << "." << ielem.get_name() << "\");\n"; } - out << " if (wrap != NULL) {\n" + out << " if (wrap != nullptr) {\n" " wrap->_getitem_func = &Dtool_" << ClassName << "_" << ielem.get_name() << "_Mapping_Getitem;\n"; if (!property->_setter_remaps.empty()) { out << " if (!DtoolInstance_IS_CONST(self)) {\n"; @@ -6863,18 +6870,18 @@ write_getset(ostream &out, Object *obj, Property *property) { } else if (ielem.is_sequence()) { out << "static PyObject *Dtool_" + ClassName + "_" + ielem.get_name() + "_Getter(PyObject *self, void *) {\n"; if (property->_has_this) { - out << " nassertr(self != NULL, NULL);\n"; + out << " nassertr(self != nullptr, nullptr);\n"; } if (property->_setter_remaps.empty()) { out << " Dtool_SequenceWrapper *wrap = Dtool_NewSequenceWrapper(self, \"" << ClassName << "." << ielem.get_name() << "\");\n" - " if (wrap != NULL) {\n" + " if (wrap != nullptr) {\n" " wrap->_len_func = &Dtool_" << ClassName << "_" << ielem.get_name() << "_Len;\n" " wrap->_getitem_func = &Dtool_" << ClassName << "_" << ielem.get_name() << "_Sequence_Getitem;\n"; } else { out << " Dtool_MutableSequenceWrapper *wrap = Dtool_NewMutableSequenceWrapper(self, \"" << ClassName << "." << ielem.get_name() << "\");\n" - " if (wrap != NULL) {\n" + " if (wrap != nullptr) {\n" " wrap->_len_func = &Dtool_" << ClassName << "_" << ielem.get_name() << "_Len;\n" " wrap->_getitem_func = &Dtool_" << ClassName << "_" << ielem.get_name() << "_Sequence_Getitem;\n"; if (!property->_setter_remaps.empty()) { @@ -6897,18 +6904,18 @@ write_getset(ostream &out, Object *obj, Property *property) { if (remap->_has_this) { if (remap->_const_method) { - out << " const " << cClassName << " *local_this = NULL;\n"; + out << " const " << cClassName << " *local_this = nullptr;\n"; out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n"; } else { - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " if (!Dtool_Call_ExtractThisPointer_NonConst(self, Dtool_" << ClassName << ", (void **)&local_this, \"" << classNameFromCppName(cClassName, false) << "." << ielem.get_name() << "\")) {\n"; } - out << " return NULL;\n"; + out << " return nullptr;\n"; out << " }\n\n"; } - if (property->_has_function != NULL) { + if (property->_has_function != nullptr) { if (remap->_has_this) { out << " if (!local_this->" << property->_has_function->_ifunc.get_name() << "()) {\n"; } else { @@ -6932,18 +6939,18 @@ write_getset(ostream &out, Object *obj, Property *property) { if (!property->_setter_remaps.empty()) { out << "static int Dtool_" + ClassName + "_" + ielem.get_name() + "_Setter(PyObject *self, PyObject *arg, void *) {\n"; if (remap->_has_this) { - out << " " << cClassName << " *local_this = NULL;\n"; + out << " " << cClassName << " *local_this = nullptr;\n"; out << " if (!Dtool_Call_ExtractThisPointer_NonConst(self, Dtool_" << ClassName << ", (void **)&local_this, \"" << classNameFromCppName(cClassName, false) << "." << ielem.get_name() << "\")) {\n"; out << " return -1;\n"; out << " }\n\n"; } - out << " if (arg == (PyObject *)NULL) {\n"; - if (property->_deleter != NULL && remap->_has_this) { + out << " if (arg == nullptr) {\n"; + if (property->_deleter != nullptr && remap->_has_this) { out << " local_this->" << property->_deleter->_ifunc.get_name() << "();\n" << " return 0;\n"; - } else if (property->_deleter != NULL) { + } else if (property->_deleter != nullptr) { out << " " << cClassName << "::" << property->_deleter->_ifunc.get_name() << "();\n" << " return 0;\n"; } else { @@ -6952,7 +6959,7 @@ write_getset(ostream &out, Object *obj, Property *property) { } out << " }\n"; - if (property->_clear_function != NULL) { + if (property->_clear_function != nullptr) { out << " if (arg == Py_None) {\n"; if (remap->_has_this) { out << " local_this->" << property->_clear_function->_ifunc.get_name() << "();\n"; @@ -6966,11 +6973,7 @@ write_getset(ostream &out, Object *obj, Property *property) { std::set remaps; // Extract only the setters that take one argument. - Function::Remaps::iterator it; - for (it = property->_setter_remaps.begin(); - it != property->_setter_remaps.end(); - ++it) { - FunctionRemap *remap = *it; + for (FunctionRemap *remap : property->_setter_remaps) { int min_num_args = remap->get_min_num_args(); int max_num_args = remap->get_max_num_args(); if (min_num_args <= 1 && max_num_args >= 1) { @@ -7001,7 +7004,7 @@ write_getset(ostream &out, Object *obj, Property *property) { InterfaceMaker::Object *InterfaceMakerPythonNative:: record_object(TypeIndex type_index) { if (type_index == 0) { - return (Object *)NULL; + return nullptr; } Objects::iterator oi = _objects.find(type_index); @@ -7013,7 +7016,7 @@ record_object(TypeIndex type_index) { const InterrogateType &itype = idb->get_type(type_index); if (!is_cpp_type_legal(itype._cpptype)) { - return (Object *)NULL; + return nullptr; } Object *object = new Object(itype); @@ -7079,9 +7082,8 @@ record_object(TypeIndex type_index) { int num_elements = itype.number_of_elements(); for (int ei = 0; ei < num_elements; ei++) { ElementIndex element_index = itype.get_element(ei); - const InterrogateElement &ielement = idb->get_element(element_index); - Property *property = record_property(itype, itype.get_element(ei)); + Property *property = record_property(itype, element_index); if (property != nullptr) { object->_properties.push_back(property); } else { @@ -7286,7 +7288,7 @@ generate_wrappers() { */ bool InterfaceMakerPythonNative:: is_cpp_type_legal(CPPType *in_ctype) { - if (in_ctype == NULL) { + if (in_ctype == nullptr) { return false; } @@ -7302,6 +7304,10 @@ is_cpp_type_legal(CPPType *in_ctype) { // bool answer = false; CPPType *type = TypeManager::resolve_type(in_ctype); + if (TypeManager::is_rvalue_reference(type)) { + return false; + } + type = TypeManager::unwrap(type); if (TypeManager::is_void(type)) { @@ -7356,13 +7362,11 @@ isExportThisRun(CPPType *ctype) { */ bool InterfaceMakerPythonNative:: isExportThisRun(Function *func) { - if (func == NULL || !is_function_legal(func)) { + if (func == nullptr || !is_function_legal(func)) { return false; } - Function::Remaps::const_iterator ri; - for (ri = func->_remaps.begin(); ri != func->_remaps.end();) { - FunctionRemap *remap = (*ri); + for (FunctionRemap *remap : func->_remaps) { return isExportThisRun(remap->_cpptype); } @@ -7374,7 +7378,7 @@ isExportThisRun(Function *func) { */ bool InterfaceMakerPythonNative:: is_remap_legal(FunctionRemap *remap) { - if (remap == NULL) { + if (remap == nullptr) { return false; } @@ -7401,7 +7405,7 @@ is_remap_legal(FunctionRemap *remap) { for (size_t pn = 0; pn < remap->_parameters.size(); pn++) { ParameterRemap *param = remap->_parameters[pn]._remap; CPPType *orig_type = param->get_orig_type(); - if (param->get_default_value() == NULL && !is_cpp_type_legal(orig_type)) { + if (param->get_default_value() == nullptr && !is_cpp_type_legal(orig_type)) { return false; } } @@ -7415,7 +7419,7 @@ is_remap_legal(FunctionRemap *remap) { */ int InterfaceMakerPythonNative:: has_coerce_constructor(CPPStructType *type) { - if (type == NULL) { + if (type == nullptr) { return 0; } @@ -7428,7 +7432,7 @@ has_coerce_constructor(CPPStructType *type) { } CPPScope *scope = type->get_scope(); - if (scope == NULL) { + if (scope == nullptr) { return 0; } @@ -7437,12 +7441,9 @@ has_coerce_constructor(CPPStructType *type) { CPPScope::Functions::iterator fgi; for (fgi = scope->_functions.begin(); fgi != scope->_functions.end(); ++fgi) { CPPFunctionGroup *fgroup = fgi->second; - - CPPFunctionGroup::Instances::iterator ii; - for (ii = fgroup->_instances.begin(); ii != fgroup->_instances.end(); ++ii) { - CPPInstance *inst = (*ii); + for (CPPInstance *inst : fgroup->_instances) { CPPFunctionType *ftype = inst->_type->as_function_type(); - if (ftype == NULL) { + if (ftype == nullptr) { continue; } if (inst->_storage_class & CPPInstance::SC_explicit) { @@ -7488,7 +7489,7 @@ has_coerce_constructor(CPPStructType *type) { */ bool InterfaceMakerPythonNative:: is_remap_coercion_possible(FunctionRemap *remap) { - if (remap == NULL) { + if (remap == nullptr) { return false; } @@ -7525,9 +7526,7 @@ is_remap_coercion_possible(FunctionRemap *remap) { */ bool InterfaceMakerPythonNative:: is_function_legal(Function *func) { - Function::Remaps::const_iterator ri; - for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri) { - FunctionRemap *remap = (*ri); + for (FunctionRemap *remap : func->_remaps) { if (is_remap_legal(remap)) { // printf(" Function Is Marked Legal %s\n",func->_name.c_str()); @@ -7564,7 +7563,7 @@ IsRunTimeTyped(const InterrogateType &itype) { */ bool InterfaceMakerPythonNative:: DoesInheritFromIsClass(const CPPStructType *inclass, const std::string &name) { - if (inclass == NULL) { + if (inclass == nullptr) { return false; } @@ -7573,15 +7572,9 @@ DoesInheritFromIsClass(const CPPStructType *inclass, const std::string &name) { return true; } - CPPStructType::Derivation::const_iterator bi; - for (bi = inclass->_derivation.begin(); - bi != inclass->_derivation.end(); - ++bi) { - - const CPPStructType::Base &base = (*bi); - + for (const CPPStructType::Base &base : inclass->_derivation) { CPPStructType *base_type = TypeManager::resolve_type(base._base)->as_struct_type(); - if (base_type != NULL) { + if (base_type != nullptr) { if (DoesInheritFromIsClass(base_type, name)) { return true; } @@ -7600,7 +7593,7 @@ has_get_class_type_function(CPPType *type) { } CPPStructType *struct_type = type->as_struct_type(); - if (struct_type == NULL) { + if (struct_type == nullptr) { return false; } @@ -7619,7 +7612,7 @@ has_init_type_function(CPPType *type) { } CPPStructType *struct_type = type->as_struct_type(); - if (struct_type == NULL) { + if (struct_type == nullptr) { return false; } @@ -7630,13 +7623,11 @@ has_init_type_function(CPPType *type) { } const CPPFunctionGroup *group = it->second; - CPPFunctionGroup::Instances::const_iterator ii; - for (ii = group->_instances.begin(); ii != group->_instances.end(); ++ii) { - const CPPInstance *cppinst = *ii; + for (const CPPInstance *cppinst : group->_instances) { const CPPFunctionType *cppfunc = cppinst->_type->as_function_type(); - if (cppfunc != NULL && - cppfunc->_parameters != NULL && + if (cppfunc != nullptr && + cppfunc->_parameters != nullptr && cppfunc->_parameters->_parameters.size() == 0 && (cppinst->_storage_class & CPPInstance::SC_static) != 0) { return true; @@ -7668,7 +7659,7 @@ NeedsAStrFunction(const InterrogateType &itype_class) { FunctionIndex func_index = itype_class.get_method(mi); const InterrogateFunction &ifunc = idb->get_function(func_index); if (ifunc.get_name() == "write") { - if (ifunc._instances != (InterrogateFunction::Instances *)NULL) { + if (ifunc._instances != nullptr) { InterrogateFunction::Instances::const_iterator ii; for (ii = ifunc._instances->begin(); ii != ifunc._instances->end(); @@ -7676,9 +7667,9 @@ NeedsAStrFunction(const InterrogateType &itype_class) { CPPInstance *cppinst = (*ii).second; CPPFunctionType *cppfunc = cppinst->_type->as_function_type(); - if (cppfunc != NULL) { - if (cppfunc->_parameters != NULL && - cppfunc->_return_type != NULL && + if (cppfunc != nullptr) { + if (cppfunc->_parameters != nullptr && + cppfunc->_return_type != nullptr && TypeManager::is_void(cppfunc->_return_type)) { if (cppfunc->_parameters->_parameters.size() == 1) { CPPInstance *inst1 = cppfunc->_parameters->_parameters[0]; @@ -7692,7 +7683,7 @@ NeedsAStrFunction(const InterrogateType &itype_class) { CPPInstance *inst1 = cppfunc->_parameters->_parameters[0]; if (TypeManager::is_pointer_to_ostream(inst1->_type)) { inst1 = cppfunc->_parameters->_parameters[1]; - if (inst1->_initializer != NULL) { + if (inst1->_initializer != nullptr) { // write(ostream, int = 0) return 1; } @@ -7738,7 +7729,7 @@ NeedsAReprFunction(const InterrogateType &itype_class) { FunctionIndex func_index = itype_class.get_method(mi); const InterrogateFunction &ifunc = idb->get_function(func_index); if (ifunc.get_name() == "python_repr") { - if (ifunc._instances != (InterrogateFunction::Instances *)NULL) { + if (ifunc._instances != nullptr) { InterrogateFunction::Instances::const_iterator ii; for (ii = ifunc._instances->begin(); ii != ifunc._instances->end(); @@ -7746,9 +7737,9 @@ NeedsAReprFunction(const InterrogateType &itype_class) { CPPInstance *cppinst = (*ii).second; CPPFunctionType *cppfunc = cppinst->_type->as_function_type(); - if (cppfunc != NULL) { - if (cppfunc->_parameters != NULL && - cppfunc->_return_type != NULL && + if (cppfunc != nullptr) { + if (cppfunc->_parameters != nullptr && + cppfunc->_return_type != nullptr && TypeManager::is_void(cppfunc->_return_type)) { if (cppfunc->_parameters->_parameters.size() == 2) { CPPInstance *inst1 = cppfunc->_parameters->_parameters[0]; @@ -7776,7 +7767,7 @@ NeedsAReprFunction(const InterrogateType &itype_class) { FunctionIndex func_index = itype_class.get_method(mi); const InterrogateFunction &ifunc = idb->get_function(func_index); if (ifunc.get_name() == "output") { - if (ifunc._instances != (InterrogateFunction::Instances *)NULL) { + if (ifunc._instances != nullptr) { InterrogateFunction::Instances::const_iterator ii; for (ii = ifunc._instances->begin(); ii != ifunc._instances->end(); @@ -7784,9 +7775,9 @@ NeedsAReprFunction(const InterrogateType &itype_class) { CPPInstance *cppinst = (*ii).second; CPPFunctionType *cppfunc = cppinst->_type->as_function_type(); - if (cppfunc != NULL) { - if (cppfunc->_parameters != NULL && - cppfunc->_return_type != NULL && + if (cppfunc != nullptr) { + if (cppfunc->_parameters != nullptr && + cppfunc->_return_type != nullptr && TypeManager::is_void(cppfunc->_return_type)) { if (cppfunc->_parameters->_parameters.size() == 1) { CPPInstance *inst1 = cppfunc->_parameters->_parameters[0]; @@ -7800,7 +7791,7 @@ NeedsAReprFunction(const InterrogateType &itype_class) { CPPInstance *inst1 = cppfunc->_parameters->_parameters[0]; if (TypeManager::is_pointer_to_ostream(inst1->_type)) { inst1 = cppfunc->_parameters->_parameters[1]; - if (inst1->_initializer != NULL) { + if (inst1->_initializer != nullptr) { // output(ostream, foo = bar, ...) return 2; } @@ -7881,7 +7872,7 @@ output_quoted(ostream &out, int indent_level, const std::string &str, default: if (!isprint(*si)) { - out << "\\" << oct << setw(3) << setfill('0') << (unsigned int)(*si) + out << "\\" << oct << std::setw(3) << std::setfill('0') << (unsigned int)(*si) << dec; } else { out << *si; diff --git a/dtool/src/interrogate/interfaceMakerPythonNative.h b/dtool/src/interrogate/interfaceMakerPythonNative.h index 2c0195fdbf..00374397c9 100644 --- a/dtool/src/interrogate/interfaceMakerPythonNative.h +++ b/dtool/src/interrogate/interfaceMakerPythonNative.h @@ -31,17 +31,17 @@ public: virtual ~InterfaceMakerPythonNative(); - virtual void write_prototypes(ostream &out, ostream *out_h); - void write_prototypes_class(ostream &out, ostream *out_h, Object *obj) ; - void write_prototypes_class_external(ostream &out, Object *obj); + virtual void write_prototypes(std::ostream &out, std::ostream *out_h); + void write_prototypes_class(std::ostream &out, std::ostream *out_h, Object *obj) ; + void write_prototypes_class_external(std::ostream &out, Object *obj); - virtual void write_functions(ostream &out); + virtual void write_functions(std::ostream &out); - virtual void write_module(ostream &out, ostream *out_h, InterrogateModuleDef *def); - virtual void write_module_support(ostream &out, ostream *out_h, InterrogateModuleDef *def); + virtual void write_module(std::ostream &out, std::ostream *out_h, InterrogateModuleDef *def); + virtual void write_module_support(std::ostream &out, std::ostream *out_h, InterrogateModuleDef *def); - void write_module_class(ostream &out, Object *cls); - virtual void write_sub_module(ostream &out, Object *obj); + void write_module_class(std::ostream &out, Object *cls); + virtual void write_sub_module(std::ostream &out, Object *obj); virtual bool synthesize_this_parameter(); virtual bool separate_overloading(); @@ -50,8 +50,8 @@ public: Property *record_property(const InterrogateType &itype, ElementIndex element_index); protected: - virtual string get_wrapper_prefix(); - virtual string get_unique_prefix(); + virtual std::string get_wrapper_prefix(); + virtual std::string get_unique_prefix(); virtual void record_function_wrapper(InterrogateFunction &ifunc, FunctionWrapperIndex wrapper_index); @@ -119,67 +119,67 @@ private: class SlottedFunctionDef { public: - string _answer_location; + std::string _answer_location; WrapperType _wrapper_type; int _min_version; - string _wrapper_name; - set _remaps; + std::string _wrapper_name; + std::set _remaps; bool _keep_method; }; - typedef std::map SlottedFunctions; + typedef std::map SlottedFunctions; static bool get_slotted_function_def(Object *obj, Function *func, FunctionRemap *remap, SlottedFunctionDef &def); - static void write_function_slot(ostream &out, int indent_level, + static void write_function_slot(std::ostream &out, int indent_level, const SlottedFunctions &slots, - const string &slot, const string &def = "0"); + const std::string &slot, const std::string &def = "nullptr"); - void write_prototype_for_name(ostream &out, Function *func, const std::string &name); - void write_prototype_for(ostream &out, Function *func); - void write_function_for_top(ostream &out, Object *obj, Function *func); + void write_prototype_for_name(std::ostream &out, Function *func, const std::string &name); + void write_prototype_for(std::ostream &out, Function *func); + void write_function_for_top(std::ostream &out, Object *obj, Function *func); - void write_function_for_name(ostream &out, Object *obj, + void write_function_for_name(std::ostream &out, Object *obj, const Function::Remaps &remaps, - const std::string &name, string &expected_params, + const std::string &name, std::string &expected_params, bool coercion_allowed, ArgsType args_type, int return_flags); - void write_coerce_constructor(ostream &out, Object *obj, bool is_const); + void write_coerce_constructor(std::ostream &out, Object *obj, bool is_const); int collapse_default_remaps(std::map > &map_sets, int max_required_args); - void write_function_forset(ostream &out, + void write_function_forset(std::ostream &out, const std::set &remaps, int min_num_args, int max_num_args, - string &expected_params, int indent_level, + std::string &expected_params, int indent_level, bool coercion_allowed, bool report_errors, ArgsType args_type, int return_flags, bool check_exceptions = true, bool verify_const = true, - const string &first_expr = string()); + const std::string &first_expr = std::string()); - void write_function_instance(ostream &out, FunctionRemap *remap, + void write_function_instance(std::ostream &out, FunctionRemap *remap, int min_num_args, int max_num_args, - string &expected_params, int indent_level, + std::string &expected_params, int indent_level, bool coercion_allowed, bool report_errors, ArgsType args_type, int return_flags, bool check_exceptions = true, - const string &first_pexpr = string()); + const std::string &first_pexpr = std::string()); - void error_return(ostream &out, int indent_level, int return_flags); - void error_raise_return(ostream &out, int indent_level, int return_flags, - const string &exc_type, const string &message, - const string &format_args = ""); - void pack_return_value(ostream &out, int indent_level, FunctionRemap *remap, + void error_return(std::ostream &out, int indent_level, int return_flags); + void error_raise_return(std::ostream &out, int indent_level, int return_flags, + const std::string &exc_type, const std::string &message, + const std::string &format_args = ""); + void pack_return_value(std::ostream &out, int indent_level, FunctionRemap *remap, std::string return_expr, int return_flags); - void write_make_seq(ostream &out, Object *obj, const std::string &ClassName, + void write_make_seq(std::ostream &out, Object *obj, const std::string &ClassName, const std::string &cClassName, MakeSeq *make_seq); - void write_getset(ostream &out, Object *obj, Property *property); + void write_getset(std::ostream &out, Object *obj, Property *property); - void write_class_prototypes(ostream &out) ; - void write_class_declarations(ostream &out, ostream *out_h, Object *obj); - void write_class_details(ostream &out, Object *obj); + void write_class_prototypes(std::ostream &out) ; + void write_class_declarations(std::ostream &out, std::ostream *out_h, Object *obj); + void write_class_details(std::ostream &out, Object *obj); public: bool is_remap_legal(FunctionRemap *remap); @@ -204,14 +204,14 @@ public: void get_valid_child_classes(std::map &answer, CPPStructType *inclass, const std::string &upcast_seed = "", bool can_downcast = true); bool DoesInheritFromIsClass(const CPPStructType * inclass, const std::string &name); bool IsPandaTypedObject(CPPStructType * inclass) { return DoesInheritFromIsClass(inclass,"TypedObject"); }; - void write_python_instance(ostream &out, int indent_level, const std::string &return_expr, bool owns_memory, const InterrogateType &itype, bool is_const); + void write_python_instance(std::ostream &out, int indent_level, const std::string &return_expr, bool owns_memory, const InterrogateType &itype, bool is_const); bool has_get_class_type_function(CPPType *type); bool has_init_type_function(CPPType *type); int NeedsAStrFunction(const InterrogateType &itype_class); int NeedsAReprFunction(const InterrogateType &itype_class); bool NeedsARichCompareFunction(const InterrogateType &itype_class); - void output_quoted(ostream &out, int indent_level, const std::string &str, + void output_quoted(std::ostream &out, int indent_level, const std::string &str, bool first_line=true); // stash the forward declarations for this compile pass.. diff --git a/dtool/src/interrogate/interfaceMakerPythonObj.cxx b/dtool/src/interrogate/interfaceMakerPythonObj.cxx index af48b2f016..fa0e35eaea 100644 --- a/dtool/src/interrogate/interfaceMakerPythonObj.cxx +++ b/dtool/src/interrogate/interfaceMakerPythonObj.cxx @@ -25,6 +25,9 @@ #include "interrogateFunction.h" #include "cppFunctionType.h" +using std::ostream; +using std::string; + /** * */ @@ -102,17 +105,17 @@ write_module(ostream &out,ostream *out_h, InterrogateModuleDef *def) { << ", METH_VARARGS },\n"; } } - out << " { NULL, NULL }\n" + out << " { nullptr, nullptr }\n" << "};\n\n" << "#if PY_MAJOR_VERSION >= 3\n" << "static struct PyModuleDef python_obj_module = {\n" << " PyModuleDef_HEAD_INIT,\n" << " \"" << def->library_name << "\",\n" - << " NULL,\n" + << " nullptr,\n" << " -1,\n" << " python_obj_funcs,\n" - << " NULL, NULL, NULL, NULL\n" + << " nullptr, nullptr, nullptr, nullptr\n" << "};\n\n" << "#define INIT_FUNC PyObject *PyInit_" << def->library_name << "\n" @@ -171,7 +174,7 @@ get_wrapper_prefix() { void InterfaceMakerPythonObj:: write_class_wrapper(ostream &out, InterfaceMaker::Object *object) { CPPType *struct_type = object->_itype._cpptype; - if (struct_type == (CPPType *)NULL) { + if (struct_type == nullptr) { return; } @@ -185,7 +188,7 @@ write_class_wrapper(ostream &out, InterfaceMaker::Object *object) { << " */\n" << "PyObject *\n" << name << "() {\n" - << " static PyObject *wrapper = (PyObject *)NULL;\n" + << " static PyObject *wrapper = nullptr;\n" << " static PyMethodDef methods[] = {\n"; int methods_size = 0; @@ -216,7 +219,7 @@ write_class_wrapper(ostream &out, InterfaceMaker::Object *object) { out << " };\n" << " static const int class_methods_size = " << class_methods_size << ";\n\n" - << " if (wrapper == (PyObject *)NULL) {\n" + << " if (wrapper == nullptr) {\n" << " int i;\n" << " PyObject *bases = PyTuple_New(0);\n" << " PyObject *dict = PyDict_New();\n" @@ -228,13 +231,13 @@ write_class_wrapper(ostream &out, InterfaceMaker::Object *object) { << " wrapper = PyClass_New(bases, dict, name);\n" << " for (i = 0; i < methods_size; ++i) {\n" << " PyObject *function, *method;\n" - << " function = PyCFunction_New(&methods[i], (PyObject *)NULL);\n" - << " method = PyMethod_New(function, (PyObject *)NULL, wrapper);\n" + << " function = PyCFunction_New(&methods[i], nullptr);\n" + << " method = PyMethod_New(function, nullptr, wrapper);\n" << " PyDict_SetItemString(dict, methods[i].ml_name, method);\n" << " }\n" << " for (i = 0; i < class_methods_size; ++i) {\n" << " PyObject *function;\n" - << " function = PyCFunction_New(&class_methods[i], (PyObject *)NULL);\n" + << " function = PyCFunction_New(&class_methods[i], nullptr);\n" << " PyDict_SetItemString(dict, class_methods[i].ml_name, function);\n" << " }\n" << " }\n" @@ -287,7 +290,7 @@ write_function_for(ostream &out, InterfaceMaker::Function *func) { // different overloaded C++ function signatures. out << " PyErr_SetString(PyExc_TypeError, \"" << expected_params << "\");\n" - << " return (PyObject *)NULL;\n"; + << " return nullptr;\n"; out << "}\n\n"; } @@ -366,7 +369,7 @@ write_function_instance(ostream &out, int indent_level, format_specifiers += "O"; parameter_list += ", &" + param_name; extra_convert += " PyObject *" + param_name + "_long = PyNumber_Long(" + param_name + ");"; - extra_param_check += "|| (" + param_name + "_long == NULL)"; + extra_param_check += "|| (" + param_name + "_long == nullptr)"; pexpr_string = "PyLong_AsUnsignedLongLong(" + param_name + "_long)"; extra_cleanup += " Py_XDECREF(" + param_name + "_long);"; expected_params += "long"; @@ -376,7 +379,7 @@ write_function_instance(ostream &out, int indent_level, format_specifiers += "O"; parameter_list += ", &" + param_name; extra_convert += " PyObject *" + param_name + "_long = PyNumber_Long(" + param_name + ");"; - extra_param_check += "|| (" + param_name + "_long == NULL)"; + extra_param_check += "|| (" + param_name + "_long == nullptr)"; pexpr_string = "PyLong_AsLongLong(" + param_name + "_long)"; extra_cleanup += " Py_XDECREF(" + param_name + "_long);"; expected_params += "long"; @@ -386,7 +389,7 @@ write_function_instance(ostream &out, int indent_level, format_specifiers += "O"; parameter_list += ", &" + param_name; extra_convert += " PyObject *" + param_name + "_uint = PyNumber_Long(" + param_name + ");"; - extra_param_check += "|| (" + param_name + "_uint == NULL)"; + extra_param_check += "|| (" + param_name + "_uint == nullptr)"; pexpr_string = "(unsigned int)PyLong_AsUnsignedLong(" + param_name + "_uint)"; extra_cleanup += " Py_XDECREF(" + param_name + "_uint);"; expected_params += "unsigned int"; @@ -452,7 +455,7 @@ write_function_instance(ostream &out, int indent_level, indent(out, indent_level + 6) << "PyErr_SetString(PyExc_TypeError, \"Invalid parameters.\");\n"; indent(out, indent_level + 6) - << "return (PyObject *)NULL;\n"; + << "return nullptr;\n"; indent(out, indent_level + 4) << "}\n"; } diff --git a/dtool/src/interrogate/interfaceMakerPythonObj.h b/dtool/src/interrogate/interfaceMakerPythonObj.h index df2263f8d7..be7e0d9913 100644 --- a/dtool/src/interrogate/interfaceMakerPythonObj.h +++ b/dtool/src/interrogate/interfaceMakerPythonObj.h @@ -37,32 +37,32 @@ public: InterfaceMakerPythonObj(InterrogateModuleDef *def); virtual ~InterfaceMakerPythonObj(); - virtual void write_prototypes(ostream &out,ostream *out_h); - virtual void write_functions(ostream &out); + virtual void write_prototypes(std::ostream &out,std::ostream *out_h); + virtual void write_functions(std::ostream &out); - virtual void write_module(ostream &out,ostream *out_h, InterrogateModuleDef *def); + virtual void write_module(std::ostream &out,std::ostream *out_h, InterrogateModuleDef *def); virtual bool synthesize_this_parameter(); - static string get_builder_name(CPPType *struct_type); + static std::string get_builder_name(CPPType *struct_type); protected: - virtual string get_wrapper_prefix(); + virtual std::string get_wrapper_prefix(); private: - void write_class_wrapper(ostream &out, Object *object); - void write_prototype_for(ostream &out, Function *func); - void write_function_for(ostream &out, Function *func); - void write_function_instance(ostream &out, int indent_level, Function *func, - FunctionRemap *remap, string &expected_params); + void write_class_wrapper(std::ostream &out, Object *object); + void write_prototype_for(std::ostream &out, Function *func); + void write_function_for(std::ostream &out, Function *func); + void write_function_instance(std::ostream &out, int indent_level, Function *func, + FunctionRemap *remap, std::string &expected_params); - void pack_return_value(ostream &out, int indent_level, - FunctionRemap *remap, string return_expr); + void pack_return_value(std::ostream &out, int indent_level, + FunctionRemap *remap, std::string return_expr); FunctionWriterPtrFromPython *get_ptr_from_python(CPPType *type); FunctionWriterPtrToPython *get_ptr_to_python(CPPType *type); - typedef map PtrConverter; + typedef std::map PtrConverter; PtrConverter _from_python; PtrConverter _to_python; }; diff --git a/dtool/src/interrogate/interfaceMakerPythonSimple.cxx b/dtool/src/interrogate/interfaceMakerPythonSimple.cxx index b7b5925a8c..c0f1be390a 100644 --- a/dtool/src/interrogate/interfaceMakerPythonSimple.cxx +++ b/dtool/src/interrogate/interfaceMakerPythonSimple.cxx @@ -23,6 +23,9 @@ #include "interrogateFunction.h" #include "cppFunctionType.h" +using std::ostream; +using std::string; + /** * */ @@ -89,17 +92,17 @@ write_module(ostream &out,ostream *out_h, InterrogateModuleDef *def) { << remap->_wrapper_name << ", METH_VARARGS },\n"; } } - out << " { NULL, NULL }\n" + out << " { nullptr, nullptr }\n" << "};\n\n" << "#if PY_MAJOR_VERSION >= 3\n" << "static struct PyModuleDef python_simple_module = {\n" << " PyModuleDef_HEAD_INIT,\n" << " \"" << def->library_name << "\",\n" - << " NULL,\n" + << " nullptr,\n" << " -1,\n" << " python_simple_funcs,\n" - << " NULL, NULL, NULL, NULL\n" + << " nullptr, nullptr, nullptr, nullptr\n" << "};\n\n" << "#define INIT_FUNC PyObject *PyInit_" << def->library_name << "\n" @@ -285,7 +288,7 @@ void InterfaceMakerPythonSimple::write_function_instance(ostream &out, Interface format_specifiers += "O"; parameter_list += ", &" + param_name; extra_convert += " PyObject *" + param_name + "_long = PyNumber_Long(" + param_name + ");"; - extra_param_check += "|| (" + param_name + "_long == NULL)"; + extra_param_check += "|| (" + param_name + "_long == nullptr)"; pexpr_string = "PyLong_AsUnsignedLongLong(" + param_name + "_long)"; extra_cleanup += " Py_XDECREF(" + param_name + "_long);"; @@ -294,7 +297,7 @@ void InterfaceMakerPythonSimple::write_function_instance(ostream &out, Interface format_specifiers += "O"; parameter_list += ", &" + param_name; extra_convert += " PyObject *" + param_name + "_long = PyNumber_Long(" + param_name + ");"; - extra_param_check += "|| (" + param_name + "_long == NULL)"; + extra_param_check += "|| (" + param_name + "_long == nullptr)"; pexpr_string = "PyLong_AsLongLong(" + param_name + "_long)"; extra_cleanup += " Py_XDECREF(" + param_name + "_long);"; @@ -303,7 +306,7 @@ void InterfaceMakerPythonSimple::write_function_instance(ostream &out, Interface format_specifiers += "O"; parameter_list += ", &" + param_name; extra_convert += " PyObject *" + param_name + "_uint = PyNumber_Long(" + param_name + ");"; - extra_param_check += "|| (" + param_name + "_uint == NULL)"; + extra_param_check += "|| (" + param_name + "_uint == nullptr)"; pexpr_string = "(unsigned int)PyLong_AsUnsignedLong(" + param_name + "_uint)"; extra_cleanup += " Py_XDECREF(" + param_name + "_uint);"; @@ -361,7 +364,7 @@ void InterfaceMakerPythonSimple::write_function_instance(ostream &out, Interface out << " " << extra_cleanup << "\n"; } out << " PyErr_SetString(PyExc_TypeError, \"Invalid parameters.\");\n" - << " return (PyObject *)NULL;\n" + << " return nullptr;\n" << " }\n"; } @@ -422,7 +425,7 @@ void InterfaceMakerPythonSimple::write_function_instance(ostream &out, Interface out << " }\n"; - out << " return (PyObject *)NULL;\n"; + out << " return nullptr;\n"; out << "}\n\n"; } diff --git a/dtool/src/interrogate/interfaceMakerPythonSimple.h b/dtool/src/interrogate/interfaceMakerPythonSimple.h index 0b17df3688..18cfc4d590 100644 --- a/dtool/src/interrogate/interfaceMakerPythonSimple.h +++ b/dtool/src/interrogate/interfaceMakerPythonSimple.h @@ -35,29 +35,29 @@ public: InterfaceMakerPythonSimple(InterrogateModuleDef *def); virtual ~InterfaceMakerPythonSimple(); - virtual void write_prototypes(ostream &out,ostream *out_h); - virtual void write_functions(ostream &out); + virtual void write_prototypes(std::ostream &out,std::ostream *out_h); + virtual void write_functions(std::ostream &out); - virtual void write_module(ostream &out,ostream *out_h, InterrogateModuleDef *def); + virtual void write_module(std::ostream &out,std::ostream *out_h, InterrogateModuleDef *def); virtual bool synthesize_this_parameter(); protected: - virtual string get_wrapper_prefix(); - virtual string get_unique_prefix(); + virtual std::string get_wrapper_prefix(); + virtual std::string get_unique_prefix(); virtual void record_function_wrapper(InterrogateFunction &ifunc, FunctionWrapperIndex wrapper_index); private: - void write_prototype_for(ostream &out, Function *func); - void write_function_for(ostream &out, Function *func); - void write_function_instance(ostream &out, Function *func, + void write_prototype_for(std::ostream &out, Function *func); + void write_function_for(std::ostream &out, Function *func); + void write_function_instance(std::ostream &out, Function *func, FunctionRemap *remap); - void pack_return_value(ostream &out, int indent_level, - FunctionRemap *remap, string return_expr); + void pack_return_value(std::ostream &out, int indent_level, + FunctionRemap *remap, std::string return_expr); }; #endif diff --git a/dtool/src/interrogate/interrogate.cxx b/dtool/src/interrogate/interrogate.cxx index 94175b9d2b..d11bd22ff6 100644 --- a/dtool/src/interrogate/interrogate.cxx +++ b/dtool/src/interrogate/interrogate.cxx @@ -22,6 +22,9 @@ #include "pystub.h" #include +using std::cerr; +using std::string; + CPPParser parser; Filename output_code_filename; @@ -83,32 +86,32 @@ enum CommandOptions { }; static struct option long_options[] = { - { "oc", required_argument, NULL, CO_oc }, - { "od", required_argument, NULL, CO_od }, - { "srcdir", required_argument, NULL, CO_srcdir }, - { "module", required_argument, NULL, CO_module }, - { "library", required_argument, NULL, CO_library }, - { "do-module", no_argument, NULL, CO_do_module }, - { "fptrs", no_argument, NULL, CO_fptrs }, - { "fnames", no_argument, NULL, CO_fnames }, - { "string", no_argument, NULL, CO_string }, - { "refcount", no_argument, NULL, CO_refcount }, - { "assert", no_argument, NULL, CO_assert }, - { "true-names", no_argument, NULL, CO_true_names }, - { "c", no_argument, NULL, CO_c }, - { "python", no_argument, NULL, CO_python }, - { "python-obj", no_argument, NULL, CO_python_obj }, - { "python-native", no_argument, NULL, CO_python_native }, - { "track-interpreter", no_argument, NULL, CO_track_interpreter }, - { "unique-names", no_argument, NULL, CO_unique_names }, - { "nodb", no_argument, NULL, CO_nodb }, - { "longlong", required_argument, NULL, CO_longlong }, - { "promiscuous", no_argument, NULL, CO_promiscuous }, - { "spam", no_argument, NULL, CO_spam }, - { "noangles", no_argument, NULL, CO_noangles }, - { "nomangle", no_argument, NULL, CO_nomangle }, - { "help", no_argument, NULL, CO_help }, - { NULL } + { "oc", required_argument, nullptr, CO_oc }, + { "od", required_argument, nullptr, CO_od }, + { "srcdir", required_argument, nullptr, CO_srcdir }, + { "module", required_argument, nullptr, CO_module }, + { "library", required_argument, nullptr, CO_library }, + { "do-module", no_argument, nullptr, CO_do_module }, + { "fptrs", no_argument, nullptr, CO_fptrs }, + { "fnames", no_argument, nullptr, CO_fnames }, + { "string", no_argument, nullptr, CO_string }, + { "refcount", no_argument, nullptr, CO_refcount }, + { "assert", no_argument, nullptr, CO_assert }, + { "true-names", no_argument, nullptr, CO_true_names }, + { "c", no_argument, nullptr, CO_c }, + { "python", no_argument, nullptr, CO_python }, + { "python-obj", no_argument, nullptr, CO_python_obj }, + { "python-native", no_argument, nullptr, CO_python_native }, + { "track-interpreter", no_argument, nullptr, CO_track_interpreter }, + { "unique-names", no_argument, nullptr, CO_unique_names }, + { "nodb", no_argument, nullptr, CO_nodb }, + { "longlong", required_argument, nullptr, CO_longlong }, + { "promiscuous", no_argument, nullptr, CO_promiscuous }, + { "spam", no_argument, nullptr, CO_spam }, + { "noangles", no_argument, nullptr, CO_noangles }, + { "nomangle", no_argument, nullptr, CO_nomangle }, + { "help", no_argument, nullptr, CO_help }, + { nullptr } }; void @@ -320,7 +323,7 @@ main(int argc, char **argv) { extern int optind; int flag; - flag = getopt_long_only(argc, argv, short_options, long_options, NULL); + flag = getopt_long_only(argc, argv, short_options, long_options, nullptr); while (flag != EOF) { switch (flag) { case 'I': @@ -458,7 +461,7 @@ main(int argc, char **argv) { default: exit(1); } - flag = getopt_long_only(argc, argv, short_options, long_options, NULL); + flag = getopt_long_only(argc, argv, short_options, long_options, nullptr); } argc -= (optind-1); @@ -541,10 +544,10 @@ main(int argc, char **argv) { // Make up a file identifier. This is just some bogus number that should be // the same in both the compiled-in code and in the database, so we can // check synchronicity at load time. - int file_identifier = time((time_t *)NULL); + int file_identifier = time(nullptr); InterrogateModuleDef *def = builder.make_module_def(file_identifier); - pofstream * the_output_include = NULL; + pofstream * the_output_include = nullptr; pofstream output_include; @@ -584,7 +587,7 @@ main(int argc, char **argv) { << " *\n" << " */\n\n"; - if(the_output_include != NULL) + if(the_output_include != nullptr) { output_code << "#include \""< #include +using std::cerr; +using std::istream; +using std::map; +using std::ostream; +using std::ostringstream; +using std::string; + InterrogateBuilder builder; std::string EXPORT_IMPORT_PREFIX; @@ -74,7 +81,7 @@ add_source_file(const string &filename) { void InterrogateBuilder:: read_command_file(istream &in) { string line; - getline(in, line); + std::getline(in, line); while (!in.fail() && !in.eof()) { // Strip out the comment. size_t hash = line.find('#'); @@ -110,7 +117,7 @@ read_command_file(istream &in) { do_command(command, params); } - getline(in, line); + std::getline(in, line); } } @@ -122,7 +129,7 @@ do_command(const string &command, const string ¶ms) { if (command == "forcevisible") { CPPType *type = parser.parse_type(params); - if (type == (CPPType *)NULL) { + if (type == nullptr) { nout << "Unknown type: allowtype " << params << "\n"; } else { type = type->resolve_type(&parser, &parser); @@ -132,7 +139,7 @@ do_command(const string &command, const string ¶ms) { } else if (command == "forcetype") { // forcetype explicitly exports the given type. CPPType *type = parser.parse_type(params); - if (type == (CPPType *)NULL) { + if (type == nullptr) { nout << "Unknown type: forcetype " << params << "\n"; } else { type = type->resolve_type(&parser, &parser); @@ -153,7 +160,7 @@ do_command(const string &command, const string ¶ms) { string new_name = params.substr(space + 1); CPPType *type = parser.parse_type(orig_name); - if (type == (CPPType *)NULL) { + if (type == nullptr) { nout << "Unknown type: renametype " << orig_name << "\n"; } else { type = type->resolve_type(&parser, &parser); @@ -164,7 +171,7 @@ do_command(const string &command, const string ¶ms) { } else if (command == "ignoretype") { // ignoretype explicitly ignores the given type. CPPType *type = parser.parse_type(params); - if (type == (CPPType *)NULL) { + if (type == nullptr) { nout << "Unknown type: ignoretype " << params << "\n"; } else { type = type->resolve_type(&parser, &parser); @@ -185,7 +192,7 @@ do_command(const string &command, const string ¶ms) { string constructor = params.substr(space + 1); CPPType *type = parser.parse_type(class_name); - if (type == (CPPType *)NULL) { + if (type == nullptr) { nout << "Unknown type: defconstruct " << class_name << "\n"; } else { type = type->resolve_type(&parser, &parser); @@ -254,10 +261,10 @@ build() { ci != _forcetype.end(); ++ci) { CPPType *type = parser.parse_type(*ci); - if (type == NULL) { + if (type == nullptr) { cerr << "Failure to parse forcetype " << *ci << "\n"; } - assert(type != (CPPType *)NULL); + assert(type != nullptr); get_type(type, true); } @@ -274,7 +281,7 @@ build() { scan_function(inst); } else { // Here's a data element declaration. - scan_element(inst, (CPPStructType *)NULL, &parser); + scan_element(inst, nullptr, &parser); } } else if ((*di)->get_subtype() == CPPDeclaration::ST_typedef) { @@ -323,7 +330,7 @@ build() { */ void InterrogateBuilder:: write_code(ostream &out_code,ostream * out_include, InterrogateModuleDef *def) { - typedef vector InterfaceMakers; + typedef std::vector InterfaceMakers; InterfaceMakers makers; if (build_c_wrappers) { @@ -443,7 +450,7 @@ write_code(ostream &out_code,ostream * out_include, InterrogateModuleDef *def) { } // Now collect all the function wrappers. - vector remaps; + std::vector remaps; for (mi = makers.begin(); mi != makers.end(); ++mi) { (*mi)->get_function_remaps(remaps); } @@ -457,7 +464,7 @@ write_code(ostream &out_code,ostream * out_include, InterrogateModuleDef *def) { int num_wrappers = 0; map wrappers_by_index; - vector::iterator ri; + std::vector::iterator ri; for (ri = remaps.begin(); ri != remaps.end(); ++ri) { FunctionRemap *remap = (*ri); wrappers_by_index[remap->_wrapper_index] = remap; @@ -511,7 +518,7 @@ write_code(ostream &out_code,ostream * out_include, InterrogateModuleDef *def) { << " \"" << def->library_name << "\", /* library_name */\n" << " \"" << def->library_hash_name << "\", /* library_hash_name */\n" << " \"" << def->module_name << "\", /* module_name */\n"; - if (def->database_filename != (const char *)NULL) { + if (def->database_filename != nullptr) { out_code << " \"" << def->database_filename << "\", /* database_filename */\n"; } else { @@ -522,7 +529,7 @@ write_code(ostream &out_code,ostream * out_include, InterrogateModuleDef *def) { out_code << " _in_unique_names,\n" << " " << num_wrappers << ", /* num_unique_names */\n"; } else { - out_code << " (InterrogateUniqueNameDef *)0, /* unique_names */\n" + out_code << " nullptr, /* unique_names */\n" << " 0, /* num_unique_names */\n"; } @@ -530,7 +537,7 @@ write_code(ostream &out_code,ostream * out_include, InterrogateModuleDef *def) { out_code << " _in_fptrs,\n" << " " << num_wrappers << ", /* num_fptrs */\n"; } else { - out_code << " (void **)0, /* fptrs */\n" + out_code << " nullptr, /* fptrs */\n" << " 0, /* num_fptrs */\n"; } @@ -921,17 +928,17 @@ bool InterrogateBuilder:: is_inherited_published(CPPInstance *function, CPPStructType *struct_type) { nassertr(struct_type->_derivation.size() == 1, false); CPPStructType *base = struct_type->_derivation[0]._base->as_struct_type(); - nassertr(base != (CPPStructType *)NULL, false); + nassertr(base != nullptr, false); CPPScope *base_scope = base->get_scope(); CPPDeclaration *symbol = base_scope->find_symbol(function->get_simple_name(), true); - if (symbol == (CPPDeclaration *)NULL) { + if (symbol == nullptr) { // Couldn't find the inherited function. return false; } CPPFunctionGroup *fgroup = symbol->as_function_group(); - if (fgroup == (CPPFunctionGroup *)NULL) { + if (fgroup == nullptr) { // Weird, it wasn't a function. return false; } @@ -960,7 +967,7 @@ is_inherited_published(CPPInstance *function, CPPStructType *struct_type) { * purpose of this function. */ void InterrogateBuilder:: -remap_indices(vector &remaps) { +remap_indices(std::vector &remaps) { IndexRemapper index_remap; InterrogateDatabase::get_ptr()->remap_indices(1, index_remap); @@ -976,7 +983,7 @@ remap_indices(vector &remaps) { (*fi).second = index_remap.map_from((*fi).second); } - vector::iterator ri; + std::vector::iterator ri; for (ri = remaps.begin(); ri != remaps.end(); ++ri) { FunctionRemap *remap = (*ri); remap->_wrapper_index = index_remap.map_from(remap->_wrapper_index); @@ -1000,22 +1007,22 @@ scan_function(CPPFunctionGroup *fgroup) { */ void InterrogateBuilder:: scan_function(CPPInstance *function) { - assert(function != (CPPInstance *)NULL); - assert(function->_type != (CPPType *)NULL && function->_type->as_function_type() != (CPPFunctionType *)NULL); + assert(function != nullptr); + assert(function->_type != nullptr && function->_type->as_function_type() != nullptr); CPPFunctionType *ftype = function->_type->resolve_type(&parser, &parser)->as_function_type(); - assert(ftype != (CPPFunctionType *)NULL); + assert(ftype != nullptr); CPPScope *scope = &parser; if (function->is_scoped()) { scope = function->get_scope(&parser, &parser); - if (scope == (CPPScope *)NULL) { + if (scope == nullptr) { // Invalid scope. nout << "Invalid scope: " << *function->_ident << "\n"; return; } - if (scope->get_struct_type() != (CPPStructType *)NULL) { + if (scope->get_struct_type() != nullptr) { // Wait, this is a method, not a function. This must be the declaration // for the method (since it's appearing out-of-scope). We don't need to // define a new method for it, but we'd like to update the comment, if @@ -1070,7 +1077,7 @@ scan_function(CPPInstance *function) { } get_function(function, "", - (CPPStructType *)NULL, scope, + nullptr, scope, InterrogateFunction::F_global); } @@ -1079,7 +1086,7 @@ scan_function(CPPInstance *function) { */ void InterrogateBuilder:: scan_struct_type(CPPStructType *type) { - if (type == (CPPStructType *)NULL) { + if (type == nullptr) { return; } @@ -1129,7 +1136,7 @@ scan_struct_type(CPPStructType *type) { */ void InterrogateBuilder:: scan_enum_type(CPPEnumType *type) { - if (type == (CPPEnumType *)NULL) { + if (type == nullptr) { return; } @@ -1163,7 +1170,7 @@ scan_enum_type(CPPEnumType *type) { */ void InterrogateBuilder:: scan_typedef_type(CPPTypedefType *type) { - if (type == (CPPTypedefType *)NULL) { + if (type == nullptr) { return; } @@ -1202,7 +1209,7 @@ scan_typedef_type(CPPTypedefType *type) { } CPPStructType *struct_type = wrapped_type->as_struct_type(); - if (struct_type == (CPPStructType *)NULL) { + if (struct_type == nullptr) { // We only export typedefs to structs, for now. return; } @@ -1247,7 +1254,7 @@ scan_typedef_type(CPPTypedefType *type) { */ void InterrogateBuilder:: scan_manifest(CPPManifest *manifest) { - if (manifest == (CPPManifest *)NULL) { + if (manifest == nullptr) { return; } @@ -1278,7 +1285,7 @@ scan_manifest(CPPManifest *manifest) { imanifest._definition = manifest->expand(); CPPType *type = manifest->determine_type(); - if (type != (CPPType *)NULL) { + if (type != nullptr) { imanifest._flags |= InterrogateManifest::F_has_type; imanifest._type = get_type(type, false); @@ -1292,8 +1299,8 @@ scan_manifest(CPPManifest *manifest) { } else { // We have a more complex expression. Generate a getter function. FunctionIndex getter = - get_getter(type, manifest->_name, (CPPStructType *)NULL, &parser, - (CPPInstance *)NULL); + get_getter(type, manifest->_name, nullptr, &parser, + nullptr); if (getter != 0) { imanifest._flags |= InterrogateManifest::F_has_getter; @@ -1313,7 +1320,7 @@ scan_manifest(CPPManifest *manifest) { ElementIndex InterrogateBuilder:: scan_element(CPPInstance *element, CPPStructType *struct_type, CPPScope *scope) { - if (element == (CPPInstance *)NULL) { + if (element == nullptr) { return 0; } @@ -1336,7 +1343,7 @@ scan_element(CPPInstance *element, CPPStructType *struct_type, return 0; } - if (struct_type == NULL && + if (struct_type == nullptr && (element->_file._source != CPPFile::S_local || in_ignorefile(element->_file._filename_as_referenced))) { // The element is defined in some other package or in an ignorable file. @@ -1368,7 +1375,7 @@ scan_element(CPPInstance *element, CPPStructType *struct_type, ielement._scoped_name = descope(element->get_local_name(&parser)); // See if there happens to be a comment before the element. - if (element->_leading_comment != (CPPCommentBlock *)NULL) { + if (element->_leading_comment != nullptr) { ielement._comment = trim_blanks(element->_leading_comment->_comment); } @@ -1382,7 +1389,7 @@ scan_element(CPPInstance *element, CPPStructType *struct_type, // We can only generate a getter and a setter if we can talk about the // type it is. - if (parameter_type->as_struct_type() != (CPPStructType *)NULL) { + if (parameter_type->as_struct_type() != nullptr) { // Wrap the type in a const reference. parameter_type = TypeManager::wrap_const_reference(parameter_type); } @@ -1407,7 +1414,7 @@ scan_element(CPPInstance *element, CPPStructType *struct_type, } } - if (struct_type == (CPPStructType *)NULL) { + if (struct_type == nullptr) { // This is a global data element: not a data member. ielement._flags |= InterrogateElement::F_global; } @@ -1432,9 +1439,9 @@ get_getter(CPPType *expr_type, string expression, // Unroll the "const" from the expr_type, since that doesn't matter for a // return type. - while (expr_type->as_const_type() != (CPPConstType *)NULL) { + while (expr_type->as_const_type() != nullptr) { expr_type = expr_type->as_const_type()->_wrapped_around; - assert(expr_type != (CPPType *)NULL); + assert(expr_type != nullptr); } // We can't return an array from a function, but we can decay it into a @@ -1453,10 +1460,10 @@ get_getter(CPPType *expr_type, string expression, int getter_flags = InterrogateFunction::F_getter; - if (struct_type != (CPPStructType *)NULL) { + if (struct_type != nullptr) { // This is a data member for some class. - assert(element != (CPPInstance *)NULL); - assert(scope != (CPPScope *)NULL); + assert(element != nullptr); + assert(scope != nullptr); if ((element->_storage_class & CPPInstance::SC_static) != 0) { // This is a static data member; therefore, the synthesized getter is @@ -1487,8 +1494,8 @@ get_getter(CPPType *expr_type, string expression, ostringstream desc; desc << "getter for "; - if (element != (CPPInstance *)NULL) { - element->_initializer = (CPPExpression *)NULL; + if (element != nullptr) { + element->_initializer = nullptr; element->output(desc, 0, &parser, false); desc << ";"; } else { @@ -1530,10 +1537,10 @@ get_setter(CPPType *expr_type, string expression, int setter_flags = InterrogateFunction::F_setter; - if (struct_type != (CPPStructType *)NULL) { + if (struct_type != nullptr) { // This is a data member for some class. - assert(element != (CPPInstance *)NULL); - assert(scope != (CPPScope *)NULL); + assert(element != nullptr); + assert(scope != nullptr); if ((element->_storage_class & CPPInstance::SC_static) != 0) { // This is a static data member; therefore, the synthesized setter is @@ -1560,8 +1567,8 @@ get_setter(CPPType *expr_type, string expression, ostringstream desc; desc << "setter for "; - if (element != (CPPInstance *)NULL) { - element->_initializer = (CPPExpression *)NULL; + if (element != nullptr) { + element->_initializer = nullptr; element->output(desc, 0, &parser, false); desc << ";"; } else { @@ -1590,7 +1597,7 @@ get_cast_function(CPPType *to_type, CPPType *from_type, CPPStructType *struct_type = from_type->as_struct_type(); CPPScope *scope = &parser; - if (struct_type != (CPPStructType *)NULL) { + if (struct_type != nullptr) { // We'll make this a method of the from type. scope = struct_type->get_scope(); @@ -1666,14 +1673,14 @@ get_function(CPPInstance *function, string description, function->_type = ftype; if ((ftype->_flags & CPPFunctionType::F_constructor) && - struct_type != (CPPStructType *)NULL && + struct_type != nullptr && struct_type->is_abstract()) { // This is a constructor for an abstract class; forget it. return 0; } TypeIndex class_index = 0; - if (struct_type != (CPPStructType *)NULL) { + if (struct_type != nullptr) { class_index = get_type(struct_type, false); } @@ -1696,12 +1703,10 @@ get_function(CPPInstance *function, string description, InterrogateFunction &ifunction = InterrogateDatabase::get_ptr()->update_function(index); - nassertr(&ifunction != NULL, 0); - ifunction._flags |= flags; // Also, make sure this particular signature is defined. - pair result = + std::pair result = ifunction._instances->insert(InterrogateFunction::Instances::value_type(function_signature, function)); InterrogateFunction::Instances::iterator ii = result.first; @@ -1716,7 +1721,7 @@ get_function(CPPInstance *function, string description, } // Also set the comment. - if (function->_leading_comment != (CPPCommentBlock *)NULL) { + if (function->_leading_comment != nullptr) { string comment = trim_blanks(function->_leading_comment->_comment); if (!ifunction._comment.empty()) { ifunction._comment += "\n\n"; @@ -1724,7 +1729,7 @@ get_function(CPPInstance *function, string description, ifunction._comment += comment; // And update the particular wrapper comment. - if ((*ii).second->_leading_comment == NULL || + if ((*ii).second->_leading_comment == nullptr || function->_leading_comment->_comment.length() > (*ii).second->_leading_comment->_comment.length()) { (*ii).second->_leading_comment = function->_leading_comment; @@ -1744,7 +1749,7 @@ get_function(CPPInstance *function, string description, ifunction->_scoped_name = descope(function->get_local_name(&parser)); ifunction->_instances = new InterrogateFunction::Instances; - if (function->_leading_comment != (CPPCommentBlock *)NULL) { + if (function->_leading_comment != nullptr) { ifunction->_comment = trim_blanks(function->_leading_comment->_comment); } @@ -1753,7 +1758,7 @@ get_function(CPPInstance *function, string description, prototype << ";"; ifunction->_prototype = prototype.str(); - if (struct_type != (CPPStructType *)NULL) { + if (struct_type != nullptr) { // The function is a method. ifunction->_flags |= InterrogateFunction::F_method; ifunction->_class = class_index; @@ -1846,19 +1851,19 @@ get_make_property(CPPMakeProperty *make_property, CPPStructType *struct_type, CP } // Find the getter so we can get its return type. - CPPInstance *getter = NULL; - CPPType *return_type = NULL; + CPPInstance *getter = nullptr; + CPPType *return_type = nullptr; // How many arguments we expect the getter to have. size_t num_args = (size_t)(make_property->_type != CPPMakeProperty::T_normal); fgroup = make_property->_get_function; - if (fgroup != NULL) { + if (fgroup != nullptr) { CPPFunctionGroup::Instances::const_iterator fi; for (fi = fgroup->_instances.begin(); fi != fgroup->_instances.end(); ++fi) { CPPInstance *function = (*fi); CPPFunctionType *ftype = function->_type->as_function_type(); - if (ftype == NULL) { + if (ftype == nullptr) { continue; } @@ -1881,7 +1886,7 @@ get_make_property(CPPMakeProperty *make_property, CPPStructType *struct_type, CP // The getter must either take no arguments, or all defaults. if (params.size() == expected_num_args || (params.size() > expected_num_args && - params[expected_num_args]->_initializer != NULL)) { + params[expected_num_args]->_initializer != nullptr)) { // If this is a sequence getter, it must take an index argument. if (make_property->_type == CPPMakeProperty::T_sequence && !TypeManager::is_integer(params[index_arg]->_type)) { @@ -1899,7 +1904,7 @@ get_make_property(CPPMakeProperty *make_property, CPPStructType *struct_type, CP } } - if (getter == NULL || return_type == NULL) { + if (getter == nullptr || return_type == nullptr) { cerr << "No instance of getter '" << fgroup->_name << "' is suitable!\n"; return 0; @@ -1907,10 +1912,10 @@ get_make_property(CPPMakeProperty *make_property, CPPStructType *struct_type, CP } // Find the "hasser". - CPPInstance *hasser = NULL; + CPPInstance *hasser = nullptr; fgroup = make_property->_has_function; - if (fgroup != NULL) { + if (fgroup != nullptr) { CPPFunctionGroup::Instances::const_iterator fi; for (fi = fgroup->_instances.begin(); fi != fgroup->_instances.end(); ++fi) { CPPInstance *function = (*fi); @@ -1931,10 +1936,10 @@ get_make_property(CPPMakeProperty *make_property, CPPStructType *struct_type, CP } // And the "deleter". - CPPInstance *deleter = NULL; + CPPInstance *deleter = nullptr; fgroup = make_property->_del_function; - if (fgroup != NULL) { + if (fgroup != nullptr) { CPPFunctionGroup::Instances::const_iterator fi; for (fi = fgroup->_instances.begin(); fi != fgroup->_instances.end(); ++fi) { CPPInstance *function = (*fi); @@ -2013,7 +2018,7 @@ get_make_property(CPPMakeProperty *make_property, CPPStructType *struct_type, CP InterrogateElement &iproperty = idb->update_element(index); - if (return_type != NULL) { + if (return_type != nullptr) { TypeIndex return_index = get_type(TypeManager::unwrap_reference(return_type), false); if (iproperty._type != 0 && iproperty._type != return_index) { cerr << "Property " << property_name << " has inconsistent element type!\n"; @@ -2034,7 +2039,7 @@ get_make_property(CPPMakeProperty *make_property, CPPStructType *struct_type, CP } if (make_property->_type == CPPMakeProperty::T_normal) { - if (getter != NULL) { + if (getter != nullptr) { iproperty._flags |= InterrogateElement::F_has_getter; iproperty._getter = get_function(getter, "", struct_type, struct_type->get_scope(), 0); @@ -2062,28 +2067,28 @@ get_make_property(CPPMakeProperty *make_property, CPPStructType *struct_type, CP ifunction._instances->insert(InterrogateFunction::Instances::value_type(signature, getter)); } - if (hasser != NULL) { + if (hasser != nullptr) { iproperty._flags |= InterrogateElement::F_has_has_function; iproperty._has_function = get_function(hasser, "", struct_type, struct_type->get_scope(), 0); nassertr(iproperty._has_function, 0); } - if (deleter != NULL) { + if (deleter != nullptr) { iproperty._flags |= InterrogateElement::F_has_del_function; iproperty._del_function = get_function(deleter, "", struct_type, struct_type->get_scope(), 0); nassertr(iproperty._del_function, 0); } - if (inserter != NULL) { + if (inserter != nullptr) { iproperty._flags |= InterrogateElement::F_has_insert_function; iproperty._insert_function = get_function(inserter, "", struct_type, struct_type->get_scope(), 0); nassertr(iproperty._insert_function, 0); } - if (getkey_function != NULL) { + if (getkey_function != nullptr) { iproperty._flags |= InterrogateElement::F_has_getkey_function; iproperty._getkey_function = get_function(getkey_function, "", struct_type, struct_type->get_scope(), 0); @@ -2091,17 +2096,17 @@ get_make_property(CPPMakeProperty *make_property, CPPStructType *struct_type, CP } // See if there happens to be a comment before the MAKE_PROPERTY macro. - if (make_property->_leading_comment != (CPPCommentBlock *)NULL) { + if (make_property->_leading_comment != nullptr) { iproperty._comment = trim_blanks(make_property->_leading_comment->_comment); - } else if (getter->_leading_comment != (CPPCommentBlock *)NULL) { + } else if (getter->_leading_comment != nullptr) { // Take the comment from the getter. iproperty._comment = trim_blanks(getter->_leading_comment->_comment); } // Now look for setters. fgroup = make_property->_set_function; - if (fgroup != NULL) { + if (fgroup != nullptr) { CPPFunctionGroup::Instances::const_iterator fi; for (fi = fgroup->_instances.begin(); fi != fgroup->_instances.end(); ++fi) { CPPInstance *function = (*fi); @@ -2114,7 +2119,7 @@ get_make_property(CPPMakeProperty *make_property, CPPStructType *struct_type, CP } fgroup = make_property->_clear_function; - if (fgroup != NULL) { + if (fgroup != nullptr) { CPPFunctionGroup::Instances::const_iterator fi; for (fi = fgroup->_instances.begin(); fi != fgroup->_instances.end(); ++fi) { CPPInstance *function = (*fi); @@ -2150,12 +2155,12 @@ get_make_seq(CPPMakeSeq *make_seq, CPPStructType *struct_type) { CPPFunctionGroup::Instances::const_iterator fi; CPPFunctionGroup *fgroup = make_seq->_length_getter; - if (fgroup != NULL) { + if (fgroup != nullptr) { for (fi = fgroup->_instances.begin(); fi != fgroup->_instances.end(); ++fi) { CPPInstance *function = (*fi); CPPFunctionType *ftype = function->_type->as_function_type(); - if (ftype != NULL) { + if (ftype != nullptr) { length_getter = get_function(function, "", struct_type, struct_type->get_scope(), 0); if (length_getter != 0) { @@ -2174,12 +2179,12 @@ get_make_seq(CPPMakeSeq *make_seq, CPPStructType *struct_type) { } fgroup = make_seq->_element_getter; - if (fgroup != NULL) { + if (fgroup != nullptr) { for (fi = fgroup->_instances.begin(); fi != fgroup->_instances.end(); ++fi) { CPPInstance *function = (*fi); CPPFunctionType *ftype = function->_type->as_function_type(); - if (ftype != NULL && ftype->_parameters->_parameters.size() >= 1 && + if (ftype != nullptr && ftype->_parameters->_parameters.size() >= 1 && TypeManager::is_integer(ftype->_parameters->_parameters[0]->_type)) { // It really doesn't matter whether we grab the const or non-const // version, since they should all return the same function anyway. @@ -2213,7 +2218,7 @@ get_make_seq(CPPMakeSeq *make_seq, CPPStructType *struct_type) { imake_seq._element_getter = element_getter; // See if there happens to be a comment before the MAKE_SEQ macro. - if (make_seq->_leading_comment != (CPPCommentBlock *)NULL) { + if (make_seq->_leading_comment != nullptr) { imake_seq._comment = trim_blanks(make_seq->_leading_comment->_comment); } @@ -2269,6 +2274,10 @@ get_type(CPPType *type, bool global) { return 0; } + if (type->get_subtype() == CPPType::ST_tbd) { + type = type->resolve_type(&parser, &parser); + } + TypeIndex index = 0; // First, check to see if it's already there. @@ -2338,21 +2347,21 @@ get_type(CPPType *type, bool global) { itype._true_name = true_name; itype._cpptype = type; - if (type->_declaration != (CPPTypeDeclaration *)NULL) { + if (type->_declaration != nullptr) { // This type has a declaration; does the declaration have a comment? CPPTypeDeclaration *decl = type->_declaration; - if (decl->_leading_comment != (CPPCommentBlock *)NULL) { + if (decl->_leading_comment != nullptr) { itype._comment = trim_blanks(decl->_leading_comment->_comment); } } - CPPScope *scope = NULL; + CPPScope *scope = nullptr; // If it's an extension type or typedef, it might be scoped. if (CPPTypedefType *td_type = type->as_typedef_type()) { scope = td_type->_ident->get_scope(&parser, &parser); } else if (CPPExtensionType *ext_type = type->as_extension_type()) { - if (ext_type->_ident != (CPPIdentifier *)NULL) { + if (ext_type->_ident != nullptr) { scope = ext_type->_ident->get_scope(&parser, &parser); } else if (CPPEnumType *enum_type = ext_type->as_enum_type()) { @@ -2362,11 +2371,11 @@ get_type(CPPType *type, bool global) { } - if (scope != (CPPScope *)NULL) { - while (scope->as_template_scope() != (CPPTemplateScope *)NULL) { + if (scope != nullptr) { + while (scope->as_template_scope() != nullptr) { assert(scope->get_parent_scope() != scope); scope = scope->get_parent_scope(); - assert(scope != (CPPScope *)NULL); + assert(scope != nullptr); } itype._cppscope = scope; @@ -2376,7 +2385,7 @@ get_type(CPPType *type, bool global) { descope(scope->get_local_name(&parser) + "::" + itype._name); CPPStructType *struct_type = scope->get_struct_type(); - if (struct_type != (CPPStructType *)NULL) { + if (struct_type != nullptr) { itype._flags |= InterrogateType::F_nested; itype._outer_class = get_type(struct_type, false); } @@ -2386,28 +2395,28 @@ get_type(CPPType *type, bool global) { if (forced || !in_ignoretype(true_name)) { itype._flags |= InterrogateType::F_fully_defined; - if (type->as_simple_type() != (CPPSimpleType *)NULL) { + if (type->as_simple_type() != nullptr) { define_atomic_type(itype, type->as_simple_type()); - } else if (type->as_pointer_type() != (CPPPointerType *)NULL) { + } else if (type->as_pointer_type() != nullptr) { define_wrapped_type(itype, type->as_pointer_type()); - } else if (type->as_const_type() != (CPPConstType *)NULL) { + } else if (type->as_const_type() != nullptr) { define_wrapped_type(itype, type->as_const_type()); - } else if (type->as_struct_type() != (CPPStructType *)NULL) { + } else if (type->as_struct_type() != nullptr) { define_struct_type(itype, type->as_struct_type(), index, forced); - } else if (type->as_enum_type() != (CPPEnumType *)NULL) { + } else if (type->as_enum_type() != nullptr) { define_enum_type(itype, type->as_enum_type()); - } else if (type->as_extension_type() != (CPPExtensionType *)NULL) { + } else if (type->as_extension_type() != nullptr) { define_extension_type(itype, type->as_extension_type()); - } else if (type->as_typedef_type() != (CPPTypedefType *)NULL) { + } else if (type->as_typedef_type() != nullptr) { define_typedef_type(itype, type->as_typedef_type()); - } else if (type->as_array_type() != (CPPArrayType *)NULL) { + } else if (type->as_array_type() != nullptr) { define_array_type(itype, type->as_array_type()); } else { @@ -2534,7 +2543,7 @@ define_struct_type(InterrogateType &itype, CPPStructType *cpptype, } cpptype = TypeManager::resolve_type(cpptype)->as_struct_type(); - assert(cpptype != (CPPStructType *)NULL); + assert(cpptype != nullptr); bool has_virt_methods = cpptype->is_polymorphic(); switch (cpptype->_type) { @@ -2606,7 +2615,7 @@ define_struct_type(InterrogateType &itype, CPPStructType *cpptype, TypeIndex base_index = get_type(base_type, false); if (base_index == 0) { - if (base_type != NULL) { + if (base_type != nullptr) { nout << *cpptype << " reports a derivation from invalid type " << *base_type << ".\n"; } else { nout << *cpptype << " reports a derivation from an invalid type.\n"; @@ -2639,7 +2648,7 @@ define_struct_type(InterrogateType &itype, CPPStructType *cpptype, // (For many compilers, this does not require a pointer change.) generate_casts = true; - } else if (has_virt_methods && (base_type->as_struct_type() == (CPPStructType *)NULL || !base_type->as_struct_type()->is_polymorphic())) { + } else if (has_virt_methods && (base_type->as_struct_type() == nullptr || !base_type->as_struct_type()->is_polymorphic())) { // Finally, if this class has virtual methods, but its parent // doesn't, then we have to upcast (because this class will require // space for a virtual function table pointer, while the parent @@ -2688,17 +2697,17 @@ define_struct_type(InterrogateType &itype, CPPStructType *cpptype, CPPType *type = (*di)->as_type_declaration()->_type; if ((*di)->_vis <= min_vis || in_forcetype(type->get_local_name(&parser))) { - if (type->as_struct_type() != (CPPStructType *)NULL || - type->as_enum_type() != (CPPEnumType *)NULL) { + if (type->as_struct_type() != nullptr || + type->as_enum_type() != nullptr) { // Here's a nested class or enum definition. type->_vis = (*di)->_vis; CPPExtensionType *nested_type = type->as_extension_type(); - assert(nested_type != (CPPExtensionType *)NULL); + assert(nested_type != nullptr); // For now, we don't allow anonymous structs. - if (nested_type->_ident != (CPPIdentifier *)NULL || - nested_type->as_enum_type() != (CPPEnumType *)NULL) { + if (nested_type->_ident != nullptr || + nested_type->as_enum_type() != nullptr) { TypeIndex nested_index = get_type(nested_type, false); itype._nested_types.push_back(nested_index); } @@ -2724,7 +2733,7 @@ define_struct_type(InterrogateType &itype, CPPStructType *cpptype, } CPPStructType *struct_type = wrapped_type->as_struct_type(); - if (struct_type != (CPPStructType *)NULL) { + if (struct_type != nullptr) { // We only export typedefs to structs, for now. if (type->_vis <= min_vis) { @@ -2747,7 +2756,7 @@ define_struct_type(InterrogateType &itype, CPPStructType *cpptype, // See if we need to generate an implicit default constructor. CPPFunctionGroup *constructor = cpptype->get_constructor(); - if (constructor == (CPPFunctionGroup *)NULL && cpptype->is_default_constructible()) { + if (constructor == nullptr && cpptype->is_default_constructible()) { // Make a default constructor. CPPType *void_type = TypeManager::get_void_type(); CPPParameterList *params = new CPPParameterList; @@ -2767,11 +2776,11 @@ define_struct_type(InterrogateType &itype, CPPStructType *cpptype, // See if we need to generate an implicit copy constructor. CPPInstance *copy_constructor = cpptype->get_copy_constructor(); - if (copy_constructor == (CPPInstance *)NULL && + if (copy_constructor == nullptr && cpptype->is_copy_constructible()) { // Make an implicit copy constructor. CPPType *const_ref_type = TypeManager::wrap_const_reference(cpptype); - CPPInstance *param = new CPPInstance(const_ref_type, NULL); + CPPInstance *param = new CPPInstance(const_ref_type, nullptr); CPPType *void_type = TypeManager::get_void_type(); CPPParameterList *params = new CPPParameterList; @@ -2838,7 +2847,7 @@ define_struct_type(InterrogateType &itype, CPPStructType *cpptype, */ void InterrogateBuilder:: update_function_comment(CPPInstance *function, CPPScope *scope) { - if (function->_leading_comment == (CPPCommentBlock *)NULL) { + if (function->_leading_comment == nullptr) { // No comment anyway. Forget it. return; } @@ -2883,7 +2892,7 @@ update_function_comment(CPPInstance *function, CPPScope *scope) { InterrogateFunction::Instances::iterator ii = ifunction._instances->find(function_signature); if (ii != ifunction._instances->end()) { - if ((*ii).second->_leading_comment == NULL || + if ((*ii).second->_leading_comment == nullptr || function->_leading_comment->_comment.length() > (*ii).second->_leading_comment->_comment.length()) { (*ii).second->_leading_comment = function->_leading_comment; @@ -2912,9 +2921,9 @@ define_method(CPPFunctionGroup *fgroup, InterrogateType &itype, void InterrogateBuilder:: define_method(CPPInstance *function, InterrogateType &itype, CPPStructType *struct_type, CPPScope *scope) { - assert(function != (CPPInstance *)NULL); - assert(function->_type != (CPPType *)NULL && - function->_type->as_function_type() != (CPPFunctionType *)NULL); + assert(function != nullptr); + assert(function->_type != nullptr && + function->_type->as_function_type() != nullptr); CPPFunctionType *ftype = function->_type->resolve_type(scope, &parser)->as_function_type(); @@ -3035,7 +3044,7 @@ define_enum_type(InterrogateType &itype, CPPEnumType *cpptype) { itype._flags |= InterrogateType::F_enum; CPPScope *scope = cpptype->_parent_scope; - if (cpptype->_ident != (CPPIdentifier *)NULL) { + if (cpptype->_ident != nullptr) { scope = cpptype->_ident->get_scope(&parser, &parser); } @@ -3072,11 +3081,11 @@ define_enum_type(InterrogateType &itype, CPPEnumType *cpptype) { evalue._name = element->get_simple_name(); evalue._scoped_name = descope(element->get_local_name(&parser)); - if (element->_leading_comment != (CPPCommentBlock *)NULL) { + if (element->_leading_comment != nullptr) { evalue._comment = trim_blanks(element->_leading_comment->_comment); } - if (element->_initializer != (CPPExpression *)NULL) { + if (element->_initializer != nullptr) { CPPExpression::Result result = element->_initializer->evaluate(); if (result._type == CPPExpression::RT_error) { @@ -3112,7 +3121,7 @@ define_array_type(InterrogateType &itype, CPPArrayType *cpptype) { itype._flags |= InterrogateType::F_array; itype._wrapped_type = get_type(cpptype->_element_type, false); - if (cpptype->_bounds == NULL) { + if (cpptype->_bounds == nullptr) { // This indicates an unsized array. itype._array_size = -1; } else { diff --git a/dtool/src/interrogate/interrogateBuilder.h b/dtool/src/interrogate/interrogateBuilder.h index 41096a6f6a..1b182d3f56 100644 --- a/dtool/src/interrogate/interrogateBuilder.h +++ b/dtool/src/interrogate/interrogateBuilder.h @@ -52,41 +52,41 @@ class InterfaceMaker; */ class InterrogateBuilder { public: - void add_source_file(const string &filename); - void read_command_file(istream &in); - void do_command(const string &command, const string ¶ms); + void add_source_file(const std::string &filename); + void read_command_file(std::istream &in); + void do_command(const std::string &command, const std::string ¶ms); void build(); - void write_code(ostream &out_code, ostream *out_include, InterrogateModuleDef *def); + void write_code(std::ostream &out_code, std::ostream *out_include, InterrogateModuleDef *def); InterrogateModuleDef *make_module_def(int file_identifier); - static string clean_identifier(const string &name); - static string descope(const string &name); + static std::string clean_identifier(const std::string &name); + static std::string descope(const std::string &name); FunctionIndex get_destructor_for(CPPType *type); - string get_preferred_name(CPPType *type); - static string hash_string(const string &name, int shift_offset); + std::string get_preferred_name(CPPType *type); + static std::string hash_string(const std::string &name, int shift_offset); TypeIndex get_type(CPPType *type, bool global); public: - typedef set Commands; - typedef map CommandParams; + typedef std::set Commands; + typedef std::map CommandParams; void insert_param_list(InterrogateBuilder::Commands &commands, - const string ¶ms); + const std::string ¶ms); - bool in_forcetype(const string &name) const; - string in_renametype(const string &name) const; - bool in_ignoretype(const string &name) const; - string in_defconstruct(const string &name) const; - bool in_ignoreinvolved(const string &name) const; + bool in_forcetype(const std::string &name) const; + std::string in_renametype(const std::string &name) const; + bool in_ignoretype(const std::string &name) const; + std::string in_defconstruct(const std::string &name) const; + bool in_ignoreinvolved(const std::string &name) const; bool in_ignoreinvolved(CPPType *type) const; - bool in_ignorefile(const string &name) const; - bool in_ignoremember(const string &name) const; - bool in_noinclude(const string &name) const; - bool should_include(const string &filename) const; + bool in_ignorefile(const std::string &name) const; + bool in_ignoremember(const std::string &name) const; + bool in_noinclude(const std::string &name) const; + bool should_include(const std::string &filename) const; bool is_inherited_published(CPPInstance *function, CPPStructType *struct_type); - void remap_indices(vector &remaps); + void remap_indices(std::vector &remaps); void scan_function(CPPFunctionGroup *fgroup); void scan_function(CPPInstance *function); void scan_struct_type(CPPStructType *type); @@ -96,18 +96,18 @@ public: ElementIndex scan_element(CPPInstance *element, CPPStructType *struct_type, CPPScope *scope); - FunctionIndex get_getter(CPPType *expr_type, string expression, + FunctionIndex get_getter(CPPType *expr_type, std::string expression, CPPStructType *struct_type, CPPScope *scope, CPPInstance *element); - FunctionIndex get_setter(CPPType *expr_type, string expression, + FunctionIndex get_setter(CPPType *expr_type, std::string expression, CPPStructType *struct_type, CPPScope *scope, CPPInstance *element); FunctionIndex get_cast_function(CPPType *to_type, CPPType *from_type, - const string &prefix); + const std::string &prefix); FunctionIndex - get_function(CPPInstance *function, string description, + get_function(CPPInstance *function, std::string description, CPPStructType *struct_type, CPPScope *scope, - int flags, const string &expression = string()); + int flags, const std::string &expression = std::string()); ElementIndex get_make_property(CPPMakeProperty *make_property, CPPStructType *struct_type, CPPScope *scope); @@ -133,19 +133,19 @@ public: void define_extension_type(InterrogateType &itype, CPPExtensionType *cpptype); - static string trim_blanks(const string &str); + static std::string trim_blanks(const std::string &str); - typedef map TypesByName; - typedef map FunctionsByName; - typedef map MakeSeqsByName; - typedef map PropertiesByName; + typedef std::map TypesByName; + typedef std::map FunctionsByName; + typedef std::map MakeSeqsByName; + typedef std::map PropertiesByName; TypesByName _types_by_name; FunctionsByName _functions_by_name; MakeSeqsByName _make_seqs_by_name; PropertiesByName _properties_by_name; - typedef map IncludeFiles; + typedef std::map IncludeFiles; IncludeFiles _include_files; Commands _forcetype; @@ -157,7 +157,7 @@ public: Commands _ignoremember; Commands _noinclude; - string _library_hash_name; + std::string _library_hash_name; friend class FunctionRemap; }; diff --git a/dtool/src/interrogate/interrogate_module.cxx b/dtool/src/interrogate/interrogate_module.cxx index 8c843e9da1..5c5cc9d9ab 100644 --- a/dtool/src/interrogate/interrogate_module.cxx +++ b/dtool/src/interrogate/interrogate_module.cxx @@ -27,6 +27,9 @@ #include +using std::cerr; +using std::string; + Filename output_code_filename; string module_name; string library_name; @@ -52,15 +55,15 @@ enum CommandOptions { }; static struct option long_options[] = { - { "oc", required_argument, NULL, CO_oc }, - { "module", required_argument, NULL, CO_module }, - { "library", required_argument, NULL, CO_library }, - { "c", no_argument, NULL, CO_c }, - { "python", no_argument, NULL, CO_python }, - { "python-native", no_argument, NULL, CO_python_native }, - { "track-interpreter", no_argument, NULL, CO_track_interpreter }, - { "import", required_argument, NULL, CO_import }, - { NULL } + { "oc", required_argument, nullptr, CO_oc }, + { "module", required_argument, nullptr, CO_module }, + { "library", required_argument, nullptr, CO_library }, + { "c", no_argument, nullptr, CO_c }, + { "python", no_argument, nullptr, CO_python }, + { "python-native", no_argument, nullptr, CO_python_native }, + { "track-interpreter", no_argument, nullptr, CO_track_interpreter }, + { "import", required_argument, nullptr, CO_import }, + { nullptr } }; /* @@ -80,10 +83,10 @@ upcase_string(const string &str) { * Finds a dependency cycle between the given dependency mapping, starting at * the node that is already placed in the given cycle vector. */ -static bool find_dependency_cycle(vector_string &cycle, map > &dependencies) { +static bool find_dependency_cycle(vector_string &cycle, std::map > &dependencies) { assert(!cycle.empty()); - const set &deps = dependencies[cycle.back()]; + const std::set &deps = dependencies[cycle.back()]; for (auto it = deps.begin(); it != deps.end(); ++it) { auto it2 = std::find(cycle.begin(), cycle.end(), *it); if (it2 != cycle.end()) { @@ -149,14 +152,14 @@ static bool print_dependent_types(const string &lib1, const string &lib2) { return false; } -int write_python_table_native(ostream &out) { +int write_python_table_native(std::ostream &out) { out << "\n#include \"dtoolbase.h\"\n" << "#include \"interrogate_request.h\"\n\n" << "#include \"py_panda.h\"\n\n"; int count = 0; - map > dependencies; + std::map > dependencies; // out << "extern \"C\" {\n"; @@ -182,7 +185,7 @@ int write_python_table_native(ostream &out) { if (interrogate_type_has_module_name(thetype) && module_name == interrogate_type_module_name(thetype)) { if (interrogate_type_has_library_name(thetype)) { string library_name = interrogate_type_library_name(thetype); - set &deps = dependencies[library_name]; + std::set &deps = dependencies[library_name]; // Get the dependencies for this library. int num_derivations = interrogate_type_number_of_derivations(thetype); @@ -192,7 +195,7 @@ int write_python_table_native(ostream &out) { interrogate_type_has_library_name(basetype)) { string baselib = interrogate_type_library_name(basetype); if (baselib != library_name) { - deps.insert(move(baselib)); + deps.insert(std::move(baselib)); } } } @@ -203,7 +206,7 @@ int write_python_table_native(ostream &out) { interrogate_type_has_library_name(wrapped)) { string wrappedlib = interrogate_type_library_name(wrapped); if (wrappedlib != library_name) { - deps.insert(move(wrappedlib)); + deps.insert(std::move(wrappedlib)); } } } @@ -219,7 +222,7 @@ int write_python_table_native(ostream &out) { for (auto it = dependencies.begin(); it != dependencies.end(); ++it) { const string &library_name = it->first; - set &deps = dependencies[library_name]; + std::set &deps = dependencies[library_name]; // Remove the dependencies that have already been added from the deps. if (!deps.empty()) { @@ -243,7 +246,7 @@ int write_python_table_native(ostream &out) { cerr << "Circular dependency between libraries detected:\n"; for (auto it = dependencies.begin(); it != dependencies.end(); ++it) { const string &library_name = it->first; - set &deps = dependencies[library_name]; + std::set &deps = dependencies[library_name]; if (deps.empty()) { continue; } @@ -316,10 +319,10 @@ int write_python_table_native(ostream &out) { << "static struct PyModuleDef py_" << library_name << "_module = {\n" << " PyModuleDef_HEAD_INIT,\n" << " \"" << library_name << "\",\n" - << " NULL,\n" + << " nullptr,\n" << " -1,\n" - << " NULL,\n" - << " NULL, NULL, NULL, NULL\n" + << " nullptr,\n" + << " nullptr, nullptr, nullptr, nullptr\n" << "};\n" << "\n" << "PyObject *PyInit_" << library_name << "() {\n"; @@ -346,10 +349,10 @@ int write_python_table_native(ostream &out) { out << "&" << *ii << "_moddef, "; } - out << "NULL};\n" + out << "nullptr};\n" << "\n" << " PyObject *module = Dtool_PyModuleInitHelper(defs, &py_" << library_name << "_module);\n" - << " if (module != NULL) {\n"; + << " if (module != nullptr) {\n"; for (ii = libraries.begin(); ii != libraries.end(); ii++) { out << " Dtool_" << *ii << "_BuildInstants(module);\n"; @@ -393,10 +396,10 @@ int write_python_table_native(ostream &out) { out << "&" << *ii << "_moddef, "; } - out << "NULL};\n" + out << "nullptr};\n" << "\n" << " PyObject *module = Dtool_PyModuleInitHelper(defs, \"" << module_name << "\");\n" - << " if (module != NULL) {\n"; + << " if (module != nullptr) {\n"; for (ii = libraries.begin(); ii != libraries.end(); ii++) { out << " Dtool_" << *ii << "_BuildInstants(module);\n"; @@ -410,7 +413,7 @@ int write_python_table_native(ostream &out) { << " PyErr_SetString(PyExc_ImportError, \"" << module_name << " was " << "compiled for Python \" PY_VERSION \", which is incompatible " << "with Python 3\");\n" - << " return (PyObject *)NULL;\n" + << " return nullptr;\n" << "}\n" << "#endif\n" << "#endif\n" @@ -420,7 +423,7 @@ int write_python_table_native(ostream &out) { return count; } -int write_python_table(ostream &out) { +int write_python_table(std::ostream &out) { out << "\n#include \"dtoolbase.h\"\n" << "#include \"interrogate_request.h\"\n\n" << "#undef _POSIX_C_SOURCE\n" @@ -497,17 +500,17 @@ int write_python_table(ostream &out) { library_name = module_name; } - out << " { NULL, NULL }\n" + out << " { nullptr, nullptr }\n" << "};\n\n" << "#if PY_MAJOR_VERSION >= 3\n" << "static struct PyModuleDef python_module = {\n" << " PyModuleDef_HEAD_INIT,\n" << " \"" << library_name << "\",\n" - << " NULL,\n" + << " nullptr,\n" << " -1,\n" << " python_methods,\n" - << " NULL, NULL, NULL, NULL\n" + << " nullptr, nullptr, nullptr, nullptr\n" << "};\n\n" << "#define INIT_FUNC PyObject *PyInit_" << library_name << "\n" @@ -545,7 +548,7 @@ int main(int argc, char *argv[]) { pystub(); preprocess_argv(argc, argv); - flag = getopt_long_only(argc, argv, short_options, long_options, NULL); + flag = getopt_long_only(argc, argv, short_options, long_options, nullptr); while (flag != EOF) { switch (flag) { case CO_oc: @@ -583,7 +586,7 @@ int main(int argc, char *argv[]) { default: exit(1); } - flag = getopt_long_only(argc, argv, short_options, long_options, NULL); + flag = getopt_long_only(argc, argv, short_options, long_options, nullptr); } argc -= (optind-1); @@ -617,7 +620,7 @@ int main(int argc, char *argv[]) { pathname.set_type(Filename::T_dso); nout << "Loading " << pathname << "\n"; void *dl = load_dso(DSearchPath(), pathname); - if (dl == NULL) { + if (dl == nullptr) { nout << "Unable to load: " << load_dso_error() << "\n"; exit(1); } diff --git a/dtool/src/interrogate/parameterRemap.I b/dtool/src/interrogate/parameterRemap.I index 4b3040e514..dac104e87f 100644 --- a/dtool/src/interrogate/parameterRemap.I +++ b/dtool/src/interrogate/parameterRemap.I @@ -20,8 +20,8 @@ ParameterRemap(CPPType *orig_type) : _new_type(orig_type) { _is_valid = true; - _temporary_type = (CPPType *)NULL; - _default_value = (CPPExpression *)NULL; + _temporary_type = nullptr; + _default_value = nullptr; } /** @@ -57,7 +57,7 @@ get_new_type() const { */ INLINE CPPType *ParameterRemap:: get_temporary_type() const { - if (_temporary_type == (CPPType *)NULL) { + if (_temporary_type == nullptr) { return _new_type; } else { return _temporary_type; @@ -69,7 +69,7 @@ get_temporary_type() const { */ INLINE bool ParameterRemap:: has_default_value() const { - return (_default_value != (CPPExpression *)NULL); + return (_default_value != nullptr); } /** diff --git a/dtool/src/interrogate/parameterRemap.cxx b/dtool/src/interrogate/parameterRemap.cxx index 19c6bb4251..4794c7c16d 100644 --- a/dtool/src/interrogate/parameterRemap.cxx +++ b/dtool/src/interrogate/parameterRemap.cxx @@ -13,6 +13,8 @@ #include "parameterRemap.h" +using std::string; + /** * @@ -26,7 +28,7 @@ ParameterRemap:: * original type to the new type, for passing into the actual C++ function. */ void ParameterRemap:: -pass_parameter(ostream &out, const string &variable_name) { +pass_parameter(std::ostream &out, const string &variable_name) { out << variable_name; } @@ -37,7 +39,7 @@ pass_parameter(ostream &out, const string &variable_name) { * return the modified expression. */ string ParameterRemap:: -prepare_return_expr(ostream &, int, const string &expression) { +prepare_return_expr(std::ostream &, int, const string &expression) { return expression; } diff --git a/dtool/src/interrogate/parameterRemap.h b/dtool/src/interrogate/parameterRemap.h index 1e34fd0a8f..9ae351e29c 100644 --- a/dtool/src/interrogate/parameterRemap.h +++ b/dtool/src/interrogate/parameterRemap.h @@ -47,11 +47,11 @@ public: INLINE CPPExpression *get_default_value() const; INLINE void set_default_value(CPPExpression *expr); - virtual void pass_parameter(ostream &out, const string &variable_name); - virtual string prepare_return_expr(ostream &out, int indent_level, - const string &expression); - virtual string get_return_expr(const string &expression); - virtual string temporary_to_return(const string &temporary); + virtual void pass_parameter(std::ostream &out, const std::string &variable_name); + virtual std::string prepare_return_expr(std::ostream &out, int indent_level, + const std::string &expression); + virtual std::string get_return_expr(const std::string &expression); + virtual std::string temporary_to_return(const std::string &temporary); virtual bool return_value_needs_management(); virtual FunctionIndex get_return_value_destructor(); virtual bool return_value_should_be_simple(); diff --git a/dtool/src/interrogate/parameterRemapBasicStringPtrToString.cxx b/dtool/src/interrogate/parameterRemapBasicStringPtrToString.cxx index 8c9c247ac7..07dad4694a 100644 --- a/dtool/src/interrogate/parameterRemapBasicStringPtrToString.cxx +++ b/dtool/src/interrogate/parameterRemapBasicStringPtrToString.cxx @@ -14,6 +14,8 @@ #include "parameterRemapBasicStringPtrToString.h" #include "interrogate.h" +using std::string; + /** * */ @@ -21,8 +23,8 @@ ParameterRemapBasicStringPtrToString:: ParameterRemapBasicStringPtrToString(CPPType *orig_type) : ParameterRemapToString(orig_type) { - static CPPType *const_char_star_type = (CPPType *)NULL; - if (const_char_star_type == (CPPType *)NULL) { + static CPPType *const_char_star_type = nullptr; + if (const_char_star_type == nullptr) { const_char_star_type = parser.parse_type("const char *"); } @@ -34,7 +36,7 @@ ParameterRemapBasicStringPtrToString(CPPType *orig_type) : * original type to the new type, for passing into the actual C++ function. */ void ParameterRemapBasicStringPtrToString:: -pass_parameter(ostream &out, const string &variable_name) { +pass_parameter(std::ostream &out, const string &variable_name) { out << "&std::string(" << variable_name << ")"; } @@ -54,8 +56,8 @@ ParameterRemapBasicWStringPtrToWString:: ParameterRemapBasicWStringPtrToWString(CPPType *orig_type) : ParameterRemapToWString(orig_type) { - static CPPType *const_wchar_star_type = (CPPType *)NULL; - if (const_wchar_star_type == (CPPType *)NULL) { + static CPPType *const_wchar_star_type = nullptr; + if (const_wchar_star_type == nullptr) { const_wchar_star_type = parser.parse_type("const wchar_t *"); } @@ -67,7 +69,7 @@ ParameterRemapBasicWStringPtrToWString(CPPType *orig_type) : * original type to the new type, for passing into the actual C++ function. */ void ParameterRemapBasicWStringPtrToWString:: -pass_parameter(ostream &out, const string &variable_name) { +pass_parameter(std::ostream &out, const string &variable_name) { out << "&std::wstring(" << variable_name << ")"; } diff --git a/dtool/src/interrogate/parameterRemapBasicStringPtrToString.h b/dtool/src/interrogate/parameterRemapBasicStringPtrToString.h index e034d8ebad..c0c385af5e 100644 --- a/dtool/src/interrogate/parameterRemapBasicStringPtrToString.h +++ b/dtool/src/interrogate/parameterRemapBasicStringPtrToString.h @@ -25,8 +25,8 @@ class ParameterRemapBasicStringPtrToString : public ParameterRemapToString { public: ParameterRemapBasicStringPtrToString(CPPType *orig_type); - virtual void pass_parameter(ostream &out, const string &variable_name); - virtual string get_return_expr(const string &expression); + virtual void pass_parameter(std::ostream &out, const std::string &variable_name); + virtual std::string get_return_expr(const std::string &expression); }; /** @@ -36,8 +36,8 @@ class ParameterRemapBasicWStringPtrToWString : public ParameterRemapToWString { public: ParameterRemapBasicWStringPtrToWString(CPPType *orig_type); - virtual void pass_parameter(ostream &out, const string &variable_name); - virtual string get_return_expr(const string &expression); + virtual void pass_parameter(std::ostream &out, const std::string &variable_name); + virtual std::string get_return_expr(const std::string &expression); }; #endif diff --git a/dtool/src/interrogate/parameterRemapBasicStringRefToString.cxx b/dtool/src/interrogate/parameterRemapBasicStringRefToString.cxx index a94055f899..90cd3d7e45 100644 --- a/dtool/src/interrogate/parameterRemapBasicStringRefToString.cxx +++ b/dtool/src/interrogate/parameterRemapBasicStringRefToString.cxx @@ -14,6 +14,8 @@ #include "parameterRemapBasicStringRefToString.h" #include "interrogate.h" +using std::string; + /** * */ @@ -21,8 +23,8 @@ ParameterRemapBasicStringRefToString:: ParameterRemapBasicStringRefToString(CPPType *orig_type) : ParameterRemapToString(orig_type) { - static CPPType *const_char_star_type = (CPPType *)NULL; - if (const_char_star_type == (CPPType *)NULL) { + static CPPType *const_char_star_type = nullptr; + if (const_char_star_type == nullptr) { const_char_star_type = parser.parse_type("const char *"); } @@ -34,7 +36,7 @@ ParameterRemapBasicStringRefToString(CPPType *orig_type) : * original type to the new type, for passing into the actual C++ function. */ void ParameterRemapBasicStringRefToString:: -pass_parameter(ostream &out, const string &variable_name) { +pass_parameter(std::ostream &out, const string &variable_name) { out << "std::string(" << variable_name << ")"; } @@ -54,8 +56,8 @@ ParameterRemapBasicWStringRefToWString:: ParameterRemapBasicWStringRefToWString(CPPType *orig_type) : ParameterRemapToWString(orig_type) { - static CPPType *const_wchar_star_type = (CPPType *)NULL; - if (const_wchar_star_type == (CPPType *)NULL) { + static CPPType *const_wchar_star_type = nullptr; + if (const_wchar_star_type == nullptr) { const_wchar_star_type = parser.parse_type("const wchar_t *"); } @@ -67,7 +69,7 @@ ParameterRemapBasicWStringRefToWString(CPPType *orig_type) : * original type to the new type, for passing into the actual C++ function. */ void ParameterRemapBasicWStringRefToWString:: -pass_parameter(ostream &out, const string &variable_name) { +pass_parameter(std::ostream &out, const string &variable_name) { out << "std::wstring(" << variable_name << ")"; } diff --git a/dtool/src/interrogate/parameterRemapBasicStringRefToString.h b/dtool/src/interrogate/parameterRemapBasicStringRefToString.h index 65c6bc23fc..546e5aad97 100644 --- a/dtool/src/interrogate/parameterRemapBasicStringRefToString.h +++ b/dtool/src/interrogate/parameterRemapBasicStringRefToString.h @@ -25,8 +25,8 @@ class ParameterRemapBasicStringRefToString : public ParameterRemapToString { public: ParameterRemapBasicStringRefToString(CPPType *orig_type); - virtual void pass_parameter(ostream &out, const string &variable_name); - virtual string get_return_expr(const string &expression); + virtual void pass_parameter(std::ostream &out, const std::string &variable_name); + virtual std::string get_return_expr(const std::string &expression); }; /** @@ -36,8 +36,8 @@ class ParameterRemapBasicWStringRefToWString : public ParameterRemapToWString { public: ParameterRemapBasicWStringRefToWString(CPPType *orig_type); - virtual void pass_parameter(ostream &out, const string &variable_name); - virtual string get_return_expr(const string &expression); + virtual void pass_parameter(std::ostream &out, const std::string &variable_name); + virtual std::string get_return_expr(const std::string &expression); }; #endif diff --git a/dtool/src/interrogate/parameterRemapBasicStringToString.cxx b/dtool/src/interrogate/parameterRemapBasicStringToString.cxx index db031004c6..21faabfaac 100644 --- a/dtool/src/interrogate/parameterRemapBasicStringToString.cxx +++ b/dtool/src/interrogate/parameterRemapBasicStringToString.cxx @@ -15,6 +15,9 @@ #include "interfaceMaker.h" #include "interrogate.h" +using std::ostream; +using std::string; + /** * */ @@ -22,8 +25,8 @@ ParameterRemapBasicStringToString:: ParameterRemapBasicStringToString(CPPType *orig_type) : ParameterRemapToString(orig_type) { - static CPPType *const_char_star_type = (CPPType *)NULL; - if (const_char_star_type == (CPPType *)NULL) { + static CPPType *const_char_star_type = nullptr; + if (const_char_star_type == nullptr) { const_char_star_type = parser.parse_type("const char *"); } @@ -68,8 +71,8 @@ ParameterRemapBasicWStringToWString:: ParameterRemapBasicWStringToWString(CPPType *orig_type) : ParameterRemapToWString(orig_type) { - static CPPType *const_wchar_star_type = (CPPType *)NULL; - if (const_wchar_star_type == (CPPType *)NULL) { + static CPPType *const_wchar_star_type = nullptr; + if (const_wchar_star_type == nullptr) { const_wchar_star_type = parser.parse_type("const wchar_t *"); } diff --git a/dtool/src/interrogate/parameterRemapBasicStringToString.h b/dtool/src/interrogate/parameterRemapBasicStringToString.h index 57d1a5624e..d27da23796 100644 --- a/dtool/src/interrogate/parameterRemapBasicStringToString.h +++ b/dtool/src/interrogate/parameterRemapBasicStringToString.h @@ -25,10 +25,10 @@ class ParameterRemapBasicStringToString : public ParameterRemapToString { public: ParameterRemapBasicStringToString(CPPType *orig_type); - virtual void pass_parameter(ostream &out, const string &variable_name); - virtual string prepare_return_expr(ostream &out, int indent_level, - const string &expression); - virtual string get_return_expr(const string &expression); + virtual void pass_parameter(std::ostream &out, const std::string &variable_name); + virtual std::string prepare_return_expr(std::ostream &out, int indent_level, + const std::string &expression); + virtual std::string get_return_expr(const std::string &expression); }; /** @@ -38,10 +38,10 @@ class ParameterRemapBasicWStringToWString : public ParameterRemapToWString { public: ParameterRemapBasicWStringToWString(CPPType *orig_type); - virtual void pass_parameter(ostream &out, const string &variable_name); - virtual string prepare_return_expr(ostream &out, int indent_level, - const string &expression); - virtual string get_return_expr(const string &expression); + virtual void pass_parameter(std::ostream &out, const std::string &variable_name); + virtual std::string prepare_return_expr(std::ostream &out, int indent_level, + const std::string &expression); + virtual std::string get_return_expr(const std::string &expression); }; #endif diff --git a/dtool/src/interrogate/parameterRemapConcreteToPointer.cxx b/dtool/src/interrogate/parameterRemapConcreteToPointer.cxx index 05f0eda533..f5e7c35b39 100644 --- a/dtool/src/interrogate/parameterRemapConcreteToPointer.cxx +++ b/dtool/src/interrogate/parameterRemapConcreteToPointer.cxx @@ -36,7 +36,7 @@ ParameterRemapConcreteToPointer(CPPType *orig_type) : * type to the original type, for passing into the actual C++ function. */ void ParameterRemapConcreteToPointer:: -pass_parameter(ostream &out, const string &variable_name) { +pass_parameter(std::ostream &out, const std::string &variable_name) { if (variable_name.size() > 1 && variable_name[0] == '&') { // Prevent generating something like *¶m Also, if this is really some // local type, we can presumably just move it? @@ -50,8 +50,8 @@ pass_parameter(ostream &out, const string &variable_name) { * Returns an expression that evalutes to the appropriate value type for * returning from the function, given an expression of the original type. */ -string ParameterRemapConcreteToPointer:: -get_return_expr(const string &expression) { +std::string ParameterRemapConcreteToPointer:: +get_return_expr(const std::string &expression) { return "new " + _orig_type->get_local_name(&parser) + "(" + expression + ")"; diff --git a/dtool/src/interrogate/parameterRemapConcreteToPointer.h b/dtool/src/interrogate/parameterRemapConcreteToPointer.h index 50c9bbab2e..2e69597712 100644 --- a/dtool/src/interrogate/parameterRemapConcreteToPointer.h +++ b/dtool/src/interrogate/parameterRemapConcreteToPointer.h @@ -26,8 +26,8 @@ class ParameterRemapConcreteToPointer : public ParameterRemap { public: ParameterRemapConcreteToPointer(CPPType *orig_type); - virtual void pass_parameter(ostream &out, const string &variable_name); - virtual string get_return_expr(const string &expression); + virtual void pass_parameter(std::ostream &out, const std::string &variable_name); + virtual std::string get_return_expr(const std::string &expression); virtual bool return_value_needs_management(); virtual FunctionIndex get_return_value_destructor(); virtual bool return_value_should_be_simple(); diff --git a/dtool/src/interrogate/parameterRemapConstToNonConst.cxx b/dtool/src/interrogate/parameterRemapConstToNonConst.cxx index c031350e70..2fb23e90bc 100644 --- a/dtool/src/interrogate/parameterRemapConstToNonConst.cxx +++ b/dtool/src/interrogate/parameterRemapConstToNonConst.cxx @@ -31,7 +31,7 @@ ParameterRemapConstToNonConst(CPPType *orig_type) : * type to the original type, for passing into the actual C++ function. */ void ParameterRemapConstToNonConst:: -pass_parameter(ostream &out, const string &variable_name) { +pass_parameter(std::ostream &out, const std::string &variable_name) { out << variable_name; } @@ -39,7 +39,7 @@ pass_parameter(ostream &out, const string &variable_name) { * Returns an expression that evalutes to the appropriate value type for * returning from the function, given an expression of the original type. */ -string ParameterRemapConstToNonConst:: -get_return_expr(const string &expression) { +std::string ParameterRemapConstToNonConst:: +get_return_expr(const std::string &expression) { return expression; } diff --git a/dtool/src/interrogate/parameterRemapConstToNonConst.h b/dtool/src/interrogate/parameterRemapConstToNonConst.h index d952e26167..ee376764e1 100644 --- a/dtool/src/interrogate/parameterRemapConstToNonConst.h +++ b/dtool/src/interrogate/parameterRemapConstToNonConst.h @@ -27,8 +27,8 @@ class ParameterRemapConstToNonConst : public ParameterRemap { public: ParameterRemapConstToNonConst(CPPType *orig_type); - virtual void pass_parameter(ostream &out, const string &variable_name); - virtual string get_return_expr(const string &expression); + virtual void pass_parameter(std::ostream &out, const std::string &variable_name); + virtual std::string get_return_expr(const std::string &expression); }; #endif diff --git a/dtool/src/interrogate/parameterRemapEnumToInt.cxx b/dtool/src/interrogate/parameterRemapEnumToInt.cxx index 40283dd364..59fb6019fc 100644 --- a/dtool/src/interrogate/parameterRemapEnumToInt.cxx +++ b/dtool/src/interrogate/parameterRemapEnumToInt.cxx @@ -35,7 +35,7 @@ ParameterRemapEnumToInt(CPPType *orig_type) : * type to the original type, for passing into the actual C++ function. */ void ParameterRemapEnumToInt:: -pass_parameter(ostream &out, const string &variable_name) { +pass_parameter(std::ostream &out, const std::string &variable_name) { out << "(" << _enum_type->get_local_name(&parser) << ")" << variable_name; } @@ -43,8 +43,8 @@ pass_parameter(ostream &out, const string &variable_name) { * Returns an expression that evalutes to the appropriate value type for * returning from the function, given an expression of the original type. */ -string ParameterRemapEnumToInt:: -get_return_expr(const string &expression) { +std::string ParameterRemapEnumToInt:: +get_return_expr(const std::string &expression) { return "(int)(" + expression + ")"; } diff --git a/dtool/src/interrogate/parameterRemapEnumToInt.h b/dtool/src/interrogate/parameterRemapEnumToInt.h index f3a33bc631..a74951bcaa 100644 --- a/dtool/src/interrogate/parameterRemapEnumToInt.h +++ b/dtool/src/interrogate/parameterRemapEnumToInt.h @@ -26,8 +26,8 @@ class ParameterRemapEnumToInt : public ParameterRemap { public: ParameterRemapEnumToInt(CPPType *orig_type); - virtual void pass_parameter(ostream &out, const string &variable_name); - virtual string get_return_expr(const string &expression); + virtual void pass_parameter(std::ostream &out, const std::string &variable_name); + virtual std::string get_return_expr(const std::string &expression); private: CPPType *_enum_type; diff --git a/dtool/src/interrogate/parameterRemapHandleToInt.cxx b/dtool/src/interrogate/parameterRemapHandleToInt.cxx index b22052c7c3..4594ca45c8 100644 --- a/dtool/src/interrogate/parameterRemapHandleToInt.cxx +++ b/dtool/src/interrogate/parameterRemapHandleToInt.cxx @@ -36,7 +36,7 @@ ParameterRemapHandleToInt(CPPType *orig_type) : * type to the original type, for passing into the actual C++ function. */ void ParameterRemapHandleToInt:: -pass_parameter(ostream &out, const string &variable_name) { +pass_parameter(std::ostream &out, const std::string &variable_name) { CPPType *unwrapped = TypeManager::unwrap_const(_orig_type); if (unwrapped->get_local_name(&parser) == "TypeHandle") { @@ -50,7 +50,7 @@ pass_parameter(ostream &out, const string &variable_name) { * Returns an expression that evalutes to the appropriate value type for * returning from the function, given an expression of the original type. */ -string ParameterRemapHandleToInt:: -get_return_expr(const string &expression) { +std::string ParameterRemapHandleToInt:: +get_return_expr(const std::string &expression) { return "(" + expression + ").get_index()"; } diff --git a/dtool/src/interrogate/parameterRemapHandleToInt.h b/dtool/src/interrogate/parameterRemapHandleToInt.h index 840a768180..32c2016300 100644 --- a/dtool/src/interrogate/parameterRemapHandleToInt.h +++ b/dtool/src/interrogate/parameterRemapHandleToInt.h @@ -30,8 +30,8 @@ class ParameterRemapHandleToInt : public ParameterRemap { public: ParameterRemapHandleToInt(CPPType *orig_type); - virtual void pass_parameter(ostream &out, const string &variable_name); - virtual string get_return_expr(const string &expression); + virtual void pass_parameter(std::ostream &out, const std::string &variable_name); + virtual std::string get_return_expr(const std::string &expression); }; #endif diff --git a/dtool/src/interrogate/parameterRemapPTToPointer.cxx b/dtool/src/interrogate/parameterRemapPTToPointer.cxx index 44f6a0d036..243b907260 100644 --- a/dtool/src/interrogate/parameterRemapPTToPointer.cxx +++ b/dtool/src/interrogate/parameterRemapPTToPointer.cxx @@ -21,6 +21,8 @@ #include "cppDeclaration.h" #include "pnotify.h" +using std::string; + /** * */ @@ -29,23 +31,23 @@ ParameterRemapPTToPointer(CPPType *orig_type) : ParameterRemap(orig_type) { CPPStructType *pt_type = TypeManager::unwrap(_orig_type)->as_struct_type(); - assert(pt_type != (CPPStructType *)NULL); + assert(pt_type != nullptr); // A horrible hack around a CPPParser bug. We don't trust the CPPStructType // pointer we were given; instead, we ask CPPParser to parse a new type of // the same name. This has a better chance of fully resolving templates. string name = pt_type->get_local_name(&parser); CPPType *new_type = parser.parse_type(name); - if (new_type == (CPPType *)NULL) { + if (new_type == nullptr) { nout << "Type " << name << " is unknown to parser.\n"; } else { new_type = new_type->resolve_type(&parser, &parser); pt_type = new_type->as_struct_type(); - assert(pt_type != (CPPStructType *)NULL); + assert(pt_type != nullptr); } _pointer_type = TypeManager::get_pointer_type(pt_type); - if (_pointer_type == (CPPType *)NULL) { + if (_pointer_type == nullptr) { // If we couldn't figure out the pointer type, forget it. nout << "Couldn't figure out pointer type for " << *pt_type << "\n"; _is_valid = false; @@ -64,7 +66,7 @@ ParameterRemapPTToPointer(CPPType *orig_type) : * type to the original type, for passing into the actual C++ function. */ void ParameterRemapPTToPointer:: -pass_parameter(ostream &out, const string &variable_name) { +pass_parameter(std::ostream &out, const string &variable_name) { out << variable_name; } diff --git a/dtool/src/interrogate/parameterRemapPTToPointer.h b/dtool/src/interrogate/parameterRemapPTToPointer.h index e92bd5b5e8..5c59f075b9 100644 --- a/dtool/src/interrogate/parameterRemapPTToPointer.h +++ b/dtool/src/interrogate/parameterRemapPTToPointer.h @@ -29,9 +29,9 @@ class ParameterRemapPTToPointer : public ParameterRemap { public: ParameterRemapPTToPointer(CPPType *orig_type); - virtual void pass_parameter(ostream &out, const string &variable_name); - virtual string get_return_expr(const string &expression); - virtual string temporary_to_return(const string &temporary); + virtual void pass_parameter(std::ostream &out, const std::string &variable_name); + virtual std::string get_return_expr(const std::string &expression); + virtual std::string temporary_to_return(const std::string &temporary); private: CPPType *_pointer_type; diff --git a/dtool/src/interrogate/parameterRemapReferenceToConcrete.cxx b/dtool/src/interrogate/parameterRemapReferenceToConcrete.cxx index c4a4e77451..bdb613cef6 100644 --- a/dtool/src/interrogate/parameterRemapReferenceToConcrete.cxx +++ b/dtool/src/interrogate/parameterRemapReferenceToConcrete.cxx @@ -35,7 +35,7 @@ ParameterRemapReferenceToConcrete(CPPType *orig_type) : * type to the original type, for passing into the actual C++ function. */ void ParameterRemapReferenceToConcrete:: -pass_parameter(ostream &out, const string &variable_name) { +pass_parameter(std::ostream &out, const std::string &variable_name) { out << variable_name; } @@ -43,7 +43,7 @@ pass_parameter(ostream &out, const string &variable_name) { * Returns an expression that evalutes to the appropriate value type for * returning from the function, given an expression of the original type. */ -string ParameterRemapReferenceToConcrete:: -get_return_expr(const string &expression) { +std::string ParameterRemapReferenceToConcrete:: +get_return_expr(const std::string &expression) { return expression; } diff --git a/dtool/src/interrogate/parameterRemapReferenceToConcrete.h b/dtool/src/interrogate/parameterRemapReferenceToConcrete.h index 47ac919a39..12c7ef27bd 100644 --- a/dtool/src/interrogate/parameterRemapReferenceToConcrete.h +++ b/dtool/src/interrogate/parameterRemapReferenceToConcrete.h @@ -27,8 +27,8 @@ class ParameterRemapReferenceToConcrete : public ParameterRemap { public: ParameterRemapReferenceToConcrete(CPPType *orig_type); - virtual void pass_parameter(ostream &out, const string &variable_name); - virtual string get_return_expr(const string &expression); + virtual void pass_parameter(std::ostream &out, const std::string &variable_name); + virtual std::string get_return_expr(const std::string &expression); }; #endif diff --git a/dtool/src/interrogate/parameterRemapReferenceToPointer.cxx b/dtool/src/interrogate/parameterRemapReferenceToPointer.cxx index 3199017eea..6c8e8b05a9 100644 --- a/dtool/src/interrogate/parameterRemapReferenceToPointer.cxx +++ b/dtool/src/interrogate/parameterRemapReferenceToPointer.cxx @@ -35,7 +35,7 @@ ParameterRemapReferenceToPointer(CPPType *orig_type) : * type to the original type, for passing into the actual C++ function. */ void ParameterRemapReferenceToPointer:: -pass_parameter(ostream &out, const string &variable_name) { +pass_parameter(std::ostream &out, const std::string &variable_name) { if (variable_name.size() > 1 && variable_name[0] == '&') { // Prevent generating something like *¶m Also, if this is really some // local type, we can presumably just move it? This is only relevant if @@ -52,7 +52,7 @@ pass_parameter(ostream &out, const string &variable_name) { * Returns an expression that evalutes to the appropriate value type for * returning from the function, given an expression of the original type. */ -string ParameterRemapReferenceToPointer:: -get_return_expr(const string &expression) { +std::string ParameterRemapReferenceToPointer:: +get_return_expr(const std::string &expression) { return "&(" + expression + ")"; } diff --git a/dtool/src/interrogate/parameterRemapReferenceToPointer.h b/dtool/src/interrogate/parameterRemapReferenceToPointer.h index 3e6d4bd87d..6ee71d86c5 100644 --- a/dtool/src/interrogate/parameterRemapReferenceToPointer.h +++ b/dtool/src/interrogate/parameterRemapReferenceToPointer.h @@ -26,8 +26,8 @@ class ParameterRemapReferenceToPointer : public ParameterRemap { public: ParameterRemapReferenceToPointer(CPPType *orig_type); - virtual void pass_parameter(ostream &out, const string &variable_name); - virtual string get_return_expr(const string &expression); + virtual void pass_parameter(std::ostream &out, const std::string &variable_name); + virtual std::string get_return_expr(const std::string &expression); }; #endif diff --git a/dtool/src/interrogate/parameterRemapThis.cxx b/dtool/src/interrogate/parameterRemapThis.cxx index e0ef867931..7fd8be4243 100644 --- a/dtool/src/interrogate/parameterRemapThis.cxx +++ b/dtool/src/interrogate/parameterRemapThis.cxx @@ -39,7 +39,7 @@ ParameterRemapThis(CPPType *type, bool is_const) : * type to the original type, for passing into the actual C++ function. */ void ParameterRemapThis:: -pass_parameter(ostream &out, const string &variable_name) { +pass_parameter(std::ostream &out, const std::string &variable_name) { out << "(*" << variable_name << ")"; } @@ -47,8 +47,8 @@ pass_parameter(ostream &out, const string &variable_name) { * Returns an expression that evalutes to the appropriate value type for * returning from the function, given an expression of the original type. */ -string ParameterRemapThis:: -get_return_expr(const string &) { +std::string ParameterRemapThis:: +get_return_expr(const std::string &) { return "**invalid**"; } diff --git a/dtool/src/interrogate/parameterRemapThis.h b/dtool/src/interrogate/parameterRemapThis.h index 31204684b1..3d13b66717 100644 --- a/dtool/src/interrogate/parameterRemapThis.h +++ b/dtool/src/interrogate/parameterRemapThis.h @@ -27,8 +27,8 @@ class ParameterRemapThis : public ParameterRemap { public: ParameterRemapThis(CPPType *type, bool is_const); - virtual void pass_parameter(ostream &out, const string &variable_name); - virtual string get_return_expr(const string &expression); + virtual void pass_parameter(std::ostream &out, const std::string &variable_name); + virtual std::string get_return_expr(const std::string &expression); virtual bool is_this(); }; diff --git a/dtool/src/interrogate/parameterRemapToString.cxx b/dtool/src/interrogate/parameterRemapToString.cxx index fe7c7a8253..9771a2db1b 100644 --- a/dtool/src/interrogate/parameterRemapToString.cxx +++ b/dtool/src/interrogate/parameterRemapToString.cxx @@ -15,6 +15,8 @@ #include "interrogate.h" #include "typeManager.h" +using std::string; + /** * */ @@ -22,13 +24,13 @@ ParameterRemapToString:: ParameterRemapToString(CPPType *orig_type) : ParameterRemap(orig_type) { - static CPPType *char_star_type = (CPPType *)NULL; - if (char_star_type == (CPPType *)NULL) { + static CPPType *char_star_type = nullptr; + if (char_star_type == nullptr) { char_star_type = parser.parse_type("char *"); } - static CPPType *const_char_star_type = (CPPType *)NULL; - if (const_char_star_type == (CPPType *)NULL) { + static CPPType *const_char_star_type = nullptr; + if (const_char_star_type == nullptr) { const_char_star_type = parser.parse_type("const char *"); } @@ -44,7 +46,7 @@ ParameterRemapToString(CPPType *orig_type) : * original type to the new type, for passing into the actual C++ function. */ void ParameterRemapToString:: -pass_parameter(ostream &out, const string &variable_name) { +pass_parameter(std::ostream &out, const string &variable_name) { out << variable_name; } @@ -75,8 +77,8 @@ ParameterRemapToWString:: ParameterRemapToWString(CPPType *orig_type) : ParameterRemap(orig_type) { - static CPPType *char_star_type = (CPPType *)NULL; - if (char_star_type == (CPPType *)NULL) { + static CPPType *char_star_type = nullptr; + if (char_star_type == nullptr) { char_star_type = parser.parse_type("const wchar_t *"); } @@ -88,7 +90,7 @@ ParameterRemapToWString(CPPType *orig_type) : * original type to the new type, for passing into the actual C++ function. */ void ParameterRemapToWString:: -pass_parameter(ostream &out, const string &variable_name) { +pass_parameter(std::ostream &out, const string &variable_name) { out << variable_name; } diff --git a/dtool/src/interrogate/parameterRemapToString.h b/dtool/src/interrogate/parameterRemapToString.h index b41369f9c0..5eed97d731 100644 --- a/dtool/src/interrogate/parameterRemapToString.h +++ b/dtool/src/interrogate/parameterRemapToString.h @@ -30,8 +30,8 @@ class ParameterRemapToString : public ParameterRemap { public: ParameterRemapToString(CPPType *orig_type); - virtual void pass_parameter(ostream &out, const string &variable_name); - virtual string get_return_expr(const string &expression); + virtual void pass_parameter(std::ostream &out, const std::string &variable_name); + virtual std::string get_return_expr(const std::string &expression); virtual bool new_type_is_atomic_string(); }; @@ -48,8 +48,8 @@ class ParameterRemapToWString : public ParameterRemap { public: ParameterRemapToWString(CPPType *orig_type); - virtual void pass_parameter(ostream &out, const string &variable_name); - virtual string get_return_expr(const string &expression); + virtual void pass_parameter(std::ostream &out, const std::string &variable_name); + virtual std::string get_return_expr(const std::string &expression); virtual bool new_type_is_atomic_string(); }; diff --git a/dtool/src/interrogate/parse_file.cxx b/dtool/src/interrogate/parse_file.cxx index 6670bcbe44..aa903407d1 100644 --- a/dtool/src/interrogate/parse_file.cxx +++ b/dtool/src/interrogate/parse_file.cxx @@ -25,6 +25,11 @@ #include "pystub.h" #include +using std::cerr; +using std::cin; +using std::cout; +using std::string; + CPPParser parser; void @@ -48,10 +53,10 @@ predefine_macro(CPPParser &parser, const string &option) { void show_type_or_expression(const string &str) { CPPExpression *expr = parser.parse_expr(str); - if (expr != NULL) { + if (expr != nullptr) { cout << "\nExpression: " << *expr << "\n"; CPPType *type = expr->determine_type(); - if (type == NULL) { + if (type == nullptr) { cout << "type is unknown\n"; } else { cout << "type is " << *type << "\n"; @@ -60,13 +65,13 @@ show_type_or_expression(const string &str) { } else { CPPType *type = parser.parse_type(str); - if (type != NULL) { + if (type != nullptr) { cout << "\nType: " << *type << "\n" << "Defined in: " << type->_file << "\n" << "Subtype code is: " << (int)type->get_subtype() << "\n\n"; CPPStructType *stype = type->as_struct_type(); - if (stype != (CPPStructType *)NULL) { + if (stype != nullptr) { stype->check_virtual(); } @@ -74,7 +79,14 @@ show_type_or_expression(const string &str) { cout << "\n\n" << "is_template = " << type->is_template() << "\n" << "is_fully_specified = " << type->is_fully_specified() << "\n" - << "is_tbd = " << type->is_tbd() << "\n"; + << "is_tbd = " << type->is_tbd() << "\n" + << "is_fundamental = " << type->is_fundamental() << "\n" + << "is_standard_layout = " << type->is_standard_layout() << "\n" + << "is_trivial = " << type->is_trivial() << "\n" + << "is_default_constructible = " << type->is_default_constructible() << "\n" + << "is_copy_constructible = " << type->is_copy_constructible() << "\n" + << "is_copy_assignable = " << type->is_copy_assignable() << "\n" + << "is_destructible = " << type->is_destructible() << "\n"; if (type->has_typedef_name()) { cout << "get_typedef_name = " << type->get_typedef_name() << "\n"; } @@ -84,7 +96,7 @@ show_type_or_expression(const string &str) { << "get_preferred_name = " << type->get_preferred_name() << "\n" << "is_incomplete = " << type->is_incomplete() << "\n"; - if (stype != (CPPStructType *)NULL) { + if (stype != nullptr) { cout << "scope = " << stype->get_scope()->get_fully_scoped_name() << "\n"; bool is_abstract = stype->is_abstract(); cout << "is_abstract = " << is_abstract << "\n"; @@ -109,19 +121,19 @@ show_type_or_expression(const string &str) { void show_methods(const string &str) { CPPType *type = parser.parse_type(str); - if (type == NULL) { + if (type == nullptr) { cerr << "Invalid type: " << str << "\n"; return; } CPPStructType *stype = type->as_struct_type(); - if (stype == NULL) { + if (stype == nullptr) { cerr << "Type is not a structure or class.\n"; return; } CPPScope *scope = stype->get_scope(); - assert(scope != (CPPScope *)NULL); + assert(scope != nullptr); cerr << "Methods in " << *stype << ":\n"; @@ -142,19 +154,19 @@ show_methods(const string &str) { void show_data_members(const string &str) { CPPType *type = parser.parse_type(str); - if (type == NULL) { + if (type == nullptr) { cerr << "Invalid type: " << str << "\n"; return; } CPPStructType *stype = type->as_struct_type(); - if (stype == NULL) { + if (stype == nullptr) { cerr << "Type is not a structure or class.\n"; return; } CPPScope *scope = stype->get_scope(); - assert(scope != (CPPScope *)NULL); + assert(scope != nullptr); cerr << "Data members in " << *stype << ":\n"; @@ -168,19 +180,19 @@ show_data_members(const string &str) { void show_nested_types(const string &str) { CPPType *type = parser.parse_type(str); - if (type == NULL) { + if (type == nullptr) { cerr << "Invalid type: " << str << "\n"; return; } CPPStructType *stype = type->as_struct_type(); - if (stype == NULL) { + if (stype == nullptr) { cerr << "Type is not a structure or class.\n"; return; } CPPScope *scope = stype->get_scope(); - assert(scope != (CPPScope *)NULL); + assert(scope != nullptr); cerr << "Nested types in " << *stype << ":\n"; @@ -276,7 +288,7 @@ main(int argc, char **argv) { while (cin) { string str; cout << "Enter an expression or type name:\n"; - getline(cin, str); + std::getline(std::cin, str); if (!str.empty()) { size_t space = str.find(' '); diff --git a/dtool/src/interrogate/typeManager.cxx b/dtool/src/interrogate/typeManager.cxx index 1485c785ca..ab1fbffce3 100644 --- a/dtool/src/interrogate/typeManager.cxx +++ b/dtool/src/interrogate/typeManager.cxx @@ -30,6 +30,8 @@ #include "cppTypedefType.h" #include "pnotify.h" +using std::string; + /** * A horrible hack around a CPPParser bug. We don't trust the CPPType pointer * we were given; instead, we ask CPPParser to parse a new type of the same @@ -37,7 +39,7 @@ */ CPPType *TypeManager:: resolve_type(CPPType *type, CPPScope *scope) { - if (scope == (CPPScope *)NULL) { + if (scope == nullptr) { scope = &parser; } @@ -122,6 +124,26 @@ is_reference(CPPType *type) { } } +/** + * Returns true if the indicated type is some kind of an rvalue reference. + */ +bool TypeManager:: +is_rvalue_reference(CPPType *type) { + switch (type->get_subtype()) { + case CPPDeclaration::ST_const: + return is_rvalue_reference(type->as_const_type()->_wrapped_around); + + case CPPDeclaration::ST_reference: + return type->as_reference_type()->_value_category == CPPReferenceType::VC_rvalue; + + case CPPDeclaration::ST_typedef: + return is_rvalue_reference(type->as_typedef_type()->_type); + + default: + return false; + } +} + /** * Returns true if the indicated type is some kind of a reference or const * reference type at all, false otherwise. @@ -308,6 +330,26 @@ is_struct(CPPType *type) { } } +/** + * Returns true if the indicated type is an enum class, const or otherwise. + */ +bool TypeManager:: +is_scoped_enum(CPPType *type) { + switch (type->get_subtype()) { + case CPPDeclaration::ST_enum: + return ((CPPEnumType *)type)->is_scoped(); + + case CPPDeclaration::ST_const: + return is_scoped_enum(type->as_const_type()->_wrapped_around); + + case CPPDeclaration::ST_typedef: + return is_scoped_enum(type->as_typedef_type()->_type); + + default: + return false; + } +} + /** * Returns true if the indicated type is some kind of enumerated type, const * or otherwise. @@ -550,7 +592,7 @@ is_char(CPPType *type) { case CPPDeclaration::ST_simple: { CPPSimpleType *simple_type = type->as_simple_type(); - if (simple_type != (CPPSimpleType *)NULL) { + if (simple_type != nullptr) { return simple_type->_type == CPPSimpleType::T_char && simple_type->_flags == 0; @@ -581,7 +623,7 @@ is_unsigned_char(CPPType *type) { { CPPSimpleType *simple_type = type->as_simple_type(); - if (simple_type != (CPPSimpleType *)NULL) { + if (simple_type != nullptr) { return (simple_type->_type == CPPSimpleType::T_char) && (simple_type->_flags & CPPSimpleType::F_unsigned) != 0; @@ -613,7 +655,7 @@ is_signed_char(CPPType *type) { { CPPSimpleType *simple_type = type->as_simple_type(); - if (simple_type != (CPPSimpleType *)NULL) { + if (simple_type != nullptr) { return (simple_type->_type == CPPSimpleType::T_char) && (simple_type->_flags & CPPSimpleType::F_signed) != 0; @@ -717,7 +759,7 @@ is_const_unsigned_char_pointer(CPPType *type) { bool TypeManager:: is_basic_string_char(CPPType *type) { CPPType *string_type = get_basic_string_char_type(); - if (string_type != (CPPType *)NULL && + if (string_type != nullptr && string_type->get_local_name(&parser) == type->get_local_name(&parser)) { return true; } @@ -822,7 +864,7 @@ is_wchar(CPPType *type) { case CPPDeclaration::ST_simple: { CPPSimpleType *simple_type = type->as_simple_type(); - if (simple_type != (CPPSimpleType *)NULL) { + if (simple_type != nullptr) { return simple_type->_type == CPPSimpleType::T_wchar_t; } } @@ -865,7 +907,7 @@ is_wchar_pointer(CPPType *type) { bool TypeManager:: is_basic_string_wchar(CPPType *type) { CPPType *string_type = get_basic_string_wchar_type(); - if (string_type != (CPPType *)NULL && + if (string_type != nullptr && string_type->get_local_name(&parser) == type->get_local_name(&parser)) { return true; } @@ -965,6 +1007,7 @@ is_wstring(CPPType *type) { bool TypeManager:: is_vector_unsigned_char(CPPType *type) { if (type->get_local_name(&parser) == "vector< unsigned char >" || + type->get_local_name(&parser) == "std::vector< unsigned char >" || type->get_local_name(&parser) == "pvector< unsigned char >") { return true; } @@ -1030,7 +1073,7 @@ is_bool(CPPType *type) { case CPPDeclaration::ST_simple: { CPPSimpleType *simple_type = type->as_simple_type(); - if (simple_type != (CPPSimpleType *)NULL) { + if (simple_type != nullptr) { return simple_type->_type == CPPSimpleType::T_bool; } @@ -1063,7 +1106,7 @@ is_integer(CPPType *type) { case CPPDeclaration::ST_simple: { CPPSimpleType *simple_type = type->as_simple_type(); - if (simple_type != (CPPSimpleType *)NULL) { + if (simple_type != nullptr) { return (simple_type->_type == CPPSimpleType::T_bool || simple_type->_type == CPPSimpleType::T_char || @@ -1098,7 +1141,7 @@ is_unsigned_integer(CPPType *type) { case CPPDeclaration::ST_simple: { CPPSimpleType *simple_type = type->as_simple_type(); - if (simple_type != (CPPSimpleType *)NULL) { + if (simple_type != nullptr) { return ((simple_type->_type == CPPSimpleType::T_bool || simple_type->_type == CPPSimpleType::T_char || @@ -1187,7 +1230,7 @@ is_long(CPPType *type) { case CPPDeclaration::ST_simple: { CPPSimpleType *simple_type = type->as_simple_type(); - if (simple_type != (CPPSimpleType *)NULL) { + if (simple_type != nullptr) { return (simple_type->_type == CPPSimpleType::T_int && (simple_type->_flags & CPPSimpleType::F_long) != 0); } @@ -1217,7 +1260,7 @@ is_short(CPPType *type) { case CPPDeclaration::ST_simple: { CPPSimpleType *simple_type = type->as_simple_type(); - if (simple_type != (CPPSimpleType *)NULL) { + if (simple_type != nullptr) { return (simple_type->_type == CPPSimpleType::T_int && (simple_type->_flags & CPPSimpleType::F_short) != 0); } @@ -1246,7 +1289,7 @@ is_unsigned_short(CPPType *type) { case CPPDeclaration::ST_simple: { CPPSimpleType *simple_type = type->as_simple_type(); - if (simple_type != (CPPSimpleType *)NULL) { + if (simple_type != nullptr) { return (simple_type->_type == CPPSimpleType::T_int && (simple_type->_flags & (CPPSimpleType::F_short | CPPSimpleType::F_unsigned)) == (CPPSimpleType::F_short | CPPSimpleType::F_unsigned)); } @@ -1276,7 +1319,7 @@ is_longlong(CPPType *type) { case CPPDeclaration::ST_simple: { CPPSimpleType *simple_type = type->as_simple_type(); - if (simple_type != (CPPSimpleType *)NULL) { + if (simple_type != nullptr) { return (simple_type->_type == CPPSimpleType::T_int && (simple_type->_flags & CPPSimpleType::F_longlong) != 0); } @@ -1306,7 +1349,7 @@ is_unsigned_longlong(CPPType *type) { case CPPDeclaration::ST_simple: { CPPSimpleType *simple_type = type->as_simple_type(); - if (simple_type != (CPPSimpleType *)NULL) { + if (simple_type != nullptr) { return (simple_type->_type == CPPSimpleType::T_int && (simple_type->_flags & (CPPSimpleType::F_longlong | CPPSimpleType::F_unsigned)) == (CPPSimpleType::F_longlong | CPPSimpleType::F_unsigned)); } @@ -1335,7 +1378,7 @@ is_double(CPPType *type) { case CPPDeclaration::ST_simple: { CPPSimpleType *simple_type = type->as_simple_type(); - if (simple_type != (CPPSimpleType *)NULL) { + if (simple_type != nullptr) { return (simple_type->_type == CPPSimpleType::T_double); } } @@ -1364,7 +1407,7 @@ is_float(CPPType *type) { case CPPDeclaration::ST_simple: { CPPSimpleType *simple_type = type->as_simple_type(); - if (simple_type != (CPPSimpleType *)NULL) { + if (simple_type != nullptr) { return (simple_type->_type == CPPSimpleType::T_float || simple_type->_type == CPPSimpleType::T_double); @@ -1388,7 +1431,7 @@ is_float(CPPType *type) { bool TypeManager:: is_void(CPPType *type) { CPPSimpleType *simple_type = type->as_simple_type(); - if (simple_type != (CPPSimpleType *)NULL) { + if (simple_type != nullptr) { return simple_type->_type == CPPSimpleType::T_void && simple_type->_flags == 0; @@ -1404,7 +1447,7 @@ is_void(CPPType *type) { bool TypeManager:: is_reference_count(CPPType *type) { CPPType *refcount_type = get_reference_count_type(); - if (refcount_type != (CPPType *)NULL && + if (refcount_type != nullptr && refcount_type->get_local_name(&parser) == type->get_local_name(&parser)) { return true; } @@ -1804,7 +1847,9 @@ bool TypeManager::is_ostream(CPPType *type) { return is_ostream(type->as_const_type()->_wrapped_around); case CPPDeclaration::ST_struct: - return (type->get_local_name(&parser) == "ostream"); + return (type->get_local_name(&parser) == "std::ostream" || + type->get_local_name(&parser) == "ostream" || + type->get_local_name(&parser) == "std::basic_ostream< char >"); case CPPDeclaration::ST_typedef: return is_ostream(type->as_typedef_type()->_type); @@ -1859,7 +1904,7 @@ involves_unpublished(CPPType *type) { case CPPDeclaration::ST_struct: // A struct type is unpublished only if all of its members are // unpublished. - if (type->_declaration != (CPPTypeDeclaration *)NULL) { + if (type->_declaration != nullptr) { if (type->_declaration->_vis <= min_vis) { return false; } @@ -1881,7 +1926,7 @@ involves_unpublished(CPPType *type) { } case CPPDeclaration::ST_function: - if (type->_declaration != (CPPTypeDeclaration *)NULL) { + if (type->_declaration != nullptr) { if (type->_declaration->_vis <= min_vis) { return false; } @@ -1909,7 +1954,7 @@ involves_unpublished(CPPType *type) { return involves_unpublished(type->as_typedef_type()->_type); default: - if (type->_declaration != (CPPTypeDeclaration *)NULL) { + if (type->_declaration != nullptr) { return (type->_declaration->_vis > min_vis); } return false; @@ -1955,7 +2000,7 @@ involves_protected(CPPType *type) { return involves_protected(type->as_typedef_type()->_type); default: - if (type->_declaration != (CPPTypeDeclaration *)NULL) { + if (type->_declaration != nullptr) { return (type->_declaration->_vis > V_public); } return false; @@ -2073,7 +2118,7 @@ get_pointer_type(CPPStructType *pt_type) { ++ii) { CPPInstance *function = (*ii); CPPFunctionType *ftype = function->_type->as_function_type(); - assert(ftype != (CPPFunctionType *)NULL); + assert(ftype != nullptr); if (ftype->_parameters->_parameters.empty()) { // Here's the function p(). What's its return type? return resolve_type(ftype->_return_type); @@ -2081,7 +2126,7 @@ get_pointer_type(CPPStructType *pt_type) { } } - return (CPPType *)NULL; + return nullptr; } /** @@ -2106,15 +2151,15 @@ get_template_parameter_type(CPPType *source_type, int i) { } CPPStructType *type = source_type->as_struct_type(); - if (type == NULL) { - return NULL; + if (type == nullptr) { + return nullptr; } // I'm not sure how reliable this is, but I don't know if there is a more // proper way to access this. CPPTemplateParameterList *templ = type->_ident->_names.back().get_templ(); - if (templ == NULL || i >= (int)templ->_parameters.size()) { - return NULL; + if (templ == nullptr || i >= (int)templ->_parameters.size()) { + return nullptr; } CPPDeclaration *decl = templ->_parameters[i]; @@ -2134,7 +2179,7 @@ wrap_pointer(CPPType *source_type) { */ CPPType *TypeManager:: wrap_const_pointer(CPPType *source_type) { - if (source_type->as_const_type() != (CPPConstType *)NULL) { + if (source_type->as_const_type() != nullptr) { // It's already const. return CPPType::new_type(new CPPPointerType(source_type)); @@ -2149,7 +2194,7 @@ wrap_const_pointer(CPPType *source_type) { */ CPPType *TypeManager:: wrap_const_reference(CPPType *source_type) { - if (source_type->as_const_type() != (CPPConstType *)NULL) { + if (source_type->as_const_type() != nullptr) { // It's already const. return CPPType::new_type(new CPPReferenceType(source_type)); @@ -2166,7 +2211,7 @@ wrap_const_reference(CPPType *source_type) { CPPType *TypeManager:: get_basic_string_char_type() { static bool got_type = false; - static CPPType *type = (CPPType *)NULL; + static CPPType *type = nullptr; if (!got_type) { type = parser.parse_type("std::basic_string"); got_type = true; @@ -2181,7 +2226,7 @@ get_basic_string_char_type() { CPPType *TypeManager:: get_basic_string_wchar_type() { static bool got_type = false; - static CPPType *type = (CPPType *)NULL; + static CPPType *type = nullptr; if (!got_type) { type = parser.parse_type("std::basic_string"); got_type = true; @@ -2196,7 +2241,7 @@ get_basic_string_wchar_type() { CPPType *TypeManager:: get_reference_count_type() { static bool got_type = false; - static CPPType *type = (CPPType *)NULL; + static CPPType *type = nullptr; if (!got_type) { type = parser.parse_type("ReferenceCount"); got_type = true; @@ -2210,7 +2255,7 @@ get_reference_count_type() { CPPType *TypeManager:: get_void_type() { static bool got_type = false; - static CPPType *type = (CPPType *)NULL; + static CPPType *type = nullptr; if (!got_type) { type = CPPType::new_type(new CPPSimpleType(CPPSimpleType::T_void)); got_type = true; @@ -2224,7 +2269,7 @@ get_void_type() { CPPType *TypeManager:: get_int_type() { static bool got_type = false; - static CPPType *type = (CPPType *)NULL; + static CPPType *type = nullptr; if (!got_type) { type = CPPType::new_type(new CPPSimpleType(CPPSimpleType::T_int)); got_type = true; @@ -2246,9 +2291,9 @@ string TypeManager:: get_function_signature(CPPInstance *function, int num_default_parameters) { CPPFunctionType *ftype = function->_type->as_function_type(); - assert(ftype != (CPPFunctionType *)NULL); + assert(ftype != nullptr); - ostringstream out; + std::ostringstream out; // It's tempting to mark static methods with a different function signature // than non-static, because a static method doesn't have an implicit 'this' @@ -2315,7 +2360,7 @@ get_function_name(CPPInstance *function) { bool TypeManager:: has_protected_destructor(CPPType *type) { CPPStructType *struct_type = type->as_struct_type(); - if (struct_type == (CPPStructType *)NULL) { + if (struct_type == nullptr) { // It's not even a struct type! return false; } @@ -2332,7 +2377,7 @@ has_protected_destructor(CPPType *type) { if (inst->_type->get_subtype() == CPPDeclaration::ST_function) { // Here's a function declaration. CPPFunctionType *ftype = inst->_type->as_function_type(); - assert(ftype != (CPPFunctionType *)NULL); + assert(ftype != nullptr); if ((ftype->_flags & CPPFunctionType::F_destructor) != 0) { // Here's the destructor! Is it protected? return (inst->_vis > V_public); diff --git a/dtool/src/interrogate/typeManager.h b/dtool/src/interrogate/typeManager.h index 65f192edf7..f1aa2908b1 100644 --- a/dtool/src/interrogate/typeManager.h +++ b/dtool/src/interrogate/typeManager.h @@ -39,11 +39,12 @@ class CPPManifest; class TypeManager { public: - static CPPType *resolve_type(CPPType *type, CPPScope *scope = (CPPScope *)NULL); + static CPPType *resolve_type(CPPType *type, CPPScope *scope = nullptr); static bool is_assignable(CPPType *type); static bool is_reference(CPPType *type); + static bool is_rvalue_reference(CPPType *type); static bool is_ref_to_anything(CPPType *type); static bool is_const_ref_to_anything(CPPType *type); static bool is_const_pointer_to_anything(CPPType *type); @@ -52,6 +53,7 @@ public: static bool is_pointer(CPPType *type); static bool is_const(CPPType *type); static bool is_struct(CPPType *type); + static bool is_scoped_enum(CPPType *type); static bool is_enum(CPPType *type); static bool is_const_enum(CPPType *type); static bool is_const_ref_to_enum(CPPType *type); @@ -139,10 +141,10 @@ public: static CPPType *get_void_type(); static CPPType *get_int_type(); - static string get_function_signature(CPPInstance *function, + static std::string get_function_signature(CPPInstance *function, int num_default_parameters = 0); - static string get_function_name(CPPInstance *function); + static std::string get_function_name(CPPInstance *function); static bool has_protected_destructor(CPPType *type); diff --git a/dtool/src/interrogatedb/dtool_super_base.cxx b/dtool/src/interrogatedb/dtool_super_base.cxx index 26b57a157d..9170af9d4f 100644 --- a/dtool/src/interrogatedb/dtool_super_base.cxx +++ b/dtool/src/interrogatedb/dtool_super_base.cxx @@ -26,7 +26,7 @@ static PyObject *GetSuperBase(PyObject *self) { PyMethodDef Dtool_Methods_DTOOL_SUPER_BASE[] = { { "DtoolGetSuperBase", (PyCFunction) &GetSuperBase, METH_NOARGS, "Will Return SUPERbase Class"}, - { NULL, NULL } + { nullptr, nullptr, 0, nullptr } }; EXPCL_INTERROGATEDB void Dtool_PyModuleClassInit_DTOOL_SUPER_BASE(PyObject *module) { @@ -46,89 +46,89 @@ EXPCL_INTERROGATEDB void Dtool_PyModuleClassInit_DTOOL_SUPER_BASE(PyObject *modu PyDict_SetItemString(Dtool_DTOOL_SUPER_BASE._PyType.tp_dict, "DtoolGetSuperBase", PyCFunction_New(&Dtool_Methods_DTOOL_SUPER_BASE[0], (PyObject *)&Dtool_DTOOL_SUPER_BASE)); } - if (module != NULL) { + if (module != nullptr) { Py_INCREF((PyTypeObject *)&Dtool_DTOOL_SUPER_BASE); PyModule_AddObject(module, "DTOOL_SUPER_BASE", (PyObject *)&Dtool_DTOOL_SUPER_BASE); } } inline void *Dtool_DowncastInterface_DTOOL_SUPER_BASE(void *from_this, Dtool_PyTypedObject *from_type) { - return (void *) NULL; + return nullptr; } inline void *Dtool_UpcastInterface_DTOOL_SUPER_BASE(PyObject *self, Dtool_PyTypedObject *requested_type) { - return NULL; + return nullptr; } int Dtool_Init_DTOOL_SUPER_BASE(PyObject *self, PyObject *args, PyObject *kwds) { - assert(self != NULL); + assert(self != nullptr); PyErr_Format(PyExc_TypeError, "cannot init constant class %s", Py_TYPE(self)->tp_name); return -1; } EXPORT_THIS Dtool_PyTypedObject Dtool_DTOOL_SUPER_BASE = { { - PyVarObject_HEAD_INIT(NULL, 0) + PyVarObject_HEAD_INIT(nullptr, 0) "dtoolconfig.DTOOL_SUPER_BASE", sizeof(Dtool_PyInstDef), - 0, + 0, // tp_itemsize &Dtool_FreeInstance_DTOOL_SUPER_BASE, - 0, - 0, - 0, + nullptr, // tp_print + nullptr, // tp_getattr + nullptr, // tp_setattr #if PY_MAJOR_VERSION >= 3 - 0, + nullptr, // tp_compare #else - &DTOOL_PyObject_ComparePointers, + &DtoolInstance_ComparePointers, #endif - 0, - 0, - 0, - 0, - &DTOOL_PyObject_HashPointer, - 0, - 0, + nullptr, // tp_repr + nullptr, // tp_as_number + nullptr, // tp_as_sequence + nullptr, // tp_as_mapping + &DtoolInstance_HashPointer, + nullptr, // tp_call + nullptr, // tp_str PyObject_GenericGetAttr, PyObject_GenericSetAttr, - 0, + nullptr, // tp_as_buffer (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_CHECKTYPES), - 0, - 0, - 0, + nullptr, // tp_doc + nullptr, // tp_traverse + nullptr, // tp_clear #if PY_MAJOR_VERSION >= 3 - &DTOOL_PyObject_RichCompare, + &DtoolInstance_RichComparePointers, #else - 0, + nullptr, // tp_richcompare #endif - 0, - 0, - 0, + 0, // tp_weaklistoffset + nullptr, // tp_iter + nullptr, // tp_iternext Dtool_Methods_DTOOL_SUPER_BASE, standard_type_members, - 0, - 0, - 0, - 0, - 0, - 0, + nullptr, // tp_getset + nullptr, // tp_base + nullptr, // tp_dict + nullptr, // tp_descr_get + nullptr, // tp_descr_set + 0, // tp_dictoffset Dtool_Init_DTOOL_SUPER_BASE, PyType_GenericAlloc, Dtool_new_DTOOL_SUPER_BASE, PyObject_Del, - 0, - 0, - 0, - 0, - 0, - 0, - 0, + nullptr, // tp_is_gc + nullptr, // tp_bases + nullptr, // tp_mro + nullptr, // tp_cache + nullptr, // tp_subclasses + nullptr, // tp_weaklist + nullptr, // tp_del }, TypeHandle::none(), Dtool_PyModuleClassInit_DTOOL_SUPER_BASE, Dtool_UpcastInterface_DTOOL_SUPER_BASE, Dtool_DowncastInterface_DTOOL_SUPER_BASE, - NULL, - NULL, + nullptr, + nullptr, }; #endif // HAVE_PYTHON diff --git a/dtool/src/interrogatedb/indexRemapper.cxx b/dtool/src/interrogatedb/indexRemapper.cxx index eee236cf08..7c606bec06 100644 --- a/dtool/src/interrogatedb/indexRemapper.cxx +++ b/dtool/src/interrogatedb/indexRemapper.cxx @@ -59,7 +59,7 @@ in_map(int from) const { */ int IndexRemapper:: map_from(int from) const { - map::const_iterator mi; + std::map::const_iterator mi; mi = _map_int.find(from); if (mi == _map_int.end()) { return from; diff --git a/dtool/src/interrogatedb/indexRemapper.h b/dtool/src/interrogatedb/indexRemapper.h index 9318777c94..c89a7a2988 100644 --- a/dtool/src/interrogatedb/indexRemapper.h +++ b/dtool/src/interrogatedb/indexRemapper.h @@ -38,7 +38,7 @@ public: int map_from(int from) const; private: - map _map_int; + std::map _map_int; }; #endif diff --git a/dtool/src/interrogatedb/interrogateComponent.I b/dtool/src/interrogatedb/interrogateComponent.I index 4617eee858..dddbb421fb 100644 --- a/dtool/src/interrogatedb/interrogateComponent.I +++ b/dtool/src/interrogatedb/interrogateComponent.I @@ -46,7 +46,7 @@ operator = (const InterrogateComponent ©) { INLINE bool InterrogateComponent:: has_library_name() const { const char *name = get_library_name(); - return (name != (const char *)NULL && name[0] != '\0'); + return (name != nullptr && name[0] != '\0'); } /** @@ -57,10 +57,10 @@ has_library_name() const { */ INLINE const char *InterrogateComponent:: get_library_name() const { - if (_def != (InterrogateModuleDef *)NULL) { + if (_def != nullptr) { return _def->library_name; } - return (const char *)NULL; + return nullptr; } /** @@ -70,7 +70,7 @@ get_library_name() const { INLINE bool InterrogateComponent:: has_module_name() const { const char *name = get_module_name(); - return (name != (const char *)NULL && name[0] != '\0'); + return (name != nullptr && name[0] != '\0'); } /** @@ -81,10 +81,10 @@ has_module_name() const { */ INLINE const char *InterrogateComponent:: get_module_name() const { - if (_def != (InterrogateModuleDef *)NULL) { + if (_def != nullptr) { return _def->module_name; } - return (const char *)NULL; + return nullptr; } /** @@ -98,7 +98,7 @@ has_name() const { /** * */ -INLINE const string &InterrogateComponent:: +INLINE const std::string &InterrogateComponent:: get_name() const { return _name; } @@ -114,7 +114,7 @@ get_num_alt_names() const { /** * */ -INLINE const string &InterrogateComponent:: +INLINE const std::string &InterrogateComponent:: get_alt_name(int n) const { if (n >= 0 && n < (int)_alt_names.size()) { return _alt_names[n]; diff --git a/dtool/src/interrogatedb/interrogateComponent.cxx b/dtool/src/interrogatedb/interrogateComponent.cxx index c5a8e15df0..61398f686f 100644 --- a/dtool/src/interrogatedb/interrogateComponent.cxx +++ b/dtool/src/interrogatedb/interrogateComponent.cxx @@ -16,13 +16,13 @@ // This static string is just kept around as a handy bogus return value for // functions that must return a const string reference. -string InterrogateComponent::_empty_string; +std::string InterrogateComponent::_empty_string; /** * Formats the component for output to a data file. */ void InterrogateComponent:: -output(ostream &out) const { +output(std::ostream &out) const { idf_output_string(out, _name); out << _alt_names.size() << " "; @@ -36,14 +36,14 @@ output(ostream &out) const { * Reads the data file as previously formatted by output(). */ void InterrogateComponent:: -input(istream &in) { +input(std::istream &in) { idf_input_string(in, _name); int num_alt_names; in >> num_alt_names; _alt_names.reserve(num_alt_names); for (int i = 0; i < num_alt_names; ++i) { - string alt_name; + std::string alt_name; idf_input_string(in, alt_name); _alt_names.push_back(alt_name); } diff --git a/dtool/src/interrogatedb/interrogateComponent.h b/dtool/src/interrogatedb/interrogateComponent.h index c69dc26886..2555769756 100644 --- a/dtool/src/interrogatedb/interrogateComponent.h +++ b/dtool/src/interrogatedb/interrogateComponent.h @@ -29,7 +29,7 @@ class IndexRemapper; */ class EXPCL_INTERROGATEDB InterrogateComponent { public: - INLINE InterrogateComponent(InterrogateModuleDef *def = NULL); + INLINE InterrogateComponent(InterrogateModuleDef *def = nullptr); INLINE InterrogateComponent(const InterrogateComponent ©); INLINE void operator = (const InterrogateComponent ©); @@ -40,22 +40,22 @@ public: INLINE const char *get_module_name() const; INLINE bool has_name() const; - INLINE const string &get_name() const; + INLINE const std::string &get_name() const; INLINE int get_num_alt_names() const; - INLINE const string &get_alt_name(int n) const; + INLINE const std::string &get_alt_name(int n) const; - void output(ostream &out) const; - void input(istream &in); + void output(std::ostream &out) const; + void input(std::istream &in); protected: - static string _empty_string; + static std::string _empty_string; private: InterrogateModuleDef *_def; - string _name; + std::string _name; - typedef vector Strings; + typedef std::vector Strings; Strings _alt_names; friend class InterrogateBuilder; diff --git a/dtool/src/interrogatedb/interrogateDatabase.I b/dtool/src/interrogatedb/interrogateDatabase.I index 91493a1772..cf15d962bf 100644 --- a/dtool/src/interrogatedb/interrogateDatabase.I +++ b/dtool/src/interrogatedb/interrogateDatabase.I @@ -27,7 +27,7 @@ check_latest() { * name, or 0 if no type has this name. */ INLINE TypeIndex InterrogateDatabase:: -lookup_type_by_name(const string &name) { +lookup_type_by_name(const std::string &name) { check_latest(); return lookup(name, _types_by_name, LT_type_name, &InterrogateDatabase::freshen_types_by_name); @@ -38,7 +38,7 @@ lookup_type_by_name(const string &name) { * scoped name, or 0 if no type has this name. */ INLINE TypeIndex InterrogateDatabase:: -lookup_type_by_scoped_name(const string &name) { +lookup_type_by_scoped_name(const std::string &name) { check_latest(); return lookup(name, _types_by_scoped_name, LT_type_scoped_name, &InterrogateDatabase::freshen_types_by_scoped_name); @@ -49,7 +49,7 @@ lookup_type_by_scoped_name(const string &name) { * true name, or 0 if no type has this name. */ INLINE TypeIndex InterrogateDatabase:: -lookup_type_by_true_name(const string &name) { +lookup_type_by_true_name(const std::string &name) { check_latest(); return lookup(name, _types_by_true_name, LT_type_true_name, &InterrogateDatabase::freshen_types_by_true_name); @@ -60,7 +60,7 @@ lookup_type_by_true_name(const string &name) { * given name, or 0 if no manifest has this name. */ INLINE ManifestIndex InterrogateDatabase:: -lookup_manifest_by_name(const string &name) { +lookup_manifest_by_name(const std::string &name) { check_latest(); return lookup(name, _manifests_by_name, LT_manifest_name, &InterrogateDatabase::freshen_manifests_by_name); @@ -71,7 +71,7 @@ lookup_manifest_by_name(const string &name) { * given name, or 0 if no element has this name. */ INLINE ElementIndex InterrogateDatabase:: -lookup_element_by_name(const string &name) { +lookup_element_by_name(const std::string &name) { check_latest(); return lookup(name, _elements_by_name, LT_element_name, &InterrogateDatabase::freshen_elements_by_name); @@ -82,7 +82,7 @@ lookup_element_by_name(const string &name) { * given scoped name, or 0 if no element has this name. */ INLINE ElementIndex InterrogateDatabase:: -lookup_element_by_scoped_name(const string &name) { +lookup_element_by_scoped_name(const std::string &name) { check_latest(); return lookup(name, _elements_by_scoped_name, LT_element_scoped_name, &InterrogateDatabase::freshen_elements_by_scoped_name); diff --git a/dtool/src/interrogatedb/interrogateDatabase.cxx b/dtool/src/interrogatedb/interrogateDatabase.cxx index c11675d352..a8e7b37a6c 100644 --- a/dtool/src/interrogatedb/interrogateDatabase.cxx +++ b/dtool/src/interrogatedb/interrogateDatabase.cxx @@ -16,7 +16,10 @@ #include "indexRemapper.h" #include "interrogate_datafile.h" -InterrogateDatabase *InterrogateDatabase::_global_ptr = NULL; +using std::map; +using std::string; + +InterrogateDatabase *InterrogateDatabase::_global_ptr = nullptr; int InterrogateDatabase::_file_major_version = 0; int InterrogateDatabase::_file_minor_version = 0; int InterrogateDatabase::_current_major_version = 3; @@ -37,7 +40,7 @@ InterrogateDatabase() { */ InterrogateDatabase *InterrogateDatabase:: get_ptr() { - if (_global_ptr == (InterrogateDatabase *)NULL) { + if (_global_ptr == nullptr) { if (interrogatedb_cat->is_debug()) { interrogatedb_cat->debug() << "Creating interrogate database\n"; @@ -56,7 +59,7 @@ get_ptr() { void InterrogateDatabase:: request_module(InterrogateModuleDef *def) { if (interrogatedb_cat->is_debug()) { - if (def->library_name == (const char *)NULL) { + if (def->library_name == nullptr) { interrogatedb_cat->debug() << "Got interrogate data for anonymous module\n"; } else { @@ -78,13 +81,13 @@ request_module(InterrogateModuleDef *def) { _modules.push_back(def); } - if (def->num_unique_names > 0 && def->library_name != (const char *)NULL) { + if (def->num_unique_names > 0 && def->library_name != nullptr) { // Define a lookup by hash for this module, mainly so we can look up // functions by their unique names. _modules_by_hash[def->library_hash_name] = def; } - if (def->database_filename != (const char *)NULL) { + if (def->database_filename != nullptr) { _requests.push_back(def); } } @@ -361,7 +364,7 @@ get_fptr(FunctionWrapperIndex wrapper) { return def->fptrs[module_index]; } } - return (void *)NULL; + return nullptr; } /** @@ -734,7 +737,7 @@ remap_indices(int first_index, IndexRemapper &remap) { * Writes the database to the indicated stream for later reading. */ void InterrogateDatabase:: -write(ostream &out, InterrogateModuleDef *def) const { +write(std::ostream &out, InterrogateModuleDef *def) const { // Write out the file header. out << def->file_identifier << "\n" << _current_major_version << " " << _current_minor_version << "\n"; @@ -793,7 +796,7 @@ write(ostream &out, InterrogateModuleDef *def) const { * Returns true if the file is read successfully, false if there is an error. */ bool InterrogateDatabase:: -read(istream &in, InterrogateModuleDef *def) { +read(std::istream &in, InterrogateModuleDef *def) { InterrogateDatabase temp; if (!temp.read_new(in, def)) { return false; @@ -830,7 +833,7 @@ load_latest() { for (ri = copy_requests.begin(); ri != copy_requests.end(); ++ri) { InterrogateModuleDef *def = (*ri); - if (def->database_filename != (char *)NULL) { + if (def->database_filename != nullptr) { Filename filename = def->database_filename; Filename pathname = filename; if (!pathname.empty() && pathname[0] != '/') { @@ -899,7 +902,7 @@ load_latest() { * already has some data in it. */ bool InterrogateDatabase:: -read_new(istream &in, InterrogateModuleDef *def) { +read_new(std::istream &in, InterrogateModuleDef *def) { // We've already read the header. Read the module definition. idf_input_string(in, def->library_name); idf_input_string(in, def->library_hash_name); diff --git a/dtool/src/interrogatedb/interrogateDatabase.h b/dtool/src/interrogatedb/interrogateDatabase.h index 84fc55fbab..9c60b0318e 100644 --- a/dtool/src/interrogatedb/interrogateDatabase.h +++ b/dtool/src/interrogatedb/interrogateDatabase.h @@ -65,18 +65,18 @@ public: const InterrogateElement &get_element(ElementIndex element); const InterrogateMakeSeq &get_make_seq(MakeSeqIndex element); - INLINE TypeIndex lookup_type_by_name(const string &name); - INLINE TypeIndex lookup_type_by_scoped_name(const string &name); - INLINE TypeIndex lookup_type_by_true_name(const string &name); - INLINE ManifestIndex lookup_manifest_by_name(const string &name); - INLINE ElementIndex lookup_element_by_name(const string &name); - INLINE ElementIndex lookup_element_by_scoped_name(const string &name); + INLINE TypeIndex lookup_type_by_name(const std::string &name); + INLINE TypeIndex lookup_type_by_scoped_name(const std::string &name); + INLINE TypeIndex lookup_type_by_true_name(const std::string &name); + INLINE ManifestIndex lookup_manifest_by_name(const std::string &name); + INLINE ElementIndex lookup_element_by_name(const std::string &name); + INLINE ElementIndex lookup_element_by_scoped_name(const std::string &name); void remove_type(TypeIndex type); void *get_fptr(FunctionWrapperIndex wrapper); - FunctionWrapperIndex get_wrapper_by_unique_name(const string &unique_name); + FunctionWrapperIndex get_wrapper_by_unique_name(const std::string &unique_name); static int get_file_major_version(); static int get_file_minor_version(); @@ -106,14 +106,14 @@ public: int remap_indices(int first_index); int remap_indices(int first_index, IndexRemapper &remap); - void write(ostream &out, InterrogateModuleDef *def) const; - bool read(istream &in, InterrogateModuleDef *def); + void write(std::ostream &out, InterrogateModuleDef *def) const; + bool read(std::istream &in, InterrogateModuleDef *def); private: INLINE void check_latest(); void load_latest(); - bool read_new(istream &in, InterrogateModuleDef *def); + bool read_new(std::istream &in, InterrogateModuleDef *def); void merge_from(const InterrogateDatabase &other); bool find_module(FunctionWrapperIndex wrapper, @@ -121,44 +121,44 @@ private: int binary_search_module(int begin, int end, FunctionIndex function); int binary_search_wrapper_hash(InterrogateUniqueNameDef *begin, InterrogateUniqueNameDef *end, - const string &wrapper_hash_name); + const std::string &wrapper_hash_name); // This data is loaded from the various database files. - typedef map TypeMap; + typedef std::map TypeMap; TypeMap _type_map; - typedef map FunctionMap; + typedef std::map FunctionMap; FunctionMap _function_map; - typedef map FunctionWrapperMap; + typedef std::map FunctionWrapperMap; FunctionWrapperMap _wrapper_map; - typedef map ManifestMap; + typedef std::map ManifestMap; ManifestMap _manifest_map; - typedef map ElementMap; + typedef std::map ElementMap; ElementMap _element_map; - typedef map MakeSeqMap; + typedef std::map MakeSeqMap; MakeSeqMap _make_seq_map; - typedef vector GlobalTypes; + typedef std::vector GlobalTypes; GlobalTypes _global_types; GlobalTypes _all_types; - typedef vector GlobalFunctions; + typedef std::vector GlobalFunctions; GlobalFunctions _global_functions; GlobalFunctions _all_functions; - typedef vector GlobalManifests; + typedef std::vector GlobalManifests; GlobalManifests _global_manifests; - typedef vector GlobalElements; + typedef std::vector GlobalElements; GlobalElements _global_elements; // This data is compiled in directly to the shared libraries that we link // with. - typedef vector Modules; + typedef std::vector Modules; Modules _modules; - typedef map ModulesByHash; + typedef std::map ModulesByHash; ModulesByHash _modules_by_hash; // This records the set of database files that are still to be loaded. - typedef vector Requests; + typedef std::vector Requests; Requests _requests; bool _error_flag; @@ -174,7 +174,7 @@ private: }; int _lookups_fresh; - typedef map Lookup; + typedef std::map Lookup; Lookup _types_by_name; Lookup _types_by_scoped_name; Lookup _types_by_true_name; @@ -189,7 +189,7 @@ private: void freshen_elements_by_name(); void freshen_elements_by_scoped_name(); - int lookup(const string &name, + int lookup(const std::string &name, Lookup &lookup, LookupType type, void (InterrogateDatabase::*freshen)()); diff --git a/dtool/src/interrogatedb/interrogateElement.I b/dtool/src/interrogatedb/interrogateElement.I index 914aba2327..93e6889b16 100644 --- a/dtool/src/interrogatedb/interrogateElement.I +++ b/dtool/src/interrogatedb/interrogateElement.I @@ -80,7 +80,7 @@ has_scoped_name() const { /** * */ -INLINE const string &InterrogateElement:: +INLINE const std::string &InterrogateElement:: get_scoped_name() const { return _scoped_name; } @@ -96,7 +96,7 @@ has_comment() const { /** * */ -INLINE const string &InterrogateElement:: +INLINE const std::string &InterrogateElement:: get_comment() const { return _comment; } @@ -246,14 +246,14 @@ is_mapping() const { } -INLINE ostream & -operator << (ostream &out, const InterrogateElement &element) { +INLINE std::ostream & +operator << (std::ostream &out, const InterrogateElement &element) { element.output(out); return out; } -INLINE istream & -operator >> (istream &in, InterrogateElement &element) { +INLINE std::istream & +operator >> (std::istream &in, InterrogateElement &element) { element.input(in); return in; } diff --git a/dtool/src/interrogatedb/interrogateElement.cxx b/dtool/src/interrogatedb/interrogateElement.cxx index 38c7c8f4ec..4b6b3d948f 100644 --- a/dtool/src/interrogatedb/interrogateElement.cxx +++ b/dtool/src/interrogatedb/interrogateElement.cxx @@ -20,7 +20,7 @@ * Formats the InterrogateElement data for output to a data file. */ void InterrogateElement:: -output(ostream &out) const { +output(std::ostream &out) const { InterrogateComponent::output(out); out << _flags << " " << _type << " " @@ -40,7 +40,7 @@ output(ostream &out) const { * Reads the data file as previously formatted by output(). */ void InterrogateElement:: -input(istream &in) { +input(std::istream &in) { InterrogateComponent::input(in); in >> _flags >> _type >> _getter >> _setter; if (InterrogateDatabase::get_file_minor_version() >= 1) { diff --git a/dtool/src/interrogatedb/interrogateElement.h b/dtool/src/interrogatedb/interrogateElement.h index f824b760cf..e3d55569f0 100644 --- a/dtool/src/interrogatedb/interrogateElement.h +++ b/dtool/src/interrogatedb/interrogateElement.h @@ -27,17 +27,17 @@ class CPPMakeProperty; */ class EXPCL_INTERROGATEDB InterrogateElement : public InterrogateComponent { public: - INLINE InterrogateElement(InterrogateModuleDef *def = NULL); + INLINE InterrogateElement(InterrogateModuleDef *def = nullptr); INLINE InterrogateElement(const InterrogateElement ©); INLINE void operator = (const InterrogateElement ©); INLINE bool is_global() const; INLINE bool has_scoped_name() const; - INLINE const string &get_scoped_name() const; + INLINE const std::string &get_scoped_name() const; INLINE bool has_comment() const; - INLINE const string &get_comment() const; + INLINE const std::string &get_comment() const; INLINE TypeIndex get_type() const; INLINE bool has_getter() const; @@ -58,8 +58,8 @@ public: INLINE FunctionIndex get_length_function() const; INLINE bool is_mapping() const; - void output(ostream &out) const; - void input(istream &in); + void output(std::ostream &out) const; + void input(std::istream &in); void remap_indices(const IndexRemapper &remap); @@ -78,8 +78,8 @@ private: }; int _flags; - string _scoped_name; - string _comment; + std::string _scoped_name; + std::string _comment; TypeIndex _type; FunctionIndex _length_function; FunctionIndex _getter; @@ -95,8 +95,8 @@ private: friend class InterrogateBuilder; }; -INLINE ostream &operator << (ostream &out, const InterrogateElement &element); -INLINE istream &operator >> (istream &in, InterrogateElement &element); +INLINE std::ostream &operator << (std::ostream &out, const InterrogateElement &element); +INLINE std::istream &operator >> (std::istream &in, InterrogateElement &element); #include "interrogateElement.I" diff --git a/dtool/src/interrogatedb/interrogateFunction.I b/dtool/src/interrogatedb/interrogateFunction.I index c394c8ac6f..3834e60782 100644 --- a/dtool/src/interrogatedb/interrogateFunction.I +++ b/dtool/src/interrogatedb/interrogateFunction.I @@ -73,7 +73,7 @@ has_scoped_name() const { /** * */ -INLINE const string &InterrogateFunction:: +INLINE const std::string &InterrogateFunction:: get_scoped_name() const { return _scoped_name; } @@ -89,7 +89,7 @@ has_comment() const { /** * */ -INLINE const string &InterrogateFunction:: +INLINE const std::string &InterrogateFunction:: get_comment() const { return _comment; } @@ -105,7 +105,7 @@ has_prototype() const { /** * */ -INLINE const string &InterrogateFunction:: +INLINE const std::string &InterrogateFunction:: get_prototype() const { return _prototype; } @@ -149,14 +149,14 @@ get_python_wrapper(int n) const { } -INLINE ostream & -operator << (ostream &out, const InterrogateFunction &function) { +INLINE std::ostream & +operator << (std::ostream &out, const InterrogateFunction &function) { function.output(out); return out; } -INLINE istream & -operator >> (istream &in, InterrogateFunction &function) { +INLINE std::istream & +operator >> (std::istream &in, InterrogateFunction &function) { function.input(in); return in; } diff --git a/dtool/src/interrogatedb/interrogateFunction.cxx b/dtool/src/interrogatedb/interrogateFunction.cxx index 6510f86fc9..db70cc0b9c 100644 --- a/dtool/src/interrogatedb/interrogateFunction.cxx +++ b/dtool/src/interrogatedb/interrogateFunction.cxx @@ -25,7 +25,7 @@ InterrogateFunction(InterrogateModuleDef *def) : { _flags = 0; _class = 0; - _instances = (Instances *)NULL; + _instances = nullptr; } /** @@ -58,7 +58,7 @@ operator = (const InterrogateFunction ©) { * Formats the InterrogateFunction data for output to a data file. */ void InterrogateFunction:: -output(ostream &out) const { +output(std::ostream &out) const { InterrogateComponent::output(out); out << _flags << " " << _class << " "; @@ -73,7 +73,7 @@ output(ostream &out) const { * Reads the data file as previously formatted by output(). */ void InterrogateFunction:: -input(istream &in) { +input(std::istream &in) { InterrogateComponent::input(in); in >> _flags >> _class; idf_input_string(in, _scoped_name); diff --git a/dtool/src/interrogatedb/interrogateFunction.h b/dtool/src/interrogatedb/interrogateFunction.h index 312f69a97e..1e3a251032 100644 --- a/dtool/src/interrogatedb/interrogateFunction.h +++ b/dtool/src/interrogatedb/interrogateFunction.h @@ -29,7 +29,7 @@ class CPPInstance; */ class EXPCL_INTERROGATEDB InterrogateFunction : public InterrogateComponent { public: - InterrogateFunction(InterrogateModuleDef *def = NULL); + InterrogateFunction(InterrogateModuleDef *def = nullptr); InterrogateFunction(const InterrogateFunction ©); void operator = (const InterrogateFunction ©); @@ -41,13 +41,13 @@ public: INLINE TypeIndex get_class() const; INLINE bool has_scoped_name() const; - INLINE const string &get_scoped_name() const; + INLINE const std::string &get_scoped_name() const; INLINE bool has_comment() const; - INLINE const string &get_comment() const; + INLINE const std::string &get_comment() const; INLINE bool has_prototype() const; - INLINE const string &get_prototype() const; + INLINE const std::string &get_prototype() const; INLINE int number_of_c_wrappers() const; INLINE FunctionWrapperIndex get_c_wrapper(int n) const; @@ -55,8 +55,8 @@ public: INLINE int number_of_python_wrappers() const; INLINE FunctionWrapperIndex get_python_wrapper(int n) const; - void output(ostream &out) const; - void input(istream &in); + void output(std::ostream &out) const; + void input(std::istream &in); void remap_indices(const IndexRemapper &remap); @@ -73,12 +73,12 @@ private: }; int _flags; - string _scoped_name; - string _comment; - string _prototype; + std::string _scoped_name; + std::string _comment; + std::string _prototype; TypeIndex _class; - typedef vector Wrappers; + typedef std::vector Wrappers; Wrappers _c_wrappers; Wrappers _python_wrappers; @@ -92,9 +92,9 @@ public: // This must be a pointer, rather than a concrete map, so we don't risk // trying to create a map in one DLL and access it in another. Silly // Windows. - typedef map Instances; + typedef std::map Instances; Instances *_instances; - string _expression; + std::string _expression; friend class InterrogateBuilder; friend class InterfaceMakerC; @@ -103,8 +103,8 @@ public: friend class FunctionRemap; }; -INLINE ostream &operator << (ostream &out, const InterrogateFunction &function); -INLINE istream &operator >> (istream &in, InterrogateFunction &function); +INLINE std::ostream &operator << (std::ostream &out, const InterrogateFunction &function); +INLINE std::istream &operator >> (std::istream &in, InterrogateFunction &function); #include "interrogateFunction.I" diff --git a/dtool/src/interrogatedb/interrogateFunctionWrapper.I b/dtool/src/interrogatedb/interrogateFunctionWrapper.I index 955800e5c1..d636e32ebf 100644 --- a/dtool/src/interrogatedb/interrogateFunctionWrapper.I +++ b/dtool/src/interrogatedb/interrogateFunctionWrapper.I @@ -128,9 +128,9 @@ parameter_has_name(int n) const { /** * */ -INLINE const string &InterrogateFunctionWrapper:: +INLINE const std::string &InterrogateFunctionWrapper:: parameter_get_name(int n) const { - static string bogus_string; + static std::string bogus_string; if (n >= 0 && n < (int)_parameters.size()) { return _parameters[n]._name; } @@ -151,7 +151,7 @@ parameter_is_this(int n) const { /** * */ -INLINE const string &InterrogateFunctionWrapper:: +INLINE const std::string &InterrogateFunctionWrapper:: get_unique_name() const { return _unique_name; } @@ -167,31 +167,31 @@ has_comment() const { /** * */ -INLINE const string &InterrogateFunctionWrapper:: +INLINE const std::string &InterrogateFunctionWrapper:: get_comment() const { return _comment; } -INLINE ostream & -operator << (ostream &out, const InterrogateFunctionWrapper &wrapper) { +INLINE std::ostream & +operator << (std::ostream &out, const InterrogateFunctionWrapper &wrapper) { wrapper.output(out); return out; } -INLINE istream & -operator >> (istream &in, InterrogateFunctionWrapper &wrapper) { +INLINE std::istream & +operator >> (std::istream &in, InterrogateFunctionWrapper &wrapper) { wrapper.input(in); return in; } -INLINE ostream & -operator << (ostream &out, const InterrogateFunctionWrapper::Parameter &p) { +INLINE std::ostream & +operator << (std::ostream &out, const InterrogateFunctionWrapper::Parameter &p) { p.output(out); return out; } -INLINE istream & -operator >> (istream &in, InterrogateFunctionWrapper::Parameter &p) { +INLINE std::istream & +operator >> (std::istream &in, InterrogateFunctionWrapper::Parameter &p) { p.input(in); return in; } diff --git a/dtool/src/interrogatedb/interrogateFunctionWrapper.cxx b/dtool/src/interrogatedb/interrogateFunctionWrapper.cxx index 3cb143a2f3..9cad10ef4e 100644 --- a/dtool/src/interrogatedb/interrogateFunctionWrapper.cxx +++ b/dtool/src/interrogatedb/interrogateFunctionWrapper.cxx @@ -17,6 +17,9 @@ #include +using std::istream; +using std::ostream; + /** * */ diff --git a/dtool/src/interrogatedb/interrogateFunctionWrapper.h b/dtool/src/interrogatedb/interrogateFunctionWrapper.h index 511e8c6263..43b01a9a79 100644 --- a/dtool/src/interrogatedb/interrogateFunctionWrapper.h +++ b/dtool/src/interrogatedb/interrogateFunctionWrapper.h @@ -27,7 +27,7 @@ class IndexRemapper; */ class EXPCL_INTERROGATEDB InterrogateFunctionWrapper : public InterrogateComponent { public: - INLINE InterrogateFunctionWrapper(InterrogateModuleDef *def = NULL); + INLINE InterrogateFunctionWrapper(InterrogateModuleDef *def = nullptr); INLINE InterrogateFunctionWrapper(const InterrogateFunctionWrapper ©); INLINE void operator = (const InterrogateFunctionWrapper ©); @@ -43,16 +43,16 @@ public: INLINE int number_of_parameters() const; INLINE TypeIndex parameter_get_type(int n) const; INLINE bool parameter_has_name(int n) const; - INLINE const string ¶meter_get_name(int n) const; + INLINE const std::string ¶meter_get_name(int n) const; INLINE bool parameter_is_this(int n) const; - INLINE const string &get_unique_name() const; + INLINE const std::string &get_unique_name() const; INLINE bool has_comment() const; - INLINE const string &get_comment() const; + INLINE const std::string &get_comment() const; - void output(ostream &out) const; - void input(istream &in); + void output(std::ostream &out) const; + void input(std::istream &in); void remap_indices(const IndexRemapper &remap); @@ -72,8 +72,8 @@ private: FunctionIndex _function; TypeIndex _return_type; FunctionIndex _return_value_destructor; - string _unique_name; - string _comment; + std::string _unique_name; + std::string _comment; public: // This nested class must be declared public just so we can declare the @@ -81,27 +81,27 @@ public: // Arguably a compiler bug, but what can you do. class Parameter { public: - void output(ostream &out) const; - void input(istream &in); + void output(std::ostream &out) const; + void input(std::istream &in); int _parameter_flags; TypeIndex _type; - string _name; + std::string _name; }; private: - typedef vector Parameters; + typedef std::vector Parameters; Parameters _parameters; friend class InterrogateBuilder; friend class FunctionRemap; }; -INLINE ostream &operator << (ostream &out, const InterrogateFunctionWrapper &wrapper); -INLINE istream &operator >> (istream &in, InterrogateFunctionWrapper &wrapper); +INLINE std::ostream &operator << (std::ostream &out, const InterrogateFunctionWrapper &wrapper); +INLINE std::istream &operator >> (std::istream &in, InterrogateFunctionWrapper &wrapper); -INLINE ostream &operator << (ostream &out, const InterrogateFunctionWrapper::Parameter &p); -INLINE istream &operator >> (istream &in, InterrogateFunctionWrapper::Parameter &p); +INLINE std::ostream &operator << (std::ostream &out, const InterrogateFunctionWrapper::Parameter &p); +INLINE std::istream &operator >> (std::istream &in, InterrogateFunctionWrapper::Parameter &p); #include "interrogateFunctionWrapper.I" diff --git a/dtool/src/interrogatedb/interrogateMakeSeq.I b/dtool/src/interrogatedb/interrogateMakeSeq.I index dde5247912..82e01761ea 100644 --- a/dtool/src/interrogatedb/interrogateMakeSeq.I +++ b/dtool/src/interrogatedb/interrogateMakeSeq.I @@ -53,7 +53,7 @@ has_scoped_name() const { /** * */ -INLINE const string &InterrogateMakeSeq:: +INLINE const std::string &InterrogateMakeSeq:: get_scoped_name() const { return _scoped_name; } @@ -69,7 +69,7 @@ has_comment() const { /** * */ -INLINE const string &InterrogateMakeSeq:: +INLINE const std::string &InterrogateMakeSeq:: get_comment() const { return _comment; } @@ -90,14 +90,14 @@ get_element_getter() const { return _element_getter; } -INLINE ostream & -operator << (ostream &out, const InterrogateMakeSeq &make_seq) { +INLINE std::ostream & +operator << (std::ostream &out, const InterrogateMakeSeq &make_seq) { make_seq.output(out); return out; } -INLINE istream & -operator >> (istream &in, InterrogateMakeSeq &make_seq) { +INLINE std::istream & +operator >> (std::istream &in, InterrogateMakeSeq &make_seq) { make_seq.input(in); return in; } diff --git a/dtool/src/interrogatedb/interrogateMakeSeq.cxx b/dtool/src/interrogatedb/interrogateMakeSeq.cxx index 68f3f5999e..d875a91809 100644 --- a/dtool/src/interrogatedb/interrogateMakeSeq.cxx +++ b/dtool/src/interrogatedb/interrogateMakeSeq.cxx @@ -19,7 +19,7 @@ * Formats the InterrogateMakeSeq data for output to a data file. */ void InterrogateMakeSeq:: -output(ostream &out) const { +output(std::ostream &out) const { InterrogateComponent::output(out); out << _length_getter << " " << _element_getter << " "; @@ -31,7 +31,7 @@ output(ostream &out) const { * Reads the data file as previously formatted by output(). */ void InterrogateMakeSeq:: -input(istream &in) { +input(std::istream &in) { InterrogateComponent::input(in); in >> _length_getter >> _element_getter; diff --git a/dtool/src/interrogatedb/interrogateMakeSeq.h b/dtool/src/interrogatedb/interrogateMakeSeq.h index 6883e81126..5d6e1858b2 100644 --- a/dtool/src/interrogatedb/interrogateMakeSeq.h +++ b/dtool/src/interrogatedb/interrogateMakeSeq.h @@ -25,35 +25,35 @@ class IndexRemapper; */ class EXPCL_INTERROGATEDB InterrogateMakeSeq : public InterrogateComponent { public: - INLINE InterrogateMakeSeq(InterrogateModuleDef *def = NULL); + INLINE InterrogateMakeSeq(InterrogateModuleDef *def = nullptr); INLINE InterrogateMakeSeq(const InterrogateMakeSeq ©); INLINE void operator = (const InterrogateMakeSeq ©); INLINE bool has_scoped_name() const; - INLINE const string &get_scoped_name() const; + INLINE const std::string &get_scoped_name() const; INLINE bool has_comment() const; - INLINE const string &get_comment() const; + INLINE const std::string &get_comment() const; INLINE FunctionIndex get_length_getter() const; INLINE FunctionIndex get_element_getter() const; - void output(ostream &out) const; - void input(istream &in); + void output(std::ostream &out) const; + void input(std::istream &in); void remap_indices(const IndexRemapper &remap); private: - string _scoped_name; - string _comment; + std::string _scoped_name; + std::string _comment; FunctionIndex _length_getter; FunctionIndex _element_getter; friend class InterrogateBuilder; }; -INLINE ostream &operator << (ostream &out, const InterrogateMakeSeq &make_seq); -INLINE istream &operator >> (istream &in, InterrogateMakeSeq &make_seq); +INLINE std::ostream &operator << (std::ostream &out, const InterrogateMakeSeq &make_seq); +INLINE std::istream &operator >> (std::istream &in, InterrogateMakeSeq &make_seq); #include "interrogateMakeSeq.I" diff --git a/dtool/src/interrogatedb/interrogateManifest.I b/dtool/src/interrogatedb/interrogateManifest.I index 877b28a98e..2aedf8a682 100644 --- a/dtool/src/interrogatedb/interrogateManifest.I +++ b/dtool/src/interrogatedb/interrogateManifest.I @@ -49,7 +49,7 @@ operator = (const InterrogateManifest ©) { /** * */ -INLINE const string &InterrogateManifest:: +INLINE const std::string &InterrogateManifest:: get_definition() const { return _definition; } @@ -103,14 +103,14 @@ get_int_value() const { } -INLINE ostream & -operator << (ostream &out, const InterrogateManifest &manifest) { +INLINE std::ostream & +operator << (std::ostream &out, const InterrogateManifest &manifest) { manifest.output(out); return out; } -INLINE istream & -operator >> (istream &in, InterrogateManifest &manifest) { +INLINE std::istream & +operator >> (std::istream &in, InterrogateManifest &manifest) { manifest.input(in); return in; } diff --git a/dtool/src/interrogatedb/interrogateManifest.cxx b/dtool/src/interrogatedb/interrogateManifest.cxx index 5257b85aaf..a078e868f4 100644 --- a/dtool/src/interrogatedb/interrogateManifest.cxx +++ b/dtool/src/interrogatedb/interrogateManifest.cxx @@ -19,7 +19,7 @@ * Formats the InterrogateManifest data for output to a data file. */ void InterrogateManifest:: -output(ostream &out) const { +output(std::ostream &out) const { InterrogateComponent::output(out); out << _flags << " " << _int_value << " " @@ -32,7 +32,7 @@ output(ostream &out) const { * Reads the data file as previously formatted by output(). */ void InterrogateManifest:: -input(istream &in) { +input(std::istream &in) { InterrogateComponent::input(in); in >> _flags >> _int_value >> _type >> _getter; idf_input_string(in, _definition); diff --git a/dtool/src/interrogatedb/interrogateManifest.h b/dtool/src/interrogatedb/interrogateManifest.h index 49323a75c0..a038cc0ce1 100644 --- a/dtool/src/interrogatedb/interrogateManifest.h +++ b/dtool/src/interrogatedb/interrogateManifest.h @@ -25,11 +25,11 @@ class IndexRemapper; */ class EXPCL_INTERROGATEDB InterrogateManifest : public InterrogateComponent { public: - INLINE InterrogateManifest(InterrogateModuleDef *def = NULL); + INLINE InterrogateManifest(InterrogateModuleDef *def = nullptr); INLINE InterrogateManifest(const InterrogateManifest ©); INLINE void operator = (const InterrogateManifest ©); - INLINE const string &get_definition() const; + INLINE const std::string &get_definition() const; INLINE bool has_type() const; INLINE TypeIndex get_type() const; INLINE bool has_getter() const; @@ -37,8 +37,8 @@ public: INLINE bool has_int_value() const; INLINE int get_int_value() const; - void output(ostream &out) const; - void input(istream &in); + void output(std::ostream &out) const; + void input(std::istream &in); void remap_indices(const IndexRemapper &remap); @@ -50,7 +50,7 @@ private: }; int _flags; - string _definition; + std::string _definition; int _int_value; TypeIndex _type; FunctionIndex _getter; @@ -58,8 +58,8 @@ private: friend class InterrogateBuilder; }; -INLINE ostream &operator << (ostream &out, const InterrogateManifest &manifest); -INLINE istream &operator >> (istream &in, InterrogateManifest &manifest); +INLINE std::ostream &operator << (std::ostream &out, const InterrogateManifest &manifest); +INLINE std::istream &operator >> (std::istream &in, InterrogateManifest &manifest); #include "interrogateManifest.I" diff --git a/dtool/src/interrogatedb/interrogateType.I b/dtool/src/interrogatedb/interrogateType.I index 840fdb18f3..c8a4d601b2 100644 --- a/dtool/src/interrogatedb/interrogateType.I +++ b/dtool/src/interrogatedb/interrogateType.I @@ -31,7 +31,7 @@ has_scoped_name() const { /** * */ -INLINE const string &InterrogateType:: +INLINE const std::string &InterrogateType:: get_scoped_name() const { return _scoped_name; } @@ -47,7 +47,7 @@ has_true_name() const { /** * */ -INLINE const string &InterrogateType:: +INLINE const std::string &InterrogateType:: get_true_name() const { return _true_name; } @@ -63,7 +63,7 @@ has_comment() const { /** * */ -INLINE const string &InterrogateType:: +INLINE const std::string &InterrogateType:: get_comment() const { return _comment; } @@ -224,7 +224,7 @@ number_of_enum_values() const { /** * */ -INLINE const string &InterrogateType:: +INLINE const std::string &InterrogateType:: get_enum_value_name(int n) const { if (n >= 0 && n < (int)_enum_values.size()) { return _enum_values[n]._name; @@ -235,7 +235,7 @@ get_enum_value_name(int n) const { /** * */ -INLINE const string &InterrogateType:: +INLINE const std::string &InterrogateType:: get_enum_value_scoped_name(int n) const { if (n >= 0 && n < (int)_enum_values.size()) { return _enum_values[n]._scoped_name; @@ -246,7 +246,7 @@ get_enum_value_scoped_name(int n) const { /** * */ -INLINE const string &InterrogateType:: +INLINE const std::string &InterrogateType:: get_enum_value_comment(int n) const { if (n >= 0 && n < (int)_enum_values.size()) { return _enum_values[n]._comment; @@ -547,38 +547,38 @@ get_nested_type(int n) const { } } -INLINE ostream & -operator << (ostream &out, const InterrogateType &type) { +INLINE std::ostream & +operator << (std::ostream &out, const InterrogateType &type) { type.output(out); return out; } -INLINE istream & -operator >> (istream &in, InterrogateType &type) { +INLINE std::istream & +operator >> (std::istream &in, InterrogateType &type) { type.input(in); return in; } -INLINE ostream & -operator << (ostream &out, const InterrogateType::Derivation &d) { +INLINE std::ostream & +operator << (std::ostream &out, const InterrogateType::Derivation &d) { d.output(out); return out; } -INLINE istream & -operator >> (istream &in, InterrogateType::Derivation &d) { +INLINE std::istream & +operator >> (std::istream &in, InterrogateType::Derivation &d) { d.input(in); return in; } -INLINE ostream & -operator << (ostream &out, const InterrogateType::EnumValue &ev) { +INLINE std::ostream & +operator << (std::ostream &out, const InterrogateType::EnumValue &ev) { ev.output(out); return out; } -INLINE istream & -operator >> (istream &in, InterrogateType::EnumValue &ev) { +INLINE std::istream & +operator >> (std::istream &in, InterrogateType::EnumValue &ev) { ev.input(in); return in; } diff --git a/dtool/src/interrogatedb/interrogateType.cxx b/dtool/src/interrogatedb/interrogateType.cxx index a6d6e45487..a9b9404cd4 100644 --- a/dtool/src/interrogatedb/interrogateType.cxx +++ b/dtool/src/interrogatedb/interrogateType.cxx @@ -18,6 +18,9 @@ #include +using std::istream; +using std::ostream; + /** * */ @@ -32,8 +35,8 @@ InterrogateType(InterrogateModuleDef *def) : _array_size = 1; _destructor = 0; - _cpptype = (CPPType *)NULL; - _cppscope = (CPPScope *)NULL; + _cpptype = nullptr; + _cppscope = nullptr; } /** diff --git a/dtool/src/interrogatedb/interrogateType.h b/dtool/src/interrogatedb/interrogateType.h index 176efb4fb9..0e6ade73d4 100644 --- a/dtool/src/interrogatedb/interrogateType.h +++ b/dtool/src/interrogatedb/interrogateType.h @@ -29,20 +29,20 @@ class CPPScope; */ class EXPCL_INTERROGATEDB InterrogateType : public InterrogateComponent { public: - InterrogateType(InterrogateModuleDef *def = NULL); + InterrogateType(InterrogateModuleDef *def = nullptr); InterrogateType(const InterrogateType ©); void operator = (const InterrogateType ©); INLINE bool is_global() const; INLINE bool has_scoped_name() const; - INLINE const string &get_scoped_name() const; + INLINE const std::string &get_scoped_name() const; INLINE bool has_true_name() const; - INLINE const string &get_true_name() const; + INLINE const std::string &get_true_name() const; INLINE bool has_comment() const; - INLINE const string &get_comment() const; + INLINE const std::string &get_comment() const; INLINE bool is_nested() const; INLINE TypeIndex get_outer_class() const; @@ -67,9 +67,9 @@ public: INLINE bool is_enum() const; INLINE bool is_scoped_enum() const; INLINE int number_of_enum_values() const; - INLINE const string &get_enum_value_name(int n) const; - INLINE const string &get_enum_value_scoped_name(int n) const; - INLINE const string &get_enum_value_comment(int n) const; + INLINE const std::string &get_enum_value_name(int n) const; + INLINE const std::string &get_enum_value_scoped_name(int n) const; + INLINE const std::string &get_enum_value_comment(int n) const; INLINE int get_enum_value(int n) const; INLINE bool is_struct() const; @@ -109,8 +109,8 @@ public: INLINE TypeIndex get_nested_type(int n) const; void merge_with(const InterrogateType &other); - void output(ostream &out) const; - void input(istream &in); + void output(std::ostream &out) const; + void input(std::istream &in); void remap_indices(const IndexRemapper &remap); @@ -146,24 +146,24 @@ private: public: int _flags; - string _scoped_name; - string _true_name; - string _comment; + std::string _scoped_name; + std::string _true_name; + std::string _comment; TypeIndex _outer_class; AtomicToken _atomic_token; TypeIndex _wrapped_type; int _array_size; - typedef vector Functions; + typedef std::vector Functions; Functions _constructors; FunctionIndex _destructor; - typedef vector Elements; + typedef std::vector Elements; Elements _elements; Functions _methods; Functions _casts; - typedef vector MakeSeqs; + typedef std::vector MakeSeqs; MakeSeqs _make_seqs; enum DerivationFlags { @@ -178,8 +178,8 @@ public: // Arguably a compiler bug, but what can you do. class Derivation { public: - void output(ostream &out) const; - void input(istream &in); + void output(std::ostream &out) const; + void input(std::istream &in); int _flags; TypeIndex _base; @@ -188,27 +188,27 @@ public: }; private: - typedef vector Derivations; + typedef std::vector Derivations; Derivations _derivations; public: // This nested class must also be public, for the same reason. class EnumValue { public: - void output(ostream &out) const; - void input(istream &in); + void output(std::ostream &out) const; + void input(std::istream &in); - string _name; - string _scoped_name; - string _comment; + std::string _name; + std::string _scoped_name; + std::string _comment; int _value; }; private: - typedef vector EnumValues; + typedef std::vector EnumValues; EnumValues _enum_values; - typedef vector Types; + typedef std::vector Types; Types _nested_types; public: @@ -223,14 +223,14 @@ public: friend class InterrogateBuilder; }; -INLINE ostream &operator << (ostream &out, const InterrogateType &type); -INLINE istream &operator >> (istream &in, InterrogateType &type); +INLINE std::ostream &operator << (std::ostream &out, const InterrogateType &type); +INLINE std::istream &operator >> (std::istream &in, InterrogateType &type); -INLINE ostream &operator << (ostream &out, const InterrogateType::Derivation &d); -INLINE istream &operator >> (istream &in, InterrogateType::Derivation &d); +INLINE std::ostream &operator << (std::ostream &out, const InterrogateType::Derivation &d); +INLINE std::istream &operator >> (std::istream &in, InterrogateType::Derivation &d); -INLINE ostream &operator << (ostream &out, const InterrogateType::EnumValue &d); -INLINE istream &operator >> (istream &in, InterrogateType::EnumValue &d); +INLINE std::ostream &operator << (std::ostream &out, const InterrogateType::EnumValue &d); +INLINE std::istream &operator >> (std::istream &in, InterrogateType::EnumValue &d); #include "interrogateType.I" diff --git a/dtool/src/interrogatedb/interrogate_datafile.I b/dtool/src/interrogatedb/interrogate_datafile.I index 9111260237..cb020861e2 100644 --- a/dtool/src/interrogatedb/interrogate_datafile.I +++ b/dtool/src/interrogatedb/interrogate_datafile.I @@ -17,9 +17,9 @@ */ template void -idf_output_vector(ostream &out, const vector &vec) { +idf_output_vector(std::ostream &out, const std::vector &vec) { out << vec.size() << " "; - TYPENAME vector::const_iterator vi; + typename std::vector::const_iterator vi; for (vi = vec.begin(); vi != vec.end(); ++vi) { out << (*vi) << " "; } @@ -33,7 +33,7 @@ idf_output_vector(ostream &out, const vector &vec) { */ template void -idf_input_vector(istream &in, vector &vec) { +idf_input_vector(std::istream &in, std::vector &vec) { int length; in >> length; if (in.fail()) { diff --git a/dtool/src/interrogatedb/interrogate_datafile.cxx b/dtool/src/interrogatedb/interrogate_datafile.cxx index eb5c0ca57f..a61defb368 100644 --- a/dtool/src/interrogatedb/interrogate_datafile.cxx +++ b/dtool/src/interrogatedb/interrogate_datafile.cxx @@ -13,6 +13,10 @@ #include "interrogate_datafile.h" +using std::istream; +using std::ostream; +using std::string; + /** * Writes the indicated string to the output file. Uses the given whitespace @@ -53,7 +57,7 @@ idf_input_string(istream &in, string &str) { */ void idf_output_string(ostream &out, const char *str, char whitespace) { - if (str == (const char *)NULL) { + if (str == nullptr) { out << "0 "; } else { out << strlen(str) << whitespace; diff --git a/dtool/src/interrogatedb/interrogate_datafile.h b/dtool/src/interrogatedb/interrogate_datafile.h index ecd2acbce0..8432123fdf 100644 --- a/dtool/src/interrogatedb/interrogate_datafile.h +++ b/dtool/src/interrogatedb/interrogate_datafile.h @@ -20,17 +20,17 @@ #include "dtoolbase.h" #include -void idf_output_string(ostream &out, const string &str, char whitespace = ' '); -void idf_input_string(istream &in, string &str); +void idf_output_string(std::ostream &out, const std::string &str, char whitespace = ' '); +void idf_input_string(std::istream &in, std::string &str); -void idf_output_string(ostream &out, const char *str, char whitespace = ' '); -void idf_input_string(istream &in, const char *&str); +void idf_output_string(std::ostream &out, const char *str, char whitespace = ' '); +void idf_input_string(std::istream &in, const char *&str); template -void idf_output_vector(ostream &out, const vector &vec); +void idf_output_vector(std::ostream &out, const std::vector &vec); template -void idf_input_vector(istream &in, vector &vec); +void idf_input_vector(std::istream &in, std::vector &vec); #include "interrogate_datafile.I" diff --git a/dtool/src/interrogatedb/interrogate_interface.cxx b/dtool/src/interrogatedb/interrogate_interface.cxx index 6e948134d3..2cd08d4adf 100644 --- a/dtool/src/interrogatedb/interrogate_interface.cxx +++ b/dtool/src/interrogatedb/interrogate_interface.cxx @@ -17,6 +17,8 @@ #include "interrogateFunction.h" #include "config_interrogatedb.h" +using std::string; + // This function adds one more directory to the list of directories search for // interrogate (*.in) files. In the past, this list has been defined the // environment variable ETC_PATH, but now it is passed in by the code @@ -400,7 +402,7 @@ interrogate_wrapper_parameter_is_this(FunctionWrapperIndex wrapper, int n) { bool interrogate_wrapper_has_pointer(FunctionWrapperIndex wrapper) { // cerr << "interrogate_wrapper_has_pointer(" << wrapper << ")\n"; - return (InterrogateDatabase::get_ptr()->get_fptr(wrapper) != (void *)NULL); + return (InterrogateDatabase::get_ptr()->get_fptr(wrapper) != nullptr); } void * diff --git a/dtool/src/interrogatedb/py_compat.cxx b/dtool/src/interrogatedb/py_compat.cxx index f0dd42cf73..0c1383f983 100644 --- a/dtool/src/interrogatedb/py_compat.cxx +++ b/dtool/src/interrogatedb/py_compat.cxx @@ -16,8 +16,6 @@ #ifdef HAVE_PYTHON -PyTupleObject Dtool_EmptyTuple = {PyVarObject_HEAD_INIT(nullptr, 0)}; - #if PY_MAJOR_VERSION < 3 /** * Given a long or int, returns a size_t, or raises an OverflowError if it is diff --git a/dtool/src/interrogatedb/py_compat.h b/dtool/src/interrogatedb/py_compat.h index 46537114aa..f87c73cf3d 100644 --- a/dtool/src/interrogatedb/py_compat.h +++ b/dtool/src/interrogatedb/py_compat.h @@ -138,11 +138,29 @@ typedef long Py_hash_t; /* Python 3.6 */ -// Used to implement _PyObject_CallNoArg -extern EXPCL_INTERROGATEDB PyTupleObject Dtool_EmptyTuple; - #ifndef _PyObject_CallNoArg -# define _PyObject_CallNoArg(func) PyObject_Call((func), (PyObject *)&Dtool_EmptyTuple, nullptr) +INLINE PyObject *_PyObject_CallNoArg(PyObject *func) { + static PyTupleObject empty_tuple = {PyVarObject_HEAD_INIT(nullptr, 0)}; +#ifdef Py_TRACE_REFS + _Py_AddToAllObjects((PyObject *)&empty_tuple, 0); +#endif + return PyObject_Call(func, (PyObject *)&empty_tuple, nullptr); +} +# define _PyObject_CallNoArg _PyObject_CallNoArg +#endif + +#ifndef _PyObject_FastCall +INLINE PyObject *_PyObject_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs) { + PyObject *tuple = PyTuple_New(nargs); + for (Py_ssize_t i = 0; i < nargs; ++i) { + PyTuple_SET_ITEM(tuple, i, args[i]); + Py_INCREF(args[i]); + } + PyObject *result = PyObject_Call(func, tuple, nullptr); + Py_DECREF(tuple); + return result; +} +# define _PyObject_FastCall _PyObject_FastCall #endif // Python versions before 3.6 didn't require longlong support to be enabled. @@ -161,6 +179,21 @@ extern EXPCL_INTERROGATEDB PyTupleObject Dtool_EmptyTuple; # define PyDict_GET_SIZE(mp) (((PyDictObject *)mp)->ma_used) #endif +#ifndef Py_RETURN_RICHCOMPARE +# define Py_RETURN_RICHCOMPARE(val1, val2, op) \ + do { \ + switch (op) { \ + NODEFAULT \ + case Py_EQ: if ((val1) == (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \ + case Py_NE: if ((val1) != (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \ + case Py_LT: if ((val1) < (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \ + case Py_GT: if ((val1) > (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \ + case Py_LE: if ((val1) <= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \ + case Py_GE: if ((val1) >= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \ + } \ + } while (0) +#endif + /* Other Python implementations */ // _PyErr_OCCURRED is an undocumented macro version of PyErr_Occurred. diff --git a/dtool/src/interrogatedb/py_panda.I b/dtool/src/interrogatedb/py_panda.I index 1986a128c5..69f8961463 100644 --- a/dtool/src/interrogatedb/py_panda.I +++ b/dtool/src/interrogatedb/py_panda.I @@ -31,6 +31,8 @@ DtoolInstance_GetPointer(PyObject *self, T *&into) { if (_IS_FINAL(T)) { if (DtoolInstance_TYPE(self) == target_class) { into = (T *)DtoolInstance_VOID_PTR(self); + } else { + return false; } } else { into = (T *)DtoolInstance_UPCAST(self, *target_class); @@ -52,6 +54,8 @@ DtoolInstance_GetPointer(PyObject *self, T *&into, Dtool_PyTypedObject &target_c if (_IS_FINAL(T)) { if (DtoolInstance_TYPE(self) == &target_class) { into = (T *)DtoolInstance_VOID_PTR(self); + } else { + return false; } } else { into = (T *)DtoolInstance_UPCAST(self, target_class); @@ -62,34 +66,79 @@ DtoolInstance_GetPointer(PyObject *self, T *&into, Dtool_PyTypedObject &target_c return false; } +/** + * Function to create a hash from a wrapped Python object. + */ +INLINE Py_hash_t DtoolInstance_HashPointer(PyObject *self) { + if (self != nullptr && DtoolInstance_Check(self)) { + return (Py_hash_t)(intptr_t)DtoolInstance_VOID_PTR(self); + } + return -1; +} + +/** + * Python 2-style comparison function that compares objects by pointer. + */ +INLINE int DtoolInstance_ComparePointers(PyObject *v1, PyObject *v2) { + void *v1_this = DtoolInstance_Check(v1) ? DtoolInstance_VOID_PTR(v1) : nullptr; + void *v2_this = DtoolInstance_Check(v2) ? DtoolInstance_VOID_PTR(v2) : nullptr; + if (v1_this != nullptr && v2_this != nullptr) { + return (v1_this > v2_this) - (v1_this < v2_this); + } else { + return (v1 > v2) - (v1 < v2); + } +} + +/** + * Rich comparison function that compares objects by pointer. + */ +INLINE PyObject *DtoolInstance_RichComparePointers(PyObject *v1, PyObject *v2, int op) { + int cmpval = DtoolInstance_ComparePointers(v1, v2); + Py_RETURN_RICHCOMPARE(cmpval, 0, op); +} + +/** + * Converts the enum value to a C long. + */ +INLINE long Dtool_EnumValue_AsLong(PyObject *value) { + PyObject *val = PyObject_GetAttrString(value, "value"); + if (val != nullptr) { + long as_long = PyLongOrInt_AS_LONG(val); + Py_DECREF(val); + return as_long; + } else { + return -1; + } +} + /** * These functions wrap a pointer for a class that defines get_type_handle(). */ template INLINE PyObject * DTool_CreatePyInstance(const T *obj, bool memory_rules) { Dtool_PyTypedObject *known_class = Dtool_RuntimeTypeDtoolType(get_type_handle(T).get_index()); - nassertr(known_class != NULL, NULL); + nassertr(known_class != nullptr, nullptr); return DTool_CreatePyInstance((void*) obj, *known_class, memory_rules, true); } template INLINE PyObject * DTool_CreatePyInstance(T *obj, bool memory_rules) { Dtool_PyTypedObject *known_class = Dtool_RuntimeTypeDtoolType(get_type_handle(T).get_index()); - nassertr(known_class != NULL, NULL); + nassertr(known_class != nullptr, nullptr); return DTool_CreatePyInstance((void*) obj, *known_class, memory_rules, false); } template INLINE PyObject * DTool_CreatePyInstanceTyped(const T *obj, bool memory_rules) { Dtool_PyTypedObject *known_class = Dtool_RuntimeTypeDtoolType(get_type_handle(T).get_index()); - nassertr(known_class != NULL, NULL); + nassertr(known_class != nullptr, nullptr); return DTool_CreatePyInstanceTyped((void*) obj, *known_class, memory_rules, true, obj->get_type().get_index()); } template INLINE PyObject * DTool_CreatePyInstanceTyped(T *obj, bool memory_rules) { Dtool_PyTypedObject *known_class = Dtool_RuntimeTypeDtoolType(get_type_handle(T).get_index()); - nassertr(known_class != NULL, NULL); + nassertr(known_class != nullptr, nullptr); return DTool_CreatePyInstanceTyped((void*) obj, *known_class, memory_rules, false, obj->get_type().get_index()); } @@ -180,7 +229,7 @@ ALWAYS_INLINE PyObject *Dtool_WrapValue(double value) { } ALWAYS_INLINE PyObject *Dtool_WrapValue(const char *value) { - if (value == (const char *)NULL) { + if (value == nullptr) { Py_INCREF(Py_None); return Py_None; } else { @@ -193,7 +242,7 @@ ALWAYS_INLINE PyObject *Dtool_WrapValue(const char *value) { } ALWAYS_INLINE PyObject *Dtool_WrapValue(const wchar_t *value) { - if (value == (const wchar_t *)NULL) { + if (value == nullptr) { Py_INCREF(Py_None); return Py_None; } else { @@ -214,7 +263,7 @@ ALWAYS_INLINE PyObject *Dtool_WrapValue(const std::wstring &value) { } ALWAYS_INLINE PyObject *Dtool_WrapValue(const std::string *value) { - if (value == (const std::string *)NULL) { + if (value == nullptr) { Py_INCREF(Py_None); return Py_None; } else { @@ -227,7 +276,7 @@ ALWAYS_INLINE PyObject *Dtool_WrapValue(const std::string *value) { } ALWAYS_INLINE PyObject *Dtool_WrapValue(const std::wstring *value) { - if (value == (const std::wstring *)NULL) { + if (value == nullptr) { Py_INCREF(Py_None); return Py_None; } else { @@ -247,7 +296,7 @@ ALWAYS_INLINE PyObject *Dtool_WrapValue(wchar_t value) { return PyUnicode_FromWideChar(&value, 1); } -ALWAYS_INLINE PyObject *Dtool_WrapValue(nullptr_t) { +ALWAYS_INLINE PyObject *Dtool_WrapValue(std::nullptr_t) { Py_INCREF(Py_None); return Py_None; } @@ -266,7 +315,7 @@ ALWAYS_INLINE PyObject *Dtool_WrapValue(const vector_uchar &value) { #if PY_MAJOR_VERSION >= 0x02060000 ALWAYS_INLINE PyObject *Dtool_WrapValue(Py_buffer *value) { - if (value == (Py_buffer *)NULL) { + if (value == nullptr) { return value; } else { return PyMemoryView_FromBuffer(value); diff --git a/dtool/src/interrogatedb/py_panda.cxx b/dtool/src/interrogatedb/py_panda.cxx index ce6ce5023b..2522a55cc2 100644 --- a/dtool/src/interrogatedb/py_panda.cxx +++ b/dtool/src/interrogatedb/py_panda.cxx @@ -17,6 +17,8 @@ #ifdef HAVE_PYTHON +using std::string; + PyMemberDef standard_type_members[] = { {(char *)"this", (sizeof(void*) == sizeof(int)) ? T_UINT : T_ULONGLONG, offsetof(Dtool_PyInstDef, _ptr_to_object), READONLY, (char *)"C++ 'this' pointer, if any"}, {(char *)"this_ownership", T_BOOL, offsetof(Dtool_PyInstDef, _memory_rules), READONLY, (char *)"C++ 'this' ownership rules"}, @@ -24,7 +26,7 @@ PyMemberDef standard_type_members[] = { // {(char *)"this_signature", T_INT, offsetof(Dtool_PyInstDef, _signature), // READONLY, (char *)"A type check signature"}, {(char *)"this_metatype", T_OBJECT, offsetof(Dtool_PyInstDef, _My_Type), READONLY, (char *)"The dtool meta object"}, - {NULL} /* Sentinel */ + {nullptr} /* Sentinel */ }; static RuntimeTypeMap runtime_type_map; @@ -143,13 +145,6 @@ DTOOL_Call_GetPointerThisClass(PyObject *self, Dtool_PyTypedObject *classdef, return nullptr; } -void *DTOOL_Call_GetPointerThis(PyObject *self) { - if (self != nullptr && DtoolInstance_Check(self)) { - return DtoolInstance_VOID_PTR(self); - } - return nullptr; -} - /** * This is similar to a PyErr_Occurred() check, except that it also checks * Notify to see if an assertion has occurred. If that is the case, then it @@ -183,9 +178,9 @@ PyObject *Dtool_Raise_AssertionError() { PyObject *message = PyString_FromString(notify->get_assert_error_message().c_str()); #endif Py_INCREF(PyExc_AssertionError); - PyErr_Restore(PyExc_AssertionError, message, (PyObject *)NULL); + PyErr_Restore(PyExc_AssertionError, message, nullptr); notify->clear_assert_failed(); - return NULL; + return nullptr; } /** @@ -196,11 +191,11 @@ PyObject *Dtool_Raise_TypeError(const char *message) { // eventually anyway, so we might as well just get to the point. Py_INCREF(PyExc_TypeError); #if PY_MAJOR_VERSION >= 3 - PyErr_Restore(PyExc_TypeError, PyUnicode_FromString(message), (PyObject *)NULL); + PyErr_Restore(PyExc_TypeError, PyUnicode_FromString(message), nullptr); #else - PyErr_Restore(PyExc_TypeError, PyString_FromString(message), (PyObject *)NULL); + PyErr_Restore(PyExc_TypeError, PyString_FromString(message), nullptr); #endif - return NULL; + return nullptr; } /** @@ -221,8 +216,8 @@ PyObject *Dtool_Raise_ArgTypeError(PyObject *obj, int param, const char *functio Py_TYPE(obj)->tp_name); Py_INCREF(PyExc_TypeError); - PyErr_Restore(PyExc_TypeError, message, (PyObject *)NULL); - return NULL; + PyErr_Restore(PyExc_TypeError, message, nullptr); + return nullptr; } /** @@ -241,8 +236,8 @@ PyObject *Dtool_Raise_AttributeError(PyObject *obj, const char *attribute) { Py_TYPE(obj)->tp_name, attribute); Py_INCREF(PyExc_TypeError); - PyErr_Restore(PyExc_TypeError, message, (PyObject *)NULL); - return NULL; + PyErr_Restore(PyExc_TypeError, message, nullptr); + return nullptr; } /** @@ -265,7 +260,7 @@ PyObject *_Dtool_Raise_BadArgumentsError() { */ PyObject *_Dtool_Return_None() { if (UNLIKELY(_PyErr_OCCURRED())) { - return NULL; + return nullptr; } #ifndef NDEBUG if (UNLIKELY(Notify::ptr()->has_assert_failed())) { @@ -282,7 +277,7 @@ PyObject *_Dtool_Return_None() { */ PyObject *Dtool_Return_Bool(bool value) { if (UNLIKELY(_PyErr_OCCURRED())) { - return NULL; + return nullptr; } #ifndef NDEBUG if (UNLIKELY(Notify::ptr()->has_assert_failed())) { @@ -301,7 +296,7 @@ PyObject *Dtool_Return_Bool(bool value) { */ PyObject *_Dtool_Return(PyObject *value) { if (UNLIKELY(_PyErr_OCCURRED())) { - return NULL; + return nullptr; } #ifndef NDEBUG if (UNLIKELY(Notify::ptr()->has_assert_failed())) { @@ -311,31 +306,116 @@ PyObject *_Dtool_Return(PyObject *value) { return value; } +#if PY_VERSION_HEX < 0x03040000 +static PyObject *Dtool_EnumType_Str(PyObject *self) { + PyObject *name = PyObject_GetAttrString(self, "name"); +#if PY_MAJOR_VERSION >= 3 + PyObject *repr = PyUnicode_FromFormat("%s.%s", Py_TYPE(self)->tp_name, PyString_AS_STRING(name)); +#else + PyObject *repr = PyString_FromFormat("%s.%s", Py_TYPE(self)->tp_name, PyString_AS_STRING(name)); +#endif + Py_DECREF(name); + return repr; +} + +static PyObject *Dtool_EnumType_Repr(PyObject *self) { + PyObject *name = PyObject_GetAttrString(self, "name"); + PyObject *value = PyObject_GetAttrString(self, "value"); +#if PY_MAJOR_VERSION >= 3 + PyObject *repr = PyUnicode_FromFormat("<%s.%s: %ld>", Py_TYPE(self)->tp_name, PyString_AS_STRING(name), PyLongOrInt_AS_LONG(value)); +#else + PyObject *repr = PyString_FromFormat("<%s.%s: %ld>", Py_TYPE(self)->tp_name, PyString_AS_STRING(name), PyLongOrInt_AS_LONG(value)); +#endif + Py_DECREF(name); + Py_DECREF(value); + return repr; +} +#endif + /** - * Creates a Python 3.4-style enum type. Steals reference to 'names'. + * Creates a Python 3.4-style enum type. Steals reference to 'names', which + * should be a tuple of (name, value) pairs. */ -PyObject *Dtool_EnumType_Create(const char *name, PyObject *names, const char *module) { - static PyObject *enum_class = NULL; - static PyObject *enum_meta = NULL; - static PyObject *enum_create = NULL; - if (enum_meta == NULL) { +PyTypeObject *Dtool_EnumType_Create(const char *name, PyObject *names, const char *module) { + static PyObject *enum_class = nullptr; +#if PY_VERSION_HEX >= 0x03040000 + static PyObject *enum_meta = nullptr; + static PyObject *enum_create = nullptr; + if (enum_meta == nullptr) { PyObject *enum_module = PyImport_ImportModule("enum"); - nassertr_always(enum_module != NULL, NULL); + nassertr_always(enum_module != nullptr, nullptr); enum_class = PyObject_GetAttrString(enum_module, "Enum"); enum_meta = PyObject_GetAttrString(enum_module, "EnumMeta"); enum_create = PyObject_GetAttrString(enum_meta, "_create_"); - nassertr(enum_meta != NULL, NULL); + nassertr(enum_meta != nullptr, nullptr); } PyObject *result = PyObject_CallFunction(enum_create, (char *)"OsN", enum_class, name, names); - nassertr(result != NULL, NULL); - if (module != NULL) { + nassertr(result != nullptr, nullptr); +#else + static PyObject *name_str; + static PyObject *name_sunder_str; + static PyObject *value_str; + static PyObject *value_sunder_str; + // Emulate something vaguely like the enum module. + if (enum_class == nullptr) { +#if PY_MAJOR_VERSION >= 3 + name_str = PyUnicode_InternFromString("name"); + value_str = PyUnicode_InternFromString("value"); + name_sunder_str = PyUnicode_InternFromString("_name_"); + value_sunder_str = PyUnicode_InternFromString("_value_"); +#else + name_str = PyString_InternFromString("name"); + value_str = PyString_InternFromString("value"); + name_sunder_str = PyString_InternFromString("_name_"); + value_sunder_str = PyString_InternFromString("_value_"); +#endif + PyObject *name_value_tuple = PyTuple_New(4); + PyTuple_SET_ITEM(name_value_tuple, 0, name_str); + PyTuple_SET_ITEM(name_value_tuple, 1, value_str); + PyTuple_SET_ITEM(name_value_tuple, 2, name_sunder_str); + PyTuple_SET_ITEM(name_value_tuple, 3, value_sunder_str); + Py_INCREF(name_str); + Py_INCREF(value_str); + + PyObject *slots_dict = PyDict_New(); + PyDict_SetItemString(slots_dict, "__slots__", name_value_tuple); + Py_DECREF(name_value_tuple); + + enum_class = PyObject_CallFunction((PyObject *)&PyType_Type, (char *)"s()N", "Enum", slots_dict); + nassertr(enum_class != nullptr, nullptr); + } + PyObject *result = PyObject_CallFunction((PyObject *)&PyType_Type, (char *)"s(O)N", name, enum_class, PyDict_New()); + nassertr(result != nullptr, nullptr); + + ((PyTypeObject *)result)->tp_str = Dtool_EnumType_Str; + ((PyTypeObject *)result)->tp_repr = Dtool_EnumType_Repr; + + // Copy the names as instances of the above to the class dict. + Py_ssize_t size = PyTuple_GET_SIZE(names); + for (Py_ssize_t i = 0; i < size; ++i) { + PyObject *item = PyTuple_GET_ITEM(names, i); + PyObject *name = PyTuple_GET_ITEM(item, 0); + PyObject *value = PyTuple_GET_ITEM(item, 1); + PyObject *member = _PyObject_CallNoArg(result); + PyObject_SetAttr(member, name_str, name); + PyObject_SetAttr(member, name_sunder_str, name); + PyObject_SetAttr(member, value_str, value); + PyObject_SetAttr(member, value_sunder_str, value); + PyObject_SetAttr(result, name, member); + Py_DECREF(member); + } + Py_DECREF(names); +#endif + + if (module != nullptr) { PyObject *modstr = PyUnicode_FromString(module); PyObject_SetAttrString(result, "__module__", modstr); Py_DECREF(modstr); } - return result; + nassertr(PyType_Check(result), nullptr); + return (PyTypeObject *)result; } /** @@ -346,19 +426,19 @@ PyObject *DTool_CreatePyInstanceTyped(void *local_this_in, Dtool_PyTypedObject & // caller will have to get the type index to pass to this function to begin // with. That code probably would have crashed by now if it was really NULL // for whatever reason. - nassertr(local_this_in != NULL, NULL); + nassertr(local_this_in != nullptr, nullptr); // IF the class is possibly a run time typed object if (type_index > 0) { // get best fit class... Dtool_PyTypedObject *target_class = Dtool_RuntimeTypeDtoolType(type_index); - if (target_class != NULL) { + if (target_class != nullptr) { // cast to the type... void *new_local_this = target_class->_Dtool_DowncastInterface(local_this_in, &known_class_type); - if (new_local_this != NULL) { + if (new_local_this != nullptr) { // ask class to allocate an instance.. - Dtool_PyInstDef *self = (Dtool_PyInstDef *) target_class->_PyType.tp_new(&target_class->_PyType, NULL, NULL); - if (self != NULL) { + Dtool_PyInstDef *self = (Dtool_PyInstDef *) target_class->_PyType.tp_new(&target_class->_PyType, nullptr, nullptr); + if (self != nullptr) { self->_ptr_to_object = new_local_this; self->_memory_rules = memory_rules; self->_is_const = is_const; @@ -372,8 +452,8 @@ PyObject *DTool_CreatePyInstanceTyped(void *local_this_in, Dtool_PyTypedObject & // if we get this far .. just wrap the thing in the known type ?? better // than aborting...I guess.... - Dtool_PyInstDef *self = (Dtool_PyInstDef *) known_class_type._PyType.tp_new(&known_class_type._PyType, NULL, NULL); - if (self != NULL) { + Dtool_PyInstDef *self = (Dtool_PyInstDef *) known_class_type._PyType.tp_new(&known_class_type._PyType, nullptr, nullptr); + if (self != nullptr) { self->_ptr_to_object = local_this_in; self->_memory_rules = memory_rules; self->_is_const = is_const; @@ -386,7 +466,7 @@ PyObject *DTool_CreatePyInstanceTyped(void *local_this_in, Dtool_PyTypedObject & // DTool_CreatePyInstance .. wrapper function to finalize the existance of a // general dtool py instance.. PyObject *DTool_CreatePyInstance(void *local_this, Dtool_PyTypedObject &in_classdef, bool memory_rules, bool is_const) { - if (local_this == NULL) { + if (local_this == nullptr) { // This is actually a very common case, so let's allow this, but return // Py_None consistently. This eliminates code in the wrappers. Py_INCREF(Py_None); @@ -394,8 +474,8 @@ PyObject *DTool_CreatePyInstance(void *local_this, Dtool_PyTypedObject &in_class } Dtool_PyTypedObject *classdef = &in_classdef; - Dtool_PyInstDef *self = (Dtool_PyInstDef *) classdef->_PyType.tp_new(&classdef->_PyType, NULL, NULL); - if (self != NULL) { + Dtool_PyInstDef *self = (Dtool_PyInstDef *) classdef->_PyType.tp_new(&classdef->_PyType, nullptr, nullptr); + if (self != nullptr) { self->_ptr_to_object = local_this; self->_memory_rules = memory_rules; self->_is_const = is_const; @@ -420,7 +500,7 @@ int DTool_PyInit_Finalize(PyObject *self, void *local_this, Dtool_PyTypedObject // done at code generation time because of multiple generation passes in // interrogate.. void Dtool_Accum_MethDefs(PyMethodDef in[], MethodDefmap &themap) { - for (; in->ml_name != NULL; in++) { + for (; in->ml_name != nullptr; in++) { if (themap.find(in->ml_name) == themap.end()) { themap[in->ml_name] = in; } @@ -432,7 +512,7 @@ void Dtool_Accum_MethDefs(PyMethodDef in[], MethodDefmap &themap) { // are uniquly defined by an integer. void RegisterNamedClass(const string &name, Dtool_PyTypedObject &otype) { - pair result = + std::pair result = named_type_map.insert(NamedTypeMap::value_type(name, &otype)); if (!result.second) { @@ -457,7 +537,7 @@ RegisterRuntimeTypedClass(Dtool_PyTypedObject &otype) { << " has an illegal TypeHandle value; check that init_type() is called.\n"; } else { - pair result = + std::pair result = runtime_type_map.insert(RuntimeTypeMap::value_type(type_index, &otype)); if (!result.second) { // There was already an entry in the dictionary for type_index. @@ -492,7 +572,7 @@ LookupNamedClass(const string &name) { interrogatedb_cat.error() << "Attempt to use type " << name << " which has not yet been defined!\n"; - return NULL; + return nullptr; } else { return it->second; } @@ -506,7 +586,7 @@ LookupRuntimeTypedClass(TypeHandle handle) { if (it == runtime_type_map.end()) { interrogatedb_cat.error() << "Attempt to use type " << handle << " which has not yet been defined!\n"; - return NULL; + return nullptr; } else { return it->second; } @@ -523,7 +603,7 @@ Dtool_PyTypedObject *Dtool_RuntimeTypeDtoolType(int type) { return di->second; } } - return NULL; + return nullptr; } #if PY_MAJOR_VERSION >= 3 @@ -538,13 +618,13 @@ PyObject *Dtool_PyModuleInitHelper(LibraryDef *defs[], const char *modulename) { version[2] != '0' + PY_MINOR_VERSION) { // Raise a helpful error message. We can safely do this because the // signature and behavior for PyErr_SetString has remained consistent. - ostringstream errs; + std::ostringstream errs; errs << "this module was compiled for Python " << PY_MAJOR_VERSION << "." << PY_MINOR_VERSION << ", which is " << "incompatible with Python " << version.substr(0, 3); string error = errs.str(); PyErr_SetString(PyExc_ImportError, error.c_str()); - return (PyObject *)NULL; + return nullptr; } // Initialize the types we define in py_panda. @@ -588,17 +668,13 @@ PyObject *Dtool_PyModuleInitHelper(LibraryDef *defs[], const char *modulename) { return Dtool_Raise_TypeError("PyType_Ready(Dtool_StaticProperty_Type)"); } -#ifdef Py_TRACE_REFS - _Py_AddToAllObjects((PyObject *)&Dtool_EmptyTuple, 0); -#endif - // Initialize the base class of everything. - Dtool_PyModuleClassInit_DTOOL_SUPER_BASE(NULL); + Dtool_PyModuleClassInit_DTOOL_SUPER_BASE(nullptr); } // the module level function inits.... MethodDefmap functions; - for (int xx = 0; defs[xx] != NULL; xx++) { + for (int xx = 0; defs[xx] != nullptr; xx++) { Dtool_Accum_MethDefs(defs[xx]->_methods, functions); } @@ -608,9 +684,9 @@ PyObject *Dtool_PyModuleInitHelper(LibraryDef *defs[], const char *modulename) { for (mi = functions.begin(); mi != functions.end(); mi++, offset++) { newdef[offset] = *mi->second; } - newdef[offset].ml_doc = NULL; - newdef[offset].ml_name = NULL; - newdef[offset].ml_meth = NULL; + newdef[offset].ml_doc = nullptr; + newdef[offset].ml_name = nullptr; + newdef[offset].ml_meth = nullptr; newdef[offset].ml_flags = 0; #if PY_MAJOR_VERSION >= 3 @@ -620,7 +696,7 @@ PyObject *Dtool_PyModuleInitHelper(LibraryDef *defs[], const char *modulename) { PyObject *module = Py_InitModule((char *)modulename, newdef); #endif - if (module == NULL) { + if (module == nullptr) { #if PY_MAJOR_VERSION >= 3 return Dtool_Raise_TypeError("PyModule_Create returned NULL"); #else @@ -648,14 +724,14 @@ PyObject *Dtool_PyModuleInitHelper(LibraryDef *defs[], const char *modulename) { // Extract the __file__ attribute, if present. Filename main_dir; PyObject *file_attr = PyObject_GetAttrString(main_module, "__file__"); - if (file_attr == NULL) { + if (file_attr == nullptr) { // Must be running in the interactive interpreter. Use the CWD. main_dir = ExecutionEnvironment::get_cwd(); } else { #if PY_MAJOR_VERSION >= 3 Py_ssize_t length; wchar_t *buffer = PyUnicode_AsWideCharString(file_attr, &length); - if (buffer != NULL) { + if (buffer != nullptr) { main_dir = Filename::from_os_specific_w(std::wstring(buffer, length)); main_dir.make_absolute(); main_dir = main_dir.get_dirname(); @@ -688,8 +764,8 @@ PyObject *Dtool_PyModuleInitHelper(LibraryDef *defs[], const char *modulename) { // grab the "THIS" pointer from an object and use it Required to support // historical inheritance in the form of "is this instance of".. PyObject *Dtool_BorrowThisReference(PyObject *self, PyObject *args) { - PyObject *from_in = NULL; - PyObject *to_in = NULL; + PyObject *from_in = nullptr; + PyObject *to_in = nullptr; if (PyArg_UnpackTuple(args, "Dtool_BorrowThisReference", 2, 2, &to_in, &from_in)) { if (DtoolInstance_Check(from_in) && DtoolInstance_Check(to_in)) { @@ -712,159 +788,38 @@ PyObject *Dtool_BorrowThisReference(PyObject *self, PyObject *args) { return Dtool_Raise_TypeError("One of these does not appear to be DTOOL Instance ??"); } } - return (PyObject *) NULL; + return nullptr; } // We do expose a dictionay for dtool classes .. this should be removed at // some point.. -PyObject *Dtool_AddToDictionary(PyObject *self1, PyObject *args) { +EXPCL_INTERROGATEDB PyObject *Dtool_AddToDictionary(PyObject *self1, PyObject *args) { PyObject *self; PyObject *subject; PyObject *key; if (PyArg_ParseTuple(args, "OSO", &self, &key, &subject)) { PyObject *dict = ((PyTypeObject *)self)->tp_dict; - if (dict == NULL || !PyDict_Check(dict)) { + if (dict == nullptr || !PyDict_Check(dict)) { return Dtool_Raise_TypeError("No dictionary On Object"); } else { PyDict_SetItem(dict, key, subject); } } if (PyErr_Occurred()) { - return (PyObject *)NULL; + return nullptr; } Py_INCREF(Py_None); return Py_None; } -Py_hash_t DTOOL_PyObject_HashPointer(PyObject *self) { - if (self != nullptr && DtoolInstance_Check(self)) { - return (Py_hash_t)(intptr_t)DtoolInstance_VOID_PTR(self); - } - return -1; -} - -/* Compare v to w. Return - -1 if v < w or exception (PyErr_Occurred() true in latter case). - 0 if v == w. - 1 if v > w. - XXX The docs (C API manual) say the return value is undefined in case - XXX of error. -*/ - -int DTOOL_PyObject_ComparePointers(PyObject *v1, PyObject *v2) { - // try this compare - void *v1_this = DTOOL_Call_GetPointerThis(v1); - void *v2_this = DTOOL_Call_GetPointerThis(v2); - if (v1_this != NULL && v2_this != NULL) { // both are our types... - if (v1_this < v2_this) { - return -1; - } - if (v1_this > v2_this) { - return 1; - } - return 0; - } - - // ok self compare... - if (v1 < v2) { - return -1; - } - if (v1 > v2) { - return 1; - } - return 0; -} - -int DTOOL_PyObject_Compare(PyObject *v1, PyObject *v2) { - // First try compareTo function.. - PyObject * func = PyObject_GetAttrString(v1, "compare_to"); - if (func == NULL) { - PyErr_Clear(); - } else { -#if PY_VERSION_HEX >= 0x03060000 - PyObject *res = _PyObject_FastCall(func, &v2, 1); -#else - PyObject *res = NULL; - PyObject *args = PyTuple_Pack(1, v2); - if (args != NULL) { - res = PyObject_Call(func, args, NULL); - Py_DECREF(args); - } -#endif - Py_DECREF(func); - PyErr_Clear(); // just in case the function threw an error - // only use if the function returns an INT... hmm - if (res != NULL) { - if (PyLong_Check(res)) { - long answer = PyLong_AsLong(res); - Py_DECREF(res); - - // Python really wants us to return strictly -1, 0, or 1. - if (answer < 0) { - return -1; - } else if (answer > 0) { - return 1; - } else { - return 0; - } - } -#if PY_MAJOR_VERSION < 3 - else if (PyInt_Check(res)) { - long answer = PyInt_AsLong(res); - Py_DECREF(res); - - // Python really wants us to return strictly -1, 0, or 1. - if (answer < 0) { - return -1; - } else if (answer > 0) { - return 1; - } else { - return 0; - } - } -#endif - Py_DECREF(res); - } - } - - return DTOOL_PyObject_ComparePointers(v1, v2); -} - -PyObject *DTOOL_PyObject_RichCompare(PyObject *v1, PyObject *v2, int op) { - int cmpval = DTOOL_PyObject_Compare(v1, v2); - bool result; - switch (op) { - NODEFAULT - case Py_LT: - result = (cmpval < 0); - break; - case Py_LE: - result = (cmpval <= 0); - break; - case Py_EQ: - result = (cmpval == 0); - break; - case Py_NE: - result = (cmpval != 0); - break; - case Py_GT: - result = (cmpval > 0); - break; - case Py_GE: - result = (cmpval >= 0); - break; - } - return PyBool_FromLong(result); -} - /** * This is a support function for a synthesized __copy__() method from a C++ * make_copy() method. */ PyObject *copy_from_make_copy(PyObject *self, PyObject *noargs) { PyObject *callable = PyObject_GetAttrString(self, "make_copy"); - if (callable == NULL) { - return NULL; + if (callable == nullptr) { + return nullptr; } PyObject *result = _PyObject_CallNoArg(callable); Py_DECREF(callable); @@ -877,15 +832,7 @@ PyObject *copy_from_make_copy(PyObject *self, PyObject *noargs) { */ PyObject *copy_from_copy_constructor(PyObject *self, PyObject *noargs) { PyObject *callable = (PyObject *)Py_TYPE(self); - -#if PY_VERSION_HEX >= 0x03060000 - PyObject *result = _PyObject_FastCall(callable, &self, 1); -#else - PyObject *args = PyTuple_Pack(1, self); - PyObject *result = PyObject_Call(callable, args, NULL); - Py_DECREF(args); -#endif - return result; + return _PyObject_FastCall(callable, &self, 1); } /** @@ -895,8 +842,8 @@ PyObject *copy_from_copy_constructor(PyObject *self, PyObject *noargs) { */ PyObject *map_deepcopy_to_copy(PyObject *self, PyObject *args) { PyObject *callable = PyObject_GetAttrString(self, "__copy__"); - if (callable == NULL) { - return NULL; + if (callable == nullptr) { + return nullptr; } PyObject *result = _PyObject_CallNoArg(callable); Py_DECREF(callable); diff --git a/dtool/src/interrogatedb/py_panda.h b/dtool/src/interrogatedb/py_panda.h index f4edc8f4ad..7916147e4d 100644 --- a/dtool/src/interrogatedb/py_panda.h +++ b/dtool/src/interrogatedb/py_panda.h @@ -130,7 +130,7 @@ static void Dtool_FreeInstance_##CLASS_NAME(PyObject *self) {\ static void Dtool_FreeInstance_##CLASS_NAME(PyObject *self) {\ if (DtoolInstance_VOID_PTR(self) != nullptr) {\ if (((Dtool_PyInstDef *)self)->_memory_rules) {\ - cerr << "Detected leak for " << #CLASS_NAME \ + std::cerr << "Detected leak for " << #CLASS_NAME \ << " which interrogate cannot delete.\n"; \ }\ }\ @@ -158,6 +158,16 @@ static void Dtool_FreeInstance_##CLASS_NAME(PyObject *self) {\ Py_TYPE(self)->tp_free(self);\ } +#define Define_Dtool_FreeInstanceRef_Private(CLASS_NAME,CNAME)\ +static void Dtool_FreeInstance_##CLASS_NAME(PyObject *self) {\ + if (DtoolInstance_VOID_PTR(self) != nullptr) {\ + if (((Dtool_PyInstDef *)self)->_memory_rules) {\ + unref_delete((ReferenceCount *)(CNAME *)DtoolInstance_VOID_PTR(self));\ + }\ + }\ + Py_TYPE(self)->tp_free(self);\ +} + #define Define_Dtool_Simple_FreeInstance(CLASS_NAME, CNAME)\ static void Dtool_FreeInstance_##CLASS_NAME(PyObject *self) {\ ((Dtool_InstDef_##CLASS_NAME *)self)->_value.~##CLASS_NAME();\ @@ -180,10 +190,10 @@ static void Dtool_FreeInstance_##CLASS_NAME(PyObject *self) {\ // forward declared of typed object. We rely on the fact that typed objects // are uniquly defined by an integer. -EXPCL_INTERROGATEDB void RegisterNamedClass(const string &name, Dtool_PyTypedObject &otype); +EXPCL_INTERROGATEDB void RegisterNamedClass(const std::string &name, Dtool_PyTypedObject &otype); EXPCL_INTERROGATEDB void RegisterRuntimeTypedClass(Dtool_PyTypedObject &otype); -EXPCL_INTERROGATEDB Dtool_PyTypedObject *LookupNamedClass(const string &name); +EXPCL_INTERROGATEDB Dtool_PyTypedObject *LookupNamedClass(const std::string &name); EXPCL_INTERROGATEDB Dtool_PyTypedObject *LookupRuntimeTypedClass(TypeHandle handle); EXPCL_INTERROGATEDB Dtool_PyTypedObject *Dtool_RuntimeTypeDtoolType(int type); @@ -193,9 +203,7 @@ EXPCL_INTERROGATEDB Dtool_PyTypedObject *Dtool_RuntimeTypeDtoolType(int type); */ EXPCL_INTERROGATEDB void DTOOL_Call_ExtractThisPointerForType(PyObject *self, Dtool_PyTypedObject *classdef, void **answer); -EXPCL_INTERROGATEDB void *DTOOL_Call_GetPointerThisClass(PyObject *self, Dtool_PyTypedObject *classdef, int param, const string &function_name, bool const_ok, bool report_errors); - -EXPCL_INTERROGATEDB void *DTOOL_Call_GetPointerThis(PyObject *self); +EXPCL_INTERROGATEDB void *DTOOL_Call_GetPointerThisClass(PyObject *self, Dtool_PyTypedObject *classdef, int param, const std::string &function_name, bool const_ok, bool report_errors); EXPCL_INTERROGATEDB bool Dtool_Call_ExtractThisPointer(PyObject *self, Dtool_PyTypedObject &classdef, void **answer); @@ -205,6 +213,10 @@ EXPCL_INTERROGATEDB bool Dtool_Call_ExtractThisPointer_NonConst(PyObject *self, template INLINE bool DtoolInstance_GetPointer(PyObject *self, T *&into); template INLINE bool DtoolInstance_GetPointer(PyObject *self, T *&into, Dtool_PyTypedObject &classdef); +INLINE Py_hash_t DtoolInstance_HashPointer(PyObject *self); +INLINE int DtoolInstance_ComparePointers(PyObject *v1, PyObject *v2); +INLINE PyObject *DtoolInstance_RichComparePointers(PyObject *v1, PyObject *v2, int op); + // Functions related to error reporting. EXPCL_INTERROGATEDB bool _Dtool_CheckErrorOccurred(); @@ -246,8 +258,10 @@ EXPCL_INTERROGATEDB PyObject *_Dtool_Return(PyObject *value); /** * Wrapper around Python 3.4's enum library, which does not have a C API. */ -EXPCL_INTERROGATEDB PyObject *Dtool_EnumType_Create(const char *name, PyObject *names, - const char *module = NULL); +EXPCL_INTERROGATEDB PyTypeObject *Dtool_EnumType_Create(const char *name, PyObject *names, + const char *module = nullptr); +EXPCL_INTERROGATEDB INLINE long Dtool_EnumValue_AsLong(PyObject *value); + /** @@ -290,7 +304,7 @@ Define_Dtool_Class(MODULE_NAME,CLASS_NAME,PUBLIC_NAME) #define Define_Module_ClassRef_Private(MODULE_NAME,CLASS_NAME,CNAME,PUBLIC_NAME)\ Define_Module_Class_Internal(MODULE_NAME,CLASS_NAME,CNAME)\ Define_Dtool_new(CLASS_NAME,CNAME)\ -Define_Dtool_FreeInstance_Private(CLASS_NAME,CNAME)\ +Define_Dtool_FreeInstanceRef_Private(CLASS_NAME,CNAME)\ Define_Dtool_Class(MODULE_NAME,CLASS_NAME,PUBLIC_NAME) #define Define_Module_ClassRef(MODULE_NAME,CLASS_NAME,CNAME,PUBLIC_NAME)\ @@ -327,25 +341,8 @@ EXPCL_INTERROGATEDB PyObject *Dtool_PyModuleInitHelper(LibraryDef *defs[], const // historical inharatence in the for of "is this instance of".. EXPCL_INTERROGATEDB PyObject *Dtool_BorrowThisReference(PyObject *self, PyObject *args); -// We do expose a dictionay for dtool classes .. this should be removed at -// some point.. -EXPCL_INTERROGATEDB PyObject *Dtool_AddToDictionary(PyObject *self1, PyObject *args); - - -EXPCL_INTERROGATEDB Py_hash_t DTOOL_PyObject_HashPointer(PyObject *obj); - -/* Compare v to w. Return - -1 if v < w or exception (PyErr_Occurred() true in latter case). - 0 if v == w. - 1 if v > w. - XXX The docs (C API manual) say the return value is undefined in case - XXX of error. -*/ - -EXPCL_INTERROGATEDB int DTOOL_PyObject_ComparePointers(PyObject *v1, PyObject *v2); -EXPCL_INTERROGATEDB int DTOOL_PyObject_Compare(PyObject *v1, PyObject *v2); - -EXPCL_INTERROGATEDB PyObject *DTOOL_PyObject_RichCompare(PyObject *v1, PyObject *v2, int op); +#define DTOOL_PyObject_HashPointer DtoolInstance_HashPointer +#define DTOOL_PyObject_ComparePointers DtoolInstance_ComparePointers EXPCL_INTERROGATEDB PyObject * copy_from_make_copy(PyObject *self, PyObject *noargs); @@ -393,7 +390,7 @@ ALWAYS_INLINE PyObject *Dtool_WrapValue(const std::string *value); ALWAYS_INLINE PyObject *Dtool_WrapValue(const std::wstring *value); ALWAYS_INLINE PyObject *Dtool_WrapValue(char value); ALWAYS_INLINE PyObject *Dtool_WrapValue(wchar_t value); -ALWAYS_INLINE PyObject *Dtool_WrapValue(nullptr_t); +ALWAYS_INLINE PyObject *Dtool_WrapValue(std::nullptr_t); ALWAYS_INLINE PyObject *Dtool_WrapValue(PyObject *value); ALWAYS_INLINE PyObject *Dtool_WrapValue(const vector_uchar &value); diff --git a/dtool/src/interrogatedb/py_wrappers.cxx b/dtool/src/interrogatedb/py_wrappers.cxx index 4d56eee41a..71a5a38ffd 100644 --- a/dtool/src/interrogatedb/py_wrappers.cxx +++ b/dtool/src/interrogatedb/py_wrappers.cxx @@ -377,7 +377,7 @@ static PyObject *Dtool_MutableSequenceWrapper_insert(PyObject *self, PyObject *a return PyErr_Format(PyExc_TypeError, "%s.insert() does not support negative indices", wrap->_base._name); } } - return wrap->_insert_func(wrap->_base._self, (ssize_t)max(index, (Py_ssize_t)0), PyTuple_GET_ITEM(args, 1)); + return wrap->_insert_func(wrap->_base._self, (ssize_t)std::max(index, (Py_ssize_t)0), PyTuple_GET_ITEM(args, 1)); } /** @@ -517,7 +517,7 @@ static PyObject *Dtool_MappingWrapper_keys(PyObject *self, PyObject *) { _register_collection((PyTypeObject *)&Dtool_MappingWrapper_Keys_Type, "MappingView"); } - PyObject_INIT(keys, &Dtool_MappingWrapper_Keys_Type); + (void)PyObject_INIT(keys, &Dtool_MappingWrapper_Keys_Type); Py_XINCREF(wrap->_base._self); keys->_base._self = wrap->_base._self; keys->_base._name = wrap->_base._name; @@ -552,7 +552,7 @@ static PyObject *Dtool_MappingWrapper_values(PyObject *self, PyObject *) { _register_collection((PyTypeObject *)&Dtool_MappingWrapper_Values_Type, "ValuesView"); } - PyObject_INIT(values, &Dtool_MappingWrapper_Values_Type); + (void)PyObject_INIT(values, &Dtool_MappingWrapper_Values_Type); Py_XINCREF(wrap->_base._self); values->_base._self = wrap->_base._self; values->_base._name = wrap->_base._name; @@ -588,7 +588,7 @@ static PyObject *Dtool_MappingWrapper_items(PyObject *self, PyObject *) { _register_collection((PyTypeObject *)&Dtool_MappingWrapper_Items_Type, "MappingView"); } - PyObject_INIT(items, &Dtool_MappingWrapper_Items_Type); + (void)PyObject_INIT(items, &Dtool_MappingWrapper_Items_Type); Py_XINCREF(wrap->_base._self); items->_base._self = wrap->_base._self; items->_base._name = wrap->_base._name; @@ -797,15 +797,15 @@ static PyObject *Dtool_MutableMappingWrapper_update(PyObject *self, PyObject *ar */ static PySequenceMethods Dtool_SequenceWrapper_SequenceMethods = { Dtool_SequenceWrapper_length, - 0, // sq_concat - 0, // sq_repeat + nullptr, // sq_concat + nullptr, // sq_repeat Dtool_SequenceWrapper_getitem, - 0, // sq_slice - 0, // sq_ass_item - 0, // sq_ass_slice + nullptr, // sq_slice + nullptr, // sq_ass_item + nullptr, // sq_ass_slice Dtool_SequenceWrapper_contains, - 0, // sq_inplace_concat - 0, // sq_inplace_repeat + nullptr, // sq_inplace_concat + nullptr, // sq_inplace_repeat }; static PyMethodDef Dtool_SequenceWrapper_Methods[] = { @@ -820,47 +820,47 @@ PyTypeObject Dtool_SequenceWrapper_Type = { sizeof(Dtool_SequenceWrapper), 0, // tp_itemsize Dtool_WrapperBase_dealloc, - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_compare + nullptr, // tp_print + nullptr, // tp_getattr + nullptr, // tp_setattr + nullptr, // tp_compare Dtool_SequenceWrapper_repr, - 0, // tp_as_number + nullptr, // tp_as_number &Dtool_SequenceWrapper_SequenceMethods, - 0, // tp_as_mapping - 0, // tp_hash - 0, // tp_call - 0, // tp_str + nullptr, // tp_as_mapping + nullptr, // tp_hash + nullptr, // tp_call + nullptr, // tp_str PyObject_GenericGetAttr, PyObject_GenericSetAttr, - 0, // tp_as_buffer + nullptr, // tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES, - 0, // tp_doc - 0, // tp_traverse - 0, // tp_clear - 0, // tp_richcompare + nullptr, // tp_doc + nullptr, // tp_traverse + nullptr, // tp_clear + nullptr, // tp_richcompare 0, // tp_weaklistoffset PySeqIter_New, - 0, // tp_iternext + nullptr, // tp_iternext Dtool_SequenceWrapper_Methods, - 0, // tp_members - 0, // tp_getset - 0, // tp_base - 0, // tp_dict - 0, // tp_descr_get - 0, // tp_descr_set + nullptr, // tp_members + nullptr, // tp_getset + nullptr, // tp_base + nullptr, // tp_dict + nullptr, // tp_descr_get + nullptr, // tp_descr_set 0, // tp_dictoffset - 0, // tp_init + nullptr, // tp_init PyType_GenericAlloc, - 0, // tp_new + nullptr, // tp_new PyObject_Del, - 0, // tp_is_gc - 0, // tp_bases - 0, // tp_mro - 0, // tp_cache - 0, // tp_subclasses - 0, // tp_weaklist - 0, // tp_del + nullptr, // tp_is_gc + nullptr, // tp_bases + nullptr, // tp_mro + nullptr, // tp_cache + nullptr, // tp_subclasses + nullptr, // tp_weaklist + nullptr, // tp_del }; /** @@ -868,15 +868,15 @@ PyTypeObject Dtool_SequenceWrapper_Type = { */ static PySequenceMethods Dtool_MutableSequenceWrapper_SequenceMethods = { Dtool_SequenceWrapper_length, - 0, // sq_concat - 0, // sq_repeat + nullptr, // sq_concat + nullptr, // sq_repeat Dtool_SequenceWrapper_getitem, - 0, // sq_slice + nullptr, // sq_slice Dtool_MutableSequenceWrapper_setitem, - 0, // sq_ass_slice + nullptr, // sq_ass_slice Dtool_SequenceWrapper_contains, Dtool_MutableSequenceWrapper_extend, - 0, // sq_inplace_repeat + nullptr, // sq_inplace_repeat }; static PyMethodDef Dtool_MutableSequenceWrapper_Methods[] = { @@ -897,47 +897,47 @@ PyTypeObject Dtool_MutableSequenceWrapper_Type = { sizeof(Dtool_MutableSequenceWrapper), 0, // tp_itemsize Dtool_WrapperBase_dealloc, - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_compare + nullptr, // tp_print + nullptr, // tp_getattr + nullptr, // tp_setattr + nullptr, // tp_compare Dtool_SequenceWrapper_repr, - 0, // tp_as_number + nullptr, // tp_as_number &Dtool_MutableSequenceWrapper_SequenceMethods, - 0, // tp_as_mapping - 0, // tp_hash - 0, // tp_call - 0, // tp_str + nullptr, // tp_as_mapping + nullptr, // tp_hash + nullptr, // tp_call + nullptr, // tp_str PyObject_GenericGetAttr, PyObject_GenericSetAttr, - 0, // tp_as_buffer + nullptr, // tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES, - 0, // tp_doc - 0, // tp_traverse - 0, // tp_clear - 0, // tp_richcompare + nullptr, // tp_doc + nullptr, // tp_traverse + nullptr, // tp_clear + nullptr, // tp_richcompare 0, // tp_weaklistoffset PySeqIter_New, - 0, // tp_iternext + nullptr, // tp_iternext Dtool_MutableSequenceWrapper_Methods, - 0, // tp_members - 0, // tp_getset - 0, // tp_base - 0, // tp_dict - 0, // tp_descr_get - 0, // tp_descr_set + nullptr, // tp_members + nullptr, // tp_getset + nullptr, // tp_base + nullptr, // tp_dict + nullptr, // tp_descr_get + nullptr, // tp_descr_set 0, // tp_dictoffset - 0, // tp_init + nullptr, // tp_init PyType_GenericAlloc, - 0, // tp_new + nullptr, // tp_new PyObject_Del, - 0, // tp_is_gc - 0, // tp_bases - 0, // tp_mro - 0, // tp_cache - 0, // tp_subclasses - 0, // tp_weaklist - 0, // tp_del + nullptr, // tp_is_gc + nullptr, // tp_bases + nullptr, // tp_mro + nullptr, // tp_cache + nullptr, // tp_subclasses + nullptr, // tp_weaklist + nullptr, // tp_del }; /** @@ -945,21 +945,21 @@ PyTypeObject Dtool_MutableSequenceWrapper_Type = { */ static PySequenceMethods Dtool_MappingWrapper_SequenceMethods = { Dtool_SequenceWrapper_length, - 0, // sq_concat - 0, // sq_repeat - 0, // sq_item - 0, // sq_slice - 0, // sq_ass_item - 0, // sq_ass_slice + nullptr, // sq_concat + nullptr, // sq_repeat + nullptr, // sq_item + nullptr, // sq_slice + nullptr, // sq_ass_item + nullptr, // sq_ass_slice Dtool_MappingWrapper_contains, - 0, // sq_inplace_concat - 0, // sq_inplace_repeat + nullptr, // sq_inplace_concat + nullptr, // sq_inplace_repeat }; static PyMappingMethods Dtool_MappingWrapper_MappingMethods = { Dtool_SequenceWrapper_length, Dtool_MappingWrapper_getitem, - 0, // mp_ass_subscript + nullptr, // mp_ass_subscript }; static PyMethodDef Dtool_MappingWrapper_Methods[] = { @@ -976,47 +976,47 @@ PyTypeObject Dtool_MappingWrapper_Type = { sizeof(Dtool_MappingWrapper), 0, // tp_itemsize Dtool_WrapperBase_dealloc, - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_compare + nullptr, // tp_print + nullptr, // tp_getattr + nullptr, // tp_setattr + nullptr, // tp_compare Dtool_WrapperBase_repr, - 0, // tp_as_number + nullptr, // tp_as_number &Dtool_MappingWrapper_SequenceMethods, &Dtool_MappingWrapper_MappingMethods, - 0, // tp_hash - 0, // tp_call - 0, // tp_str + nullptr, // tp_hash + nullptr, // tp_call + nullptr, // tp_str PyObject_GenericGetAttr, PyObject_GenericSetAttr, - 0, // tp_as_buffer + nullptr, // tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES, - 0, // tp_doc - 0, // tp_traverse - 0, // tp_clear - 0, // tp_richcompare + nullptr, // tp_doc + nullptr, // tp_traverse + nullptr, // tp_clear + nullptr, // tp_richcompare 0, // tp_weaklistoffset Dtool_MappingWrapper_iter, - 0, // tp_iternext + nullptr, // tp_iternext Dtool_MappingWrapper_Methods, - 0, // tp_members - 0, // tp_getset - 0, // tp_base - 0, // tp_dict - 0, // tp_descr_get - 0, // tp_descr_set + nullptr, // tp_members + nullptr, // tp_getset + nullptr, // tp_base + nullptr, // tp_dict + nullptr, // tp_descr_get + nullptr, // tp_descr_set 0, // tp_dictoffset - 0, // tp_init + nullptr, // tp_init PyType_GenericAlloc, - 0, // tp_new + nullptr, // tp_new PyObject_Del, - 0, // tp_is_gc - 0, // tp_bases - 0, // tp_mro - 0, // tp_cache - 0, // tp_subclasses - 0, // tp_weaklist - 0, // tp_del + nullptr, // tp_is_gc + nullptr, // tp_bases + nullptr, // tp_mro + nullptr, // tp_cache + nullptr, // tp_subclasses + nullptr, // tp_weaklist + nullptr, // tp_del }; /** @@ -1047,47 +1047,47 @@ PyTypeObject Dtool_MutableMappingWrapper_Type = { sizeof(Dtool_MappingWrapper), 0, // tp_itemsize Dtool_WrapperBase_dealloc, - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_compare + nullptr, // tp_print + nullptr, // tp_getattr + nullptr, // tp_setattr + nullptr, // tp_compare Dtool_WrapperBase_repr, - 0, // tp_as_number + nullptr, // tp_as_number &Dtool_MappingWrapper_SequenceMethods, &Dtool_MutableMappingWrapper_MappingMethods, - 0, // tp_hash - 0, // tp_call - 0, // tp_str + nullptr, // tp_hash + nullptr, // tp_call + nullptr, // tp_str PyObject_GenericGetAttr, PyObject_GenericSetAttr, - 0, // tp_as_buffer + nullptr, // tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES, - 0, // tp_doc - 0, // tp_traverse - 0, // tp_clear - 0, // tp_richcompare + nullptr, // tp_doc + nullptr, // tp_traverse + nullptr, // tp_clear + nullptr, // tp_richcompare 0, // tp_weaklistoffset Dtool_MappingWrapper_iter, - 0, // tp_iternext + nullptr, // tp_iternext Dtool_MutableMappingWrapper_Methods, - 0, // tp_members - 0, // tp_getset - 0, // tp_base - 0, // tp_dict - 0, // tp_descr_get - 0, // tp_descr_set + nullptr, // tp_members + nullptr, // tp_getset + nullptr, // tp_base + nullptr, // tp_dict + nullptr, // tp_descr_get + nullptr, // tp_descr_set 0, // tp_dictoffset - 0, // tp_init + nullptr, // tp_init PyType_GenericAlloc, - 0, // tp_new + nullptr, // tp_new PyObject_Del, - 0, // tp_is_gc - 0, // tp_bases - 0, // tp_mro - 0, // tp_cache - 0, // tp_subclasses - 0, // tp_weaklist - 0, // tp_del + nullptr, // tp_is_gc + nullptr, // tp_bases + nullptr, // tp_mro + nullptr, // tp_cache + nullptr, // tp_subclasses + nullptr, // tp_weaklist + nullptr, // tp_del }; /** @@ -1131,15 +1131,15 @@ static PyObject *Dtool_MappingWrapper_Items_getitem(PyObject *self, Py_ssize_t i static PySequenceMethods Dtool_MappingWrapper_Items_SequenceMethods = { Dtool_SequenceWrapper_length, - 0, // sq_concat - 0, // sq_repeat + nullptr, // sq_concat + nullptr, // sq_repeat Dtool_MappingWrapper_Items_getitem, - 0, // sq_slice - 0, // sq_ass_item - 0, // sq_ass_slice + nullptr, // sq_slice + nullptr, // sq_ass_item + nullptr, // sq_ass_slice Dtool_MappingWrapper_contains, - 0, // sq_inplace_concat - 0, // sq_inplace_repeat + nullptr, // sq_inplace_concat + nullptr, // sq_inplace_repeat }; PyTypeObject Dtool_MappingWrapper_Items_Type = { @@ -1148,47 +1148,47 @@ PyTypeObject Dtool_MappingWrapper_Items_Type = { sizeof(Dtool_MappingWrapper), 0, // tp_itemsize Dtool_WrapperBase_dealloc, - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_compare + nullptr, // tp_print + nullptr, // tp_getattr + nullptr, // tp_setattr + nullptr, // tp_compare Dtool_MappingWrapper_Items_repr, - 0, // tp_as_number + nullptr, // tp_as_number &Dtool_MappingWrapper_Items_SequenceMethods, - 0, // tp_as_mapping - 0, // tp_hash - 0, // tp_call - 0, // tp_str + nullptr, // tp_as_mapping + nullptr, // tp_hash + nullptr, // tp_call + nullptr, // tp_str PyObject_GenericGetAttr, PyObject_GenericSetAttr, - 0, // tp_as_buffer + nullptr, // tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES, - 0, // tp_doc - 0, // tp_traverse - 0, // tp_clear - 0, // tp_richcompare + nullptr, // tp_doc + nullptr, // tp_traverse + nullptr, // tp_clear + nullptr, // tp_richcompare 0, // tp_weaklistoffset PySeqIter_New, - 0, // tp_iternext - 0, // tp_methods - 0, // tp_members - 0, // tp_getset - 0, // tp_base - 0, // tp_dict - 0, // tp_descr_get - 0, // tp_descr_set + nullptr, // tp_iternext + nullptr, // tp_methods + nullptr, // tp_members + nullptr, // tp_getset + nullptr, // tp_base + nullptr, // tp_dict + nullptr, // tp_descr_get + nullptr, // tp_descr_set 0, // tp_dictoffset - 0, // tp_init + nullptr, // tp_init PyType_GenericAlloc, - 0, // tp_new + nullptr, // tp_new PyObject_Del, - 0, // tp_is_gc - 0, // tp_bases - 0, // tp_mro - 0, // tp_cache - 0, // tp_subclasses - 0, // tp_weaklist - 0, // tp_del + nullptr, // tp_is_gc + nullptr, // tp_bases + nullptr, // tp_mro + nullptr, // tp_cache + nullptr, // tp_subclasses + nullptr, // tp_weaklist + nullptr, // tp_del }; /** @@ -1209,66 +1209,53 @@ static PyObject *Dtool_MappingWrapper_Keys_repr(PyObject *self) { return result; } -static PySequenceMethods Dtool_MappingWrapper_Keys_SequenceMethods = { - Dtool_SequenceWrapper_length, - 0, // sq_concat - 0, // sq_repeat - Dtool_MappingWrapper_Items_getitem, - 0, // sq_slice - 0, // sq_ass_item - 0, // sq_ass_slice - Dtool_MappingWrapper_contains, - 0, // sq_inplace_concat - 0, // sq_inplace_repeat -}; - PyTypeObject Dtool_MappingWrapper_Keys_Type = { PyVarObject_HEAD_INIT(nullptr, 0) "sequence wrapper", sizeof(Dtool_SequenceWrapper), 0, // tp_itemsize Dtool_WrapperBase_dealloc, - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_compare + nullptr, // tp_print + nullptr, // tp_getattr + nullptr, // tp_setattr + nullptr, // tp_compare Dtool_MappingWrapper_Keys_repr, - 0, // tp_as_number + nullptr, // tp_as_number &Dtool_SequenceWrapper_SequenceMethods, - 0, // tp_as_mapping - 0, // tp_hash - 0, // tp_call - 0, // tp_str + nullptr, // tp_as_mapping + nullptr, // tp_hash + nullptr, // tp_call + nullptr, // tp_str PyObject_GenericGetAttr, PyObject_GenericSetAttr, - 0, // tp_as_buffer + nullptr, // tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES, - 0, // tp_doc - 0, // tp_traverse - 0, // tp_clear - 0, // tp_richcompare + nullptr, // tp_doc + nullptr, // tp_traverse + nullptr, // tp_clear + nullptr, // tp_richcompare 0, // tp_weaklistoffset PySeqIter_New, - 0, // tp_iternext - 0, // tp_methods - 0, // tp_members - 0, // tp_getset - 0, // tp_base - 0, // tp_dict - 0, // tp_descr_get - 0, // tp_descr_set + nullptr, // tp_iternext + nullptr, // tp_methods + nullptr, // tp_members + nullptr, // tp_getset + nullptr, // tp_base + nullptr, // tp_dict + nullptr, // tp_descr_get + nullptr, // tp_descr_set 0, // tp_dictoffset - 0, // tp_init + nullptr, // tp_init PyType_GenericAlloc, - 0, // tp_new + nullptr, // tp_new PyObject_Del, - 0, // tp_is_gc - 0, // tp_bases - 0, // tp_mro - 0, // tp_cache - 0, // tp_subclasses - 0, // tp_weaklist - 0, // tp_del + nullptr, // tp_is_gc + nullptr, // tp_bases + nullptr, // tp_mro + nullptr, // tp_cache + nullptr, // tp_subclasses + nullptr, // tp_weaklist + nullptr, // tp_del }; /** @@ -1305,15 +1292,15 @@ static PyObject *Dtool_MappingWrapper_Values_getitem(PyObject *self, Py_ssize_t static PySequenceMethods Dtool_MappingWrapper_Values_SequenceMethods = { Dtool_SequenceWrapper_length, - 0, // sq_concat - 0, // sq_repeat + nullptr, // sq_concat + nullptr, // sq_repeat Dtool_MappingWrapper_Values_getitem, - 0, // sq_slice - 0, // sq_ass_item - 0, // sq_ass_slice + nullptr, // sq_slice + nullptr, // sq_ass_item + nullptr, // sq_ass_slice Dtool_MappingWrapper_contains, - 0, // sq_inplace_concat - 0, // sq_inplace_repeat + nullptr, // sq_inplace_concat + nullptr, // sq_inplace_repeat }; PyTypeObject Dtool_MappingWrapper_Values_Type = { @@ -1322,47 +1309,47 @@ PyTypeObject Dtool_MappingWrapper_Values_Type = { sizeof(Dtool_MappingWrapper), 0, // tp_itemsize Dtool_WrapperBase_dealloc, - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_compare + nullptr, // tp_print + nullptr, // tp_getattr + nullptr, // tp_setattr + nullptr, // tp_compare Dtool_MappingWrapper_Values_repr, - 0, // tp_as_number + nullptr, // tp_as_number &Dtool_MappingWrapper_Values_SequenceMethods, - 0, // tp_as_mapping - 0, // tp_hash - 0, // tp_call - 0, // tp_str + nullptr, // tp_as_mapping + nullptr, // tp_hash + nullptr, // tp_call + nullptr, // tp_str PyObject_GenericGetAttr, PyObject_GenericSetAttr, - 0, // tp_as_buffer + nullptr, // tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES, - 0, // tp_doc - 0, // tp_traverse - 0, // tp_clear - 0, // tp_richcompare + nullptr, // tp_doc + nullptr, // tp_traverse + nullptr, // tp_clear + nullptr, // tp_richcompare 0, // tp_weaklistoffset PySeqIter_New, - 0, // tp_iternext - 0, // tp_methods - 0, // tp_members - 0, // tp_getset - 0, // tp_base - 0, // tp_dict - 0, // tp_descr_get - 0, // tp_descr_set + nullptr, // tp_iternext + nullptr, // tp_methods + nullptr, // tp_members + nullptr, // tp_getset + nullptr, // tp_base + nullptr, // tp_dict + nullptr, // tp_descr_get + nullptr, // tp_descr_set 0, // tp_dictoffset - 0, // tp_init + nullptr, // tp_init PyType_GenericAlloc, - 0, // tp_new + nullptr, // tp_new PyObject_Del, - 0, // tp_is_gc - 0, // tp_bases - 0, // tp_mro - 0, // tp_cache - 0, // tp_subclasses - 0, // tp_weaklist - 0, // tp_del + nullptr, // tp_is_gc + nullptr, // tp_bases + nullptr, // tp_mro + nullptr, // tp_cache + nullptr, // tp_subclasses + nullptr, // tp_weaklist + nullptr, // tp_del }; /** @@ -1381,47 +1368,47 @@ PyTypeObject Dtool_GeneratorWrapper_Type = { sizeof(Dtool_GeneratorWrapper), 0, // tp_itemsize Dtool_WrapperBase_dealloc, - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_compare - 0, // tp_repr - 0, // tp_as_number - 0, // tp_as_sequence - 0, // tp_as_mapping - 0, // tp_hash - 0, // tp_call - 0, // tp_str + nullptr, // tp_print + nullptr, // tp_getattr + nullptr, // tp_setattr + nullptr, // tp_compare + nullptr, // tp_repr + nullptr, // tp_as_number + nullptr, // tp_as_sequence + nullptr, // tp_as_mapping + nullptr, // tp_hash + nullptr, // tp_call + nullptr, // tp_str PyObject_GenericGetAttr, PyObject_GenericSetAttr, - 0, // tp_as_buffer + nullptr, // tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES, - 0, // tp_doc - 0, // tp_traverse - 0, // tp_clear - 0, // tp_richcompare + nullptr, // tp_doc + nullptr, // tp_traverse + nullptr, // tp_clear + nullptr, // tp_richcompare 0, // tp_weaklistoffset PyObject_SelfIter, Dtool_GeneratorWrapper_iternext, - 0, // tp_methods - 0, // tp_members - 0, // tp_getset - 0, // tp_base - 0, // tp_dict - 0, // tp_descr_get - 0, // tp_descr_set + nullptr, // tp_methods + nullptr, // tp_members + nullptr, // tp_getset + nullptr, // tp_base + nullptr, // tp_dict + nullptr, // tp_descr_get + nullptr, // tp_descr_set 0, // tp_dictoffset - 0, // tp_init + nullptr, // tp_init PyType_GenericAlloc, - 0, // tp_new + nullptr, // tp_new PyObject_Del, - 0, // tp_is_gc - 0, // tp_bases - 0, // tp_mro - 0, // tp_cache - 0, // tp_subclasses - 0, // tp_weaklist - 0, // tp_del + nullptr, // tp_is_gc + nullptr, // tp_bases + nullptr, // tp_mro + nullptr, // tp_cache + nullptr, // tp_subclasses + nullptr, // tp_weaklist + nullptr, // tp_del }; /** @@ -1498,47 +1485,47 @@ PyTypeObject Dtool_StaticProperty_Type = { sizeof(PyGetSetDescrObject), 0, // tp_itemsize (destructor)Dtool_StaticProperty_dealloc, - 0, // tp_print - 0, // tp_getattr - 0, // tp_setattr - 0, // tp_reserved + nullptr, // tp_print + nullptr, // tp_getattr + nullptr, // tp_setattr + nullptr, // tp_reserved (reprfunc)Dtool_StaticProperty_repr, - 0, // tp_as_number - 0, // tp_as_sequence - 0, // tp_as_mapping - 0, // tp_hash - 0, // tp_call - 0, // tp_str + nullptr, // tp_as_number + nullptr, // tp_as_sequence + nullptr, // tp_as_mapping + nullptr, // tp_hash + nullptr, // tp_call + nullptr, // tp_str PyObject_GenericGetAttr, - 0, // tp_setattro - 0, // tp_as_buffer + nullptr, // tp_setattro + nullptr, // tp_as_buffer Py_TPFLAGS_DEFAULT, - 0, // tp_doc + nullptr, // tp_doc Dtool_StaticProperty_traverse, - 0, // tp_clear - 0, // tp_richcompare + nullptr, // tp_clear + nullptr, // tp_richcompare 0, // tp_weaklistoffset - 0, // tp_iter - 0, // tp_iternext - 0, // tp_methods - 0, // tp_members - 0, // tp_getset - 0, // tp_base - 0, // tp_dict + nullptr, // tp_iter + nullptr, // tp_iternext + nullptr, // tp_methods + nullptr, // tp_members + nullptr, // tp_getset + nullptr, // tp_base + nullptr, // tp_dict (descrgetfunc)Dtool_StaticProperty_get, (descrsetfunc)Dtool_StaticProperty_set, 0, // tp_dictoffset - 0, // tp_init - 0, // tp_alloc - 0, // tp_new - 0, // tp_del - 0, // tp_is_gc - 0, // tp_bases - 0, // tp_mro - 0, // tp_cache - 0, // tp_subclasses - 0, // tp_weaklist - 0, // tp_del + nullptr, // tp_init + nullptr, // tp_alloc + nullptr, // tp_new + nullptr, // tp_del + nullptr, // tp_is_gc + nullptr, // tp_bases + nullptr, // tp_mro + nullptr, // tp_cache + nullptr, // tp_subclasses + nullptr, // tp_weaklist + nullptr, // tp_del }; /** @@ -1557,7 +1544,7 @@ Dtool_SequenceWrapper *Dtool_NewSequenceWrapper(PyObject *self, const char *name _register_collection((PyTypeObject *)&Dtool_MutableSequenceWrapper_Type, "Sequence"); } - PyObject_INIT(wrap, &Dtool_SequenceWrapper_Type); + (void)PyObject_INIT(wrap, &Dtool_SequenceWrapper_Type); Py_XINCREF(self); wrap->_base._self = self; wrap->_base._name = name; @@ -1582,7 +1569,7 @@ Dtool_MutableSequenceWrapper *Dtool_NewMutableSequenceWrapper(PyObject *self, co _register_collection((PyTypeObject *)&Dtool_MutableSequenceWrapper_Type, "MutableSequence"); } - PyObject_INIT(wrap, &Dtool_MutableSequenceWrapper_Type); + (void)PyObject_INIT(wrap, &Dtool_MutableSequenceWrapper_Type); Py_XINCREF(self); wrap->_base._self = self; wrap->_base._name = name; @@ -1609,7 +1596,7 @@ Dtool_MappingWrapper *Dtool_NewMappingWrapper(PyObject *self, const char *name) _register_collection((PyTypeObject *)&Dtool_MappingWrapper_Type, "Mapping"); } - PyObject_INIT(wrap, &Dtool_MappingWrapper_Type); + (void)PyObject_INIT(wrap, &Dtool_MappingWrapper_Type); Py_XINCREF(self); wrap->_base._self = self; wrap->_base._name = name; @@ -1636,7 +1623,7 @@ Dtool_MappingWrapper *Dtool_NewMutableMappingWrapper(PyObject *self, const char _register_collection((PyTypeObject *)&Dtool_MutableMappingWrapper_Type, "MutableMapping"); } - PyObject_INIT(wrap, &Dtool_MutableMappingWrapper_Type); + (void)PyObject_INIT(wrap, &Dtool_MutableMappingWrapper_Type); Py_XINCREF(self); wrap->_base._self = self; wrap->_base._name = name; diff --git a/dtool/src/parser-inc/algorithm b/dtool/src/parser-inc/algorithm index 6f409742c2..751a8ec2cb 100644 --- a/dtool/src/parser-inc/algorithm +++ b/dtool/src/parser-inc/algorithm @@ -20,5 +20,12 @@ #ifndef ALGORITHM_H #define ALGORITHM_H +namespace std { + template + constexpr const T &min(const T &a, const T &b); + template + constexpr const T &max(const T &a, const T &b); +} + #endif diff --git a/dtool/src/parser-inc/atomic b/dtool/src/parser-inc/atomic new file mode 100644 index 0000000000..a7e174937b --- /dev/null +++ b/dtool/src/parser-inc/atomic @@ -0,0 +1,19 @@ +#pragma once + +#include + +namespace std { + typedef enum memory_order { + memory_order_relaxed, + memory_order_consume, + memory_order_acquire, + memory_order_release, + memory_order_acq_rel, + memory_order_seq_cst + } memory_order; + + template struct atomic; + template struct atomic; + + struct atomic_flag; +} diff --git a/dtool/src/parser-inc/cassert b/dtool/src/parser-inc/cassert new file mode 100644 index 0000000000..f5711e7692 --- /dev/null +++ b/dtool/src/parser-inc/cassert @@ -0,0 +1 @@ +#include diff --git a/dtool/src/parser-inc/cerrno b/dtool/src/parser-inc/cerrno new file mode 100644 index 0000000000..339f4fc10c --- /dev/null +++ b/dtool/src/parser-inc/cerrno @@ -0,0 +1 @@ +#include diff --git a/dtool/src/parser-inc/clocale b/dtool/src/parser-inc/clocale new file mode 100644 index 0000000000..a889a57372 --- /dev/null +++ b/dtool/src/parser-inc/clocale @@ -0,0 +1 @@ +#include diff --git a/dtool/src/parser-inc/csetjmp b/dtool/src/parser-inc/csetjmp new file mode 100644 index 0000000000..bff273d1d2 --- /dev/null +++ b/dtool/src/parser-inc/csetjmp @@ -0,0 +1,5 @@ +#pragma once + +namespace std { + typedef int jmp_buf[1]; +} diff --git a/dtool/src/parser-inc/cstddef b/dtool/src/parser-inc/cstddef new file mode 100644 index 0000000000..78ed8af5a5 --- /dev/null +++ b/dtool/src/parser-inc/cstddef @@ -0,0 +1,7 @@ +#pragma once + +#include + +namespace std { + enum class byte : unsigned char {}; +} diff --git a/dtool/src/parser-inc/cstdint b/dtool/src/parser-inc/cstdint new file mode 100644 index 0000000000..9a6118bd85 --- /dev/null +++ b/dtool/src/parser-inc/cstdint @@ -0,0 +1 @@ +#include diff --git a/dtool/src/parser-inc/cstdio b/dtool/src/parser-inc/cstdio new file mode 100644 index 0000000000..53c5fdf179 --- /dev/null +++ b/dtool/src/parser-inc/cstdio @@ -0,0 +1 @@ +#include diff --git a/dtool/src/parser-inc/cstdlib b/dtool/src/parser-inc/cstdlib new file mode 100644 index 0000000000..32c55863ad --- /dev/null +++ b/dtool/src/parser-inc/cstdlib @@ -0,0 +1,21 @@ +#pragma once + +#include + +namespace std { + struct div_t { + int quot, rem; + }; + + struct ldiv_t { + long quot, rem; + }; + + struct lldiv_t { + long long quot, rem; + }; + + struct imaxdiv_t { + long long quot, rem; + }; +} diff --git a/dtool/src/parser-inc/cstring b/dtool/src/parser-inc/cstring new file mode 100644 index 0000000000..3b2f590027 --- /dev/null +++ b/dtool/src/parser-inc/cstring @@ -0,0 +1 @@ +#include diff --git a/dtool/src/parser-inc/ctime b/dtool/src/parser-inc/ctime new file mode 100644 index 0000000000..91fd18715f --- /dev/null +++ b/dtool/src/parser-inc/ctime @@ -0,0 +1 @@ +#include diff --git a/dtool/src/parser-inc/cwchar b/dtool/src/parser-inc/cwchar new file mode 100644 index 0000000000..598c31d9a3 --- /dev/null +++ b/dtool/src/parser-inc/cwchar @@ -0,0 +1,8 @@ +#pragma once + +#include + +namespace std { + struct mbstate_t; + typedef int wint_t; +} diff --git a/dtool/src/parser-inc/exception b/dtool/src/parser-inc/exception new file mode 100644 index 0000000000..d48d80620e --- /dev/null +++ b/dtool/src/parser-inc/exception @@ -0,0 +1,10 @@ +#pragma once + +namespace std { + class exception; + class bad_exception; + class nested_exception; + + typedef void (*unexpected_handler)(); + typedef void (*terminate_handler)(); +} diff --git a/dtool/src/parser-inc/fstream b/dtool/src/parser-inc/fstream new file mode 100644 index 0000000000..e0b7a9c3a0 --- /dev/null +++ b/dtool/src/parser-inc/fstream @@ -0,0 +1 @@ +#include diff --git a/dtool/src/parser-inc/initializer_list b/dtool/src/parser-inc/initializer_list index 57a3f7f6c1..289b0e4bf7 100644 --- a/dtool/src/parser-inc/initializer_list +++ b/dtool/src/parser-inc/initializer_list @@ -32,3 +32,5 @@ namespace std { typedef const E* const_iterator; }; } + +#endif diff --git a/dtool/src/parser-inc/iomanip b/dtool/src/parser-inc/iomanip new file mode 100644 index 0000000000..cc19f56b38 --- /dev/null +++ b/dtool/src/parser-inc/iomanip @@ -0,0 +1,6 @@ +#pragma once + +namespace std { + template void setfill(CharT c); + void setw(int); +} diff --git a/dtool/src/parser-inc/ios b/dtool/src/parser-inc/ios new file mode 100644 index 0000000000..19758d573f --- /dev/null +++ b/dtool/src/parser-inc/ios @@ -0,0 +1,112 @@ +#pragma once + +#include + +// We actually want to wrap streampos as streamoff. +#define streampos streamoff + +namespace std { +#ifdef _WIN64 + typedef long long streamoff; + typedef long long streamsize; +#elif defined(_WIN32) + typedef long streamoff; + typedef int streamsize; +#else + typedef long long streamoff; + typedef ptrdiff_t streamsize; +#endif + + // We need to expose one method in each class to force it to publish. + // But we'd like to expose some of these methods anyway, so no + // problem. + class ios_base { + public: + class failure; + class Init; + enum event { + erase_event, + imbue_event, + copyfmt_event, + }; + + ios_base(const ios_base&) = delete; + ios_base &operator = (const ios_base&) = delete; + + __published: + enum seekdir { + beg = 0, + cur = 1, + end = 2, + }; + enum openmode { + }; + enum iostate { + }; + // Don't define these lest interrogate get tempted to actually + // substitute in the values, which are implementation-defined. + static const openmode app; + static const openmode binary; + static const openmode in; + static const openmode out; + static const openmode trunc; + static constexpr iostate goodbit = 0; + static constexpr iostate badbit; + static constexpr iostate failbit; + static constexpr iostate eofbit; + protected: + // Force this to be a non-trivial type. + ios_base() {}; + }; + + template > + class basic_ios : public ios_base { + public: + typedef charT char_type; + typedef typename traits::int_type int_type; + typedef typename traits::pos_type pos_type; + typedef typename traits::off_type off_type; + typedef traits traits_type; + + __published: + typedef long fmtflags; + + bool good() const; + bool eof() const; + bool fail() const; + bool bad() const; + void clear(); + + protected: + basic_ios(); + }; + + ios_base &boolalpha(ios_base &str); + ios_base &noboolalpha(ios_base &str); + ios_base &showbase(ios_base &str); + ios_base &noshowbase(ios_base &str); + ios_base &showpoint(ios_base &str); + ios_base &noshowpoint(ios_base &str); + ios_base &showpos(ios_base &str); + ios_base &noshowpos(ios_base &str); + ios_base &skipws(ios_base &str); + ios_base &noskipws(ios_base &str); + ios_base &uppercase(ios_base &str); + ios_base &nouppercase(ios_base &str); + ios_base &unitbuf(ios_base &str); + ios_base &nounitbuf(ios_base &str); + ios_base &internal(ios_base &str); + ios_base &left(ios_base &str); + ios_base &right(ios_base &str); + ios_base &dec(ios_base &str); + ios_base &hex(ios_base &str); + ios_base &oct(ios_base &str); + ios_base &fixed(ios_base &str); + ios_base &scientific(ios_base &str); + ios_base &hexfloat(ios_base &str); + ios_base &defaultfloat(ios_base &str); + + enum class io_errc { + stream = 1 + }; +} diff --git a/dtool/src/parser-inc/iosfwd b/dtool/src/parser-inc/iosfwd new file mode 100644 index 0000000000..abf62821ea --- /dev/null +++ b/dtool/src/parser-inc/iosfwd @@ -0,0 +1,77 @@ +#pragma once + +#include +#include +#include + +namespace std { + template class allocator; + + template > class basic_ios; + template > class basic_istream; + template > class basic_ostream; + template > class basic_iostream; + template, class Allocator = allocator > class basic_stringbuf; + + template, class Allocator = allocator > class basic_istringstream; + template, class Allocator = allocator > class basic_ostringstream; + template, class Allocator = allocator > class basic_stringstream; + + template > class basic_filebuf; + template > class basic_ifstream; + template > class basic_ofstream; + template > class basic_fstream; + + template, class Allocator = allocator > class basic_syncbuf; + template, class Allocator = allocator > class basic_osyncstream; + + template > class istreambuf_iterator; + template > class ostreambuf_iterator; + + typedef basic_ios ios; + typedef basic_ios wios; + + //typedef basic_istream istream; + //typedef basic_ostream ostream; + //typedef basic_iostream iostream; + class istream; + class ostream; + class iostream; + + typedef basic_stringbuf stringbuf; + typedef basic_istringstream istringstream; + typedef basic_ostringstream ostringstream; + typedef basic_stringstream stringstream; + + typedef basic_filebuf filebuf; + //typedef basic_ifstream ifstream; + //typedef basic_ofstream ofstream; + //typedef basic_fstream fstream; + class ifstream; + class ofstream; + class fstream; + + typedef basic_syncbuf syncbuf; + typedef basic_osyncstream osyncstream; + + typedef basic_istream wistream; + typedef basic_ostream wostream; + typedef basic_iostream wiostream; + + typedef basic_stringbuf wstringbuf; + typedef basic_istringstream wistringstream; + typedef basic_ostringstream wostringstream; + typedef basic_stringstream wstringstream; + + typedef basic_filebuf wfilebuf; + typedef basic_ifstream wifstream; + typedef basic_ofstream wofstream; + typedef basic_fstream wfstream; + + typedef basic_syncbuf wsyncbuf; + typedef basic_osyncstream wosyncstream; + + template class fpos; + typedef fpos streampos; + typedef fpos wstreampos; +} diff --git a/dtool/src/parser-inc/iostream b/dtool/src/parser-inc/iostream index 170d1d03f9..8bfe91d0aa 100644 --- a/dtool/src/parser-inc/iostream +++ b/dtool/src/parser-inc/iostream @@ -21,122 +21,69 @@ #define IOSTREAM_H #include - -#ifdef _WIN64 -typedef long long streamoff; -typedef long long streamsize; -#elif defined(_WIN32) -typedef long streamoff; -typedef int streamsize; -#else -typedef long long streamoff; -typedef ptrdiff_t streamsize; -#endif +#include +#include +#include // We don't care (much) about the actual definition of the various // iostream classes, but we do need to know the classnames that are // available. -// We need to expose one method in each class to force it to publish. -// But we'd like to expose some of these methods anyway, so no -// problem. -class ios_base { -__published: - enum seekdir { - beg = 0, - cur = 1, - end = 2, +namespace std { + class ostream : virtual public ios { + __published: + ostream(const ostream&) = delete; + + void put(char c); + void flush(); + streampos tellp(); + void seekp(streampos pos); + void seekp(streamoff off, ios_base::seekdir dir); + + protected: + ostream(ostream &&); }; - enum openmode { + class istream : virtual public ios { + __published: + istream(const istream&) = delete; + + int get(); + streampos tellg(); + void seekg(streampos pos); + void seekg(streamoff off, ios_base::seekdir dir); + + protected: + istream(istream &&); }; - // Don't define these lest interrogate get tempted to actually - // substitute in the values, which are implementation-defined. - static const openmode app; - static const openmode binary; - static const openmode in; - static const openmode out; - static const openmode trunc; -protected: - // Force this to be a non-trivial type. - ios_base() {}; -private: - ios_base(const ios_base &); -}; -class ios : public ios_base { -__published: - typedef long fmtflags; + class iostream : public istream, public ostream { + __published: + iostream(const iostream&) = delete; - bool good() const; - bool eof() const; - bool fail() const; - bool bad() const; - void clear(); + void flush(); -protected: - ios(); -}; + protected: + iostream(iostream &&); + }; -// We actually want to wrap streampos as streamoff. -#define streampos streamoff + class ofstream : public ostream { + __published: + ofstream(); + void close(); + }; + class ifstream : public istream { + __published: + ifstream(); + void close(); + }; + class fstream : public iostream { + __published: + fstream(); + void close(); + }; -class ostream : virtual public ios { -__published: - ostream(const ostream&) = delete; - - void put(char c); - void flush(); - streampos tellp(); - void seekp(streampos pos); - void seekp(streamoff off, ios_base::seekdir dir); - -protected: - ostream(ostream &&); -}; -class istream : virtual public ios { -__published: - istream(const istream&) = delete; - - int get(); - streampos tellg(); - void seekg(streampos pos); - void seekg(streamoff off, ios_base::seekdir dir); - -protected: - istream(istream &&); -}; -class iostream : public istream, public ostream { -__published: - iostream(const iostream&) = delete; - - void flush(); - -protected: - iostream(iostream &&); -}; - -class ofstream : public ostream { -__published: - ofstream(); - void close(); -}; -class ifstream : public istream { -__published: - ifstream(); - void close(); -}; -class fstream : public iostream { -__published: - fstream(); - void close(); -}; - -class ostringstream : public ostream {}; -class istringstream : public istream {}; -class stringstream : public iostream {}; -class streambuf {}; - -extern istream cin; -extern ostream cout; -extern ostream cerr; + extern istream cin; + extern ostream cout; + extern ostream cerr; +} #endif diff --git a/dtool/src/parser-inc/mutex b/dtool/src/parser-inc/mutex new file mode 100644 index 0000000000..b05214e512 --- /dev/null +++ b/dtool/src/parser-inc/mutex @@ -0,0 +1,28 @@ +#pragma once + +namespace std { + class mutex; + class recursive_mutex; + class timed_mutex; + class recursive_timed_mutex; + + struct defer_lock_t { + explicit defer_lock_t() = default; + }; + inline constexpr defer_lock_t defer_lock {}; + + struct try_to_lock_t { + explicit try_to_lock_t() = default; + }; + inline constexpr try_to_lock_t try_to_lock {}; + + struct adopt_lock_t { + explicit adopt_lock_t() = default; + }; + inline constexpr adopt_lock_t adopt_lock {}; + + template class lock_guard; + template class unique_lock; + + struct once_flag; +} diff --git a/dtool/src/parser-inc/new b/dtool/src/parser-inc/new new file mode 100644 index 0000000000..2771be683a --- /dev/null +++ b/dtool/src/parser-inc/new @@ -0,0 +1,13 @@ +#pragma once + +namespace std { + class bad_alloc; + class bad_array_new_length; + + struct nothrow_t { + explicit nothrow_t() = default; + }; + extern const nothrow_t nothrow; + + using new_handler = void (*)(); +} diff --git a/dtool/src/parser-inc/ostream b/dtool/src/parser-inc/ostream new file mode 100644 index 0000000000..fb7f7ea51e --- /dev/null +++ b/dtool/src/parser-inc/ostream @@ -0,0 +1,12 @@ +#pragma once + +namespace std { + template + std::basic_ostream &ends(std::basic_ostream &os); + + template + std::basic_ostream &flush(std::basic_ostream &os); + + template + std::basic_ostream &endl(std::basic_ostream &os); +} diff --git a/dtool/src/parser-inc/stdcompare.h b/dtool/src/parser-inc/stdcompare.h index 09c0b7d388..bbcc1bf694 100644 --- a/dtool/src/parser-inc/stdcompare.h +++ b/dtool/src/parser-inc/stdcompare.h @@ -24,7 +24,7 @@ class less { public: }; -template > +template > class hash_compare { public: }; diff --git a/dtool/src/parser-inc/stdlib.h b/dtool/src/parser-inc/stdlib.h index 74093ee881..cb05992816 100644 --- a/dtool/src/parser-inc/stdlib.h +++ b/dtool/src/parser-inc/stdlib.h @@ -1 +1,6 @@ +#pragma once + #include + +#define EXIT_SUCCESS 0 +#define EXIT_FAILURE 1 diff --git a/dtool/src/parser-inc/stdtypedefs.h b/dtool/src/parser-inc/stdtypedefs.h index f971d7e1f2..873ba9425d 100644 --- a/dtool/src/parser-inc/stdtypedefs.h +++ b/dtool/src/parser-inc/stdtypedefs.h @@ -46,7 +46,9 @@ struct timeval; #else #define NULL ((void *)0) #endif -typedef decltype(nullptr) nullptr_t; +namespace std { + typedef decltype(nullptr) nullptr_t; +} // One day, we might extend interrogate to be able to parse this, // but we currently don't need it. diff --git a/dtool/src/parser-inc/streambuf b/dtool/src/parser-inc/streambuf new file mode 100644 index 0000000000..b46f0faef3 --- /dev/null +++ b/dtool/src/parser-inc/streambuf @@ -0,0 +1,14 @@ +#pragma once + +namespace std { + template class char_traits; + template<> class char_traits; + template<> class char_traits; + template<> class char_traits; + template<> class char_traits; + + template > class basic_streambuf; + + typedef basic_streambuf streambuf; + typedef basic_streambuf wstreambuf; +} diff --git a/dtool/src/parser-inc/string b/dtool/src/parser-inc/string index 4ca8f3fa12..841e6fd7c6 100644 --- a/dtool/src/parser-inc/string +++ b/dtool/src/parser-inc/string @@ -21,10 +21,35 @@ #define STRING_H #include +#include +#include namespace std { - template - class char_traits; + template struct char_traits; + + template<> struct char_traits { + using char_type = char; + using int_type = int; + using state_type = mbstate_t; + }; + + template<> struct char_traits { + using char_type = char16_t; + using int_type = uint_least16_t; + using state_type = mbstate_t; + }; + + template<> struct char_traits { + using char_type = char32_t; + using int_type = uint_least32_t; + using state_type = mbstate_t; + }; + + template<> struct char_traits { + using char_type = wchar_t; + using int_type = wint_t; + using state_type = mbstate_t; + }; template class basic_string { diff --git a/dtool/src/parser-inc/unordered_map b/dtool/src/parser-inc/unordered_map index e3c6220d35..035932bd49 100644 --- a/dtool/src/parser-inc/unordered_map +++ b/dtool/src/parser-inc/unordered_map @@ -24,9 +24,10 @@ #include #include #include +#include namespace std { - + template , diff --git a/dtool/src/parser-inc/unordered_set b/dtool/src/parser-inc/unordered_set index 766161d12b..53b6d794c8 100644 --- a/dtool/src/parser-inc/unordered_set +++ b/dtool/src/parser-inc/unordered_set @@ -24,6 +24,7 @@ #include #include #include +#include namespace std { @@ -46,7 +47,7 @@ namespace std { typedef typename allocator_type::const_reference const_reference; typedef size_t size_type; typedef std::ptrdiff_t difference_type; - + class iterator; class const_iterator; class local_iterator; diff --git a/dtool/src/parser-inc/utility b/dtool/src/parser-inc/utility new file mode 100644 index 0000000000..119814b5c3 --- /dev/null +++ b/dtool/src/parser-inc/utility @@ -0,0 +1,16 @@ +#pragma once + +#include + +namespace std { + template void swap(T &a, T &b); + template void swap(T (&a)[N], T (&b)[N]); + + template struct remove_reference {typedef T type;}; + template struct remove_reference {typedef T type;}; + template struct remove_reference {typedef T type;}; + + template constexpr remove_reference::type &&move(T &&) noexcept; + + template struct pair; +} diff --git a/dtool/src/parser-inc/vector b/dtool/src/parser-inc/vector index fb27a78c0d..e83a5ff911 100644 --- a/dtool/src/parser-inc/vector +++ b/dtool/src/parser-inc/vector @@ -22,6 +22,8 @@ #include +inline namespace std { + template class vector { public: @@ -40,4 +42,6 @@ public: typedef size_t size_type; }; +} + #endif diff --git a/dtool/src/prc/androidLogStream.cxx b/dtool/src/prc/androidLogStream.cxx index 6427b9163a..ef05db96ee 100644 --- a/dtool/src/prc/androidLogStream.cxx +++ b/dtool/src/prc/androidLogStream.cxx @@ -56,7 +56,7 @@ AndroidLogStream::AndroidLogStreamBuf:: */ int AndroidLogStream::AndroidLogStreamBuf:: sync() { - streamsize n = pptr() - pbase(); + std::streamsize n = pptr() - pbase(); // Write the characters that remain in the buffer. for (char *p = pbase(); p < pptr(); ++p) { @@ -73,7 +73,7 @@ sync() { */ int AndroidLogStream::AndroidLogStreamBuf:: overflow(int ch) { - streamsize n = pptr() - pbase(); + std::streamsize n = pptr() - pbase(); if (n != 0 && sync() != 0) { return EOF; @@ -107,7 +107,7 @@ write_char(char c) { */ AndroidLogStream:: AndroidLogStream(int priority) : - ostream(new AndroidLogStreamBuf(priority)) { + std::ostream(new AndroidLogStreamBuf(priority)) { } /** @@ -122,11 +122,11 @@ AndroidLogStream:: * Returns an AndroidLogStream suitable for writing log messages with the * indicated severity. */ -ostream &AndroidLogStream:: +std::ostream &AndroidLogStream:: out(NotifySeverity severity) { - static AndroidLogStream* streams[NS_fatal + 1] = {NULL}; + static AndroidLogStream* streams[NS_fatal + 1] = {nullptr}; - if (streams[severity] == NULL) { + if (streams[severity] == nullptr) { int priority = ANDROID_LOG_UNKNOWN; if (severity != NS_unspecified) { priority = ((int)severity) + 1; diff --git a/dtool/src/prc/androidLogStream.h b/dtool/src/prc/androidLogStream.h index a565a348a3..aa50c8d7af 100644 --- a/dtool/src/prc/androidLogStream.h +++ b/dtool/src/prc/androidLogStream.h @@ -25,9 +25,9 @@ /** * This is a type of ostream that writes each line to the Android log. */ -class AndroidLogStream : public ostream { +class AndroidLogStream : public std::ostream { private: - class AndroidLogStreamBuf : public streambuf { + class AndroidLogStreamBuf : public std::streambuf { public: AndroidLogStreamBuf(int priority); virtual ~AndroidLogStreamBuf(); @@ -40,15 +40,15 @@ private: void write_char(char c); int _priority; - string _tag; - string _data; + std::string _tag; + std::string _data; }; AndroidLogStream(int priority); public: virtual ~AndroidLogStream(); - static ostream &out(NotifySeverity severity); + static std::ostream &out(NotifySeverity severity); }; #endif // ANDROID diff --git a/dtool/src/prc/configDeclaration.I b/dtool/src/prc/configDeclaration.I index a93fbdab10..670f49e38a 100644 --- a/dtool/src/prc/configDeclaration.I +++ b/dtool/src/prc/configDeclaration.I @@ -49,7 +49,7 @@ get_variable() const { * text defined for the variable in the .prc file (or passed to * ConfigPage::make_declaration()). */ -INLINE const string &ConfigDeclaration:: +INLINE const std::string &ConfigDeclaration:: get_string_value() const { return _string_value; } @@ -58,7 +58,7 @@ get_string_value() const { * Changes the value assigned to this variable. */ INLINE void ConfigDeclaration:: -set_string_value(const string &string_value) { +set_string_value(const std::string &string_value) { _string_value = string_value; _got_words = false; invalidate_cache(); @@ -145,12 +145,12 @@ has_double_word(size_t n) const { * Returns the string value of the nth word of the declaration's value, or * empty string if there is no nth value. See also has_string_word(). */ -INLINE string ConfigDeclaration:: +INLINE std::string ConfigDeclaration:: get_string_word(size_t n) const { if (has_string_word(n)) { return _words[n]._str; } - return string(); + return std::string(); } /** @@ -225,8 +225,8 @@ get_decl_seq() const { return _decl_seq; } -INLINE ostream & -operator << (ostream &out, const ConfigDeclaration &decl) { +INLINE std::ostream & +operator << (std::ostream &out, const ConfigDeclaration &decl) { decl.output(out); return out; } diff --git a/dtool/src/prc/configDeclaration.cxx b/dtool/src/prc/configDeclaration.cxx index d692bec013..7cbfa5ba6e 100644 --- a/dtool/src/prc/configDeclaration.cxx +++ b/dtool/src/prc/configDeclaration.cxx @@ -17,6 +17,8 @@ #include "pstrtod.h" #include "string_utils.h" +using std::string; + /** * Use the ConfigPage::make_declaration() interface to create a new * declaration. @@ -133,7 +135,7 @@ set_double_word(size_t n, double value) { * */ void ConfigDeclaration:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_variable()->get_name() << " " << get_string_value(); } @@ -141,7 +143,7 @@ output(ostream &out) const { * */ void ConfigDeclaration:: -write(ostream &out) const { +write(std::ostream &out) const { out << get_variable()->get_name() << " " << get_string_value(); // if (!get_variable()->is_used()) { out << " (not used)"; } out << "\n"; diff --git a/dtool/src/prc/configDeclaration.h b/dtool/src/prc/configDeclaration.h index 9a74acd8d2..38129670d5 100644 --- a/dtool/src/prc/configDeclaration.h +++ b/dtool/src/prc/configDeclaration.h @@ -33,7 +33,7 @@ class ConfigVariableCore; class EXPCL_DTOOL_PRC ConfigDeclaration : public ConfigFlags { private: ConfigDeclaration(ConfigPage *page, ConfigVariableCore *variable, - const string &string_value, int decl_seq); + const std::string &string_value, int decl_seq); ~ConfigDeclaration(); public: @@ -45,8 +45,8 @@ PUBLISHED: MAKE_PROPERTY(page, get_page); MAKE_PROPERTY(variable, get_variable); - INLINE const string &get_string_value() const; - INLINE void set_string_value(const string &value); + INLINE const std::string &get_string_value() const; + INLINE void set_string_value(const std::string &value); INLINE size_t get_num_words() const; @@ -56,13 +56,13 @@ PUBLISHED: INLINE bool has_int64_word(size_t n) const; INLINE bool has_double_word(size_t n) const; - INLINE string get_string_word(size_t n) const; + INLINE std::string get_string_word(size_t n) const; INLINE bool get_bool_word(size_t n) const; INLINE int get_int_word(size_t n) const; INLINE int64_t get_int64_word(size_t n) const; INLINE double get_double_word(size_t n) const; - void set_string_word(size_t n, const string &value); + void set_string_word(size_t n, const std::string &value); void set_bool_word(size_t n, bool value); void set_int_word(size_t n, int value); void set_int64_word(size_t n, int64_t value); @@ -70,12 +70,12 @@ PUBLISHED: INLINE int get_decl_seq() const; - void output(ostream &out) const; - void write(ostream &out) const; + void output(std::ostream &out) const; + void write(std::ostream &out) const; public: - static size_t extract_words(const string &str, vector_string &words); - static string downcase(const string &s); + static size_t extract_words(const std::string &str, vector_string &words); + static std::string downcase(const std::string &s); private: void get_words(); @@ -87,7 +87,7 @@ private: private: ConfigPage *_page; ConfigVariableCore *_variable; - string _string_value; + std::string _string_value; int _decl_seq; enum WordFlags { @@ -103,7 +103,7 @@ private: class Word { public: - string _str; + std::string _str; bool _bool; int _int; int64_t _int_64; @@ -111,14 +111,14 @@ private: short _flags; }; - typedef vector Words; + typedef std::vector Words; Words _words; bool _got_words; friend class ConfigPage; }; -INLINE ostream &operator << (ostream &out, const ConfigDeclaration &decl); +INLINE std::ostream &operator << (std::ostream &out, const ConfigDeclaration &decl); #include "configDeclaration.I" diff --git a/dtool/src/prc/configFlags.cxx b/dtool/src/prc/configFlags.cxx index 7d9fb90eec..4613dc4615 100644 --- a/dtool/src/prc/configFlags.cxx +++ b/dtool/src/prc/configFlags.cxx @@ -18,8 +18,8 @@ TVOLATILE AtomicAdjust::Integer ConfigFlags::_global_modified; /** * */ -ostream & -operator << (ostream &out, ConfigFlags::ValueType type) { +std::ostream & +operator << (std::ostream &out, ConfigFlags::ValueType type) { switch (type) { case ConfigFlags::VT_undefined: return out << "undefined"; diff --git a/dtool/src/prc/configFlags.h b/dtool/src/prc/configFlags.h index 23dfd3fb30..f4b95757d6 100644 --- a/dtool/src/prc/configFlags.h +++ b/dtool/src/prc/configFlags.h @@ -67,7 +67,7 @@ private: static TVOLATILE AtomicAdjust::Integer _global_modified; }; -ostream &operator << (ostream &out, ConfigFlags::ValueType type); +std::ostream &operator << (std::ostream &out, ConfigFlags::ValueType type); #include "configFlags.I" diff --git a/dtool/src/prc/configPage.I b/dtool/src/prc/configPage.I index e4ed5ccf60..2624f6a60b 100644 --- a/dtool/src/prc/configPage.I +++ b/dtool/src/prc/configPage.I @@ -33,7 +33,7 @@ operator < (const ConfigPage &other) const { * Returns the name of the page. If the page was loaded from a .prc file, * this is usually the filename. */ -INLINE const string &ConfigPage:: +INLINE const std::string &ConfigPage:: get_name() const { return _name; } @@ -109,7 +109,7 @@ set_trust_level(int trust_level) { * Returns the raw binary signature that was found in the prc file, if any. * This method is probably not terribly useful for most applications. */ -INLINE const string &ConfigPage:: +INLINE const std::string &ConfigPage:: get_signature() const { return _signature; } @@ -124,8 +124,8 @@ make_dirty() { _trust_level = 0; } -INLINE ostream & -operator << (ostream &out, const ConfigPage &page) { +INLINE std::ostream & +operator << (std::ostream &out, const ConfigPage &page) { page.output(out); return out; } diff --git a/dtool/src/prc/configPage.cxx b/dtool/src/prc/configPage.cxx index 981caadf87..b7f1d06bd9 100644 --- a/dtool/src/prc/configPage.cxx +++ b/dtool/src/prc/configPage.cxx @@ -25,8 +25,12 @@ #include "openssl/evp.h" #endif -ConfigPage *ConfigPage::_default_page = NULL; -ConfigPage *ConfigPage::_local_page = NULL; +using std::istream; +using std::ostream; +using std::string; + +ConfigPage *ConfigPage::_default_page = nullptr; +ConfigPage *ConfigPage::_local_page = nullptr; /** * The constructor is private because a ConfigPage should be constructed via @@ -58,7 +62,7 @@ ConfigPage:: */ ConfigPage *ConfigPage:: get_default_page() { - if (_default_page == (ConfigPage *)NULL) { + if (_default_page == nullptr) { _default_page = new ConfigPage("default", false, 0); } return _default_page; @@ -71,7 +75,7 @@ get_default_page() { */ ConfigPage *ConfigPage:: get_local_page() { - if (_local_page == (ConfigPage *)NULL) { + if (_local_page == nullptr) { _local_page = new ConfigPage("local", false, 0); } return _local_page; @@ -142,7 +146,7 @@ read_prc(istream &in) { // Look for the first line in the buffer.. char *newline = (char *)memchr((void *)buffer, '\n', count); - if (newline == (char *)NULL) { + if (newline == nullptr) { // The buffer was one long line. Huh. prev_line += string(buffer, count); @@ -154,7 +158,7 @@ read_prc(istream &in) { // Now look for the next line, etc. char *start = newline + 1; newline = (char *)memchr((void *)start, '\n', buffer_end - start); - while (newline != (char *)NULL) { + while (newline != nullptr) { length = newline - start; read_prc_line(string(start, length + 1)); start = newline + 1; @@ -189,7 +193,7 @@ read_prc(istream &in) { int num_keys = pkr->get_num_keys(); for (int i = 1; i < num_keys && _trust_level == 0; i++) { EVP_PKEY *pkey = pkr->get_key(i); - if (pkey != (EVP_PKEY *)NULL) { + if (pkey != nullptr) { int verify_result = EVP_VerifyFinal((EVP_MD_CTX *)_md_ctx, (unsigned char *)_signature.data(), @@ -283,7 +287,7 @@ get_num_declarations() const { */ const ConfigDeclaration *ConfigPage:: get_declaration(size_t n) const { - nassertr(n < _declarations.size(), (ConfigDeclaration *)NULL); + nassertr(n < _declarations.size(), nullptr); return _declarations[n]; } @@ -294,7 +298,7 @@ get_declaration(size_t n) const { */ ConfigDeclaration *ConfigPage:: modify_declaration(size_t n) { - nassertr(n < _declarations.size(), (ConfigDeclaration *)NULL); + nassertr(n < _declarations.size(), nullptr); return _declarations[n]; } @@ -340,7 +344,7 @@ output(ostream &out) const { */ void ConfigPage:: output_brief_signature(ostream &out) const { - size_t num_bytes = min(_signature.size(), (size_t)8); + size_t num_bytes = std::min(_signature.size(), (size_t)8); for (size_t p = 0; p < num_bytes; ++p) { unsigned int byte = _signature[p]; diff --git a/dtool/src/prc/configPage.h b/dtool/src/prc/configPage.h index 72659fe096..8dd0d822c1 100644 --- a/dtool/src/prc/configPage.h +++ b/dtool/src/prc/configPage.h @@ -29,7 +29,7 @@ class ConfigVariableCore; */ class EXPCL_DTOOL_PRC ConfigPage { private: - ConfigPage(const string &name, bool implicit_load, int page_seq); + ConfigPage(const std::string &name, bool implicit_load, int page_seq); ~ConfigPage(); public: @@ -39,7 +39,7 @@ PUBLISHED: static ConfigPage *get_default_page(); static ConfigPage *get_local_page(); - INLINE const string &get_name() const; + INLINE const std::string &get_name() const; MAKE_PROPERTY(name, get_name); INLINE bool is_special() const; @@ -54,48 +54,48 @@ PUBLISHED: INLINE int get_page_seq() const; INLINE int get_trust_level() const; INLINE void set_trust_level(int trust_level); - INLINE const string &get_signature() const; + INLINE const std::string &get_signature() const; MAKE_PROPERTY(page_seq, get_page_seq); MAKE_PROPERTY(trust_level, get_trust_level, set_trust_level); MAKE_PROPERTY(signature, get_signature); void clear(); - bool read_prc(istream &in); - bool read_encrypted_prc(istream &in, const string &password); + bool read_prc(std::istream &in); + bool read_encrypted_prc(std::istream &in, const std::string &password); - ConfigDeclaration *make_declaration(const string &variable, const string &value); - ConfigDeclaration *make_declaration(ConfigVariableCore *variable, const string &value); + ConfigDeclaration *make_declaration(const std::string &variable, const std::string &value); + ConfigDeclaration *make_declaration(ConfigVariableCore *variable, const std::string &value); bool delete_declaration(ConfigDeclaration *decl); size_t get_num_declarations() const; const ConfigDeclaration *get_declaration(size_t n) const; ConfigDeclaration *modify_declaration(size_t n); - string get_variable_name(size_t n) const; - string get_string_value(size_t n) const; + std::string get_variable_name(size_t n) const; + std::string get_string_value(size_t n) const; bool is_variable_used(size_t n) const; MAKE_SEQ_PROPERTY(declarations, get_num_declarations, modify_declaration); - void output(ostream &out) const; - void output_brief_signature(ostream &out) const; - void write(ostream &out) const; + void output(std::ostream &out) const; + void output_brief_signature(std::ostream &out) const; + void write(std::ostream &out) const; private: INLINE void make_dirty(); - void read_prc_line(const string &line); + void read_prc_line(const std::string &line); static unsigned int hex_digit(unsigned char digit); - string _name; + std::string _name; bool _implicit_load; int _page_seq; int _sort; int _next_decl_seq; int _trust_level; - typedef vector Declarations; + typedef std::vector Declarations; Declarations _declarations; - string _signature; + std::string _signature; #ifdef HAVE_OPENSSL // This maintains the hash of the prc file as we are scanning it, so we can @@ -109,7 +109,7 @@ private: friend class ConfigPageManager; }; -INLINE ostream &operator << (ostream &out, const ConfigPage &page); +INLINE std::ostream &operator << (std::ostream &out, const ConfigPage &page); #include "configPage.I" diff --git a/dtool/src/prc/configPageManager.I b/dtool/src/prc/configPageManager.I index 16dbeb3e6c..30e6c64950 100644 --- a/dtool/src/prc/configPageManager.I +++ b/dtool/src/prc/configPageManager.I @@ -60,9 +60,9 @@ get_num_prc_patterns() const { * Returns the nth filename pattern that will be considered a match as a valid * config file. See get_num_prc_patterns(). */ -INLINE string ConfigPageManager:: +INLINE std::string ConfigPageManager:: get_prc_pattern(size_t n) const { - nassertr(n < _prc_patterns.size(), string()); + nassertr(n < _prc_patterns.size(), std::string()); return _prc_patterns[n].get_pattern(); } @@ -80,9 +80,9 @@ get_num_prc_encrypted_patterns() const { * Returns the nth filename pattern that will be considered a match as a valid * encrypted config file. See get_num_prc_encrypted_patterns(). */ -INLINE string ConfigPageManager:: +INLINE std::string ConfigPageManager:: get_prc_encrypted_pattern(size_t n) const { - nassertr(n < _prc_patterns.size(), string()); + nassertr(n < _prc_patterns.size(), std::string()); return _prc_encrypted_patterns[n].get_pattern(); } @@ -100,9 +100,9 @@ get_num_prc_executable_patterns() const { * Returns the nth filename pattern that will be considered a match as a valid * executable-style config file. See get_num_prc_executable_patterns(). */ -INLINE string ConfigPageManager:: +INLINE std::string ConfigPageManager:: get_prc_executable_pattern(size_t n) const { - nassertr(n < _prc_patterns.size(), string()); + nassertr(n < _prc_patterns.size(), std::string()); return _prc_executable_patterns[n].get_pattern(); } @@ -123,7 +123,7 @@ get_num_implicit_pages() const { INLINE ConfigPage *ConfigPageManager:: get_implicit_page(size_t n) const { check_sort_pages(); - nassertr(n < _implicit_pages.size(), (ConfigPage *)NULL); + nassertr(n < _implicit_pages.size(), nullptr); return _implicit_pages[n]; } @@ -144,7 +144,7 @@ get_num_explicit_pages() const { INLINE ConfigPage *ConfigPageManager:: get_explicit_page(size_t n) const { check_sort_pages(); - nassertr(n < _explicit_pages.size(), (ConfigPage *)NULL); + nassertr(n < _explicit_pages.size(), nullptr); return _explicit_pages[n]; } @@ -169,8 +169,8 @@ check_sort_pages() const { } } -INLINE ostream & -operator << (ostream &out, const ConfigPageManager &pageMgr) { +INLINE std::ostream & +operator << (std::ostream &out, const ConfigPageManager &pageMgr) { pageMgr.output(out); return out; } diff --git a/dtool/src/prc/configPageManager.cxx b/dtool/src/prc/configPageManager.cxx index 2f584bd0c5..72e00f0189 100644 --- a/dtool/src/prc/configPageManager.cxx +++ b/dtool/src/prc/configPageManager.cxx @@ -13,6 +13,7 @@ #include "configPageManager.h" #include "configDeclaration.h" +#include "configVariableBool.h" #include "configVariableString.h" #include "configPage.h" #include "prcKeyRegistry.h" @@ -41,7 +42,9 @@ #include #endif -ConfigPageManager *ConfigPageManager::_global_ptr = NULL; +using std::string; + +ConfigPageManager *ConfigPageManager::_global_ptr = nullptr; /** * The constructor is private (actually, just protected, but only to avoid a @@ -308,7 +311,7 @@ reload_implicit_pages() { // Use a set to ensure that we only visit each directory once, even if it // appears multiple times (under different aliases!) in the path. - set unique_dirnames; + std::set unique_dirnames; // We walk through the list of directories in forward order, so that the // most important directories are visited first. @@ -374,7 +377,7 @@ reload_implicit_pages() { _implicit_pages.push_back(page); _pages_sorted = false; - istringstream in(blobinfo->prc_data); + std::istringstream in(blobinfo->prc_data); page->read_prc(in); } @@ -533,7 +536,7 @@ delete_explicit_page(ConfigPage *page) { * */ void ConfigPageManager:: -output(ostream &out) const { +output(std::ostream &out) const { out << "ConfigPageManager, " << _explicit_pages.size() + _implicit_pages.size() << " pages."; @@ -543,7 +546,7 @@ output(ostream &out) const { * */ void ConfigPageManager:: -write(ostream &out) const { +write(std::ostream &out) const { check_sort_pages(); out << _explicit_pages.size() << " explicit pages:\n"; @@ -587,7 +590,7 @@ write(ostream &out) const { */ ConfigPageManager *ConfigPageManager:: get_global_ptr() { - if (_global_ptr == (ConfigPageManager *)NULL) { + if (_global_ptr == nullptr) { _global_ptr = new ConfigPageManager; } return _global_ptr; @@ -644,7 +647,7 @@ scan_auto_prc_dir(Filename &prc_dir) const { } // Didn't find it; too bad. - cerr << "Warning: unable to auto-locate config files in directory named by \"" + std::cerr << "Warning: unable to auto-locate config files in directory named by \"" << prc_dir << "\".\n"; return false; } diff --git a/dtool/src/prc/configPageManager.h b/dtool/src/prc/configPageManager.h index 1ad8f6c3bd..5afba59796 100644 --- a/dtool/src/prc/configPageManager.h +++ b/dtool/src/prc/configPageManager.h @@ -41,15 +41,15 @@ PUBLISHED: INLINE DSearchPath &get_search_path(); INLINE size_t get_num_prc_patterns() const; - INLINE string get_prc_pattern(size_t n) const; + INLINE std::string get_prc_pattern(size_t n) const; INLINE size_t get_num_prc_encrypted_patterns() const; - INLINE string get_prc_encrypted_pattern(size_t n) const; + INLINE std::string get_prc_encrypted_pattern(size_t n) const; INLINE size_t get_num_prc_executable_patterns() const; - INLINE string get_prc_executable_pattern(size_t n) const; + INLINE std::string get_prc_executable_pattern(size_t n) const; - ConfigPage *make_explicit_page(const string &name); + ConfigPage *make_explicit_page(const std::string &name); bool delete_explicit_page(ConfigPage *page); INLINE size_t get_num_implicit_pages() const; @@ -58,8 +58,8 @@ PUBLISHED: INLINE size_t get_num_explicit_pages() const; INLINE ConfigPage *get_explicit_page(size_t n) const; - void output(ostream &out) const; - void write(ostream &out) const; + void output(std::ostream &out) const; + void write(std::ostream &out) const; static ConfigPageManager *get_global_ptr(); @@ -76,7 +76,7 @@ private: void config_initialized(); - typedef vector Pages; + typedef std::vector Pages; Pages _implicit_pages; Pages _explicit_pages; bool _pages_sorted; @@ -87,7 +87,7 @@ private: DSearchPath _search_path; - typedef vector Globs; + typedef std::vector Globs; Globs _prc_patterns; Globs _prc_encrypted_patterns; Globs _prc_executable_patterns; @@ -105,12 +105,12 @@ private: int _file_flags; Filename _filename; }; - typedef vector ConfigFiles; + typedef std::vector ConfigFiles; static ConfigPageManager *_global_ptr; }; -INLINE ostream &operator << (ostream &out, const ConfigPageManager &pageMgr); +INLINE std::ostream &operator << (std::ostream &out, const ConfigPageManager &pageMgr); #include "configPageManager.I" diff --git a/dtool/src/prc/configVariable.I b/dtool/src/prc/configVariable.I index b46bc63529..53d73ff4c8 100644 --- a/dtool/src/prc/configVariable.I +++ b/dtool/src/prc/configVariable.I @@ -16,7 +16,7 @@ * ConfigVariableFoo derived class. */ INLINE ConfigVariable:: -ConfigVariable(const string &name, ConfigVariable::ValueType value_type) : +ConfigVariable(const std::string &name, ConfigVariable::ValueType value_type) : ConfigVariableBase(name, value_type) { } @@ -26,8 +26,8 @@ ConfigVariable(const string &name, ConfigVariable::ValueType value_type) : * ConfigVariableFoo derived class. */ INLINE ConfigVariable:: -ConfigVariable(const string &name, ConfigVariable::ValueType value_type, - const string &description, int flags) : +ConfigVariable(const std::string &name, ConfigVariable::ValueType value_type, + const std::string &description, int flags) : ConfigVariableBase(name, value_type, description, flags) { } @@ -38,7 +38,7 @@ ConfigVariable(const string &name, ConfigVariable::ValueType value_type, * ConfigVariable of a specific type, without having to know what type it is. */ INLINE ConfigVariable:: -ConfigVariable(const string &name) : +ConfigVariable(const std::string &name) : ConfigVariableBase(name, VT_undefined) { _core->set_used(); @@ -57,16 +57,16 @@ INLINE ConfigVariable:: */ INLINE const ConfigDeclaration *ConfigVariable:: get_default_value() const { - nassertr(is_constructed(), (ConfigDeclaration *)NULL); + nassertr(is_constructed(), nullptr); return _core->get_default_value(); } /** * Returns the toplevel value of the variable, formatted as a string. */ -INLINE const string &ConfigVariable:: +INLINE const std::string &ConfigVariable:: get_string_value() const { - nassertr(is_constructed(), *new string()); + nassertr(is_constructed(), *new std::string()); const ConfigDeclaration *decl = _core->get_declaration(0); return decl->get_string_value(); } @@ -77,7 +77,7 @@ get_string_value() const { * clear_local_value() is called. */ INLINE void ConfigVariable:: -set_string_value(const string &string_value) { +set_string_value(const std::string &string_value) { nassertv(is_constructed()); _core->make_local_value()->set_string_value(string_value); } @@ -163,9 +163,9 @@ has_double_word(size_t n) const { * Returns the string value of the nth word of the variable's value, or empty * string if there is no nth value. See also has_string_word(). */ -INLINE string ConfigVariable:: +INLINE std::string ConfigVariable:: get_string_word(size_t n) const { - nassertr(is_constructed(), string()); + nassertr(is_constructed(), std::string()); const ConfigDeclaration *decl = _core->get_declaration(0); return decl->get_string_word(n); } @@ -219,7 +219,7 @@ get_double_word(size_t n) const { * words. */ INLINE void ConfigVariable:: -set_string_word(size_t n, const string &value) { +set_string_word(size_t n, const std::string &value) { nassertv(is_constructed()); _core->make_local_value()->set_string_word(n, value); } @@ -273,7 +273,7 @@ set_double_word(size_t n, double value) { INLINE bool ConfigVariable:: is_constructed() const { #ifndef NDEBUG - if (_core == (ConfigVariableCore *)NULL) { + if (_core == nullptr) { report_unconstructed(); return false; } diff --git a/dtool/src/prc/configVariable.h b/dtool/src/prc/configVariable.h index c4f6d20527..c07f12e453 100644 --- a/dtool/src/prc/configVariable.h +++ b/dtool/src/prc/configVariable.h @@ -30,16 +30,16 @@ */ class EXPCL_DTOOL_PRC ConfigVariable : public ConfigVariableBase { protected: - INLINE ConfigVariable(const string &name, ValueType type); - INLINE ConfigVariable(const string &name, ValueType type, - const string &description, int flags); + INLINE ConfigVariable(const std::string &name, ValueType type); + INLINE ConfigVariable(const std::string &name, ValueType type, + const std::string &description, int flags); PUBLISHED: - INLINE explicit ConfigVariable(const string &name); + INLINE explicit ConfigVariable(const std::string &name); INLINE ~ConfigVariable(); - INLINE const string &get_string_value() const; - INLINE void set_string_value(const string &value); + INLINE const std::string &get_string_value() const; + INLINE void set_string_value(const std::string &value); INLINE void clear_value(); INLINE size_t get_num_words() const; @@ -53,13 +53,13 @@ protected: INLINE bool has_int64_word(size_t n) const; INLINE bool has_double_word(size_t n) const; - INLINE string get_string_word(size_t n) const; + INLINE std::string get_string_word(size_t n) const; INLINE bool get_bool_word(size_t n) const; INLINE int get_int_word(size_t n) const; INLINE int64_t get_int64_word(size_t n) const; INLINE double get_double_word(size_t n) const; - INLINE void set_string_word(size_t n, const string &value); + INLINE void set_string_word(size_t n, const std::string &value); INLINE void set_bool_word(size_t n, bool value); INLINE void set_int_word(size_t n, int value); INLINE void set_int64_word(size_t n, int64_t value); diff --git a/dtool/src/prc/configVariableBase.I b/dtool/src/prc/configVariableBase.I index 09db1c4088..e57bceeb21 100644 --- a/dtool/src/prc/configVariableBase.I +++ b/dtool/src/prc/configVariableBase.I @@ -16,7 +16,7 @@ * ConfigVariableFoo derived class. */ INLINE ConfigVariableBase:: -ConfigVariableBase(const string &name, +ConfigVariableBase(const std::string &name, ConfigVariableBase::ValueType value_type) : _core(ConfigVariableManager::get_global_ptr()->make_variable(name)) { @@ -35,9 +35,9 @@ INLINE ConfigVariableBase:: /** * Returns the name of the variable. */ -INLINE const string &ConfigVariableBase:: +INLINE const std::string &ConfigVariableBase:: get_name() const { - nassertr(_core != (ConfigVariableCore *)NULL, *new string()); + nassertr(_core != nullptr, *new std::string()); return _core->get_name(); } @@ -47,16 +47,16 @@ get_name() const { */ INLINE ConfigVariableBase::ValueType ConfigVariableBase:: get_value_type() const { - nassertr(_core != (ConfigVariableCore *)NULL, VT_undefined); + nassertr(_core != nullptr, VT_undefined); return _core->get_value_type(); } /** * Returns the brief description of this variable, if it has been defined. */ -INLINE const string &ConfigVariableBase:: +INLINE const std::string &ConfigVariableBase:: get_description() const { - nassertr(_core != (ConfigVariableCore *)NULL, *new string()); + nassertr(_core != nullptr, *new std::string()); return _core->get_description(); } @@ -68,7 +68,7 @@ get_description() const { */ INLINE int ConfigVariableBase:: get_flags() const { - nassertr(_core != (ConfigVariableCore *)NULL, 0); + nassertr(_core != nullptr, 0); return _core->get_flags(); } @@ -83,7 +83,7 @@ get_flags() const { */ INLINE bool ConfigVariableBase:: is_closed() const { - nassertr(_core != (ConfigVariableCore *)NULL, false); + nassertr(_core != nullptr, false); return _core->is_closed(); } @@ -99,7 +99,7 @@ is_closed() const { */ INLINE int ConfigVariableBase:: get_trust_level() const { - nassertr(_core != (ConfigVariableCore *)NULL, 0); + nassertr(_core != nullptr, 0); return _core->get_trust_level(); } @@ -110,7 +110,7 @@ get_trust_level() const { */ INLINE bool ConfigVariableBase:: is_dynamic() const { - nassertr(_core != (ConfigVariableCore *)NULL, false); + nassertr(_core != nullptr, false); return _core->is_dynamic(); } @@ -123,7 +123,7 @@ is_dynamic() const { */ INLINE bool ConfigVariableBase:: clear_local_value() { - nassertr(_core != (ConfigVariableCore *)NULL, false); + nassertr(_core != nullptr, false); return _core->clear_local_value(); } @@ -133,7 +133,7 @@ clear_local_value() { */ INLINE bool ConfigVariableBase:: has_local_value() const { - nassertr(_core != (ConfigVariableCore *)NULL, false); + nassertr(_core != nullptr, false); return _core->has_local_value(); } @@ -143,7 +143,7 @@ has_local_value() const { */ INLINE bool ConfigVariableBase:: has_value() const { - nassertr(_core != (ConfigVariableCore *)NULL, false); + nassertr(_core != nullptr, false); return _core->has_value(); } @@ -151,8 +151,8 @@ has_value() const { * */ INLINE void ConfigVariableBase:: -output(ostream &out) const { - nassertv(_core != (ConfigVariableCore *)NULL); +output(std::ostream &out) const { + nassertv(_core != nullptr); _core->output(out); } @@ -160,13 +160,13 @@ output(ostream &out) const { * */ INLINE void ConfigVariableBase:: -write(ostream &out) const { - nassertv(_core != (ConfigVariableCore *)NULL); +write(std::ostream &out) const { + nassertv(_core != nullptr); _core->write(out); } -INLINE ostream & -operator << (ostream &out, const ConfigVariableBase &variable) { +INLINE std::ostream & +operator << (std::ostream &out, const ConfigVariableBase &variable) { variable.output(out); return out; } diff --git a/dtool/src/prc/configVariableBase.cxx b/dtool/src/prc/configVariableBase.cxx index 52b113b79a..0b4e728b94 100644 --- a/dtool/src/prc/configVariableBase.cxx +++ b/dtool/src/prc/configVariableBase.cxx @@ -21,9 +21,9 @@ ConfigVariableBase::Unconstructed *ConfigVariableBase::_unconstructed; * ConfigVariableFoo derived class. */ ConfigVariableBase:: -ConfigVariableBase(const string &name, +ConfigVariableBase(const std::string &name, ConfigVariableBase::ValueType value_type, - const string &description, int flags) : + const std::string &description, int flags) : _core(ConfigVariableManager::get_global_ptr()->make_variable(name)) { #ifndef NDEBUG @@ -55,7 +55,7 @@ ConfigVariableBase(const string &name, void ConfigVariableBase:: record_unconstructed() const { #ifndef NDEBUG - if (_unconstructed == (Unconstructed *)NULL) { + if (_unconstructed == nullptr) { _unconstructed = new Unconstructed; } _unconstructed->insert(this); @@ -69,7 +69,7 @@ record_unconstructed() const { bool ConfigVariableBase:: was_unconstructed() const { #ifndef NDEBUG - if (_unconstructed != (Unconstructed *)NULL) { + if (_unconstructed != nullptr) { Unconstructed::const_iterator ui = _unconstructed->find(this); if (ui != _unconstructed->end()) { return true; diff --git a/dtool/src/prc/configVariableBase.h b/dtool/src/prc/configVariableBase.h index 8bc51a7431..ac256f1e8d 100644 --- a/dtool/src/prc/configVariableBase.h +++ b/dtool/src/prc/configVariableBase.h @@ -44,16 +44,16 @@ */ class EXPCL_DTOOL_PRC ConfigVariableBase : public ConfigFlags { protected: - INLINE ConfigVariableBase(const string &name, ValueType type); - ConfigVariableBase(const string &name, ValueType type, - const string &description, int flags); + INLINE ConfigVariableBase(const std::string &name, ValueType type); + ConfigVariableBase(const std::string &name, ValueType type, + const std::string &description, int flags); INLINE ~ConfigVariableBase(); PUBLISHED: - INLINE const string &get_name() const; + INLINE const std::string &get_name() const; INLINE ValueType get_value_type() const; - INLINE const string &get_description() const; + INLINE const std::string &get_description() const; INLINE int get_flags() const; INLINE bool is_closed() const; INLINE int get_trust_level() const; @@ -70,8 +70,8 @@ PUBLISHED: INLINE bool has_local_value() const; INLINE bool has_value() const; - INLINE void output(ostream &out) const; - INLINE void write(ostream &out) const; + INLINE void output(std::ostream &out) const; + INLINE void write(std::ostream &out) const; protected: void record_unconstructed() const; @@ -83,7 +83,7 @@ protected: static Unconstructed *_unconstructed; }; -INLINE ostream &operator << (ostream &out, const ConfigVariableBase &variable); +INLINE std::ostream &operator << (std::ostream &out, const ConfigVariableBase &variable); #include "configVariableBase.I" diff --git a/dtool/src/prc/configVariableBool.I b/dtool/src/prc/configVariableBool.I index 7eba0820d0..8551815e67 100644 --- a/dtool/src/prc/configVariableBool.I +++ b/dtool/src/prc/configVariableBool.I @@ -15,7 +15,7 @@ * */ INLINE ConfigVariableBool:: -ConfigVariableBool(const string &name) : +ConfigVariableBool(const std::string &name) : ConfigVariable(name, VT_bool), _local_modified(initial_invalid_cache()) { @@ -26,12 +26,12 @@ ConfigVariableBool(const string &name) : * */ INLINE ConfigVariableBool:: -ConfigVariableBool(const string &name, bool default_value, - const string &description, int flags) : +ConfigVariableBool(const std::string &name, bool default_value, + const std::string &description, int flags) : #ifdef PRC_SAVE_DESCRIPTIONS ConfigVariable(name, VT_bool, description, flags), #else - ConfigVariable(name, VT_bool, string(), flags), + ConfigVariable(name, VT_bool, std::string(), flags), #endif _local_modified(initial_invalid_cache()) { @@ -43,12 +43,12 @@ ConfigVariableBool(const string &name, bool default_value, * */ INLINE ConfigVariableBool:: -ConfigVariableBool(const string &name, const string &default_value, - const string &description, int flags) : +ConfigVariableBool(const std::string &name, const std::string &default_value, + const std::string &description, int flags) : #ifdef PRC_SAVE_DESCRIPTIONS ConfigVariable(name, VT_bool, description, flags), #else - ConfigVariable(name, VT_bool, string(), flags), + ConfigVariable(name, VT_bool, std::string(), flags), #endif _local_modified(initial_invalid_cache()) { @@ -115,7 +115,7 @@ get_value() const { INLINE bool ConfigVariableBool:: get_default_value() const { const ConfigDeclaration *decl = ConfigVariable::get_default_value(); - if (decl != (ConfigDeclaration *)NULL) { + if (decl != nullptr) { return decl->get_bool_word(0); } return false; diff --git a/dtool/src/prc/configVariableBool.h b/dtool/src/prc/configVariableBool.h index c955b6b16f..c2c4da14c7 100644 --- a/dtool/src/prc/configVariableBool.h +++ b/dtool/src/prc/configVariableBool.h @@ -22,11 +22,11 @@ */ class EXPCL_DTOOL_PRC ConfigVariableBool : public ConfigVariable { PUBLISHED: - INLINE ConfigVariableBool(const string &name); - INLINE ConfigVariableBool(const string &name, bool default_value, - const string &description = string(), int flags = 0); - INLINE ConfigVariableBool(const string &name, const string &default_value, - const string &description = string(), int flags = 0); + INLINE ConfigVariableBool(const std::string &name); + INLINE ConfigVariableBool(const std::string &name, bool default_value, + const std::string &description = std::string(), int flags = 0); + INLINE ConfigVariableBool(const std::string &name, const std::string &default_value, + const std::string &description = std::string(), int flags = 0); INLINE void operator = (bool value); ALWAYS_INLINE operator bool () const; diff --git a/dtool/src/prc/configVariableCore.I b/dtool/src/prc/configVariableCore.I index 057beb0449..4cb0d05108 100644 --- a/dtool/src/prc/configVariableCore.I +++ b/dtool/src/prc/configVariableCore.I @@ -14,7 +14,7 @@ /** * Returns the name of the variable. */ -INLINE const string &ConfigVariableCore:: +INLINE const std::string &ConfigVariableCore:: get_name() const { return _name; } @@ -40,7 +40,7 @@ get_value_type() const { /** * Returns the brief description of this variable, if it has been defined. */ -INLINE const string &ConfigVariableCore:: +INLINE const std::string &ConfigVariableCore:: get_description() const { return _description; } @@ -118,7 +118,7 @@ set_used() { */ INLINE bool ConfigVariableCore:: has_local_value() const { - return _local_value != (ConfigDeclaration *)NULL; + return _local_value != nullptr; } /** @@ -141,7 +141,7 @@ get_num_references() const { INLINE const ConfigDeclaration *ConfigVariableCore:: get_reference(size_t n) const { check_sort_declarations(); - nassertr(n < _declarations.size(), (ConfigDeclaration *)NULL); + nassertr(n < _declarations.size(), nullptr); return _declarations[n]; } @@ -167,7 +167,7 @@ get_num_trusted_references() const { INLINE const ConfigDeclaration *ConfigVariableCore:: get_trusted_reference(size_t n) const { check_sort_declarations(); - nassertr(n < _trusted_declarations.size(), (ConfigDeclaration *)NULL); + nassertr(n < _trusted_declarations.size(), nullptr); return _trusted_declarations[n]; } @@ -188,7 +188,7 @@ get_num_unique_references() const { INLINE const ConfigDeclaration *ConfigVariableCore:: get_unique_reference(size_t n) const { check_sort_declarations(); - nassertr(n < _unique_declarations.size(), (ConfigDeclaration *)NULL); + nassertr(n < _unique_declarations.size(), nullptr); return _unique_declarations[n]; } @@ -208,8 +208,8 @@ check_sort_declarations() const { } } -INLINE ostream & -operator << (ostream &out, const ConfigVariableCore &variable) { +INLINE std::ostream & +operator << (std::ostream &out, const ConfigVariableCore &variable) { variable.output(out); return out; } diff --git a/dtool/src/prc/configVariableCore.cxx b/dtool/src/prc/configVariableCore.cxx index 7bf355ba3c..8ae104efd8 100644 --- a/dtool/src/prc/configVariableCore.cxx +++ b/dtool/src/prc/configVariableCore.cxx @@ -23,6 +23,8 @@ #include +using std::string; + /** * Use the ConfigVariableManager::make_variable() interface to create a new @@ -34,8 +36,8 @@ ConfigVariableCore(const string &name) : _is_used(false), _value_type(VT_undefined), _flags(0), - _default_value(NULL), - _local_value(NULL), + _default_value(nullptr), + _local_value(nullptr), _declarations_sorted(true), _value_queried(false) { @@ -56,12 +58,12 @@ ConfigVariableCore(const ConfigVariableCore &templ, const string &name) : _value_type(templ._value_type), _description(templ._description), _flags(templ._flags), - _default_value(NULL), - _local_value(NULL), + _default_value(nullptr), + _local_value(nullptr), _declarations_sorted(false), _value_queried(false) { - if (templ._default_value != (ConfigDeclaration *)NULL) { + if (templ._default_value != nullptr) { set_default_value(templ._default_value->get_string_value()); } } @@ -126,9 +128,9 @@ set_flags(int flags) { if ((bits_changed & ~(F_trust_level_mask | F_dconfig)) != 0) { prc_cat->warning() << "changing flags for ConfigVariable " - << get_name() << " from " << hex + << get_name() << " from " << std::hex << (_flags & ~F_trust_level_mask) << " to " - << (flags & ~F_trust_level_mask) << dec << ".\n"; + << (flags & ~F_trust_level_mask) << std::dec << ".\n"; } } @@ -187,7 +189,7 @@ set_description(const string &description) { */ void ConfigVariableCore:: set_default_value(const string &default_value) { - if (_default_value == (ConfigDeclaration *)NULL) { + if (_default_value == nullptr) { // Defining the default value for the first time. ConfigPage *default_page = ConfigPage::get_default_page(); _default_value = default_page->make_declaration(this, default_value); @@ -228,7 +230,7 @@ set_default_value(const string &default_value) { */ ConfigDeclaration *ConfigVariableCore:: make_local_value() { - if (_local_value == (ConfigDeclaration *)NULL) { + if (_local_value == nullptr) { ConfigPage *local_page = ConfigPage::get_local_page(); string string_value = get_declaration(0)->get_string_value(); _local_value = local_page->make_declaration(this, string_value); @@ -253,9 +255,9 @@ make_local_value() { */ bool ConfigVariableCore:: clear_local_value() { - if (_local_value != (ConfigDeclaration *)NULL) { + if (_local_value != nullptr) { ConfigPage::get_local_page()->delete_declaration(_local_value); - _local_value = (ConfigDeclaration *)NULL; + _local_value = nullptr; invalidate_cache(); return true; } @@ -304,7 +306,7 @@ get_num_declarations() const { const ConfigDeclaration *ConfigVariableCore:: get_declaration(size_t n) const { ((ConfigVariableCore *)this)->_value_queried = true; - if (_default_value == (ConfigDeclaration *)NULL) { + if (_default_value == nullptr) { prc_cat->warning() << "value queried before default value set for " << get_name() << ".\n"; @@ -325,7 +327,7 @@ get_declaration(size_t n) const { * */ void ConfigVariableCore:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_declaration(0)->get_string_value(); } @@ -333,7 +335,7 @@ output(ostream &out) const { * */ void ConfigVariableCore:: -write(ostream &out) const { +write(std::ostream &out) const { out << "ConfigVariable " << get_name() << ":\n"; check_sort_declarations(); @@ -350,7 +352,7 @@ write(ostream &out) const { << " (from " << (*di)->get_page()->get_name() << ")\n"; } - if (_default_value != (ConfigDeclaration *)NULL) { + if (_default_value != nullptr) { out << " " << *_default_value << " (default value)\n"; } diff --git a/dtool/src/prc/configVariableCore.h b/dtool/src/prc/configVariableCore.h index 19e03436d2..8849cc401b 100644 --- a/dtool/src/prc/configVariableCore.h +++ b/dtool/src/prc/configVariableCore.h @@ -33,16 +33,16 @@ class ConfigDeclaration; */ class EXPCL_DTOOL_PRC ConfigVariableCore : public ConfigFlags { private: - ConfigVariableCore(const string &name); - ConfigVariableCore(const ConfigVariableCore &templ, const string &name); + ConfigVariableCore(const std::string &name); + ConfigVariableCore(const ConfigVariableCore &templ, const std::string &name); ~ConfigVariableCore(); PUBLISHED: - INLINE const string &get_name() const; + INLINE const std::string &get_name() const; INLINE bool is_used() const; INLINE ValueType get_value_type() const; - INLINE const string &get_description() const; + INLINE const std::string &get_description() const; INLINE int get_flags() const; INLINE bool is_closed() const; INLINE int get_trust_level() const; @@ -51,8 +51,8 @@ PUBLISHED: void set_value_type(ValueType value_type); void set_flags(int flags); - void set_description(const string &description); - void set_default_value(const string &default_value); + void set_description(const std::string &description); + void set_default_value(const std::string &default_value); INLINE void set_used(); ConfigDeclaration *make_local_value(); @@ -77,8 +77,8 @@ PUBLISHED: MAKE_SEQ(get_unique_references, get_num_unique_references, get_unique_reference); MAKE_SEQ_PROPERTY(declarations, get_num_declarations, get_declaration); - void output(ostream &out) const; - void write(ostream &out) const; + void output(std::ostream &out) const; + void write(std::ostream &out) const; MAKE_PROPERTY(name, get_name); MAKE_PROPERTY(used, is_used); @@ -102,15 +102,15 @@ private: void sort_declarations(); private: - string _name; + std::string _name; bool _is_used; ValueType _value_type; - string _description; + std::string _description; int _flags; ConfigDeclaration *_default_value; ConfigDeclaration *_local_value; - typedef vector Declarations; + typedef std::vector Declarations; Declarations _declarations; Declarations _trusted_declarations; Declarations _untrusted_declarations; @@ -122,7 +122,7 @@ private: friend class ConfigVariableManager; }; -INLINE ostream &operator << (ostream &out, const ConfigVariableCore &variable); +INLINE std::ostream &operator << (std::ostream &out, const ConfigVariableCore &variable); #include "configVariableCore.I" diff --git a/dtool/src/prc/configVariableDouble.I b/dtool/src/prc/configVariableDouble.I index 8cd2cd1e91..3075591c0f 100644 --- a/dtool/src/prc/configVariableDouble.I +++ b/dtool/src/prc/configVariableDouble.I @@ -15,7 +15,7 @@ * */ INLINE ConfigVariableDouble:: -ConfigVariableDouble(const string &name) : +ConfigVariableDouble(const std::string &name) : ConfigVariable(name, VT_double), _local_modified(initial_invalid_cache()) { @@ -26,12 +26,12 @@ ConfigVariableDouble(const string &name) : * */ INLINE ConfigVariableDouble:: -ConfigVariableDouble(const string &name, double default_value, - const string &description, int flags) : +ConfigVariableDouble(const std::string &name, double default_value, + const std::string &description, int flags) : #ifdef PRC_SAVE_DESCRIPTIONS ConfigVariable(name, ConfigVariableCore::VT_double, description, flags), #else - ConfigVariable(name, ConfigVariableCore::VT_double, string(), flags), + ConfigVariable(name, ConfigVariableCore::VT_double, std::string(), flags), #endif _local_modified(initial_invalid_cache()) { @@ -43,12 +43,12 @@ ConfigVariableDouble(const string &name, double default_value, * */ INLINE ConfigVariableDouble:: -ConfigVariableDouble(const string &name, const string &default_value, - const string &description, int flags) : +ConfigVariableDouble(const std::string &name, const std::string &default_value, + const std::string &description, int flags) : #ifdef PRC_SAVE_DESCRIPTIONS ConfigVariable(name, ConfigVariableCore::VT_double, description, flags), #else - ConfigVariable(name, ConfigVariableCore::VT_double, string(), flags), + ConfigVariable(name, ConfigVariableCore::VT_double, std::string(), flags), #endif _local_modified(initial_invalid_cache()) { @@ -116,7 +116,7 @@ get_value() const { INLINE double ConfigVariableDouble:: get_default_value() const { const ConfigDeclaration *decl = ConfigVariable::get_default_value(); - if (decl != (ConfigDeclaration *)NULL) { + if (decl != nullptr) { return decl->get_double_word(0); } return 0.0; diff --git a/dtool/src/prc/configVariableDouble.h b/dtool/src/prc/configVariableDouble.h index 49e9585475..12332016ec 100644 --- a/dtool/src/prc/configVariableDouble.h +++ b/dtool/src/prc/configVariableDouble.h @@ -23,12 +23,12 @@ */ class EXPCL_DTOOL_PRC ConfigVariableDouble : public ConfigVariable { PUBLISHED: - INLINE ConfigVariableDouble(const string &name); - INLINE ConfigVariableDouble(const string &name, double default_value, - const string &description = string(), + INLINE ConfigVariableDouble(const std::string &name); + INLINE ConfigVariableDouble(const std::string &name, double default_value, + const std::string &description = std::string(), int flags = 0); - INLINE ConfigVariableDouble(const string &name, const string &default_value, - const string &description = string(), + INLINE ConfigVariableDouble(const std::string &name, const std::string &default_value, + const std::string &description = std::string(), int flags = 0); INLINE void operator = (double value); diff --git a/dtool/src/prc/configVariableEnum.I b/dtool/src/prc/configVariableEnum.I index 04464fcc41..a13076e794 100644 --- a/dtool/src/prc/configVariableEnum.I +++ b/dtool/src/prc/configVariableEnum.I @@ -16,12 +16,12 @@ */ template INLINE ConfigVariableEnum:: -ConfigVariableEnum(const string &name, EnumType default_value, - const string &description, int flags) : +ConfigVariableEnum(const std::string &name, EnumType default_value, + const std::string &description, int flags) : #ifdef PRC_SAVE_DESCRIPTIONS ConfigVariable(name, ConfigVariableCore::VT_enum, description, flags), #else - ConfigVariable(name, ConfigVariableCore::VT_enum, string(), flags), + ConfigVariable(name, ConfigVariableCore::VT_enum, std::string(), flags), #endif _got_default_value(true), _default_value(default_value), @@ -36,12 +36,12 @@ ConfigVariableEnum(const string &name, EnumType default_value, */ template INLINE ConfigVariableEnum:: -ConfigVariableEnum(const string &name, const string &default_value, - const string &description, int flags) : +ConfigVariableEnum(const std::string &name, const std::string &default_value, + const std::string &description, int flags) : #ifdef PRC_SAVE_DESCRIPTIONS ConfigVariable(name, ConfigVariableCore::VT_enum, description, flags), #else - ConfigVariable(name, ConfigVariableCore::VT_enum, string(), flags), + ConfigVariable(name, ConfigVariableCore::VT_enum, std::string(), flags), #endif _got_default_value(true), _default_value(parse_string(default_value)), @@ -126,7 +126,7 @@ INLINE EnumType ConfigVariableEnum:: get_default_value() const { if (!_got_default_value) { const ConfigDeclaration *decl = ConfigVariable::get_default_value(); - if (decl != (ConfigDeclaration *)NULL) { + if (decl != nullptr) { ((ConfigVariableEnum *)this)->_default_value = (EnumType)parse_string(decl->get_string_value()); ((ConfigVariableEnum *)this)->_got_default_value = true; } @@ -159,8 +159,8 @@ set_word(size_t n, EnumType value) { */ template INLINE EnumType ConfigVariableEnum:: -parse_string(const string &value) const { - istringstream strm(value); +parse_string(const std::string &value) const { + std::istringstream strm(value); EnumType result; strm >> result; return result; @@ -172,9 +172,9 @@ parse_string(const string &value) const { * operator. */ template -INLINE string ConfigVariableEnum:: +INLINE std::string ConfigVariableEnum:: format_enum(EnumType value) const { - ostringstream strm; + std::ostringstream strm; strm << value; return strm.str(); } diff --git a/dtool/src/prc/configVariableEnum.h b/dtool/src/prc/configVariableEnum.h index 81f5c91a09..80aaf23b65 100644 --- a/dtool/src/prc/configVariableEnum.h +++ b/dtool/src/prc/configVariableEnum.h @@ -30,11 +30,11 @@ template class ConfigVariableEnum : public ConfigVariable { public: - INLINE ConfigVariableEnum(const string &name, EnumType default_value, - const string &description = string(), + INLINE ConfigVariableEnum(const std::string &name, EnumType default_value, + const std::string &description = std::string(), int flags = 0); - INLINE ConfigVariableEnum(const string &name, const string &default_value, - const string &description = string(), + INLINE ConfigVariableEnum(const std::string &name, const std::string &default_value, + const std::string &description = std::string(), int flags = 0); INLINE ~ConfigVariableEnum(); @@ -54,8 +54,8 @@ public: INLINE void set_word(size_t n, EnumType value); private: - INLINE EnumType parse_string(const string &value) const; - INLINE string format_enum(EnumType value) const; + INLINE EnumType parse_string(const std::string &value) const; + INLINE std::string format_enum(EnumType value) const; private: bool _got_default_value; diff --git a/dtool/src/prc/configVariableFilename.I b/dtool/src/prc/configVariableFilename.I index d84d92dcb0..51013ddfcf 100644 --- a/dtool/src/prc/configVariableFilename.I +++ b/dtool/src/prc/configVariableFilename.I @@ -15,7 +15,7 @@ * */ INLINE ConfigVariableFilename:: -ConfigVariableFilename(const string &name) : +ConfigVariableFilename(const std::string &name) : ConfigVariable(name, VT_filename), _local_modified(initial_invalid_cache()) { @@ -26,12 +26,12 @@ ConfigVariableFilename(const string &name) : * */ INLINE ConfigVariableFilename:: -ConfigVariableFilename(const string &name, const Filename &default_value, - const string &description, int flags) : +ConfigVariableFilename(const std::string &name, const Filename &default_value, + const std::string &description, int flags) : #ifdef PRC_SAVE_DESCRIPTIONS ConfigVariable(name, VT_filename, description, flags), #else - ConfigVariable(name, VT_filename, string(), flags), + ConfigVariable(name, VT_filename, std::string(), flags), #endif _local_modified(initial_invalid_cache()) { @@ -93,7 +93,7 @@ operator [] (size_t n) const { * same thing returned by the string typecast operator, so this function is a * little redundant. */ -INLINE string ConfigVariableFilename:: +INLINE std::string ConfigVariableFilename:: get_fullpath() const { return get_ref_value().get_fullpath(); } @@ -102,7 +102,7 @@ get_fullpath() const { * Returns the directory part of the filename. This is everything in the * filename up to, but not including the rightmost slash. */ -INLINE string ConfigVariableFilename:: +INLINE std::string ConfigVariableFilename:: get_dirname() const { return get_ref_value().get_dirname(); } @@ -111,7 +111,7 @@ get_dirname() const { * Returns the basename part of the filename. This is everything in the * filename after the rightmost slash, including any extensions. */ -INLINE string ConfigVariableFilename:: +INLINE std::string ConfigVariableFilename:: get_basename() const { return get_ref_value().get_basename(); } @@ -121,7 +121,7 @@ get_basename() const { * Returns the full filename--directory and basename parts--except for the * extension. */ -INLINE string ConfigVariableFilename:: +INLINE std::string ConfigVariableFilename:: get_fullpath_wo_extension() const { return get_ref_value().get_fullpath_wo_extension(); } @@ -130,7 +130,7 @@ get_fullpath_wo_extension() const { /** * Returns the basename part of the filename, without the file extension. */ -INLINE string ConfigVariableFilename:: +INLINE std::string ConfigVariableFilename:: get_basename_wo_extension() const { return get_ref_value().get_basename_wo_extension(); } @@ -140,7 +140,7 @@ get_basename_wo_extension() const { * Returns the file extension. This is everything after the rightmost dot, if * there is one, or the empty string if there is not. */ -INLINE string ConfigVariableFilename:: +INLINE std::string ConfigVariableFilename:: get_extension() const { return get_ref_value().get_extension(); } @@ -195,7 +195,7 @@ get_value() const { INLINE Filename ConfigVariableFilename:: get_default_value() const { const ConfigDeclaration *decl = ConfigVariable::get_default_value(); - if (decl != (ConfigDeclaration *)NULL) { + if (decl != nullptr) { return Filename::expand_from(decl->get_string_value()); } return Filename(); diff --git a/dtool/src/prc/configVariableFilename.cxx b/dtool/src/prc/configVariableFilename.cxx index 3939199148..4c8941babd 100644 --- a/dtool/src/prc/configVariableFilename.cxx +++ b/dtool/src/prc/configVariableFilename.cxx @@ -23,12 +23,12 @@ reload_cache() { // thread-safe manner. But chances are that the first time this is called // is at static init time, when there is no risk of data races. static MutexImpl lock; - lock.acquire(); + lock.lock(); // We check again for cache validity since another thread may have beaten // us to the punch while we were waiting for the lock. if (!is_cache_valid(_local_modified)) { - nassertv(_core != (ConfigVariableCore *)NULL); + nassertv(_core != nullptr); const ConfigDeclaration *decl = _core->get_declaration(0); const ConfigPage *page = decl->get_page(); @@ -42,5 +42,5 @@ reload_cache() { mark_cache_valid(_local_modified); } - lock.release(); + lock.unlock(); } diff --git a/dtool/src/prc/configVariableFilename.h b/dtool/src/prc/configVariableFilename.h index 6feb82a24a..7537e22117 100644 --- a/dtool/src/prc/configVariableFilename.h +++ b/dtool/src/prc/configVariableFilename.h @@ -26,9 +26,9 @@ */ class EXPCL_DTOOL_PRC ConfigVariableFilename : public ConfigVariable { PUBLISHED: - INLINE ConfigVariableFilename(const string &name); - INLINE ConfigVariableFilename(const string &name, const Filename &default_value, - const string &description = string(), int flags = 0); + INLINE ConfigVariableFilename(const std::string &name); + INLINE ConfigVariableFilename(const std::string &name, const Filename &default_value, + const std::string &description = std::string(), int flags = 0); INLINE void operator = (const Filename &value); INLINE operator const Filename &() const; @@ -39,12 +39,12 @@ PUBLISHED: INLINE size_t length() const; INLINE char operator [] (size_t n) const; - INLINE string get_fullpath() const; - INLINE string get_dirname() const; - INLINE string get_basename() const; - INLINE string get_fullpath_wo_extension() const; - INLINE string get_basename_wo_extension() const; - INLINE string get_extension() const; + INLINE std::string get_fullpath() const; + INLINE std::string get_dirname() const; + INLINE std::string get_basename() const; + INLINE std::string get_fullpath_wo_extension() const; + INLINE std::string get_basename_wo_extension() const; + INLINE std::string get_extension() const; // Comparison operators are handy. INLINE bool operator == (const Filename &other) const; diff --git a/dtool/src/prc/configVariableInt.I b/dtool/src/prc/configVariableInt.I index 7c91ce1d6a..f341070b77 100644 --- a/dtool/src/prc/configVariableInt.I +++ b/dtool/src/prc/configVariableInt.I @@ -15,7 +15,7 @@ * */ INLINE ConfigVariableInt:: -ConfigVariableInt(const string &name) : +ConfigVariableInt(const std::string &name) : ConfigVariable(name, VT_int), _local_modified(initial_invalid_cache()) { @@ -26,12 +26,12 @@ ConfigVariableInt(const string &name) : * */ INLINE ConfigVariableInt:: -ConfigVariableInt(const string &name, int default_value, - const string &description, int flags) : +ConfigVariableInt(const std::string &name, int default_value, + const std::string &description, int flags) : #ifdef PRC_SAVE_DESCRIPTIONS ConfigVariable(name, ConfigVariableCore::VT_int, description, flags), #else - ConfigVariable(name, ConfigVariableCore::VT_int, string(), flags), + ConfigVariable(name, ConfigVariableCore::VT_int, std::string(), flags), #endif _local_modified(initial_invalid_cache()) { @@ -43,12 +43,12 @@ ConfigVariableInt(const string &name, int default_value, * */ INLINE ConfigVariableInt:: -ConfigVariableInt(const string &name, const string &default_value, - const string &description, int flags) : +ConfigVariableInt(const std::string &name, const std::string &default_value, + const std::string &description, int flags) : #ifdef PRC_SAVE_DESCRIPTIONS ConfigVariable(name, ConfigVariableCore::VT_int, description, flags), #else - ConfigVariable(name, ConfigVariableCore::VT_int, string(), flags), + ConfigVariable(name, ConfigVariableCore::VT_int, std::string(), flags), #endif _local_modified(initial_invalid_cache()) { @@ -116,7 +116,7 @@ get_value() const { INLINE int ConfigVariableInt:: get_default_value() const { const ConfigDeclaration *decl = ConfigVariable::get_default_value(); - if (decl != (ConfigDeclaration *)NULL) { + if (decl != nullptr) { return decl->get_int_word(0); } return 0; diff --git a/dtool/src/prc/configVariableInt.h b/dtool/src/prc/configVariableInt.h index 0156bed21a..9d87fe3344 100644 --- a/dtool/src/prc/configVariableInt.h +++ b/dtool/src/prc/configVariableInt.h @@ -23,12 +23,12 @@ */ class EXPCL_DTOOL_PRC ConfigVariableInt : public ConfigVariable { PUBLISHED: - INLINE ConfigVariableInt(const string &name); - INLINE ConfigVariableInt(const string &name, int default_value, - const string &description = string(), + INLINE ConfigVariableInt(const std::string &name); + INLINE ConfigVariableInt(const std::string &name, int default_value, + const std::string &description = std::string(), int flags = 0); - INLINE ConfigVariableInt(const string &name, const string &default_value, - const string &description = string(), + INLINE ConfigVariableInt(const std::string &name, const std::string &default_value, + const std::string &description = std::string(), int flags = 0); INLINE void operator = (int value); diff --git a/dtool/src/prc/configVariableInt64.I b/dtool/src/prc/configVariableInt64.I index f7c1c5d66b..a86fcc296e 100644 --- a/dtool/src/prc/configVariableInt64.I +++ b/dtool/src/prc/configVariableInt64.I @@ -15,7 +15,7 @@ * */ INLINE ConfigVariableInt64:: -ConfigVariableInt64(const string &name) : +ConfigVariableInt64(const std::string &name) : ConfigVariable(name, VT_int64), _local_modified(initial_invalid_cache()) { @@ -26,12 +26,12 @@ ConfigVariableInt64(const string &name) : * */ INLINE ConfigVariableInt64:: -ConfigVariableInt64(const string &name, int64_t default_value, - const string &description, int flags) : +ConfigVariableInt64(const std::string &name, int64_t default_value, + const std::string &description, int flags) : #ifdef PRC_SAVE_DESCRIPTIONS ConfigVariable(name, ConfigVariableCore::VT_int64, description, flags), #else - ConfigVariable(name, ConfigVariableCore::VT_int64, string(), flags), + ConfigVariable(name, ConfigVariableCore::VT_int64, std::string(), flags), #endif _local_modified(initial_invalid_cache()) { @@ -43,12 +43,12 @@ ConfigVariableInt64(const string &name, int64_t default_value, * */ INLINE ConfigVariableInt64:: -ConfigVariableInt64(const string &name, const string &default_value, - const string &description, int flags) : +ConfigVariableInt64(const std::string &name, const std::string &default_value, + const std::string &description, int flags) : #ifdef PRC_SAVE_DESCRIPTIONS ConfigVariable(name, ConfigVariableCore::VT_int64, description, flags), #else - ConfigVariable(name, ConfigVariableCore::VT_int64, string(), flags), + ConfigVariable(name, ConfigVariableCore::VT_int64, std::string(), flags), #endif _local_modified(initial_invalid_cache()) { @@ -116,7 +116,7 @@ get_value() const { INLINE int64_t ConfigVariableInt64:: get_default_value() const { const ConfigDeclaration *decl = ConfigVariable::get_default_value(); - if (decl != (ConfigDeclaration *)NULL) { + if (decl != nullptr) { return decl->get_int64_word(0); } return 0; diff --git a/dtool/src/prc/configVariableInt64.h b/dtool/src/prc/configVariableInt64.h index 14d02e2ee9..a88f2272d8 100644 --- a/dtool/src/prc/configVariableInt64.h +++ b/dtool/src/prc/configVariableInt64.h @@ -24,12 +24,12 @@ */ class EXPCL_DTOOL_PRC ConfigVariableInt64 : public ConfigVariable { PUBLISHED: - INLINE ConfigVariableInt64(const string &name); - INLINE ConfigVariableInt64(const string &name, int64_t default_value, - const string &description = string(), + INLINE ConfigVariableInt64(const std::string &name); + INLINE ConfigVariableInt64(const std::string &name, int64_t default_value, + const std::string &description = std::string(), int flags = 0); - INLINE ConfigVariableInt64(const string &name, const string &default_value, - const string &description = string(), + INLINE ConfigVariableInt64(const std::string &name, const std::string &default_value, + const std::string &description = std::string(), int flags = 0); INLINE void operator = (int64_t value); diff --git a/dtool/src/prc/configVariableList.I b/dtool/src/prc/configVariableList.I index 4429e31fb9..606d8d47fd 100644 --- a/dtool/src/prc/configVariableList.I +++ b/dtool/src/prc/configVariableList.I @@ -22,18 +22,18 @@ INLINE ConfigVariableList:: * */ INLINE ConfigVariableList:: -ConfigVariableList(const string &name, - const string &description, int flags) : +ConfigVariableList(const std::string &name, + const std::string &description, int flags) : #ifdef PRC_SAVE_DESCRIPTIONS ConfigVariableBase(name, VT_list, description, flags) #else - ConfigVariableBase(name, VT_list, string(), flags) + ConfigVariableBase(name, VT_list, std::string(), flags) #endif { // A list variable implicitly defines a default value of the empty string. // This is just to prevent the core variable from complaining should anyone // ask for its solitary value. - if (_core->get_default_value() == (ConfigDeclaration *)NULL) { + if (_core->get_default_value() == nullptr) { _core->set_default_value(""); } _core->set_used(); @@ -44,21 +44,21 @@ ConfigVariableList(const string &name, */ INLINE size_t ConfigVariableList:: get_num_values() const { - nassertr(_core != (ConfigVariableCore *)NULL, 0); + nassertr(_core != nullptr, 0); return _core->get_num_trusted_references(); } /** * Returns the nth value of the variable. */ -INLINE string ConfigVariableList:: +INLINE std::string ConfigVariableList:: get_string_value(size_t n) const { - nassertr(_core != (ConfigVariableCore *)NULL, string()); + nassertr(_core != nullptr, std::string()); const ConfigDeclaration *decl = _core->get_trusted_reference(n); - if (decl != (ConfigDeclaration *)NULL) { + if (decl != nullptr) { return decl->get_string_value(); } - return string(); + return std::string(); } /** @@ -66,21 +66,21 @@ get_string_value(size_t n) const { */ INLINE size_t ConfigVariableList:: get_num_unique_values() const { - nassertr(_core != (ConfigVariableCore *)NULL, 0); + nassertr(_core != nullptr, 0); return _core->get_num_unique_references(); } /** * Returns the nth unique value of the variable. */ -INLINE string ConfigVariableList:: +INLINE std::string ConfigVariableList:: get_unique_value(size_t n) const { - nassertr(_core != (ConfigVariableCore *)NULL, string()); + nassertr(_core != nullptr, std::string()); const ConfigDeclaration *decl = _core->get_unique_reference(n); - if (decl != (ConfigDeclaration *)NULL) { + if (decl != nullptr) { return decl->get_string_value(); } - return string(); + return std::string(); } /** @@ -96,13 +96,13 @@ size() const { * operator returns the list of unique values, and so the maximum range is * get_num_unique_values(). */ -INLINE string ConfigVariableList:: +INLINE std::string ConfigVariableList:: operator [] (size_t n) const { return get_unique_value(n); } -INLINE ostream & -operator << (ostream &out, const ConfigVariableList &variable) { +INLINE std::ostream & +operator << (std::ostream &out, const ConfigVariableList &variable) { variable.output(out); return out; } diff --git a/dtool/src/prc/configVariableList.cxx b/dtool/src/prc/configVariableList.cxx index 7ecd861837..f663ac5adc 100644 --- a/dtool/src/prc/configVariableList.cxx +++ b/dtool/src/prc/configVariableList.cxx @@ -17,7 +17,7 @@ * */ void ConfigVariableList:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_num_values() << " values."; } @@ -25,7 +25,7 @@ output(ostream &out) const { * */ void ConfigVariableList:: -write(ostream &out) const { +write(std::ostream &out) const { size_t num_values = get_num_values(); for (size_t i = 0; i < num_values; ++i) { out << get_string_value(i) << "\n"; diff --git a/dtool/src/prc/configVariableList.h b/dtool/src/prc/configVariableList.h index ca639a94ae..188b33c5fb 100644 --- a/dtool/src/prc/configVariableList.h +++ b/dtool/src/prc/configVariableList.h @@ -30,25 +30,25 @@ */ class EXPCL_DTOOL_PRC ConfigVariableList : public ConfigVariableBase { PUBLISHED: - INLINE ConfigVariableList(const string &name, - const string &description = string(), + INLINE ConfigVariableList(const std::string &name, + const std::string &description = std::string(), int flags = 0); INLINE ~ConfigVariableList(); INLINE size_t get_num_values() const; - INLINE string get_string_value(size_t n) const; + INLINE std::string get_string_value(size_t n) const; INLINE size_t get_num_unique_values() const; - INLINE string get_unique_value(size_t n) const; + INLINE std::string get_unique_value(size_t n) const; INLINE size_t size() const; - INLINE string operator [] (size_t n) const; + INLINE std::string operator [] (size_t n) const; - void output(ostream &out) const; - void write(ostream &out) const; + void output(std::ostream &out) const; + void write(std::ostream &out) const; }; -INLINE ostream &operator << (ostream &out, const ConfigVariableList &variable); +INLINE std::ostream &operator << (std::ostream &out, const ConfigVariableList &variable); #include "configVariableList.I" diff --git a/dtool/src/prc/configVariableManager.I b/dtool/src/prc/configVariableManager.I index 4ca5363bde..d0c1633c27 100644 --- a/dtool/src/prc/configVariableManager.I +++ b/dtool/src/prc/configVariableManager.I @@ -24,12 +24,12 @@ get_num_variables() const { */ INLINE ConfigVariableCore *ConfigVariableManager:: get_variable(size_t n) const { - nassertr(n < _variables.size(), (ConfigVariableCore *)NULL); + nassertr(n < _variables.size(), nullptr); return _variables[n]; } -INLINE ostream & -operator << (ostream &out, const ConfigVariableManager &variableMgr) { +INLINE std::ostream & +operator << (std::ostream &out, const ConfigVariableManager &variableMgr) { variableMgr.output(out); return out; } diff --git a/dtool/src/prc/configVariableManager.cxx b/dtool/src/prc/configVariableManager.cxx index 4231abbbaa..774dc19f6b 100644 --- a/dtool/src/prc/configVariableManager.cxx +++ b/dtool/src/prc/configVariableManager.cxx @@ -17,7 +17,9 @@ #include "configPage.h" #include "config_prc.h" -ConfigVariableManager *ConfigVariableManager::_global_ptr = NULL; +using std::string; + +ConfigVariableManager *ConfigVariableManager::_global_ptr = nullptr; /** * The constructor is private (actually, just protected, but only to avoid a @@ -52,12 +54,12 @@ make_variable(const string &name) { return (*ni).second; } - ConfigVariableCore *variable = NULL; + ConfigVariableCore *variable = nullptr; // See if there's a template that matches this name. VariableTemplates::const_iterator ti; for (ti = _variable_templates.begin(); - ti != _variable_templates.end() && variable == (ConfigVariableCore *)NULL; + ti != _variable_templates.end() && variable == nullptr; ++ti) { const GlobPattern &pattern = (*ti).first; ConfigVariableCore *templ = (*ti).second; @@ -66,7 +68,7 @@ make_variable(const string &name) { } } - if (variable == (ConfigVariableCore *)NULL) { + if (variable == nullptr) { variable = new ConfigVariableCore(name); } @@ -116,7 +118,7 @@ make_variable_template(const string &pattern, core->set_value_type(value_type); } if (!default_value.empty() || - core->get_default_value() == (ConfigDeclaration *)NULL) { + core->get_default_value() == nullptr) { core->set_default_value(default_value); } if (!description.empty()) { @@ -137,7 +139,7 @@ make_variable_template(const string &pattern, variable->set_value_type(value_type); } if (!default_value.empty() || - variable->get_default_value() == (ConfigDeclaration *)NULL) { + variable->get_default_value() == nullptr) { variable->set_default_value(default_value); } if (!description.empty()) { @@ -180,7 +182,7 @@ is_variable_used(size_t n) const { * */ void ConfigVariableManager:: -output(ostream &out) const { +output(std::ostream &out) const { out << "ConfigVariableManager, " << _variables.size() << " variables."; } @@ -188,7 +190,7 @@ output(ostream &out) const { * */ void ConfigVariableManager:: -write(ostream &out) const { +write(std::ostream &out) const { VariablesByName::const_iterator ni; for (ni = _variables_by_name.begin(); ni != _variables_by_name.end(); @@ -211,7 +213,7 @@ write(ostream &out) const { * state. */ void ConfigVariableManager:: -write_prc_variables(ostream &out) const { +write_prc_variables(std::ostream &out) const { VariablesByName::const_iterator ni; for (ni = _variables_by_name.begin(); ni != _variables_by_name.end(); @@ -300,7 +302,7 @@ list_dynamic_variables() const { */ ConfigVariableManager *ConfigVariableManager:: get_global_ptr() { - if (_global_ptr == (ConfigVariableManager *)NULL) { + if (_global_ptr == nullptr) { _global_ptr = new ConfigVariableManager; } return _global_ptr; @@ -357,7 +359,7 @@ list_variable(const ConfigVariableCore *variable, } decl = variable->get_default_value(); - if (decl != (ConfigDeclaration *)NULL) { + if (decl != nullptr) { nout << " default value = " << decl->get_string_value() << "\n"; } } diff --git a/dtool/src/prc/configVariableManager.h b/dtool/src/prc/configVariableManager.h index 713e1bc5d2..22c0c6e3f5 100644 --- a/dtool/src/prc/configVariableManager.h +++ b/dtool/src/prc/configVariableManager.h @@ -34,26 +34,26 @@ protected: ~ConfigVariableManager(); PUBLISHED: - ConfigVariableCore *make_variable(const string &name); - ConfigVariableCore *make_variable_template(const string &pattern, + ConfigVariableCore *make_variable(const std::string &name); + ConfigVariableCore *make_variable_template(const std::string &pattern, ConfigFlags::ValueType type, - const string &default_value, - const string &description = string(), + const std::string &default_value, + const std::string &description = std::string(), int flags = 0); INLINE size_t get_num_variables() const; INLINE ConfigVariableCore *get_variable(size_t n) const; MAKE_SEQ(get_variables, get_num_variables, get_variable); - string get_variable_name(size_t n) const; + std::string get_variable_name(size_t n) const; bool is_variable_used(size_t n) const; MAKE_SEQ_PROPERTY(variables, get_num_variables, get_variable); - void output(ostream &out) const; - void write(ostream &out) const; + void output(std::ostream &out) const; + void write(std::ostream &out) const; - void write_prc_variables(ostream &out) const; + void write_prc_variables(std::ostream &out) const; void list_unused_variables() const; void list_variables() const; @@ -67,19 +67,19 @@ private: // We have to avoid pmap and pvector, due to the very low-level nature of // this stuff. - typedef vector Variables; + typedef std::vector Variables; Variables _variables; - typedef map VariablesByName; + typedef std::map VariablesByName; VariablesByName _variables_by_name; - typedef map VariableTemplates; + typedef std::map VariableTemplates; VariableTemplates _variable_templates; static ConfigVariableManager *_global_ptr; }; -INLINE ostream &operator << (ostream &out, const ConfigVariableManager &variableMgr); +INLINE std::ostream &operator << (std::ostream &out, const ConfigVariableManager &variableMgr); #include "configVariableManager.I" diff --git a/dtool/src/prc/configVariableSearchPath.I b/dtool/src/prc/configVariableSearchPath.I index 9017d1cf0a..46e542e24c 100644 --- a/dtool/src/prc/configVariableSearchPath.I +++ b/dtool/src/prc/configVariableSearchPath.I @@ -15,12 +15,12 @@ * */ INLINE ConfigVariableSearchPath:: -ConfigVariableSearchPath(const string &name, - const string &description, int flags) : +ConfigVariableSearchPath(const std::string &name, + const std::string &description, int flags) : #ifdef PRC_SAVE_DESCRIPTIONS ConfigVariableBase(name, VT_search_path, description, flags), #else - ConfigVariableBase(name, VT_search_path, string(), flags), + ConfigVariableBase(name, VT_search_path, std::string(), flags), #endif _default_value(Filename(".")), _local_modified(initial_invalid_cache()) @@ -28,7 +28,7 @@ ConfigVariableSearchPath(const string &name, // A SearchPath variable implicitly defines a default value of the empty // string. This is just to prevent the core variable from complaining // should anyone ask for its solitary value. - if (_core->get_default_value() == (ConfigDeclaration *)NULL) { + if (_core->get_default_value() == nullptr) { _core->set_default_value(""); } _core->set_used(); @@ -38,13 +38,13 @@ ConfigVariableSearchPath(const string &name, * */ INLINE ConfigVariableSearchPath:: -ConfigVariableSearchPath(const string &name, +ConfigVariableSearchPath(const std::string &name, const DSearchPath &default_value, - const string &description, int flags) : + const std::string &description, int flags) : #ifdef PRC_SAVE_DESCRIPTIONS ConfigVariableBase(name, VT_search_path, description, flags), #else - ConfigVariableBase(name, VT_search_path, string(), flags), + ConfigVariableBase(name, VT_search_path, std::string(), flags), #endif _default_value(default_value), _local_modified(initial_invalid_cache()) @@ -52,7 +52,7 @@ ConfigVariableSearchPath(const string &name, // A SearchPath variable implicitly defines a default value of the empty // string. This is just to prevent the core variable from complaining // should anyone ask for its solitary value. - if (_core->get_default_value() == (ConfigDeclaration *)NULL) { + if (_core->get_default_value() == nullptr) { _core->set_default_value(""); } _core->set_used(); @@ -62,13 +62,13 @@ ConfigVariableSearchPath(const string &name, * */ INLINE ConfigVariableSearchPath:: -ConfigVariableSearchPath(const string &name, - const string &default_value, - const string &description, int flags) : +ConfigVariableSearchPath(const std::string &name, + const std::string &default_value, + const std::string &description, int flags) : #ifdef PRC_SAVE_DESCRIPTIONS ConfigVariableBase(name, VT_search_path, description, flags), #else - ConfigVariableBase(name, VT_search_path, string(), flags), + ConfigVariableBase(name, VT_search_path, std::string(), flags), #endif _default_value(Filename(default_value)), _local_modified(initial_invalid_cache()) @@ -76,7 +76,7 @@ ConfigVariableSearchPath(const string &name, // A SearchPath variable implicitly defines a default value of the empty // string. This is just to prevent the core variable from complaining // should anyone ask for its solitary value. - if (_core->get_default_value() == (ConfigDeclaration *)NULL) { + if (_core->get_default_value() == nullptr) { _core->set_default_value(""); } _core->set_used(); @@ -123,7 +123,7 @@ get_default_value() const { */ INLINE bool ConfigVariableSearchPath:: clear_local_value() { - nassertr(_core != (ConfigVariableCore *)NULL, false); + nassertr(_core != nullptr, false); bool any_to_clear = !_prefix.is_empty() || _postfix.is_empty(); _prefix.clear(); @@ -169,7 +169,7 @@ prepend_directory(const Filename &directory) { * search list. */ INLINE void ConfigVariableSearchPath:: -append_path(const string &path, const string &separator) { +append_path(const std::string &path, const std::string &separator) { _postfix.append_path(path, separator); _local_modified = initial_invalid_cache(); } @@ -256,7 +256,7 @@ find_all_files(const Filename &filename) const { * */ INLINE void ConfigVariableSearchPath:: -output(ostream &out) const { +output(std::ostream &out) const { get_value().output(out); } @@ -264,12 +264,12 @@ output(ostream &out) const { * */ INLINE void ConfigVariableSearchPath:: -write(ostream &out) const { +write(std::ostream &out) const { get_value().write(out); } -INLINE ostream & -operator << (ostream &out, const ConfigVariableSearchPath &variable) { +INLINE std::ostream & +operator << (std::ostream &out, const ConfigVariableSearchPath &variable) { variable.output(out); return out; } diff --git a/dtool/src/prc/configVariableSearchPath.cxx b/dtool/src/prc/configVariableSearchPath.cxx index 2ae4d87d16..2231626a7a 100644 --- a/dtool/src/prc/configVariableSearchPath.cxx +++ b/dtool/src/prc/configVariableSearchPath.cxx @@ -19,7 +19,7 @@ */ void ConfigVariableSearchPath:: reload_search_path() { - nassertv(_core != (ConfigVariableCore *)NULL); + nassertv(_core != nullptr); mark_cache_valid(_local_modified); _cache.clear(); @@ -32,7 +32,7 @@ reload_search_path() { Filename page_filename(page->get_name()); Filename page_dirname = page_filename.get_dirname(); ExecutionEnvironment::shadow_environment_variable("THIS_PRC_DIR", page_dirname.to_os_specific()); - string expanded = ExecutionEnvironment::expand_string(decl->get_string_value()); + std::string expanded = ExecutionEnvironment::expand_string(decl->get_string_value()); ExecutionEnvironment::clear_shadow("THIS_PRC_DIR"); if (!expanded.empty()) { Filename dir = Filename::from_os_specific(expanded); diff --git a/dtool/src/prc/configVariableSearchPath.h b/dtool/src/prc/configVariableSearchPath.h index 4dfe1b0fcf..02a4fd65c3 100644 --- a/dtool/src/prc/configVariableSearchPath.h +++ b/dtool/src/prc/configVariableSearchPath.h @@ -35,16 +35,16 @@ */ class EXPCL_DTOOL_PRC ConfigVariableSearchPath : public ConfigVariableBase { PUBLISHED: - INLINE ConfigVariableSearchPath(const string &name, - const string &description = string(), + INLINE ConfigVariableSearchPath(const std::string &name, + const std::string &description = std::string(), int flags = 0); - INLINE ConfigVariableSearchPath(const string &name, + INLINE ConfigVariableSearchPath(const std::string &name, const DSearchPath &default_value, - const string &description, + const std::string &description, int flags = 0); - INLINE ConfigVariableSearchPath(const string &name, - const string &default_value, - const string &description, + INLINE ConfigVariableSearchPath(const std::string &name, + const std::string &default_value, + const std::string &description, int flags = 0); INLINE ~ConfigVariableSearchPath(); @@ -59,8 +59,8 @@ PUBLISHED: INLINE void clear(); INLINE void append_directory(const Filename &directory); INLINE void prepend_directory(const Filename &directory); - INLINE void append_path(const string &path, - const string &separator = string()); + INLINE void append_path(const std::string &path, + const std::string &separator = std::string()); INLINE void append_path(const DSearchPath &path); INLINE void prepend_path(const DSearchPath &path); @@ -75,8 +75,8 @@ PUBLISHED: DSearchPath::Results &results) const; INLINE DSearchPath::Results find_all_files(const Filename &filename) const; - INLINE void output(ostream &out) const; - INLINE void write(ostream &out) const; + INLINE void output(std::ostream &out) const; + INLINE void write(std::ostream &out) const; private: void reload_search_path(); @@ -88,7 +88,7 @@ private: DSearchPath _cache; }; -INLINE ostream &operator << (ostream &out, const ConfigVariableSearchPath &variable); +INLINE std::ostream &operator << (std::ostream &out, const ConfigVariableSearchPath &variable); #include "configVariableSearchPath.I" diff --git a/dtool/src/prc/configVariableString.I b/dtool/src/prc/configVariableString.I index 1adbbe6797..d72c48cb8c 100644 --- a/dtool/src/prc/configVariableString.I +++ b/dtool/src/prc/configVariableString.I @@ -15,7 +15,7 @@ * */ INLINE ConfigVariableString:: -ConfigVariableString(const string &name) : +ConfigVariableString(const std::string &name) : ConfigVariable(name, VT_string), _local_modified(initial_invalid_cache()) { @@ -26,12 +26,12 @@ ConfigVariableString(const string &name) : * */ INLINE ConfigVariableString:: -ConfigVariableString(const string &name, const string &default_value, - const string &description, int flags) : +ConfigVariableString(const std::string &name, const std::string &default_value, + const std::string &description, int flags) : #ifdef PRC_SAVE_DESCRIPTIONS ConfigVariable(name, VT_string, description, flags), #else - ConfigVariable(name, VT_string, string(), flags), + ConfigVariable(name, VT_string, std::string(), flags), #endif _local_modified(initial_invalid_cache()) { @@ -43,7 +43,7 @@ ConfigVariableString(const string &name, const string &default_value, * Reassigns the variable's local value. */ INLINE void ConfigVariableString:: -operator = (const string &value) { +operator = (const std::string &value) { set_value(value); } @@ -51,7 +51,7 @@ operator = (const string &value) { * Returns the variable's value. */ INLINE ConfigVariableString:: -operator const string & () const { +operator const std::string & () const { return get_value(); } @@ -92,7 +92,7 @@ operator [] (size_t n) const { * */ INLINE bool ConfigVariableString:: -operator == (const string &other) const { +operator == (const std::string &other) const { return get_value() == other; } @@ -100,7 +100,7 @@ operator == (const string &other) const { * */ INLINE bool ConfigVariableString:: -operator != (const string &other) const { +operator != (const std::string &other) const { return get_value() != other; } @@ -108,7 +108,7 @@ operator != (const string &other) const { * */ INLINE bool ConfigVariableString:: -operator < (const string &other) const { +operator < (const std::string &other) const { return get_value() < other; } @@ -116,14 +116,14 @@ operator < (const string &other) const { * Reassigns the variable's local value. */ INLINE void ConfigVariableString:: -set_value(const string &value) { +set_value(const std::string &value) { set_string_value(value); } /** * Returns the variable's value. */ -INLINE const string &ConfigVariableString:: +INLINE const std::string &ConfigVariableString:: get_value() const { TAU_PROFILE("const string &ConfigVariableString::get_value() const", " ", TAU_USER); if (!is_cache_valid(_local_modified)) { @@ -135,19 +135,19 @@ get_value() const { /** * Returns the variable's default value. */ -INLINE string ConfigVariableString:: +INLINE std::string ConfigVariableString:: get_default_value() const { const ConfigDeclaration *decl = ConfigVariable::get_default_value(); - if (decl != (ConfigDeclaration *)NULL) { + if (decl != nullptr) { return decl->get_string_value(); } - return string(); + return std::string(); } /** * Returns the variable's nth value. */ -INLINE string ConfigVariableString:: +INLINE std::string ConfigVariableString:: get_word(size_t n) const { return get_string_word(n); } @@ -157,6 +157,6 @@ get_word(size_t n) const { * variable's overall value. */ INLINE void ConfigVariableString:: -set_word(size_t n, const string &value) { +set_word(size_t n, const std::string &value) { set_string_word(n, value); } diff --git a/dtool/src/prc/configVariableString.cxx b/dtool/src/prc/configVariableString.cxx index 3dcaaf6deb..ebb4a751d2 100644 --- a/dtool/src/prc/configVariableString.cxx +++ b/dtool/src/prc/configVariableString.cxx @@ -22,7 +22,7 @@ reload_cache() { // thread-safe manner. But chances are that the first time this is called // is at static init time, when there is no risk of data races. static MutexImpl lock; - lock.acquire(); + lock.lock(); // We check again for cache validity since another thread may have beaten // us to the punch while we were waiting for the lock. @@ -31,5 +31,5 @@ reload_cache() { mark_cache_valid(_local_modified); } - lock.release(); + lock.unlock(); } diff --git a/dtool/src/prc/configVariableString.h b/dtool/src/prc/configVariableString.h index 0b6d615667..d2b5b38b78 100644 --- a/dtool/src/prc/configVariableString.h +++ b/dtool/src/prc/configVariableString.h @@ -22,12 +22,12 @@ */ class EXPCL_DTOOL_PRC ConfigVariableString : public ConfigVariable { PUBLISHED: - INLINE ConfigVariableString(const string &name); - INLINE ConfigVariableString(const string &name, const string &default_value, - const string &description = string(), int flags = 0); + INLINE ConfigVariableString(const std::string &name); + INLINE ConfigVariableString(const std::string &name, const std::string &default_value, + const std::string &description = std::string(), int flags = 0); - INLINE void operator = (const string &value); - INLINE operator const string & () const; + INLINE void operator = (const std::string &value); + INLINE operator const std::string & () const; // These methods help the ConfigVariableString act like a C++ string object. INLINE const char *c_str() const; @@ -36,25 +36,25 @@ PUBLISHED: INLINE char operator [] (size_t n) const; // Comparison operators are handy. - INLINE bool operator == (const string &other) const; - INLINE bool operator != (const string &other) const; - INLINE bool operator < (const string &other) const; + INLINE bool operator == (const std::string &other) const; + INLINE bool operator != (const std::string &other) const; + INLINE bool operator < (const std::string &other) const; - INLINE void set_value(const string &value); - INLINE const string &get_value() const; - INLINE string get_default_value() const; + INLINE void set_value(const std::string &value); + INLINE const std::string &get_value() const; + INLINE std::string get_default_value() const; MAKE_PROPERTY(value, get_value, set_value); MAKE_PROPERTY(default_value, get_default_value); - INLINE string get_word(size_t n) const; - INLINE void set_word(size_t n, const string &value); + INLINE std::string get_word(size_t n) const; + INLINE void set_word(size_t n, const std::string &value); private: void reload_cache(); private: AtomicAdjust::Integer _local_modified; - string _cache; + std::string _cache; }; #include "configVariableString.I" diff --git a/dtool/src/prc/encryptStream.I b/dtool/src/prc/encryptStream.I index bad15bd7e7..f93e6c01a3 100644 --- a/dtool/src/prc/encryptStream.I +++ b/dtool/src/prc/encryptStream.I @@ -15,15 +15,15 @@ * */ INLINE IDecryptStream:: -IDecryptStream() : istream(&_buf) { +IDecryptStream() : std::istream(&_buf) { } /** * */ INLINE IDecryptStream:: -IDecryptStream(istream *source, bool owns_source, - const string &password) : istream(&_buf) { +IDecryptStream(std::istream *source, bool owns_source, + const std::string &password) : std::istream(&_buf) { open(source, owns_source, password); } @@ -31,7 +31,7 @@ IDecryptStream(istream *source, bool owns_source, * */ INLINE IDecryptStream &IDecryptStream:: -open(istream *source, bool owns_source, const string &password) { +open(std::istream *source, bool owns_source, const std::string &password) { clear((ios_iostate)0); _buf.open_read(source, owns_source, password); return *this; @@ -50,7 +50,7 @@ close() { /** * Returns the encryption algorithm that was read from the stream. */ -INLINE const string &IDecryptStream:: +INLINE const std::string &IDecryptStream:: get_algorithm() const { return _buf.get_algorithm(); } @@ -76,15 +76,15 @@ get_iteration_count() const { * */ INLINE OEncryptStream:: -OEncryptStream() : ostream(&_buf) { +OEncryptStream() : std::ostream(&_buf) { } /** * */ INLINE OEncryptStream:: -OEncryptStream(ostream *dest, bool owns_dest, const string &password) : - ostream(&_buf) +OEncryptStream(std::ostream *dest, bool owns_dest, const std::string &password) : + std::ostream(&_buf) { open(dest, owns_dest, password); } @@ -93,7 +93,7 @@ OEncryptStream(ostream *dest, bool owns_dest, const string &password) : * */ INLINE OEncryptStream &OEncryptStream:: -open(ostream *dest, bool owns_dest, const string &password) { +open(std::ostream *dest, bool owns_dest, const std::string &password) { clear((ios_iostate)0); _buf.open_write(dest, owns_dest, password); return *this; @@ -112,7 +112,7 @@ close() { /** * Returns the encryption algorithm that was read from the stream. */ -INLINE const string &OEncryptStream:: +INLINE const std::string &OEncryptStream:: get_algorithm() const { return _buf.get_algorithm(); } @@ -143,7 +143,7 @@ get_iteration_count() const { * code, but open() will fail. */ INLINE void OEncryptStream:: -set_algorithm(const string &algorithm) { +set_algorithm(const std::string &algorithm) { _buf.set_algorithm(algorithm); } diff --git a/dtool/src/prc/encryptStream.h b/dtool/src/prc/encryptStream.h index 540d4b3209..94deaeb62e 100644 --- a/dtool/src/prc/encryptStream.h +++ b/dtool/src/prc/encryptStream.h @@ -31,21 +31,21 @@ * * Seeking is not supported. */ -class EXPCL_DTOOL_PRC IDecryptStream : public istream { +class EXPCL_DTOOL_PRC IDecryptStream : public std::istream { PUBLISHED: INLINE IDecryptStream(); - INLINE explicit IDecryptStream(istream *source, bool owns_source, - const string &password); + INLINE explicit IDecryptStream(std::istream *source, bool owns_source, + const std::string &password); #if _MSC_VER >= 1800 INLINE IDecryptStream(const IDecryptStream ©) = delete; #endif - INLINE IDecryptStream &open(istream *source, bool owns_source, - const string &password); + INLINE IDecryptStream &open(std::istream *source, bool owns_source, + const std::string &password); INLINE IDecryptStream &close(); - INLINE const string &get_algorithm() const; + INLINE const std::string &get_algorithm() const; INLINE int get_key_length() const; INLINE int get_iteration_count() const; @@ -66,27 +66,27 @@ private: * * Seeking is not supported. */ -class EXPCL_DTOOL_PRC OEncryptStream : public ostream { +class EXPCL_DTOOL_PRC OEncryptStream : public std::ostream { PUBLISHED: INLINE OEncryptStream(); - INLINE explicit OEncryptStream(ostream *dest, bool owns_dest, - const string &password); + INLINE explicit OEncryptStream(std::ostream *dest, bool owns_dest, + const std::string &password); #if _MSC_VER >= 1800 INLINE OEncryptStream(const OEncryptStream ©) = delete; #endif - INLINE OEncryptStream &open(ostream *dest, bool owns_dest, - const string &password); + INLINE OEncryptStream &open(std::ostream *dest, bool owns_dest, + const std::string &password); INLINE OEncryptStream &close(); public: - INLINE const string &get_algorithm() const; + INLINE const std::string &get_algorithm() const; INLINE int get_key_length() const; INLINE int get_iteration_count() const; PUBLISHED: - INLINE void set_algorithm(const string &algorithm); + INLINE void set_algorithm(const std::string &algorithm); INLINE void set_key_length(int key_length); INLINE void set_iteration_count(int iteration_count); diff --git a/dtool/src/prc/encryptStreamBuf.I b/dtool/src/prc/encryptStreamBuf.I index 88537ca09e..cbf9f59470 100644 --- a/dtool/src/prc/encryptStreamBuf.I +++ b/dtool/src/prc/encryptStreamBuf.I @@ -21,7 +21,7 @@ * code, but open_write() will fail. */ INLINE void EncryptStreamBuf:: -set_algorithm(const string &algorithm) { +set_algorithm(const std::string &algorithm) { _algorithm = algorithm; } @@ -29,7 +29,7 @@ set_algorithm(const string &algorithm) { * Returns the encryption algorithm that was specified by set_algorithm(), or * was read from the stream by the last successful open_read(). */ -INLINE const string &EncryptStreamBuf:: +INLINE const std::string &EncryptStreamBuf:: get_algorithm() const { return _algorithm; } diff --git a/dtool/src/prc/encryptStreamBuf.cxx b/dtool/src/prc/encryptStreamBuf.cxx index dc38ac5894..192c1181c6 100644 --- a/dtool/src/prc/encryptStreamBuf.cxx +++ b/dtool/src/prc/encryptStreamBuf.cxx @@ -23,11 +23,6 @@ #include "openssl/rand.h" #include "openssl/evp.h" -#ifndef HAVE_STREAMSIZE -// Some compilers (notably SGI) don't define this for us -typedef int streamsize; -#endif /* HAVE_STREAMSIZE */ - // The iteration count is scaled by this factor for writing to the stream. static const int iteration_count_factor = 1000; @@ -36,9 +31,9 @@ static const int iteration_count_factor = 1000; */ EncryptStreamBuf:: EncryptStreamBuf() { - _source = (istream *)NULL; + _source = nullptr; _owns_source = false; - _dest = (ostream *)NULL; + _dest = nullptr; _owns_dest = false; ConfigVariableString encryption_algorithm @@ -74,10 +69,10 @@ EncryptStreamBuf() { _key_length = encryption_key_length; _iteration_count = encryption_iteration_count; - _read_ctx = NULL; - _write_ctx = NULL; + _read_ctx = nullptr; + _write_ctx = nullptr; - _read_overflow_buffer = NULL; + _read_overflow_buffer = nullptr; _in_read_overflow_buffer = 0; #ifdef PHAVE_IOSTREAM @@ -106,15 +101,15 @@ EncryptStreamBuf:: * */ void EncryptStreamBuf:: -open_read(istream *source, bool owns_source, const string &password) { +open_read(std::istream *source, bool owns_source, const std::string &password) { OpenSSL_add_all_algorithms(); _source = source; _owns_source = owns_source; - if (_read_ctx != NULL) { + if (_read_ctx != nullptr) { EVP_CIPHER_CTX_free(_read_ctx); - _read_ctx = NULL; + _read_ctx = nullptr; } // Now read the header information. @@ -125,7 +120,7 @@ open_read(istream *source, bool owns_source, const string &password) { const EVP_CIPHER *cipher = EVP_get_cipherbynid(nid); - if (cipher == NULL) { + if (cipher == nullptr) { prc_cat.error() << "Unknown encryption algorithm in stream.\n"; return; @@ -150,11 +145,11 @@ open_read(istream *source, bool owns_source, const string &password) { iv_length = (int)sr.extract_bytes(iv, iv_length); _read_ctx = EVP_CIPHER_CTX_new(); - nassertv(_read_ctx != NULL); + nassertv(_read_ctx != nullptr); // Initialize the context int result; - result = EVP_DecryptInit(_read_ctx, cipher, NULL, (unsigned char *)iv); + result = EVP_DecryptInit(_read_ctx, cipher, nullptr, (unsigned char *)iv); nassertv(result > 0); result = EVP_CIPHER_CTX_set_key_length(_read_ctx, key_length); @@ -163,7 +158,7 @@ open_read(istream *source, bool owns_source, const string &password) { << "Invalid key length " << key_length * 8 << " bits for algorithm " << OBJ_nid2sn(nid) << "\n"; EVP_CIPHER_CTX_free(_read_ctx); - _read_ctx = NULL; + _read_ctx = nullptr; return; } @@ -177,7 +172,7 @@ open_read(istream *source, bool owns_source, const string &password) { nassertv(result > 0); // Store the key within the context. - result = EVP_DecryptInit(_read_ctx, NULL, key, NULL); + result = EVP_DecryptInit(_read_ctx, nullptr, key, nullptr); nassertv(result > 0); _read_overflow_buffer = new unsigned char[_read_block_size]; @@ -190,22 +185,22 @@ open_read(istream *source, bool owns_source, const string &password) { */ void EncryptStreamBuf:: close_read() { - if (_read_ctx != NULL) { + if (_read_ctx != nullptr) { EVP_CIPHER_CTX_free(_read_ctx); - _read_ctx = NULL; + _read_ctx = nullptr; } - if (_read_overflow_buffer != (unsigned char *)NULL) { + if (_read_overflow_buffer != nullptr) { delete[] _read_overflow_buffer; - _read_overflow_buffer = NULL; + _read_overflow_buffer = nullptr; } - if (_source != (istream *)NULL) { + if (_source != nullptr) { if (_owns_source) { delete _source; _owns_source = false; } - _source = (istream *)NULL; + _source = nullptr; } } @@ -213,7 +208,7 @@ close_read() { * */ void EncryptStreamBuf:: -open_write(ostream *dest, bool owns_dest, const string &password) { +open_write(std::ostream *dest, bool owns_dest, const std::string &password) { OpenSSL_add_all_algorithms(); close_write(); @@ -223,7 +218,7 @@ open_write(ostream *dest, bool owns_dest, const string &password) { const EVP_CIPHER *cipher = EVP_get_cipherbyname(_algorithm.c_str()); - if (cipher == NULL) { + if (cipher == nullptr) { prc_cat.error() << "Unknown encryption algorithm: " << _algorithm << "\n"; return; @@ -240,10 +235,10 @@ open_write(ostream *dest, bool owns_dest, const string &password) { RAND_bytes(iv, iv_length); _write_ctx = EVP_CIPHER_CTX_new(); - nassertv(_write_ctx != NULL); + nassertv(_write_ctx != nullptr); int result; - result = EVP_EncryptInit(_write_ctx, cipher, NULL, iv); + result = EVP_EncryptInit(_write_ctx, cipher, nullptr, iv); nassertv(result > 0); // Store the appropriate key length in the context. @@ -257,7 +252,7 @@ open_write(ostream *dest, bool owns_dest, const string &password) { << "Invalid key length " << key_length * 8 << " bits for algorithm " << OBJ_nid2sn(nid) << "\n"; EVP_CIPHER_CTX_free(_write_ctx); - _write_ctx = NULL; + _write_ctx = nullptr; return; } @@ -281,7 +276,7 @@ open_write(ostream *dest, bool owns_dest, const string &password) { nassertv(result > 0); // Store the key in the context. - result = EVP_EncryptInit(_write_ctx, NULL, key, NULL); + result = EVP_EncryptInit(_write_ctx, nullptr, key, nullptr); nassertv(result > 0); // Now write the header information to the stream. @@ -302,12 +297,12 @@ open_write(ostream *dest, bool owns_dest, const string &password) { */ void EncryptStreamBuf:: close_write() { - if (_dest != (ostream *)NULL) { + if (_dest != nullptr) { size_t n = pptr() - pbase(); write_chars(pbase(), n); pbump(-(int)n); - if (_write_ctx != NULL) { + if (_write_ctx != nullptr) { unsigned char *write_buffer = (unsigned char *)alloca(_write_block_size); int bytes_written = 0; EVP_EncryptFinal(_write_ctx, write_buffer, &bytes_written); @@ -316,14 +311,14 @@ close_write() { _dest->write((const char *)write_buffer, bytes_written); EVP_CIPHER_CTX_free(_write_ctx); - _write_ctx = NULL; + _write_ctx = nullptr; } if (_owns_dest) { delete _dest; _owns_dest = false; } - _dest = (ostream *)NULL; + _dest = nullptr; } } @@ -354,12 +349,12 @@ overflow(int ch) { */ int EncryptStreamBuf:: sync() { - if (_source != (istream *)NULL) { + if (_source != nullptr) { size_t n = egptr() - gptr(); gbump((int)n); } - if (_dest != (ostream *)NULL) { + if (_dest != nullptr) { size_t n = pptr() - pbase(); write_chars(pbase(), n); pbump(-(int)n); @@ -413,7 +408,7 @@ read_chars(char *start, size_t length) { if (_in_read_overflow_buffer != 0) { // Take from the overflow buffer. - length = min(length, _in_read_overflow_buffer); + length = std::min(length, _in_read_overflow_buffer); memcpy(start, _read_overflow_buffer, length); _in_read_overflow_buffer -= length; memcpy(_read_overflow_buffer + length, _read_overflow_buffer, _in_read_overflow_buffer); @@ -428,7 +423,7 @@ read_chars(char *start, size_t length) { do { // Get more bytes from the stream. - if (_read_ctx == NULL) { + if (_read_ctx == nullptr) { return 0; } @@ -445,15 +440,15 @@ read_chars(char *start, size_t length) { result = EVP_DecryptFinal(_read_ctx, read_buffer, &bytes_read); EVP_CIPHER_CTX_free(_read_ctx); - _read_ctx = NULL; + _read_ctx = nullptr; } if (result <= 0) { prc_cat.error() << "Error decrypting stream.\n"; - if (_read_ctx != NULL) { + if (_read_ctx != nullptr) { EVP_CIPHER_CTX_free(_read_ctx); - _read_ctx = NULL; + _read_ctx = nullptr; } } thread_consider_yield(); @@ -483,7 +478,7 @@ read_chars(char *start, size_t length) { */ void EncryptStreamBuf:: write_chars(const char *start, size_t length) { - if (_write_ctx != NULL && length != 0) { + if (_write_ctx != nullptr && length != 0) { size_t max_write_buffer = length + _write_block_size; unsigned char *write_buffer = (unsigned char *)alloca(max_write_buffer); diff --git a/dtool/src/prc/encryptStreamBuf.h b/dtool/src/prc/encryptStreamBuf.h index 8a812f1701..7bc4db5199 100644 --- a/dtool/src/prc/encryptStreamBuf.h +++ b/dtool/src/prc/encryptStreamBuf.h @@ -24,19 +24,19 @@ typedef struct evp_cipher_ctx_st EVP_CIPHER_CTX; /** * The streambuf object that implements IDecompressStream and OCompressStream. */ -class EXPCL_DTOOL_PRC EncryptStreamBuf : public streambuf { +class EXPCL_DTOOL_PRC EncryptStreamBuf : public std::streambuf { public: EncryptStreamBuf(); virtual ~EncryptStreamBuf(); - void open_read(istream *source, bool owns_source, const string &password); + void open_read(std::istream *source, bool owns_source, const std::string &password); void close_read(); - void open_write(ostream *dest, bool owns_dest, const string &password); + void open_write(std::ostream *dest, bool owns_dest, const std::string &password); void close_write(); - INLINE void set_algorithm(const string &algorithm); - INLINE const string &get_algorithm() const; + INLINE void set_algorithm(const std::string &algorithm); + INLINE const std::string &get_algorithm() const; INLINE void set_key_length(int key_length); INLINE int get_key_length() const; @@ -54,13 +54,13 @@ private: void write_chars(const char *start, size_t length); private: - istream *_source; + std::istream *_source; bool _owns_source; - ostream *_dest; + std::ostream *_dest; bool _owns_dest; - string _algorithm; + std::string _algorithm; int _key_length; int _iteration_count; diff --git a/dtool/src/prc/notify.cxx b/dtool/src/prc/notify.cxx index f74f55e596..f9c39135e8 100644 --- a/dtool/src/prc/notify.cxx +++ b/dtool/src/prc/notify.cxx @@ -29,18 +29,24 @@ #include #endif -Notify *Notify::_global_ptr = (Notify *)NULL; +using std::cerr; +using std::cout; +using std::ostream; +using std::ostringstream; +using std::string; + +Notify *Notify::_global_ptr = nullptr; /** * */ Notify:: Notify() { - _ostream_ptr = &cerr; + _ostream_ptr = &std::cerr; _owns_ostream_ptr = false; - _null_ostream_ptr = new fstream; + _null_ostream_ptr = new std::fstream; - _assert_handler = (AssertHandler *)NULL; + _assert_handler = nullptr; _assert_failed = false; } @@ -67,7 +73,7 @@ set_ostream_ptr(ostream *ostream_ptr, bool delete_later) { delete _ostream_ptr; } - if (ostream_ptr == (ostream *)NULL) { + if (ostream_ptr == nullptr) { _ostream_ptr = &cerr; _owns_ostream_ptr = false; } else { @@ -101,7 +107,7 @@ get_literal_flag() { if (!got_flag) { #ifndef PHAVE_IOSTREAM - flag = ios::bitalloc(); + flag = std::ios::bitalloc(); #else // We lost bitalloc in the new iostream? Ok, this feature will just be // disabled for now. No big deal. @@ -135,7 +141,7 @@ set_assert_handler(Notify::AssertHandler *assert_handler) { */ void Notify:: clear_assert_handler() { - _assert_handler = (AssertHandler *)NULL; + _assert_handler = nullptr; } /** @@ -143,7 +149,7 @@ clear_assert_handler() { */ bool Notify:: has_assert_handler() const { - return (_assert_handler != (AssertHandler *)NULL); + return (_assert_handler != nullptr); } /** @@ -172,10 +178,10 @@ get_top_category() { NotifyCategory *Notify:: get_category(const string &basename, NotifyCategory *parent_category) { // The string should not contain colons. - nassertr(basename.find(':') == string::npos, (NotifyCategory *)NULL); + nassertr(basename.find(':') == string::npos, nullptr); string fullname; - if (parent_category != (NotifyCategory *)NULL) { + if (parent_category != nullptr) { fullname = parent_category->get_fullname() + ":" + basename; } else { // The parent_category is NULL. If basename is empty, that means we refer @@ -187,8 +193,8 @@ get_category(const string &basename, NotifyCategory *parent_category) { } } - pair result = - _categories.insert(Categories::value_type(fullname, (NotifyCategory *)NULL)); + std::pair result = + _categories.insert(Categories::value_type(fullname, nullptr)); bool inserted = result.second; NotifyCategory *&category = (*result.first).second; @@ -230,7 +236,7 @@ get_category(const string &fullname) { // No such Category; create one. First identify the parent name, based on // the rightmost colon. - NotifyCategory *parent_category = (NotifyCategory *)NULL; + NotifyCategory *parent_category = nullptr; string basename = fullname; size_t colon = fullname.rfind(':'); @@ -281,7 +287,7 @@ write_string(const string &str) { */ Notify *Notify:: ptr() { - if (_global_ptr == (Notify *)NULL) { + if (_global_ptr == nullptr) { init_memory_hook(); _global_ptr = new Notify; } @@ -360,7 +366,7 @@ assert_failure(const char *expression, int line, // debugger otherwise. // So we'll force a segfault, which works every time. - int *ptr = (int *)NULL; + int *ptr = nullptr; *ptr = 1; #else // WIN32 @@ -430,7 +436,7 @@ config_initialized() { if (!notify_output.empty()) { if (notify_output == "stdout") { - cout.setf(ios::unitbuf); + cout.setf(std::ios::unitbuf); set_ostream_ptr(&cout, false); } else if (notify_output == "stderr") { @@ -459,7 +465,7 @@ config_initialized() { nout << "Unable to open file " << filename << " for output.\n"; delete out; } else { - out->setf(ios::unitbuf); + out->setf(std::ios::unitbuf); set_ostream_ptr(out, true); } #endif // BUILD_IPHONE diff --git a/dtool/src/prc/notifyCategory.I b/dtool/src/prc/notifyCategory.I index 46aca56bb2..5793917d91 100644 --- a/dtool/src/prc/notifyCategory.I +++ b/dtool/src/prc/notifyCategory.I @@ -14,7 +14,7 @@ /** * */ -INLINE string NotifyCategory:: +INLINE std::string NotifyCategory:: get_fullname() const { return _fullname; } @@ -22,7 +22,7 @@ get_fullname() const { /** * */ -INLINE string NotifyCategory:: +INLINE std::string NotifyCategory:: get_basename() const { return _basename; } @@ -49,7 +49,7 @@ set_severity(NotifySeverity severity) { _severity = severity; #else // enforce the no-debug, no-spam rule. - _severity = max(severity, NS_info); + _severity = std::max(severity, NS_info); #endif invalidate_cache(); } @@ -88,7 +88,7 @@ is_debug() const { * "debug" severities, and these methods are redefined to be static to make it * more obvious to the compiler. */ -CONSTEXPR bool NotifyCategory:: +constexpr bool NotifyCategory:: is_spam() { return false; } @@ -98,7 +98,7 @@ is_spam() { * "debug" severities, and these methods are redefined to be static to make it * more obvious to the compiler. */ -CONSTEXPR bool NotifyCategory:: +constexpr bool NotifyCategory:: is_debug() { return false; } @@ -139,7 +139,7 @@ is_fatal() const { /** * A shorthand way to write out(NS_spam). */ -INLINE ostream &NotifyCategory:: +INLINE std::ostream &NotifyCategory:: spam(bool prefix) const { #if defined(NOTIFY_DEBUG) return out(NS_spam, prefix); @@ -151,7 +151,7 @@ spam(bool prefix) const { /** * A shorthand way to write out(NS_debug). */ -INLINE ostream &NotifyCategory:: +INLINE std::ostream &NotifyCategory:: debug(bool prefix) const { #if defined(NOTIFY_DEBUG) return out(NS_debug, prefix); @@ -163,7 +163,7 @@ debug(bool prefix) const { /** * A shorthand way to write out(NS_info). */ -INLINE ostream &NotifyCategory:: +INLINE std::ostream &NotifyCategory:: info(bool prefix) const { return out(NS_info, prefix); } @@ -171,7 +171,7 @@ info(bool prefix) const { /** * A shorthand way to write out(NS_warning). */ -INLINE ostream &NotifyCategory:: +INLINE std::ostream &NotifyCategory:: warning(bool prefix) const { return out(NS_warning, prefix); } @@ -179,7 +179,7 @@ warning(bool prefix) const { /** * A shorthand way to write out(NS_error). */ -INLINE ostream &NotifyCategory:: +INLINE std::ostream &NotifyCategory:: error(bool prefix) const { return out(NS_error, prefix); } @@ -187,12 +187,12 @@ error(bool prefix) const { /** * A shorthand way to write out(NS_fatal). */ -INLINE ostream &NotifyCategory:: +INLINE std::ostream &NotifyCategory:: fatal(bool prefix) const { return out(NS_fatal, prefix); } -INLINE ostream & -operator << (ostream &out, const NotifyCategory &cat) { +INLINE std::ostream & +operator << (std::ostream &out, const NotifyCategory &cat) { return out << cat.get_fullname(); } diff --git a/dtool/src/prc/notifyCategory.cxx b/dtool/src/prc/notifyCategory.cxx index 432dfca159..11a3c52587 100644 --- a/dtool/src/prc/notifyCategory.cxx +++ b/dtool/src/prc/notifyCategory.cxx @@ -31,7 +31,7 @@ long NotifyCategory::_server_delta = 0; * */ NotifyCategory:: -NotifyCategory(const string &fullname, const string &basename, +NotifyCategory(const std::string &fullname, const std::string &basename, NotifyCategory *parent) : _fullname(fullname), _basename(basename), @@ -41,12 +41,12 @@ NotifyCategory(const string &fullname, const string &basename, ConfigVariable::F_dynamic), _local_modified(initial_invalid_cache()) { - if (_parent != (NotifyCategory *)NULL) { + if (_parent != nullptr) { _parent->_children.push_back(this); } // Only the unnamed top category is allowed not to have a parent. - nassertv(_parent != (NotifyCategory *)NULL || _fullname.empty()); + nassertv(_parent != nullptr || _fullname.empty()); } /** @@ -55,7 +55,7 @@ NotifyCategory(const string &fullname, const string &basename, * the Notify::out() stream and returns that. If the severity level is * disabled, this returns Notify::null(). */ -ostream &NotifyCategory:: +std::ostream &NotifyCategory:: out(NotifySeverity severity, bool prefix) const { if (is_on(severity)) { @@ -77,7 +77,7 @@ out(NotifySeverity severity, bool prefix) const { if (prefix) { if (get_notify_timestamp()) { // Format a timestamp to include as a prefix as well. - time_t now = time(NULL) + _server_delta; + time_t now = time(nullptr) + _server_delta; struct tm atm; #ifdef _WIN32 localtime_s(&atm, &now); @@ -151,9 +151,9 @@ set_server_delta(long delta) { * Returns the name of the config variable that controls this category. This * is called at construction time. */ -string NotifyCategory:: +std::string NotifyCategory:: get_config_name() const { - string config_name; + std::string config_name; if (_fullname.empty()) { config_name = "notify-level"; @@ -175,7 +175,7 @@ update_severity_cache() { nout << "Invalid severity name for " << _severity.get_name() << ": " << _severity.get_string_value() << "\n"; } - if (_parent != (NotifyCategory *)NULL) { + if (_parent != nullptr) { _severity_cache = _parent->get_severity(); } else { @@ -195,8 +195,8 @@ update_severity_cache() { */ bool NotifyCategory:: get_notify_timestamp() { - static ConfigVariableBool *notify_timestamp = NULL; - if (notify_timestamp == (ConfigVariableBool *)NULL) { + static ConfigVariableBool *notify_timestamp = nullptr; + if (notify_timestamp == nullptr) { notify_timestamp = new ConfigVariableBool ("notify-timestamp", false, "Set true to output the date & time with each notify message."); @@ -211,8 +211,8 @@ get_notify_timestamp() { */ bool NotifyCategory:: get_check_debug_notify_protect() { - static ConfigVariableBool *check_debug_notify_protect = NULL; - if (check_debug_notify_protect == (ConfigVariableBool *)NULL) { + static ConfigVariableBool *check_debug_notify_protect = nullptr; + if (check_debug_notify_protect == nullptr) { check_debug_notify_protect = new ConfigVariableBool ("check-debug-notify-protect", false, "Set true to issue a warning message if a debug or spam " diff --git a/dtool/src/prc/notifyCategory.h b/dtool/src/prc/notifyCategory.h index 61f4e71906..f3e99b09ba 100644 --- a/dtool/src/prc/notifyCategory.h +++ b/dtool/src/prc/notifyCategory.h @@ -31,12 +31,12 @@ */ class EXPCL_DTOOL_PRC NotifyCategory : public MemoryBase, public ConfigFlags { private: - NotifyCategory(const string &fullname, const string &basename, + NotifyCategory(const std::string &fullname, const std::string &basename, NotifyCategory *parent); PUBLISHED: - INLINE string get_fullname() const; - INLINE string get_basename() const; + INLINE std::string get_fullname() const; + INLINE std::string get_basename() const; INLINE NotifySeverity get_severity() const; INLINE void set_severity(NotifySeverity severity); MAKE_PROPERTY(fullname, get_fullname); @@ -55,21 +55,21 @@ PUBLISHED: INLINE bool is_spam() const; INLINE bool is_debug() const; #else - CONSTEXPR static bool is_spam(); - CONSTEXPR static bool is_debug(); + constexpr static bool is_spam(); + constexpr static bool is_debug(); #endif INLINE bool is_info() const; INLINE bool is_warning() const; INLINE bool is_error() const; INLINE bool is_fatal() const; - ostream &out(NotifySeverity severity, bool prefix = true) const; - INLINE ostream &spam(bool prefix = true) const; - INLINE ostream &debug(bool prefix = true) const; - INLINE ostream &info(bool prefix = true) const; - INLINE ostream &warning(bool prefix = true) const; - INLINE ostream &error(bool prefix = true) const; - INLINE ostream &fatal(bool prefix = true) const; + std::ostream &out(NotifySeverity severity, bool prefix = true) const; + INLINE std::ostream &spam(bool prefix = true) const; + INLINE std::ostream &debug(bool prefix = true) const; + INLINE std::ostream &info(bool prefix = true) const; + INLINE std::ostream &warning(bool prefix = true) const; + INLINE std::ostream &error(bool prefix = true) const; + INLINE std::ostream &fatal(bool prefix = true) const; size_t get_num_children() const; NotifyCategory *get_child(size_t i) const; @@ -79,16 +79,16 @@ PUBLISHED: static void set_server_delta(long delta); private: - string get_config_name() const; + std::string get_config_name() const; void update_severity_cache(); static bool get_notify_timestamp(); static bool get_check_debug_notify_protect(); - string _fullname; - string _basename; + std::string _fullname; + std::string _basename; NotifyCategory *_parent; ConfigVariableEnum _severity; - typedef vector Children; + typedef std::vector Children; Children _children; static long _server_delta; // not a time_t because server delta may be signed. @@ -99,7 +99,7 @@ private: friend class Notify; }; -INLINE ostream &operator << (ostream &out, const NotifyCategory &cat); +INLINE std::ostream &operator << (std::ostream &out, const NotifyCategory &cat); #include "notifyCategory.I" diff --git a/dtool/src/prc/notifyCategoryProxy.I b/dtool/src/prc/notifyCategoryProxy.I index 9a05f35625..eaca9b6e33 100644 --- a/dtool/src/prc/notifyCategoryProxy.I +++ b/dtool/src/prc/notifyCategoryProxy.I @@ -18,7 +18,7 @@ template NotifyCategory *NotifyCategoryProxy:: init() { - if (_ptr == (NotifyCategory *)NULL) { + if (_ptr == nullptr) { _ptr = GetCategory::get_category(); } return _ptr; @@ -33,7 +33,7 @@ init() { template INLINE NotifyCategory *NotifyCategoryProxy:: get_unsafe_ptr() { - nassertd(_ptr != (NotifyCategory *)NULL) { + nassertd(_ptr != nullptr) { init(); nout << "Uninitialized notify proxy: " << _ptr->get_fullname() << "\n"; } @@ -74,7 +74,7 @@ is_spam() { } #else template -CONSTEXPR bool NotifyCategoryProxy:: +constexpr bool NotifyCategoryProxy:: is_spam() { return false; } @@ -92,7 +92,7 @@ is_debug() { } #else template -CONSTEXPR bool NotifyCategoryProxy:: +constexpr bool NotifyCategoryProxy:: is_debug() { return false; } @@ -138,7 +138,7 @@ is_fatal() { * */ template -INLINE ostream &NotifyCategoryProxy:: +INLINE std::ostream &NotifyCategoryProxy:: out(NotifySeverity severity, bool prefix) { return get_unsafe_ptr()->out(severity, prefix); } @@ -147,7 +147,7 @@ out(NotifySeverity severity, bool prefix) { * */ template -INLINE ostream &NotifyCategoryProxy:: +INLINE std::ostream &NotifyCategoryProxy:: spam(bool prefix) { return get_unsafe_ptr()->spam(prefix); } @@ -156,7 +156,7 @@ spam(bool prefix) { * */ template -INLINE ostream &NotifyCategoryProxy:: +INLINE std::ostream &NotifyCategoryProxy:: debug(bool prefix) { return get_unsafe_ptr()->debug(prefix); } @@ -165,7 +165,7 @@ debug(bool prefix) { * */ template -INLINE ostream &NotifyCategoryProxy:: +INLINE std::ostream &NotifyCategoryProxy:: info(bool prefix) { return get_unsafe_ptr()->info(prefix); } @@ -174,7 +174,7 @@ info(bool prefix) { * */ template -INLINE ostream &NotifyCategoryProxy:: +INLINE std::ostream &NotifyCategoryProxy:: warning(bool prefix) { return get_unsafe_ptr()->warning(prefix); } @@ -183,7 +183,7 @@ warning(bool prefix) { * */ template -INLINE ostream &NotifyCategoryProxy:: +INLINE std::ostream &NotifyCategoryProxy:: error(bool prefix) { return get_unsafe_ptr()->error(prefix); } @@ -192,7 +192,7 @@ error(bool prefix) { * */ template -INLINE ostream &NotifyCategoryProxy:: +INLINE std::ostream &NotifyCategoryProxy:: fatal(bool prefix) { return get_unsafe_ptr()->fatal(prefix); } diff --git a/dtool/src/prc/notifyCategoryProxy.h b/dtool/src/prc/notifyCategoryProxy.h index 653da558de..06f38ec804 100644 --- a/dtool/src/prc/notifyCategoryProxy.h +++ b/dtool/src/prc/notifyCategoryProxy.h @@ -75,21 +75,21 @@ public: INLINE bool is_spam(); INLINE bool is_debug(); #else - CONSTEXPR static bool is_spam(); - CONSTEXPR static bool is_debug(); + constexpr static bool is_spam(); + constexpr static bool is_debug(); #endif INLINE bool is_info(); INLINE bool is_warning(); INLINE bool is_error(); INLINE bool is_fatal(); - INLINE ostream &out(NotifySeverity severity, bool prefix = true); - INLINE ostream &spam(bool prefix = true); - INLINE ostream &debug(bool prefix = true); - INLINE ostream &info(bool prefix = true); - INLINE ostream &warning(bool prefix = true); - INLINE ostream &error(bool prefix = true); - INLINE ostream &fatal(bool prefix = true); + INLINE std::ostream &out(NotifySeverity severity, bool prefix = true); + INLINE std::ostream &spam(bool prefix = true); + INLINE std::ostream &debug(bool prefix = true); + INLINE std::ostream &info(bool prefix = true); + INLINE std::ostream &warning(bool prefix = true); + INLINE std::ostream &error(bool prefix = true); + INLINE std::ostream &fatal(bool prefix = true); // The same functions as above, when accessed using proxy->function() // syntax, call get_safe_ptr(). These can be used safely either in static- @@ -103,7 +103,7 @@ private: }; template -INLINE ostream &operator << (ostream &out, NotifyCategoryProxy &proxy) { +INLINE std::ostream &operator << (std::ostream &out, NotifyCategoryProxy &proxy) { return out << proxy->get_fullname(); } @@ -159,7 +159,7 @@ INLINE ostream &operator << (ostream &out, NotifyCategoryProxy &pro } \ NotifyCategory *NotifyCategoryGetCategory_ ## basename:: \ get_category() { \ - return Notify::ptr()->get_category(string(actual_name), parent_category); \ + return Notify::ptr()->get_category(std::string(actual_name), parent_category); \ } #define NotifyCategoryDef(basename, parent_category) \ NotifyCategoryDefName(basename, #basename, parent_category); diff --git a/dtool/src/prc/notifySeverity.cxx b/dtool/src/prc/notifySeverity.cxx index 0ee750e879..d6547e8de1 100644 --- a/dtool/src/prc/notifySeverity.cxx +++ b/dtool/src/prc/notifySeverity.cxx @@ -14,6 +14,10 @@ #include "notifySeverity.h" #include "pnotify.h" +using std::istream; +using std::ostream; +using std::string; + ostream & operator << (ostream &out, NotifySeverity severity) { switch (severity) { diff --git a/dtool/src/prc/notifySeverity.h b/dtool/src/prc/notifySeverity.h index d16cdb89d8..f44e79ba55 100644 --- a/dtool/src/prc/notifySeverity.h +++ b/dtool/src/prc/notifySeverity.h @@ -28,8 +28,8 @@ enum NotifySeverity { }; END_PUBLISH -EXPCL_DTOOL_PRC ostream &operator << (ostream &out, NotifySeverity severity); -EXPCL_DTOOL_PRC istream &operator >> (istream &in, NotifySeverity &severity); +EXPCL_DTOOL_PRC std::ostream &operator << (std::ostream &out, NotifySeverity severity); +EXPCL_DTOOL_PRC std::istream &operator >> (std::istream &in, NotifySeverity &severity); #endif diff --git a/dtool/src/prc/pnotify.I b/dtool/src/prc/pnotify.I index 1cdea86f2d..4a1730acf5 100644 --- a/dtool/src/prc/pnotify.I +++ b/dtool/src/prc/pnotify.I @@ -34,7 +34,7 @@ has_assert_failed() const { * Returns the error message that corresponds to the assertion that most * recently failed. */ -INLINE const string &Notify:: +INLINE const std::string &Notify:: get_assert_error_message() const { return _assert_error_message; } diff --git a/dtool/src/prc/pnotify.h b/dtool/src/prc/pnotify.h index 27a346d0d9..6fe488862e 100644 --- a/dtool/src/prc/pnotify.h +++ b/dtool/src/prc/pnotify.h @@ -35,8 +35,8 @@ PUBLISHED: Notify(); ~Notify(); - void set_ostream_ptr(ostream *ostream_ptr, bool delete_later); - ostream *get_ostream_ptr() const; + void set_ostream_ptr(std::ostream *ostream_ptr, bool delete_later); + std::ostream *get_ostream_ptr() const; typedef bool AssertHandler(const char *expression, int line, const char *source_file); @@ -47,45 +47,45 @@ PUBLISHED: AssertHandler *get_assert_handler() const; INLINE bool has_assert_failed() const; - INLINE const string &get_assert_error_message() const; + INLINE const std::string &get_assert_error_message() const; INLINE void clear_assert_failed(); NotifyCategory *get_top_category(); - NotifyCategory *get_category(const string &basename, + NotifyCategory *get_category(const std::string &basename, NotifyCategory *parent_category); - NotifyCategory *get_category(const string &basename, - const string &parent_fullname); - NotifyCategory *get_category(const string &fullname); + NotifyCategory *get_category(const std::string &basename, + const std::string &parent_fullname); + NotifyCategory *get_category(const std::string &fullname); - static ostream &out(); - static ostream &null(); - static void write_string(const string &str); + static std::ostream &out(); + static std::ostream &null(); + static void write_string(const std::string &str); static Notify *ptr(); public: static ios_fmtflags get_literal_flag(); - bool assert_failure(const string &expression, int line, + bool assert_failure(const std::string &expression, int line, const char *source_file); bool assert_failure(const char *expression, int line, const char *source_file); - static NotifySeverity string_severity(const string &string); + static NotifySeverity string_severity(const std::string &string); void config_initialized(); private: - ostream *_ostream_ptr; + std::ostream *_ostream_ptr; bool _owns_ostream_ptr; - ostream *_null_ostream_ptr; + std::ostream *_null_ostream_ptr; AssertHandler *_assert_handler; bool _assert_failed; - string _assert_error_message; + std::string _assert_error_message; // This shouldn't be a pmap, since it might be invoked before we initialize // the global malloc pointers. - typedef map Categories; + typedef std::map Categories; Categories _categories; static Notify *_global_ptr; diff --git a/dtool/src/prc/prcKeyRegistry.cxx b/dtool/src/prc/prcKeyRegistry.cxx index 6329a8abbd..e505b96ecc 100644 --- a/dtool/src/prc/prcKeyRegistry.cxx +++ b/dtool/src/prc/prcKeyRegistry.cxx @@ -25,7 +25,7 @@ // Some versions of OpenSSL appear to define this as a macro. Yucky. #undef set_key -PrcKeyRegistry *PrcKeyRegistry::_global_ptr = NULL; +PrcKeyRegistry *PrcKeyRegistry::_global_ptr = nullptr; /** * There is only one PrcKeyRegistry in the world; use get_global_ptr() to get @@ -56,19 +56,19 @@ void PrcKeyRegistry:: record_keys(const KeyDef *key_def, size_t num_keys) { for (size_t i = 0; i < num_keys; i++) { const KeyDef *def = &key_def[i]; - if (def->_data != (char *)NULL) { + if (def->_data != nullptr) { // Clear the ith key. while (_keys.size() <= i) { Key key; - key._def = NULL; - key._pkey = NULL; + key._def = nullptr; + key._pkey = nullptr; key._generated_time = 0; _keys.push_back(key); } if (_keys[i]._def != def) { - if (_keys[i]._pkey != (EVP_PKEY *)NULL) { + if (_keys[i]._pkey != nullptr) { EVP_PKEY_free(_keys[i]._pkey); - _keys[i]._pkey = NULL; + _keys[i]._pkey = nullptr; } _keys[i]._def = def; _keys[i]._generated_time = def->_generated_time; @@ -88,15 +88,15 @@ set_key(size_t n, EVP_PKEY *pkey, time_t generated_time) { // Clear the nth key. while (_keys.size() <= n) { Key key; - key._def = NULL; - key._pkey = NULL; + key._def = nullptr; + key._pkey = nullptr; key._generated_time = 0; _keys.push_back(key); } - _keys[n]._def = NULL; - if (_keys[n]._pkey != (EVP_PKEY *)NULL) { + _keys[n]._def = nullptr; + if (_keys[n]._pkey != nullptr) { EVP_PKEY_free(_keys[n]._pkey); - _keys[n]._pkey = NULL; + _keys[n]._pkey = nullptr; } _keys[n]._pkey = pkey; _keys[n]._generated_time = generated_time; @@ -117,20 +117,20 @@ get_num_keys() const { */ EVP_PKEY *PrcKeyRegistry:: get_key(size_t n) const { - nassertr(n < _keys.size(), (EVP_PKEY *)NULL); + nassertr(n < _keys.size(), nullptr); - if (_keys[n]._def != (KeyDef *)NULL) { - if (_keys[n]._pkey == (EVP_PKEY *)NULL) { + if (_keys[n]._def != nullptr) { + if (_keys[n]._pkey == nullptr) { // Convert the def to a EVP_PKEY structure. const KeyDef *def = _keys[n]._def; BIO *mbio = BIO_new_mem_buf((void *)def->_data, def->_length); - EVP_PKEY *pkey = PEM_read_bio_PUBKEY(mbio, NULL, NULL, NULL); + EVP_PKEY *pkey = PEM_read_bio_PUBKEY(mbio, nullptr, nullptr, nullptr); ((PrcKeyRegistry *)this)->_keys[n]._pkey = pkey; BIO_free(mbio); - if (pkey == (EVP_PKEY *)NULL) { + if (pkey == nullptr) { // Couldn't read the bio for some reason. - ((PrcKeyRegistry *)this)->_keys[n]._def = NULL; + ((PrcKeyRegistry *)this)->_keys[n]._def = nullptr; } } } @@ -154,7 +154,7 @@ get_generated_time(size_t n) const { */ PrcKeyRegistry *PrcKeyRegistry:: get_global_ptr() { - if (_global_ptr == (PrcKeyRegistry *)NULL) { + if (_global_ptr == nullptr) { _global_ptr = new PrcKeyRegistry; } return _global_ptr; diff --git a/dtool/src/prc/prcKeyRegistry.h b/dtool/src/prc/prcKeyRegistry.h index 0a21d182ad..c05e69a445 100644 --- a/dtool/src/prc/prcKeyRegistry.h +++ b/dtool/src/prc/prcKeyRegistry.h @@ -63,7 +63,7 @@ private: time_t _generated_time; }; - typedef vector Keys; + typedef std::vector Keys; Keys _keys; static PrcKeyRegistry *_global_ptr; diff --git a/dtool/src/prc/streamReader.I b/dtool/src/prc/streamReader.I index 8f96aa85f4..e15953aeba 100644 --- a/dtool/src/prc/streamReader.I +++ b/dtool/src/prc/streamReader.I @@ -15,7 +15,7 @@ * */ INLINE StreamReader:: -StreamReader(istream &in) : +StreamReader(std::istream &in) : _in(&in), _owns_stream(false) { @@ -26,7 +26,7 @@ StreamReader(istream &in) : * StreamReader destructs. */ INLINE StreamReader:: -StreamReader(istream *in, bool owns_stream) : +StreamReader(std::istream *in, bool owns_stream) : _in(in), _owns_stream(owns_stream) { @@ -67,7 +67,7 @@ INLINE StreamReader:: /** * Returns the stream in use. */ -INLINE istream *StreamReader:: +INLINE std::istream *StreamReader:: get_istream() const { return _in; } diff --git a/dtool/src/prc/streamReader.cxx b/dtool/src/prc/streamReader.cxx index e9fa173ad1..74f278e220 100644 --- a/dtool/src/prc/streamReader.cxx +++ b/dtool/src/prc/streamReader.cxx @@ -14,6 +14,8 @@ #include "streamReader.h" #include "memoryHook.h" +using std::string; + /** * Extracts a variable-length string. diff --git a/dtool/src/prc/streamReader.h b/dtool/src/prc/streamReader.h index 1643dd4a9c..a317f0a783 100644 --- a/dtool/src/prc/streamReader.h +++ b/dtool/src/prc/streamReader.h @@ -27,15 +27,15 @@ */ class EXPCL_DTOOL_PRC StreamReader { public: - INLINE StreamReader(istream &in); + INLINE StreamReader(std::istream &in); PUBLISHED: - INLINE explicit StreamReader(istream *in, bool owns_stream); + INLINE explicit StreamReader(std::istream *in, bool owns_stream); INLINE StreamReader(const StreamReader ©); INLINE void operator = (const StreamReader ©); INLINE ~StreamReader(); - INLINE istream *get_istream() const; - MAKE_PROPERTY(istream, get_istream); + INLINE std::istream *get_istream() const; + MAKE_PROPERTY(std::istream, get_istream); BLOCKING INLINE bool get_bool(); BLOCKING INLINE int8_t get_int8(); @@ -59,10 +59,10 @@ PUBLISHED: BLOCKING INLINE float get_be_float32(); BLOCKING INLINE PN_float64 get_be_float64(); - BLOCKING string get_string(); - BLOCKING string get_string32(); - BLOCKING string get_z_string(); - BLOCKING string get_fixed_string(size_t size); + BLOCKING std::string get_string(); + BLOCKING std::string get_string32(); + BLOCKING std::string get_z_string(); + BLOCKING std::string get_fixed_string(size_t size); BLOCKING void skip_bytes(size_t size); BLOCKING size_t extract_bytes(unsigned char *into, size_t size); @@ -73,10 +73,10 @@ PUBLISHED: public: BLOCKING vector_uchar extract_bytes(size_t size); - BLOCKING string readline(); + BLOCKING std::string readline(); private: - istream *_in; + std::istream *_in; bool _owns_stream; }; diff --git a/dtool/src/prc/streamReader_ext.cxx b/dtool/src/prc/streamReader_ext.cxx index 2876f82faa..94c346e370 100644 --- a/dtool/src/prc/streamReader_ext.cxx +++ b/dtool/src/prc/streamReader_ext.cxx @@ -41,9 +41,9 @@ extract_bytes(size_t size) { */ PyObject *Extension:: readline() { - istream *in = _this->get_istream(); + std::istream *in = _this->get_istream(); - string line; + std::string line; int ch = in->get(); while (!in->eof() && !in->fail()) { line += ch; @@ -68,8 +68,8 @@ readline() { PyObject *Extension:: readlines() { PyObject *lst = PyList_New(0); - if (lst == NULL) { - return NULL; + if (lst == nullptr) { + return nullptr; } PyObject *py_line = readline(); diff --git a/dtool/src/prc/streamWrapper.I b/dtool/src/prc/streamWrapper.I index 788498aceb..0f9d65d414 100644 --- a/dtool/src/prc/streamWrapper.I +++ b/dtool/src/prc/streamWrapper.I @@ -36,7 +36,7 @@ StreamWrapperBase() { */ INLINE void StreamWrapperBase:: acquire() { - _lock.acquire(); + _lock.lock(); #ifdef SIMPLE_THREADS while (_lock_flag) { thread_yield(); @@ -55,14 +55,14 @@ release() { assert(_lock_flag); _lock_flag = false; #endif - _lock.release(); + _lock.unlock(); } /** * */ INLINE IStreamWrapper:: -IStreamWrapper(istream *stream, bool owns_pointer) : +IStreamWrapper(std::istream *stream, bool owns_pointer) : _istream(stream), _owns_pointer(owns_pointer) { @@ -72,7 +72,7 @@ IStreamWrapper(istream *stream, bool owns_pointer) : * */ INLINE IStreamWrapper:: -IStreamWrapper(istream &stream) : +IStreamWrapper(std::istream &stream) : _istream(&stream), _owns_pointer(false) { @@ -81,7 +81,7 @@ IStreamWrapper(istream &stream) : /** * Returns the istream this object is wrapping. */ -INLINE istream *IStreamWrapper:: +INLINE std::istream *IStreamWrapper:: get_istream() const { return _istream; } @@ -103,7 +103,7 @@ get() { * */ INLINE OStreamWrapper:: -OStreamWrapper(ostream *stream, bool owns_pointer, bool stringstream_hack) : +OStreamWrapper(std::ostream *stream, bool owns_pointer, bool stringstream_hack) : _ostream(stream), _owns_pointer(owns_pointer) #ifdef WIN32_VC @@ -116,7 +116,7 @@ OStreamWrapper(ostream *stream, bool owns_pointer, bool stringstream_hack) : * */ INLINE OStreamWrapper:: -OStreamWrapper(ostream &stream) : +OStreamWrapper(std::ostream &stream) : _ostream(&stream), _owns_pointer(false) #ifdef WIN32_VC @@ -128,7 +128,7 @@ OStreamWrapper(ostream &stream) : /** * Returns the ostream this object is wrapping. */ -INLINE ostream *OStreamWrapper:: +INLINE std::ostream *OStreamWrapper:: get_ostream() const { return _ostream; } @@ -151,7 +151,7 @@ put(char c) { * */ INLINE StreamWrapper:: -StreamWrapper(iostream *stream, bool owns_pointer, bool stringstream_hack) : +StreamWrapper(std::iostream *stream, bool owns_pointer, bool stringstream_hack) : IStreamWrapper(stream, false), OStreamWrapper(stream, false, stringstream_hack), _iostream(stream), @@ -163,7 +163,7 @@ StreamWrapper(iostream *stream, bool owns_pointer, bool stringstream_hack) : * */ INLINE StreamWrapper:: -StreamWrapper(iostream &stream) : +StreamWrapper(std::iostream &stream) : IStreamWrapper(&stream, false), OStreamWrapper(&stream, false), _iostream(&stream), @@ -174,7 +174,7 @@ StreamWrapper(iostream &stream) : /** * Returns the iostream this object is wrapping. */ -INLINE iostream *StreamWrapper:: +INLINE std::iostream *StreamWrapper:: get_iostream() const { return _iostream; } diff --git a/dtool/src/prc/streamWrapper.cxx b/dtool/src/prc/streamWrapper.cxx index 68f8e47abb..3c59fb3a90 100644 --- a/dtool/src/prc/streamWrapper.cxx +++ b/dtool/src/prc/streamWrapper.cxx @@ -13,6 +13,8 @@ #include "streamWrapper.h" +using std::streamsize; + /** * */ @@ -121,7 +123,7 @@ streamsize IStreamWrapper:: seek_gpos_eof() { streamsize pos; acquire(); - _istream->seekg(0, ios::end); + _istream->seekg(0, std::ios::end); pos = _istream->tellg(); release(); @@ -204,7 +206,7 @@ void OStreamWrapper:: seek_eof_write(const char *buffer, streamsize num_bytes, bool &fail) { acquire(); _ostream->clear(); - _ostream->seekp(0, ios::end); + _ostream->seekp(0, std::ios::end); #ifdef WIN32_VC if (_ostream->fail() && _stringstream_hack) { @@ -228,7 +230,7 @@ streamsize OStreamWrapper:: seek_ppos_eof() { streamsize pos; acquire(); - _ostream->seekp(0, ios::end); + _ostream->seekp(0, std::ios::end); #ifdef WIN32_VC if (_ostream->fail() && _stringstream_hack) { diff --git a/dtool/src/prc/streamWrapper.h b/dtool/src/prc/streamWrapper.h index f3e4028c1b..b5a4d5bf72 100644 --- a/dtool/src/prc/streamWrapper.h +++ b/dtool/src/prc/streamWrapper.h @@ -24,9 +24,7 @@ class EXPCL_DTOOL_PRC StreamWrapperBase { protected: INLINE StreamWrapperBase(); - -private: - INLINE StreamWrapperBase(const StreamWrapperBase ©) DELETED; + INLINE StreamWrapperBase(const StreamWrapperBase ©) = delete; PUBLISHED: INLINE void acquire(); @@ -50,24 +48,24 @@ private: */ class EXPCL_DTOOL_PRC IStreamWrapper : virtual public StreamWrapperBase { public: - INLINE IStreamWrapper(istream *stream, bool owns_pointer); + INLINE IStreamWrapper(std::istream *stream, bool owns_pointer); PUBLISHED: - INLINE explicit IStreamWrapper(istream &stream); + INLINE explicit IStreamWrapper(std::istream &stream); ~IStreamWrapper(); - INLINE istream *get_istream() const; - MAKE_PROPERTY(istream, get_istream); + INLINE std::istream *get_istream() const; + MAKE_PROPERTY(std::istream, get_istream); public: - void read(char *buffer, streamsize num_bytes); - void read(char *buffer, streamsize num_bytes, streamsize &read_bytes); - void read(char *buffer, streamsize num_bytes, streamsize &read_bytes, bool &eof); - void seek_read(streamsize pos, char *buffer, streamsize num_bytes, streamsize &read_bytes, bool &eof); + void read(char *buffer, std::streamsize num_bytes); + void read(char *buffer, std::streamsize num_bytes, std::streamsize &read_bytes); + void read(char *buffer, std::streamsize num_bytes, std::streamsize &read_bytes, bool &eof); + void seek_read(std::streamsize pos, char *buffer, std::streamsize num_bytes, std::streamsize &read_bytes, bool &eof); INLINE int get(); - streamsize seek_gpos_eof(); + std::streamsize seek_gpos_eof(); private: - istream *_istream; + std::istream *_istream; bool _owns_pointer; }; @@ -77,24 +75,24 @@ private: */ class EXPCL_DTOOL_PRC OStreamWrapper : virtual public StreamWrapperBase { public: - INLINE OStreamWrapper(ostream *stream, bool owns_pointer, bool stringstream_hack = false); + INLINE OStreamWrapper(std::ostream *stream, bool owns_pointer, bool stringstream_hack = false); PUBLISHED: - INLINE explicit OStreamWrapper(ostream &stream); + INLINE explicit OStreamWrapper(std::ostream &stream); ~OStreamWrapper(); - INLINE ostream *get_ostream() const; - MAKE_PROPERTY(ostream, get_ostream); + INLINE std::ostream *get_ostream() const; + MAKE_PROPERTY(std::ostream, get_ostream); public: - void write(const char *buffer, streamsize num_bytes); - void write(const char *buffer, streamsize num_bytes, bool &fail); - void seek_write(streamsize pos, const char *buffer, streamsize num_bytes, bool &fail); - void seek_eof_write(const char *buffer, streamsize num_bytes, bool &fail); + void write(const char *buffer, std::streamsize num_bytes); + void write(const char *buffer, std::streamsize num_bytes, bool &fail); + void seek_write(std::streamsize pos, const char *buffer, std::streamsize num_bytes, bool &fail); + void seek_eof_write(const char *buffer, std::streamsize num_bytes, bool &fail); INLINE bool put(char c); - streamsize seek_ppos_eof(); + std::streamsize seek_ppos_eof(); private: - ostream *_ostream; + std::ostream *_ostream; bool _owns_pointer; // This flag is necessary to work around a weird quirk in the MSVS C++ @@ -113,16 +111,16 @@ private: */ class EXPCL_DTOOL_PRC StreamWrapper : public IStreamWrapper, public OStreamWrapper { public: - INLINE StreamWrapper(iostream *stream, bool owns_pointer, bool stringstream_hack = false); + INLINE StreamWrapper(std::iostream *stream, bool owns_pointer, bool stringstream_hack = false); PUBLISHED: - INLINE explicit StreamWrapper(iostream &stream); + INLINE explicit StreamWrapper(std::iostream &stream); ~StreamWrapper(); - INLINE iostream *get_iostream() const; - MAKE_PROPERTY(iostream, get_iostream); + INLINE std::iostream *get_iostream() const; + MAKE_PROPERTY(std::iostream, get_iostream); private: - iostream *_iostream; + std::iostream *_iostream; bool _owns_pointer; }; diff --git a/dtool/src/prc/streamWriter.I b/dtool/src/prc/streamWriter.I index 8bbe23af62..b2485d3fc7 100644 --- a/dtool/src/prc/streamWriter.I +++ b/dtool/src/prc/streamWriter.I @@ -15,7 +15,7 @@ * */ INLINE StreamWriter:: -StreamWriter(ostream &out) : +StreamWriter(std::ostream &out) : #ifdef HAVE_PYTHON softspace(0), #endif @@ -28,7 +28,7 @@ StreamWriter(ostream &out) : * */ INLINE StreamWriter:: -StreamWriter(ostream *out, bool owns_stream) : +StreamWriter(std::ostream *out, bool owns_stream) : #ifdef HAVE_PYTHON softspace(0), #endif @@ -75,7 +75,7 @@ INLINE StreamWriter:: /** * Returns the stream in use. */ -INLINE ostream *StreamWriter:: +INLINE std::ostream *StreamWriter:: get_ostream() const { return _out; } @@ -265,7 +265,7 @@ add_be_float64(PN_float64 value) { * followed by n bytes. */ INLINE void StreamWriter:: -add_string(const string &str) { +add_string(const std::string &str) { // The max sendable length for a string is 2^16. nassertv(str.length() <= (uint16_t)0xffff); @@ -280,7 +280,7 @@ add_string(const string &str) { * Adds a variable-length string to the stream, using a 32-bit length field. */ INLINE void StreamWriter:: -add_string32(const string &str) { +add_string32(const std::string &str) { // Strings always are preceded by their length add_uint32((uint32_t)str.length()); @@ -292,7 +292,7 @@ add_string32(const string &str) { * Adds a variable-length string to the stream, as a NULL-terminated string. */ INLINE void StreamWriter:: -add_z_string(string str) { +add_z_string(std::string str) { // We must not have any nested null characters in the string. size_t null_pos = str.find('\0'); // Add the string (sans the null character). @@ -308,7 +308,7 @@ add_z_string(string str) { * greater than the requested size, this will silently truncate the string. */ INLINE void StreamWriter:: -add_fixed_string(const string &str, size_t size) { +add_fixed_string(const std::string &str, size_t size) { if (str.length() < size) { append_data(str); pad_bytes(size - str.length()); @@ -330,7 +330,7 @@ append_data(const void *data, size_t size) { * Appends some more raw data to the end of the streamWriter. */ INLINE void StreamWriter:: -append_data(const string &data) { +append_data(const std::string &data) { append_data(data.data(), data.length()); } @@ -347,6 +347,6 @@ flush() { * to sys.stderr and/or sys.stdout in Python. */ INLINE void StreamWriter:: -write(const string &data) { +write(const std::string &data) { append_data(data.data(), data.length()); } diff --git a/dtool/src/prc/streamWriter.h b/dtool/src/prc/streamWriter.h index b39db968c0..cc00ef9ce3 100644 --- a/dtool/src/prc/streamWriter.h +++ b/dtool/src/prc/streamWriter.h @@ -28,15 +28,15 @@ */ class EXPCL_DTOOL_PRC StreamWriter { public: - INLINE StreamWriter(ostream &out); + INLINE StreamWriter(std::ostream &out); PUBLISHED: - INLINE explicit StreamWriter(ostream *out, bool owns_stream); + INLINE explicit StreamWriter(std::ostream *out, bool owns_stream); INLINE StreamWriter(const StreamWriter ©); INLINE void operator = (const StreamWriter ©); INLINE ~StreamWriter(); - INLINE ostream *get_ostream() const; - MAKE_PROPERTY(ostream, get_ostream); + INLINE std::ostream *get_ostream() const; + MAKE_PROPERTY(std::ostream, get_ostream); BLOCKING INLINE void add_bool(bool value); BLOCKING INLINE void add_int8(int8_t value); @@ -62,24 +62,24 @@ PUBLISHED: BLOCKING INLINE void add_be_float32(float value); BLOCKING INLINE void add_be_float64(PN_float64 value); - BLOCKING INLINE void add_string(const string &str); - BLOCKING INLINE void add_string32(const string &str); - BLOCKING INLINE void add_z_string(string str); - BLOCKING INLINE void add_fixed_string(const string &str, size_t size); + BLOCKING INLINE void add_string(const std::string &str); + BLOCKING INLINE void add_string32(const std::string &str); + BLOCKING INLINE void add_z_string(std::string str); + BLOCKING INLINE void add_fixed_string(const std::string &str, size_t size); BLOCKING void pad_bytes(size_t size); EXTENSION(void append_data(PyObject *data)); BLOCKING INLINE void flush(); - BLOCKING INLINE void write(const string &str); + BLOCKING INLINE void write(const std::string &str); public: BLOCKING INLINE void append_data(const void *data, size_t size); - BLOCKING INLINE void append_data(const string &data); + BLOCKING INLINE void append_data(const std::string &data); private: - ostream *_out; + std::ostream *_out; bool _owns_stream; #ifdef HAVE_PYTHON diff --git a/dtool/src/prckeys/makePrcKey.cxx b/dtool/src/prckeys/makePrcKey.cxx index 6832860540..a6ee834b04 100644 --- a/dtool/src/prckeys/makePrcKey.cxx +++ b/dtool/src/prckeys/makePrcKey.cxx @@ -30,6 +30,9 @@ #include "openssl/rand.h" #include "openssl/bio.h" +using std::cerr; +using std::string; + class KeyNumber { public: int _number; @@ -69,7 +72,7 @@ output_ssl_errors() { * string. */ void -output_c_string(ostream &out, const string &string_name, +output_c_string(std::ostream &out, const string &string_name, size_t index, BIO *mbio) { char *data_ptr; size_t data_size = BIO_get_mem_data(mbio, &data_ptr); @@ -94,8 +97,8 @@ output_c_string(ostream &out, const string &string_name, out << data_ptr[i]; } else { - out << "\\x" << hex << setw(2) << setfill('0') - << (unsigned int)(unsigned char)data_ptr[i] << dec; + out << "\\x" << std::hex << std::setw(2) << std::setfill('0') + << (unsigned int)(unsigned char)data_ptr[i] << std::dec; } } } @@ -163,7 +166,7 @@ write_public_keys(Filename outfile) { for (i = 0; i < num_keys; i++) { EVP_PKEY *pkey = pkr->get_key(i); - if (pkey != (EVP_PKEY *)NULL) { + if (pkey != nullptr) { if (!PEM_write_bio_PUBKEY(mbio, pkey)) { output_ssl_errors(); exit(1); @@ -184,11 +187,11 @@ write_public_keys(Filename outfile) { EVP_PKEY *pkey = pkr->get_key(i); time_t generated_time = pkr->get_generated_time(i); - if (pkey != (EVP_PKEY *)NULL) { + if (pkey != nullptr) { out << " { prc_pubkey" << i << "_data, prc_pubkey" << i << "_length, " << generated_time << " },\n"; } else { - out << " { NULL, 0, 0 },\n"; + out << " { nullptr, 0, 0 },\n"; } }; @@ -220,17 +223,17 @@ write_private_key(EVP_PKEY *pkey, Filename outfile, int n, time_t now, BIO *mbio = BIO_new(BIO_s_mem()); int write_result; - if (pp != NULL && *pp == '\0') { + if (pp != nullptr && *pp == '\0') { // The supplied password was the empty string. This means not to encrypt // the private key. write_result = - PEM_write_bio_PKCS8PrivateKey(mbio, pkey, NULL, NULL, 0, NULL, NULL); + PEM_write_bio_PKCS8PrivateKey(mbio, pkey, nullptr, nullptr, 0, nullptr, nullptr); } else { // Otherwise, the default is to encrypt it. write_result = PEM_write_bio_PKCS8PrivateKey(mbio, pkey, EVP_des_ede3_cbc(), - NULL, 0, NULL, (void *)pp); + nullptr, 0, nullptr, (void *)pp); } if (!write_result) { @@ -427,7 +430,7 @@ main(int argc, char **argv) { // Load the OpenSSL algorithms. OpenSSL_add_all_algorithms(); - time_t now = time(NULL); + time_t now = time(nullptr); string name = priv_outfile.get_fullpath_wo_extension(); string prefix, suffix; @@ -448,7 +451,7 @@ main(int argc, char **argv) { KeyNumbers::iterator ki; for (ki = key_numbers.begin(); ki != key_numbers.end(); ++ki) { int n = (*ki)._number; - const char *pp = NULL; + const char *pp = nullptr; if ((*ki)._got_pass_phrase) { pp = (*ki)._pass_phrase.c_str(); } @@ -456,7 +459,7 @@ main(int argc, char **argv) { EVP_PKEY *pkey = generate_key(); PrcKeyRegistry::get_global_ptr()->set_key(n, pkey, now); - ostringstream strm; + std::ostringstream strm; if (got_hash || n != 1) { // If we got an explicit hash mark, we always output the number. If we // did not get an explicit hash mark, we output the number only if it is diff --git a/dtool/src/prckeys/signPrcFile_src.cxx b/dtool/src/prckeys/signPrcFile_src.cxx index 0d9f58cfa4..5e9d04a1b4 100644 --- a/dtool/src/prckeys/signPrcFile_src.cxx +++ b/dtool/src/prckeys/signPrcFile_src.cxx @@ -30,6 +30,9 @@ #include "openssl/bio.h" #include "openssl/evp.h" +using std::cerr; +using std::string; + string progname = PROGNAME; /** @@ -77,7 +80,7 @@ read_prc_line(const string &line, string &data) { * indicated string. */ void -read_file(istream &in, string &data) { +read_file(std::istream &in, string &data) { // We avoid getline() here because of its notorious problem with last lines // that lack a trailing newline character. static const size_t buffer_size = 1024; @@ -92,7 +95,7 @@ read_file(istream &in, string &data) { // Look for the first line in the buffer.. char *newline = (char *)memchr((void *)buffer, '\n', count); - if (newline == NULL) { + if (newline == nullptr) { // The buffer was one long line. Huh. prev_line += string(buffer, count); @@ -104,7 +107,7 @@ read_file(istream &in, string &data) { // Now look for the next line, etc. char *start = newline + 1; newline = (char *)memchr((void *)start, '\n', buffer_end - start); - while (newline != NULL) { + while (newline != nullptr) { length = newline - start; read_prc_line(string(start, length + 1), data); start = newline + 1; @@ -129,7 +132,7 @@ read_file(istream &in, string &data) { * Outputs the indicated data stream as a series of hex digits. */ void -output_hex(ostream &out, const unsigned char *data, size_t size) { +output_hex(std::ostream &out, const unsigned char *data, size_t size) { } /** @@ -155,10 +158,10 @@ sign_prc(Filename filename, bool no_comments, EVP_PKEY *pkey) { } // Append the comments before the signature (these get signed too). - ostringstream strm; + std::ostringstream strm; strm << "##!\n"; if (!no_comments) { - time_t now = time(NULL); + time_t now = time(nullptr); struct tm *t = localtime(&now); char formatted[128]; strftime(formatted, 128, "%I:%M %p %B %d, %Y", t); @@ -203,7 +206,7 @@ sign_prc(Filename filename, bool no_comments, EVP_PKEY *pkey) { } cerr << "Rewriting " << filename << "\n"; - out << data << hex << setfill('0'); + out << data << std::hex << std::setfill('0'); static const size_t row_width = 32; for (size_t p = 0; p < sig_size; p += row_width) { out << "##!sig "; @@ -214,11 +217,11 @@ sign_prc(Filename filename, bool no_comments, EVP_PKEY *pkey) { end = p+row_width; for (size_t q = p; q < end; q++) { - out << setw(2) << (unsigned int)sig_data[q]; + out << std::setw(2) << (unsigned int)sig_data[q]; } out << "\n"; } - out << dec; + out << std::dec; delete[] sig_data; } @@ -265,7 +268,7 @@ usage() { int main(int argc, char **argv) { preprocess_argv(argc, argv); - if (argv[0] != NULL && *argv[0]) { + if (argv[0] != nullptr && *argv[0]) { // Get the program name from the command-line arguments, if the OS // provides it. Filename progfile = Filename::from_os_specific(argv[0]); @@ -318,16 +321,16 @@ main(int argc, char **argv) { OpenSSL_add_all_algorithms(); // Convert the compiled-in data to an EVP_PKEY. - const char *pp = NULL; + const char *pp = nullptr; if (got_pass_phrase) { pp = pass_phrase.c_str(); } BIO *mbio = BIO_new_mem_buf((void *)KEY_DATA, KEY_LENGTH); - EVP_PKEY *pkey = PEM_read_bio_PrivateKey(mbio, NULL, NULL, (void *)pp); + EVP_PKEY *pkey = PEM_read_bio_PrivateKey(mbio, nullptr, nullptr, (void *)pp); BIO_free(mbio); - if (pkey == (EVP_PKEY *)NULL) { + if (pkey == nullptr) { // Actually, we're not 100% sure this was the problem, but we can't really // tell why it failed, and we're 99% sure anyway. cerr << "Invalid pass phrase.\n"; diff --git a/dtool/src/pystub/pystub.cxx b/dtool/src/pystub/pystub.cxx index f9a30e74bf..ac6586c6ff 100644 --- a/dtool/src/pystub/pystub.cxx +++ b/dtool/src/pystub/pystub.cxx @@ -121,6 +121,7 @@ extern "C" { EXPCL_PYSTUB int PyObject_Repr(...); EXPCL_PYSTUB int PyObject_RichCompareBool(...); EXPCL_PYSTUB int PyObject_SelfIter(...); + EXPCL_PYSTUB int PyObject_SetAttr(...); EXPCL_PYSTUB int PyObject_SetAttrString(...); EXPCL_PYSTUB int PyObject_Str(...); EXPCL_PYSTUB int PyObject_Type(...); @@ -192,6 +193,7 @@ extern "C" { EXPCL_PYSTUB int _PyArg_Parse_SizeT(...); EXPCL_PYSTUB int _PyErr_BadInternalCall(...); EXPCL_PYSTUB int _PyLong_AsByteArray(...); + EXPCL_PYSTUB int _PyLong_Sign(...); EXPCL_PYSTUB int _PyObject_CallFunction_SizeT(...); EXPCL_PYSTUB int _PyObject_CallMethod_SizeT(...); EXPCL_PYSTUB int _PyObject_DebugFree(...); @@ -350,6 +352,7 @@ int PyObject_Malloc(...) { return 0; } int PyObject_Repr(...) { return 0; } int PyObject_RichCompareBool(...) { return 0; } int PyObject_SelfIter(...) { return 0; } +int PyObject_SetAttr(...) { return 0; } int PyObject_SetAttrString(...) { return 0; } int PyObject_Str(...) { return 0; } int PyObject_Type(...) { return 0; } @@ -421,6 +424,7 @@ int _PyArg_ParseTupleAndKeywords_SizeT(...) { return 0; }; int _PyArg_Parse_SizeT(...) { return 0; }; int _PyErr_BadInternalCall(...) { return 0; }; int _PyLong_AsByteArray(...) { return 0; }; +int _PyLong_Sign(...) { return 0; }; int _PyObject_CallFunction_SizeT(...) { return 0; }; int _PyObject_CallMethod_SizeT(...) { return 0; }; int _PyObject_DebugFree(...) { return 0; }; @@ -449,31 +453,31 @@ void PyEval_InitThreads() { } -void *PyExc_AssertionError = (void *)NULL; -void *PyExc_AttributeError = (void *)NULL; -void *PyExc_BufferError = (void *)NULL; -void *PyExc_ConnectionError = (void *)NULL; -void *PyExc_Exception = (void *)NULL; -void *PyExc_FutureWarning = (void *)NULL; -void *PyExc_ImportError = (void *)NULL; -void *PyExc_IndexError = (void *)NULL; -void *PyExc_KeyError = (void *)NULL; -void *PyExc_OSError = (void *)NULL; -void *PyExc_OverflowError = (void *)NULL; -void *PyExc_RuntimeError = (void *)NULL; -void *PyExc_StandardError = (void *)NULL; -void *PyExc_StopIteration = (void *)NULL; -void *PyExc_SystemExit = (void *)NULL; -void *PyExc_TypeError = (void *)NULL; -void *PyExc_ValueError = (void *)NULL; -void *PyTuple_Type = (void *)NULL; -void *PyType_Type = (void *)NULL; -void *_PyThreadState_Current = (void *)NULL; -void *_Py_FalseStruct = (void *)NULL; -void *_Py_NoneStruct = (void *)NULL; -void *_Py_NotImplementedStruct = (void *)NULL; -void *_Py_TrueStruct = (void *)NULL; -void *_Py_ZeroStruct = (void *)NULL; +void *PyExc_AssertionError = nullptr; +void *PyExc_AttributeError = nullptr; +void *PyExc_BufferError = nullptr; +void *PyExc_ConnectionError = nullptr; +void *PyExc_Exception = nullptr; +void *PyExc_FutureWarning = nullptr; +void *PyExc_ImportError = nullptr; +void *PyExc_IndexError = nullptr; +void *PyExc_KeyError = nullptr; +void *PyExc_OSError = nullptr; +void *PyExc_OverflowError = nullptr; +void *PyExc_RuntimeError = nullptr; +void *PyExc_StandardError = nullptr; +void *PyExc_StopIteration = nullptr; +void *PyExc_SystemExit = nullptr; +void *PyExc_TypeError = nullptr; +void *PyExc_ValueError = nullptr; +void *PyTuple_Type = nullptr; +void *PyType_Type = nullptr; +void *_PyThreadState_Current = nullptr; +void *_Py_FalseStruct = nullptr; +void *_Py_NoneStruct = nullptr; +void *_Py_NotImplementedStruct = nullptr; +void *_Py_TrueStruct = nullptr; +void *_Py_ZeroStruct = nullptr; void diff --git a/dtool/src/test_interrogate/test_interrogate.cxx b/dtool/src/test_interrogate/test_interrogate.cxx index 6c2b961ff3..590b8ac873 100644 --- a/dtool/src/test_interrogate/test_interrogate.cxx +++ b/dtool/src/test_interrogate/test_interrogate.cxx @@ -23,6 +23,11 @@ #include +using std::cerr; +using std::cout; +using std::ostream; +using std::string; + static ostream & indent(ostream &out, int indent_level) { for (int i = 0; i < indent_level; i++) { @@ -586,7 +591,7 @@ main(int argc, char **argv) { #endif void *dl = load_dso(DSearchPath(), pathname); - if (dl == NULL) { + if (dl == nullptr) { cerr << "Unable to load: " << load_dso_error() << "\n"; return_status++; } diff --git a/dtool/src/test_interrogate/test_lib.cxx b/dtool/src/test_interrogate/test_lib.cxx index cab224118c..89ccafccfc 100644 --- a/dtool/src/test_interrogate/test_lib.cxx +++ b/dtool/src/test_interrogate/test_lib.cxx @@ -34,7 +34,7 @@ int stupid_global; Configure(test_lib); ConfigureFn(test_lib) { - cerr << "In test_lib configure function!" << endl; + std::cerr << "In test_lib configure function!" << std::endl; } ConfigureLibSym; diff --git a/makepanda/installer.nsi b/makepanda/installer.nsi index 58cfd2e9db..f158a50c26 100644 --- a/makepanda/installer.nsi +++ b/makepanda/installer.nsi @@ -1239,8 +1239,13 @@ done: FunctionEnd +!ifndef LVM_GETITEMCOUNT !define LVM_GETITEMCOUNT 0x1004 +!endif + +!ifndef LVM_GETITEMTEXT !define LVM_GETITEMTEXT 0x102D +!endif Function DumpLog Exch $5 diff --git a/makepanda/makepanda.py b/makepanda/makepanda.py index 131f5d0af0..3d220b380d 100755 --- a/makepanda/makepanda.py +++ b/makepanda/makepanda.py @@ -15,9 +15,11 @@ try: import queue else: import Queue as queue +except KeyboardInterrupt: + raise except: print("You are either using an incomplete or an old version of Python!") - print("Please install the development package of Python 2.x and try again.") + print("Please install the development package of Python and try again.") exit(1) from makepandacore import * @@ -317,9 +319,7 @@ def parseopts(args): usage("Invalid SHA-1 hash given for --git-commit option!") if GetTarget() == 'windows': - show_warning = False if not MSVC_VERSION: - show_warning = True print("No MSVC version specified. Defaulting to 14 (Visual Studio 2015).") MSVC_VERSION = (14, 0) else: @@ -327,22 +327,19 @@ def parseopts(args): MSVC_VERSION = tuple(int(d) for d in MSVC_VERSION.split('.'))[:2] if (len(MSVC_VERSION) == 1): MSVC_VERSION += (0,) - if MSVC_VERSION < (14, 0): - show_warning = True except: usage("Invalid setting for --msvc-version") - if show_warning: - warn_prefix = "%sWARNING:%s " % (GetColor("red"), GetColor()) + if MSVC_VERSION < (14, 0): + warn_prefix = "%sERROR:%s " % (GetColor("red"), GetColor()) print("=========================================================================") - print(warn_prefix + "Support for MSVC versions before 2015 will soon be discontinued.") - print(warn_prefix + "If you wish to keep using MSVC 2010, make your voice heard at:") + print(warn_prefix + "Support for MSVC versions before 2015 has been discontinued.") + print(warn_prefix + "For more information, or any questions, please visit:") print(warn_prefix + " https://github.com/panda3d/panda3d/issues/288") - if MSVC_VERSION >= (14, 0): - print(warn_prefix + "To squelch this warning, pass --msvc-version {0}.{1}".format(*MSVC_VERSION)) print("=========================================================================") sys.stdout.flush() time.sleep(1.0) + sys.exit(1) if not WINDOWS_SDK: print("No Windows SDK version specified. Defaulting to '7.1'.") @@ -1423,6 +1420,16 @@ def CompileCxx(obj,src,opts): if (optlevel==3): cmd += " -O2" if (optlevel==4): cmd += " -O3 -DNDEBUG" + # Enable more warnings. + cmd += " -Wall -Wno-unused-function" + + if not src.endswith(".c"): + cmd += " -Wno-reorder" + + # Ignore unused variables in NDEBUG builds, often used in asserts. + if optlevel == 4: + cmd += " -Wno-unused-variable" + if src.endswith(".c"): cmd += ' ' + CFLAGS else: @@ -2336,12 +2343,7 @@ DTOOL_CONFIG=[ ("DO_PIPELINING", '1', '1'), ("DEFAULT_PATHSEP", '";"', '":"'), ("WORDS_BIGENDIAN", 'UNDEF', 'UNDEF'), - ("HAVE_NAMESPACE", '1', '1'), - ("HAVE_OPEN_MASK", 'UNDEF', 'UNDEF'), - ("HAVE_LOCKF", '1', '1'), - ("HAVE_WCHAR_T", '1', '1'), - ("HAVE_WSTRING", '1', '1'), - ("HAVE_TYPENAME", '1', '1'), + ("PHAVE_LOCKF", '1', '1'), ("SIMPLE_STRUCT_POINTERS", '1', 'UNDEF'), ("HAVE_DINKUM", 'UNDEF', 'UNDEF'), ("HAVE_STL_HASH", 'UNDEF', 'UNDEF'), @@ -2351,7 +2353,6 @@ DTOOL_CONFIG=[ ("PHAVE_GETOPT_H", 'UNDEF', '1'), ("PHAVE_LINUX_INPUT_H", 'UNDEF', '1'), ("IOCTL_TERMINAL_WIDTH", 'UNDEF', '1'), - ("HAVE_STREAMSIZE", '1', '1'), ("HAVE_IOS_TYPEDEFS", '1', '1'), ("HAVE_IOS_BINARY", '1', '1'), ("STATIC_INIT_GETENV", '1', 'UNDEF'), @@ -2375,7 +2376,6 @@ DTOOL_CONFIG=[ ("PHAVE_SYS_MALLOC_H", 'UNDEF', 'UNDEF'), ("PHAVE_ALLOCA_H", 'UNDEF', '1'), ("PHAVE_LOCALE_H", 'UNDEF', '1'), - ("PHAVE_MINMAX_H", '1', 'UNDEF'), ("PHAVE_SSTREAM", '1', '1'), ("PHAVE_NEW", '1', '1'), ("PHAVE_SYS_TYPES_H", '1', '1'), @@ -2384,7 +2384,6 @@ DTOOL_CONFIG=[ ("PHAVE_UTIME_H", 'UNDEF', '1'), ("PHAVE_GLOB_H", 'UNDEF', '1'), ("PHAVE_DIRENT_H", 'UNDEF', '1'), - ("PHAVE_SYS_SOUNDCARD_H", 'UNDEF', '1'), ("PHAVE_UCONTEXT_H", 'UNDEF', '1'), ("PHAVE_STDINT_H", '1', '1'), ("HAVE_RTTI", '1', '1'), @@ -2397,7 +2396,6 @@ DTOOL_CONFIG=[ ("HAVE_ZLIB", 'UNDEF', 'UNDEF'), ("HAVE_PNG", 'UNDEF', 'UNDEF'), ("HAVE_JPEG", 'UNDEF', 'UNDEF'), - ("PHAVE_JPEGINT_H", '1', '1'), ("HAVE_VIDEO4LINUX", 'UNDEF', '1'), ("HAVE_TIFF", 'UNDEF', 'UNDEF'), ("HAVE_OPENEXR", 'UNDEF', 'UNDEF'), @@ -2516,7 +2514,7 @@ def WriteConfigSettings(): # Android does have RTTI, but we disable it anyway. dtool_config["HAVE_RTTI"] = 'UNDEF' dtool_config["PHAVE_GLOB_H"] = 'UNDEF' - dtool_config["HAVE_LOCKF"] = 'UNDEF' + dtool_config["PHAVE_LOCKF"] = 'UNDEF' dtool_config["HAVE_VIDEO4LINUX"] = 'UNDEF' if (GetOptimize() <= 2 and GetTarget() == "windows"): @@ -2680,18 +2678,21 @@ PANDAVERSION_H_RUNTIME=""" CHECKPANDAVERSION_CXX=""" # include "dtoolbase.h" -EXPCL_DTOOL_DTOOLUTIL int panda_version_$VERSION1_$VERSION2 = 0; +EXPCL_DTOOL_DTOOLBASE int panda_version_$VERSION1_$VERSION2 = 0; """ CHECKPANDAVERSION_H=""" +# ifndef CHECKPANDAVERSION_H +# define CHECKPANDAVERSION_H # include "dtoolbase.h" -extern EXPCL_DTOOL_DTOOLUTIL int panda_version_$VERSION1_$VERSION2; -# ifndef WIN32 -/* For Windows, exporting the symbol from the DLL is sufficient; the - DLL will not load unless all expected public symbols are defined. - Other systems may not mind if the symbol is absent unless we - explictly write code that references it. */ -static int check_panda_version = panda_version_$VERSION1_$VERSION2; +extern EXPCL_DTOOL_DTOOLBASE int panda_version_$VERSION1_$VERSION2; +// Hack to forcibly depend on the check +template +class CheckPandaVersion { +public: + int check_version() { return panda_version_$VERSION1_$VERSION2; } +}; +template class CheckPandaVersion; # endif """ diff --git a/makepanda/makepandacore.py b/makepanda/makepandacore.py index cb2f5a7ae3..9e5a46c4c6 100644 --- a/makepanda/makepandacore.py +++ b/makepanda/makepandacore.py @@ -321,8 +321,12 @@ def GetHostArch(): target = GetTarget() if target == 'windows': return 'x64' if host_64 else 'x86' - else: #TODO - return platform.machine() + + machine = platform.machine() + if machine.startswith('armv7'): + return 'armv7a' + else: + return machine def SetTarget(target, arch=None): """Sets the target platform; the one we're compiling for. Also diff --git a/panda/metalibs/panda/panda.cxx b/panda/metalibs/panda/panda.cxx index 8a193a8a28..9c9cb8bb60 100644 --- a/panda/metalibs/panda/panda.cxx +++ b/panda/metalibs/panda/panda.cxx @@ -14,12 +14,6 @@ #include "config_pstatclient.h" #endif -// By including checkPandaVersion.h, we guarantee that runtime attempts to -// load libpanda.so.dll will fail if they inadvertently link with the wrong -// version of libdtool.so.dll. - -#include "checkPandaVersion.h" - #if !defined(CPPPARSER) && !defined(BUILDING_LIBPANDA) #error Buildsystem error: BUILDING_LIBPANDA not defined #endif diff --git a/panda/metalibs/pandabullet/pandabullet.cxx b/panda/metalibs/pandabullet/pandabullet.cxx index 4eaa6fcd04..588d47266e 100644 --- a/panda/metalibs/pandabullet/pandabullet.cxx +++ b/panda/metalibs/pandabullet/pandabullet.cxx @@ -7,12 +7,6 @@ #include "pandabullet.h" #include "config_bullet.h" -// By including checkPandaVersion.h, we guarantee that runtime attempts to -// load libpandabullet.so.dll will fail if they inadvertently link with the -// wrong version of libdtool.so.dll. - -#include "checkPandaVersion.h" - /** * Initializes the library. This must be called at least once before any of * the functions or classes in this library can be used. Normally it will be diff --git a/panda/metalibs/pandadx9/pandadx9.cxx b/panda/metalibs/pandadx9/pandadx9.cxx index 8953365225..a54bb7dbf2 100644 --- a/panda/metalibs/pandadx9/pandadx9.cxx +++ b/panda/metalibs/pandadx9/pandadx9.cxx @@ -9,12 +9,6 @@ #include "config_dxgsg9.h" #include "wdxGraphicsPipe9.h" -// By including checkPandaVersion.h, we guarantee that runtime attempts to -// load libpandadx9.dll will fail if they inadvertently link with the wrong -// version of libdtool.dll. - -#include "checkPandaVersion.h" - /** * Initializes the library. This must be called at least once before any of * the functions or classes in this library can be used. Normally it will be diff --git a/panda/metalibs/pandaegg/pandaegg.cxx b/panda/metalibs/pandaegg/pandaegg.cxx index 7bb592e488..235dc62a5b 100644 --- a/panda/metalibs/pandaegg/pandaegg.cxx +++ b/panda/metalibs/pandaegg/pandaegg.cxx @@ -9,12 +9,6 @@ #include "config_egg.h" #include "config_egg2pg.h" -// By including checkPandaVersion.h, we guarantee that runtime attempts to -// load libpandaegg.so.dll will fail if they inadvertently link with the wrong -// version of libdtool.so.dll. - -#include "checkPandaVersion.h" - /** * Initializes the library. This must be called at least once before any of * the functions or classes in this library can be used. Normally it will be diff --git a/panda/metalibs/pandaegg/pandaeggnopg.cxx b/panda/metalibs/pandaegg/pandaeggnopg.cxx index 1b72143237..2a5c86fead 100644 --- a/panda/metalibs/pandaegg/pandaeggnopg.cxx +++ b/panda/metalibs/pandaegg/pandaeggnopg.cxx @@ -8,12 +8,6 @@ #include "config_egg.h" -// By including checkPandaVersion.h, we guarantee that runtime attempts to -// load libpandaegg.so.dll will fail if they inadvertently link with the wrong -// version of libdtool.so.dll. - -#include "checkPandaVersion.h" - /** * Initializes the library. This must be called at least once before any of * the functions or classes in this library can be used. Normally it will be diff --git a/panda/metalibs/pandaexpress/pandaexpress.cxx b/panda/metalibs/pandaexpress/pandaexpress.cxx index 6c6adc0e77..d50aead132 100644 --- a/panda/metalibs/pandaexpress/pandaexpress.cxx +++ b/panda/metalibs/pandaexpress/pandaexpress.cxx @@ -3,9 +3,3 @@ * @author drose * @date 2000-05-15 */ - -// By including checkPandaVersion.h, we guarantee that runtime attempts to -// load libpandaexpress.so.dll will fail if they inadvertently link with the -// wrong version of libdtool.so.dll. - -#include "checkPandaVersion.h" diff --git a/panda/metalibs/pandafx/pandafx.cxx b/panda/metalibs/pandafx/pandafx.cxx index 968ab2f285..64f4a3abd8 100644 --- a/panda/metalibs/pandafx/pandafx.cxx +++ b/panda/metalibs/pandafx/pandafx.cxx @@ -8,12 +8,6 @@ #include "config_distort.h" -// By including checkPandaVersion.h, we guarantee that runtime attempts to -// load libpandafx.so.dll will fail if they inadvertently link with the wrong -// version of libdtool.so.dll. - -#include "checkPandaVersion.h" - /** * Initializes the library. This must be called at least once before any of * the functions or classes in this library can be used. Normally it will be diff --git a/panda/metalibs/pandagl/pandagl.cxx b/panda/metalibs/pandagl/pandagl.cxx index 71b6e83025..0e33961c9f 100644 --- a/panda/metalibs/pandagl/pandagl.cxx +++ b/panda/metalibs/pandagl/pandagl.cxx @@ -30,12 +30,6 @@ #error One of HAVE_WGL, HAVE_COCOA, HAVE_CARBON or HAVE_GLX must be defined when compiling pandagl! #endif -// By including checkPandaVersion.h, we guarantee that runtime attempts to -// load libpandagl.so.dll will fail if they inadvertently link with the wrong -// version of libdtool.so.dll. - -#include "checkPandaVersion.h" - /** * Initializes the library. This must be called at least once before any of * the functions or classes in this library can be used. Normally it will be diff --git a/panda/metalibs/pandagles/pandagles.cxx b/panda/metalibs/pandagles/pandagles.cxx index 27053534c6..f2ed5f3e1a 100644 --- a/panda/metalibs/pandagles/pandagles.cxx +++ b/panda/metalibs/pandagles/pandagles.cxx @@ -17,12 +17,6 @@ #include "eglGraphicsPipe.h" #endif -// By including checkPandaVersion.h, we guarantee that runtime attempts to -// load libpandagles.so.dll will fail if they inadvertently link with the -// wrong version of libdtool.so.dll. - -#include "checkPandaVersion.h" - /** * Initializes the library. This must be called at least once before any of * the functions or classes in this library can be used. Normally it will be diff --git a/panda/metalibs/pandagles2/pandagles2.cxx b/panda/metalibs/pandagles2/pandagles2.cxx index 4810bd60af..b0b36c63ff 100644 --- a/panda/metalibs/pandagles2/pandagles2.cxx +++ b/panda/metalibs/pandagles2/pandagles2.cxx @@ -12,12 +12,6 @@ #include "config_egldisplay.h" #include "eglGraphicsPipe.h" -// By including checkPandaVersion.h, we guarantee that runtime attempts to -// load libpandagles2.so.dll will fail if they inadvertently link with the -// wrong version of libdtool.so.dll. - -#include "checkPandaVersion.h" - /** * Initializes the library. This must be called at least once before any of * the functions or classes in this library can be used. Normally it will be diff --git a/panda/metalibs/pandaode/pandaode.cxx b/panda/metalibs/pandaode/pandaode.cxx index 583b9c3a9d..2b19c71e3b 100644 --- a/panda/metalibs/pandaode/pandaode.cxx +++ b/panda/metalibs/pandaode/pandaode.cxx @@ -7,12 +7,6 @@ #include "pandaode.h" #include "config_ode.h" -// By including checkPandaVersion.h, we guarantee that runtime attempts to -// load libpandaode.so.dll will fail if they inadvertently link with the wrong -// version of libdtool.so.dll. - -#include "checkPandaVersion.h" - /** * Initializes the library. This must be called at least once before any of * the functions or classes in this library can be used. Normally it will be diff --git a/panda/metalibs/pandaphysics/pandaphysics.cxx b/panda/metalibs/pandaphysics/pandaphysics.cxx index 890d450d47..02997a1505 100644 --- a/panda/metalibs/pandaphysics/pandaphysics.cxx +++ b/panda/metalibs/pandaphysics/pandaphysics.cxx @@ -8,12 +8,6 @@ #include "config_physics.h" #include "config_particlesystem.h" -// By including checkPandaVersion.h, we guarantee that runtime attempts to -// load libpandaphysics.so.dll will fail if they inadvertently link with the -// wrong version of libdtool.so.dll. - -#include "checkPandaVersion.h" - /** * Initializes the library. This must be called at least once before any of * the functions or classes in this library can be used. Normally it will be diff --git a/panda/metalibs/pandaphysx/pandaphysx.cxx b/panda/metalibs/pandaphysx/pandaphysx.cxx index fd75ee86b5..3e505f1d7d 100644 --- a/panda/metalibs/pandaphysx/pandaphysx.cxx +++ b/panda/metalibs/pandaphysx/pandaphysx.cxx @@ -7,12 +7,6 @@ #include "pandaphysx.h" #include "config_physx.h" -// By including checkPandaVersion.h, we guarantee that runtime attempts to -// load libpandaphysx.so.dll will fail if they inadvertently link with the -// wrong version of libdtool.so.dll. - -#include "checkPandaVersion.h" - /** * Initializes the library. This must be called at least once before any of * the functions or classes in this library can be used. Normally it will be diff --git a/panda/src/android/android_main.cxx b/panda/src/android/android_main.cxx index 865936e2ed..626111ed83 100644 --- a/panda/src/android/android_main.cxx +++ b/panda/src/android/android_main.cxx @@ -26,6 +26,8 @@ #include #include +using std::string; + // struct android_app* panda_android_app = NULL; extern int main(int argc, const char **argv); @@ -197,7 +199,7 @@ void android_main(struct android_app* app) { get_model_path().append_directory(asset_dir); // Now load the configuration files. - vector pages; + std::vector pages; ConfigPageManager *cp_mgr; AAssetDir *etc = AAssetManager_openDir(app->activity->assetManager, "etc"); if (etc != nullptr) { @@ -209,7 +211,7 @@ void android_main(struct android_app* app) { GlobPattern pattern = cp_mgr->get_prc_pattern(i); if (pattern.matches(filename)) { Filename prc_fn("etc", filename); - istream *in = asset_mount->open_read_file(prc_fn); + std::istream *in = asset_mount->open_read_file(prc_fn); if (in != nullptr) { ConfigPage *page = cp_mgr->make_explicit_page(Filename("/android_asset", prc_fn)); page->read_prc(*in); diff --git a/panda/src/android/config_android.cxx b/panda/src/android/config_android.cxx index afbaf243ff..083cd7c192 100644 --- a/panda/src/android/config_android.cxx +++ b/panda/src/android/config_android.cxx @@ -19,7 +19,7 @@ NotifyCategoryDef(android, ""); -struct android_app *panda_android_app = NULL; +struct android_app *panda_android_app = nullptr; jclass jni_PandaActivity; jmethodID jni_PandaActivity_readBitmapSize; @@ -139,7 +139,7 @@ void JNI_OnUnload(JavaVM *jvm, void *reserved) { * Shows a toast notification at the bottom of the activity. The duration * should be 0 for short and 1 for long. */ -void android_show_toast(ANativeActivity *activity, const string &message, int duration) { +void android_show_toast(ANativeActivity *activity, const std::string &message, int duration) { Thread *thread = Thread::get_current_thread(); JNIEnv *env = thread->get_jni_env(); nassertv(env != nullptr); diff --git a/panda/src/android/config_android.h b/panda/src/android/config_android.h index 2224dbd065..4935db0718 100644 --- a/panda/src/android/config_android.h +++ b/panda/src/android/config_android.h @@ -39,6 +39,6 @@ extern jclass jni_BitmapFactory_Options; extern jfieldID jni_BitmapFactory_Options_outWidth; extern jfieldID jni_BitmapFactory_Options_outHeight; -EXPORT_CLASS void android_show_toast(ANativeActivity *activity, const string &message, int duration); +EXPORT_CLASS void android_show_toast(ANativeActivity *activity, const std::string &message, int duration); #endif diff --git a/panda/src/android/jni_NativeIStream.cxx b/panda/src/android/jni_NativeIStream.cxx index 56e0c8c8bc..8bb60dfe8c 100644 --- a/panda/src/android/jni_NativeIStream.cxx +++ b/panda/src/android/jni_NativeIStream.cxx @@ -39,8 +39,8 @@ Java_org_panda3d_android_NativeIStream_nativeGet(JNIEnv *env, jclass clazz, jlon EXPORT_JNI jint Java_org_panda3d_android_NativeIStream_nativeRead(JNIEnv *env, jclass clazz, jlong ptr, jbyteArray byte_array, jint offset, jint length) { std::istream *stream = (std::istream *) ptr; - jbyte *buffer = (jbyte *) env->GetPrimitiveArrayCritical(byte_array, NULL); - if (buffer == NULL) { + jbyte *buffer = (jbyte *) env->GetPrimitiveArrayCritical(byte_array, nullptr); + if (buffer == nullptr) { return -1; } diff --git a/panda/src/android/pnmFileTypeAndroid.cxx b/panda/src/android/pnmFileTypeAndroid.cxx index aa25b2c777..535cc30563 100644 --- a/panda/src/android/pnmFileTypeAndroid.cxx +++ b/panda/src/android/pnmFileTypeAndroid.cxx @@ -27,7 +27,7 @@ PNMFileTypeAndroid(CompressFormat format) : _format(format) { /** * Returns a few words describing the file type. */ -string PNMFileTypeAndroid:: +std::string PNMFileTypeAndroid:: get_name() const { return "Android Bitmap"; } @@ -54,7 +54,7 @@ get_num_extensions() const { * Returns the nth possible filename extension associated with this particular * file type, without a leading dot. */ -string PNMFileTypeAndroid:: +std::string PNMFileTypeAndroid:: get_extension(int n) const { static const char *const jpeg_extensions[] = {"jpg", "jpeg", "jpe"}; switch (_format) { @@ -84,7 +84,7 @@ has_magic_number() const { * returns NULL. */ PNMReader *PNMFileTypeAndroid:: -make_reader(istream *file, bool owns_file, const string &magic_number) { +make_reader(std::istream *file, bool owns_file, const std::string &magic_number) { return new Reader(this, file, owns_file, magic_number); } @@ -94,7 +94,7 @@ make_reader(istream *file, bool owns_file, const string &magic_number) { * NULL. */ PNMWriter *PNMFileTypeAndroid:: -make_writer(ostream *file, bool owns_file) { +make_writer(std::ostream *file, bool owns_file) { return new Writer(this, file, owns_file, _format); } diff --git a/panda/src/android/pnmFileTypeAndroid.h b/panda/src/android/pnmFileTypeAndroid.h index f27cc4f23d..3501f31239 100644 --- a/panda/src/android/pnmFileTypeAndroid.h +++ b/panda/src/android/pnmFileTypeAndroid.h @@ -28,7 +28,7 @@ * Wrapper class around the Android Bitmap mechanism to allow loading images * on Android without needing libpng or libjpeg. */ -class EXPCL_PANDA_PNMIMAGETYPES PNMFileTypeAndroid : public PNMFileType { +class PNMFileTypeAndroid : public PNMFileType { public: enum CompressFormat : jint { CF_jpeg = 0, @@ -38,21 +38,21 @@ public: PNMFileTypeAndroid(CompressFormat format); - virtual string get_name() const; + virtual std::string get_name() const; virtual int get_num_extensions() const; - virtual string get_extension(int n) const; + virtual std::string get_extension(int n) const; virtual bool has_magic_number() const; - virtual PNMReader *make_reader(istream *file, bool owns_file = true, - const string &magic_number = string()); - virtual PNMWriter *make_writer(ostream *file, bool owns_file = true); + virtual PNMReader *make_reader(std::istream *file, bool owns_file = true, + const std::string &magic_number = std::string()); + virtual PNMWriter *make_writer(std::ostream *file, bool owns_file = true); public: class Reader : public PNMReader { public: - Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number); + Reader(PNMFileType *type, std::istream *file, bool owns_file, std::string magic_number); virtual ~Reader(); virtual void prepare_read(); @@ -69,7 +69,7 @@ public: class Writer : public PNMWriter { public: - Writer(PNMFileType *type, ostream *file, bool owns_file, + Writer(PNMFileType *type, std::ostream *file, bool owns_file, CompressFormat format); virtual int write_data(xel *array, xelval *alpha); diff --git a/panda/src/android/pnmFileTypeAndroidReader.cxx b/panda/src/android/pnmFileTypeAndroidReader.cxx index e18ebcbaea..7feceffa1c 100644 --- a/panda/src/android/pnmFileTypeAndroidReader.cxx +++ b/panda/src/android/pnmFileTypeAndroidReader.cxx @@ -60,11 +60,11 @@ static void conv_rgba4444(uint16_t in, xel &rgb, xelval &alpha) { * */ PNMFileTypeAndroid::Reader:: -Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number) : - PNMReader(type, file, owns_file), _bitmap(NULL) +Reader(PNMFileType *type, std::istream *file, bool owns_file, std::string magic_number) : + PNMReader(type, file, owns_file), _bitmap(nullptr) { // Hope we can putback() more than one character. - for (string::reverse_iterator mi = magic_number.rbegin(); + for (std::string::reverse_iterator mi = magic_number.rbegin(); mi != magic_number.rend(); ++mi) { _file->putback(*mi); }; @@ -75,7 +75,7 @@ Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number) : return; } - streampos pos = _file->tellg(); + std::streampos pos = _file->tellg(); Thread *current_thread = Thread::get_current_thread(); _env = current_thread->get_jni_env(); @@ -120,7 +120,7 @@ Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number) : */ PNMFileTypeAndroid::Reader:: ~Reader() { - if (_bitmap != NULL) { + if (_bitmap != nullptr) { _env->DeleteGlobalRef(_bitmap); } } @@ -143,14 +143,14 @@ prepare_read() { int x_reduction = _orig_x_size / _read_x_size; int y_reduction = _orig_y_size / _read_y_size; - _sample_size = max(min(x_reduction, y_reduction), 1); + _sample_size = std::max(std::min(x_reduction, y_reduction), 1); } _bitmap = _env->CallStaticObjectMethod(jni_PandaActivity, jni_PandaActivity_readBitmap, (jlong) _file, _sample_size); - if (_bitmap == NULL) { + if (_bitmap == nullptr) { android_cat.error() << "Failed to read " << *this << "\n"; _is_valid = false; diff --git a/panda/src/android/pnmFileTypeAndroidWriter.cxx b/panda/src/android/pnmFileTypeAndroidWriter.cxx index 4677a25cbd..3157733115 100644 --- a/panda/src/android/pnmFileTypeAndroidWriter.cxx +++ b/panda/src/android/pnmFileTypeAndroidWriter.cxx @@ -34,7 +34,7 @@ enum class BitmapConfig : jint { * */ PNMFileTypeAndroid::Writer:: -Writer(PNMFileType *type, ostream *file, bool owns_file, +Writer(PNMFileType *type, std::ostream *file, bool owns_file, CompressFormat format) : PNMWriter(type, file, owns_file), _format(format) diff --git a/panda/src/android/pview.cxx b/panda/src/android/pview.cxx index 2b31bb7577..5df6f7465b 100644 --- a/panda/src/android/pview.cxx +++ b/panda/src/android/pview.cxx @@ -21,12 +21,6 @@ #include "bamCache.h" #include "virtualFileSystem.h" -// By including checkPandaVersion.h, we guarantee that runtime attempts to run -// pview will fail if it inadvertently links with the wrong version of -// libdtool.so.dll. - -#include "checkPandaVersion.h" - int main(int argc, char **argv) { PandaFramework framework; framework.open_framework(argc, argv); @@ -36,7 +30,7 @@ int main(int argc, char **argv) { PartGroup::HMF_ok_anim_extra; WindowFramework *window = framework.open_window(); - if (window != (WindowFramework *)NULL) { + if (window != nullptr) { // We've successfully opened a window. NodePath loading_np; diff --git a/panda/src/android/python_main.cxx b/panda/src/android/python_main.cxx index c1fc0a39fe..0e4059c61c 100644 --- a/panda/src/android/python_main.cxx +++ b/panda/src/android/python_main.cxx @@ -38,7 +38,7 @@ int main(int argc, char *argv[]) { Py_SetProgramName(Py_DecodeLocale("ppython", nullptr)); // Set PYTHONHOME to the location of the .apk file. - string apk_path = ExecutionEnvironment::get_binary_name(); + std::string apk_path = ExecutionEnvironment::get_binary_name(); Py_SetPythonHome(Py_DecodeLocale(apk_path.c_str(), nullptr)); // We need to make zlib available to zipimport, but I don't know how @@ -56,7 +56,7 @@ int main(int argc, char *argv[]) { // This is used by the import hook to locate the module libraries. Filename dtool_name = ExecutionEnvironment::get_dtool_name(); - string native_dir = dtool_name.get_dirname(); + std::string native_dir = dtool_name.get_dirname(); PyObject *py_native_dir = PyUnicode_FromStringAndSize(native_dir.c_str(), native_dir.size()); PySys_SetObject("_native_library_dir", py_native_dir); Py_DECREF(py_native_dir); diff --git a/panda/src/androiddisplay/androidGraphicsPipe.cxx b/panda/src/androiddisplay/androidGraphicsPipe.cxx index 00ff6f924f..53f0f72310 100644 --- a/panda/src/androiddisplay/androidGraphicsPipe.cxx +++ b/panda/src/androiddisplay/androidGraphicsPipe.cxx @@ -28,13 +28,13 @@ AndroidGraphicsPipe:: AndroidGraphicsPipe() { _is_valid = false; _supported_types = OT_window | OT_buffer | OT_texture_buffer; - _egl_display = NULL; + _egl_display = nullptr; _display_width = 0; _display_height = 0; _egl_display = eglGetDisplay(EGL_DEFAULT_DISPLAY); - if (!eglInitialize(_egl_display, NULL, NULL)) { + if (!eglInitialize(_egl_display, nullptr, nullptr)) { androiddisplay_cat.error() << "Couldn't initialize the EGL display: " << get_egl_error_string(eglGetError()) << "\n"; @@ -68,7 +68,7 @@ AndroidGraphicsPipe:: * choose between several possible GraphicsPipes available on a particular * platform, so the name should be meaningful and unique for a given platform. */ -string AndroidGraphicsPipe:: +std::string AndroidGraphicsPipe:: get_interface_name() const { return "OpenGL ES"; } @@ -99,7 +99,7 @@ AndroidGraphicsPipe::get_preferred_window_thread() const { * Creates a new window on the pipe, if possible. */ PT(GraphicsOutput) AndroidGraphicsPipe:: -make_output(const string &name, +make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -110,12 +110,12 @@ make_output(const string &name, bool &precertify) { if (!_is_valid) { - return NULL; + return nullptr; } AndroidGraphicsStateGuardian *androidgsg = 0; if (gsg != 0) { - DCAST_INTO_R(androidgsg, gsg, NULL); + DCAST_INTO_R(androidgsg, gsg, nullptr); } // First thing to try: an eglGraphicsWindow @@ -128,7 +128,7 @@ make_output(const string &name, ((flags&BF_rtt_cumulative)!=0)|| ((flags&BF_can_bind_color)!=0)|| ((flags&BF_can_bind_every)!=0)) { - return NULL; + return nullptr; } return new AndroidGraphicsWindow(engine, this, name, fb_prop, win_prop, flags, gsg, host); @@ -212,5 +212,5 @@ make_output(const string &name, }*/ // Nothing else left to try. - return NULL; + return nullptr; } diff --git a/panda/src/androiddisplay/androidGraphicsPipe.h b/panda/src/androiddisplay/androidGraphicsPipe.h index cead149963..8767f1ee23 100644 --- a/panda/src/androiddisplay/androidGraphicsPipe.h +++ b/panda/src/androiddisplay/androidGraphicsPipe.h @@ -42,14 +42,14 @@ public: AndroidGraphicsPipe(); virtual ~AndroidGraphicsPipe(); - virtual string get_interface_name() const; + virtual std::string get_interface_name() const; static PT(GraphicsPipe) pipe_constructor(); public: virtual PreferredWindowThread get_preferred_window_thread() const; protected: - virtual PT(GraphicsOutput) make_output(const string &name, + virtual PT(GraphicsOutput) make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/androiddisplay/androidGraphicsStateGuardian.cxx b/panda/src/androiddisplay/androidGraphicsStateGuardian.cxx index 409baa0a96..e5c8177d9e 100644 --- a/panda/src/androiddisplay/androidGraphicsStateGuardian.cxx +++ b/panda/src/androiddisplay/androidGraphicsStateGuardian.cxx @@ -37,7 +37,7 @@ AndroidGraphicsStateGuardian(GraphicsEngine *engine, GraphicsPipe *pipe, _fbconfig = 0; _format = 0; - if (share_with != (AndroidGraphicsStateGuardian *)NULL) { + if (share_with != nullptr) { _prepared_objects = share_with->get_prepared_objects(); _share_context = share_with->_context; } @@ -48,12 +48,12 @@ AndroidGraphicsStateGuardian(GraphicsEngine *engine, GraphicsPipe *pipe, */ AndroidGraphicsStateGuardian:: ~AndroidGraphicsStateGuardian() { - if (_context != (EGLContext)NULL) { + if (_context != (EGLContext)nullptr) { if (!eglDestroyContext(_egl_display, _context)) { androiddisplay_cat.error() << "Failed to destroy EGL context: " << get_egl_error_string(eglGetError()) << "\n"; } - _context = (EGLContext)NULL; + _context = (EGLContext)nullptr; } } @@ -145,7 +145,7 @@ choose_pixel_format(const FrameBufferProperties &properties, // First get the number of matching configurations, so we know how much // memory to allocate. int num_configs = 0, returned_configs; - if (!eglChooseConfig(_egl_display, attrib_list, NULL, num_configs, &returned_configs) || returned_configs <= 0) { + if (!eglChooseConfig(_egl_display, attrib_list, nullptr, num_configs, &returned_configs) || returned_configs <= 0) { androiddisplay_cat.error() << "eglChooseConfig failed: " << get_egl_error_string(eglGetError()) << "\n"; return; @@ -228,7 +228,7 @@ create_context() { EGLint context_attribs[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE}; _context = eglCreateContext(_egl_display, _fbconfig, _share_context, context_attribs); #else - _context = eglCreateContext(_egl_display, _fbconfig, _share_context, NULL); + _context = eglCreateContext(_egl_display, _fbconfig, _share_context, nullptr); #endif int err = eglGetError(); @@ -275,7 +275,7 @@ reset() { #endif // If "PixelFlinger" is present, assume software. - if (_gl_renderer.find("PixelFlinger") != string::npos) { + if (_gl_renderer.find("PixelFlinger") != std::string::npos) { _fbprops.set_force_software(1); _fbprops.set_force_hardware(0); } else { diff --git a/panda/src/androiddisplay/androidGraphicsWindow.cxx b/panda/src/androiddisplay/androidGraphicsWindow.cxx index 1a91f21186..431f9419b7 100644 --- a/panda/src/androiddisplay/androidGraphicsWindow.cxx +++ b/panda/src/androiddisplay/androidGraphicsWindow.cxx @@ -38,7 +38,7 @@ TypeHandle AndroidGraphicsWindow::_type_handle; */ AndroidGraphicsWindow:: AndroidGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -79,7 +79,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { PStatTimer timer(_make_current_pcollector, current_thread); begin_frame_spam(mode); - if (_gsg == (GraphicsStateGuardian *)NULL) { + if (_gsg == nullptr) { return false; } @@ -129,7 +129,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { void AndroidGraphicsWindow:: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); - nassertv(_gsg != (GraphicsStateGuardian *)NULL); + nassertv(_gsg != nullptr); if (mode == FM_render) { // end_render_texture(); @@ -153,7 +153,7 @@ end_frame(FrameMode mode, Thread *current_thread) { */ void AndroidGraphicsWindow:: end_flip() { - if (_gsg != (GraphicsStateGuardian *)NULL && _flip_ready) { + if (_gsg != nullptr && _flip_ready) { // It doesn't appear to be necessary to ensure the graphics context is // current before flipping the windows, and insisting on doing so can be a @@ -185,9 +185,9 @@ process_events() { struct android_poll_source* source; // Loop until all events are read. - while ((looper_id = ALooper_pollAll(0, NULL, &events, (void**)&source)) >= 0) { + while ((looper_id = ALooper_pollAll(0, nullptr, &events, (void**)&source)) >= 0) { // Process this event. - if (source != NULL) { + if (source != nullptr) { source->process(_app, source); } } @@ -207,7 +207,7 @@ process_events() { */ void AndroidGraphicsWindow:: set_properties_now(WindowProperties &properties) { - if (_pipe == (GraphicsPipe *)NULL) { + if (_pipe == nullptr) { // If the pipe is null, we're probably closing down. GraphicsWindow::set_properties_now(properties); return; @@ -242,7 +242,7 @@ void AndroidGraphicsWindow:: close_window() { destroy_surface(); - if (_gsg != (GraphicsStateGuardian *)NULL) { + if (_gsg != nullptr) { _gsg.clear(); } @@ -266,7 +266,7 @@ open_window() { AndroidGraphicsStateGuardian *androidgsg; if (_gsg == 0) { // There is no old gsg. Create a new one. - androidgsg = new AndroidGraphicsStateGuardian(_engine, _pipe, NULL); + androidgsg = new AndroidGraphicsStateGuardian(_engine, _pipe, nullptr); androidgsg->choose_pixel_format(_fb_properties, false, false); _gsg = androidgsg; } else { @@ -281,13 +281,13 @@ open_window() { } // Register the callbacks - assert(_app != NULL); + assert(_app != nullptr); _app->userData = this; _app->onAppCmd = handle_command; _app->onInputEvent = handle_input_event; // Wait until Android has opened the window. - while (_app->window == NULL) { + while (_app->window == nullptr) { process_events(); } @@ -326,7 +326,7 @@ destroy_surface() { } // Destroy the current context. - if (_gsg != (GraphicsStateGuardian *)NULL) { + if (_gsg != nullptr) { AndroidGraphicsStateGuardian *androidgsg; DCAST_INTO_V(androidgsg, _gsg); androidgsg->destroy_context(); @@ -355,7 +355,7 @@ create_surface() { ANativeActivity_setWindowFlags(_app->activity, add_flags, del_flags); // Create the EGL surface. - _egl_surface = eglCreateWindowSurface(_egl_display, androidgsg->_fbconfig, _app->window, NULL); + _egl_surface = eglCreateWindowSurface(_egl_display, androidgsg->_fbconfig, _app->window, nullptr); if (eglGetError() != EGL_SUCCESS) { androiddisplay_cat.error() << "Failed to create window surface.\n"; @@ -415,7 +415,7 @@ ns_handle_command(int32_t command) { break; case APP_CMD_INIT_WINDOW: // The window is being shown, get it ready. - if (_app->window != NULL) { + if (_app->window != nullptr) { create_surface(); properties.set_size(ANativeWindow_getWidth(_app->window), ANativeWindow_getHeight(_app->window)); diff --git a/panda/src/androiddisplay/androidGraphicsWindow.h b/panda/src/androiddisplay/androidGraphicsWindow.h index 3d1ca79946..0842b18f2b 100644 --- a/panda/src/androiddisplay/androidGraphicsWindow.h +++ b/panda/src/androiddisplay/androidGraphicsWindow.h @@ -33,7 +33,7 @@ struct android_app; class AndroidGraphicsWindow : public GraphicsWindow { public: AndroidGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/androiddisplay/config_androiddisplay.cxx b/panda/src/androiddisplay/config_androiddisplay.cxx index 6b344b6c9d..42b0fb8120 100644 --- a/panda/src/androiddisplay/config_androiddisplay.cxx +++ b/panda/src/androiddisplay/config_androiddisplay.cxx @@ -64,7 +64,7 @@ init_libandroiddisplay() { /** * Returns the given EGL error as string. */ -const string get_egl_error_string(int error) { +const std::string get_egl_error_string(int error) { switch (error) { case 0x3000: return "EGL_SUCCESS"; break; case 0x3001: return "EGL_NOT_INITIALIZED"; break; diff --git a/panda/src/androiddisplay/config_androiddisplay.h b/panda/src/androiddisplay/config_androiddisplay.h index 29c5c3417c..78c42211c0 100644 --- a/panda/src/androiddisplay/config_androiddisplay.h +++ b/panda/src/androiddisplay/config_androiddisplay.h @@ -31,12 +31,12 @@ NotifyCategoryDecl(androiddisplay, EXPCL_PANDAGLES2, EXPTP_PANDAGLES2); extern EXPCL_PANDAGLES2 void init_libandroiddisplay(); - extern EXPCL_PANDAGLES2 const string get_egl_error_string(int error); + extern EXPCL_PANDAGLES2 const std::string get_egl_error_string(int error); #else NotifyCategoryDecl(androiddisplay, EXPCL_PANDAGLES, EXPTP_PANDAGLES); extern EXPCL_PANDAGLES void init_libandroiddisplay(); - extern EXPCL_PANDAGLES const string get_egl_error_string(int error); + extern EXPCL_PANDAGLES const std::string get_egl_error_string(int error); #endif #endif diff --git a/panda/src/audio/audioLoadRequest.I b/panda/src/audio/audioLoadRequest.I index 647692315d..019501aa77 100644 --- a/panda/src/audio/audioLoadRequest.I +++ b/panda/src/audio/audioLoadRequest.I @@ -16,7 +16,7 @@ * to begin an asynchronous load. */ INLINE AudioLoadRequest:: -AudioLoadRequest(AudioManager *audio_manager, const string &filename, +AudioLoadRequest(AudioManager *audio_manager, const std::string &filename, bool positional) : _audio_manager(audio_manager), _filename(filename), @@ -36,7 +36,7 @@ get_audio_manager() const { /** * Returns the filename associated with this asynchronous AudioLoadRequest. */ -INLINE const string &AudioLoadRequest:: +INLINE const std::string &AudioLoadRequest:: get_filename() const { return _filename; } diff --git a/panda/src/audio/audioLoadRequest.h b/panda/src/audio/audioLoadRequest.h index 6d0e59bf4c..1c07098b91 100644 --- a/panda/src/audio/audioLoadRequest.h +++ b/panda/src/audio/audioLoadRequest.h @@ -33,11 +33,11 @@ public: PUBLISHED: INLINE explicit AudioLoadRequest(AudioManager *audio_manager, - const string &filename, + const std::string &filename, bool positional); INLINE AudioManager *get_audio_manager() const; - INLINE const string &get_filename() const; + INLINE const std::string &get_filename() const; INLINE bool get_positional() const; INLINE bool is_ready() const; @@ -48,7 +48,7 @@ protected: private: PT(AudioManager) _audio_manager; - string _filename; + std::string _filename; bool _positional; public: diff --git a/panda/src/audio/audioManager.cxx b/panda/src/audio/audioManager.cxx index b52ceb50e5..39d16156ef 100644 --- a/panda/src/audio/audioManager.cxx +++ b/panda/src/audio/audioManager.cxx @@ -25,6 +25,8 @@ #include // For GetSystemDirectory() #endif +using std::string; + TypeHandle AudioManager::_type_handle; @@ -36,11 +38,11 @@ namespace { } } -Create_AudioManager_proc *AudioManager::_create_AudioManager = NULL; +Create_AudioManager_proc *AudioManager::_create_AudioManager = nullptr; void AudioManager:: register_AudioManager_creator(Create_AudioManager_proc* proc) { - nassertv(_create_AudioManager == NULL || _create_AudioManager == proc); + nassertv(_create_AudioManager == nullptr || _create_AudioManager == proc); _create_AudioManager = proc; } @@ -48,7 +50,7 @@ register_AudioManager_creator(Create_AudioManager_proc* proc) { PT(AudioManager) AudioManager::create_AudioManager() { audio_debug("create_AudioManager()\n audio_library_name=\""<ref(); - void *result = AtomicAdjust::compare_and_exchange_ptr(_null_sound, (void *)NULL, (void *)new_sound); - if (result != NULL) { + void *result = AtomicAdjust::compare_and_exchange_ptr(_null_sound, nullptr, (void *)new_sound); + if (result != nullptr) { // Someone else must have assigned the AudioSound first. OK. - nassertr(_null_sound != new_sound, NULL); + nassertr(_null_sound != new_sound, nullptr); unref_delete(new_sound); } - nassertr(_null_sound != NULL, NULL); + nassertr(_null_sound != nullptr, nullptr); } return (AudioSound *)_null_sound; @@ -312,7 +314,7 @@ get_dls_pathname() { * */ void AudioManager:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type(); } @@ -320,7 +322,7 @@ output(ostream &out) const { * */ void AudioManager:: -write(ostream &out) const { +write(std::ostream &out) const { out << (*this) << "\n"; } diff --git a/panda/src/audio/audioManager.h b/panda/src/audio/audioManager.h index c957581534..2ee14f10cb 100644 --- a/panda/src/audio/audioManager.h +++ b/panda/src/audio/audioManager.h @@ -86,7 +86,7 @@ PUBLISHED: virtual bool is_valid() = 0; // Get a sound: - virtual PT(AudioSound) get_sound(const string& file_name, bool positional = false, int mode=SM_heuristic) = 0; + virtual PT(AudioSound) get_sound(const std::string& file_name, bool positional = false, int mode=SM_heuristic) = 0; virtual PT(AudioSound) get_sound(MovieAudio *source, bool positional = false, int mode=SM_heuristic) = 0; PT(AudioSound) get_null_sound(); @@ -95,7 +95,7 @@ PUBLISHED: // doesn't break any connection between AudioSounds that have already given // by get_sound() from this manager. It's only affecting whether the // AudioManager keeps a copy of the sound in its poolcache. - virtual void uncache_sound(const string& file_name) = 0; + virtual void uncache_sound(const std::string& file_name) = 0; virtual void clear_cache() = 0; virtual void set_cache_limit(unsigned int count) = 0; virtual unsigned int get_cache_limit() const = 0; @@ -175,11 +175,11 @@ PUBLISHED: static Filename get_dls_pathname(); MAKE_PROPERTY(dls_pathname, get_dls_pathname); - virtual void output(ostream &out) const; - virtual void write(ostream &out) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out) const; // set_speaker_configuration is a Miles only method. - virtual void set_speaker_configuration(LVecBase3 *speaker1, LVecBase3 *speaker2=NULL, LVecBase3 *speaker3=NULL, LVecBase3 *speaker4=NULL, LVecBase3 *speaker5=NULL, LVecBase3 *speaker6=NULL, LVecBase3 *speaker7=NULL, LVecBase3 *speaker8=NULL, LVecBase3 *speaker9=NULL); + virtual void set_speaker_configuration(LVecBase3 *speaker1, LVecBase3 *speaker2=nullptr, LVecBase3 *speaker3=nullptr, LVecBase3 *speaker4=nullptr, LVecBase3 *speaker5=nullptr, LVecBase3 *speaker6=nullptr, LVecBase3 *speaker7=nullptr, LVecBase3 *speaker8=nullptr, LVecBase3 *speaker9=nullptr); public: static void register_AudioManager_creator(Create_AudioManager_proc* proc); @@ -214,8 +214,8 @@ private: static TypeHandle _type_handle; }; -inline ostream & -operator << (ostream &out, const AudioManager &mgr) { +inline std::ostream & +operator << (std::ostream &out, const AudioManager &mgr) { mgr.output(out); return out; } diff --git a/panda/src/audio/audioSound.cxx b/panda/src/audio/audioSound.cxx index 9d121e06b0..19cc27f030 100644 --- a/panda/src/audio/audioSound.cxx +++ b/panda/src/audio/audioSound.cxx @@ -14,6 +14,8 @@ #include "audioSound.h" +using std::ostream; + TypeHandle AudioSound::_type_handle; /** diff --git a/panda/src/audio/audioSound.h b/panda/src/audio/audioSound.h index 357df8ad11..e348ad4daf 100644 --- a/panda/src/audio/audioSound.h +++ b/panda/src/audio/audioSound.h @@ -74,11 +74,11 @@ PUBLISHED: // Set (or clear) the event that will be thrown when the sound finishes // playing. To clear the event, pass an empty string. - virtual void set_finished_event(const string& event) = 0; - virtual const string& get_finished_event() const = 0; + virtual void set_finished_event(const std::string& event) = 0; + virtual const std::string& get_finished_event() const = 0; // There is no set_name(), this is intentional. - virtual const string& get_name() const = 0; + virtual const std::string& get_name() const = 0; // return: playing time in seconds. virtual PN_stdfloat length() const = 0; @@ -123,8 +123,8 @@ PUBLISHED: enum SoundStatus { BAD, READY, PLAYING }; virtual SoundStatus status() const = 0; - virtual void output(ostream &out) const; - virtual void write(ostream &out) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out) const; protected: AudioSound(); @@ -149,15 +149,15 @@ private: static TypeHandle _type_handle; }; -inline ostream & -operator << (ostream &out, const AudioSound &sound) { +inline std::ostream & +operator << (std::ostream &out, const AudioSound &sound) { sound.output(out); return out; } #include "audioSound.I" -EXPCL_PANDA_AUDIO ostream & -operator << (ostream &out, AudioSound::SoundStatus status); +EXPCL_PANDA_AUDIO std::ostream & +operator << (std::ostream &out, AudioSound::SoundStatus status); #endif /* __AUDIOSOUND_H__ */ diff --git a/panda/src/audio/config_audio.cxx b/panda/src/audio/config_audio.cxx index 0f58e56a32..1ea8053eb6 100644 --- a/panda/src/audio/config_audio.cxx +++ b/panda/src/audio/config_audio.cxx @@ -25,6 +25,10 @@ #error Buildsystem error: BUILDING_PANDA_AUDIO not defined #endif +using std::istream; +using std::ostream; +using std::string; + Configure(config_audio); NotifyCategoryDef(audio, ""); diff --git a/panda/src/audio/config_audio.h b/panda/src/audio/config_audio.h index bb84a9bf2d..47853ac143 100644 --- a/panda/src/audio/config_audio.h +++ b/panda/src/audio/config_audio.h @@ -52,8 +52,8 @@ enum FmodSpeakerMode { FSM_unspecified }; -EXPCL_PANDA_AUDIO ostream &operator << (ostream &out, FmodSpeakerMode sm); -EXPCL_PANDA_AUDIO istream &operator >> (istream &in, FmodSpeakerMode &sm); +EXPCL_PANDA_AUDIO std::ostream &operator << (std::ostream &out, FmodSpeakerMode sm); +EXPCL_PANDA_AUDIO std::istream &operator >> (std::istream &in, FmodSpeakerMode &sm); extern EXPCL_PANDA_AUDIO ConfigVariableInt fmod_number_of_sound_channels; extern EXPCL_PANDA_AUDIO ConfigVariableBool fmod_use_surround_sound; @@ -84,7 +84,7 @@ extern EXPCL_PANDA_AUDIO ConfigVariableInt audio_output_channels; // Non-release build: #define audio_debug(msg) \ if (audio_cat.is_debug()) { \ - audio_cat->debug() << msg << endl; \ + audio_cat->debug() << msg << std::endl; \ } else {} #else //][ // Release build: @@ -92,12 +92,12 @@ extern EXPCL_PANDA_AUDIO ConfigVariableInt audio_output_channels; #endif //] #define audio_info(msg) \ - audio_cat->info() << msg << endl + audio_cat->info() << msg << std::endl #define audio_warning(msg) \ - audio_cat->warning() << msg << endl + audio_cat->warning() << msg << std::endl #define audio_error(msg) \ - audio_cat->error() << msg << endl + audio_cat->error() << msg << std::endl #endif /* __CONFIG_AUDIO_H__ */ diff --git a/panda/src/audio/nullAudioManager.cxx b/panda/src/audio/nullAudioManager.cxx index f7126e9b7b..dabeb8c825 100644 --- a/panda/src/audio/nullAudioManager.cxx +++ b/panda/src/audio/nullAudioManager.cxx @@ -49,7 +49,7 @@ is_valid() { * */ PT(AudioSound) NullAudioManager:: -get_sound(const string&, bool positional, int mode) { +get_sound(const std::string&, bool positional, int mode) { return get_null_sound(); } @@ -65,7 +65,7 @@ get_sound(MovieAudio *sound, bool positional, int mode) { * */ void NullAudioManager:: -uncache_sound(const string&) { +uncache_sound(const std::string&) { // intentionally blank. } diff --git a/panda/src/audio/nullAudioManager.h b/panda/src/audio/nullAudioManager.h index cebf6ab08a..9a8ff921e4 100644 --- a/panda/src/audio/nullAudioManager.h +++ b/panda/src/audio/nullAudioManager.h @@ -29,9 +29,9 @@ public: virtual bool is_valid(); - virtual PT(AudioSound) get_sound(const string&, bool positional = false, int mode=SM_heuristic); + virtual PT(AudioSound) get_sound(const std::string&, bool positional = false, int mode=SM_heuristic); virtual PT(AudioSound) get_sound(MovieAudio *sound, bool positional = false, int mode=SM_heuristic); - virtual void uncache_sound(const string&); + virtual void uncache_sound(const std::string&); virtual void clear_cache(); virtual void set_cache_limit(unsigned int); virtual unsigned int get_cache_limit() const; diff --git a/panda/src/audio/nullAudioSound.cxx b/panda/src/audio/nullAudioSound.cxx index 980083b468..0fbdf14672 100644 --- a/panda/src/audio/nullAudioSound.cxx +++ b/panda/src/audio/nullAudioSound.cxx @@ -14,6 +14,8 @@ #include "nullAudioSound.h" +using std::string; + TypeHandle NullAudioSound::_type_handle; namespace { diff --git a/panda/src/audio/nullAudioSound.h b/panda/src/audio/nullAudioSound.h index 87ef0c9b95..d388493132 100644 --- a/panda/src/audio/nullAudioSound.h +++ b/panda/src/audio/nullAudioSound.h @@ -52,10 +52,10 @@ public: void set_active(bool); bool get_active() const; - void set_finished_event(const string& event); - const string& get_finished_event() const; + void set_finished_event(const std::string& event); + const std::string& get_finished_event() const; - const string& get_name() const; + const std::string& get_name() const; PN_stdfloat length() const; diff --git a/panda/src/audio/test_audio.cxx b/panda/src/audio/test_audio.cxx index a2a7ac06fb..612ad1bcb5 100644 --- a/panda/src/audio/test_audio.cxx +++ b/panda/src/audio/test_audio.cxx @@ -26,9 +26,9 @@ main(int argc, char* argv[]) { PT(AudioSound) tester = AudioPool::load_sound(argv[1]); AudioManager::play(tester); AudioPool::release_all_sounds(); - cerr << "all sounds but 1 released" << endl; + std::cerr << "all sounds but 1 released" << std::endl; } - cerr << "all sounds released" << endl; + std::cerr << "all sounds released" << std::endl; } /* diff --git a/panda/src/audiotraits/fmodAudioManager.cxx b/panda/src/audiotraits/fmodAudioManager.cxx index 012fd103cd..42fd08c536 100644 --- a/panda/src/audiotraits/fmodAudioManager.cxx +++ b/panda/src/audiotraits/fmodAudioManager.cxx @@ -98,7 +98,7 @@ FmodAudioManager() { _saved_outputtype = FMOD_OUTPUTTYPE_AUTODETECT; - if (_system == (FMOD::System *)NULL) { + if (_system == nullptr) { // Create the global FMOD System object. This one object must be shared // by all FmodAudioManagers (this is particularly true on OSX, but the // FMOD documentation is unclear as to whether this is the intended design @@ -196,7 +196,7 @@ FmodAudioManager:: if (_all_managers.empty()) { result = _system->release(); fmod_audio_errcheck("_system->release()", result); - _system = NULL; + _system = nullptr; _system_is_valid = false; } } @@ -232,13 +232,13 @@ make_dsp(const FilterProperties::FilterConfig &conf) { case FilterProperties::FT_compress: dsptype = FMOD_DSP_TYPE_COMPRESSOR; break; default: audio_error("Garbage in DSP configuration data"); - return NULL; + return nullptr; } result = _system->createDSPByType( dsptype, &dsp); if (result != 0) { audio_error("Could not create DSP object"); - return NULL; + return nullptr; } FMOD_RESULT res1 = FMOD_OK; @@ -334,7 +334,7 @@ make_dsp(const FilterProperties::FilterConfig &conf) { (res13!=FMOD_OK)||(res14!=FMOD_OK)) { audio_error("Could not configure DSP"); dsp->release(); - return NULL; + return nullptr; } dsp->setUserData(USER_DSP_MAGIC); @@ -364,7 +364,7 @@ update_dsp_chain(FMOD::DSP *head, FilterProperties *config) { break; } FMOD::DSP *prev; - result = head->getInput(0, &prev, NULL); + result = head->getInput(0, &prev, nullptr); fmod_audio_errcheck("head->getInput()", result); void *userdata; result = prev->getUserData(&userdata); @@ -380,7 +380,7 @@ update_dsp_chain(FMOD::DSP *head, FilterProperties *config) { for (int i=0; i<(int)(conf.size()); i++) { FMOD::DSP *dsp = make_dsp(conf[i]); - result = _channelgroup->addDSP(dsp, NULL); + result = _channelgroup->addDSP(dsp, nullptr); fmod_audio_errcheck("_channelgroup->addDSP()", result); } } @@ -409,7 +409,7 @@ configure_filters(FilterProperties *config) { * This is what creates a sound instance. */ PT(AudioSound) FmodAudioManager:: -get_sound(const string &file_name, bool positional, int) { +get_sound(const std::string &file_name, bool positional, int) { ReMutexHolder holder(_lock); // Needed so People use Panda's Generic UNIX Style Paths for Filename. // path.to_os_specific() converts it back to the proper OS version later on. @@ -419,15 +419,19 @@ get_sound(const string &file_name, bool positional, int) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->resolve_filename(path, get_model_path()); - // Build a new AudioSound from the audio data. - PT(AudioSound) audioSound; - PT(FmodAudioSound) fmodAudioSound = new FmodAudioSound(this, path, positional); + // Locate the file on disk. + path.set_binary(); + PT(VirtualFile) file = vfs->get_file(path); + if (file != nullptr) { + // Build a new AudioSound from the audio data. + PT(FmodAudioSound) sound = new FmodAudioSound(this, file, positional); - _all_sounds.insert(fmodAudioSound); - - audioSound = fmodAudioSound; - - return audioSound; + _all_sounds.insert(sound); + return sound; + } else { + audio_error("createSound(" << path << "): File not found."); + return get_null_sound(); + } } /** @@ -436,7 +440,7 @@ get_sound(const string &file_name, bool positional, int) { PT(AudioSound) FmodAudioManager:: get_sound(MovieAudio *source, bool positional, int) { nassert_raise("FMOD audio manager does not support MovieAudio sources"); - return NULL; + return nullptr; } /** @@ -768,7 +772,7 @@ reduce_sounds_playing_to(unsigned int count) { * NOT USED FOR FMOD-EX!!! Clears a sound out of the sound cache. */ void FmodAudioManager:: -uncache_sound(const string& file_name) { +uncache_sound(const std::string& file_name) { audio_debug("FmodAudioManager::uncache_sound(\""<get_original_filename()); _active = manager->get_active(); _paused = false; @@ -73,20 +78,14 @@ FmodAudioSound(AudioManager *manager, Filename file_name, bool positional) { _manager = fmanager; _channel = 0; - _file_name = file_name; + _file_name = file->get_original_filename(); _file_name.set_binary(); // Get the Speaker Mode [Important for later on.] result = _manager->_system->getSpeakerMode( &_speakermode ); fmod_audio_errcheck("_system->getSpeakerMode()", result); - VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); - PT(VirtualFile) file = vfs->get_file(_file_name); - if (file == (VirtualFile *)NULL) { - // File not found. We will display the appropriate error message below. - result = FMOD_ERR_FILE_NOTFOUND; - - } else { + { bool preload = (fmod_audio_preload_threshold < 0) || (file->get_file_size() < fmod_audio_preload_threshold); int flags = FMOD_SOFTWARE; flags |= positional ? FMOD_3D : FMOD_2D; @@ -99,7 +98,7 @@ FmodAudioSound(AudioManager *manager, Filename file_name, bool positional) { if (ext == "mid") { // Get the MIDI parameters. memcpy(&sound_info, &_manager->_midi_info, sizeof(sound_info)); - if (sound_info.dlsname != NULL) { + if (sound_info.dlsname != nullptr) { audio_debug("Using DLS file " << sound_info.dlsname); } } @@ -107,7 +106,7 @@ FmodAudioSound(AudioManager *manager, Filename file_name, bool positional) { const char *name_or_data = _file_name.c_str(); string os_filename; - pvector mem_buffer; + vector_uchar mem_buffer; SubfileInfo info; if (preload) { // Pre-read the file right now, and pass it in as a memory buffer. This @@ -145,7 +144,7 @@ FmodAudioSound(AudioManager *manager, Filename file_name, bool positional) { #if defined(HAVE_THREADS) && !defined(SIMPLE_THREADS) // Otherwise, if the Panda threading system is compiled in, we can // assign callbacks to read the file through the VFS. - name_or_data = (const char *)file.p(); + name_or_data = (const char *)file; sound_info.length = (unsigned int)info.get_size(); sound_info.useropen = open_callback; sound_info.userclose = close_callback; @@ -880,7 +879,7 @@ sound_end_callback(FMOD_CHANNEL * channel, // have to worry about thread-related issues here. if (type == FMOD_CHANNEL_CALLBACKTYPE_END) { FMOD::Channel *fc = (FMOD::Channel *)channel; - void *userdata = NULL; + void *userdata = nullptr; FMOD_RESULT result = fc->getUserData(&userdata); fmod_audio_errcheck("channel->getUserData()", result); FmodAudioSound *fsound = (FmodAudioSound*)userdata; @@ -897,7 +896,7 @@ open_callback(const char *name, int, unsigned int *file_size, void **handle, void **user_data) { // We actually pass in the VirtualFile pointer as the "name". VirtualFile *file = (VirtualFile *)name; - if (file == (VirtualFile *)NULL) { + if (file == nullptr) { return FMOD_ERR_FILE_NOTFOUND; } if (fmodAudio_cat.is_spam()) { diff --git a/panda/src/audiotraits/fmodAudioSound.h b/panda/src/audiotraits/fmodAudioSound.h index c77664ab61..40de00823d 100644 --- a/panda/src/audiotraits/fmodAudioSound.h +++ b/panda/src/audiotraits/fmodAudioSound.h @@ -70,10 +70,11 @@ #include #include -class EXPCL_FMOD_AUDIO FmodAudioSound : public AudioSound { - public: +class VirtualFile; - FmodAudioSound(AudioManager *manager, Filename fn, bool positional ); +class EXPCL_FMOD_AUDIO FmodAudioSound : public AudioSound { +public: + FmodAudioSound(AudioManager *manager, VirtualFile *file, bool positional); ~FmodAudioSound(); // For best compatibility, set the loop_count, start_time, volume, and @@ -106,7 +107,7 @@ class EXPCL_FMOD_AUDIO FmodAudioSound : public AudioSound { void set_play_rate(PN_stdfloat play_rate=1.0f); PN_stdfloat get_play_rate() const; - const string &get_name() const; + const std::string &get_name() const; // return: playing time in seconds. PN_stdfloat length() const; @@ -132,8 +133,8 @@ class EXPCL_FMOD_AUDIO FmodAudioSound : public AudioSound { bool get_active() const; void finished(); - void set_finished_event(const string& event); - const string& get_finished_event() const; + void set_finished_event(const std::string& event); + const std::string& get_finished_event() const; private: PT(FmodAudioManager) _manager; @@ -175,7 +176,7 @@ class EXPCL_FMOD_AUDIO FmodAudioSound : public AudioSound { bool _paused; PN_stdfloat _start_time; - string _finished_event; + std::string _finished_event; // This reference-counting pointer is set to this while the sound is // playing, and cleared when we get an indication that the sound has diff --git a/panda/src/audiotraits/globalMilesManager.cxx b/panda/src/audiotraits/globalMilesManager.cxx index 163147c75e..796b099425 100644 --- a/panda/src/audiotraits/globalMilesManager.cxx +++ b/panda/src/audiotraits/globalMilesManager.cxx @@ -26,6 +26,9 @@ #include #endif +using std::istream; +using std::string; + GlobalMilesManager *GlobalMilesManager::_global_ptr; /** @@ -100,7 +103,7 @@ get_sample(HSAMPLE &sample, size_t &index, MilesAudioSample *sound) { for (size_t i = 0; i < _samples.size(); ++i) { SampleData &smp = _samples[i]; if (AIL_sample_status(smp._sample) == SMP_DONE) { - if (smp._sound != NULL) { + if (smp._sound != nullptr) { // Tell the last sound that was using this sample that it's done now. smp._sound->internal_stop(); } @@ -137,7 +140,7 @@ release_sample(size_t index, MilesAudioSample *sound) { SampleData &smp = _samples[index]; if (smp._sound == sound) { - smp._sound = NULL; + smp._sound = nullptr; } } @@ -159,7 +162,7 @@ get_sequence(HSEQUENCE &sequence, size_t &index, MilesAudioSequence *sound) { for (size_t i = 0; i < _sequences.size(); ++i) { SequenceData &seq = _sequences[i]; if (AIL_sequence_status(seq._sequence) == SEQ_DONE) { - if (seq._sound != NULL) { + if (seq._sound != nullptr) { // Tell the last sound that was using this sequence that it's done // now. seq._sound->internal_stop(); @@ -196,7 +199,7 @@ release_sequence(size_t index, MilesAudioSequence *sound) { SequenceData &seq = _sequences[index]; if (seq._sound == sound) { - seq._sound = NULL; + seq._sound = nullptr; } } @@ -214,7 +217,7 @@ force_midi_reset() { audio_debug("MilesAudioManager::force_midi_reset"); #ifdef WIN32 - if ((_midi_driver!=NULL) && (_midi_driver->deviceid != MIDI_NULL_DRIVER) && (_midi_driver->hMidiOut != NULL)) { + if ((_midi_driver!=nullptr) && (_midi_driver->deviceid != MIDI_nullptr_DRIVER) && (_midi_driver->hMidiOut != nullptr)) { audio_debug("MilesAudioManager::calling midiOutReset"); midiOutReset(_midi_driver->hMidiOut); } @@ -226,7 +229,7 @@ force_midi_reset() { */ GlobalMilesManager *GlobalMilesManager:: get_global_ptr() { - if (_global_ptr == NULL) { + if (_global_ptr == nullptr) { _global_ptr = new GlobalMilesManager; } return _global_ptr; @@ -282,7 +285,7 @@ open_api() { _midi_driver = AIL_open_XMIDI_driver(AIL_OPEN_XMIDI_NULL_DRIVER); // Load the downloadable sounds file: - _dls_device = AIL_DLS_open(_midi_driver, _digital_driver, NULL, 0, + _dls_device = AIL_DLS_open(_midi_driver, _digital_driver, nullptr, 0, audio_output_rate, audio_output_bits, audio_output_channels); @@ -293,7 +296,7 @@ open_api() { _dls_data.clear(); PT(VirtualFile) file = vfs->get_file(dls_pathname); - if (file == (VirtualFile *)NULL) { + if (file == nullptr) { milesAudio_cat.warning() << "DLS file does not exist: " << dls_pathname << "\n"; @@ -384,7 +387,7 @@ U32 AILCALLBACK GlobalMilesManager:: open_callback(char const *filename, UINTa *file_handle) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); istream *strm = vfs->open_read_file(Filename::binary_filename(string(filename)), true); - if (strm == NULL) { + if (strm == nullptr) { // Failure. return 0; } @@ -414,15 +417,15 @@ seek_callback(UINTa file_handle, S32 offset, U32 type) { strm->clear(); switch (type) { case AIL_FILE_SEEK_BEGIN: - strm->seekg(offset, ios::beg); + strm->seekg(offset, std::ios::beg); break; case AIL_FILE_SEEK_CURRENT: - strm->seekg(offset, ios::cur); + strm->seekg(offset, std::ios::cur); break; case AIL_FILE_SEEK_END: - strm->seekg(offset, ios::end); + strm->seekg(offset, std::ios::end); break; } diff --git a/panda/src/audiotraits/globalMilesManager.h b/panda/src/audiotraits/globalMilesManager.h index e7e0a11646..3e9f2f0084 100644 --- a/panda/src/audiotraits/globalMilesManager.h +++ b/panda/src/audiotraits/globalMilesManager.h @@ -67,7 +67,7 @@ public: // For software MIDI: HDLSDEVICE _dls_device; HDLSFILEID _dls_file; - pvector _dls_data; + vector_uchar _dls_data; private: void open_api(); diff --git a/panda/src/audiotraits/milesAudioManager.cxx b/panda/src/audiotraits/milesAudioManager.cxx index c20ebd1a9a..2aed1ce44b 100644 --- a/panda/src/audiotraits/milesAudioManager.cxx +++ b/panda/src/audiotraits/milesAudioManager.cxx @@ -31,6 +31,8 @@ #include +using std::string; + TypeHandle MilesAudioManager::_type_handle; @@ -147,18 +149,18 @@ get_sound(const string &file_name, bool, int) { } else { // ...the sound was not found in the cachepool. sd = load(path); - if (sd != (SoundData *)NULL) { + if (sd != nullptr) { while (_sounds.size() >= (unsigned int)_cache_limit) { uncache_a_sound(); } // Put it in the pool: The following is roughly like: _sounds[path] = // sd; But, it gives us an iterator into the map. - pair ib + std::pair ib = _sounds.insert(SoundMap::value_type(path, sd)); if (!ib.second) { // The insert failed. audio_debug(" failed map insert of "<_file_type == AILFILETYPE_MIDI || sd->_file_type == AILFILETYPE_XMIDI || @@ -199,7 +201,7 @@ get_sound(const string &file_name, bool, int) { } audio_debug(" returning 0x" << (void*)audioSound); - nassertr(do_is_valid(), NULL); + nassertr(do_is_valid(), nullptr); return audioSound; } @@ -209,7 +211,7 @@ get_sound(const string &file_name, bool, int) { PT(AudioSound) MilesAudioManager:: get_sound(MovieAudio *sound, bool, int) { nassert_raise("Miles audio manager does not support MovieAudio sources."); - return NULL; + return nullptr; } /** @@ -505,69 +507,69 @@ set_speaker_configuration(LVecBase3 *speaker1, LVecBase3 *speaker2, LVecBase3 *s MSSVECTOR3D speakers[9]; - if(speaker1 != NULL) { + if(speaker1 != nullptr) { speakers[0].x = speaker1->get_x(); speakers[0].y = speaker1->get_z(); speakers[0].z = speaker1->get_y(); } - if(speaker2 != NULL) { + if(speaker2 != nullptr) { speakers[1].x = speaker2->get_x(); speakers[1].y = speaker2->get_z(); speakers[1].z = speaker2->get_y(); } - if(speaker3 != NULL) { + if(speaker3 != nullptr) { speakers[2].x = speaker3->get_x(); speakers[2].y = speaker3->get_z(); speakers[2].z = speaker3->get_y(); } - if(speaker4 != NULL) { + if(speaker4 != nullptr) { speakers[3].x = speaker4->get_x(); speakers[3].y = speaker4->get_z(); speakers[3].z = speaker4->get_y(); } - if(speaker5 != NULL) { + if(speaker5 != nullptr) { speakers[4].x = speaker5->get_x(); speakers[4].y = speaker5->get_z(); speakers[4].z = speaker5->get_y(); } - if(speaker6 != NULL) { + if(speaker6 != nullptr) { speakers[5].x = speaker6->get_x(); speakers[5].y = speaker6->get_z(); speakers[5].z = speaker6->get_y(); } - if(speaker7 != NULL) { + if(speaker7 != nullptr) { speakers[6].x = speaker7->get_x(); speakers[6].y = speaker7->get_z(); speakers[6].z = speaker7->get_y(); } - if(speaker8 != NULL) { + if(speaker8 != nullptr) { speakers[7].x = speaker8->get_x(); speakers[7].y = speaker8->get_z(); speakers[7].z = speaker8->get_y(); } - if(speaker9 != NULL) { + if(speaker9 != nullptr) { speakers[8].x = speaker9->get_x(); speakers[8].y = speaker9->get_z(); speakers[8].z = speaker9->get_y(); } - if(speaker1 == NULL) { + if(speaker1 == nullptr) { audio_error("No valid speaker positions specified in MilesAudioManager::set_speaker_configuration()."); - } else if(speaker2 == NULL) { + } else if(speaker2 == nullptr) { AIL_set_speaker_configuration(mgr->_digital_driver, speakers, 1, 1.0); - } else if(speaker3 == NULL) { + } else if(speaker3 == nullptr) { AIL_set_speaker_configuration(mgr->_digital_driver, speakers, 2, 1.0); - } else if(speaker4 == NULL) { + } else if(speaker4 == nullptr) { AIL_set_speaker_configuration(mgr->_digital_driver, speakers, 3, 1.0); - } else if(speaker5 == NULL) { + } else if(speaker5 == nullptr) { AIL_set_speaker_configuration(mgr->_digital_driver, speakers, 4, 1.0); - } else if(speaker6 == NULL) { + } else if(speaker6 == nullptr) { AIL_set_speaker_configuration(mgr->_digital_driver, speakers, 5, 1.0); - } else if(speaker7 == NULL) { + } else if(speaker7 == nullptr) { AIL_set_speaker_configuration(mgr->_digital_driver, speakers, 6, 1.0); - } else if(speaker8 == NULL) { + } else if(speaker8 == nullptr) { AIL_set_speaker_configuration(mgr->_digital_driver, speakers, 7, 1.0); - } else if(speaker9 == NULL) { + } else if(speaker9 == nullptr) { AIL_set_speaker_configuration(mgr->_digital_driver, speakers, 8, 1.0); } else { AIL_set_speaker_configuration(mgr->_digital_driver, speakers, 9, 1.0); @@ -673,7 +675,7 @@ cleanup() { * */ void MilesAudioManager:: -output(ostream &out) const { +output(std::ostream &out) const { LightReMutexHolder holder(_lock); out << get_type() << ": " << _sounds_playing.size() << " / " << _sounds_on_loan.size() << " sounds playing / total"; @@ -683,7 +685,7 @@ output(ostream &out) const { * */ void MilesAudioManager:: -write(ostream &out) const { +write(std::ostream &out) const { LightReMutexHolder holder(_lock); out << (*this) << "\n"; @@ -878,16 +880,16 @@ load(const Filename &file_name) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); PT(VirtualFile) file = vfs->get_file(file_name); - if (file == (VirtualFile *)NULL) { + if (file == nullptr) { milesAudio_cat.warning() << "No such file: " << file_name << "\n"; - return NULL; + return nullptr; } if (file->get_file_size() == 0) { milesAudio_cat.warning() << "File " << file_name << " is empty\n"; - return NULL; + return nullptr; } sd->_basename = file_name.get_basename(); @@ -899,7 +901,7 @@ load(const Filename &file_name) { bool is_midi_file = (downcase(extension) == "mid"); - if ((miles_audio_preload_threshold == -1 || file->get_file_size() < (streamsize)miles_audio_preload_threshold) || + if ((miles_audio_preload_threshold == -1 || file->get_file_size() < (std::streamsize)miles_audio_preload_threshold) || is_midi_file) { // If the file is sufficiently small, we'll preload it into memory. MIDI // files cannot be streamed, so we always preload them, regardless of @@ -908,7 +910,7 @@ load(const Filename &file_name) { if (!file->read_file(sd->_raw_data, true)) { milesAudio_cat.warning() << "Unable to read " << file_name << "\n"; - return NULL; + return nullptr; } sd->_file_type = @@ -955,7 +957,7 @@ load(const Filename &file_name) { U32 wav_data_size; if (AIL_decompress_ASI(&sd->_raw_data[0], sd->_raw_data.size(), sd->_basename.c_str(), &wav_data, &wav_data_size, - NULL)) { + nullptr)) { audio_debug("expanded " << sd->_basename << " from " << sd->_raw_data.size() << " bytes to " << wav_data_size << " bytes."); diff --git a/panda/src/audiotraits/milesAudioManager.h b/panda/src/audiotraits/milesAudioManager.h index ead813b679..e6e7f65555 100644 --- a/panda/src/audiotraits/milesAudioManager.h +++ b/panda/src/audiotraits/milesAudioManager.h @@ -28,6 +28,7 @@ #include "pmutex.h" #include "lightReMutex.h" #include "conditionVar.h" +#include "vector_uchar.h" class MilesAudioSound; @@ -42,9 +43,9 @@ public: virtual bool is_valid(); - virtual PT(AudioSound) get_sound(const string &file_name, bool positional = false, int mode=SM_heuristic); + virtual PT(AudioSound) get_sound(const std::string &file_name, bool positional = false, int mode=SM_heuristic); virtual PT(AudioSound) get_sound(MovieAudio *sound, bool positional = false, int mode=SM_heuristic); - virtual void uncache_sound(const string &file_name); + virtual void uncache_sound(const std::string &file_name); virtual void clear_cache(); virtual void set_cache_limit(unsigned int count); virtual unsigned int get_cache_limit() const; @@ -81,10 +82,10 @@ public: virtual PN_stdfloat audio_3d_get_doppler_factor() const; virtual void audio_3d_set_drop_off_factor(PN_stdfloat factor); virtual PN_stdfloat audio_3d_get_drop_off_factor() const; - virtual void set_speaker_configuration(LVecBase3 *speaker1, LVecBase3 *speaker2=NULL, LVecBase3 *speaker3=NULL, LVecBase3 *speaker4=NULL, LVecBase3 *speaker5=NULL, LVecBase3 *speaker6=NULL, LVecBase3 *speaker7=NULL, LVecBase3 *speaker8=NULL, LVecBase3 *speaker9=NULL); + virtual void set_speaker_configuration(LVecBase3 *speaker1, LVecBase3 *speaker2=nullptr, LVecBase3 *speaker3=nullptr, LVecBase3 *speaker4=nullptr, LVecBase3 *speaker5=nullptr, LVecBase3 *speaker6=nullptr, LVecBase3 *speaker7=nullptr, LVecBase3 *speaker8=nullptr, LVecBase3 *speaker9=nullptr); - virtual void output(ostream &out) const; - virtual void write(ostream &out) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out) const; private: bool do_is_valid(); @@ -94,7 +95,7 @@ private: void start_service_stream(HSTREAM stream); void stop_service_stream(HSTREAM stream); - void most_recently_used(const string &path); + void most_recently_used(const std::string &path); void uncache_a_sound(); void starting_sound(MilesAudioSound *audio); @@ -126,11 +127,11 @@ private: Filename _basename; S32 _file_type; - pvector _raw_data; + vector_uchar _raw_data; bool _has_length; PN_stdfloat _length; // in seconds. }; - typedef pmap SoundMap; + typedef pmap SoundMap; SoundMap _sounds; typedef pset AudioSet; @@ -142,7 +143,7 @@ private: SoundsPlaying _sounds_playing; // The Least Recently Used mechanism: - typedef pdeque LRU; + typedef pdeque LRU; LRU _lru; // State: PN_stdfloat _volume; diff --git a/panda/src/audiotraits/milesAudioSample.cxx b/panda/src/audiotraits/milesAudioSample.cxx index c89addb1a5..8eb0ab2d26 100644 --- a/panda/src/audiotraits/milesAudioSample.cxx +++ b/panda/src/audiotraits/milesAudioSample.cxx @@ -34,11 +34,11 @@ TypeHandle MilesAudioSample::_type_handle; */ MilesAudioSample:: MilesAudioSample(MilesAudioManager *manager, MilesAudioManager::SoundData *sd, - const string &file_name) : + const std::string &file_name) : MilesAudioSound(manager, file_name), _sd(sd) { - nassertv(sd != NULL); + nassertv(sd != nullptr); audio_debug("MilesAudioSample(manager=0x"<<(void*)&manager <<", sd=0x"<<(void*)sd<<", file_name="<release_sound(this); - _manager = NULL; + _manager = nullptr; } } @@ -269,7 +269,7 @@ cleanup() { * */ void MilesAudioSample:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << " " << get_name() << " " << status(); if (!_sd.is_null()) { out << " " << (_sd->_raw_data.size() + 1023) / 1024 << "K"; @@ -325,7 +325,7 @@ void MilesAudioSample::set_3d_min_distance(PN_stdfloat dist) { // distances in a single operation. float max_dist; int auto_3D_wet_atten; - AIL_sample_3D_distances(_sample, &max_dist, NULL, &auto_3D_wet_atten); + AIL_sample_3D_distances(_sample, &max_dist, nullptr, &auto_3D_wet_atten); AIL_set_sample_3D_distances(_sample, max_dist, dist, auto_3D_wet_atten); } else { @@ -341,7 +341,7 @@ PN_stdfloat MilesAudioSample::get_3d_min_distance() const { if(_sample != 0) { float min_dist; - AIL_sample_3D_distances(_sample, NULL, &min_dist, NULL); + AIL_sample_3D_distances(_sample, nullptr, &min_dist, nullptr); return (PN_stdfloat)min_dist; } else { audio_warning("_sample == 0 in MilesAudioSample::get_3d_min_distance()."); @@ -362,7 +362,7 @@ void MilesAudioSample::set_3d_max_distance(PN_stdfloat dist) { // distances in a single operation. float min_dist; int auto_3D_wet_atten; - AIL_sample_3D_distances(_sample, NULL, &min_dist, &auto_3D_wet_atten); + AIL_sample_3D_distances(_sample, nullptr, &min_dist, &auto_3D_wet_atten); AIL_set_sample_3D_distances(_sample, dist, min_dist, auto_3D_wet_atten); } else { @@ -378,7 +378,7 @@ PN_stdfloat MilesAudioSample::get_3d_max_distance() const { if(_sample != 0) { float max_dist; - AIL_sample_3D_distances(_sample, &max_dist, NULL, NULL); + AIL_sample_3D_distances(_sample, &max_dist, nullptr, nullptr); return (PN_stdfloat)max_dist; } else { audio_warning("_sample == 0 in MilesAudioSample::get_3d_max_distance()."); @@ -500,7 +500,7 @@ finish_callback(HSAMPLE sample) { milesAudio_cat.debug() << "finished " << *self << "\n"; } - if (self->_manager == (MilesAudioManager *)NULL) { + if (self->_manager == nullptr) { return; } self->_manager->_sounds_finished = true; diff --git a/panda/src/audiotraits/milesAudioSample.h b/panda/src/audiotraits/milesAudioSample.h index 6e976fa212..22f5e5d457 100644 --- a/panda/src/audiotraits/milesAudioSample.h +++ b/panda/src/audiotraits/milesAudioSample.h @@ -30,7 +30,7 @@ class EXPCL_MILES_AUDIO MilesAudioSample : public MilesAudioSound { private: MilesAudioSample(MilesAudioManager *manager, MilesAudioManager::SoundData *sd, - const string &file_name); + const std::string &file_name); public: virtual ~MilesAudioSample(); @@ -49,7 +49,7 @@ public: virtual AudioSound::SoundStatus status() const; virtual void cleanup(); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; // 3D spatialized sound support. Spatialized sound was originally added for // FMOD, so there are parts of the interface in the Miles implementation diff --git a/panda/src/audiotraits/milesAudioSequence.cxx b/panda/src/audiotraits/milesAudioSequence.cxx index 3b79099db8..b214644e54 100644 --- a/panda/src/audiotraits/milesAudioSequence.cxx +++ b/panda/src/audiotraits/milesAudioSequence.cxx @@ -34,11 +34,11 @@ TypeHandle MilesAudioSequence::_type_handle; */ MilesAudioSequence:: MilesAudioSequence(MilesAudioManager *manager, MilesAudioManager::SoundData *sd, - const string &file_name) : + const std::string &file_name) : MilesAudioSound(manager, file_name), _sd(sd) { - nassertv(sd != NULL); + nassertv(sd != nullptr); audio_debug("MilesAudioSequence(manager=0x"<<(void*)&manager <<", sd=0x"<<(void*)sd<<", file_name="<_raw_data[0], 0); S32 length_ms; - AIL_sequence_ms_position(_sequence, &length_ms, NULL); + AIL_sequence_ms_position(_sequence, &length_ms, nullptr); PN_stdfloat time = (PN_stdfloat)length_ms * 0.001f; mgr->release_sequence(_sequence_index, this); _sequence = 0; diff --git a/panda/src/audiotraits/milesAudioSequence.h b/panda/src/audiotraits/milesAudioSequence.h index 8f01a037fd..2386c6d17b 100644 --- a/panda/src/audiotraits/milesAudioSequence.h +++ b/panda/src/audiotraits/milesAudioSequence.h @@ -29,7 +29,7 @@ class EXPCL_MILES_AUDIO MilesAudioSequence : public MilesAudioSound { private: MilesAudioSequence(MilesAudioManager *manager, MilesAudioManager::SoundData *sd, - const string &file_name); + const std::string &file_name); public: virtual ~MilesAudioSequence(); diff --git a/panda/src/audiotraits/milesAudioSound.cxx b/panda/src/audiotraits/milesAudioSound.cxx index 0988eaf48e..75ca1d012b 100644 --- a/panda/src/audiotraits/milesAudioSound.cxx +++ b/panda/src/audiotraits/milesAudioSound.cxx @@ -16,6 +16,8 @@ #include "milesAudioManager.h" +using std::string; + TypeHandle MilesAudioSound::_type_handle; #undef miles_audio_debug @@ -130,7 +132,7 @@ set_time(PN_stdfloat time) { */ void MilesAudioSound:: set_active(bool active) { - if (_manager == (MilesAudioManager *)NULL) { + if (_manager == nullptr) { return; } diff --git a/panda/src/audiotraits/milesAudioSound.h b/panda/src/audiotraits/milesAudioSound.h index 46c6aa74c3..c44584d69a 100644 --- a/panda/src/audiotraits/milesAudioSound.h +++ b/panda/src/audiotraits/milesAudioSound.h @@ -26,7 +26,7 @@ */ class EXPCL_MILES_AUDIO MilesAudioSound : public AudioSound { protected: - MilesAudioSound(MilesAudioManager *manager, const string &file_name); + MilesAudioSound(MilesAudioManager *manager, const std::string &file_name); public: virtual void set_loop(bool loop=true); @@ -44,16 +44,16 @@ public: virtual void set_active(bool active=true); virtual bool get_active() const; - virtual void set_finished_event(const string &event); - virtual const string &get_finished_event() const; + virtual void set_finished_event(const std::string &event); + virtual const std::string &get_finished_event() const; - virtual const string &get_name() const; + virtual const std::string &get_name() const; virtual void cleanup(); protected: PT(MilesAudioManager) _manager; - string _file_name; + std::string _file_name; PN_stdfloat _volume; // 0..1.0 PN_stdfloat _balance; // -1..1 @@ -72,7 +72,7 @@ protected: // This is the string that throw_event() will throw when the sound finishes // playing. It is not triggered when the sound is stopped with stop(). // Note: no longer implemented. - string _finished_event; + std::string _finished_event; // This is set whenever we call set_time(). Calling play() will respect // this if it is set, and then reset it. diff --git a/panda/src/audiotraits/milesAudioStream.cxx b/panda/src/audiotraits/milesAudioStream.cxx index c8b9251cbd..480d35c81c 100644 --- a/panda/src/audiotraits/milesAudioStream.cxx +++ b/panda/src/audiotraits/milesAudioStream.cxx @@ -32,7 +32,7 @@ TypeHandle MilesAudioStream::_type_handle; * */ MilesAudioStream:: -MilesAudioStream(MilesAudioManager *manager, const string &file_name, +MilesAudioStream(MilesAudioManager *manager, const std::string &file_name, const Filename &path) : MilesAudioSound(manager, file_name), _path(path) @@ -118,7 +118,7 @@ play() { */ void MilesAudioStream:: stop() { - if (_manager == (MilesAudioManager *)NULL) { + if (_manager == nullptr) { return; } miles_audio_debug("stop()"); @@ -152,7 +152,7 @@ get_time() const { } S32 current_ms; - AIL_stream_ms_position(_stream, NULL, ¤t_ms); + AIL_stream_ms_position(_stream, nullptr, ¤t_ms); PN_stdfloat time = PN_stdfloat(current_ms * 0.001f); return time; @@ -173,8 +173,8 @@ set_volume(PN_stdfloat volume) { // Change to Miles volume, range 0 to 1.0: F32 milesVolume = volume; - milesVolume = min(milesVolume, 1.0f); - milesVolume = max(milesVolume, 0.0f); + milesVolume = std::min(milesVolume, 1.0f); + milesVolume = std::max(milesVolume, 0.0f); // Convert balance of -1.0..1.0 to 0-1.0: F32 milesBalance = (F32)((_balance + 1.0f) * 0.5f); @@ -226,7 +226,7 @@ length() const { } S32 length_ms; - AIL_stream_ms_position(_stream, &length_ms, NULL); + AIL_stream_ms_position(_stream, &length_ms, nullptr); _length = (PN_stdfloat)length_ms * 0.001f; _got_length = true; } @@ -266,9 +266,9 @@ cleanup() { set_active(false); nassertv(_stream == 0); - if (_manager != (MilesAudioManager *)NULL) { + if (_manager != nullptr) { _manager->release_sound(this); - _manager = NULL; + _manager = nullptr; } } @@ -283,7 +283,7 @@ finish_callback(HSTREAM stream) { milesAudio_cat.debug() << "finished " << *self << "\n"; } - if (self->_manager == (MilesAudioManager *)NULL) { + if (self->_manager == nullptr) { return; } self->_manager->_sounds_finished = true; @@ -300,8 +300,8 @@ do_set_time(PN_stdfloat time) { // Ensure we don't inadvertently run off the end of the sound. S32 length_ms; - AIL_stream_ms_position(_stream, &length_ms, NULL); - time_ms = min(time_ms, length_ms); + AIL_stream_ms_position(_stream, &length_ms, nullptr); + time_ms = std::min(time_ms, length_ms); AIL_set_stream_ms_position(_stream, time_ms); } diff --git a/panda/src/audiotraits/milesAudioStream.h b/panda/src/audiotraits/milesAudioStream.h index 8050f513cf..42bda6b6ab 100644 --- a/panda/src/audiotraits/milesAudioStream.h +++ b/panda/src/audiotraits/milesAudioStream.h @@ -28,7 +28,7 @@ */ class EXPCL_MILES_AUDIO MilesAudioStream : public MilesAudioSound { private: - MilesAudioStream(MilesAudioManager *manager, const string &file_name, + MilesAudioStream(MilesAudioManager *manager, const std::string &file_name, const Filename &path); public: diff --git a/panda/src/audiotraits/openalAudioManager.cxx b/panda/src/audiotraits/openalAudioManager.cxx index 1a91185ecf..feee7a62aa 100644 --- a/panda/src/audiotraits/openalAudioManager.cxx +++ b/panda/src/audiotraits/openalAudioManager.cxx @@ -33,20 +33,23 @@ #define ALC_ALL_DEVICES_SPECIFIER 0x1013 #endif +using std::endl; +using std::string; + TypeHandle OpenALAudioManager::_type_handle; ReMutex OpenALAudioManager::_lock; int OpenALAudioManager::_active_managers = 0; bool OpenALAudioManager::_openal_active = false; -ALCdevice* OpenALAudioManager::_device = NULL; -ALCcontext* OpenALAudioManager::_context = NULL; +ALCdevice* OpenALAudioManager::_device = nullptr; +ALCcontext* OpenALAudioManager::_context = nullptr; // This is the list of all OpenALAudioManager objects in the world. It must // be a pointer rather than a concrete object, so it won't be destructed at // exit time before we're done removing things from it. -OpenALAudioManager::Managers *OpenALAudioManager::_managers = NULL; +OpenALAudioManager::Managers *OpenALAudioManager::_managers = nullptr; -OpenALAudioManager::SourceCache *OpenALAudioManager::_al_sources = NULL; +OpenALAudioManager::SourceCache *OpenALAudioManager::_al_sources = nullptr; // Central dispatcher for audio errors. @@ -79,7 +82,7 @@ AudioManager *Create_OpenALAudioManager() { OpenALAudioManager:: OpenALAudioManager() { ReMutexHolder holder(_lock); - if (_managers == (Managers *)NULL) { + if (_managers == nullptr) { _managers = new Managers; _al_sources = new SourceCache; } @@ -118,7 +121,7 @@ OpenALAudioManager() { // Initialization audio_cat.init(); if (_active_managers == 0 || !_openal_active) { - _device = NULL; + _device = nullptr; string dev_name = select_audio_device(); if (!dev_name.empty()) { @@ -126,7 +129,7 @@ OpenALAudioManager() { audio_cat.info() << "Using OpenAL device " << dev_name << "\n"; _device = alcOpenDevice(dev_name.c_str()); - if (_device == NULL) { + if (_device == nullptr) { audio_cat.error() << "Couldn't open OpenAL device \"" << dev_name << "\", falling back to default device\n"; } @@ -134,27 +137,27 @@ OpenALAudioManager() { audio_cat.info() << "Using default OpenAL device\n"; } - if (_device == NULL) { + if (_device == nullptr) { // Open the default device. - _device = alcOpenDevice(NULL); + _device = alcOpenDevice(nullptr); - if (_device == NULL && dev_name != "OpenAL Soft") { + if (_device == nullptr && dev_name != "OpenAL Soft") { // Try the OpenAL Soft driver instead, which is fairly reliable. _device = alcOpenDevice("OpenAL Soft"); - if (_device == NULL) { + if (_device == nullptr) { audio_cat.error() << "Couldn't open default OpenAL device\n"; } } } - if (_device != NULL) { + if (_device != nullptr) { // We managed to get a device open. alcGetError(_device); // clear errors - _context = alcCreateContext(_device, NULL); + _context = alcCreateContext(_device, nullptr); alc_audio_errcheck("alcCreateContext(_device, NULL)", _device); - if (_context != NULL) { + if (_context != nullptr) { _openal_active = true; } } @@ -197,7 +200,7 @@ OpenALAudioManager() { OpenALAudioManager:: ~OpenALAudioManager() { ReMutexHolder holder(_lock); - nassertv(_managers != (Managers *)NULL); + nassertv(_managers != nullptr); Managers::iterator mi = _managers->find(this); nassertv(mi != _managers->end()); _managers->erase(mi); @@ -213,7 +216,7 @@ OpenALAudioManager:: void OpenALAudioManager:: shutdown() { ReMutexHolder holder(_lock); - if (_managers != (Managers *)NULL) { + if (_managers != nullptr) { Managers::iterator mi; for (mi = _managers->begin(); mi != _managers->end(); ++mi) { (*mi)->cleanup(); @@ -241,12 +244,12 @@ string OpenALAudioManager:: select_audio_device() { string selected_device = openal_device; - const char *devices = NULL; + const char *devices = nullptr; // This extension gives us all audio paths on all drivers. - if (alcIsExtensionPresent(NULL, "ALC_ENUMERATE_ALL_EXT") == AL_TRUE) { - string default_device = alcGetString(NULL, ALC_DEFAULT_ALL_DEVICES_SPECIFIER); - devices = (const char *)alcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER); + if (alcIsExtensionPresent(nullptr, "ALC_ENUMERATE_ALL_EXT") == AL_TRUE) { + string default_device = alcGetString(nullptr, ALC_DEFAULT_ALL_DEVICES_SPECIFIER); + devices = (const char *)alcGetString(nullptr, ALC_ALL_DEVICES_SPECIFIER); if (devices) { audio_cat.debug() << "All OpenAL devices:\n"; @@ -272,9 +275,9 @@ select_audio_device() { // This extension just gives us generic driver names, like "OpenAL Soft" and // "Generic Software", rather than individual outputs. - if (alcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT") == AL_TRUE) { - string default_device = alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER); - devices = (const char *)alcGetString(NULL, ALC_DEVICE_SPECIFIER); + if (alcIsExtensionPresent(nullptr, "ALC_ENUMERATION_EXT") == AL_TRUE) { + string default_device = alcGetString(nullptr, ALC_DEFAULT_DEVICE_SPECIFIER); + devices = (const char *)alcGetString(nullptr, ALC_DEVICE_SPECIFIER); if (devices) { audio_cat.debug() << "OpenAL drivers:\n"; @@ -402,14 +405,14 @@ get_sound_data(MovieAudio *movie, int mode) { } PT(MovieAudioCursor) stream = movie->open(); - if (stream == 0) { + if (stream == nullptr) { audio_error("Cannot open file: "<_sample == 0) { audio_error("Could not create an OpenAL buffer object"); delete sd; - return NULL; + return nullptr; } int channels = stream->audio_channels(); int samples = (int)(stream->length() * stream->audio_rate()); @@ -448,7 +451,7 @@ get_sound_data(MovieAudio *movie, int mode) { if (err != AL_NO_ERROR) { audio_error("could not fill OpenAL buffer object with data"); delete sd; - return NULL; + return nullptr; } _sample_cache.insert(SampleCache::value_type(path, sd)); } else { @@ -498,7 +501,7 @@ get_sound(const string &file_name, bool positional, int mode) { if (path.empty()) { audio_error("get_sound - invalid filename"); - return NULL; + return nullptr; } PT(MovieAudio) mva = MovieAudio::get(path); @@ -1007,18 +1010,18 @@ cleanup() { // make sure that the context is not current when it is destroyed alcGetError(_device); // clear errors - alcMakeContextCurrent(NULL); + alcMakeContextCurrent(nullptr); alc_audio_errcheck("alcMakeContextCurrent(NULL)",_device); alcDestroyContext(_context); alc_audio_errcheck("alcDestroyContext(_context)",_device); - _context = NULL; + _context = nullptr; if (_device) { audio_debug("Going to try to close openAL"); alcCloseDevice(_device); // alc_audio_errcheck("alcCloseDevice(_device)",_device); - _device = NULL; + _device = nullptr; audio_debug("openAL Closed"); } @@ -1033,9 +1036,9 @@ cleanup() { */ OpenALAudioManager::SoundData:: SoundData() : - _manager(0), + _manager(nullptr), _sample(0), - _stream(NULL), + _stream(nullptr), _length(0.0), _rate(0), _channels(0), diff --git a/panda/src/audiotraits/openalAudioManager.h b/panda/src/audiotraits/openalAudioManager.h index 1e16e4000b..8fe8a8f3f3 100644 --- a/panda/src/audiotraits/openalAudioManager.h +++ b/panda/src/audiotraits/openalAudioManager.h @@ -51,10 +51,10 @@ class EXPCL_OPENAL_AUDIO OpenALAudioManager : public AudioManager { virtual bool is_valid(); - virtual PT(AudioSound) get_sound(const string&, bool positional = false, int mode=SM_heuristic); + virtual PT(AudioSound) get_sound(const std::string&, bool positional = false, int mode=SM_heuristic); virtual PT(AudioSound) get_sound(MovieAudio *sound, bool positional = false, int mode=SM_heuristic); - virtual void uncache_sound(const string&); + virtual void uncache_sound(const std::string&); virtual void clear_cache(); virtual void set_cache_limit(unsigned int count); virtual unsigned int get_cache_limit() const; @@ -114,7 +114,7 @@ class EXPCL_OPENAL_AUDIO OpenALAudioManager : public AudioManager { virtual void update(); private: - string select_audio_device(); + std::string select_audio_device(); void make_current() const; @@ -175,7 +175,7 @@ private: }; - typedef phash_map SampleCache; + typedef phash_map SampleCache; SampleCache _sample_cache; typedef phash_set SoundsPlaying; diff --git a/panda/src/audiotraits/openalAudioSound.I b/panda/src/audiotraits/openalAudioSound.I index 9a090adc3d..5bbf56e871 100644 --- a/panda/src/audiotraits/openalAudioSound.I +++ b/panda/src/audiotraits/openalAudioSound.I @@ -76,7 +76,7 @@ release_sound_data(bool force) { */ INLINE bool OpenALAudioSound:: is_valid() const { - return _manager != NULL; + return _manager != nullptr; } /** @@ -98,5 +98,5 @@ is_playing() const { */ INLINE bool OpenALAudioSound:: has_sound_data() const { - return _sd != NULL; + return _sd != nullptr; } diff --git a/panda/src/audiotraits/openalAudioSound.cxx b/panda/src/audiotraits/openalAudioSound.cxx index faa9df5717..8d41a61fa3 100644 --- a/panda/src/audiotraits/openalAudioSound.cxx +++ b/panda/src/audiotraits/openalAudioSound.cxx @@ -38,7 +38,7 @@ OpenALAudioSound(OpenALAudioManager* manager, bool positional, int mode) : _movie(movie), - _sd(NULL), + _sd(nullptr), _playing_loops(0), _playing_rate(0.0), _loops_completed(0), @@ -109,7 +109,7 @@ cleanup() { release_sound_data(true); } _manager->release_sound(this); - _manager = 0; + _manager = nullptr; } /** @@ -836,14 +836,14 @@ get_active() const { * */ void OpenALAudioSound:: -set_finished_event(const string& event) { +set_finished_event(const std::string& event) { _finished_event = event; } /** * */ -const string& OpenALAudioSound:: +const std::string& OpenALAudioSound:: get_finished_event() const { return _finished_event; } @@ -851,7 +851,7 @@ get_finished_event() const { /** * Get name of sound file */ -const string& OpenALAudioSound:: +const std::string& OpenALAudioSound:: get_name() const { return _basename; } diff --git a/panda/src/audiotraits/openalAudioSound.h b/panda/src/audiotraits/openalAudioSound.h index e10f4f179a..3c1feda08a 100644 --- a/panda/src/audiotraits/openalAudioSound.h +++ b/panda/src/audiotraits/openalAudioSound.h @@ -72,10 +72,10 @@ public: // This is the string that throw_event() will throw when the sound finishes // playing. It is not triggered when the sound is stopped with stop(). - void set_finished_event(const string& event); - const string& get_finished_event() const; + void set_finished_event(const std::string& event); + const std::string& get_finished_event() const; - const string &get_name() const; + const std::string &get_name() const; // return: playing time in seconds. PN_stdfloat length() const; @@ -177,7 +177,7 @@ private: // This is the string that throw_event() will throw when the sound finishes // playing. It is not triggered when the sound is stopped with stop(). - string _finished_event; + std::string _finished_event; Filename _basename; diff --git a/panda/src/awesomium/AwMouseAndKeyboard.cxx b/panda/src/awesomium/AwMouseAndKeyboard.cxx index 2ee5728584..9948c0d49d 100644 --- a/panda/src/awesomium/AwMouseAndKeyboard.cxx +++ b/panda/src/awesomium/AwMouseAndKeyboard.cxx @@ -17,7 +17,7 @@ TypeHandle AwMouseAndKeyboard::_type_handle; -AwMouseAndKeyboard::AwMouseAndKeyboard(const string &name): +AwMouseAndKeyboard::AwMouseAndKeyboard(const std::string &name): DataNode(name) { _button_events_input = define_input("button_events", ButtonEventList::get_class_type()); @@ -34,7 +34,7 @@ void AwMouseAndKeyboard::do_transmit_data(DataGraphTraverser *trav, const DataNo int num_events = button_events->get_num_events(); for (int i = 0; i < num_events; i++) { const ButtonEvent &be = button_events->get_event(i); - string event_name = be._button.get_name(); + std::string event_name = be._button.get_name(); printf("Button Event! : %s with code %i and index %i ", event_name.c_str(), be._keycode, be._button.get_index()); if(be._type == ButtonEvent::T_down) printf("down"); if(be._type == ButtonEvent::T_repeat) printf("repeat"); diff --git a/panda/src/awesomium/AwMouseAndKeyboard.h b/panda/src/awesomium/AwMouseAndKeyboard.h index 2a70904523..e338939001 100644 --- a/panda/src/awesomium/AwMouseAndKeyboard.h +++ b/panda/src/awesomium/AwMouseAndKeyboard.h @@ -32,7 +32,7 @@ protected: int _button_events_output; PUBLISHED: - AwMouseAndKeyboard(const string &name); + AwMouseAndKeyboard(const std::string &name); protected: // Inherited from DataNode diff --git a/panda/src/awesomium/WebBrowserTexture.cxx b/panda/src/awesomium/WebBrowserTexture.cxx index 7872574b9d..1051a33e36 100644 --- a/panda/src/awesomium/WebBrowserTexture.cxx +++ b/panda/src/awesomium/WebBrowserTexture.cxx @@ -33,7 +33,7 @@ Texture(copy) /** * This initializes a web browser texture with the given AwWebView class. */ -WebBrowserTexture::WebBrowserTexture(const string &name, AwWebView* aw_web_view): +WebBrowserTexture::WebBrowserTexture(const std::string &name, AwWebView* aw_web_view): Texture(name), _update_active(true), _flip_texture_active(false) @@ -149,7 +149,7 @@ bool WebBrowserTexture::get_flip_texture_active() const { bool WebBrowserTexture::cull_callback(CullTraverser *trav, const CullTraverserData &data) const{ // see if we are in a state where udpates can happen. else just return if( !_update_active ) return true; - if( _aw_web_view == NULL ) return true; + if( _aw_web_view == nullptr ) return true; // do we even need to update? if( !_aw_web_view->is_dirty() ) return true; diff --git a/panda/src/awesomium/WebBrowserTexture.h b/panda/src/awesomium/WebBrowserTexture.h index e9ae392d10..3c9e6aaa08 100644 --- a/panda/src/awesomium/WebBrowserTexture.h +++ b/panda/src/awesomium/WebBrowserTexture.h @@ -37,7 +37,7 @@ protected: private: WebBrowserTexture(const WebBrowserTexture ©); PUBLISHED: - WebBrowserTexture(const string &name, AwWebView* aw_web_view = NULL); + WebBrowserTexture(const std::string &name, AwWebView* aw_web_view = nullptr); virtual ~WebBrowserTexture(); diff --git a/panda/src/awesomium/awWebView.cxx b/panda/src/awesomium/awWebView.cxx index 5ef0b95181..ebc3a63f89 100644 --- a/panda/src/awesomium/awWebView.cxx +++ b/panda/src/awesomium/awWebView.cxx @@ -28,7 +28,7 @@ AwWebView:: void AwWebView:: -loadURL2(const string& url, const string& frameName , const string& username , const string& password ) +loadURL2(const std::string& url, const std::string& frameName , const std::string& username , const std::string& password ) { _myWebView->loadURL2(url, frameName, username, password); diff --git a/panda/src/awesomium/awWebView.h b/panda/src/awesomium/awWebView.h index 5a5550c4ee..ad5c9d223c 100644 --- a/panda/src/awesomium/awWebView.h +++ b/panda/src/awesomium/awWebView.h @@ -63,7 +63,7 @@ PUBLISHED: // VC7 linker doesn't like wstring from VS2008, hence using the all regular // string version - void loadURL2(const string& url, const string& frameName ="", const string& username="" , const string& password=""); + void loadURL2(const std::string& url, const std::string& frameName ="", const std::string& username="" , const std::string& password=""); // VC7 linker doesn't like wstring from VS2008, hence using the all regular // string version diff --git a/panda/src/bullet/bulletAllHitsRayResult.cxx b/panda/src/bullet/bulletAllHitsRayResult.cxx index 12c6abacc4..1b638efcf9 100644 --- a/panda/src/bullet/bulletAllHitsRayResult.cxx +++ b/panda/src/bullet/bulletAllHitsRayResult.cxx @@ -136,7 +136,7 @@ get_hit_fraction() const { PandaNode *BulletRayHit:: get_node() const { - return (_object) ? (PandaNode *)_object->getUserPointer() : NULL; + return (_object) ? (PandaNode *)_object->getUserPointer() : nullptr; } /** diff --git a/panda/src/bullet/bulletBodyNode.cxx b/panda/src/bullet/bulletBodyNode.cxx index f02641cd96..9067999599 100644 --- a/panda/src/bullet/bulletBodyNode.cxx +++ b/panda/src/bullet/bulletBodyNode.cxx @@ -20,6 +20,7 @@ #include "collisionPlane.h" #include "collisionSphere.h" #include "collisionPolygon.h" +#include "collisionTube.h" TypeHandle BulletBodyNode::_type_handle; @@ -150,7 +151,7 @@ safe_to_flatten_below() const { * */ void BulletBodyNode:: -do_output(ostream &out) const { +do_output(std::ostream &out) const { PandaNode::output(out); @@ -166,7 +167,7 @@ do_output(ostream &out) const { * */ void BulletBodyNode:: -output(ostream &out) const { +output(std::ostream &out) const { LightMutexHolder holder(BulletWorld::get_global_lock()); do_output(out); @@ -310,7 +311,7 @@ BulletShape *BulletBodyNode:: get_shape(int idx) const { LightMutexHolder holder(BulletWorld::get_global_lock()); - nassertr(idx >= 0 && idx < (int)_shapes.size(), NULL); + nassertr(idx >= 0 && idx < (int)_shapes.size(), nullptr); return _shapes[idx]; } @@ -334,7 +335,7 @@ do_add_shape(BulletShape *bullet_shape, const TransformState *ts) { nassertv(ts); btCollisionShape *shape = bullet_shape->ptr(); - nassertv(shape != NULL); + nassertv(shape != nullptr); nassertv(!(shape->getShapeType() == CONVEX_HULL_SHAPE_PROXYTYPE && ((btConvexHullShape *)shape)->getNumVertices() == 0)); @@ -427,7 +428,7 @@ remove_shape(BulletShape *shape) { found = find(_shapes.begin(), _shapes.end(), ptshape); if (found == _shapes.end()) { - bullet_cat.warning() << "shape not attached" << endl; + bullet_cat.warning() << "shape not attached" << std::endl; } else { _shapes.erase(found); @@ -782,9 +783,9 @@ void BulletBodyNode:: add_shapes_from_collision_solids(CollisionNode *cnode) { LightMutexHolder holder(BulletWorld::get_global_lock()); - PT(BulletTriangleMesh) mesh = NULL; + PT(BulletTriangleMesh) mesh = nullptr; - for (int j=0; jget_num_solids(); j++) { + for (size_t j = 0; j < cnode->get_num_solids(); ++j) { CPT(CollisionSolid) solid = cnode->get_solid(j); TypeHandle type = solid->get_type(); @@ -804,6 +805,14 @@ add_shapes_from_collision_solids(CollisionNode *cnode) { do_add_shape(BulletBoxShape::make_from_solid(box), ts); } + // CollisionTube + else if (CollisionTube::get_class_type() == type) { + CPT(CollisionTube) tube = DCAST(CollisionTube, solid); + CPT(TransformState) ts = TransformState::make_pos((tube->get_point_b() + tube->get_point_a()) / 2.0); + + do_add_shape(BulletCapsuleShape::make_from_solid(tube), ts); + } + // CollisionPlane else if (CollisionPlane::get_class_type() == type) { CPT(CollisionPlane) plane = DCAST(CollisionPlane, solid); @@ -819,9 +828,9 @@ add_shapes_from_collision_solids(CollisionNode *cnode) { mesh = new BulletTriangleMesh(); } - for (int i=2; i < polygon->get_num_points(); i++ ) { + for (size_t i = 2; i < polygon->get_num_points(); ++i) { LPoint3 p1 = polygon->get_point(0); - LPoint3 p2 = polygon->get_point(i-1); + LPoint3 p2 = polygon->get_point(i - 1); LPoint3 p3 = polygon->get_point(i); mesh->do_add_triangle(p1, p2, p3, true); @@ -864,7 +873,7 @@ cout << "origin " << aabbMin.x() << " " << aabbMin.y() << " " << aabbMin.z() << */ btVector3 center; - btScalar radius; + btScalar radius = 0; if (_shape) { _shape->getBoundingSphere(center, radius); @@ -914,7 +923,7 @@ write_datagram(BamWriter *manager, Datagram &dg) { } // Write NULL pointer to indicate the end of the list. - manager->write_pointer(dg, NULL); + manager->write_pointer(dg, nullptr); } /** @@ -927,7 +936,7 @@ complete_pointers(TypedWritable **p_list, BamReader *manager) { PT(BulletShape) shape = DCAST(BulletShape, p_list[pi++]); - while (shape != (BulletShape *)NULL) { + while (shape != nullptr) { const TransformState *trans = DCAST(TransformState, p_list[pi++]); add_shape(shape, trans); diff --git a/panda/src/bullet/bulletBodyNode.h b/panda/src/bullet/bulletBodyNode.h index 55f8583938..90578eb62b 100644 --- a/panda/src/bullet/bulletBodyNode.h +++ b/panda/src/bullet/bulletBodyNode.h @@ -150,8 +150,8 @@ public: virtual bool safe_to_combine_children() const; virtual bool safe_to_flatten_below() const; - virtual void output(ostream &out) const; - virtual void do_output(ostream &out) const; + virtual void output(std::ostream &out) const; + virtual void do_output(std::ostream &out) const; protected: void set_collision_flag(int flag, bool value); diff --git a/panda/src/bullet/bulletCapsuleShape.cxx b/panda/src/bullet/bulletCapsuleShape.cxx index 44fbc3e501..ba9e02ab83 100644 --- a/panda/src/bullet/bulletCapsuleShape.cxx +++ b/panda/src/bullet/bulletCapsuleShape.cxx @@ -35,7 +35,7 @@ BulletCapsuleShape(PN_stdfloat radius, PN_stdfloat height, BulletUpAxis up) : _shape = new btCapsuleShapeZ(radius, height); break; default: - bullet_cat.error() << "invalid up-axis:" << up << endl; + bullet_cat.error() << "invalid up-axis:" << up << std::endl; break; } @@ -65,7 +65,7 @@ BulletCapsuleShape(const BulletCapsuleShape ©) { _shape = new btCapsuleShapeZ(_radius, _height); break; default: - bullet_cat.error() << "invalid up-axis:" << _up << endl; + bullet_cat.error() << "invalid up-axis:" << _up << std::endl; break; } @@ -82,6 +82,22 @@ ptr() const { return _shape; } + +/** + * Constructs a new BulletCapsuleShape using the information from a + * CollisionTube from the builtin collision system. + */ +BulletCapsuleShape *BulletCapsuleShape:: +make_from_solid(const CollisionTube *solid) { + + PN_stdfloat radius = solid->get_radius(); + // CollisionTube height includes the hemispheres, Bullet only wants the cylinder height. + PN_stdfloat height = (solid->get_point_b() - solid->get_point_a()).length() - (radius * 2); + + // CollisionTubes are always Z-Up. + return new BulletCapsuleShape(radius, height, Z_up); +} + /** * Tells the BamReader how to create objects of type BulletShape. */ @@ -150,7 +166,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { _shape = new btCapsuleShapeZ(_radius, _height); break; default: - bullet_cat.error() << "invalid up-axis:" << _up << endl; + bullet_cat.error() << "invalid up-axis:" << _up << std::endl; break; } diff --git a/panda/src/bullet/bulletCapsuleShape.h b/panda/src/bullet/bulletCapsuleShape.h index 9994d9f1dc..f8eecfe3d7 100644 --- a/panda/src/bullet/bulletCapsuleShape.h +++ b/panda/src/bullet/bulletCapsuleShape.h @@ -20,6 +20,8 @@ #include "bullet_utils.h" #include "bulletShape.h" +#include "collisionTube.h" + /** * */ @@ -33,6 +35,8 @@ PUBLISHED: BulletCapsuleShape(const BulletCapsuleShape ©); INLINE ~BulletCapsuleShape(); + static BulletCapsuleShape *make_from_solid(const CollisionTube *solid); + INLINE PN_stdfloat get_radius() const; INLINE PN_stdfloat get_half_height() const; diff --git a/panda/src/bullet/bulletCharacterControllerNode.cxx b/panda/src/bullet/bulletCharacterControllerNode.cxx index d65948a824..e9652de7e5 100644 --- a/panda/src/bullet/bulletCharacterControllerNode.cxx +++ b/panda/src/bullet/bulletCharacterControllerNode.cxx @@ -34,7 +34,7 @@ BulletCharacterControllerNode(BulletShape *shape, PN_stdfloat step_height, const // Get convex shape (for ghost object) if (!shape->is_convex()) { - bullet_cat.error() << "a convex shape is required!" << endl; + bullet_cat.error() << "a convex shape is required!" << std::endl; return; } diff --git a/panda/src/bullet/bulletClosestHitRayResult.cxx b/panda/src/bullet/bulletClosestHitRayResult.cxx index 2e831c9308..094d404a6e 100644 --- a/panda/src/bullet/bulletClosestHitRayResult.cxx +++ b/panda/src/bullet/bulletClosestHitRayResult.cxx @@ -78,7 +78,7 @@ PandaNode *BulletClosestHitRayResult:: get_node() const { const btCollisionObject *objectPtr = m_collisionObject; - return (objectPtr) ? (PandaNode *)objectPtr->getUserPointer() : NULL; + return (objectPtr) ? (PandaNode *)objectPtr->getUserPointer() : nullptr; } /** diff --git a/panda/src/bullet/bulletClosestHitSweepResult.cxx b/panda/src/bullet/bulletClosestHitSweepResult.cxx index f86bc0456a..0e3d08ffc4 100644 --- a/panda/src/bullet/bulletClosestHitSweepResult.cxx +++ b/panda/src/bullet/bulletClosestHitSweepResult.cxx @@ -60,7 +60,7 @@ PandaNode *BulletClosestHitSweepResult:: get_node() const { const btCollisionObject *objectPtr = m_hitCollisionObject; - return (objectPtr) ? (PandaNode *)objectPtr->getUserPointer() : NULL; + return (objectPtr) ? (PandaNode *)objectPtr->getUserPointer() : nullptr; } /** diff --git a/panda/src/bullet/bulletConeShape.cxx b/panda/src/bullet/bulletConeShape.cxx index 84c1fc4157..c4c554ba2f 100644 --- a/panda/src/bullet/bulletConeShape.cxx +++ b/panda/src/bullet/bulletConeShape.cxx @@ -35,7 +35,7 @@ BulletConeShape(PN_stdfloat radius, PN_stdfloat height, BulletUpAxis up) : _shape = new btConeShapeZ((btScalar)radius, (btScalar)height); break; default: - bullet_cat.error() << "invalid up-axis:" << up << endl; + bullet_cat.error() << "invalid up-axis:" << up << std::endl; break; } @@ -65,7 +65,7 @@ BulletConeShape(const BulletConeShape ©) { _shape = new btConeShapeZ((btScalar)_radius, (btScalar)_height); break; default: - bullet_cat.error() << "invalid up-axis:" << _up << endl; + bullet_cat.error() << "invalid up-axis:" << _up << std::endl; break; } @@ -150,7 +150,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { _shape = new btConeShapeZ((btScalar)_radius, (btScalar)_height); break; default: - bullet_cat.error() << "invalid up-axis:" << _up << endl; + bullet_cat.error() << "invalid up-axis:" << _up << std::endl; break; } diff --git a/panda/src/bullet/bulletContactCallbacks.h b/panda/src/bullet/bulletContactCallbacks.h index 27e8093e55..e9891fda8a 100644 --- a/panda/src/bullet/bulletContactCallbacks.h +++ b/panda/src/bullet/bulletContactCallbacks.h @@ -51,7 +51,7 @@ contact_added_callback(btManifoldPoint &cp, int id1, int index1) { - if (cp.m_userPersistentData == NULL) { + if (cp.m_userPersistentData == nullptr) { #if BT_BULLET_VERSION >= 281 PT(PandaNode) node0 = (PandaNode *)wrap0->getCollisionObject()->getUserPointer(); @@ -61,7 +61,7 @@ contact_added_callback(btManifoldPoint &cp, PT(PandaNode) node1 = (PandaNode *)obj1->getUserPointer(); #endif - bullet_cat.debug() << "contact added: " << cp.m_userPersistentData << endl; + bullet_cat.debug() << "contact added: " << cp.m_userPersistentData << std::endl; // Gather persistent data UserPersistentData *data = new UserPersistentData(); @@ -124,7 +124,7 @@ contact_processed_callback(btManifoldPoint &cp, static bool contact_destroyed_callback(void *userPersistentData) { - bullet_cat.debug() << "contact removed: " << userPersistentData << endl; + bullet_cat.debug() << "contact removed: " << userPersistentData << std::endl; UserPersistentData *data = (UserPersistentData *)userPersistentData; diff --git a/panda/src/bullet/bulletContactResult.cxx b/panda/src/bullet/bulletContactResult.cxx index 4d9e2588bd..ad4e5b8801 100644 --- a/panda/src/bullet/bulletContactResult.cxx +++ b/panda/src/bullet/bulletContactResult.cxx @@ -22,8 +22,8 @@ BulletContact BulletContactResult::_empty; BulletContact:: BulletContact() : _mp(_empty) { - _node0 = NULL; - _node1 = NULL; + _node0 = nullptr; + _node1 = nullptr; } /** @@ -47,8 +47,8 @@ BulletContactResult:: BulletContactResult() : btCollisionWorld::ContactResultCallback() { #if BT_BULLET_VERSION >= 281 - _filter_cb = NULL; - _filter_proxy = NULL; + _filter_cb = nullptr; + _filter_proxy = nullptr; _filter_set = false; #endif } @@ -96,8 +96,8 @@ addSingleResult(btManifoldPoint &mp, BulletContact contact; contact._mp = BulletManifoldPoint(mp); - contact._node0 = obj0 ? (PandaNode *)obj0->getUserPointer() : NULL; - contact._node1 = obj1 ? (PandaNode *)obj1->getUserPointer() : NULL; + contact._node0 = obj0 ? (PandaNode *)obj0->getUserPointer() : nullptr; + contact._node1 = obj1 ? (PandaNode *)obj1->getUserPointer() : nullptr; contact._part_id0 = part_id0; contact._part_id1 = part_id1; contact._idx0 = idx0; @@ -119,8 +119,8 @@ addSingleResult(btManifoldPoint &mp, BulletContact contact; contact._mp = BulletManifoldPoint(mp); - contact._node0 = obj0 ? (PandaNode *)obj0->getUserPointer() : NULL; - contact._node1 = obj1 ? (PandaNode *)obj1->getUserPointer() : NULL; + contact._node0 = obj0 ? (PandaNode *)obj0->getUserPointer() : nullptr; + contact._node1 = obj1 ? (PandaNode *)obj1->getUserPointer() : nullptr; contact._part_id0 = part_id0; contact._part_id1 = part_id1; contact._idx0 = idx0; diff --git a/panda/src/bullet/bulletConvexHullShape.cxx b/panda/src/bullet/bulletConvexHullShape.cxx index 07d559c2fd..487219c7fd 100644 --- a/panda/src/bullet/bulletConvexHullShape.cxx +++ b/panda/src/bullet/bulletConvexHullShape.cxx @@ -25,7 +25,7 @@ TypeHandle BulletConvexHullShape::_type_handle; BulletConvexHullShape:: BulletConvexHullShape() { - _shape = new btConvexHullShape(NULL, 0); + _shape = new btConvexHullShape(nullptr, 0); _shape->setUserPointer(this); } @@ -36,7 +36,7 @@ BulletConvexHullShape:: BulletConvexHullShape(const BulletConvexHullShape ©) { LightMutexHolder holder(BulletWorld::get_global_lock()); - _shape = new btConvexHullShape(NULL, 0); + _shape = new btConvexHullShape(nullptr, 0); _shape->setUserPointer(this); #if BT_BULLET_VERSION >= 282 @@ -80,7 +80,7 @@ add_array(const PTA_LVecBase3 &points) { if (_shape) delete _shape; - _shape = new btConvexHullShape(NULL, 0); + _shape = new btConvexHullShape(nullptr, 0); _shape->setUserPointer(this); PTA_LVecBase3::const_iterator it; @@ -123,20 +123,18 @@ add_geom(const Geom *geom, const TransformState *ts) { delete _shape; // Create shape - _shape = new btConvexHullShape(NULL, 0); + _shape = new btConvexHullShape(nullptr, 0); _shape->setUserPointer(this); pvector::const_iterator it; #if BT_BULLET_VERSION >= 282 for (it = points.begin(); it != points.end(); ++it) { - LVecBase3 v = *it; _shape->addPoint(LVecBase3_to_btVector3(*it), false); } _shape->recalcLocalAabb(); #else for (it = points.begin(); it != points.end(); ++it) { - LVecBase3 v = *it; _shape->addPoint(LVecBase3_to_btVector3(*it)); } #endif diff --git a/panda/src/bullet/bulletCylinderShape.cxx b/panda/src/bullet/bulletCylinderShape.cxx index 6d107bff7a..976daac96e 100644 --- a/panda/src/bullet/bulletCylinderShape.cxx +++ b/panda/src/bullet/bulletCylinderShape.cxx @@ -13,6 +13,8 @@ #include "bulletCylinderShape.h" +using std::endl; + TypeHandle BulletCylinderShape::_type_handle; /** diff --git a/panda/src/bullet/bulletDebugNode.cxx b/panda/src/bullet/bulletDebugNode.cxx index 743b5163ff..ce0c044758 100644 --- a/panda/src/bullet/bulletDebugNode.cxx +++ b/panda/src/bullet/bulletDebugNode.cxx @@ -256,12 +256,12 @@ add_for_draw(CullTraverser *trav, CullTraverserData &data) { trav->_geoms_pcollector.add_level(2); { CullableObject *object = - new CullableObject(move(debug_lines), RenderState::make_empty(), trav->get_scene()->get_cs_world_transform()); + new CullableObject(std::move(debug_lines), RenderState::make_empty(), trav->get_scene()->get_cs_world_transform()); trav->get_cull_handler()->record_object(object, trav); } { CullableObject *object = - new CullableObject(move(debug_triangles), RenderState::make_empty(), trav->get_scene()->get_cs_world_transform()); + new CullableObject(std::move(debug_triangles), RenderState::make_empty(), trav->get_scene()->get_cs_world_transform()); trav->get_cull_handler()->record_object(object, trav); } } @@ -300,7 +300,7 @@ getDebugMode() const { void BulletDebugNode::DebugDraw:: reportErrorWarning(const char *warning) { - bullet_cat.error() << warning << endl; + bullet_cat.error() << warning << std::endl; } /** @@ -381,7 +381,7 @@ drawTriangle(const btVector3 &v0, const btVector3 &v1, const btVector3 &v2, cons void BulletDebugNode::DebugDraw:: drawTriangle(const btVector3 &v0, const btVector3 &v1, const btVector3 &v2, const btVector3 &n0, const btVector3 &n1, const btVector3 &n2, const btVector3 &color, btScalar alpha) { - bullet_cat.debug() << "drawTriangle(2) - not yet implemented!" << endl; + bullet_cat.debug() << "drawTriangle(2) - not yet implemented!" << std::endl; } /** @@ -402,7 +402,7 @@ drawContactPoint(const btVector3 &point, const btVector3 &normal, btScalar dista void BulletDebugNode::DebugDraw:: draw3dText(const btVector3 &location, const char *text) { - bullet_cat.debug() << "draw3dText - not yet implemented!" << endl; + bullet_cat.debug() << "draw3dText - not yet implemented!" << std::endl; } /** diff --git a/panda/src/bullet/bulletGhostNode.cxx b/panda/src/bullet/bulletGhostNode.cxx index 14b693bda6..b4008820a1 100644 --- a/panda/src/bullet/bulletGhostNode.cxx +++ b/panda/src/bullet/bulletGhostNode.cxx @@ -97,8 +97,7 @@ do_transform_changed() { if (ts->has_scale()) { LVecBase3 scale = ts->get_scale(); if (!scale.almost_equal(LVecBase3(1.0f, 1.0f, 1.0f))) { - for (int i=0; i < _shapes.size(); i++) { - PT(BulletShape) shape = _shapes[i]; + for (BulletShape *shape : _shapes) { shape->do_set_local_scale(scale); } } @@ -133,10 +132,10 @@ PandaNode *BulletGhostNode:: get_overlapping_node(int idx) const { LightMutexHolder holder(BulletWorld::get_global_lock()); - nassertr(idx >=0 && idx < _ghost->getNumOverlappingObjects(), NULL); + nassertr(idx >=0 && idx < _ghost->getNumOverlappingObjects(), nullptr); btCollisionObject *object = _ghost->getOverlappingObject(idx); - return (object) ? (PandaNode *)object->getUserPointer() : NULL; + return (object) ? (PandaNode *)object->getUserPointer() : nullptr; } /** diff --git a/panda/src/bullet/bulletHeightfieldShape.cxx b/panda/src/bullet/bulletHeightfieldShape.cxx index 6f5f0529e3..15e8d6f75f 100644 --- a/panda/src/bullet/bulletHeightfieldShape.cxx +++ b/panda/src/bullet/bulletHeightfieldShape.cxx @@ -89,7 +89,7 @@ BulletHeightfieldShape(Texture *tex, PN_stdfloat max_height, BulletUpAxis up) : for (int row=0; row < _num_rows; row++) { for (int column=0; column < _num_cols; column++) { if (!peeker->lookup_bilinear(sample, row * step_x, column * step_y)) { - bullet_cat.error() << "Could not sample texture." << endl; + bullet_cat.error() << "Could not sample texture." << std::endl; } // Transpose _data[_num_rows * column + row] = max_height * sample.get_x(); diff --git a/panda/src/bullet/bulletHelper.I b/panda/src/bullet/bulletHelper.I index 51c4f4b830..85e168eb70 100644 --- a/panda/src/bullet/bulletHelper.I +++ b/panda/src/bullet/bulletHelper.I @@ -17,7 +17,7 @@ INLINE PT(InternalName) BulletHelper:: get_sb_index() { - if (_sb_index == (InternalName *)NULL) { + if (_sb_index == nullptr) { _sb_index = InternalName::make("sb_index"); } return _sb_index; @@ -29,7 +29,7 @@ get_sb_index() { INLINE PT(InternalName) BulletHelper:: get_sb_flip() { - if (_sb_flip == (InternalName *)NULL) { + if (_sb_flip == nullptr) { _sb_flip = InternalName::make("sb_flip"); } return _sb_flip; diff --git a/panda/src/bullet/bulletHelper.cxx b/panda/src/bullet/bulletHelper.cxx index a12a773740..e786e34d40 100644 --- a/panda/src/bullet/bulletHelper.cxx +++ b/panda/src/bullet/bulletHelper.cxx @@ -37,7 +37,7 @@ from_collision_solids(NodePath &np, bool clear) { NodePath cnp = npc.get_path(i); CollisionNode *cnode = DCAST(CollisionNode, cnp.node()); - PT(PandaNode) bnode = NULL; + PT(PandaNode) bnode = nullptr; // Create a either a new rigid body or a new ghost for each CollisionNode, // and add one shape per CollisionSolid contained in the CollisionNode @@ -83,7 +83,7 @@ from_collision_solids(NodePath &np, bool clear) { bool BulletHelper:: is_tangible(CollisionNode *cnode) { - for (int j=0; jget_num_solids(); j++) { + for (size_t j = 0; j < cnode->get_num_solids(); ++j) { CPT(CollisionSolid) solid = cnode->get_solid(j); if (solid->is_tangible()) { return true; @@ -179,8 +179,8 @@ make_geom(BulletSoftBodyNode *node, const GeomVertexFormat *format, bool two_sid CPT(GeomVertexFormat) fmt = (format) ? format : GeomVertexFormat::get_v3n3t2(); fmt = BulletHelper::add_sb_flip_column(fmt); - nassertr(fmt->has_column(InternalName::get_vertex()), NULL); - nassertr(fmt->has_column(InternalName::get_normal()), NULL); + nassertr(fmt->has_column(InternalName::get_vertex()), nullptr); + nassertr(fmt->has_column(InternalName::get_normal()), nullptr); btSoftBody::tNodeArray &nodes(body->m_nodes); diff --git a/panda/src/bullet/bulletHelper.h b/panda/src/bullet/bulletHelper.h index c63f70f111..f2195d4d92 100644 --- a/panda/src/bullet/bulletHelper.h +++ b/panda/src/bullet/bulletHelper.h @@ -43,11 +43,11 @@ PUBLISHED: // Geom utils static PT(Geom) make_geom_from_faces(BulletSoftBodyNode *node, - const GeomVertexFormat *format=NULL, + const GeomVertexFormat *format=nullptr, bool two_sided=false); static PT(Geom) make_geom_from_links(BulletSoftBodyNode *node, - const GeomVertexFormat *format=NULL); + const GeomVertexFormat *format=nullptr); static void make_texcoords_for_patch(Geom *geom, int resx, int resy); diff --git a/panda/src/bullet/bulletMultiSphereShape.cxx b/panda/src/bullet/bulletMultiSphereShape.cxx index ffaed8bafb..52d1edc42f 100644 --- a/panda/src/bullet/bulletMultiSphereShape.cxx +++ b/panda/src/bullet/bulletMultiSphereShape.cxx @@ -23,7 +23,7 @@ TypeHandle BulletMultiSphereShape::_type_handle; BulletMultiSphereShape:: BulletMultiSphereShape(const PTA_LVecBase3 &points, const PTA_stdfloat &radii) { - int num_spheres = min(points.size(), radii.size()); + int num_spheres = std::min(points.size(), radii.size()); // Convert points btVector3 *bt_points = new btVector3[num_spheres]; diff --git a/panda/src/bullet/bulletPersistentManifold.cxx b/panda/src/bullet/bulletPersistentManifold.cxx index e42ea3c6f8..67d760e8df 100644 --- a/panda/src/bullet/bulletPersistentManifold.cxx +++ b/panda/src/bullet/bulletPersistentManifold.cxx @@ -65,7 +65,7 @@ get_node0() { const btCollisionObject *obj = (btCollisionObject *)_manifold->getBody0(); #endif - return (obj) ? (PandaNode *)obj->getUserPointer(): NULL; + return (obj) ? (PandaNode *)obj->getUserPointer(): nullptr; } /** @@ -81,7 +81,7 @@ get_node1() { const btCollisionObject *obj = (btCollisionObject *)_manifold->getBody1(); #endif - return (obj) ? (PandaNode *)obj->getUserPointer(): NULL; + return (obj) ? (PandaNode *)obj->getUserPointer(): nullptr; } /** @@ -101,7 +101,7 @@ BulletManifoldPoint *BulletPersistentManifold:: get_manifold_point(int idx) const { LightMutexHolder holder(BulletWorld::get_global_lock()); - nassertr(idx < _manifold->getNumContacts(), NULL) + nassertr(idx < _manifold->getNumContacts(), nullptr) return new BulletManifoldPoint(_manifold->getContactPoint(idx)); } diff --git a/panda/src/bullet/bulletPlaneShape.cxx b/panda/src/bullet/bulletPlaneShape.cxx index 0d1a97fd4e..98dce53577 100644 --- a/panda/src/bullet/bulletPlaneShape.cxx +++ b/panda/src/bullet/bulletPlaneShape.cxx @@ -15,6 +15,18 @@ TypeHandle BulletPlaneShape::_type_handle; +/** + * Creates a plane shape from a plane definition. + */ +BulletPlaneShape:: +BulletPlaneShape(LPlane plane) { + + btVector3 btNormal = LVecBase3_to_btVector3(plane.get_normal()); + + _shape = new btStaticPlaneShape(btNormal, plane.get_w()); + _shape->setUserPointer(this); +} + /** * */ @@ -50,6 +62,17 @@ ptr() const { return _shape; } +/** + * + */ +LPlane BulletPlaneShape:: +get_plane() const { + LightMutexHolder holder(BulletWorld::get_global_lock()); + + btVector3 normal = _shape->getPlaneNormal(); + return LPlane(normal[0], normal[1], normal[2], (PN_stdfloat)_shape->getPlaneConstant()); +} + /** * */ diff --git a/panda/src/bullet/bulletPlaneShape.h b/panda/src/bullet/bulletPlaneShape.h index dfee91f12c..4521007ecb 100644 --- a/panda/src/bullet/bulletPlaneShape.h +++ b/panda/src/bullet/bulletPlaneShape.h @@ -29,18 +29,21 @@ class EXPCL_PANDABULLET BulletPlaneShape : public BulletShape { private: // Only used by make_from_bam - INLINE BulletPlaneShape() : _shape(NULL) {}; + INLINE BulletPlaneShape() : _shape(nullptr) {}; PUBLISHED: + explicit BulletPlaneShape(LPlane plane); explicit BulletPlaneShape(const LVector3 &normal, PN_stdfloat constant); BulletPlaneShape(const BulletPlaneShape ©); INLINE ~BulletPlaneShape(); + LPlane get_plane() const; LVector3 get_plane_normal() const; PN_stdfloat get_plane_constant() const; static BulletPlaneShape *make_from_solid(const CollisionPlane *solid); + MAKE_PROPERTY(plane, get_plane); MAKE_PROPERTY(plane_normal, get_plane_normal); MAKE_PROPERTY(plane_constant, get_plane_constant); diff --git a/panda/src/bullet/bulletRigidBodyNode.cxx b/panda/src/bullet/bulletRigidBodyNode.cxx index ab8c4327f9..b0d36f705e 100644 --- a/panda/src/bullet/bulletRigidBodyNode.cxx +++ b/panda/src/bullet/bulletRigidBodyNode.cxx @@ -74,7 +74,7 @@ make_copy() const { * */ void BulletRigidBodyNode:: -output(ostream &out) const { +output(std::ostream &out) const { LightMutexHolder holder(BulletWorld::get_global_lock()); BulletBodyNode::do_output(out); diff --git a/panda/src/bullet/bulletRigidBodyNode.h b/panda/src/bullet/bulletRigidBodyNode.h index 641fdc9fd9..d0e11da6cf 100644 --- a/panda/src/bullet/bulletRigidBodyNode.h +++ b/panda/src/bullet/bulletRigidBodyNode.h @@ -106,7 +106,7 @@ PUBLISHED: public: virtual btCollisionObject *get_object() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; void do_sync_p2b(); void do_sync_b2p(); diff --git a/panda/src/bullet/bulletSoftBodyNode.cxx b/panda/src/bullet/bulletSoftBodyNode.cxx index c4094af652..cf027f208d 100644 --- a/panda/src/bullet/bulletSoftBodyNode.cxx +++ b/panda/src/bullet/bulletSoftBodyNode.cxx @@ -41,15 +41,15 @@ BulletSoftBodyNode(btSoftBody *body, const char *name) : BulletBodyNode(name) { // Shape btCollisionShape *shape_ptr = _soft->getCollisionShape(); - nassertv(shape_ptr != NULL); + nassertv(shape_ptr != nullptr); nassertv(shape_ptr->getShapeType() == SOFTBODY_SHAPE_PROXYTYPE); _shapes.push_back(new BulletSoftBodyShape((btSoftBodyCollisionShape *)shape_ptr)); // Rendering - _geom = NULL; - _curve = NULL; - _surface = NULL; + _geom = nullptr; + _curve = nullptr; + _surface = nullptr; } /** @@ -134,7 +134,7 @@ BulletSoftBodyNodeElement BulletSoftBodyNode:: get_node(int idx) const { LightMutexHolder holder(BulletWorld::get_global_lock()); - nassertr(idx >=0 && idx < get_num_nodes(), BulletSoftBodyNodeElement::empty()); + nassertr(idx >= 0 && idx < _soft->m_nodes.size(), BulletSoftBodyNodeElement::empty()); return BulletSoftBodyNodeElement(_soft->m_nodes[idx]); } @@ -207,7 +207,7 @@ transform_changed() { _soft->scale(new_scale); } - _sync = move(ts); + _sync = std::move(ts); } } @@ -276,8 +276,15 @@ do_sync_b2p() { // Update the synchronized transform with the current approximate center of // the soft body - LVecBase3 pos = this->do_get_aabb().get_approx_center(); - CPT(TransformState) ts = TransformState::make_pos(pos); + btVector3 pMin, pMax; + _soft->getAabb(pMin, pMax); + LPoint3 pos = (btVector3_to_LPoint3(pMin) + btVector3_to_LPoint3(pMax)) * 0.5; + CPT(TransformState) ts; + if (!pos.is_nan()) { + ts = TransformState::make_pos(pos); + } else { + ts = TransformState::make_identity(); + } NodePath np = NodePath::any_path((PandaNode *)this); LVecBase3 scale = np.get_net_transform()->get_scale(); @@ -385,7 +392,7 @@ void BulletSoftBodyNode:: unlink_geom() { LightMutexHolder holder(BulletWorld::get_global_lock()); - _geom = NULL; + _geom = nullptr; } /** @@ -407,7 +414,7 @@ void BulletSoftBodyNode:: unlink_curve() { LightMutexHolder holder(BulletWorld::get_global_lock()); - _curve = NULL; + _curve = nullptr; } /** @@ -429,7 +436,7 @@ void BulletSoftBodyNode:: unlink_surface() { LightMutexHolder holder(BulletWorld::get_global_lock()); - _surface = NULL; + _surface = nullptr; } /** @@ -851,7 +858,7 @@ make_tri_mesh(BulletSoftBodyWorldInfo &info, PTA_LVecBase3 points, PTA_int indic num_triangles, randomizeConstraints); - nassertr(body, NULL); + nassertr(body, nullptr); delete[] vertices; delete[] triangles; @@ -873,7 +880,7 @@ make_tri_mesh(BulletSoftBodyWorldInfo &info, const Geom *geom, bool randomizeCon CPT(GeomVertexData) vdata = geom->get_vertex_data(); - nassertr(vdata->has_column(InternalName::get_vertex()), NULL); + nassertr(vdata->has_column(InternalName::get_vertex()), nullptr); GeomVertexReader vreader(vdata, InternalName::get_vertex()); @@ -883,7 +890,7 @@ make_tri_mesh(BulletSoftBodyWorldInfo &info, const Geom *geom, bool randomizeCon } // Read indices - for (int i=0; iget_num_primitives(); i++) { + for (size_t i = 0; i < geom->get_num_primitives(); ++i) { CPT(GeomPrimitive) prim = geom->get_primitive(i); prim = prim->decompose(); @@ -953,7 +960,7 @@ make_tet_mesh(BulletSoftBodyWorldInfo &info, PTA_LVecBase3 points, PTA_int indic PT(BulletSoftBodyNode) BulletSoftBodyNode:: make_tet_mesh(BulletSoftBodyWorldInfo &info, const char *ele, const char *face, const char *node) { - nassertr(node && node[0], NULL); + nassertr(node && node[0], nullptr); // Nodes btAlignedObjectArray pos; diff --git a/panda/src/bullet/bulletSoftBodyNode.h b/panda/src/bullet/bulletSoftBodyNode.h index 600e185fac..26d7cc6fce 100644 --- a/panda/src/bullet/bulletSoftBodyNode.h +++ b/panda/src/bullet/bulletSoftBodyNode.h @@ -78,7 +78,7 @@ PUBLISHED: BulletSoftBodyConfig get_cfg(); BulletSoftBodyWorldInfo get_world_info(); - void generate_bending_constraints(int distance, BulletSoftBodyMaterial *material=NULL); + void generate_bending_constraints(int distance, BulletSoftBodyMaterial *material=nullptr); void randomize_constraints(); // Mass, volume, density @@ -146,7 +146,7 @@ PUBLISHED: PN_stdfloat erp=1.0, PN_stdfloat cfm=1.0, PN_stdfloat split=1.0, - BulletSoftBodyControl *control=NULL); + BulletSoftBodyControl *control=nullptr); // Materials int get_num_materials() const; diff --git a/panda/src/bullet/bulletSoftBodyShape.cxx b/panda/src/bullet/bulletSoftBodyShape.cxx index 9e6aa2929b..c6df128687 100644 --- a/panda/src/bullet/bulletSoftBodyShape.cxx +++ b/panda/src/bullet/bulletSoftBodyShape.cxx @@ -47,6 +47,6 @@ get_body() const { } else { - return NULL; + return nullptr; } } diff --git a/panda/src/bullet/bulletSphereShape.h b/panda/src/bullet/bulletSphereShape.h index aad49a145c..e0634d50c2 100644 --- a/panda/src/bullet/bulletSphereShape.h +++ b/panda/src/bullet/bulletSphereShape.h @@ -28,7 +28,7 @@ class EXPCL_PANDABULLET BulletSphereShape : public BulletShape { private: // Only used by make_from_bam - INLINE BulletSphereShape() : _shape(NULL) {}; + INLINE BulletSphereShape() : _shape(nullptr) {}; PUBLISHED: explicit BulletSphereShape(PN_stdfloat radius); diff --git a/panda/src/bullet/bulletTriangleMesh.I b/panda/src/bullet/bulletTriangleMesh.I index 33b9b9bf47..acce8e7cfc 100644 --- a/panda/src/bullet/bulletTriangleMesh.I +++ b/panda/src/bullet/bulletTriangleMesh.I @@ -22,8 +22,8 @@ ptr() const { /** * */ -INLINE ostream & -operator << (ostream &out, const BulletTriangleMesh &obj) { +INLINE std::ostream & +operator << (std::ostream &out, const BulletTriangleMesh &obj) { obj.output(out); return out; } diff --git a/panda/src/bullet/bulletTriangleMesh.cxx b/panda/src/bullet/bulletTriangleMesh.cxx index e2d3e0b242..368aa22fac 100644 --- a/panda/src/bullet/bulletTriangleMesh.cxx +++ b/panda/src/bullet/bulletTriangleMesh.cxx @@ -17,6 +17,8 @@ #include "geomVertexData.h" #include "geomVertexReader.h" +using std::endl; + TypeHandle BulletTriangleMesh::_type_handle; /** @@ -53,7 +55,7 @@ LPoint3 BulletTriangleMesh:: get_vertex(size_t index) const { LightMutexHolder holder(BulletWorld::get_global_lock()); - nassertr(index < _vertices.size(), LPoint3::zero()); + nassertr(index < (size_t)_vertices.size(), LPoint3::zero()); const btVector3 &vertex = _vertices[index]; return LPoint3(vertex[0], vertex[1], vertex[2]); } @@ -66,7 +68,7 @@ get_triangle(size_t index) const { LightMutexHolder holder(BulletWorld::get_global_lock()); index *= 3; - nassertr(index + 2 < _indices.size(), LVecBase3i::zero()); + nassertr(index + 2 < (size_t)_indices.size(), LVecBase3i::zero()); return LVecBase3i(_indices[index], _indices[index + 1], _indices[index + 2]); } @@ -226,7 +228,7 @@ add_geom(const Geom *geom, bool remove_duplicate_vertices, const TransformState } } - for (int k = 0; k < geom->get_num_primitives(); ++k) { + for (size_t k = 0; k < geom->get_num_primitives(); ++k) { CPT(GeomPrimitive) prim = geom->get_primitive(k); prim = prim->decompose(); @@ -237,7 +239,7 @@ add_geom(const Geom *geom, bool remove_duplicate_vertices, const TransformState CPT(GeomVertexArrayData) vertices = prim->get_vertices(); if (vertices != nullptr) { - GeomVertexReader index(move(vertices), 0); + GeomVertexReader index(std::move(vertices), 0); while (!index.is_at_end()) { _indices.push_back(index_offset + index.get_data1i()); } @@ -269,7 +271,7 @@ add_geom(const Geom *geom, bool remove_duplicate_vertices, const TransformState } // Add triangles - for (int k = 0; k < geom->get_num_primitives(); ++k) { + for (size_t k = 0; k < geom->get_num_primitives(); ++k) { CPT(GeomPrimitive) prim = geom->get_primitive(k); prim = prim->decompose(); @@ -280,7 +282,7 @@ add_geom(const Geom *geom, bool remove_duplicate_vertices, const TransformState CPT(GeomVertexArrayData) vertices = prim->get_vertices(); if (vertices != nullptr) { - GeomVertexReader index(move(vertices), 0); + GeomVertexReader index(std::move(vertices), 0); while (!index.is_at_end()) { _indices.push_back(find_or_add_vertex(points[index.get_data1i()])); } @@ -351,7 +353,7 @@ add_array(const PTA_LVecBase3 &points, const PTA_int &indices, bool remove_dupli * */ void BulletTriangleMesh:: -output(ostream &out) const { +output(std::ostream &out) const { LightMutexHolder holder(BulletWorld::get_global_lock()); out << get_type() << ", " << _indices.size() / 3 << " triangles"; @@ -361,11 +363,11 @@ output(ostream &out) const { * */ void BulletTriangleMesh:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type() << ":" << endl; const IndexedMeshArray &array = _mesh.getIndexedMeshArray(); - for (size_t i = 0; i < array.size(); ++i) { + for (int i = 0; i < array.size(); ++i) { indent(out, indent_level + 2) << "IndexedMesh " << i << ":" << endl; const btIndexedMesh &mesh = array[0]; indent(out, indent_level + 4) << "num triangles:" << mesh.m_numTriangles << endl; @@ -423,7 +425,7 @@ write_datagram(BamWriter *manager, Datagram &dg) { // Add the vertices. const unsigned char *vptr = mesh.m_vertexBase; - nassertv(vptr != NULL || mesh.m_numVertices == 0); + nassertv(vptr != nullptr || mesh.m_numVertices == 0); for (int i = 0; i < mesh.m_numVertices; ++i) { const btVector3 &vertex = *((btVector3 *)vptr); @@ -435,7 +437,7 @@ write_datagram(BamWriter *manager, Datagram &dg) { // Now add the triangle indices. const unsigned char *iptr = mesh.m_triangleIndexBase; - nassertv(iptr != NULL || mesh.m_numTriangles == 0); + nassertv(iptr != nullptr || mesh.m_numTriangles == 0); for (int i = 0; i < mesh.m_numTriangles; ++i) { int *triangle = (int *)iptr; diff --git a/panda/src/bullet/bulletTriangleMesh.h b/panda/src/bullet/bulletTriangleMesh.h index 0f9cb8174b..e3ce0805ad 100644 --- a/panda/src/bullet/bulletTriangleMesh.h +++ b/panda/src/bullet/bulletTriangleMesh.h @@ -32,7 +32,7 @@ class EXPCL_PANDABULLET BulletTriangleMesh : public TypedWritableReferenceCount { PUBLISHED: BulletTriangleMesh(); - ~BulletTriangleMesh() DEFAULT_DTOR; + ~BulletTriangleMesh() = default; void add_triangle(const LPoint3 &p0, const LPoint3 &p1, @@ -51,8 +51,8 @@ PUBLISHED: size_t get_num_triangles() const; PN_stdfloat get_welding_distance() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; public: size_t get_num_vertices() const; @@ -112,7 +112,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const BulletTriangleMesh &obj); +INLINE std::ostream &operator << (std::ostream &out, const BulletTriangleMesh &obj); #include "bulletTriangleMesh.I" diff --git a/panda/src/bullet/bulletTriangleMeshShape.I b/panda/src/bullet/bulletTriangleMeshShape.I index f178723ebc..f1263cbed6 100644 --- a/panda/src/bullet/bulletTriangleMeshShape.I +++ b/panda/src/bullet/bulletTriangleMeshShape.I @@ -32,7 +32,7 @@ INLINE BulletTriangleMeshShape:: INLINE bool BulletTriangleMeshShape:: is_static() const { - return (_bvh_shape != NULL); + return (_bvh_shape != nullptr); } /** @@ -41,5 +41,5 @@ is_static() const { INLINE bool BulletTriangleMeshShape:: is_dynamic() const { - return (_gimpact_shape != NULL); + return (_gimpact_shape != nullptr); } diff --git a/panda/src/bullet/bulletTriangleMeshShape.cxx b/panda/src/bullet/bulletTriangleMeshShape.cxx index ced374a3fc..8416c52cbc 100644 --- a/panda/src/bullet/bulletTriangleMeshShape.cxx +++ b/panda/src/bullet/bulletTriangleMeshShape.cxx @@ -25,9 +25,9 @@ TypeHandle BulletTriangleMeshShape::_type_handle; */ BulletTriangleMeshShape:: BulletTriangleMeshShape() : - _mesh(NULL), - _gimpact_shape(NULL), - _bvh_shape(NULL), + _mesh(nullptr), + _gimpact_shape(nullptr), + _bvh_shape(nullptr), _dynamic(false), _compress(false), _bvh(false) { @@ -46,13 +46,13 @@ BulletTriangleMeshShape(BulletTriangleMesh *mesh, bool dynamic, bool compress, b // Assert that mesh is not NULL if (!mesh) { - bullet_cat.warning() << "mesh is NULL! creating new mesh." << endl; + bullet_cat.warning() << "mesh is NULL! creating new mesh." << std::endl; mesh = new BulletTriangleMesh(); } // Assert that mesh has at least one triangle if (mesh->do_get_num_triangles() == 0) { - bullet_cat.warning() << "mesh has zero triangles! adding degenerated triangle." << endl; + bullet_cat.warning() << "mesh has zero triangles! adding degenerated triangle." << std::endl; mesh->add_triangle(LPoint3::zero(), LPoint3::zero(), LPoint3::zero()); } @@ -66,7 +66,7 @@ BulletTriangleMeshShape(BulletTriangleMesh *mesh, bool dynamic, bool compress, b _gimpact_shape->updateBound(); _gimpact_shape->setUserPointer(this); - _bvh_shape = NULL; + _bvh_shape = nullptr; } // Static will create a Bvh mesh shape @@ -75,7 +75,7 @@ BulletTriangleMeshShape(BulletTriangleMesh *mesh, bool dynamic, bool compress, b _bvh_shape = new btBvhTriangleMeshShape(mesh->ptr(), compress, bvh); _bvh_shape->setUserPointer(this); - _gimpact_shape = NULL; + _gimpact_shape = nullptr; } } @@ -95,11 +95,11 @@ BulletTriangleMeshShape(const BulletTriangleMeshShape ©) { _gimpact_shape = new btGImpactMeshShape(_mesh->ptr()); _gimpact_shape->updateBound(); _gimpact_shape->setUserPointer(this); - _bvh_shape = NULL; + _bvh_shape = nullptr; } else { _bvh_shape = new btBvhTriangleMeshShape(_mesh->ptr(), _compress, _bvh); _bvh_shape->setUserPointer(this); - _gimpact_shape = NULL; + _gimpact_shape = nullptr; } } @@ -117,7 +117,7 @@ ptr() const { return _gimpact_shape; } - return NULL; + return nullptr; } /** @@ -174,7 +174,7 @@ complete_pointers(TypedWritable **p_list, BamReader *manager) { _mesh = DCAST(BulletTriangleMesh, p_list[pi++]); btStridingMeshInterface *mesh_ptr = _mesh->ptr(); - nassertr(mesh_ptr != NULL, pi); + nassertr(mesh_ptr != nullptr, pi); if (_dynamic) { _gimpact_shape = new btGImpactMeshShape(mesh_ptr); diff --git a/panda/src/bullet/bulletVehicle.cxx b/panda/src/bullet/bulletVehicle.cxx index e2d74c131d..5dbb70cc7f 100644 --- a/panda/src/bullet/bulletVehicle.cxx +++ b/panda/src/bullet/bulletVehicle.cxx @@ -52,7 +52,7 @@ set_coordinate_system(BulletUpAxis up) { _vehicle->setCoordinateSystem(0, 2, 1); break; default: - bullet_cat.error() << "invalid up axis:" << up << endl; + bullet_cat.error() << "invalid up axis:" << up << std::endl; break; } } @@ -76,7 +76,7 @@ BulletRigidBodyNode *BulletVehicle:: do_get_chassis() { btRigidBody *bodyPtr = _vehicle->getRigidBody(); - return (bodyPtr) ? (BulletRigidBodyNode *)bodyPtr->getUserPointer() : NULL; + return (bodyPtr) ? (BulletRigidBodyNode *)bodyPtr->getUserPointer() : nullptr; } /** @@ -180,7 +180,7 @@ create_wheel() { btWheelInfo &info = _vehicle->addWheel(pos, direction, axle, suspension, radius, _tuning._, false); - info.m_clientInfo = NULL; + info.m_clientInfo = nullptr; return BulletWheel(info); } @@ -232,6 +232,9 @@ void BulletVehicle:: do_sync_b2p() { for (int i=0; i < _vehicle->getNumWheels(); i++) { + // synchronize the wheels with the (interpolated) chassis worldtransform + _vehicle->updateWheelTransform(i, true); + btWheelInfo info = _vehicle->getWheelInfo(i); PandaNode *node = (PandaNode *)info.m_clientInfo; diff --git a/panda/src/bullet/bulletWheel.I b/panda/src/bullet/bulletWheel.I index cbf82a40bc..0523ba9727 100644 --- a/panda/src/bullet/bulletWheel.I +++ b/panda/src/bullet/bulletWheel.I @@ -34,7 +34,7 @@ INLINE BulletWheelRaycastInfo:: INLINE BulletWheel BulletWheel:: empty() { - btWheelInfoConstructionInfo ci; + btWheelInfoConstructionInfo ci {}; btWheelInfo info(ci); return BulletWheel(info); diff --git a/panda/src/bullet/bulletWheel.cxx b/panda/src/bullet/bulletWheel.cxx index 149dbd8bf5..c24369546b 100644 --- a/panda/src/bullet/bulletWheel.cxx +++ b/panda/src/bullet/bulletWheel.cxx @@ -517,7 +517,7 @@ PandaNode *BulletWheel:: get_node() const { LightMutexHolder holder(BulletWorld::get_global_lock()); - return (_info.m_clientInfo == NULL) ? NULL : (PandaNode *)_info.m_clientInfo; + return (_info.m_clientInfo == nullptr) ? nullptr : (PandaNode *)_info.m_clientInfo; } /** @@ -597,5 +597,5 @@ PandaNode *BulletWheelRaycastInfo:: get_ground_object() const { LightMutexHolder holder(BulletWorld::get_global_lock()); - return _info.m_groundObject ? (PandaNode *)_info.m_groundObject : NULL; + return _info.m_groundObject ? (PandaNode *)_info.m_groundObject : nullptr; } diff --git a/panda/src/bullet/bulletWorld.I b/panda/src/bullet/bulletWorld.I index 61893a1531..d79534c865 100644 --- a/panda/src/bullet/bulletWorld.I +++ b/panda/src/bullet/bulletWorld.I @@ -65,7 +65,7 @@ get_debug_node() const { INLINE bool BulletWorld:: has_debug_node() const { - return _debug != NULL; + return _debug != nullptr; } /** diff --git a/panda/src/bullet/bulletWorld.cxx b/panda/src/bullet/bulletWorld.cxx index 6098759581..e1e416a2bb 100644 --- a/panda/src/bullet/bulletWorld.cxx +++ b/panda/src/bullet/bulletWorld.cxx @@ -19,7 +19,12 @@ #include "collideMask.h" #include "lightMutexHolder.h" -#define clamp(x, x_min, x_max) max(min(x, x_max), x_min) +#define clamp(x, x_min, x_max) std::max(std::min(x, x_max), x_min) + +using std::endl; +using std::istream; +using std::ostream; +using std::string; TypeHandle BulletWorld::_type_handle; @@ -37,7 +42,7 @@ BulletWorld:: BulletWorld() { // Init groups filter matrix - for (int i=0; i<32; i++) { + for (size_t i = 0; i < 32; ++i) { _filter_cb2._collide[i].clear(); _filter_cb2._collide[i].set_bit(i); } @@ -95,13 +100,13 @@ BulletWorld() { break; default: bullet_cat.error() << "no proper filter algorithm!" << endl; - _filter_cb = NULL; + _filter_cb = nullptr; } _world->getPairCache()->setOverlapFilterCallback(_filter_cb); // Tick callback - _tick_callback_obj = NULL; + _tick_callback_obj = nullptr; // SoftBodyWorldInfo _info.m_dispatcher = _dispatcher; @@ -248,20 +253,20 @@ do_physics(PN_stdfloat dt, int max_substeps, PN_stdfloat stepsize) { void BulletWorld:: do_sync_p2b(PN_stdfloat dt, int num_substeps) { - for (int i=0; i < _bodies.size(); i++) { - _bodies[i]->do_sync_p2b(); + for (BulletRigidBodyNode *body : _bodies) { + body->do_sync_p2b(); } - for (int i=0; i < _softbodies.size(); i++) { - _softbodies[i]->do_sync_p2b(); + for (BulletSoftBodyNode *softbody : _softbodies) { + softbody->do_sync_p2b(); } - for (int i=0; i < _ghosts.size(); i++) { - _ghosts[i]->do_sync_p2b(); + for (BulletGhostNode *ghost : _ghosts) { + ghost->do_sync_p2b(); } - for (int i=0; i < _characters.size(); i++) { - _characters[i]->do_sync_p2b(dt, num_substeps); + for (BulletBaseCharacterControllerNode *character : _characters) { + character->do_sync_p2b(dt, num_substeps); } } @@ -271,24 +276,24 @@ do_sync_p2b(PN_stdfloat dt, int num_substeps) { void BulletWorld:: do_sync_b2p() { - for (int i=0; i < _vehicles.size(); i++) { - _vehicles[i]->do_sync_b2p(); + for (BulletRigidBodyNode *body : _bodies) { + body->do_sync_b2p(); } - for (int i=0; i < _bodies.size(); i++) { - _bodies[i]->do_sync_b2p(); + for (BulletSoftBodyNode *softbody : _softbodies) { + softbody->do_sync_b2p(); } - for (int i=0; i < _softbodies.size(); i++) { - _softbodies[i]->do_sync_b2p(); + for (BulletGhostNode *ghost : _ghosts) { + ghost->do_sync_b2p(); } - for (int i=0; i < _ghosts.size(); i++) { - _ghosts[i]->do_sync_b2p(); + for (BulletBaseCharacterControllerNode *character : _characters) { + character->do_sync_b2p(); } - for (int i=0; i < _characters.size(); i++) { - _characters[i]->do_sync_b2p(); + for (BulletVehicle *vehicle : _vehicles) { + vehicle->do_sync_b2p(); } } @@ -786,7 +791,7 @@ BulletRigidBodyNode *BulletWorld:: get_rigid_body(int idx) const { LightMutexHolder holder(get_global_lock()); - nassertr(idx >= 0 && idx < (int)_bodies.size(), NULL); + nassertr(idx >= 0 && idx < (int)_bodies.size(), nullptr); return _bodies[idx]; } @@ -807,7 +812,7 @@ BulletSoftBodyNode *BulletWorld:: get_soft_body(int idx) const { LightMutexHolder holder(get_global_lock()); - nassertr(idx >= 0 && idx < (int)_softbodies.size(), NULL); + nassertr(idx >= 0 && idx < (int)_softbodies.size(), nullptr); return _softbodies[idx]; } @@ -828,7 +833,7 @@ BulletGhostNode *BulletWorld:: get_ghost(int idx) const { LightMutexHolder holder(get_global_lock()); - nassertr(idx >= 0 && idx < (int)_ghosts.size(), NULL); + nassertr(idx >= 0 && idx < (int)_ghosts.size(), nullptr); return _ghosts[idx]; } @@ -849,7 +854,7 @@ BulletBaseCharacterControllerNode *BulletWorld:: get_character(int idx) const { LightMutexHolder holder(get_global_lock()); - nassertr(idx >= 0 && idx < (int)_characters.size(), NULL); + nassertr(idx >= 0 && idx < (int)_characters.size(), nullptr); return _characters[idx]; } @@ -870,7 +875,7 @@ BulletVehicle *BulletWorld:: get_vehicle(int idx) const { LightMutexHolder holder(get_global_lock()); - nassertr(idx >= 0 && idx < (int)_vehicles.size(), NULL); + nassertr(idx >= 0 && idx < (int)_vehicles.size(), nullptr); return _vehicles[idx]; } @@ -891,7 +896,7 @@ BulletConstraint *BulletWorld:: get_constraint(int idx) const { LightMutexHolder holder(get_global_lock()); - nassertr(idx >= 0 && idx < (int)_constraints.size(), NULL); + nassertr(idx >= 0 && idx < (int)_constraints.size(), nullptr); return _constraints[idx]; } @@ -942,7 +947,9 @@ ray_test_all(const LPoint3 &from_pos, const LPoint3 &to_pos, const CollideMask & } /** - * + * Performs a sweep test against all other shapes that match the given group + * mask. The provided shape must be a convex shape; it is an error to invoke + * this method using a non-convex shape. */ BulletClosestHitSweepResult BulletWorld:: sweep_test_closest(BulletShape *shape, const TransformState &from_ts, const TransformState &to_ts, const CollideMask &mask, PN_stdfloat penetration) const { @@ -1052,10 +1059,10 @@ BulletPersistentManifold *BulletWorld:: get_manifold(int idx) const { LightMutexHolder holder(get_global_lock()); - nassertr(idx < _dispatcher->getNumManifolds(), NULL); + nassertr(idx < _dispatcher->getNumManifolds(), nullptr); btPersistentManifold *ptr = _dispatcher->getManifoldByIndexInternal(idx); - return (ptr) ? new BulletPersistentManifold(ptr) : NULL; + return (ptr) ? new BulletPersistentManifold(ptr) : nullptr; } /** @@ -1077,7 +1084,7 @@ get_collision_object(PandaNode *node) { return ((BulletSoftBodyNode *)node)->get_object(); } - return NULL; + return nullptr; } /** @@ -1148,7 +1155,7 @@ clear_contact_added_callback() { _world->getSolverInfo().m_solverMode &= ~SOLVER_USE_2_FRICTION_DIRECTIONS; _world->getSolverInfo().m_solverMode &= ~SOLVER_ENABLE_FRICTION_DIRECTION_CACHING; - bullet_contact_added_callback = NULL; + bullet_contact_added_callback = nullptr; } /** @@ -1158,7 +1165,7 @@ void BulletWorld:: set_tick_callback(CallbackObject *obj, bool is_pretick) { LightMutexHolder holder(get_global_lock()); - nassertv(obj != NULL); + nassertv(obj != nullptr); _tick_callback_obj = obj; _world->setInternalTickCallback(&BulletWorld::tick_callback, this, is_pretick); } @@ -1170,8 +1177,8 @@ void BulletWorld:: clear_tick_callback() { LightMutexHolder holder(get_global_lock()); - _tick_callback_obj = NULL; - _world->setInternalTickCallback(NULL); + _tick_callback_obj = nullptr; + _world->setInternalTickCallback(nullptr); } /** @@ -1202,7 +1209,7 @@ void BulletWorld:: set_filter_callback(CallbackObject *obj) { LightMutexHolder holder(get_global_lock()); - nassertv(obj != NULL); + nassertv(obj != nullptr); if (_filter_algorithm != FA_callback) { bullet_cat.warning() << "filter algorithm is not 'callback'" << endl; @@ -1218,7 +1225,7 @@ void BulletWorld:: clear_filter_callback() { LightMutexHolder holder(get_global_lock()); - _filter_cb3._filter_callback_obj = NULL; + _filter_cb3._filter_callback_obj = nullptr; } /** @@ -1268,7 +1275,7 @@ needBroadphaseCollision(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1) co // cout << mask0 << " " << mask1 << endl; - for (int i=0; i<32; i++) { + for (size_t i = 0; i < 32; ++i) { if (mask0.get_bit(i)) { if ((_collide[i] & mask1) != 0) // cout << "collide: i=" << i << " _collide[i]" << _collide[i] << endl; diff --git a/panda/src/bullet/bulletWorld.h b/panda/src/bullet/bulletWorld.h index 35a2c8c634..9c709c1e91 100644 --- a/panda/src/bullet/bulletWorld.h +++ b/panda/src/bullet/bulletWorld.h @@ -305,15 +305,15 @@ private: static TypeHandle _type_handle; }; -EXPCL_PANDABULLET ostream & -operator << (ostream &out, BulletWorld::BroadphaseAlgorithm algorithm); -EXPCL_PANDABULLET istream & -operator >> (istream &in, BulletWorld::BroadphaseAlgorithm &algorithm); +EXPCL_PANDABULLET std::ostream & +operator << (std::ostream &out, BulletWorld::BroadphaseAlgorithm algorithm); +EXPCL_PANDABULLET std::istream & +operator >> (std::istream &in, BulletWorld::BroadphaseAlgorithm &algorithm); -EXPCL_PANDABULLET ostream & -operator << (ostream &out, BulletWorld::FilterAlgorithm algorithm); -EXPCL_PANDABULLET istream & -operator >> (istream &in, BulletWorld::FilterAlgorithm &algorithm); +EXPCL_PANDABULLET std::ostream & +operator << (std::ostream &out, BulletWorld::FilterAlgorithm algorithm); +EXPCL_PANDABULLET std::istream & +operator >> (std::istream &in, BulletWorld::FilterAlgorithm &algorithm); #include "bulletWorld.I" diff --git a/panda/src/bullet/config_bullet.cxx b/panda/src/bullet/config_bullet.cxx index 4e228427b9..5997bf575b 100644 --- a/panda/src/bullet/config_bullet.cxx +++ b/panda/src/bullet/config_bullet.cxx @@ -207,7 +207,7 @@ init_libbullet() { // Initialize notification category bullet_cat.init(); - bullet_cat.debug() << "initialize module" << endl; + bullet_cat.debug() << "initialize module" << std::endl; // Register the Bullet system PandaSystem *ps = PandaSystem::get_global_ptr(); diff --git a/panda/src/chan/animBundle.I b/panda/src/chan/animBundle.I index 2859273786..c52608f852 100644 --- a/panda/src/chan/animBundle.I +++ b/panda/src/chan/animBundle.I @@ -15,7 +15,7 @@ * */ INLINE AnimBundle:: -AnimBundle(const string &name, PN_stdfloat fps, int num_frames) : AnimGroup(name) { +AnimBundle(const std::string &name, PN_stdfloat fps, int num_frames) : AnimGroup(name) { _fps = fps; _num_frames = num_frames; _root = this; diff --git a/panda/src/chan/animBundle.cxx b/panda/src/chan/animBundle.cxx index ad67124966..8313516485 100644 --- a/panda/src/chan/animBundle.cxx +++ b/panda/src/chan/animBundle.cxx @@ -32,7 +32,7 @@ AnimBundle(AnimGroup *parent, const AnimBundle ©) : _fps(copy._fps), _num_frames(copy._num_frames) { - nassertv(_root == (AnimBundle *)NULL); + nassertv(_root == nullptr); _root = this; } @@ -43,7 +43,7 @@ AnimBundle(AnimGroup *parent, const AnimBundle ©) : */ PT(AnimBundle) AnimBundle:: copy_bundle() const { - PT(AnimGroup) group = copy_subtree((AnimGroup *)NULL); + PT(AnimGroup) group = copy_subtree(nullptr); return DCAST(AnimBundle, group.p()); } @@ -51,7 +51,7 @@ copy_bundle() const { * Writes a one-line description of the bundle. */ void AnimBundle:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << " " << get_name() << ", " << get_num_frames() << " frames at " << get_base_frame_rate() << " fps"; } diff --git a/panda/src/chan/animBundle.h b/panda/src/chan/animBundle.h index 799d262ab8..659f15e58c 100644 --- a/panda/src/chan/animBundle.h +++ b/panda/src/chan/animBundle.h @@ -31,14 +31,14 @@ protected: AnimBundle(AnimGroup *parent, const AnimBundle ©); PUBLISHED: - INLINE explicit AnimBundle(const string &name, PN_stdfloat fps, int num_frames); + INLINE explicit AnimBundle(const std::string &name, PN_stdfloat fps, int num_frames); PT(AnimBundle) copy_bundle() const; INLINE double get_base_frame_rate() const; INLINE int get_num_frames() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: INLINE AnimBundle(); @@ -77,7 +77,7 @@ private: static TypeHandle _type_handle; }; -inline ostream &operator <<(ostream &out, const AnimBundle &bundle) { +inline std::ostream &operator <<(std::ostream &out, const AnimBundle &bundle) { bundle.output(out); return out; } diff --git a/panda/src/chan/animBundleNode.I b/panda/src/chan/animBundleNode.I index b7ac18c818..ced5541dbe 100644 --- a/panda/src/chan/animBundleNode.I +++ b/panda/src/chan/animBundleNode.I @@ -17,7 +17,7 @@ * the appropriate type, and pass it up to this constructor. */ INLINE AnimBundleNode:: -AnimBundleNode(const string &name, AnimBundle *bundle) : +AnimBundleNode(const std::string &name, AnimBundle *bundle) : PandaNode(name), _bundle(bundle) { diff --git a/panda/src/chan/animBundleNode.cxx b/panda/src/chan/animBundleNode.cxx index b3e49ca6a7..f6fab7a110 100644 --- a/panda/src/chan/animBundleNode.cxx +++ b/panda/src/chan/animBundleNode.cxx @@ -46,12 +46,12 @@ safe_to_flatten() const { */ AnimBundle *AnimBundleNode:: find_anim_bundle(PandaNode *root) { - nassertr(root != (PandaNode *)NULL, NULL); + nassertr(root != nullptr, nullptr); if (root->is_of_type(AnimBundleNode::get_class_type())) { AnimBundleNode *anode = DCAST(AnimBundleNode, root); AnimBundle *anim = anode->get_bundle(); - if (anim != (AnimBundle *)NULL) { + if (anim != nullptr) { return anim; } } @@ -60,12 +60,12 @@ find_anim_bundle(PandaNode *root) { int num_children = cr.get_num_children(); for (int i = 0; i < num_children; i++) { AnimBundle *anim = find_anim_bundle(cr.get_child(i)); - if (anim != (AnimBundle *)NULL) { + if (anim != nullptr) { return anim; } } - return NULL; + return nullptr; } /** diff --git a/panda/src/chan/animBundleNode.h b/panda/src/chan/animBundleNode.h index 38df110191..fbf9dcbbe2 100644 --- a/panda/src/chan/animBundleNode.h +++ b/panda/src/chan/animBundleNode.h @@ -28,7 +28,7 @@ */ class EXPCL_PANDA_CHAN AnimBundleNode : public PandaNode { PUBLISHED: - INLINE explicit AnimBundleNode(const string &name, AnimBundle *bundle); + INLINE explicit AnimBundleNode(const std::string &name, AnimBundle *bundle); protected: INLINE AnimBundleNode(); diff --git a/panda/src/chan/animChannel.I b/panda/src/chan/animChannel.I index 6dd73d5240..921536f0b3 100644 --- a/panda/src/chan/animChannel.I +++ b/panda/src/chan/animChannel.I @@ -26,7 +26,7 @@ TypeHandle AnimChannel::_type_handle; */ template INLINE AnimChannel:: -AnimChannel(const string &name) +AnimChannel(const std::string &name) : AnimChannelBase(name) { } @@ -48,7 +48,7 @@ AnimChannel(AnimGroup *parent, const AnimChannel ©) : */ template INLINE AnimChannel:: -AnimChannel(AnimGroup *parent, const string &name) +AnimChannel(AnimGroup *parent, const std::string &name) : AnimChannelBase(parent, name) { } @@ -60,21 +60,6 @@ INLINE AnimChannel:: ~AnimChannel() { } -#if defined(WIN32_VC) || defined(WIN64_VC) -/** - * Gets the value of the channel at the indicated frame. This is a pure - * virtual function and normally would not need a function body, except that - * VC++ seems to be unhappy about instantiating the template without it. - * - * However, GCC seems to get confused when it *is* defined. So this whole - * thing is protected within an ifdef. - */ -template -void AnimChannel:: -get_value(int, TYPENAME AnimChannel::ValueType &) { -} -#endif - /** * Returns the value associated with the current frame, with no scale or share * components. This only makes sense for a matrix-type channel, although for diff --git a/panda/src/chan/animChannel.cxx b/panda/src/chan/animChannel.cxx index dfaf152b7b..d34d364068 100644 --- a/panda/src/chan/animChannel.cxx +++ b/panda/src/chan/animChannel.cxx @@ -22,7 +22,7 @@ template class AnimChannel; * Outputs a very brief description of a matrix. */ void ACMatrixSwitchType:: -output_value(ostream &out, const ACMatrixSwitchType::ValueType &value) { +output_value(std::ostream &out, const ACMatrixSwitchType::ValueType &value) { LVecBase3 scale, shear, hpr, translate; if (decompose_matrix(value, scale, shear, hpr, translate)) { if (!scale.almost_equal(LVecBase3(1.0f, 1.0f, 1.0f))) { diff --git a/panda/src/chan/animChannel.h b/panda/src/chan/animChannel.h index 4137196f52..eb024ea31e 100644 --- a/panda/src/chan/animChannel.h +++ b/panda/src/chan/animChannel.h @@ -30,12 +30,12 @@ protected: // The default constructor is protected: don't try to create an AnimChannel // without a parent. To create an AnimChannel hierarchy, you must first // create an AnimBundle, and use that to create any subsequent children. - INLINE AnimChannel(const string &name = ""); + INLINE AnimChannel(const std::string &name = ""); INLINE AnimChannel(AnimGroup *parent, const AnimChannel ©); public: - typedef TYPENAME SwitchType::ValueType ValueType; + typedef typename SwitchType::ValueType ValueType; - INLINE AnimChannel(AnimGroup *parent, const string &name); + INLINE AnimChannel(AnimGroup *parent, const std::string &name); INLINE ~AnimChannel(); PUBLISHED: @@ -81,7 +81,7 @@ public: static const char *get_channel_type_name() { return "AnimChannelMatrix"; } static const char *get_fixed_channel_type_name() { return "AnimChannelFixed"; } static const char *get_part_type_name() { return "MovingPart"; } - static void output_value(ostream &out, const ValueType &value); + static void output_value(std::ostream &out, const ValueType &value); static void write_datagram(Datagram &dest, ValueType& me) { @@ -103,7 +103,7 @@ public: static const char *get_channel_type_name() { return "AnimChannelScalar"; } static const char *get_fixed_channel_type_name() { return "AnimChannelScalarFixed"; } static const char *get_part_type_name() { return "MovingPart"; } - static void output_value(ostream &out, ValueType value) { + static void output_value(std::ostream &out, ValueType value) { out << value; } static void write_datagram(Datagram &dest, ValueType& me) diff --git a/panda/src/chan/animChannelBase.I b/panda/src/chan/animChannelBase.I index dbe24dcc9d..0e86c51027 100644 --- a/panda/src/chan/animChannelBase.I +++ b/panda/src/chan/animChannelBase.I @@ -17,7 +17,7 @@ * created as part of a hierarchy. */ INLINE AnimChannelBase:: -AnimChannelBase(const string &name) +AnimChannelBase(const std::string &name) : AnimGroup(name) { _last_frame = -1; @@ -40,7 +40,7 @@ AnimChannelBase(AnimGroup *parent, const AnimChannelBase ©) : * in the previously-created hierarchy. */ INLINE AnimChannelBase:: -AnimChannelBase(AnimGroup *parent, const string &name) +AnimChannelBase(AnimGroup *parent, const std::string &name) : AnimGroup(parent, name) { _last_frame = -1; diff --git a/panda/src/chan/animChannelBase.h b/panda/src/chan/animChannelBase.h index c3512db282..71493de31d 100644 --- a/panda/src/chan/animChannelBase.h +++ b/panda/src/chan/animChannelBase.h @@ -32,11 +32,11 @@ protected: // The default constructor is protected: don't try to create an AnimChannel // without a parent. To create an AnimChannel hierarchy, you must first // create an AnimBundle, and use that to create any subsequent children. - INLINE AnimChannelBase(const string &name = ""); + INLINE AnimChannelBase(const std::string &name = ""); INLINE AnimChannelBase(AnimGroup *parent, const AnimChannelBase ©); public: - INLINE AnimChannelBase(AnimGroup *parent, const string &name); + INLINE AnimChannelBase(AnimGroup *parent, const std::string &name); virtual bool has_changed(int last_frame, double last_frac, int this_frame, double this_frac); diff --git a/panda/src/chan/animChannelFixed.I b/panda/src/chan/animChannelFixed.I index 9c71438b86..c430366945 100644 --- a/panda/src/chan/animChannelFixed.I +++ b/panda/src/chan/animChannelFixed.I @@ -32,7 +32,7 @@ AnimChannelFixed(AnimGroup *parent, const AnimChannelFixed ©) : */ template INLINE AnimChannelFixed:: -AnimChannelFixed(const string &name, const ValueType &value) +AnimChannelFixed(const std::string &name, const ValueType &value) : AnimChannel(name), _value(value) { } @@ -63,7 +63,7 @@ get_value(int, ValueType &value) { */ template void AnimChannelFixed:: -output(ostream &out) const { +output(std::ostream &out) const { AnimChannel::output(out); out << " = " << _value; } diff --git a/panda/src/chan/animChannelFixed.h b/panda/src/chan/animChannelFixed.h index 9940f5bdcf..a2317d257b 100644 --- a/panda/src/chan/animChannelFixed.h +++ b/panda/src/chan/animChannelFixed.h @@ -28,19 +28,19 @@ template class AnimChannelFixed : public AnimChannel { public: - typedef TYPENAME AnimChannel::ValueType ValueType; + typedef typename AnimChannel::ValueType ValueType; protected: INLINE AnimChannelFixed(AnimGroup *parent, const AnimChannelFixed ©); public: - INLINE AnimChannelFixed(const string &name, const ValueType &value); + INLINE AnimChannelFixed(const std::string &name, const ValueType &value); virtual bool has_changed(int last_frame, double last_frac, int this_frame, double this_frac); virtual void get_value(int frame, ValueType &value); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; ValueType _value; diff --git a/panda/src/chan/animChannelMatrixDynamic.cxx b/panda/src/chan/animChannelMatrixDynamic.cxx index fb60451bc3..53b2771685 100644 --- a/panda/src/chan/animChannelMatrixDynamic.cxx +++ b/panda/src/chan/animChannelMatrixDynamic.cxx @@ -41,7 +41,7 @@ AnimChannelMatrixDynamic(AnimGroup *parent, const AnimChannelMatrixDynamic © AnimChannelMatrix(parent, copy), _value_node(copy._value_node), _value(copy._value), - _last_value(NULL) + _last_value(nullptr) { } @@ -49,11 +49,11 @@ AnimChannelMatrixDynamic(AnimGroup *parent, const AnimChannelMatrixDynamic © * */ AnimChannelMatrixDynamic:: -AnimChannelMatrixDynamic(const string &name) +AnimChannelMatrixDynamic(const std::string &name) : AnimChannelMatrix(name) { _value = TransformState::make_identity(); - _last_value = NULL; // This is impossible; thus, has_changed() will + _last_value = nullptr; // This is impossible; thus, has_changed() will // always return true the first time. } @@ -64,7 +64,7 @@ AnimChannelMatrixDynamic(const string &name) */ bool AnimChannelMatrixDynamic:: has_changed(int, double, int, double) { - if (_value_node != (PandaNode *)NULL) { + if (_value_node != nullptr) { _value = _value_node->get_transform(); } bool has_changed = (_value != _last_value); @@ -77,7 +77,7 @@ has_changed(int, double, int, double) { */ void AnimChannelMatrixDynamic:: get_value(int, LMatrix4 &mat) { - if (_value_node != (PandaNode *)NULL) { + if (_value_node != nullptr) { _value = _value_node->get_transform(); } mat = _value->get_mat(); @@ -89,7 +89,7 @@ get_value(int, LMatrix4 &mat) { */ void AnimChannelMatrixDynamic:: get_value_no_scale_shear(int, LMatrix4 &mat) { - if (_value_node != (PandaNode *)NULL) { + if (_value_node != nullptr) { _value = _value_node->get_transform(); } if (_value->has_scale() || _value->has_shear()) { @@ -105,7 +105,7 @@ get_value_no_scale_shear(int, LMatrix4 &mat) { */ void AnimChannelMatrixDynamic:: get_scale(int, LVecBase3 &scale) { - if (_value_node != (PandaNode *)NULL) { + if (_value_node != nullptr) { _value = _value_node->get_transform(); } scale = _value->get_scale(); @@ -117,7 +117,7 @@ get_scale(int, LVecBase3 &scale) { */ void AnimChannelMatrixDynamic:: get_hpr(int, LVecBase3 &hpr) { - if (_value_node != (PandaNode *)NULL) { + if (_value_node != nullptr) { _value = _value_node->get_transform(); } hpr = _value->get_hpr(); @@ -130,7 +130,7 @@ get_hpr(int, LVecBase3 &hpr) { */ void AnimChannelMatrixDynamic:: get_quat(int, LQuaternion &quat) { - if (_value_node != (PandaNode *)NULL) { + if (_value_node != nullptr) { _value = _value_node->get_transform(); } quat = _value->get_quat(); @@ -142,7 +142,7 @@ get_quat(int, LQuaternion &quat) { */ void AnimChannelMatrixDynamic:: get_pos(int, LVecBase3 &pos) { - if (_value_node != (PandaNode *)NULL) { + if (_value_node != nullptr) { _value = _value_node->get_transform(); } pos = _value->get_pos(); @@ -154,7 +154,7 @@ get_pos(int, LVecBase3 &pos) { */ void AnimChannelMatrixDynamic:: get_shear(int, LVecBase3 &shear) { - if (_value_node != (PandaNode *)NULL) { + if (_value_node != nullptr) { _value = _value_node->get_transform(); } shear = _value->get_shear(); @@ -186,7 +186,7 @@ set_value(const TransformState *value) { void AnimChannelMatrixDynamic:: set_value_node(PandaNode *value_node) { _value_node = value_node; - if (_value_node != (PandaNode *)NULL) { + if (_value_node != nullptr) { _value = _value_node->get_transform(); } } diff --git a/panda/src/chan/animChannelMatrixDynamic.h b/panda/src/chan/animChannelMatrixDynamic.h index 8cd9d38904..589b2e7a10 100644 --- a/panda/src/chan/animChannelMatrixDynamic.h +++ b/panda/src/chan/animChannelMatrixDynamic.h @@ -36,7 +36,7 @@ protected: AnimChannelMatrixDynamic(AnimGroup *parent, const AnimChannelMatrixDynamic ©); public: - AnimChannelMatrixDynamic(const string &name); + AnimChannelMatrixDynamic(const std::string &name); virtual bool has_changed(int last_frame, double last_frac, int this_frame, double this_frac); diff --git a/panda/src/chan/animChannelMatrixFixed.cxx b/panda/src/chan/animChannelMatrixFixed.cxx index cf79e7ea5a..d5f0ef3d84 100644 --- a/panda/src/chan/animChannelMatrixFixed.cxx +++ b/panda/src/chan/animChannelMatrixFixed.cxx @@ -34,7 +34,7 @@ AnimChannelMatrixFixed(AnimGroup *parent, const AnimChannelMatrixFixed ©) : * */ AnimChannelMatrixFixed:: -AnimChannelMatrixFixed(const string &name, const LVecBase3 &pos, const LVecBase3 &hpr, const LVecBase3 &scale) : +AnimChannelMatrixFixed(const std::string &name, const LVecBase3 &pos, const LVecBase3 &hpr, const LVecBase3 &scale) : AnimChannel(name), _pos(pos), _hpr(hpr), _scale(scale) { @@ -116,7 +116,7 @@ get_shear(int, LVecBase3 &shear) { * */ void AnimChannelMatrixFixed:: -output(ostream &out) const { +output(std::ostream &out) const { AnimChannel::output(out); out << ": pos " << _pos << " hpr " << _hpr << " scale " << _scale; } diff --git a/panda/src/chan/animChannelMatrixFixed.h b/panda/src/chan/animChannelMatrixFixed.h index eb34c78321..8b6e06c8ab 100644 --- a/panda/src/chan/animChannelMatrixFixed.h +++ b/panda/src/chan/animChannelMatrixFixed.h @@ -28,7 +28,7 @@ protected: AnimChannelMatrixFixed(AnimGroup *parent, const AnimChannelMatrixFixed ©); public: - AnimChannelMatrixFixed(const string &name, const LVecBase3 &pos, const LVecBase3 &hpr, const LVecBase3 &scale); + AnimChannelMatrixFixed(const std::string &name, const LVecBase3 &pos, const LVecBase3 &hpr, const LVecBase3 &scale); virtual bool has_changed(int last_frame, double last_frac, int this_frame, double this_frac); @@ -40,7 +40,7 @@ public: virtual void get_pos(int frame, LVecBase3 &pos); virtual void get_shear(int frame, LVecBase3 &shear); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: LVecBase3 _pos, _hpr, _scale; diff --git a/panda/src/chan/animChannelMatrixXfmTable.I b/panda/src/chan/animChannelMatrixXfmTable.I index 93fceb143c..e86bc56658 100644 --- a/panda/src/chan/animChannelMatrixXfmTable.I +++ b/panda/src/chan/animChannelMatrixXfmTable.I @@ -41,7 +41,7 @@ has_table(char table_id) const { if (table_index < 0) { return false; } - return !(_tables[table_index] == (const PN_stdfloat *)NULL); + return !(_tables[table_index] == nullptr); } /** @@ -51,7 +51,7 @@ INLINE void AnimChannelMatrixXfmTable:: clear_table(char table_id) { int table_index = get_table_index(table_id); if (table_index >= 0) { - _tables[table_index] = NULL; + _tables[table_index] = nullptr; } } diff --git a/panda/src/chan/animChannelMatrixXfmTable.cxx b/panda/src/chan/animChannelMatrixXfmTable.cxx index 6c404d06fe..c6c27b8b7a 100644 --- a/panda/src/chan/animChannelMatrixXfmTable.cxx +++ b/panda/src/chan/animChannelMatrixXfmTable.cxx @@ -54,7 +54,7 @@ AnimChannelMatrixXfmTable(AnimGroup *parent, const AnimChannelMatrixXfmTable &co * */ AnimChannelMatrixXfmTable:: -AnimChannelMatrixXfmTable(AnimGroup *parent, const string &name) +AnimChannelMatrixXfmTable(AnimGroup *parent, const std::string &name) : AnimChannelMatrix(parent, name) { for (int i = 0; i < num_matrix_components; i++) { @@ -267,7 +267,7 @@ clear_all_tables() { * Writes a brief description of the table and all of its descendants. */ void AnimChannelMatrixXfmTable:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type() << " " << get_name() << " "; @@ -369,7 +369,7 @@ write_datagram(BamWriter *manager, Datagram &me) { // Now, write out the joint angles. For these we need to build up a HPR // array. pvector hprs; - int hprs_length = max(max(_tables[6].size(), _tables[7].size()), _tables[8].size()); + int hprs_length = std::max(std::max(_tables[6].size(), _tables[7].size()), _tables[8].size()); hprs.reserve(hprs_length); for (i = 0; i < hprs_length; i++) { PN_stdfloat h = _tables[6].empty() ? 0.0f : _tables[6][i % _tables[6].size()]; @@ -377,7 +377,7 @@ write_datagram(BamWriter *manager, Datagram &me) { PN_stdfloat r = _tables[8].empty() ? 0.0f : _tables[8][i % _tables[8].size()]; hprs.push_back(LVecBase3(h, p, r)); } - const LVecBase3 *hprs_array = NULL; + const LVecBase3 *hprs_array = nullptr; if (hprs_length != 0) { hprs_array = &hprs[0]; } @@ -419,7 +419,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { if (!new_hpr) { // Convert between the old HPR form and the new HPR form. - size_t num_hprs = max(max(_tables[6].size(), _tables[7].size()), + size_t num_hprs = std::max(std::max(_tables[6].size(), _tables[7].size()), _tables[8].size()); LVecBase3 default_hpr(0.0, 0.0, 0.0); diff --git a/panda/src/chan/animChannelMatrixXfmTable.h b/panda/src/chan/animChannelMatrixXfmTable.h index e3a81a7b2a..a5923e59c0 100644 --- a/panda/src/chan/animChannelMatrixXfmTable.h +++ b/panda/src/chan/animChannelMatrixXfmTable.h @@ -34,7 +34,7 @@ protected: AnimChannelMatrixXfmTable(AnimGroup *parent, const AnimChannelMatrixXfmTable ©); PUBLISHED: - explicit AnimChannelMatrixXfmTable(AnimGroup *parent, const string &name); + explicit AnimChannelMatrixXfmTable(AnimGroup *parent, const std::string &name); virtual ~AnimChannelMatrixXfmTable(); public: @@ -60,7 +60,7 @@ PUBLISHED: INLINE void clear_table(char table_id); public: - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; protected: virtual AnimGroup *make_copy(AnimGroup *parent) const; diff --git a/panda/src/chan/animChannelScalarDynamic.cxx b/panda/src/chan/animChannelScalarDynamic.cxx index ead0d539a6..8a9835a550 100644 --- a/panda/src/chan/animChannelScalarDynamic.cxx +++ b/panda/src/chan/animChannelScalarDynamic.cxx @@ -41,7 +41,7 @@ AnimChannelScalarDynamic(AnimGroup *parent, const AnimChannelScalarDynamic © AnimChannelScalar(parent, copy), _value_node(copy._value_node), _value(copy._value), - _last_value(NULL), + _last_value(nullptr), _value_changed(true), _float_value(copy._float_value) { @@ -51,7 +51,7 @@ AnimChannelScalarDynamic(AnimGroup *parent, const AnimChannelScalarDynamic © * */ AnimChannelScalarDynamic:: -AnimChannelScalarDynamic(const string &name) +AnimChannelScalarDynamic(const std::string &name) : AnimChannelScalar(name) { _last_value = _value = TransformState::make_identity(); @@ -66,7 +66,7 @@ AnimChannelScalarDynamic(const string &name) */ bool AnimChannelScalarDynamic:: has_changed(int, double, int, double) { - if (_value_node != (PandaNode *)NULL) { + if (_value_node != nullptr) { _value = _value_node->get_transform(); bool has_changed = (_value != _last_value); _last_value = _value; @@ -84,7 +84,7 @@ has_changed(int, double, int, double) { */ void AnimChannelScalarDynamic:: get_value(int, PN_stdfloat &value) { - if (_value_node != (PandaNode *)NULL) { + if (_value_node != nullptr) { value = _value->get_pos()[0]; } else { @@ -108,13 +108,13 @@ set_value(PN_stdfloat value) { */ void AnimChannelScalarDynamic:: set_value_node(PandaNode *value_node) { - if (_value_node == (PandaNode *)NULL) { + if (_value_node == nullptr) { _last_value = TransformState::make_pos(LVecBase3(_float_value, 0.0f, 0.0f)); } _value_node = value_node; - if (_value_node != (PandaNode *)NULL) { + if (_value_node != nullptr) { _value = _value_node->get_transform(); } } diff --git a/panda/src/chan/animChannelScalarDynamic.h b/panda/src/chan/animChannelScalarDynamic.h index 72828d968d..ab009a4f1f 100644 --- a/panda/src/chan/animChannelScalarDynamic.h +++ b/panda/src/chan/animChannelScalarDynamic.h @@ -36,7 +36,7 @@ protected: AnimChannelScalarDynamic(AnimGroup *parent, const AnimChannelScalarDynamic ©); public: - AnimChannelScalarDynamic(const string &name); + AnimChannelScalarDynamic(const std::string &name); virtual bool has_changed(int last_frame, double last_frac, int this_frame, double this_frac); diff --git a/panda/src/chan/animChannelScalarTable.I b/panda/src/chan/animChannelScalarTable.I index 1a41648490..b9dda3154c 100644 --- a/panda/src/chan/animChannelScalarTable.I +++ b/panda/src/chan/animChannelScalarTable.I @@ -25,7 +25,7 @@ get_table() const { */ INLINE bool AnimChannelScalarTable:: has_table() const { - return _table != (const PN_stdfloat *)NULL; + return _table != nullptr; } @@ -34,5 +34,5 @@ has_table() const { */ INLINE void AnimChannelScalarTable:: clear_table() { - _table = NULL; + _table = nullptr; } diff --git a/panda/src/chan/animChannelScalarTable.cxx b/panda/src/chan/animChannelScalarTable.cxx index 195258b9c7..54953164e7 100644 --- a/panda/src/chan/animChannelScalarTable.cxx +++ b/panda/src/chan/animChannelScalarTable.cxx @@ -47,7 +47,7 @@ AnimChannelScalarTable(AnimGroup *parent, const AnimChannelScalarTable ©) : * */ AnimChannelScalarTable:: -AnimChannelScalarTable(AnimGroup *parent, const string &name) : +AnimChannelScalarTable(AnimGroup *parent, const std::string &name) : AnimChannelScalar(parent, name), _table(get_class_type()) { @@ -115,7 +115,7 @@ set_table(const CPTA_stdfloat &table) { * Writes a brief description of the table and all of its descendants. */ void AnimChannelScalarTable:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type() << " " << get_name() << " " << _table.size(); diff --git a/panda/src/chan/animChannelScalarTable.h b/panda/src/chan/animChannelScalarTable.h index 2d706b9e7c..e150d8d82e 100644 --- a/panda/src/chan/animChannelScalarTable.h +++ b/panda/src/chan/animChannelScalarTable.h @@ -31,7 +31,7 @@ protected: AnimChannelScalarTable(AnimGroup *parent, const AnimChannelScalarTable ©); public: - AnimChannelScalarTable(AnimGroup *parent, const string &name); + AnimChannelScalarTable(AnimGroup *parent, const std::string &name); virtual bool has_changed(int last_frame, double last_frac, int this_frame, double this_frac); @@ -45,7 +45,7 @@ PUBLISHED: INLINE void clear_table(); public: - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; protected: virtual AnimGroup *make_copy(AnimGroup *parent) const; diff --git a/panda/src/chan/animControl.I b/panda/src/chan/animControl.I index 3b79891fc4..dd85c9cdea 100644 --- a/panda/src/chan/animControl.I +++ b/panda/src/chan/animControl.I @@ -28,7 +28,7 @@ is_pending() const { */ INLINE bool AnimControl:: has_anim() const { - return (_anim != (AnimBundle *)NULL); + return (_anim != nullptr); } /** @@ -88,8 +88,8 @@ get_anim_model() const { return _anim_model; } -INLINE ostream & -operator << (ostream &out, const AnimControl &control) { +INLINE std::ostream & +operator << (std::ostream &out, const AnimControl &control) { control.output(out); return out; } diff --git a/panda/src/chan/animControl.cxx b/panda/src/chan/animControl.cxx index 35e56374f7..aa47ea7486 100644 --- a/panda/src/chan/animControl.cxx +++ b/panda/src/chan/animControl.cxx @@ -27,7 +27,7 @@ TypeHandle AnimControl::_type_handle; * being loaded during an asynchronous load-and-bind operation. */ AnimControl:: -AnimControl(const string &name, PartBundle *part, +AnimControl(const std::string &name, PartBundle *part, double frame_rate, int num_frames) : Namable(name), _pending_lock(name), @@ -40,7 +40,7 @@ AnimControl(const string &name, PartBundle *part, _pending = true; _part = part; - _anim = NULL; + _anim = nullptr; _channel_index = -1; set_frame_rate(frame_rate); set_num_frames(num_frames); @@ -57,7 +57,7 @@ setup_anim(PartBundle *part, AnimBundle *anim, int channel_index, const BitArray &bound_joints) { MutexHolder holder(_pending_lock); nassertv(_pending && part == _part); - nassertv(_anim == (AnimBundle *)NULL); + nassertv(_anim == nullptr); _anim = anim; _channel_index = channel_index; _bound_joints = bound_joints; @@ -131,7 +131,7 @@ wait_pending() { * binding, the event will be thrown immediately. */ void AnimControl:: -set_pending_done_event(const string &done_event) { +set_pending_done_event(const std::string &done_event) { MutexHolder holder(_pending_lock); _pending_done_event = done_event; if (!_pending) { @@ -143,7 +143,7 @@ set_pending_done_event(const string &done_event) { * Returns the event name that will be thrown when the AnimControl is finished * binding asynchronously. */ -string AnimControl:: +std::string AnimControl:: get_pending_done_event() const { MutexHolder holder(_pending_lock); return _pending_done_event; @@ -161,7 +161,7 @@ get_part() const { * */ void AnimControl:: -output(ostream &out) const { +output(std::ostream &out) const { out << "AnimControl(" << get_name() << ", " << get_part()->get_name() << ": "; AnimInterface::output(out); diff --git a/panda/src/chan/animControl.h b/panda/src/chan/animControl.h index 09b5e203a1..bee9f7223b 100644 --- a/panda/src/chan/animControl.h +++ b/panda/src/chan/animControl.h @@ -37,7 +37,7 @@ class AnimChannelBase; */ class EXPCL_PANDA_CHAN AnimControl : public TypedReferenceCount, public AnimInterface, public Namable { public: - AnimControl(const string &name, PartBundle *part, + AnimControl(const std::string &name, PartBundle *part, double frame_rate, int num_frames); void setup_anim(PartBundle *part, AnimBundle *anim, int channel_index, const BitArray &bound_joints); @@ -50,8 +50,8 @@ PUBLISHED: INLINE bool is_pending() const; void wait_pending(); INLINE bool has_anim() const; - void set_pending_done_event(const string &done_event); - string get_pending_done_event() const; + void set_pending_done_event(const std::string &done_event); + std::string get_pending_done_event() const; PartBundle *get_part() const; INLINE AnimBundle *get_anim() const; @@ -61,7 +61,7 @@ PUBLISHED: INLINE void set_anim_model(PandaNode *model); INLINE PandaNode *get_anim_model() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; public: // The following functions aren't really part of the public interface; @@ -75,7 +75,7 @@ protected: private: bool _pending; - string _pending_done_event; + std::string _pending_done_event; Mutex _pending_lock; // protects the above two. ConditionVarFull _pending_cvar; // signals when _pending goes true. @@ -118,7 +118,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const AnimControl &control); +INLINE std::ostream &operator << (std::ostream &out, const AnimControl &control); #include "animControl.I" diff --git a/panda/src/chan/animControlCollection.I b/panda/src/chan/animControlCollection.I index fd4b7251b1..d103140992 100644 --- a/panda/src/chan/animControlCollection.I +++ b/panda/src/chan/animControlCollection.I @@ -15,9 +15,9 @@ * Starts the named animation playing. */ INLINE bool AnimControlCollection:: -play(const string &anim_name) { +play(const std::string &anim_name) { AnimControl *control = find_anim(anim_name); - if (control == (AnimControl *)NULL) { + if (control == nullptr) { return false; } _last_started_control = control; @@ -29,9 +29,9 @@ play(const string &anim_name) { * Starts the named animation playing. */ INLINE bool AnimControlCollection:: -play(const string &anim_name, double from, double to) { +play(const std::string &anim_name, double from, double to) { AnimControl *control = find_anim(anim_name); - if (control == (AnimControl *)NULL) { + if (control == nullptr) { return false; } _last_started_control = control; @@ -43,9 +43,9 @@ play(const string &anim_name, double from, double to) { * Starts the named animation looping. */ INLINE bool AnimControlCollection:: -loop(const string &anim_name, bool restart) { +loop(const std::string &anim_name, bool restart) { AnimControl *control = find_anim(anim_name); - if (control == (AnimControl *)NULL) { + if (control == nullptr) { return false; } _last_started_control = control; @@ -57,9 +57,9 @@ loop(const string &anim_name, bool restart) { * Starts the named animation looping. */ INLINE bool AnimControlCollection:: -loop(const string &anim_name, bool restart, double from, double to) { +loop(const std::string &anim_name, bool restart, double from, double to) { AnimControl *control = find_anim(anim_name); - if (control == (AnimControl *)NULL) { + if (control == nullptr) { return false; } _last_started_control = control; @@ -71,9 +71,9 @@ loop(const string &anim_name, bool restart, double from, double to) { * Stops the named animation. */ INLINE bool AnimControlCollection:: -stop(const string &anim_name) { +stop(const std::string &anim_name) { AnimControl *control = find_anim(anim_name); - if (control == (AnimControl *)NULL) { + if (control == nullptr) { return false; } control->stop(); @@ -85,9 +85,9 @@ stop(const string &anim_name) { * Sets to a particular frame in the named animation. */ INLINE bool AnimControlCollection:: -pose(const string &anim_name, double frame) { +pose(const std::string &anim_name, double frame) { AnimControl *control = find_anim(anim_name); - if (control == (AnimControl *)NULL) { + if (control == nullptr) { return false; } _last_started_control = control; @@ -100,9 +100,9 @@ pose(const string &anim_name, double frame) { * not found. */ INLINE int AnimControlCollection:: -get_frame(const string &anim_name) const { +get_frame(const std::string &anim_name) const { AnimControl *control = find_anim(anim_name); - if (control == (AnimControl *)NULL) { + if (control == nullptr) { return 0; } return control->get_frame(); @@ -113,7 +113,7 @@ get_frame(const string &anim_name) const { */ INLINE int AnimControlCollection:: get_frame() const { - if (_last_started_control == (AnimControl *)NULL) { + if (_last_started_control == nullptr) { return 0; } return _last_started_control->get_frame(); @@ -123,9 +123,9 @@ get_frame() const { * Returns true if the named animation is currently playing, false otherwise. */ INLINE bool AnimControlCollection:: -is_playing(const string &anim_name) const { +is_playing(const std::string &anim_name) const { AnimControl *control = find_anim(anim_name); - if (control == (AnimControl *)NULL) { + if (control == nullptr) { return false; } return control->is_playing(); @@ -137,7 +137,7 @@ is_playing(const string &anim_name) const { */ INLINE bool AnimControlCollection:: is_playing() const { - if (_last_started_control == (AnimControl *)NULL) { + if (_last_started_control == nullptr) { return false; } return _last_started_control->is_playing(); @@ -148,9 +148,9 @@ is_playing() const { * animation is not found. */ INLINE int AnimControlCollection:: -get_num_frames(const string &anim_name) const { +get_num_frames(const std::string &anim_name) const { AnimControl *control = find_anim(anim_name); - if (control == (AnimControl *)NULL) { + if (control == nullptr) { return 0; } return control->get_num_frames(); @@ -161,14 +161,14 @@ get_num_frames(const string &anim_name) const { */ INLINE int AnimControlCollection:: get_num_frames() const { - if (_last_started_control == (AnimControl *)NULL) { + if (_last_started_control == nullptr) { return 0; } return _last_started_control->get_num_frames(); } -INLINE ostream & -operator << (ostream &out, const AnimControlCollection &collection) { +INLINE std::ostream & +operator << (std::ostream &out, const AnimControlCollection &collection) { collection.output(out); return out; } diff --git a/panda/src/chan/animControlCollection.cxx b/panda/src/chan/animControlCollection.cxx index 2a46ebb88f..f8e6ed7b17 100644 --- a/panda/src/chan/animControlCollection.cxx +++ b/panda/src/chan/animControlCollection.cxx @@ -13,6 +13,8 @@ #include "animControlCollection.h" +using std::string; + /** * Returns the AnimControl associated with the given name, or NULL if no such @@ -20,7 +22,7 @@ */ AnimControlCollection:: AnimControlCollection() { - _last_started_control = (AnimControl *)NULL; + _last_started_control = nullptr; } /** @@ -55,7 +57,7 @@ store_anim(AnimControl *control, const string &name) { nassertv(index < _controls.size()); nassertv(_controls[index]._name == name); if (_last_started_control == _controls[index]._control) { - _last_started_control = (AnimControl *)NULL; + _last_started_control = nullptr; } _controls[index]._control = control; } @@ -69,11 +71,11 @@ AnimControl *AnimControlCollection:: find_anim(const string &name) const { ControlsByName::const_iterator ci = _controls_by_name.find(name); if (ci == _controls_by_name.end()) { - return (AnimControl *)NULL; + return nullptr; } size_t index = (*ci).second; - nassertr(index < _controls.size(), NULL); - nassertr(_controls[index]._name == name, NULL); + nassertr(index < _controls.size(), nullptr); + nassertr(_controls[index]._name == name, nullptr); return _controls[index]._control; } @@ -93,7 +95,7 @@ unbind_anim(const string &name) { nassertr(_controls[index]._name == name, false); if (_last_started_control == _controls[index]._control) { - _last_started_control = (AnimControl *)NULL; + _last_started_control = nullptr; } _controls_by_name.erase(ci); @@ -124,7 +126,7 @@ get_num_anims() const { */ AnimControl *AnimControlCollection:: get_anim(int n) const { - nassertr(n >= 0 && n < (int)_controls.size(), NULL); + nassertr(n >= 0 && n < (int)_controls.size(), nullptr); return _controls[n]._control; } @@ -252,7 +254,7 @@ which_anim_playing() const { * */ void AnimControlCollection:: -output(ostream &out) const { +output(std::ostream &out) const { out << _controls.size() << " anims."; } @@ -260,7 +262,7 @@ output(ostream &out) const { * */ void AnimControlCollection:: -write(ostream &out) const { +write(std::ostream &out) const { ControlsByName::const_iterator ci; for (ci = _controls_by_name.begin(); ci != _controls_by_name.end(); diff --git a/panda/src/chan/animControlCollection.h b/panda/src/chan/animControlCollection.h index 74db2fea86..4467520e54 100644 --- a/panda/src/chan/animControlCollection.h +++ b/panda/src/chan/animControlCollection.h @@ -35,13 +35,13 @@ PUBLISHED: AnimControlCollection(); ~AnimControlCollection(); - void store_anim(AnimControl *control, const string &name); - AnimControl *find_anim(const string &name) const; - bool unbind_anim(const string &name); + void store_anim(AnimControl *control, const std::string &name); + AnimControl *find_anim(const std::string &name) const; + bool unbind_anim(const std::string &name); int get_num_anims() const; AnimControl *get_anim(int n) const; - string get_anim_name(int n) const; + std::string get_anim_name(int n) const; MAKE_SEQ(get_anims, get_num_anims, get_anim); MAKE_SEQ(get_anim_names, get_num_anims, get_anim_name); @@ -50,12 +50,12 @@ PUBLISHED: // The following functions are convenience functions that vector directly // into the AnimControl's functionality by anim name. - INLINE bool play(const string &anim_name); - INLINE bool play(const string &anim_name, double from, double to); - INLINE bool loop(const string &anim_name, bool restart); - INLINE bool loop(const string &anim_name, bool restart, double from, double to); - INLINE bool stop(const string &anim_name); - INLINE bool pose(const string &anim_name, double frame); + INLINE bool play(const std::string &anim_name); + INLINE bool play(const std::string &anim_name, double from, double to); + INLINE bool loop(const std::string &anim_name, bool restart); + INLINE bool loop(const std::string &anim_name, bool restart, double from, double to); + INLINE bool stop(const std::string &anim_name); + INLINE bool pose(const std::string &anim_name, double frame); // These functions operate on all anims at once. void play_all(); @@ -65,36 +65,36 @@ PUBLISHED: bool stop_all(); void pose_all(double frame); - INLINE int get_frame(const string &anim_name) const; + INLINE int get_frame(const std::string &anim_name) const; INLINE int get_frame() const; - INLINE int get_num_frames(const string &anim_name) const; + INLINE int get_num_frames(const std::string &anim_name) const; INLINE int get_num_frames() const; - INLINE bool is_playing(const string &anim_name) const; + INLINE bool is_playing(const std::string &anim_name) const; INLINE bool is_playing() const; - string which_anim_playing() const; + std::string which_anim_playing() const; - void output(ostream &out) const; - void write(ostream &out) const; + void output(std::ostream &out) const; + void write(std::ostream &out) const; private: class ControlDef { public: - string _name; + std::string _name; PT(AnimControl) _control; }; typedef pvector Controls; Controls _controls; - typedef pmap ControlsByName; + typedef pmap ControlsByName; ControlsByName _controls_by_name; AnimControl *_last_started_control; }; -INLINE ostream &operator << (ostream &out, const AnimControlCollection &collection); +INLINE std::ostream &operator << (std::ostream &out, const AnimControlCollection &collection); #include "animControlCollection.I" diff --git a/panda/src/chan/animGroup.cxx b/panda/src/chan/animGroup.cxx index 364da1bd58..17a83f1f20 100644 --- a/panda/src/chan/animGroup.cxx +++ b/panda/src/chan/animGroup.cxx @@ -24,6 +24,8 @@ #include +using std::string; + TypeHandle AnimGroup::_type_handle; @@ -36,7 +38,7 @@ AnimGroup:: AnimGroup(const string &name) : Namable(name), _children(get_class_type()), - _root(NULL) + _root(nullptr) { } @@ -50,11 +52,11 @@ AnimGroup(AnimGroup *parent, const AnimGroup ©) : Namable(copy), _children(get_class_type()) { - if (parent != (AnimGroup *)NULL) { + if (parent != nullptr) { parent->_children.push_back(this); _root = parent->_root; } else { - _root = NULL; + _root = nullptr; } } @@ -67,7 +69,7 @@ AnimGroup(AnimGroup *parent, const string &name) : Namable(name), _children(get_class_type()) { - nassertv(parent != NULL); + nassertv(parent != nullptr); parent->_children.push_back(this); _root = parent->_root; @@ -95,7 +97,7 @@ get_num_children() const { */ AnimGroup *AnimGroup:: get_child(int n) const { - nassertr(n >= 0 && n < (int)_children.size(), NULL); + nassertr(n >= 0 && n < (int)_children.size(), nullptr); return _children[n]; } @@ -115,7 +117,7 @@ get_child_named(const string &name) const { } } - return (AnimGroup *)NULL; + return nullptr; } /** @@ -132,12 +134,12 @@ find_child(const string &name) const { return child; } AnimGroup *result = child->find_child(name); - if (result != (AnimGroup *)NULL) { + if (result != nullptr) { return result; } } - return (AnimGroup *)NULL; + return nullptr; } // An STL object to sort a list of children into alphabetical order. @@ -179,7 +181,7 @@ get_value_type() const { * Writes a one-line description of the group. */ void AnimGroup:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << " " << get_name(); } @@ -187,7 +189,7 @@ output(ostream &out) const { * Writes a brief description of the group and all of its descendants. */ void AnimGroup:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << *this; if (!_children.empty()) { out << " {\n"; @@ -201,7 +203,7 @@ write(ostream &out, int indent_level) const { * Writes a brief description of all of the group's descendants. */ void AnimGroup:: -write_descendants(ostream &out, int indent_level) const { +write_descendants(std::ostream &out, int indent_level) const { Children::const_iterator ci; for (ci = _children.begin(); ci != _children.end(); ++ci) { @@ -277,7 +279,7 @@ complete_pointers(TypedWritable **p_list, BamReader *) { for (int i = 1; i < _num_children+1; i++) { if (p_list[i] == TypedWritable::Null) { chan_cat->warning() << get_type().get_name() - << " Ignoring null child" << endl; + << " Ignoring null child" << std::endl; } else { _children.push_back(DCAST(AnimGroup, p_list[i])); } diff --git a/panda/src/chan/animGroup.h b/panda/src/chan/animGroup.h index 50067213d8..cc3fdb3394 100644 --- a/panda/src/chan/animGroup.h +++ b/panda/src/chan/animGroup.h @@ -32,20 +32,20 @@ class FactoryParams; */ class EXPCL_PANDA_CHAN AnimGroup : public TypedWritableReferenceCount, public Namable { protected: - AnimGroup(const string &name = ""); + AnimGroup(const std::string &name = ""); AnimGroup(AnimGroup *parent, const AnimGroup ©); PUBLISHED: // This is the normal AnimGroup constructor. - explicit AnimGroup(AnimGroup *parent, const string &name); + explicit AnimGroup(AnimGroup *parent, const std::string &name); virtual ~AnimGroup(); int get_num_children() const; AnimGroup *get_child(int n) const; MAKE_SEQ(get_children, get_num_children, get_child); - AnimGroup *get_child_named(const string &name) const; - AnimGroup *find_child(const string &name) const; + AnimGroup *get_child_named(const std::string &name) const; + AnimGroup *find_child(const std::string &name) const; void sort_descendants(); MAKE_SEQ_PROPERTY(children, get_num_children, get_child); @@ -54,11 +54,11 @@ public: virtual TypeHandle get_value_type() const; PUBLISHED: - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; protected: - void write_descendants(ostream &out, int indent_level) const; + void write_descendants(std::ostream &out, int indent_level) const; virtual AnimGroup *make_copy(AnimGroup *parent) const; PT(AnimGroup) copy_subtree(AnimGroup *parent) const; @@ -80,7 +80,7 @@ protected: void fillin(DatagramIterator& scan, BamReader* manager); private: - typedef pvector< string > frozenJoints; + typedef pvector< std::string > frozenJoints; int _num_children; public: @@ -102,7 +102,7 @@ private: static TypeHandle _type_handle; }; -inline ostream &operator << (ostream &out, const AnimGroup &anim) { +inline std::ostream &operator << (std::ostream &out, const AnimGroup &anim) { anim.output(out); return out; } diff --git a/panda/src/chan/animPreloadTable.I b/panda/src/chan/animPreloadTable.I index a2555c5a9d..fc996c2859 100644 --- a/panda/src/chan/animPreloadTable.I +++ b/panda/src/chan/animPreloadTable.I @@ -29,9 +29,9 @@ operator < (const AnimRecord &other) const { /** * Returns the basename stored for the nth animation record. See find_anim(). */ -INLINE string AnimPreloadTable:: +INLINE std::string AnimPreloadTable:: get_basename(int n) const { - nassertr(n >= 0 && n < (int)_anims.size(), string()); + nassertr(n >= 0 && n < (int)_anims.size(), std::string()); consider_sort(); return _anims[n]._basename; } diff --git a/panda/src/chan/animPreloadTable.cxx b/panda/src/chan/animPreloadTable.cxx index 9303c11490..43958482b3 100644 --- a/panda/src/chan/animPreloadTable.cxx +++ b/panda/src/chan/animPreloadTable.cxx @@ -60,7 +60,7 @@ get_num_anims() const { * Filename::get_basename_wo_extension(). */ int AnimPreloadTable:: -find_anim(const string &basename) const { +find_anim(const std::string &basename) const { consider_sort(); AnimRecord record; record._basename = basename; @@ -96,7 +96,7 @@ remove_anim(int n) { * See find_anim(). This will invalidate existing index numbers. */ void AnimPreloadTable:: -add_anim(const string &basename, PN_stdfloat base_frame_rate, int num_frames) { +add_anim(const std::string &basename, PN_stdfloat base_frame_rate, int num_frames) { AnimRecord record; record._basename = basename; record._base_frame_rate = base_frame_rate; @@ -124,7 +124,7 @@ add_anims_from(const AnimPreloadTable *other) { * */ void AnimPreloadTable:: -output(ostream &out) const { +output(std::ostream &out) const { consider_sort(); out << "AnimPreloadTable, " << _anims.size() << " animation records."; } @@ -133,7 +133,7 @@ output(ostream &out) const { * */ void AnimPreloadTable:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { consider_sort(); indent(out, indent_level) << "AnimPreloadTable, " << _anims.size() << " animation records:\n"; diff --git a/panda/src/chan/animPreloadTable.h b/panda/src/chan/animPreloadTable.h index 123cd00eb4..e4fd64915b 100644 --- a/panda/src/chan/animPreloadTable.h +++ b/panda/src/chan/animPreloadTable.h @@ -39,7 +39,7 @@ public: INLINE AnimRecord(); INLINE bool operator < (const AnimRecord &other) const; - string _basename; + std::string _basename; PN_stdfloat _base_frame_rate; int _num_frames; }; @@ -52,19 +52,19 @@ PUBLISHED: virtual ~AnimPreloadTable(); int get_num_anims() const; - int find_anim(const string &basename) const; + int find_anim(const std::string &basename) const; - INLINE string get_basename(int n) const; + INLINE std::string get_basename(int n) const; INLINE PN_stdfloat get_base_frame_rate(int n) const; INLINE int get_num_frames(int n) const; void clear_anims(); void remove_anim(int n); - void add_anim(const string &basename, PN_stdfloat base_frame_rate, int num_frames); + void add_anim(const std::string &basename, PN_stdfloat base_frame_rate, int num_frames); void add_anims_from(const AnimPreloadTable *other); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; private: INLINE void consider_sort() const; @@ -101,7 +101,7 @@ private: static TypeHandle _type_handle; }; -inline ostream &operator << (ostream &out, const AnimPreloadTable &anim) { +inline std::ostream &operator << (std::ostream &out, const AnimPreloadTable &anim) { anim.output(out); return out; } diff --git a/panda/src/chan/auto_bind.cxx b/panda/src/chan/auto_bind.cxx index 912b199ac8..993201a8ef 100644 --- a/panda/src/chan/auto_bind.cxx +++ b/panda/src/chan/auto_bind.cxx @@ -18,6 +18,8 @@ #include "string_utils.h" #include "partGroup.h" +using std::string; + typedef pset AnimBundles; typedef pmap Anims; @@ -52,15 +54,15 @@ bind_anims(const PartBundles &parts, const AnimBundles &anims, if (name.empty()) { name = anim->get_name(); } - if (control != (AnimControl *)NULL) { - if (controls.find_anim(name) != (AnimControl *)NULL) { + if (control != nullptr) { + if (controls.find_anim(name) != nullptr) { // That name's already used; synthesize another one. int index = 0; string new_name; do { index++; new_name = name + '.' + format_string(index); - } while (controls.find_anim(new_name) != (AnimControl *)NULL); + } while (controls.find_anim(new_name) != nullptr); name = new_name; } @@ -68,7 +70,7 @@ bind_anims(const PartBundles &parts, const AnimBundles &anims, } if (chan_cat.is_info()) { - if (control == (AnimControl *)NULL) { + if (control == nullptr) { chan_cat.info() << "Bind failed.\n"; } else { diff --git a/panda/src/chan/bindAnimRequest.cxx b/panda/src/chan/bindAnimRequest.cxx index b1315044b9..637f44831d 100644 --- a/panda/src/chan/bindAnimRequest.cxx +++ b/panda/src/chan/bindAnimRequest.cxx @@ -22,7 +22,7 @@ TypeHandle BindAnimRequest::_type_handle; * */ BindAnimRequest:: -BindAnimRequest(const string &name, +BindAnimRequest(const std::string &name, const Filename &filename, const LoaderOptions &options, Loader *loader, AnimControl *control, int hierarchy_match_flags, @@ -51,7 +51,7 @@ do_task() { } PT(PandaNode) model = get_model(); - if (model == (PandaNode *)NULL) { + if (model == nullptr) { // Couldn't load the file. _control->fail_anim(part); return DS_done; @@ -59,7 +59,7 @@ do_task() { _control->set_anim_model(model); AnimBundle *anim = AnimBundleNode::find_anim_bundle(model); - if (anim == (AnimBundle *)NULL) { + if (anim == nullptr) { // No anim bundle. _control->fail_anim(part); return DS_done; diff --git a/panda/src/chan/bindAnimRequest.h b/panda/src/chan/bindAnimRequest.h index fed5e5d596..f3d0314b6a 100644 --- a/panda/src/chan/bindAnimRequest.h +++ b/panda/src/chan/bindAnimRequest.h @@ -25,12 +25,12 @@ class AnimControl; * This class object manages an asynchronous load-and-bind animation request, * as issued through PartBundle::load_bind_anim(). */ -class EXPCL_PANDA_PGRAPH BindAnimRequest : public ModelLoadRequest { +class EXPCL_PANDA_CHAN BindAnimRequest : public ModelLoadRequest { public: ALLOC_DELETED_CHAIN(BindAnimRequest); PUBLISHED: - explicit BindAnimRequest(const string &name, + explicit BindAnimRequest(const std::string &name, const Filename &filename, const LoaderOptions &options, Loader *loader, diff --git a/panda/src/chan/movingPart.I b/panda/src/chan/movingPart.I index 8b988d9422..9b0d35e9c8 100644 --- a/panda/src/chan/movingPart.I +++ b/panda/src/chan/movingPart.I @@ -43,7 +43,7 @@ MovingPart(const MovingPart ©) : */ template INLINE MovingPart:: -MovingPart(PartGroup *parent, const string &name, +MovingPart(PartGroup *parent, const std::string &name, const ValueType &default_value) : MovingPartBase(parent, name), _value(default_value), @@ -87,7 +87,7 @@ make_default_channel() const { */ template void MovingPart:: -output_value(ostream &out) const { +output_value(std::ostream &out) const { SwitchType::output_value(out, _value); } diff --git a/panda/src/chan/movingPart.h b/panda/src/chan/movingPart.h index 7b3640b981..8673a271d6 100644 --- a/panda/src/chan/movingPart.h +++ b/panda/src/chan/movingPart.h @@ -26,19 +26,19 @@ template class MovingPart : public MovingPartBase { public: - typedef TYPENAME SwitchType::ValueType ValueType; + typedef typename SwitchType::ValueType ValueType; typedef AnimChannel ChannelType; protected: INLINE MovingPart(const MovingPart ©); public: - INLINE MovingPart(PartGroup *parent, const string &name, + INLINE MovingPart(PartGroup *parent, const std::string &name, const ValueType &default_value); virtual TypeHandle get_value_type() const; virtual AnimChannelBase *make_default_channel() const; - virtual void output_value(ostream &out) const; + virtual void output_value(std::ostream &out) const; ValueType _value; ValueType _default_value; diff --git a/panda/src/chan/movingPartBase.I b/panda/src/chan/movingPartBase.I index 2c18cb7584..182f597b67 100644 --- a/panda/src/chan/movingPartBase.I +++ b/panda/src/chan/movingPartBase.I @@ -18,7 +18,7 @@ INLINE MovingPartBase:: MovingPartBase(const MovingPartBase ©) : PartGroup(copy), _num_effective_channels(0), - _effective_control(NULL), + _effective_control(nullptr), _forced_channel(copy._forced_channel) { // We don't copy the bound channels. We do copy the forced_channel, though @@ -47,6 +47,6 @@ get_max_bound() const { */ INLINE AnimChannelBase *MovingPartBase:: get_bound(int n) const { - nassertr(n >= 0 && n < (int)_channels.size(), NULL); + nassertr(n >= 0 && n < (int)_channels.size(), nullptr); return _channels[n]; } diff --git a/panda/src/chan/movingPartBase.cxx b/panda/src/chan/movingPartBase.cxx index b623e7f689..e4016edd2c 100644 --- a/panda/src/chan/movingPartBase.cxx +++ b/panda/src/chan/movingPartBase.cxx @@ -26,10 +26,10 @@ TypeHandle MovingPartBase::_type_handle; * */ MovingPartBase:: -MovingPartBase(PartGroup *parent, const string &name) : +MovingPartBase(PartGroup *parent, const std::string &name) : PartGroup(parent, name), _num_effective_channels(0), - _effective_control(NULL) + _effective_control(nullptr) { } @@ -39,7 +39,7 @@ MovingPartBase(PartGroup *parent, const string &name) : MovingPartBase:: MovingPartBase() : _num_effective_channels(0), - _effective_control(NULL) + _effective_control(nullptr) { } @@ -49,7 +49,7 @@ MovingPartBase() : */ bool MovingPartBase:: clear_forced_channel() { - if (_forced_channel != (AnimChannelBase *)NULL) { + if (_forced_channel != nullptr) { _forced_channel.clear(); return true; } @@ -70,7 +70,7 @@ get_forced_channel() const { * Writes a brief description of the channel and all of its descendants. */ void MovingPartBase:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_value_type() << " " << get_name(); if (_children.empty()) { out << "\n"; @@ -86,7 +86,7 @@ write(ostream &out, int indent_level) const { * with their values. */ void MovingPartBase:: -write_with_value(ostream &out, int indent_level) const { +write_with_value(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_value_type() << " " << get_name() << "\n"; indent(out, indent_level); output_value(out); @@ -117,10 +117,10 @@ do_update(PartBundle *root, const CycleData *root_cdata, PartGroup *parent, // See if any of the channel values have changed since last time. if (!needs_update) { - if (_forced_channel != (AnimChannelBase *)NULL) { + if (_forced_channel != nullptr) { needs_update = _forced_channel->has_changed(0, 0.0, 0, 0.0); - } else if (_effective_control != (AnimControl *)NULL) { + } else if (_effective_control != nullptr) { const PartBundle::CData *cdata = (const PartBundle::CData *)root_cdata; needs_update = _effective_control->channel_has_changed(_effective_channel, cdata->_frame_blend_flag); @@ -132,12 +132,12 @@ do_update(PartBundle *root, const CycleData *root_cdata, PartGroup *parent, ++bci) { AnimControl *control = (*bci).first; - AnimChannelBase *channel = NULL; + AnimChannelBase *channel = nullptr; int channel_index = control->get_channel_index(); if (channel_index >= 0 && channel_index < (int)_channels.size()) { channel = _channels[channel_index]; } - if (channel != (AnimChannelBase*)NULL) { + if (channel != nullptr) { needs_update = control->channel_has_changed(channel, cdata->_frame_blend_flag); } } @@ -199,7 +199,7 @@ pick_channel_index(plist &holes, int &next) const { int hole = (*ii); nassertv(hole >= 0 && hole < next); if (hole < (int)_channels.size() || - _channels[hole] != (AnimChannelBase *)NULL) { + _channels[hole] != nullptr) { // We can't accept this hole; we're using it! holes.erase(ii); } @@ -210,7 +210,7 @@ pick_channel_index(plist &holes, int &next) const { if (next < (int)_channels.size()) { int i; for (i = next; i < (int)_channels.size(); i++) { - if (_channels[i] == (AnimChannelBase*)NULL) { + if (_channels[i] == nullptr) { // Here's a hole we do have. holes.push_back(i); } @@ -238,7 +238,7 @@ bind_hierarchy(AnimGroup *anim, int channel_index, int &joint_index, } if (chan_cat.is_debug()) { - if (anim == (AnimGroup *)NULL) { + if (anim == nullptr) { chan_cat.debug() << "binding " << *this << " to NULL, is_included = " << is_included << "\n"; @@ -249,13 +249,13 @@ bind_hierarchy(AnimGroup *anim, int channel_index, int &joint_index, } } while ((int)_channels.size() <= channel_index) { - _channels.push_back((AnimChannelBase*)NULL); + _channels.push_back(nullptr); } - nassertv(_channels[channel_index] == (AnimChannelBase*)NULL); + nassertv(_channels[channel_index] == nullptr); if (is_included) { - if (anim == (AnimGroup*)NULL) { + if (anim == nullptr) { // If we're binding to the NULL anim, it means actually to create a // default AnimChannel that just returns the part's initial value. _channels[channel_index] = make_default_channel(); @@ -303,12 +303,12 @@ find_bound_joints(int &joint_index, bool is_included, BitArray &bound_joints, */ void MovingPartBase:: determine_effective_channels(const CycleData *root_cdata) { - _effective_control = NULL; - _effective_channel = NULL; + _effective_control = nullptr; + _effective_channel = nullptr; _num_effective_channels = 0; - AnimControl *effective_control = NULL; - AnimChannelBase *effective_channel = NULL; + AnimControl *effective_control = nullptr; + AnimChannelBase *effective_channel = nullptr; int num_effective_channels = 0; const PartBundle::CData *cdata = (const PartBundle::CData *)root_cdata; @@ -319,7 +319,7 @@ determine_effective_channels(const CycleData *root_cdata) { AnimControl *control = (*cbi).first; int channel_index = control->get_channel_index(); if (channel_index >= 0 && channel_index < (int)_channels.size()) { - if (_channels[channel_index] != (AnimChannelBase *)NULL) { + if (_channels[channel_index] != nullptr) { effective_control = control; effective_channel = _channels[channel_index]; ++num_effective_channels; diff --git a/panda/src/chan/movingPartBase.h b/panda/src/chan/movingPartBase.h index 3618cbfd19..c7b09c8acf 100644 --- a/panda/src/chan/movingPartBase.h +++ b/panda/src/chan/movingPartBase.h @@ -33,7 +33,7 @@ protected: INLINE MovingPartBase(const MovingPartBase ©); public: - MovingPartBase(PartGroup *parent, const string &name); + MovingPartBase(PartGroup *parent, const std::string &name); PUBLISHED: INLINE int get_max_bound() const; @@ -47,9 +47,9 @@ PUBLISHED: virtual bool clear_forced_channel(); virtual AnimChannelBase *get_forced_channel() const; - virtual void write(ostream &out, int indent_level) const; - virtual void write_with_value(ostream &out, int indent_level) const; - virtual void output_value(ostream &out) const=0; + virtual void write(std::ostream &out, int indent_level) const; + virtual void write_with_value(std::ostream &out, int indent_level) const; + virtual void output_value(std::ostream &out) const=0; public: virtual bool do_update(PartBundle *root, const CycleData *root_cdata, diff --git a/panda/src/chan/movingPartMatrix.I b/panda/src/chan/movingPartMatrix.I index a545f9f9fa..f9432b312e 100644 --- a/panda/src/chan/movingPartMatrix.I +++ b/panda/src/chan/movingPartMatrix.I @@ -24,7 +24,7 @@ MovingPartMatrix(const MovingPartMatrix ©) : * */ INLINE MovingPartMatrix:: -MovingPartMatrix(PartGroup *parent, const string &name, +MovingPartMatrix(PartGroup *parent, const std::string &name, const LMatrix4 &default_value) : MovingPart(parent, name, default_value) { } diff --git a/panda/src/chan/movingPartMatrix.cxx b/panda/src/chan/movingPartMatrix.cxx index 6477728e0d..0c8c7bc7bd 100644 --- a/panda/src/chan/movingPartMatrix.cxx +++ b/panda/src/chan/movingPartMatrix.cxx @@ -53,7 +53,7 @@ get_blend_value(const PartBundle *root) { // If a forced channel is set on this particular joint, we always return // that value instead of performing the blend. Furthermore, the frame // number is always 0 for the forced channel. - if (_forced_channel != (AnimChannelBase *)NULL) { + if (_forced_channel != nullptr) { ChannelType *channel = DCAST(ChannelType, _forced_channel); channel->get_value(0, _value); return; @@ -67,7 +67,7 @@ get_blend_value(const PartBundle *root) { _value = _default_value; } - } else if (_effective_control != (AnimControl *)NULL && + } else if (_effective_control != nullptr && !cdata->_frame_blend_flag) { // A single value, the normal case. ChannelType *channel = DCAST(ChannelType, _effective_channel); @@ -93,7 +93,7 @@ get_blend_value(const PartBundle *root) { int channel_index = control->get_channel_index(); nassertv(channel_index >= 0 && channel_index < (int)_channels.size()); ChannelType *channel = DCAST(ChannelType, _channels[channel_index]); - if (channel != (ChannelType *)NULL) { + if (channel != nullptr) { ValueType v; channel->get_value(control->get_frame(), v); @@ -140,12 +140,12 @@ get_blend_value(const PartBundle *root) { PN_stdfloat effect = (*cbi).second; nassertv(effect != 0.0f); - ChannelType *channel = NULL; + ChannelType *channel = nullptr; int channel_index = control->get_channel_index(); if (channel_index >= 0 && channel_index < (int)_channels.size()) { channel = DCAST(ChannelType, _channels[channel_index]); } - if (channel != (ChannelType *)NULL) { + if (channel != nullptr) { int frame = control->get_frame(); ValueType v; LVecBase3 iscale, ishear; @@ -213,12 +213,12 @@ get_blend_value(const PartBundle *root) { PN_stdfloat effect = (*cbi).second; nassertv(effect != 0.0f); - ChannelType *channel = NULL; + ChannelType *channel = nullptr; int channel_index = control->get_channel_index(); if (channel_index >= 0 && channel_index < (int)_channels.size()) { channel = DCAST(ChannelType, _channels[channel_index]); } - if (channel != (ChannelType *)NULL) { + if (channel != nullptr) { int frame = control->get_frame(); LVecBase3 iscale, ihpr, ipos, ishear; channel->get_scale(frame, iscale); @@ -289,12 +289,12 @@ get_blend_value(const PartBundle *root) { PN_stdfloat effect = (*cbi).second; nassertv(effect != 0.0f); - ChannelType *channel = NULL; + ChannelType *channel = nullptr; int channel_index = control->get_channel_index(); if (channel_index >= 0 && channel_index < (int)_channels.size()) { channel = DCAST(ChannelType, _channels[channel_index]); } - if (channel != (ChannelType *)NULL) { + if (channel != nullptr) { int frame = control->get_frame(); LVecBase3 iscale, ipos, ishear; LQuaternion iquat; diff --git a/panda/src/chan/movingPartMatrix.h b/panda/src/chan/movingPartMatrix.h index 3c232e63d0..364686555a 100644 --- a/panda/src/chan/movingPartMatrix.h +++ b/panda/src/chan/movingPartMatrix.h @@ -31,7 +31,7 @@ protected: INLINE MovingPartMatrix(const MovingPartMatrix ©); public: - INLINE MovingPartMatrix(PartGroup *parent, const string &name, + INLINE MovingPartMatrix(PartGroup *parent, const std::string &name, const LMatrix4 &default_value); virtual ~MovingPartMatrix(); diff --git a/panda/src/chan/movingPartScalar.I b/panda/src/chan/movingPartScalar.I index e49a542575..1b585746e4 100644 --- a/panda/src/chan/movingPartScalar.I +++ b/panda/src/chan/movingPartScalar.I @@ -24,7 +24,7 @@ MovingPartScalar(const MovingPartScalar ©) : * */ INLINE MovingPartScalar:: -MovingPartScalar(PartGroup *parent, const string &name, +MovingPartScalar(PartGroup *parent, const std::string &name, const PN_stdfloat &default_value) : MovingPart(parent, name, default_value) { } diff --git a/panda/src/chan/movingPartScalar.cxx b/panda/src/chan/movingPartScalar.cxx index abebb49a32..d0d03b4152 100644 --- a/panda/src/chan/movingPartScalar.cxx +++ b/panda/src/chan/movingPartScalar.cxx @@ -39,7 +39,7 @@ get_blend_value(const PartBundle *root) { // If a forced channel is set on this particular scalar, we always return // that value instead of performing the blend. Furthermore, the frame // number is always 0 for the forced channel. - if (_forced_channel != (AnimChannelBase *)NULL) { + if (_forced_channel != nullptr) { ChannelType *channel = DCAST(ChannelType, _forced_channel); channel->get_value(0, _value); return; @@ -53,7 +53,7 @@ get_blend_value(const PartBundle *root) { _value = _default_value; } - } else if (_effective_control != (AnimControl *)NULL && + } else if (_effective_control != nullptr && !cdata->_frame_blend_flag) { // A single value, the normal case. ChannelType *channel = DCAST(ChannelType, _effective_channel); @@ -70,12 +70,12 @@ get_blend_value(const PartBundle *root) { PN_stdfloat effect = (*cbi).second; nassertv(effect != 0.0f); - ChannelType *channel = NULL; + ChannelType *channel = nullptr; int channel_index = control->get_channel_index(); if (channel_index >= 0 && channel_index < (int)_channels.size()) { channel = DCAST(ChannelType, _channels[channel_index]); } - if (channel != NULL) { + if (channel != nullptr) { ValueType v; channel->get_value(control->get_frame(), v); diff --git a/panda/src/chan/movingPartScalar.h b/panda/src/chan/movingPartScalar.h index 90bd049ee5..d05e58f4e7 100644 --- a/panda/src/chan/movingPartScalar.h +++ b/panda/src/chan/movingPartScalar.h @@ -30,7 +30,7 @@ protected: INLINE MovingPartScalar(const MovingPartScalar ©); public: - INLINE MovingPartScalar(PartGroup *parent, const string &name, + INLINE MovingPartScalar(PartGroup *parent, const std::string &name, const PN_stdfloat &default_value = 0); virtual ~MovingPartScalar(); diff --git a/panda/src/chan/partBundle.I b/panda/src/chan/partBundle.I index ca6ec4c7cf..ca4ffdaad4 100644 --- a/panda/src/chan/partBundle.I +++ b/panda/src/chan/partBundle.I @@ -43,7 +43,7 @@ set_anim_preload(AnimPreloadTable *anim_preload) { */ INLINE void PartBundle:: clear_anim_preload() { - _anim_preload = NULL; + _anim_preload = nullptr; } /** @@ -165,7 +165,7 @@ get_num_nodes() const { */ INLINE PartBundleNode *PartBundle:: get_node(int n) const { - nassertr(n >= 0 && n < (int)_nodes.size(), NULL); + nassertr(n >= 0 && n < (int)_nodes.size(), nullptr); return _nodes[n]; } diff --git a/panda/src/chan/partBundle.cxx b/panda/src/chan/partBundle.cxx index f519d09a60..966987995a 100644 --- a/panda/src/chan/partBundle.cxx +++ b/panda/src/chan/partBundle.cxx @@ -31,6 +31,10 @@ #include +using std::istream; +using std::ostream; +using std::string; + TypeHandle PartBundle::_type_handle; @@ -85,13 +89,13 @@ make_copy() const { */ void PartBundle:: merge_anim_preloads(const PartBundle *other) { - if (other->_anim_preload == (AnimPreloadTable *)NULL || + if (other->_anim_preload == nullptr || _anim_preload == other->_anim_preload) { // No-op. return; } - if (_anim_preload == (AnimPreloadTable *)NULL) { + if (_anim_preload == nullptr) { // Trivial case. _anim_preload = other->_anim_preload; return; @@ -128,7 +132,7 @@ set_anim_blend_flag(bool anim_blend_flag) { // eliminate all the AnimControls other than the most-recently-added // one. - nassertv(cdataw->_last_control_set != NULL); + nassertv(cdataw->_last_control_set != nullptr); clear_and_stop_intersecting(cdataw->_last_control_set, cdataw); } @@ -150,10 +154,11 @@ apply_transform(const TransformState *transform) { AppliedTransforms::iterator ati = _applied_transforms.find(transform); if (ati != _applied_transforms.end()) { - if ((*ati).first.is_valid_pointer() && - (*ati).second.is_valid_pointer()) { - // Here's our cached result. - return (*ati).second.p(); + if ((*ati).first.is_valid_pointer()) { + if (auto new_bundle = (*ati).second.lock()) { + // Here's our cached result. + return new_bundle; + } } } @@ -247,7 +252,7 @@ bind_anim(AnimBundle *anim, int hierarchy_match_flags, return control; } - return NULL; + return nullptr; } /** @@ -275,7 +280,7 @@ PT(AnimControl) PartBundle:: load_bind_anim(Loader *loader, const Filename &filename, int hierarchy_match_flags, const PartSubset &subset, bool allow_async) { - nassertr(loader != (Loader *)NULL, NULL); + nassertr(loader != nullptr, nullptr); LoaderOptions anim_options(LoaderOptions::LF_search | LoaderOptions::LF_report_errors | @@ -284,7 +289,7 @@ load_bind_anim(Loader *loader, const Filename &filename, int anim_index = -1; CPT(AnimPreloadTable) anim_preload = _anim_preload.get_read_pointer(); - if (anim_preload != (AnimPreloadTable *)NULL) { + if (anim_preload != nullptr) { anim_index = anim_preload->find_anim(basename); } @@ -293,19 +298,19 @@ load_bind_anim(Loader *loader, const Filename &filename, // Therefore, perform an ordinary synchronous load-and-bind. PT(PandaNode) model = loader->load_sync(filename, anim_options); - if (model == (PandaNode *)NULL) { + if (model == nullptr) { // Couldn't load the file. - return NULL; + return nullptr; } AnimBundle *anim = AnimBundleNode::find_anim_bundle(model); - if (anim == (AnimBundle *)NULL) { + if (anim == nullptr) { // No anim bundle. - return NULL; + return nullptr; } PT(AnimControl) control = bind_anim(anim, hierarchy_match_flags, subset); - if (control == (AnimControl *)NULL) { + if (control == nullptr) { // Couldn't bind. - return NULL; + return nullptr; } control->set_anim_model(model); return control; @@ -366,7 +371,7 @@ wait_pending() { bool PartBundle:: freeze_joint(const string &joint_name, const TransformState *transform) { PartGroup *child = find_child(joint_name); - if (child == (PartGroup *)NULL) { + if (child == nullptr) { return false; } @@ -387,7 +392,7 @@ freeze_joint(const string &joint_name, const TransformState *transform) { bool PartBundle:: freeze_joint(const string &joint_name, const LVecBase3 &pos, const LVecBase3 &hpr, const LVecBase3 &scale) { PartGroup *child = find_child(joint_name); - if (child == (PartGroup *)NULL) { + if (child == nullptr) { return false; } @@ -408,7 +413,7 @@ freeze_joint(const string &joint_name, const LVecBase3 &pos, const LVecBase3 &hp bool PartBundle:: freeze_joint(const string &joint_name, PN_stdfloat value) { PartGroup *child = find_child(joint_name); - if (child == (PartGroup *)NULL) { + if (child == nullptr) { return false; } @@ -430,7 +435,7 @@ freeze_joint(const string &joint_name, PN_stdfloat value) { bool PartBundle:: control_joint(const string &joint_name, PandaNode *node) { PartGroup *child = find_child(joint_name); - if (child == (PartGroup *)NULL) { + if (child == nullptr) { return false; } @@ -451,7 +456,7 @@ control_joint(const string &joint_name, PandaNode *node) { bool PartBundle:: release_joint(const string &joint_name) { PartGroup *child = find_child(joint_name); - if (child == (PartGroup *)NULL) { + if (child == nullptr) { return false; } @@ -479,7 +484,7 @@ update() { bool anim_changed = cdata->_anim_changed; bool frame_blend_flag = cdata->_frame_blend_flag; - any_changed = do_update(this, cdata, NULL, false, anim_changed, + any_changed = do_update(this, cdata, nullptr, false, anim_changed, current_thread); // Now update all the controls for next time. @@ -504,7 +509,7 @@ bool PartBundle:: force_update() { Thread *current_thread = Thread::get_current_thread(); CDWriter cdata(_cycler, false, current_thread); - bool any_changed = do_update(this, cdata, NULL, true, true, current_thread); + bool any_changed = do_update(this, cdata, nullptr, true, true, current_thread); // Now update all the controls for next time. ChannelBlend::const_iterator cbi; @@ -585,7 +590,7 @@ do_bind_anim(AnimControl *control, AnimBundle *anim, } } - if (!check_hierarchy(anim, NULL, hierarchy_match_flags)) { + if (!check_hierarchy(anim, nullptr, hierarchy_match_flags)) { return false; } @@ -747,7 +752,7 @@ void PartBundle:: finalize(BamReader *) { Thread *current_thread = Thread::get_current_thread(); CDWriter cdata(_cycler, true); - do_update(this, cdata, NULL, true, true, current_thread); + do_update(this, cdata, nullptr, true, true, current_thread); } /** @@ -827,7 +832,7 @@ CData() { _anim_blend_flag = false; _frame_blend_flag = interpolate_frames; _root_xform = LMatrix4::ident_mat(); - _last_control_set = NULL; + _last_control_set = nullptr; _net_blend = 0.0f; _anim_changed = false; _last_update = 0.0; diff --git a/panda/src/chan/partBundle.h b/panda/src/chan/partBundle.h index 80ddb4122d..7a611a80de 100644 --- a/panda/src/chan/partBundle.h +++ b/panda/src/chan/partBundle.h @@ -55,7 +55,7 @@ protected: PartBundle(const PartBundle ©); PUBLISHED: - explicit PartBundle(const string &name = ""); + explicit PartBundle(const std::string &name = ""); virtual PartGroup *make_copy() const; INLINE CPT(AnimPreloadTable) get_anim_preload() const; @@ -123,8 +123,8 @@ PUBLISHED: INLINE void set_control_effect(AnimControl *control, PN_stdfloat effect); INLINE PN_stdfloat get_control_effect(AnimControl *control) const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; PT(AnimControl) bind_anim(AnimBundle *anim, int hierarchy_match_flags = 0, @@ -136,11 +136,11 @@ PUBLISHED: bool allow_async); void wait_pending(); - bool freeze_joint(const string &joint_name, const TransformState *transform); - bool freeze_joint(const string &joint_name, const LVecBase3 &pos, const LVecBase3 &hpr, const LVecBase3 &scale); - bool freeze_joint(const string &joint_name, PN_stdfloat value); - bool control_joint(const string &joint_name, PandaNode *node); - bool release_joint(const string &joint_name); + bool freeze_joint(const std::string &joint_name, const TransformState *transform); + bool freeze_joint(const std::string &joint_name, const LVecBase3 &pos, const LVecBase3 &hpr, const LVecBase3 &scale); + bool freeze_joint(const std::string &joint_name, PN_stdfloat value); + bool control_joint(const std::string &joint_name, PandaNode *node); + bool release_joint(const std::string &joint_name); bool update(); bool force_update(); @@ -243,13 +243,13 @@ private: friend class MovingPartScalar; }; -inline ostream &operator <<(ostream &out, const PartBundle &bundle) { +inline std::ostream &operator <<(std::ostream &out, const PartBundle &bundle) { bundle.output(out); return out; } -ostream &operator <<(ostream &out, PartBundle::BlendType blend_type); -istream &operator >>(istream &in, PartBundle::BlendType &blend_type); +std::ostream &operator <<(std::ostream &out, PartBundle::BlendType blend_type); +std::istream &operator >>(std::istream &in, PartBundle::BlendType &blend_type); #include "partBundle.I" diff --git a/panda/src/chan/partBundleNode.I b/panda/src/chan/partBundleNode.I index c1251b7eac..e9da42359c 100644 --- a/panda/src/chan/partBundleNode.I +++ b/panda/src/chan/partBundleNode.I @@ -17,7 +17,7 @@ * the appropriate type, and pass it up to this constructor. */ INLINE PartBundleNode:: -PartBundleNode(const string &name, PartBundle *bundle) : +PartBundleNode(const std::string &name, PartBundle *bundle) : PandaNode(name) { add_bundle(bundle); @@ -54,7 +54,7 @@ get_num_bundles() const { */ INLINE PartBundle *PartBundleNode:: get_bundle(int n) const { - nassertr(n >= 0 && n < (int)_bundles.size(), NULL); + nassertr(n >= 0 && n < (int)_bundles.size(), nullptr); return _bundles[n]->get_bundle(); } @@ -65,6 +65,6 @@ get_bundle(int n) const { */ INLINE PartBundleHandle *PartBundleNode:: get_bundle_handle(int n) const { - nassertr(n >= 0 && n < (int)_bundles.size(), NULL); + nassertr(n >= 0 && n < (int)_bundles.size(), nullptr); return _bundles[n]; } diff --git a/panda/src/chan/partBundleNode.cxx b/panda/src/chan/partBundleNode.cxx index e0a726fd39..9fe5473fe0 100644 --- a/panda/src/chan/partBundleNode.cxx +++ b/panda/src/chan/partBundleNode.cxx @@ -192,6 +192,6 @@ fillin(DatagramIterator &scan, BamReader* manager) { // Remaining bundles. Push a new slot for each one. for (int i = 1; i < num_bundles; ++i) { manager->read_pointer(scan); - _bundles.push_back(NULL); + _bundles.push_back(nullptr); } } diff --git a/panda/src/chan/partBundleNode.h b/panda/src/chan/partBundleNode.h index 231c1175ee..6cb98638d1 100644 --- a/panda/src/chan/partBundleNode.h +++ b/panda/src/chan/partBundleNode.h @@ -34,7 +34,7 @@ */ class EXPCL_PANDA_CHAN PartBundleNode : public PandaNode { PUBLISHED: - INLINE explicit PartBundleNode(const string &name, PartBundle *bundle); + INLINE explicit PartBundleNode(const std::string &name, PartBundle *bundle); protected: INLINE PartBundleNode(); diff --git a/panda/src/chan/partGroup.I b/panda/src/chan/partGroup.I index 4b1c166bad..250cd195eb 100644 --- a/panda/src/chan/partGroup.I +++ b/panda/src/chan/partGroup.I @@ -16,7 +16,7 @@ * You should normally use the non-default constructor, below. */ INLINE PartGroup:: -PartGroup(const string &name) : +PartGroup(const std::string &name) : Namable(name), _children(get_class_type()) { diff --git a/panda/src/chan/partGroup.cxx b/panda/src/chan/partGroup.cxx index 20fe582ae9..52cee4ce19 100644 --- a/panda/src/chan/partGroup.cxx +++ b/panda/src/chan/partGroup.cxx @@ -25,6 +25,8 @@ #include +using std::ostream; + TypeHandle PartGroup::_type_handle; /** @@ -32,11 +34,11 @@ TypeHandle PartGroup::_type_handle; * to delete it subsequently is to delete the entire hierarchy. */ PartGroup:: -PartGroup(PartGroup *parent, const string &name) : +PartGroup(PartGroup *parent, const std::string &name) : Namable(name), _children(get_class_type()) { - nassertv(parent != NULL); + nassertv(parent != nullptr); parent->_children.push_back(this); } @@ -102,7 +104,7 @@ get_num_children() const { */ PartGroup *PartGroup:: get_child(int n) const { - nassertr(n >= 0 && n < (int)_children.size(), NULL); + nassertr(n >= 0 && n < (int)_children.size(), nullptr); return _children[n]; } @@ -113,7 +115,7 @@ get_child(int n) const { * find_child(). */ PartGroup *PartGroup:: -get_child_named(const string &name) const { +get_child_named(const std::string &name) const { Children::const_iterator ci; for (ci = _children.begin(); ci != _children.end(); ++ci) { PartGroup *child = (*ci); @@ -122,7 +124,7 @@ get_child_named(const string &name) const { } } - return (PartGroup *)NULL; + return nullptr; } /** @@ -131,7 +133,7 @@ get_child_named(const string &name) const { * this PartGroup; see also get_child_named(). */ PartGroup *PartGroup:: -find_child(const string &name) const { +find_child(const std::string &name) const { Children::const_iterator ci; for (ci = _children.begin(); ci != _children.end(); ++ci) { PartGroup *child = (*ci); @@ -139,12 +141,12 @@ find_child(const string &name) const { return child; } PartGroup *result = child->find_child(name); - if (result != (PartGroup *)NULL) { + if (result != nullptr) { return result; } } - return (PartGroup *)NULL; + return nullptr; } // An STL object to sort a list of children into alphabetical order. @@ -163,7 +165,7 @@ public: */ void PartGroup:: sort_descendants() { - stable_sort(_children.begin(), _children.end(), PartGroupAlphabeticalOrder()); + std::stable_sort(_children.begin(), _children.end(), PartGroupAlphabeticalOrder()); Children::iterator ci; for (ci = _children.begin(); ci != _children.end(); ++ci) { @@ -243,7 +245,7 @@ clear_forced_channel() { */ AnimChannelBase *PartGroup:: get_forced_channel() const { - return NULL; + return nullptr; } @@ -314,14 +316,14 @@ check_hierarchy(const AnimGroup *anim, const PartGroup *, // to differ meaninglessly here. Any differences here remain // unreported. if (anim->get_num_children() == get_num_children() + 1 && - anim->get_child_named("morph") != NULL && - get_child_named("morph") == NULL) { + anim->get_child_named("morph") != nullptr && + get_child_named("morph") == nullptr) { // Anim has "morph" and model does not, but there are no other // differences. } else if (get_num_children() == anim->get_num_children() + 1 && - get_child_named("morph") != NULL && - anim->get_child_named("morph") == NULL) { + get_child_named("morph") != nullptr && + anim->get_child_named("morph") == nullptr) { // Model has "morph" and anim does not, but there are no other // differences. @@ -562,7 +564,7 @@ bind_hierarchy(AnimGroup *anim, int channel_index, int &joint_index, int i = 0, j = 0; int part_num_children = get_num_children(); - int anim_num_children = (anim == NULL) ? 0 : anim->get_num_children(); + int anim_num_children = (anim == nullptr) ? 0 : anim->get_num_children(); while (i < part_num_children && j < anim_num_children) { PartGroup *pc = get_child(i); @@ -570,7 +572,7 @@ bind_hierarchy(AnimGroup *anim, int channel_index, int &joint_index, if (pc->get_name() < ac->get_name()) { // Here's a part, not in the anim. Bind it to the special NULL anim. - pc->bind_hierarchy(NULL, channel_index, joint_index, is_included, + pc->bind_hierarchy(nullptr, channel_index, joint_index, is_included, bound_joints, subset); i++; @@ -590,7 +592,7 @@ bind_hierarchy(AnimGroup *anim, int channel_index, int &joint_index, // Now pick up any more parts, not in the anim. while (i < part_num_children) { PartGroup *pc = get_child(i); - pc->bind_hierarchy(NULL, channel_index, joint_index, is_included, + pc->bind_hierarchy(nullptr, channel_index, joint_index, is_included, bound_joints, subset); i++; } @@ -652,7 +654,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { _children.reserve(num_children); for (int i = 0; i < num_children; i++) { manager->read_pointer(scan); - _children.push_back(NULL); + _children.push_back(nullptr); } } diff --git a/panda/src/chan/partGroup.h b/panda/src/chan/partGroup.h index ae5f919b7c..0dd9f8c7dd 100644 --- a/panda/src/chan/partGroup.h +++ b/panda/src/chan/partGroup.h @@ -55,12 +55,12 @@ protected: // The default constructor is protected: don't try to create a PartGroup // without a parent. To create a PartGroup hierarchy, you must first create // a PartBundle, and use that as the parent of any subsequent children. - INLINE PartGroup(const string &name = ""); + INLINE PartGroup(const std::string &name = ""); INLINE PartGroup(const PartGroup ©); PUBLISHED: // This is the normal PartGroup constructor. - explicit PartGroup(PartGroup *parent, const string &name); + explicit PartGroup(PartGroup *parent, const std::string &name); virtual ~PartGroup(); virtual bool is_character_joint() const; @@ -71,8 +71,8 @@ PUBLISHED: PartGroup *get_child(int n) const; MAKE_SEQ(get_children, get_num_children, get_child); - PartGroup *get_child_named(const string &name) const; - PartGroup *find_child(const string &name) const; + PartGroup *get_child_named(const std::string &name) const; + PartGroup *find_child(const std::string &name) const; void sort_descendants(); MAKE_SEQ_PROPERTY(children, get_num_children, get_child); @@ -84,8 +84,8 @@ PUBLISHED: virtual bool clear_forced_channel(); virtual AnimChannelBase *get_forced_channel() const; - virtual void write(ostream &out, int indent_level) const; - virtual void write_with_value(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; + virtual void write_with_value(std::ostream &out, int indent_level) const; public: virtual TypeHandle get_value_type() const; @@ -101,8 +101,8 @@ public: virtual void determine_effective_channels(const CycleData *root_cdata); protected: - void write_descendants(ostream &out, int indent_level) const; - void write_descendants_with_value(ostream &out, int indent_level) const; + void write_descendants(std::ostream &out, int indent_level) const; + void write_descendants_with_value(std::ostream &out, int indent_level) const; virtual void pick_channel_index(plist &holes, int &next) const; virtual void bind_hierarchy(AnimGroup *anim, int channel_index, diff --git a/panda/src/chan/partSubset.cxx b/panda/src/chan/partSubset.cxx index 6e88cce020..5e2a6c5831 100644 --- a/panda/src/chan/partSubset.cxx +++ b/panda/src/chan/partSubset.cxx @@ -89,7 +89,7 @@ append(const PartSubset &other) { * */ void PartSubset:: -output(ostream &out) const { +output(std::ostream &out) const { if (_include_joints.empty() && _exclude_joints.empty()) { out << "PartSubset, empty"; } else { @@ -120,7 +120,7 @@ is_include_empty() const { * false otherwise. */ bool PartSubset:: -matches_include(const string &joint_name) const { +matches_include(const std::string &joint_name) const { Joints::const_iterator ji; for (ji = _include_joints.begin(); ji != _include_joints.end(); ++ji) { if ((*ji).matches(joint_name)) { @@ -137,7 +137,7 @@ matches_include(const string &joint_name) const { * false otherwise. */ bool PartSubset:: -matches_exclude(const string &joint_name) const { +matches_exclude(const std::string &joint_name) const { Joints::const_iterator ji; for (ji = _exclude_joints.begin(); ji != _exclude_joints.end(); ++ji) { if ((*ji).matches(joint_name)) { diff --git a/panda/src/chan/partSubset.h b/panda/src/chan/partSubset.h index 93e7bda47f..853849c5ea 100644 --- a/panda/src/chan/partSubset.h +++ b/panda/src/chan/partSubset.h @@ -33,11 +33,11 @@ PUBLISHED: void append(const PartSubset &other); - void output(ostream &out) const; + void output(std::ostream &out) const; bool is_include_empty() const; - bool matches_include(const string &joint_name) const; - bool matches_exclude(const string &joint_name) const; + bool matches_include(const std::string &joint_name) const; + bool matches_exclude(const std::string &joint_name) const; private: typedef pvector Joints; @@ -45,7 +45,7 @@ private: Joints _exclude_joints; }; -INLINE ostream &operator << (ostream &out, const PartSubset &subset) { +INLINE std::ostream &operator << (std::ostream &out, const PartSubset &subset) { subset.output(out); return out; } diff --git a/panda/src/char/character.cxx b/panda/src/char/character.cxx index ed28ac491e..0e2655de54 100644 --- a/panda/src/char/character.cxx +++ b/panda/src/char/character.cxx @@ -73,7 +73,7 @@ Character(const Character ©, bool copy_bundles) : * */ Character:: -Character(const string &name) : +Character(const std::string &name) : PartBundleNode(name, new CharacterJointBundle(name)), _joints_pcollector(PStatCollector(_animation_pcollector, name), "Joints"), _skinning_pcollector(PStatCollector(_animation_pcollector, name), "Vertices") @@ -355,16 +355,16 @@ clear_lod_animation() { * to a slider. */ CharacterJoint *Character:: -find_joint(const string &name) const { +find_joint(const std::string &name) const { int num_bundles = get_num_bundles(); for (int i = 0; i < num_bundles; ++i) { PartGroup *part = get_bundle(i)->find_child(name); - if (part != (PartGroup *)NULL && part->is_character_joint()) { + if (part != nullptr && part->is_character_joint()) { return DCAST(CharacterJoint, part); } } - return NULL; + return nullptr; } /** @@ -373,17 +373,17 @@ find_joint(const string &name) const { * to a joint. */ CharacterSlider *Character:: -find_slider(const string &name) const { +find_slider(const std::string &name) const { int num_bundles = get_num_bundles(); for (int i = 0; i < num_bundles; ++i) { PartGroup *part = get_bundle(i)->find_child(name); - if (part != (PartGroup *)NULL && + if (part != nullptr && part->is_of_type(CharacterSlider::get_class_type())) { return DCAST(CharacterSlider, part); } } - return NULL; + return nullptr; } /** @@ -391,7 +391,7 @@ find_slider(const string &name) const { * structure, to the indicated output stream. */ void Character:: -write_parts(ostream &out) const { +write_parts(std::ostream &out) const { int num_bundles = get_num_bundles(); for (int i = 0; i < num_bundles; ++i) { get_bundle(i)->write(out, 0); @@ -404,7 +404,7 @@ write_parts(ostream &out) const { * stream. */ void Character:: -write_part_values(ostream &out) const { +write_part_values(std::ostream &out) const { int num_bundles = get_num_bundles(); for (int i = 0; i < num_bundles; ++i) { get_bundle(i)->write_with_value(out, 0); @@ -644,7 +644,7 @@ r_merge_bundles(Character::JointMap &joint_map, // Since the old_joint will be getting dropped, reset its character // reference. - old_joint->_character = NULL; + old_joint->_character = nullptr; // Copy any _net_transform and _local_transform operations to the new // joint. @@ -671,7 +671,7 @@ r_merge_bundles(Character::JointMap &joint_map, int new_num_children = new_group->get_num_children(); PartGroup::Children new_children(PartGroup::get_class_type()); - new_children.reserve(max(old_num_children, new_num_children)); + new_children.reserve(std::max(old_num_children, new_num_children)); while (i < old_num_children && j < new_num_children) { PartGroup *pc = old_group->get_child(i); @@ -929,8 +929,8 @@ CPT(TransformTable) Character:: redirect_transform_table(const TransformTable *source, const Character::JointMap &joint_map, Character::GeomJointMap &gjmap) { - if (source == (TransformTable *)NULL) { - return NULL; + if (source == nullptr) { + return nullptr; } PT(TransformTable) dest = new TransformTable(*source); @@ -939,7 +939,7 @@ redirect_transform_table(const TransformTable *source, for (int i = 0; i < num_transforms; ++i) { const VertexTransform *vt = dest->get_transform(i); PT(JointVertexTransform) new_jvt = redirect_joint(vt, joint_map, gjmap); - if (new_jvt != (JointVertexTransform *)NULL) { + if (new_jvt != nullptr) { dest->set_transform(i, new_jvt); } } @@ -955,8 +955,8 @@ CPT(TransformBlendTable) Character:: redirect_transform_blend_table(const TransformBlendTable *source, const Character::JointMap &joint_map, Character::GeomJointMap &gjmap) { - if (source == (TransformBlendTable *)NULL) { - return NULL; + if (source == nullptr) { + return nullptr; } PT(TransformBlendTable) dest = new TransformBlendTable(*source); @@ -968,7 +968,7 @@ redirect_transform_blend_table(const TransformBlendTable *source, for (int j = 0; j < num_transforms; ++j) { const VertexTransform *vt = blend.get_transform(j); PT(JointVertexTransform) new_jvt = redirect_joint(vt, joint_map, gjmap); - if (new_jvt != (JointVertexTransform *)NULL) { + if (new_jvt != nullptr) { blend.set_transform(j, new_jvt); } } @@ -985,8 +985,8 @@ redirect_transform_blend_table(const TransformBlendTable *source, CPT(SliderTable) Character:: redirect_slider_table(const SliderTable *source, Character::GeomSliderMap &gsmap) { - if (source == (SliderTable *)NULL) { - return NULL; + if (source == nullptr) { + return nullptr; } PT(SliderTable) dest = new SliderTable(*source); @@ -995,7 +995,7 @@ redirect_slider_table(const SliderTable *source, for (int i = 0; i < num_sliders; ++i) { const VertexSlider *vs = dest->get_slider(i); PT(CharacterVertexSlider) new_cvs = redirect_slider(vs, gsmap); - if (new_cvs != (CharacterVertexSlider *)NULL) { + if (new_cvs != nullptr) { dest->set_slider(i, new_cvs); } } @@ -1057,7 +1057,7 @@ redirect_slider(const VertexSlider *vs, Character::GeomSliderMap &gsmap) { if (vs->is_of_type(CharacterVertexSlider::get_class_type())) { const CharacterVertexSlider *cvs = DCAST(CharacterVertexSlider, vs); CharacterSlider *slider = find_slider(cvs->get_char_slider()->get_name()); - if (slider != (CharacterSlider *)NULL) { + if (slider != nullptr) { new_cvs = new CharacterVertexSlider(slider); } } @@ -1081,7 +1081,7 @@ r_clear_joint_characters(PartGroup *part) { // listed within more than one Character node, but it can only point back // to one of them. if (joint->get_character() == this) { - joint->set_character(NULL); + joint->set_character(nullptr); } } diff --git a/panda/src/char/character.h b/panda/src/char/character.h index 80492df93c..a7c6c79f13 100644 --- a/panda/src/char/character.h +++ b/panda/src/char/character.h @@ -40,7 +40,7 @@ protected: Character(const Character ©, bool copy_bundles); PUBLISHED: - explicit Character(const string &name); + explicit Character(const std::string &name); virtual ~Character(); public: @@ -68,11 +68,11 @@ PUBLISHED: PN_stdfloat delay_factor); void clear_lod_animation(); - CharacterJoint *find_joint(const string &name) const; - CharacterSlider *find_slider(const string &name) const; + CharacterJoint *find_joint(const std::string &name) const; + CharacterSlider *find_slider(const std::string &name) const; - void write_parts(ostream &out) const; - void write_part_values(ostream &out) const; + void write_parts(std::ostream &out) const; + void write_part_values(std::ostream &out) const; void update_to_now(); void update(); diff --git a/panda/src/char/characterJoint.cxx b/panda/src/char/characterJoint.cxx index 6ce5b0be88..7e3e1c9b9a 100644 --- a/panda/src/char/characterJoint.cxx +++ b/panda/src/char/characterJoint.cxx @@ -27,7 +27,7 @@ TypeHandle CharacterJoint::_type_handle; */ CharacterJoint:: CharacterJoint() : - _character(NULL) + _character(nullptr) { } @@ -37,7 +37,7 @@ CharacterJoint() : CharacterJoint:: CharacterJoint(const CharacterJoint ©) : MovingPartMatrix(copy), - _character(NULL), + _character(nullptr), _net_transform(copy._net_transform), _initial_net_transform_inverse(copy._initial_net_transform_inverse), _skinning_matrix(copy._skinning_matrix) @@ -50,7 +50,7 @@ CharacterJoint(const CharacterJoint ©) : */ CharacterJoint:: CharacterJoint(Character *character, - PartBundle *root, PartGroup *parent, const string &name, + PartBundle *root, PartGroup *parent, const std::string &name, const LMatrix4 &default_value) : MovingPartMatrix(parent, name, default_value), _character(character) @@ -75,7 +75,7 @@ CharacterJoint(Character *character, CharacterJoint:: ~CharacterJoint() { nassertv(_vertex_transforms.empty()); - nassertv(_character == (Character *)NULL); + nassertv(_character == nullptr); } /** @@ -110,7 +110,7 @@ make_copy() const { bool CharacterJoint:: update_internals(PartBundle *root, PartGroup *parent, bool self_changed, bool parent_changed, Thread *current_thread) { - nassertr(parent != (PartGroup *)NULL, false); + nassertr(parent != nullptr, false); bool net_changed = false; if (parent->is_character_joint()) { @@ -194,7 +194,7 @@ do_xform(const LMatrix4 &mat, const LMatrix4 &inv_mat) { */ bool CharacterJoint:: add_net_transform(PandaNode *node) { - if (_character != (Character *)NULL) { + if (_character != nullptr) { node->set_effect(CharacterJointEffect::make(_character)); } CPT(TransformState) t = TransformState::make_mat(_net_transform); @@ -213,8 +213,8 @@ add_net_transform(PandaNode *node) { bool CharacterJoint:: remove_net_transform(PandaNode *node) { CPT(RenderEffect) effect = node->get_effect(CharacterJointEffect::get_class_type()); - if (effect != (RenderEffect *)NULL && - DCAST(CharacterJointEffect, effect)->get_character() == _character) { + if (effect != nullptr && + DCAST(CharacterJointEffect, effect)->matches_character(_character)) { node->clear_effect(CharacterJointEffect::get_class_type()); } @@ -243,8 +243,8 @@ clear_net_transforms() { PandaNode *node = *ai; CPT(RenderEffect) effect = node->get_effect(CharacterJointEffect::get_class_type()); - if (effect != (RenderEffect *)NULL && - DCAST(CharacterJointEffect, effect)->get_character() == _character) { + if (effect != nullptr && + DCAST(CharacterJointEffect, effect)->matches_character(_character)) { node->clear_effect(CharacterJointEffect::get_class_type()); } } @@ -286,7 +286,7 @@ get_net_transforms() { */ bool CharacterJoint:: add_local_transform(PandaNode *node) { - if (_character != (Character *)NULL) { + if (_character != nullptr) { node->set_effect(CharacterJointEffect::make(_character)); } CPT(TransformState) t = TransformState::make_mat(_value); @@ -305,8 +305,8 @@ add_local_transform(PandaNode *node) { bool CharacterJoint:: remove_local_transform(PandaNode *node) { CPT(RenderEffect) effect = node->get_effect(CharacterJointEffect::get_class_type()); - if (effect != (RenderEffect *)NULL && - DCAST(CharacterJointEffect, effect)->get_character() == _character) { + if (effect != nullptr && + DCAST(CharacterJointEffect, effect)->matches_character(_character)) { node->clear_effect(CharacterJointEffect::get_class_type()); } @@ -335,8 +335,8 @@ clear_local_transforms() { PandaNode *node = *ai; CPT(RenderEffect) effect = node->get_effect(CharacterJointEffect::get_class_type()); - if (effect != (RenderEffect *)NULL && - DCAST(CharacterJointEffect, effect)->get_character() == _character) { + if (effect != nullptr && + DCAST(CharacterJointEffect, effect)->matches_character(_character)) { node->clear_effect(CharacterJointEffect::get_class_type()); } } @@ -401,7 +401,7 @@ void CharacterJoint:: set_character(Character *character) { if (character != _character) { - if (character != (Character *)NULL) { + if (character != nullptr) { // Change or set a _character pointer on each joint's exposed node. NodeList::iterator ai; for (ai = _net_transform_nodes.begin(); @@ -426,8 +426,8 @@ set_character(Character *character) { PandaNode *node = *ai; CPT(RenderEffect) effect = node->get_effect(CharacterJointEffect::get_class_type()); - if (effect != (RenderEffect *)NULL && - DCAST(CharacterJointEffect, effect)->get_character() == _character) { + if (effect != nullptr && + DCAST(CharacterJointEffect, effect)->matches_character(_character)) { node->clear_effect(CharacterJointEffect::get_class_type()); } } @@ -437,8 +437,8 @@ set_character(Character *character) { PandaNode *node = *ai; CPT(RenderEffect) effect = node->get_effect(CharacterJointEffect::get_class_type()); - if (effect != (RenderEffect *)NULL && - DCAST(CharacterJointEffect, effect)->get_character() == _character) { + if (effect != nullptr && + DCAST(CharacterJointEffect, effect)->matches_character(_character)) { node->clear_effect(CharacterJointEffect::get_class_type()); } } @@ -514,7 +514,7 @@ complete_pointers(TypedWritable **p_list, BamReader* manager) { if (manager->get_file_minor_ver() >= 4) { _character = DCAST(Character, p_list[pi++]); } else { - _character = NULL; + _character = nullptr; } int i; diff --git a/panda/src/char/characterJoint.h b/panda/src/char/characterJoint.h index 5da83def66..83d155f184 100644 --- a/panda/src/char/characterJoint.h +++ b/panda/src/char/characterJoint.h @@ -36,7 +36,7 @@ protected: PUBLISHED: explicit CharacterJoint(Character *character, PartBundle *root, - PartGroup *parent, const string &name, + PartGroup *parent, const std::string &name, const LMatrix4 &default_value); virtual ~CharacterJoint(); diff --git a/panda/src/char/characterJointBundle.cxx b/panda/src/char/characterJointBundle.cxx index e6bf4061a7..86a43f7e13 100644 --- a/panda/src/char/characterJointBundle.cxx +++ b/panda/src/char/characterJointBundle.cxx @@ -24,7 +24,7 @@ TypeHandle CharacterJointBundle::_type_handle; * Character node will automatically create one for itself. */ CharacterJointBundle:: -CharacterJointBundle(const string &name) : PartBundle(name) { +CharacterJointBundle(const std::string &name) : PartBundle(name) { } /** @@ -78,7 +78,7 @@ remove_node(PartBundleNode *node) { */ void CharacterJointBundle:: r_set_character(PartGroup *group, Character *character) { - if (group == (PartGroup *)NULL) { + if (group == nullptr) { // This might happen if we are in the middle of reading the Character's // hierarchy from the bam file. return; diff --git a/panda/src/char/characterJointBundle.h b/panda/src/char/characterJointBundle.h index 4c68fb9b3d..e1c93e1842 100644 --- a/panda/src/char/characterJointBundle.h +++ b/panda/src/char/characterJointBundle.h @@ -30,7 +30,7 @@ protected: INLINE CharacterJointBundle(const CharacterJointBundle ©); PUBLISHED: - explicit CharacterJointBundle(const string &name = ""); + explicit CharacterJointBundle(const std::string &name = ""); virtual ~CharacterJointBundle(); PUBLISHED: diff --git a/panda/src/char/characterJointEffect.I b/panda/src/char/characterJointEffect.I index fb911569b3..e4d596dafe 100644 --- a/panda/src/char/characterJointEffect.I +++ b/panda/src/char/characterJointEffect.I @@ -23,11 +23,17 @@ CharacterJointEffect() { * Returns the Character that will get update() called on it when this node's * relative transform is queried, or NULL if there is no such character. */ -INLINE Character *CharacterJointEffect:: +INLINE PT(Character) CharacterJointEffect:: get_character() const { - if (_character.is_valid_pointer()) { - return _character; - } else { - return NULL; - } + return _character.lock(); +} + +/** + * Returns true if this CharacterJointEffect contains the given Character. + * This exists because it is faster to check than get_character() and can even + * be called while the Character is destructing. + */ +INLINE bool CharacterJointEffect:: +matches_character(Character *character) const { + return _character == character; } diff --git a/panda/src/char/characterJointEffect.cxx b/panda/src/char/characterJointEffect.cxx index 33441e35c2..b4bc263c20 100644 --- a/panda/src/char/characterJointEffect.cxx +++ b/panda/src/char/characterJointEffect.cxx @@ -87,10 +87,11 @@ safe_to_combine() const { * */ void CharacterJointEffect:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type(); - if (_character.is_valid_pointer()) { - out << "(" << _character->get_name() << ")"; + PT(Character) character = get_character(); + if (character != nullptr) { + out << "(" << character->get_name() << ")"; } else { out << "(**invalid**)"; } @@ -122,8 +123,8 @@ void CharacterJointEffect:: cull_callback(CullTraverser *trav, CullTraverserData &data, CPT(TransformState) &node_transform, CPT(RenderState) &) const { - if (_character.is_valid_pointer()) { - _character->update(); + if (auto character = _character.lock()) { + character->update(); } node_transform = data.node()->get_transform(); } @@ -150,8 +151,8 @@ void CharacterJointEffect:: adjust_transform(CPT(TransformState) &net_transform, CPT(TransformState) &node_transform, const PandaNode *node) const { - if (_character.is_valid_pointer()) { - _character->update(); + if (auto character = _character.lock()) { + character->update(); } node_transform = node->get_transform(); } @@ -202,11 +203,8 @@ void CharacterJointEffect:: write_datagram(BamWriter *manager, Datagram &dg) { RenderEffect::write_datagram(manager, dg); - if (_character.is_valid_pointer()) { - manager->write_pointer(dg, _character); - } else { - manager->write_pointer(dg, NULL); - } + PT(Character) character = get_character(); + manager->write_pointer(dg, character); } /** diff --git a/panda/src/char/characterJointEffect.h b/panda/src/char/characterJointEffect.h index 0df4cea6fd..8b6e11e923 100644 --- a/panda/src/char/characterJointEffect.h +++ b/panda/src/char/characterJointEffect.h @@ -38,12 +38,14 @@ private: PUBLISHED: static CPT(RenderEffect) make(Character *character); - INLINE Character *get_character() const; + INLINE PT(Character) get_character() const; public: + INLINE bool matches_character(Character *character) const; + virtual bool safe_to_transform() const; virtual bool safe_to_combine() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; virtual bool has_cull_callback() const; virtual void cull_callback(CullTraverser *trav, CullTraverserData &data, diff --git a/panda/src/char/characterSlider.cxx b/panda/src/char/characterSlider.cxx index 824b7e2737..b4ced5e782 100644 --- a/panda/src/char/characterSlider.cxx +++ b/panda/src/char/characterSlider.cxx @@ -40,7 +40,7 @@ CharacterSlider(const CharacterSlider ©) : * */ CharacterSlider:: -CharacterSlider(PartGroup *parent, const string &name) +CharacterSlider(PartGroup *parent, const std::string &name) : MovingPartScalar(parent, name) { } diff --git a/panda/src/char/characterSlider.h b/panda/src/char/characterSlider.h index fe7e38945e..9871095afd 100644 --- a/panda/src/char/characterSlider.h +++ b/panda/src/char/characterSlider.h @@ -31,9 +31,10 @@ protected: CharacterSlider(const CharacterSlider ©); PUBLISHED: - explicit CharacterSlider(PartGroup *parent, const string &name); + explicit CharacterSlider(PartGroup *parent, const std::string &name); virtual ~CharacterSlider(); +public: virtual PartGroup *make_copy() const; virtual bool update_internals(PartBundle *root, PartGroup *parent, diff --git a/panda/src/char/jointVertexTransform.cxx b/panda/src/char/jointVertexTransform.cxx index 5212aa6cd9..5f60777ff1 100644 --- a/panda/src/char/jointVertexTransform.cxx +++ b/panda/src/char/jointVertexTransform.cxx @@ -83,7 +83,7 @@ accumulate_matrix(LMatrix4 &accum, PN_stdfloat weight) const { * */ void JointVertexTransform:: -output(ostream &out) const { +output(std::ostream &out) const { out << _joint->get_name(); } diff --git a/panda/src/char/jointVertexTransform.h b/panda/src/char/jointVertexTransform.h index 1be097eba6..ee8b3aafa6 100644 --- a/panda/src/char/jointVertexTransform.h +++ b/panda/src/char/jointVertexTransform.h @@ -44,7 +44,7 @@ PUBLISHED: virtual void mult_matrix(LMatrix4 &result, const LMatrix4 &previous) const; virtual void accumulate_matrix(LMatrix4 &accum, PN_stdfloat weight) const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: PT(CharacterJoint) _joint; diff --git a/panda/src/cocoadisplay/cocoaGraphicsBuffer.h b/panda/src/cocoadisplay/cocoaGraphicsBuffer.h index ab666b6f75..3167d2c02f 100644 --- a/panda/src/cocoadisplay/cocoaGraphicsBuffer.h +++ b/panda/src/cocoadisplay/cocoaGraphicsBuffer.h @@ -24,7 +24,7 @@ class CocoaGraphicsBuffer : public GLGraphicsBuffer { public: CocoaGraphicsBuffer(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/cocoadisplay/cocoaGraphicsBuffer.mm b/panda/src/cocoadisplay/cocoaGraphicsBuffer.mm index ea6fb61e4e..f45837ed87 100644 --- a/panda/src/cocoadisplay/cocoaGraphicsBuffer.mm +++ b/panda/src/cocoadisplay/cocoaGraphicsBuffer.mm @@ -25,7 +25,7 @@ TypeHandle CocoaGraphicsBuffer::_type_handle; */ CocoaGraphicsBuffer:: CocoaGraphicsBuffer(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -105,6 +105,12 @@ open_buffer() { } } + if (cocoagsg->_context == nil) { + // Could not obtain a proper context. + _gsg.clear(); + return false; + } + FrameBufferProperties desired_props(_fb_properties); // Lock the context, so we can safely operate on it. diff --git a/panda/src/cocoadisplay/cocoaGraphicsPipe.h b/panda/src/cocoadisplay/cocoaGraphicsPipe.h index 6f2f863e9c..cc8c8142d5 100644 --- a/panda/src/cocoadisplay/cocoaGraphicsPipe.h +++ b/panda/src/cocoadisplay/cocoaGraphicsPipe.h @@ -40,14 +40,14 @@ public: INLINE CGDirectDisplayID get_display_id() const; - virtual string get_interface_name() const; + virtual std::string get_interface_name() const; static PT(GraphicsPipe) pipe_constructor(); public: virtual PreferredWindowThread get_preferred_window_thread() const; protected: - virtual PT(GraphicsOutput) make_output(const string &name, + virtual PT(GraphicsOutput) make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/cocoadisplay/cocoaGraphicsPipe.mm b/panda/src/cocoadisplay/cocoaGraphicsPipe.mm index 5430373c55..91bd0fbbb9 100644 --- a/panda/src/cocoadisplay/cocoaGraphicsPipe.mm +++ b/panda/src/cocoadisplay/cocoaGraphicsPipe.mm @@ -37,7 +37,7 @@ CocoaGraphicsPipe(CGDirectDisplayID display) : _display(display) { _supported_types = OT_window | OT_buffer | OT_texture_buffer; _is_valid = true; - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + [[NSAutoreleasePool alloc] init]; // Put Cocoa into thread-safe mode by spawning a thread which immediately // exits. @@ -169,7 +169,7 @@ CocoaGraphicsPipe:: * choose between several possible GraphicsPipes available on a particular * platform, so the name should be meaningful and unique for a given platform. */ -string CocoaGraphicsPipe:: +std::string CocoaGraphicsPipe:: get_interface_name() const { return "OpenGL"; } @@ -199,7 +199,7 @@ CocoaGraphicsPipe::get_preferred_window_thread() const { * Creates a new window on the pipe, if possible. */ PT(GraphicsOutput) CocoaGraphicsPipe:: -make_output(const string &name, +make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/cocoadisplay/cocoaGraphicsStateGuardian.mm b/panda/src/cocoadisplay/cocoaGraphicsStateGuardian.mm index ec25b94486..26d4dbdf71 100644 --- a/panda/src/cocoadisplay/cocoaGraphicsStateGuardian.mm +++ b/panda/src/cocoadisplay/cocoaGraphicsStateGuardian.mm @@ -190,7 +190,7 @@ choose_pixel_format(const FrameBufferProperties &properties, // make it grab one with 8 bits, though. Dirty hack. Needs more research. if (properties.get_alpha_bits() > 0) { attribs.push_back(NSOpenGLPFAAlphaSize); - attribs.push_back(max(8, properties.get_alpha_bits())); + attribs.push_back(std::max(8, properties.get_alpha_bits())); } if (properties.get_multisamples() > 0) { diff --git a/panda/src/cocoadisplay/cocoaGraphicsWindow.h b/panda/src/cocoadisplay/cocoaGraphicsWindow.h index de2bd8d61c..353212f056 100644 --- a/panda/src/cocoadisplay/cocoaGraphicsWindow.h +++ b/panda/src/cocoadisplay/cocoaGraphicsWindow.h @@ -30,7 +30,7 @@ class CocoaGraphicsWindow : public GraphicsWindow { public: CocoaGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/cocoadisplay/cocoaGraphicsWindow.mm b/panda/src/cocoadisplay/cocoaGraphicsWindow.mm index 72c9d57c0f..7d461817f1 100644 --- a/panda/src/cocoadisplay/cocoaGraphicsWindow.mm +++ b/panda/src/cocoadisplay/cocoaGraphicsWindow.mm @@ -50,7 +50,7 @@ TypeHandle CocoaGraphicsWindow::_type_handle; */ CocoaGraphicsWindow:: CocoaGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -362,6 +362,13 @@ open_window() { } } + if (cocoagsg->_context == nil) { + // Could not obtain a proper context. + _gsg.clear(); + close_window(); + return false; + } + // Fill in the blanks. if (!_properties.has_origin()) { _properties.set_origin(-2, -2); @@ -405,7 +412,7 @@ open_window() { cocoadisplay_cat.info() << "os_handle type " << os_handle->get_type() << "\n"; - void *ptr_handle; + void *ptr_handle = nullptr; // Depending on whether the window handle comes from a Carbon or a Cocoa // application, it could be either a HIViewRef or an NSView or NSWindow. @@ -1286,7 +1293,7 @@ load_image(const Filename &filename) { if (vfile == NULL) { return nil; } - istream *str = vfile->open_read_file(true); + std::istream *str = vfile->open_read_file(true); if (str == NULL) { cocoadisplay_cat.error() << "Could not open file " << filename << " for reading\n"; @@ -1442,7 +1449,7 @@ handle_foreground_event(bool foreground) { */ bool CocoaGraphicsWindow:: handle_close_request() { - string close_request_event = get_close_request_event(); + std::string close_request_event = get_close_request_event(); if (!close_request_event.empty()) { // In this case, the app has indicated a desire to intercept the request // and process it directly. diff --git a/panda/src/cocoadisplay/config_cocoadisplay.h b/panda/src/cocoadisplay/config_cocoadisplay.h index a5ed970b8f..43a0e057c3 100644 --- a/panda/src/cocoadisplay/config_cocoadisplay.h +++ b/panda/src/cocoadisplay/config_cocoadisplay.h @@ -18,8 +18,8 @@ #include "notifyCategoryProxy.h" #include "configVariableBool.h" -NotifyCategoryDecl(cocoadisplay, EXPCL_PANDAGL, EXPTP_PANDAGL); +NotifyCategoryDecl(cocoadisplay, EXPCL_PANDA_COCOADISPLAY, EXPTP_PANDA_COCOADISPLAY); -extern EXPCL_PANDAGL void init_libcocoadisplay(); +extern EXPCL_PANDA_COCOADISPLAY void init_libcocoadisplay(); #endif diff --git a/panda/src/cocoadisplay/config_cocoadisplay.mm b/panda/src/cocoadisplay/config_cocoadisplay.mm index c88177cf66..a41e5bc579 100644 --- a/panda/src/cocoadisplay/config_cocoadisplay.mm +++ b/panda/src/cocoadisplay/config_cocoadisplay.mm @@ -20,8 +20,8 @@ #include "dconfig.h" #include "pandaSystem.h" -#if !defined(CPPPARSER) && !defined(BUILDING_PANDAGL) - #error Buildsystem error: BUILDING_PANDAGL not defined +#if !defined(CPPPARSER) && !defined(BUILDING_PANDA_COCOADISPLAY) + #error Buildsystem error: BUILDING_PANDA_COCOADISPLAY not defined #endif Configure(config_cocoadisplay); diff --git a/panda/src/collada/colladaBindMaterial.cxx b/panda/src/collada/colladaBindMaterial.cxx index 768e31a46d..90ea8a21cf 100644 --- a/panda/src/collada/colladaBindMaterial.cxx +++ b/panda/src/collada/colladaBindMaterial.cxx @@ -37,8 +37,8 @@ */ CPT(RenderState) ColladaBindMaterial:: get_material(const ColladaPrimitive *prim) const { - if (prim == NULL || _states.count(prim->get_material()) == 0) { - return NULL; + if (prim == nullptr || _states.count(prim->get_material()) == 0) { + return nullptr; } return _states.find(prim->get_material())->second; } @@ -48,9 +48,9 @@ get_material(const ColladaPrimitive *prim) const { * found. */ CPT(RenderState) ColladaBindMaterial:: -get_material(const string &symbol) const { +get_material(const std::string &symbol) const { if (_states.count(symbol) == 0) { - return NULL; + return nullptr; } return _states.find(symbol)->second; } @@ -74,10 +74,10 @@ load_bind_material(domBind_material &bind_mat) { void ColladaBindMaterial:: load_instance_material(domInstance_material &inst) { domMaterialRef mat = daeSafeCast (inst.getTarget().getElement()); - nassertv(mat != NULL); + nassertv(mat != nullptr); domInstance_effectRef einst = mat->getInstance_effect(); - nassertv(einst != NULL); + nassertv(einst != nullptr); domInstance_effect::domSetparam_Array &setparams = einst->getSetparam_array(); diff --git a/panda/src/collada/colladaBindMaterial.h b/panda/src/collada/colladaBindMaterial.h index 18cf5b80a8..2c56f77c78 100644 --- a/panda/src/collada/colladaBindMaterial.h +++ b/panda/src/collada/colladaBindMaterial.h @@ -29,13 +29,13 @@ class domInstance_material; class ColladaBindMaterial { public: CPT(RenderState) get_material(const ColladaPrimitive *prim) const; - CPT(RenderState) get_material(const string &symbol) const; + CPT(RenderState) get_material(const std::string &symbol) const; void load_bind_material(domBind_material &bind_mat); void load_instance_material(domInstance_material &inst); private: - pmap _states; + pmap _states; }; #endif diff --git a/panda/src/collada/colladaInput.cxx b/panda/src/collada/colladaInput.cxx index b0f77ccd4e..09ce788655 100644 --- a/panda/src/collada/colladaInput.cxx +++ b/panda/src/collada/colladaInput.cxx @@ -37,8 +37,8 @@ * Pretty obvious what this does. */ ColladaInput:: -ColladaInput(const string &semantic) : - _column_name (NULL), +ColladaInput(const std::string &semantic) : + _column_name (nullptr), _semantic (semantic), _offset (0), _have_set (false), @@ -69,14 +69,14 @@ ColladaInput(const string &semantic) : * Pretty obvious what this does. */ ColladaInput:: -ColladaInput(const string &semantic, unsigned int set) : - _column_name (NULL), +ColladaInput(const std::string &semantic, unsigned int set) : + _column_name (nullptr), _semantic (semantic), _offset (0), _have_set (true), _set (set) { - ostringstream setstr; + std::ostringstream setstr; setstr << _set; if (semantic == "POSITION") { @@ -107,7 +107,7 @@ ColladaInput(const string &semantic, unsigned int set) : ColladaInput *ColladaInput:: from_dom(domInput_local_offset &input) { // If we already loaded it before, use that. - if (input.getUserData() != NULL) { + if (input.getUserData() != nullptr) { return (ColladaInput *) input.getUserData(); } @@ -117,7 +117,7 @@ from_dom(domInput_local_offset &input) { // If this has the VERTEX semantic, it points to a element. if (new_input->is_vertex_source()) { domVertices *verts = daeSafeCast (input.getSource().getElement()); - nassertr(verts != NULL, NULL); + nassertr(verts != nullptr, nullptr); daeTArray &inputs = verts->getInput_array(); // Iterate over the elements in . @@ -127,7 +127,7 @@ from_dom(domInput_local_offset &input) { } } else { domSource *source = daeSafeCast (input.getSource().getElement()); - nassertr(source != NULL, NULL); + nassertr(source != nullptr, nullptr); new_input->read_data(*source); } @@ -141,17 +141,17 @@ from_dom(domInput_local_offset &input) { ColladaInput *ColladaInput:: from_dom(domInput_local &input) { // If we already loaded it before, use that. - if (input.getUserData() != NULL) { + if (input.getUserData() != nullptr) { return (ColladaInput *) input.getUserData(); } ColladaInput *new_input = new ColladaInput(input.getSemantic()); new_input->_offset = 0; - nassertr (!new_input->is_vertex_source(), NULL); + nassertr (!new_input->is_vertex_source(), nullptr); domSource *source = daeSafeCast (input.getSource().getElement()); - nassertr(source != NULL, NULL); + nassertr(source != nullptr, nullptr); new_input->read_data(*source); return new_input; @@ -174,7 +174,7 @@ make_vertex_columns(GeomVertexArrayFormat *format) const { return counter; } - nassertr(_column_name != NULL, 0); + nassertr(_column_name != nullptr, 0); format->add_column(_column_name, _num_bound_params, GeomEnums::NT_stdfloat, _column_contents); return 1; @@ -189,7 +189,7 @@ read_data(domSource &source) { // Get this, get that domFloat_array* float_array = source.getFloat_array(); - if (float_array == NULL) { + if (float_array == nullptr) { return false; } @@ -246,7 +246,7 @@ write_data(GeomVertexData *vdata, int start_row, domP &p, unsigned int stride) c */ void ColladaInput:: write_data(GeomVertexData *vdata, int start_row, domP &p, unsigned int stride, unsigned int offset) const { - nassertv(_column_name != NULL); + nassertv(_column_name != nullptr); GeomVertexWriter writer (vdata, _column_name); writer.set_row_unsafe(start_row); diff --git a/panda/src/collada/colladaInput.h b/panda/src/collada/colladaInput.h index 53629ecf8d..7df605c73c 100644 --- a/panda/src/collada/colladaInput.h +++ b/panda/src/collada/colladaInput.h @@ -52,8 +52,8 @@ public: INLINE unsigned int get_offset() const; private: - ColladaInput(const string &semantic); - ColladaInput(const string &semantic, unsigned int set); + ColladaInput(const std::string &semantic); + ColladaInput(const std::string &semantic, unsigned int set); bool read_data(domSource &source); void write_data(GeomVertexData *vdata, int start_row, domP &p, unsigned int stride, unsigned int offset) const; @@ -67,7 +67,7 @@ private: unsigned int _num_bound_params; unsigned int _offset; - string _semantic; + std::string _semantic; bool _have_set; unsigned int _set; }; diff --git a/panda/src/collada/colladaLoader.cxx b/panda/src/collada/colladaLoader.cxx index 93749b30b6..1347d492a1 100644 --- a/panda/src/collada/colladaLoader.cxx +++ b/panda/src/collada/colladaLoader.cxx @@ -45,18 +45,18 @@ #define domTargetable_floatRef domTargetableFloatRef #endif -#define TOSTRING(x) (x == NULL ? "" : x) +#define TOSTRING(x) (x == nullptr ? "" : x) /** * */ ColladaLoader:: ColladaLoader() : - _record (NULL), + _record (nullptr), _cs (CS_default), _error (false), - _root (NULL), - _collada (NULL) { + _root (nullptr), + _collada (nullptr) { _dae = new DAE; } @@ -76,7 +76,7 @@ bool ColladaLoader:: read(const Filename &filename) { _filename = filename; - string data; + std::string data; VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); if (!vfs->read_file(_filename, data, true)) { @@ -87,7 +87,7 @@ read(const Filename &filename) { } _collada = _dae->openFromMemory(_filename.to_os_specific(), data.c_str()); - _error = (_collada == NULL); + _error = (_collada == nullptr); return !_error; } @@ -116,7 +116,7 @@ build_graph() { void ColladaLoader:: load_visual_scene(domVisual_scene& scene, PandaNode *parent) { // If we already loaded it before, instantiate the stored node. - if (scene.getUserData() != NULL) { + if (scene.getUserData() != nullptr) { parent->add_child((PandaNode *) scene.getUserData()); return; } @@ -156,7 +156,7 @@ load_visual_scene(domVisual_scene& scene, PandaNode *parent) { void ColladaLoader:: load_node(domNode& node, PandaNode *parent) { // If we already loaded it before, instantiate the stored node. - if (node.getUserData() != NULL) { + if (node.getUserData() != nullptr) { parent->add_child((PandaNode *) node.getUserData()); return; } @@ -243,7 +243,7 @@ load_node(domNode& node, PandaNode *parent) { for (size_t i = 0; i < ctrlinst.getCount(); ++i) { domController* target = daeSafeCast (ctrlinst[i]->getUrl().getElement()); // TODO: implement controllers. For now, let's just read the geometry - if (target->getSkin() != NULL) { + if (target->getSkin() != nullptr) { domGeometry* geom = daeSafeCast (target->getSkin()->getSource().getElement()); // TODO load_geometry(*geom, ctrlinst[i]->getBind_material(), pnode); } @@ -299,7 +299,7 @@ load_tags(domExtra &extra, PandaNode *node) { daeElement &child = *children[c]; if (cmp_nocase(child.getElementName(), "tag") == 0) { - const string &name = child.getAttribute("name"); + const std::string &name = child.getAttribute("name"); if (name.size() > 0) { node->set_tag(name, child.getCharData()); } else { @@ -321,7 +321,7 @@ load_tags(domExtra &extra, PandaNode *node) { void ColladaLoader:: load_camera(domCamera &cam, PandaNode *parent) { // If we already loaded it before, instantiate the stored node. - if (cam.getUserData() != NULL) { + if (cam.getUserData() != nullptr) { parent->add_child((PandaNode *) cam.getUserData()); return; } @@ -335,13 +335,13 @@ load_camera(domCamera &cam, PandaNode *parent) { void ColladaLoader:: load_instance_geometry(domInstance_geometry &inst, PandaNode *parent) { // If we already loaded it before, instantiate the stored node. - if (inst.getUserData() != NULL) { + if (inst.getUserData() != nullptr) { parent->add_child((PandaNode *) inst.getUserData()); return; } domGeometry* geom = daeSafeCast (inst.getUrl().getElement()); - nassertv(geom != NULL); + nassertv(geom != nullptr); // Create the node. PT(GeomNode) gnode = new GeomNode(TOSTRING(geom->getName())); @@ -350,7 +350,7 @@ load_instance_geometry(domInstance_geometry &inst, PandaNode *parent) { domBind_materialRef bind_mat = inst.getBind_material(); ColladaBindMaterial cbm; - if (bind_mat != NULL) { + if (bind_mat != nullptr) { cbm.load_bind_material(*bind_mat); } @@ -370,7 +370,7 @@ load_instance_geometry(domInstance_geometry &inst, PandaNode *parent) { void ColladaLoader:: load_geometry(domGeometry &geom, GeomNode *gnode, ColladaBindMaterial &bind_mat) { domMesh* mesh = geom.getMesh(); - if (mesh == NULL) { + if (mesh == nullptr) { // TODO: support non-mesh geometry. return; } @@ -379,7 +379,7 @@ load_geometry(domGeometry &geom, GeomNode *gnode, ColladaBindMaterial &bind_mat) domLines_Array &lines_array = mesh->getLines_array(); for (size_t i = 0; i < lines_array.getCount(); ++i) { PT(ColladaPrimitive) prim = ColladaPrimitive::from_dom(*lines_array[i]); - if (prim != NULL) { + if (prim != nullptr) { gnode->add_geom(prim->get_geom()); } } @@ -387,7 +387,7 @@ load_geometry(domGeometry &geom, GeomNode *gnode, ColladaBindMaterial &bind_mat) domLinestrips_Array &linestrips_array = mesh->getLinestrips_array(); for (size_t i = 0; i < linestrips_array.getCount(); ++i) { PT(ColladaPrimitive) prim = ColladaPrimitive::from_dom(*linestrips_array[i]); - if (prim != NULL) { + if (prim != nullptr) { gnode->add_geom(prim->get_geom()); } } @@ -395,7 +395,7 @@ load_geometry(domGeometry &geom, GeomNode *gnode, ColladaBindMaterial &bind_mat) domPolygons_Array &polygons_array = mesh->getPolygons_array(); for (size_t i = 0; i < polygons_array.getCount(); ++i) { PT(ColladaPrimitive) prim = ColladaPrimitive::from_dom(*polygons_array[i]); - if (prim != NULL) { + if (prim != nullptr) { gnode->add_geom(prim->get_geom()); } } @@ -403,7 +403,7 @@ load_geometry(domGeometry &geom, GeomNode *gnode, ColladaBindMaterial &bind_mat) domPolylist_Array &polylist_array = mesh->getPolylist_array(); for (size_t i = 0; i < polylist_array.getCount(); ++i) { PT(ColladaPrimitive) prim = ColladaPrimitive::from_dom(*polylist_array[i]); - if (prim != NULL) { + if (prim != nullptr) { gnode->add_geom(prim->get_geom()); } } @@ -411,7 +411,7 @@ load_geometry(domGeometry &geom, GeomNode *gnode, ColladaBindMaterial &bind_mat) domTriangles_Array &triangles_array = mesh->getTriangles_array(); for (size_t i = 0; i < triangles_array.getCount(); ++i) { PT(ColladaPrimitive) prim = ColladaPrimitive::from_dom(*triangles_array[i]); - if (prim != NULL) { + if (prim != nullptr) { gnode->add_geom(prim->get_geom()); } } @@ -419,7 +419,7 @@ load_geometry(domGeometry &geom, GeomNode *gnode, ColladaBindMaterial &bind_mat) domTrifans_Array &trifans_array = mesh->getTrifans_array(); for (size_t i = 0; i < trifans_array.getCount(); ++i) { PT(ColladaPrimitive) prim = ColladaPrimitive::from_dom(*trifans_array[i]); - if (prim != NULL) { + if (prim != nullptr) { gnode->add_geom(prim->get_geom()); } } @@ -427,7 +427,7 @@ load_geometry(domGeometry &geom, GeomNode *gnode, ColladaBindMaterial &bind_mat) domTristrips_Array &tristrips_array = mesh->getTristrips_array(); for (size_t i = 0; i < tristrips_array.getCount(); ++i) { PT(ColladaPrimitive) prim = ColladaPrimitive::from_dom(*tristrips_array[i]); - if (prim != NULL) { + if (prim != nullptr) { gnode->add_geom(prim->get_geom()); } } @@ -439,7 +439,7 @@ load_geometry(domGeometry &geom, GeomNode *gnode, ColladaBindMaterial &bind_mat) void ColladaLoader:: load_light(domLight &light, PandaNode *parent) { // If we already loaded it before, instantiate the stored node. - if (light.getUserData() != NULL) { + if (light.getUserData() != nullptr) { parent->add_child((PandaNode *) light.getUserData()); return; } @@ -449,7 +449,7 @@ load_light(domLight &light, PandaNode *parent) { // Check for an ambient light. domLight::domTechnique_common::domAmbientRef ambient = tc.getAmbient(); - if (ambient != NULL) { + if (ambient != nullptr) { PT(AmbientLight) alight = new AmbientLight(TOSTRING(light.getName())); lnode = DCAST(LightNode, alight); @@ -459,7 +459,7 @@ load_light(domLight &light, PandaNode *parent) { // Check for a directional light. domLight::domTechnique_common::domDirectionalRef directional = tc.getDirectional(); - if (directional != NULL) { + if (directional != nullptr) { PT(DirectionalLight) dlight = new DirectionalLight(TOSTRING(light.getName())); lnode = DCAST(LightNode, dlight); @@ -470,7 +470,7 @@ load_light(domLight &light, PandaNode *parent) { // Check for a point light. domLight::domTechnique_common::domPointRef point = tc.getPoint(); - if (point != NULL) { + if (point != nullptr) { PT(PointLight) plight = new PointLight(TOSTRING(light.getName())); lnode = DCAST(LightNode, plight); @@ -479,15 +479,15 @@ load_light(domLight &light, PandaNode *parent) { LVecBase3f atten (1.0f, 0.0f, 0.0f); domTargetable_floatRef fval = point->getConstant_attenuation(); - if (fval != NULL) { + if (fval != nullptr) { atten[0] = fval->getValue(); } fval = point->getLinear_attenuation(); - if (fval != NULL) { + if (fval != nullptr) { atten[1] = fval->getValue(); } fval = point->getQuadratic_attenuation(); - if (fval != NULL) { + if (fval != nullptr) { atten[2] = fval->getValue(); } @@ -496,7 +496,7 @@ load_light(domLight &light, PandaNode *parent) { // Check for a spot light. domLight::domTechnique_common::domSpotRef spot = tc.getSpot(); - if (spot != NULL) { + if (spot != nullptr) { PT(Spotlight) slight = new Spotlight(TOSTRING(light.getName())); lnode = DCAST(LightNode, slight); @@ -505,36 +505,36 @@ load_light(domLight &light, PandaNode *parent) { LVecBase3f atten (1.0f, 0.0f, 0.0f); domTargetable_floatRef fval = spot->getConstant_attenuation(); - if (fval != NULL) { + if (fval != nullptr) { atten[0] = fval->getValue(); } fval = spot->getLinear_attenuation(); - if (fval != NULL) { + if (fval != nullptr) { atten[1] = fval->getValue(); } fval = spot->getQuadratic_attenuation(); - if (fval != NULL) { + if (fval != nullptr) { atten[2] = fval->getValue(); } slight->set_attenuation(atten); fval = spot->getFalloff_angle(); - if (fval != NULL) { + if (fval != nullptr) { slight->get_lens()->set_fov(fval->getValue()); } else { slight->get_lens()->set_fov(180.0f); } fval = spot->getFalloff_exponent(); - if (fval != NULL) { + if (fval != nullptr) { slight->set_exponent(fval->getValue()); } else { slight->set_exponent(0.0f); } } - if (lnode == NULL) { + if (lnode == nullptr) { return; } parent->add_child(lnode); diff --git a/panda/src/collada/colladaPrimitive.I b/panda/src/collada/colladaPrimitive.I index 697e028f39..e97263f280 100644 --- a/panda/src/collada/colladaPrimitive.I +++ b/panda/src/collada/colladaPrimitive.I @@ -34,7 +34,7 @@ get_geom() const { * Returns the name of this primitive's material, or the empty string if none * was assigned. */ -INLINE const string &ColladaPrimitive:: +INLINE const std::string &ColladaPrimitive:: get_material() const { return _material; } diff --git a/panda/src/collada/colladaPrimitive.cxx b/panda/src/collada/colladaPrimitive.cxx index f1c627cb00..04433b72e4 100644 --- a/panda/src/collada/colladaPrimitive.cxx +++ b/panda/src/collada/colladaPrimitive.cxx @@ -65,7 +65,7 @@ ColladaPrimitive(GeomPrimitive *prim, daeTArray &input ColladaPrimitive *ColladaPrimitive:: from_dom(domLines &prim) { // If we already loaded it before, use that. - if (prim.getUserData() != NULL) { + if (prim.getUserData() != nullptr) { return (ColladaPrimitive *) prim.getUserData(); } @@ -77,7 +77,7 @@ from_dom(domLines &prim) { prim.setUserData(new_prim); domPRef p = prim.getP(); - if (p != NULL) { + if (p != nullptr) { new_prim->load_primitive(*p); } @@ -91,7 +91,7 @@ from_dom(domLines &prim) { ColladaPrimitive *ColladaPrimitive:: from_dom(domLinestrips &prim) { // If we already loaded it before, use that. - if (prim.getUserData() != NULL) { + if (prim.getUserData() != nullptr) { return (ColladaPrimitive *) prim.getUserData(); } @@ -114,7 +114,7 @@ from_dom(domLinestrips &prim) { ColladaPrimitive *ColladaPrimitive:: from_dom(domPolygons &prim) { // If we already loaded it before, use that. - if (prim.getUserData() != NULL) { + if (prim.getUserData() != nullptr) { return (ColladaPrimitive *) prim.getUserData(); } @@ -145,7 +145,7 @@ from_dom(domPolygons &prim) { ColladaPrimitive *ColladaPrimitive:: from_dom(domPolylist &prim) { // If we already loaded it before, use that. - if (prim.getUserData() != NULL) { + if (prim.getUserData() != nullptr) { return (ColladaPrimitive *) prim.getUserData(); } @@ -162,7 +162,7 @@ from_dom(domPolylist &prim) { domPRef p = prim.getP(); domPolylist::domVcountRef vcounts = prim.getVcount(); - if (p == NULL || vcounts == NULL) { + if (p == nullptr || vcounts == nullptr) { return new_prim; } @@ -185,7 +185,7 @@ from_dom(domPolylist &prim) { ColladaPrimitive *ColladaPrimitive:: from_dom(domTriangles &prim) { // If we already loaded it before, use that. - if (prim.getUserData() != NULL) { + if (prim.getUserData() != nullptr) { return (ColladaPrimitive *) prim.getUserData(); } @@ -197,7 +197,7 @@ from_dom(domTriangles &prim) { prim.setUserData(new_prim); domPRef p = prim.getP(); - if (p != NULL) { + if (p != nullptr) { new_prim->load_primitive(*p); } @@ -211,7 +211,7 @@ from_dom(domTriangles &prim) { ColladaPrimitive *ColladaPrimitive:: from_dom(domTrifans &prim) { // If we already loaded it before, use that. - if (prim.getUserData() != NULL) { + if (prim.getUserData() != nullptr) { return (ColladaPrimitive *) prim.getUserData(); } @@ -234,7 +234,7 @@ from_dom(domTrifans &prim) { ColladaPrimitive *ColladaPrimitive:: from_dom(domTristrips &prim) { // If we already loaded it before, use that. - if (prim.getUserData() != NULL) { + if (prim.getUserData() != nullptr) { return (ColladaPrimitive *) prim.getUserData(); } diff --git a/panda/src/collada/colladaPrimitive.h b/panda/src/collada/colladaPrimitive.h index 740329e020..075bce7f73 100644 --- a/panda/src/collada/colladaPrimitive.h +++ b/panda/src/collada/colladaPrimitive.h @@ -48,7 +48,7 @@ public: unsigned int write_data(GeomVertexData *vdata, int start_row, domP &p); INLINE PT(Geom) get_geom() const; - INLINE const string &get_material() const; + INLINE const std::string &get_material() const; private: ColladaPrimitive(GeomPrimitive *prim, daeTArray > &inputs); @@ -63,7 +63,7 @@ private: PT(Geom) _geom; PT(GeomVertexData) _vdata; PT(GeomPrimitive) _gprim; - string _material; + std::string _material; }; #include "colladaPrimitive.I" diff --git a/panda/src/collada/load_collada_file.cxx b/panda/src/collada/load_collada_file.cxx index 1d849f0f79..2ebdd2c340 100644 --- a/panda/src/collada/load_collada_file.cxx +++ b/panda/src/collada/load_collada_file.cxx @@ -26,10 +26,10 @@ load_from_loader(ColladaLoader &loader) { if (loader._error && !collada_accept_errors) { collada_cat.error() << "Errors in collada file.\n"; - return NULL; + return nullptr; } - if (loader._root != NULL && collada_flatten) { + if (loader._root != nullptr && collada_flatten) { SceneGraphReducer gr; int combine_siblings_bits = 0; @@ -72,7 +72,7 @@ load_collada_file(const Filename &filename, CoordinateSystem cs, VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { record->add_dependent_file(filename); } @@ -85,7 +85,7 @@ load_collada_file(const Filename &filename, CoordinateSystem cs, << "Reading " << filename << "\n"; if (!loader.read(filename)) { - return NULL; + return nullptr; } return load_from_loader(loader); diff --git a/panda/src/collada/load_collada_file.h b/panda/src/collada/load_collada_file.h index 9dea0e72f9..8217b11063 100644 --- a/panda/src/collada/load_collada_file.h +++ b/panda/src/collada/load_collada_file.h @@ -30,7 +30,7 @@ BEGIN_PUBLISH */ EXPCL_COLLADA PT(PandaNode) load_collada_file(const Filename &filename, CoordinateSystem cs = CS_default, - BamCacheRecord *record = NULL); + BamCacheRecord *record = nullptr); END_PUBLISH #endif diff --git a/panda/src/collada/loaderFileTypeDae.cxx b/panda/src/collada/loaderFileTypeDae.cxx index 9fc5785514..a35223f30c 100644 --- a/panda/src/collada/loaderFileTypeDae.cxx +++ b/panda/src/collada/loaderFileTypeDae.cxx @@ -26,7 +26,7 @@ LoaderFileTypeDae() { /** * */ -string LoaderFileTypeDae:: +std::string LoaderFileTypeDae:: get_name() const { #if PANDA_COLLADA_VERSION == 14 return "COLLADA 1.4"; @@ -40,7 +40,7 @@ get_name() const { /** * */ -string LoaderFileTypeDae:: +std::string LoaderFileTypeDae:: get_extension() const { return "dae"; } @@ -49,7 +49,7 @@ get_extension() const { * Returns a space-separated list of extension, in addition to the one * returned by get_extension(), that are recognized by this loader. */ -string LoaderFileTypeDae:: +std::string LoaderFileTypeDae:: get_additional_extensions() const { return "zae"; } diff --git a/panda/src/collada/loaderFileTypeDae.h b/panda/src/collada/loaderFileTypeDae.h index 4cb79a81f9..e762564b86 100644 --- a/panda/src/collada/loaderFileTypeDae.h +++ b/panda/src/collada/loaderFileTypeDae.h @@ -25,9 +25,9 @@ class EXPCL_COLLADA LoaderFileTypeDae : public LoaderFileType { public: LoaderFileTypeDae(); - virtual string get_name() const; - virtual string get_extension() const; - virtual string get_additional_extensions() const; + virtual std::string get_name() const; + virtual std::string get_extension() const; + virtual std::string get_additional_extensions() const; virtual bool supports_compressed() const; virtual PT(PandaNode) load_file(const Filename &path, const LoaderOptions &options, diff --git a/panda/src/collide/collisionBox.cxx b/panda/src/collide/collisionBox.cxx index b55988c352..46666722e2 100644 --- a/panda/src/collide/collisionBox.cxx +++ b/panda/src/collide/collisionBox.cxx @@ -35,6 +35,9 @@ #include +using std::max; +using std::min; + PStatCollector CollisionBox::_volume_pcollector("Collision Volumes:CollisionBox"); PStatCollector CollisionBox::_test_pcollector("Collision Tests:CollisionBox"); TypeHandle CollisionBox::_type_handle; @@ -181,7 +184,7 @@ get_test_pcollector() { * */ void CollisionBox:: -output(ostream &out) const { +output(std::ostream &out) const { } /** @@ -199,7 +202,7 @@ PT(CollisionEntry) CollisionBox:: test_intersection_from_sphere(const CollisionEntry &entry) const { const CollisionSphere *sphere; - DCAST_INTO_R(sphere, entry.get_from(), NULL); + DCAST_INTO_R(sphere, entry.get_from(), nullptr); CPT(TransformState) wrt_space = entry.get_wrt_space(); CPT(TransformState) wrt_prev_space = entry.get_wrt_prev_space(); @@ -310,7 +313,7 @@ test_intersection_from_sphere(const CollisionEntry &entry) const { PN_stdfloat edge_dist = 0.0f; const ClipPlaneAttrib *cpa = entry.get_into_clip_planes(); - if (cpa != (ClipPlaneAttrib *)NULL) { + if (cpa != nullptr) { // We have a clip plane; apply it. Points new_points; if (apply_clip_plane(new_points, cpa, entry.get_into_node_path().get_net_transform(),ip)) { @@ -361,7 +364,7 @@ test_intersection_from_sphere(const CollisionEntry &entry) const { intersect = true; } if( !intersect ) - return NULL; + return nullptr; if (collide_cat.is_debug()) { collide_cat.debug() @@ -402,7 +405,7 @@ test_intersection_from_sphere(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionBox:: test_intersection_from_ray(const CollisionEntry &entry) const { const CollisionRay *ray; - DCAST_INTO_R(ray, entry.get_from(), NULL); + DCAST_INTO_R(ray, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); LPoint3 from_origin = ray->get_origin() * wrt_mat; @@ -453,7 +456,7 @@ test_intersection_from_ray(const CollisionEntry &entry) const { if(!intersect) { // No intersection with ANY of the box's planes has been detected - return NULL; + return nullptr; } if (collide_cat.is_debug()) { @@ -483,7 +486,7 @@ test_intersection_from_ray(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionBox:: test_intersection_from_segment(const CollisionEntry &entry) const { const CollisionSegment *seg; - DCAST_INTO_R(seg, entry.get_from(), NULL); + DCAST_INTO_R(seg, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); LPoint3 from_origin = seg->get_point_a() * wrt_mat; @@ -535,7 +538,7 @@ test_intersection_from_segment(const CollisionEntry &entry) const { if(!intersect) { // No intersection with ANY of the box's planes has been detected - return NULL; + return nullptr; } if (collide_cat.is_debug()) { @@ -564,7 +567,7 @@ test_intersection_from_segment(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionBox:: test_intersection_from_box(const CollisionEntry &entry) const { const CollisionBox *box; - DCAST_INTO_R(box, entry.get_from(), NULL); + DCAST_INTO_R(box, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -603,7 +606,7 @@ test_intersection_from_box(const CollisionEntry &entry) const { cabs(box_z[0] * from_extents[2]); pen = r1 + r2 - cabs(diff[0]); if (pen < 0) { - return NULL; + return nullptr; } min_pen = pen; @@ -613,7 +616,7 @@ test_intersection_from_box(const CollisionEntry &entry) const { cabs(box_z[1] * from_extents[2]); pen = r1 + r2 - cabs(diff[1]); if (pen < 0) { - return NULL; + return nullptr; } if (pen < min_pen) { min_pen = pen; @@ -626,7 +629,7 @@ test_intersection_from_box(const CollisionEntry &entry) const { cabs(box_z[2] * from_extents[2]); pen = r1 + r2 - cabs(diff[2]); if (pen < 0) { - return NULL; + return nullptr; } if (pen < min_pen) { min_pen = pen; @@ -640,7 +643,7 @@ test_intersection_from_box(const CollisionEntry &entry) const { r2 = from_extents[0]; pen = r1 + r2 - cabs(diff.dot(box_x)); if (pen < 0) { - return NULL; + return nullptr; } if (pen < min_pen) { min_pen = pen; @@ -652,7 +655,7 @@ test_intersection_from_box(const CollisionEntry &entry) const { r2 = from_extents[1]; pen = r1 + r2 - cabs(diff.dot(box_y)); if (pen < 0) { - return NULL; + return nullptr; } if (pen < min_pen) { min_pen = pen; @@ -664,7 +667,7 @@ test_intersection_from_box(const CollisionEntry &entry) const { r2 = from_extents[2]; pen = r1 + r2 - cabs(diff.dot(box_z)); if (pen < 0) { - return NULL; + return nullptr; } if (pen < min_pen) { min_pen = pen; @@ -674,55 +677,55 @@ test_intersection_from_box(const CollisionEntry &entry) const { r1 = into_extents[1] * cabs(box_x[2]) + into_extents[2] * cabs(box_x[1]); r2 = from_extents[1] * cabs(box_z[0]) + from_extents[2] * cabs(box_y[0]); if (cabs(diff[2] * box_x[1] - diff[1] * box_x[2]) > r1 + r2) { - return NULL; + return nullptr; } r1 = into_extents[1] * cabs(box_y[2]) + into_extents[2] * cabs(box_y[1]); r2 = from_extents[0] * cabs(box_z[0]) + from_extents[2] * cabs(box_x[0]); if (cabs(diff[2] * box_y[1] - diff[1] * box_y[2]) > r1 + r2) { - return NULL; + return nullptr; } r1 = into_extents[1] * cabs(box_z[2]) + into_extents[2] * cabs(box_z[1]); r2 = from_extents[0] * cabs(box_y[0]) + from_extents[1] * cabs(box_x[0]); if (cabs(diff[2] * box_z[1] - diff[1] * box_z[2]) > r1 + r2) { - return NULL; + return nullptr; } r1 = into_extents[0] * cabs(box_x[2]) + into_extents[2] * cabs(box_x[0]); r2 = from_extents[1] * cabs(box_z[1]) + from_extents[2] * cabs(box_y[1]); if (cabs(diff[0] * box_x[2] - diff[2] * box_x[0]) > r1 + r2) { - return NULL; + return nullptr; } r1 = into_extents[0] * cabs(box_y[2]) + into_extents[2] * cabs(box_y[0]); r2 = from_extents[0] * cabs(box_z[1]) + from_extents[2] * cabs(box_x[1]); if (cabs(diff[0] * box_y[2] - diff[2] * box_y[0]) > r1 + r2) { - return NULL; + return nullptr; } r1 = into_extents[0] * cabs(box_z[2]) + into_extents[2] * cabs(box_z[0]); r2 = from_extents[0] * cabs(box_y[1]) + from_extents[1] * cabs(box_x[1]); if (cabs(diff[0] * box_z[2] - diff[2] * box_z[0]) > r1 + r2) { - return NULL; + return nullptr; } r1 = into_extents[0] * cabs(box_x[1]) + into_extents[1] * cabs(box_x[0]); r2 = from_extents[1] * cabs(box_z[2]) + from_extents[2] * cabs(box_y[2]); if (cabs(diff[1] * box_x[0] - diff[0] * box_x[1]) > r1 + r2) { - return NULL; + return nullptr; } r1 = into_extents[0] * cabs(box_y[1]) + into_extents[1] * cabs(box_y[0]); r2 = from_extents[0] * cabs(box_z[2]) + from_extents[2] * cabs(box_x[2]); if (cabs(diff[1] * box_y[0] - diff[0] * box_y[1]) > r1 + r2) { - return NULL; + return nullptr; } r1 = into_extents[0] * cabs(box_z[1]) + into_extents[1] * cabs(box_z[0]); r2 = from_extents[0] * cabs(box_y[2]) + from_extents[1] * cabs(box_x[2]); if (cabs(diff[1] * box_z[0] - diff[0] * box_z[1]) > r1 + r2) { - return NULL; + return nullptr; } if (collide_cat.is_debug()) { diff --git a/panda/src/collide/collisionBox.h b/panda/src/collide/collisionBox.h index c5bb22be88..0888d7e4da 100644 --- a/panda/src/collide/collisionBox.h +++ b/panda/src/collide/collisionBox.h @@ -46,7 +46,7 @@ public: virtual PStatCollector &get_volume_pcollector(); virtual PStatCollector &get_test_pcollector(); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; INLINE static void flush_level(); void setup_box(); diff --git a/panda/src/collide/collisionEntry.I b/panda/src/collide/collisionEntry.I index 9b535d17ce..41a591c90e 100644 --- a/panda/src/collide/collisionEntry.I +++ b/panda/src/collide/collisionEntry.I @@ -38,7 +38,7 @@ get_from() const { */ INLINE bool CollisionEntry:: has_into() const { - return (_into != (CollisionSolid *)NULL); + return (_into != nullptr); } /** @@ -338,7 +338,7 @@ test_intersection(CollisionHandler *record, PT(CollisionEntry) result = get_from()->test_intersection(*this); #ifdef DO_COLLISION_RECORDING if (trav->has_recorder()) { - if (result != (CollisionEntry *)NULL) { + if (result != nullptr) { trav->get_recorder()->collision_tested(*result, true); } else { trav->get_recorder()->collision_tested(*this, false); @@ -351,17 +351,17 @@ test_intersection(CollisionHandler *record, // if there was no collision detected but the handler wants to know about // all potential collisions, create a "didn't collide" collision entry for // it - if (record->wants_all_potential_collidees() && result == (CollisionEntry *)NULL) { + if (record->wants_all_potential_collidees() && result == nullptr) { result = new CollisionEntry(*this); result->reset_collided(); } - if (result != (CollisionEntry *)NULL) { + if (result != nullptr) { record->add_entry(result); } } -INLINE ostream & -operator << (ostream &out, const CollisionEntry &entry) { +INLINE std::ostream & +operator << (std::ostream &out, const CollisionEntry &entry) { entry.output(out); return out; } diff --git a/panda/src/collide/collisionEntry.cxx b/panda/src/collide/collisionEntry.cxx index 81814eea48..2a8c97fa2c 100644 --- a/panda/src/collide/collisionEntry.cxx +++ b/panda/src/collide/collisionEntry.cxx @@ -209,7 +209,7 @@ get_all_contact_info(const NodePath &space, LPoint3 &contact_pos, * */ void CollisionEntry:: -output(ostream &out) const { +output(std::ostream &out) const { out << _from_node_path; if (!_into_node_path.is_empty()) { out << " into " << _into_node_path; @@ -223,7 +223,7 @@ output(ostream &out) const { * */ void CollisionEntry:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "CollisionEntry:\n"; if (!_from_node_path.is_empty()) { @@ -239,7 +239,7 @@ write(ostream &out, int indent_level) const { out << "]"; const ClipPlaneAttrib *cpa = get_into_clip_planes(); - if (cpa != (ClipPlaneAttrib *)NULL) { + if (cpa != nullptr) { out << " (clipped)"; } out << "\n"; diff --git a/panda/src/collide/collisionEntry.h b/panda/src/collide/collisionEntry.h index 558a6afa70..03d39c03d5 100644 --- a/panda/src/collide/collisionEntry.h +++ b/panda/src/collide/collisionEntry.h @@ -90,8 +90,8 @@ PUBLISHED: LPoint3 &contact_pos, LVector3 &contact_normal) const; - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; PUBLISHED: MAKE_PROPERTY(from_solid, get_from); @@ -170,7 +170,7 @@ private: friend class CollisionHandlerFluidPusher; }; -INLINE ostream &operator << (ostream &out, const CollisionEntry &entry); +INLINE std::ostream &operator << (std::ostream &out, const CollisionEntry &entry); #include "collisionEntry.I" diff --git a/panda/src/collide/collisionFloorMesh.cxx b/panda/src/collide/collisionFloorMesh.cxx index d523875727..5f0ab0cabc 100644 --- a/panda/src/collide/collisionFloorMesh.cxx +++ b/panda/src/collide/collisionFloorMesh.cxx @@ -33,6 +33,10 @@ #include "geomLinestrips.h" #include "geomVertexWriter.h" #include + +using std::max; +using std::min; + PStatCollector CollisionFloorMesh::_volume_pcollector("Collision Volumes:CollisionFloorMesh"); PStatCollector CollisionFloorMesh::_test_pcollector("Collision Tests:CollisionFloorMesh"); TypeHandle CollisionFloorMesh::_type_handle; @@ -86,7 +90,7 @@ get_collision_origin() const { * */ void CollisionFloorMesh:: -output(ostream &out) const { +output(std::ostream &out) const { out << "cfloor"; } @@ -125,7 +129,7 @@ compute_internal_bounds() const { PT(CollisionEntry) CollisionFloorMesh:: test_intersection_from_ray(const CollisionEntry &entry) const { const CollisionRay *ray; - DCAST_INTO_R(ray, entry.get_from(), NULL); + DCAST_INTO_R(ray, entry.get_from(), nullptr); LPoint3 from_origin = ray->get_origin() * entry.get_wrt_mat(); double fx = from_origin[0]; @@ -180,7 +184,7 @@ test_intersection_from_ray(const CollisionEntry &entry) const { new_entry->set_surface_point(LPoint3(fx, fy, finalz)); return new_entry; } - return NULL; + return nullptr; } @@ -190,7 +194,7 @@ test_intersection_from_ray(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionFloorMesh:: test_intersection_from_sphere(const CollisionEntry &entry) const { const CollisionSphere *sphere; - DCAST_INTO_R(sphere, entry.get_from(), NULL); + DCAST_INTO_R(sphere, entry.get_from(), nullptr); LPoint3 from_origin = sphere->get_center() * entry.get_wrt_mat(); double fx = from_origin[0]; @@ -243,14 +247,14 @@ test_intersection_from_sphere(const CollisionEntry &entry) const { PN_stdfloat finalz = p0z+vz+(((uz - vz) *u)/(u+v)); PN_stdfloat dz = fz - finalz; if(dz > rad) - return NULL; + return nullptr; PT(CollisionEntry) new_entry = new CollisionEntry(entry); new_entry->set_surface_normal(LPoint3(0, 0, 1)); new_entry->set_surface_point(LPoint3(fx, fy, finalz)); return new_entry; } - return NULL; + return nullptr; } @@ -406,7 +410,7 @@ register_with_read_factory() { * */ void CollisionFloorMesh:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << (*this) << "\n"; } diff --git a/panda/src/collide/collisionFloorMesh.h b/panda/src/collide/collisionFloorMesh.h index 44e9d18e32..9304b79e11 100644 --- a/panda/src/collide/collisionFloorMesh.h +++ b/panda/src/collide/collisionFloorMesh.h @@ -69,8 +69,8 @@ public: virtual PStatCollector &get_volume_pcollector(); virtual PStatCollector &get_test_pcollector(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; INLINE static void flush_level(); diff --git a/panda/src/collide/collisionGeom.cxx b/panda/src/collide/collisionGeom.cxx index 15211b9598..b90bebe38b 100644 --- a/panda/src/collide/collisionGeom.cxx +++ b/panda/src/collide/collisionGeom.cxx @@ -47,6 +47,6 @@ get_test_pcollector() { * */ void CollisionGeom:: -output(ostream &out) const { +output(std::ostream &out) const { out << "cgeom"; } diff --git a/panda/src/collide/collisionGeom.h b/panda/src/collide/collisionGeom.h index 20e736dba4..ba63263f26 100644 --- a/panda/src/collide/collisionGeom.h +++ b/panda/src/collide/collisionGeom.h @@ -38,7 +38,7 @@ public: virtual PStatCollector &get_volume_pcollector(); virtual PStatCollector &get_test_pcollector(); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: static PStatCollector _volume_pcollector; diff --git a/panda/src/collide/collisionHandlerEvent.I b/panda/src/collide/collisionHandlerEvent.I index 28efe50dcc..d5b6327c69 100644 --- a/panda/src/collide/collisionHandlerEvent.I +++ b/panda/src/collide/collisionHandlerEvent.I @@ -73,7 +73,7 @@ clear_in_patterns() { * longer detected, the out_pattern event is thrown. */ INLINE void CollisionHandlerEvent:: -add_in_pattern(const string &in_pattern) { +add_in_pattern(const std::string &in_pattern) { _in_patterns.push_back(in_pattern); } @@ -82,7 +82,7 @@ add_in_pattern(const string &in_pattern) { * have previously been set with the indicated pattern. */ INLINE void CollisionHandlerEvent:: -set_in_pattern(const string &in_pattern) { +set_in_pattern(const std::string &in_pattern) { clear_in_patterns(); add_in_pattern(in_pattern); } @@ -99,9 +99,9 @@ get_num_in_patterns() const { * Returns the nth pattern string that indicates how the event names are * generated for each collision detected. See add_in_pattern(). */ -INLINE string CollisionHandlerEvent:: +INLINE std::string CollisionHandlerEvent:: get_in_pattern(int n) const { - nassertr(n >= 0 && n < (int)_in_patterns.size(), string()); + nassertr(n >= 0 && n < (int)_in_patterns.size(), std::string()); return _in_patterns[n]; } @@ -126,7 +126,7 @@ clear_again_patterns() { * longer detected, the out_pattern event is thrown. */ INLINE void CollisionHandlerEvent:: -add_again_pattern(const string &again_pattern) { +add_again_pattern(const std::string &again_pattern) { _again_patterns.push_back(again_pattern); } @@ -135,7 +135,7 @@ add_again_pattern(const string &again_pattern) { * have previously been set with the indicated pattern. */ INLINE void CollisionHandlerEvent:: -set_again_pattern(const string &again_pattern) { +set_again_pattern(const std::string &again_pattern) { clear_again_patterns(); add_again_pattern(again_pattern); } @@ -152,9 +152,9 @@ get_num_again_patterns() const { * Returns the nth pattern string that indicates how the event names are * generated for each collision detected. See add_again_pattern(). */ -INLINE string CollisionHandlerEvent:: +INLINE std::string CollisionHandlerEvent:: get_again_pattern(int n) const { - nassertr(n >= 0 && n < (int)_again_patterns.size(), string()); + nassertr(n >= 0 && n < (int)_again_patterns.size(), std::string()); return _again_patterns[n]; } @@ -177,7 +177,7 @@ clear_out_patterns() { * longer detected, the out_pattern event is thrown. */ INLINE void CollisionHandlerEvent:: -add_out_pattern(const string &out_pattern) { +add_out_pattern(const std::string &out_pattern) { _out_patterns.push_back(out_pattern); } @@ -186,7 +186,7 @@ add_out_pattern(const string &out_pattern) { * have previously been set with the indicated pattern. */ INLINE void CollisionHandlerEvent:: -set_out_pattern(const string &out_pattern) { +set_out_pattern(const std::string &out_pattern) { clear_out_patterns(); add_out_pattern(out_pattern); } @@ -203,8 +203,8 @@ get_num_out_patterns() const { * Returns the nth pattern string that indicates how the event names are * generated for each collision detected. See add_out_pattern(). */ -INLINE string CollisionHandlerEvent:: +INLINE std::string CollisionHandlerEvent:: get_out_pattern(int n) const { - nassertr(n >= 0 && n < (int)_out_patterns.size(), string()); + nassertr(n >= 0 && n < (int)_out_patterns.size(), std::string()); return _out_patterns[n]; } diff --git a/panda/src/collide/collisionHandlerEvent.cxx b/panda/src/collide/collisionHandlerEvent.cxx index c43a3c2ee4..0fd949074e 100644 --- a/panda/src/collide/collisionHandlerEvent.cxx +++ b/panda/src/collide/collisionHandlerEvent.cxx @@ -17,6 +17,8 @@ #include "eventParameter.h" #include "throw_event.h" +using std::string; + TypeHandle CollisionHandlerEvent::_type_handle; @@ -50,7 +52,7 @@ begin_group() { */ void CollisionHandlerEvent:: add_entry(CollisionEntry *entry) { - nassertv(entry != (CollisionEntry *)NULL); + nassertv(entry != nullptr); // Record this particular entry for later. This will keep track of all the // unique pairs of nodenode intersections. diff --git a/panda/src/collide/collisionHandlerEvent.h b/panda/src/collide/collisionHandlerEvent.h index a1240882d6..808ee888c5 100644 --- a/panda/src/collide/collisionHandlerEvent.h +++ b/panda/src/collide/collisionHandlerEvent.h @@ -40,24 +40,24 @@ public: PUBLISHED: INLINE void clear_in_patterns(); - INLINE void add_in_pattern(const string &in_pattern); - INLINE void set_in_pattern(const string &in_pattern); + INLINE void add_in_pattern(const std::string &in_pattern); + INLINE void set_in_pattern(const std::string &in_pattern); INLINE int get_num_in_patterns() const; - INLINE string get_in_pattern(int n) const; + INLINE std::string get_in_pattern(int n) const; MAKE_SEQ(get_in_patterns, get_num_in_patterns, get_in_pattern); INLINE void clear_again_patterns(); - INLINE void add_again_pattern(const string &again_pattern); - INLINE void set_again_pattern(const string &again_pattern); + INLINE void add_again_pattern(const std::string &again_pattern); + INLINE void set_again_pattern(const std::string &again_pattern); INLINE int get_num_again_patterns() const; - INLINE string get_again_pattern(int n) const; + INLINE std::string get_again_pattern(int n) const; MAKE_SEQ(get_again_patterns, get_num_again_patterns, get_again_pattern); INLINE void clear_out_patterns(); - INLINE void add_out_pattern(const string &out_pattern); - INLINE void set_out_pattern(const string &out_pattern); + INLINE void add_out_pattern(const std::string &out_pattern); + INLINE void set_out_pattern(const std::string &out_pattern); INLINE int get_num_out_patterns() const; - INLINE string get_out_pattern(int n) const; + INLINE std::string get_out_pattern(int n) const; MAKE_SEQ(get_out_patterns, get_num_out_patterns, get_out_pattern); MAKE_SEQ_PROPERTY(in_patterns, get_num_in_patterns, get_in_pattern); @@ -69,7 +69,7 @@ PUBLISHED: protected: void throw_event_for(const vector_string &patterns, CollisionEntry *entry); - void throw_event_pattern(const string &pattern, CollisionEntry *entry); + void throw_event_pattern(const std::string &pattern, CollisionEntry *entry); vector_string _in_patterns; vector_string _again_patterns; diff --git a/panda/src/collide/collisionHandlerFloor.cxx b/panda/src/collide/collisionHandlerFloor.cxx index e8f697fb5f..506101cb41 100644 --- a/panda/src/collide/collisionHandlerFloor.cxx +++ b/panda/src/collide/collisionHandlerFloor.cxx @@ -18,6 +18,9 @@ #include "clockObject.h" +using std::cout; +using std::endl; + TypeHandle CollisionHandlerFloor::_type_handle; /** @@ -62,13 +65,13 @@ set_highest_collision(const NodePath &target_node_path, const NodePath &from_nod bool got_min = false; PN_stdfloat max_height = 0.0f; PN_stdfloat min_height = 0.0f; - CollisionEntry *highest = NULL; - CollisionEntry *lowest = NULL; + CollisionEntry *highest = nullptr; + CollisionEntry *lowest = nullptr; Entries::const_iterator ei; for (ei = entries.begin(); ei != entries.end(); ++ei) { CollisionEntry *entry = (*ei); - nassertr(entry != (CollisionEntry *)NULL, 0.0f); + nassertr(entry != nullptr, 0.0f); nassertr(from_node_path == entry->get_from_node_path(), 0.0f); if (entry->has_surface_point()) { @@ -159,12 +162,12 @@ handle_entries() { // Get the maximum height for all collisions with this node. bool got_max = false; PN_stdfloat max_height = 0.0f; - CollisionEntry *max_entry = NULL; + CollisionEntry *max_entry = nullptr; Entries::const_iterator ei; for (ei = entries.begin(); ei != entries.end(); ++ei) { CollisionEntry *entry = (*ei); - nassertr(entry != (CollisionEntry *)NULL, false); + nassertr(entry != nullptr, false); nassertr(from_node_path == entry->get_from_node_path(), false); if (entry->has_surface_point()) { @@ -204,7 +207,7 @@ handle_entries() { if (adjust < 0.0f && _max_velocity != 0.0f) { PN_stdfloat max_adjust = _max_velocity * ClockObject::get_global_clock()->get_dt(); - adjust = max(adjust, -max_adjust); + adjust = std::max(adjust, -max_adjust); } CPT(TransformState) trans = def._target.get_transform(); diff --git a/panda/src/collide/collisionHandlerFluidPusher.cxx b/panda/src/collide/collisionHandlerFluidPusher.cxx index 0a48381d01..df15e8bacc 100644 --- a/panda/src/collide/collisionHandlerFluidPusher.cxx +++ b/panda/src/collide/collisionHandlerFluidPusher.cxx @@ -35,7 +35,7 @@ CollisionHandlerFluidPusher() { */ void CollisionHandlerFluidPusher:: add_entry(CollisionEntry *entry) { - nassertv(entry != (CollisionEntry *)NULL); + nassertv(entry != nullptr); // skip over CollisionHandlerPhysical::add_entry, since it filters out // collidees by orientation; our collider can change direction mid-frame, so // it may collide with something that would have been filtered out @@ -154,24 +154,24 @@ handle_entries() { // unit vector pointing out to the right relative to the direction of // motion, looking into the direction of motion - const LVector3 right_unit(LVector3::up().cross(reverse_vec)); + //const LVector3 right_unit(LVector3::up().cross(reverse_vec)); // iterate until the mover runs out of movement or gets stuck while (true) { - const CollisionEntry *C = 0; + const CollisionEntry *C = nullptr; // find the first (earliest) collision Entries::const_iterator cei; for (cei = entries.begin(); cei != entries.end(); ++cei) { const CollisionEntry *entry = (*cei); - nassertr(entry != (CollisionEntry *)NULL, false); - if (entry->collided() && ((C == 0) || (entry->get_t() < C->get_t()))) { + nassertr(entry != nullptr, false); + if (entry->collided() && ((C == nullptr) || (entry->get_t() < C->get_t()))) { nassertr(from_node_path == entry->get_from_node_path(), false); C = entry; } } // if no collisions, we're done - if (C == 0) { + if (C == nullptr) { break; } @@ -213,11 +213,11 @@ handle_entries() { prev_trans = prev_trans->set_pos(contact_pos); from_node_path.set_prev_transform(wrt_node, prev_trans); - { + /*{ const LPoint3 new_pos(from_node_path.get_pos(wrt_node)); CPT(TransformState) new_prev_trans(from_node_path.get_prev_transform(wrt_node)); const LPoint3 new_prev_pos(new_prev_trans->get_pos()); - } + }*/ // recalculate the position delta N = from_node_path.get_pos_delta(wrt_node); @@ -227,13 +227,13 @@ handle_entries() { Entries new_entries; for (ei = entries.begin(); ei != entries.end(); ++ei) { CollisionEntry *entry = (*ei); - nassertr(entry != (CollisionEntry *)NULL, false); + nassertr(entry != nullptr, false); // skip the one we just collided against if (entry != C) { entry->_from_node_path = from_node_path; entry->reset_collided(); PT(CollisionEntry) result = entry->get_from()->test_intersection(**ei); - if (result != (CollisionEntry *)NULL && result != (CollisionEntry *)0) { + if (result != nullptr && result != nullptr) { new_entries.push_back(result); } } diff --git a/panda/src/collide/collisionHandlerGravity.cxx b/panda/src/collide/collisionHandlerGravity.cxx index a09b70a0a6..023d220cd4 100644 --- a/panda/src/collide/collisionHandlerGravity.cxx +++ b/panda/src/collide/collisionHandlerGravity.cxx @@ -18,6 +18,9 @@ #include "collisionPlane.h" #include "clockObject.h" +using std::cout; +using std::endl; + TypeHandle CollisionHandlerGravity::_type_handle; /** @@ -53,12 +56,12 @@ set_highest_collision(const NodePath &target_node_path, const NodePath &from_nod // Get the maximum height for all collisions with this node. bool got_max = false; PN_stdfloat max_height = 0.0f; - CollisionEntry *highest = NULL; + CollisionEntry *highest = nullptr; Entries::const_iterator ei; for (ei = entries.begin(); ei != entries.end(); ++ei) { CollisionEntry *entry = (*ei); - nassertr(entry != (CollisionEntry *)NULL, 0.0f); + nassertr(entry != nullptr, 0.0f); nassertr(from_node_path == entry->get_from_node_path(), 0.0f); if (entry->has_surface_point()) { @@ -109,15 +112,15 @@ set_highest_collision(const NodePath &target_node_path, const NodePath &from_nod bool got_min = false; PN_stdfloat max_height = 0.0f; PN_stdfloat min_height = 0.0f; - CollisionEntry *highest = NULL; - CollisionEntry *lowest = NULL; + CollisionEntry *highest = nullptr; + CollisionEntry *lowest = nullptr; pvector valid_entries; Entries::const_iterator ei; for (ei = entries.begin(); ei != entries.end(); ++ei) { CollisionEntry *entry = (*ei); - nassertr(entry != (CollisionEntry *)NULL, 0.0f); + nassertr(entry != nullptr, 0.0f); nassertr(from_node_path == entry->get_from_node_path(), 0.0f); if (entry->has_surface_point()) { @@ -254,10 +257,10 @@ handle_entries() { // ...the node is under the floor, so it has landed. Keep the // adjust to bring us up to the ground and then add the // gravity_adjust to get us airborne: - adjust += max((PN_stdfloat)0.0, gravity_adjust); + adjust += std::max((PN_stdfloat)0.0, gravity_adjust); } else { // ...the node is above the floor, so it is airborne. - adjust = max(adjust, gravity_adjust); + adjust = std::max(adjust, gravity_adjust); } _current_velocity -= _gravity * dt; // Record the airborne height in case someone else needs it: diff --git a/panda/src/collide/collisionHandlerHighestEvent.cxx b/panda/src/collide/collisionHandlerHighestEvent.cxx index f72023153d..55eb58b221 100644 --- a/panda/src/collide/collisionHandlerHighestEvent.cxx +++ b/panda/src/collide/collisionHandlerHighestEvent.cxx @@ -46,7 +46,7 @@ begin_group() { } _current_colliding.clear(); _collider_distance = 0; - _closest_collider = NULL; + _closest_collider = nullptr; } /** @@ -55,12 +55,12 @@ begin_group() { */ void CollisionHandlerHighestEvent:: add_entry(CollisionEntry *entry) { - nassertv(entry != (CollisionEntry *)NULL); + nassertv(entry != nullptr); LVector3 vec = entry->get_surface_point(entry->get_from_node_path()) - entry->get_from()->get_collision_origin(); double dist = vec.length_squared(); - if (_closest_collider == NULL || dist < _collider_distance) { + if (_closest_collider == nullptr || dist < _collider_distance) { _collider_distance = dist; _closest_collider = entry; } diff --git a/panda/src/collide/collisionHandlerPhysical.I b/panda/src/collide/collisionHandlerPhysical.I index d0f45fd495..5000ec3f59 100644 --- a/panda/src/collide/collisionHandlerPhysical.I +++ b/panda/src/collide/collisionHandlerPhysical.I @@ -74,7 +74,7 @@ set_target(const NodePath &target, DriveInterface *drive_interface) { */ INLINE void CollisionHandlerPhysical::ColliderDef:: updated_transform() { - if (_drive_interface != (DriveInterface *)NULL) { + if (_drive_interface != nullptr) { _drive_interface->set_mat(_target.get_mat()); _drive_interface->force_dgraph(); } diff --git a/panda/src/collide/collisionHandlerPhysical.cxx b/panda/src/collide/collisionHandlerPhysical.cxx index 4b356235a3..3e65e41bfc 100644 --- a/panda/src/collide/collisionHandlerPhysical.cxx +++ b/panda/src/collide/collisionHandlerPhysical.cxx @@ -52,7 +52,7 @@ begin_group() { */ void CollisionHandlerPhysical:: add_entry(CollisionEntry *entry) { - nassertv(entry != (CollisionEntry *)NULL); + nassertv(entry != nullptr); CollisionHandlerEvent::add_entry(entry); if (entry->get_from()->is_tangible() && diff --git a/panda/src/collide/collisionHandlerPhysical.h b/panda/src/collide/collisionHandlerPhysical.h index cb3a340cdc..9a9225b6b8 100644 --- a/panda/src/collide/collisionHandlerPhysical.h +++ b/panda/src/collide/collisionHandlerPhysical.h @@ -62,7 +62,7 @@ protected: class ColliderDef { public: INLINE void set_target(const NodePath &target, - DriveInterface *drive_interface = NULL); + DriveInterface *drive_interface = nullptr); INLINE void updated_transform(); NodePath _target; diff --git a/panda/src/collide/collisionHandlerPusher.cxx b/panda/src/collide/collisionHandlerPusher.cxx index 4b1b60482a..5881b7e177 100644 --- a/panda/src/collide/collisionHandlerPusher.cxx +++ b/panda/src/collide/collisionHandlerPusher.cxx @@ -91,7 +91,7 @@ handle_entries() { Entries::const_iterator ei; for (ei = entries.begin(); ei != entries.end(); ++ei) { CollisionEntry *entry = (*ei); - nassertr(entry != (CollisionEntry *)NULL, false); + nassertr(entry != nullptr, false); nassertr(from_node_path == entry->get_from_node_path(), false); LPoint3 surface_point; @@ -171,8 +171,8 @@ handle_entries() { // concave). const CollisionSolid *s1 = sd._entry->get_into(); const CollisionSolid *s2 = sd2._entry->get_into(); - if (s1 != (CollisionSolid *)NULL && - s2 != (CollisionSolid *)NULL && + if (s1 != nullptr && + s2 != nullptr && s1->is_exact_type(CollisionPolygon::get_class_type()) && s2->is_exact_type(CollisionPolygon::get_class_type()) && sd._entry->get_into_node_path() == diff --git a/panda/src/collide/collisionHandlerQueue.cxx b/panda/src/collide/collisionHandlerQueue.cxx index 9c8909f3bc..75761362bd 100644 --- a/panda/src/collide/collisionHandlerQueue.cxx +++ b/panda/src/collide/collisionHandlerQueue.cxx @@ -58,7 +58,7 @@ begin_group() { */ void CollisionHandlerQueue:: add_entry(CollisionEntry *entry) { - nassertv(entry != (CollisionEntry *)NULL); + nassertv(entry != nullptr); _entries.push_back(entry); } @@ -118,7 +118,7 @@ get_num_entries() const { */ CollisionEntry *CollisionHandlerQueue:: get_entry(int n) const { - nassertr(n >= 0 && n < (int)_entries.size(), NULL); + nassertr(n >= 0 && n < (int)_entries.size(), nullptr); return _entries[n]; } @@ -126,7 +126,7 @@ get_entry(int n) const { * */ void CollisionHandlerQueue:: -output(ostream &out) const { +output(std::ostream &out) const { out << "CollisionHandlerQueue, " << _entries.size() << " entries"; } @@ -134,7 +134,7 @@ output(ostream &out) const { * */ void CollisionHandlerQueue:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "CollisionHandlerQueue, " << _entries.size() << " entries:\n"; diff --git a/panda/src/collide/collisionHandlerQueue.h b/panda/src/collide/collisionHandlerQueue.h index 0651b545c7..cfef93c540 100644 --- a/panda/src/collide/collisionHandlerQueue.h +++ b/panda/src/collide/collisionHandlerQueue.h @@ -42,8 +42,8 @@ PUBLISHED: MAKE_SEQ(get_entries, get_num_entries, get_entry); MAKE_SEQ_PROPERTY(entries, get_num_entries, get_entry); - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; private: typedef pvector< PT(CollisionEntry) > Entries; @@ -67,7 +67,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const CollisionHandlerQueue &chq) { +INLINE std::ostream &operator << (std::ostream &out, const CollisionHandlerQueue &chq) { chq.output(out); return out; } diff --git a/panda/src/collide/collisionInvSphere.cxx b/panda/src/collide/collisionInvSphere.cxx index 35a73225dd..8a75135e55 100644 --- a/panda/src/collide/collisionInvSphere.cxx +++ b/panda/src/collide/collisionInvSphere.cxx @@ -47,7 +47,7 @@ make_copy() { PT(CollisionEntry) CollisionInvSphere:: test_intersection(const CollisionEntry &) const { report_undefined_from_intersection(get_type()); - return NULL; + return nullptr; } /** @@ -72,7 +72,7 @@ get_test_pcollector() { * */ void CollisionInvSphere:: -output(ostream &out) const { +output(std::ostream &out) const { out << "invsphere, c (" << get_center() << "), r " << get_radius(); } @@ -92,7 +92,7 @@ compute_internal_bounds() const { PT(CollisionEntry) CollisionInvSphere:: test_intersection_from_sphere(const CollisionEntry &entry) const { const CollisionSphere *sphere; - DCAST_INTO_R(sphere, entry.get_from(), NULL); + DCAST_INTO_R(sphere, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -108,7 +108,7 @@ test_intersection_from_sphere(const CollisionEntry &entry) const { PN_stdfloat dist2 = dot(vec, vec); if (dist2 < (into_radius - from_radius) * (into_radius - from_radius)) { // No intersection--the sphere is within the hollow. - return NULL; + return nullptr; } if (collide_cat.is_debug()) { @@ -144,7 +144,7 @@ test_intersection_from_sphere(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionInvSphere:: test_intersection_from_line(const CollisionEntry &entry) const { const CollisionLine *line; - DCAST_INTO_R(line, entry.get_from(), NULL); + DCAST_INTO_R(line, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -185,7 +185,7 @@ test_intersection_from_line(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionInvSphere:: test_intersection_from_ray(const CollisionEntry &entry) const { const CollisionRay *ray; - DCAST_INTO_R(ray, entry.get_from(), NULL); + DCAST_INTO_R(ray, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -198,7 +198,7 @@ test_intersection_from_ray(const CollisionEntry &entry) const { t1 = t2 = 0.0; } - t2 = max(t2, 0.0); + t2 = std::max(t2, 0.0); if (collide_cat.is_debug()) { collide_cat.debug() @@ -228,7 +228,7 @@ test_intersection_from_ray(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionInvSphere:: test_intersection_from_segment(const CollisionEntry &entry) const { const CollisionSegment *segment; - DCAST_INTO_R(segment, entry.get_from(), NULL); + DCAST_INTO_R(segment, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -254,17 +254,17 @@ test_intersection_from_segment(const CollisionEntry &entry) const { } else if (t2 <= 1.0) { // The bottom edge of the segment intersects the shell. - t = min(t2, 1.0); + t = std::min(t2, 1.0); } else if (t1 >= 0.0) { // The top edge of the segment intersects the shell. - t = max(t1, 0.0); + t = std::max(t1, 0.0); } else { // Neither edge of the segment intersects the shell. It follows that both // intersection points are within the hollow center of the sphere; // therefore, there is no intersection. - return NULL; + return nullptr; } if (collide_cat.is_debug()) { diff --git a/panda/src/collide/collisionInvSphere.h b/panda/src/collide/collisionInvSphere.h index ffc9628a5b..fe8b43b10d 100644 --- a/panda/src/collide/collisionInvSphere.h +++ b/panda/src/collide/collisionInvSphere.h @@ -42,7 +42,7 @@ public: virtual PStatCollector &get_volume_pcollector(); virtual PStatCollector &get_test_pcollector(); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual PT(BoundingVolume) compute_internal_bounds() const; diff --git a/panda/src/collide/collisionLevelState.I b/panda/src/collide/collisionLevelState.I index 5dc74aa691..db618f99e7 100644 --- a/panda/src/collide/collisionLevelState.I +++ b/panda/src/collide/collisionLevelState.I @@ -147,7 +147,7 @@ any_in_bounds() { is_in = true; // If there's no bounding volume, we're implicitly in. - if (col_gbv != (GeometricBoundingVolume *)NULL) { + if (col_gbv != nullptr) { is_in = (node_gbv->contains(col_gbv) != 0); _node_volume_pcollector.add_level(1); @@ -231,7 +231,7 @@ apply_transform() { int num_colliders = get_num_colliders(); new_bounds.reserve(num_colliders); for (int c = 0; c < num_colliders; c++) { - new_bounds.push_back((GeometricBoundingVolume *)NULL); + new_bounds.push_back(nullptr); } _local_bounds = new_bounds; @@ -257,8 +257,8 @@ apply_transform() { new_bounds.reserve(num_colliders); for (int c = 0; c < num_colliders; c++) { if (!has_collider(c) || - get_local_bound(c) == (GeometricBoundingVolume *)NULL) { - new_bounds.push_back((GeometricBoundingVolume *)NULL); + get_local_bound(c) == nullptr) { + new_bounds.push_back(nullptr); } else { const GeometricBoundingVolume *old_bound = get_local_bound(c); GeometricBoundingVolume *new_bound = diff --git a/panda/src/collide/collisionLevelStateBase.I b/panda/src/collide/collisionLevelStateBase.I index 2f2b366fb9..20923a9c22 100644 --- a/panda/src/collide/collisionLevelStateBase.I +++ b/panda/src/collide/collisionLevelStateBase.I @@ -88,7 +88,7 @@ get_num_colliders() const { */ INLINE const CollisionSolid *CollisionLevelStateBase:: get_collider(int n) const { - nassertr(n >= 0 && n < (int)_colliders.size(), NULL); + nassertr(n >= 0 && n < (int)_colliders.size(), nullptr); return _colliders[n]._collider; } @@ -98,7 +98,7 @@ get_collider(int n) const { */ INLINE CollisionNode *CollisionLevelStateBase:: get_collider_node(int n) const { - nassertr(n >= 0 && n < (int)_colliders.size(), NULL); + nassertr(n >= 0 && n < (int)_colliders.size(), nullptr); return _colliders[n]._node; } @@ -119,8 +119,8 @@ get_collider_node_path(int n) const { */ INLINE const GeometricBoundingVolume *CollisionLevelStateBase:: get_local_bound(int n) const { - nassertr(n >= 0 && n < (int)_colliders.size(), NULL); - nassertr(n >= 0 && n < (int)_local_bounds.size(), NULL); + nassertr(n >= 0 && n < (int)_colliders.size(), nullptr); + nassertr(n >= 0 && n < (int)_local_bounds.size(), nullptr); // For whatever reason, the Intel compiler can't figure this line out. // return _local_bounds[n]; @@ -137,8 +137,8 @@ get_local_bound(int n) const { */ INLINE const GeometricBoundingVolume *CollisionLevelStateBase:: get_parent_bound(int n) const { - nassertr(n >= 0 && n < (int)_colliders.size(), NULL); - nassertr(n >= 0 && n < (int)_parent_bounds.size(), NULL); + nassertr(n >= 0 && n < (int)_colliders.size(), nullptr); + nassertr(n >= 0 && n < (int)_parent_bounds.size(), nullptr); // But it can figure out this equivalent line. return *(_parent_bounds + n); diff --git a/panda/src/collide/collisionLevelStateBase.cxx b/panda/src/collide/collisionLevelStateBase.cxx index c66f58e8fc..02d7cc2fd2 100644 --- a/panda/src/collide/collisionLevelStateBase.cxx +++ b/panda/src/collide/collisionLevelStateBase.cxx @@ -52,7 +52,7 @@ prepare_collider(const ColliderDef &def, const NodePath &root) { const CollisionSolid *collider = def._collider; CPT(BoundingVolume) bv = collider->get_bounds(); if (!bv->is_of_type(GeometricBoundingVolume::get_class_type())) { - _local_bounds.push_back((GeometricBoundingVolume *)NULL); + _local_bounds.push_back(nullptr); } else { // We can use a plain pointer, rather than a PT() here, because we know we // are going to save the volume in the vector, below. diff --git a/panda/src/collide/collisionLine.cxx b/panda/src/collide/collisionLine.cxx index 5e98087145..27b066b3c9 100644 --- a/panda/src/collide/collisionLine.cxx +++ b/panda/src/collide/collisionLine.cxx @@ -51,7 +51,7 @@ test_intersection(const CollisionEntry &entry) const { * */ void CollisionLine:: -output(ostream &out) const { +output(std::ostream &out) const { out << "line, o (" << get_origin() << "), d (" << get_direction() << ")"; } diff --git a/panda/src/collide/collisionLine.h b/panda/src/collide/collisionLine.h index 71904192de..d2a0236046 100644 --- a/panda/src/collide/collisionLine.h +++ b/panda/src/collide/collisionLine.h @@ -36,7 +36,7 @@ public: virtual PT(CollisionEntry) test_intersection(const CollisionEntry &entry) const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual void fill_viz_geom(); diff --git a/panda/src/collide/collisionNode.cxx b/panda/src/collide/collisionNode.cxx index 9de94617b3..ce037f917f 100644 --- a/panda/src/collide/collisionNode.cxx +++ b/panda/src/collide/collisionNode.cxx @@ -37,7 +37,7 @@ TypeHandle CollisionNode::_type_handle; * */ CollisionNode:: -CollisionNode(const string &name) : +CollisionNode(const std::string &name) : PandaNode(name), _from_collide_mask(get_default_collide_mask()), _collider_sort(0) @@ -142,7 +142,7 @@ combine_with(PandaNode *other) { } } - return NULL; + return nullptr; } /** @@ -184,7 +184,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { for (si = _solids.begin(); si != _solids.end(); ++si) { CPT(CollisionSolid) solid = (*si).get_read_pointer(); PT(PandaNode) node = solid->get_viz(trav, data, false); - if (node != (PandaNode *)NULL) { + if (node != nullptr) { CullTraverserData next_data(data, node); // We don't want to inherit the render state from above for these guys. @@ -206,7 +206,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { for (si = _solids.begin(); si != _solids.end(); ++si) { CPT(CollisionSolid) solid = (*si).get_read_pointer(); PT(PandaNode) node = solid->get_viz(trav, data, false); - if (node != (PandaNode *)NULL) { + if (node != nullptr) { CullTraverserData next_data(data, node); next_data._net_transform = @@ -252,7 +252,7 @@ is_collision_node() const { * classes to include some information relevant to the class. */ void CollisionNode:: -output(ostream &out) const { +output(std::ostream &out) const { PandaNode::output(out); out << " (" << _solids.size() << " solids)"; } @@ -331,8 +331,8 @@ CPT(RenderState) CollisionNode:: get_last_pos_state() { // Once someone asks for this pointer, we hold its reference count and never // free it. - static CPT(RenderState) state = (const RenderState *)NULL; - if (state == (const RenderState *)NULL) { + static CPT(RenderState) state = nullptr; + if (state == nullptr) { state = RenderState::make (ColorScaleAttrib::make(LVecBase4(1.0f, 1.0f, 1.0f, 0.5f)), TransparencyAttrib::make(TransparencyAttrib::M_alpha)); @@ -422,7 +422,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { for(int i = 0; i < num_solids; i++) { manager->read_pointer(scan); // Push back a NULL for each solid, for now. We'll fill them in later. - _solids.push_back((CollisionSolid *)NULL); + _solids.push_back(nullptr); } _from_collide_mask.set_word(scan.get_uint32()); diff --git a/panda/src/collide/collisionNode.h b/panda/src/collide/collisionNode.h index e9a61b404d..8dd46f6a28 100644 --- a/panda/src/collide/collisionNode.h +++ b/panda/src/collide/collisionNode.h @@ -29,7 +29,7 @@ */ class EXPCL_PANDA_COLLIDE CollisionNode : public PandaNode { PUBLISHED: - explicit CollisionNode(const string &name); + explicit CollisionNode(const std::string &name); protected: CollisionNode(const CollisionNode ©); @@ -46,7 +46,7 @@ public: virtual bool is_renderable() const; virtual bool is_collision_node() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; PUBLISHED: INLINE void set_collide_mask(CollideMask mask); diff --git a/panda/src/collide/collisionParabola.cxx b/panda/src/collide/collisionParabola.cxx index 734647b16c..b758cf037a 100644 --- a/panda/src/collide/collisionParabola.cxx +++ b/panda/src/collide/collisionParabola.cxx @@ -90,7 +90,7 @@ get_test_pcollector() { * */ void CollisionParabola:: -output(ostream &out) const { +output(std::ostream &out) const { out << _parabola << ", t1 = " << _t1 << ", t2 = " << _t2; } @@ -145,8 +145,8 @@ compute_internal_bounds() const { for (int i = 0; i < num_points; ++i) { double t = (double)(i + 1) / (double)(num_points + 1); LPoint3 p = psp.calc_point(get_t1() + t * (get_t2() - get_t1())); - min_z = min(min_z, p[2]); - max_z = max(max_z, p[2]); + min_z = std::min(min_z, p[2]); + max_z = std::max(max_z, p[2]); } // That gives us a simple bounding volume in parabola space. @@ -157,7 +157,7 @@ compute_internal_bounds() const { LPoint3(0.01, 0, max_z), LPoint3(-0.01, 0, max_z)); // And convert that back into real space. volume->xform(from_parabola); - return volume.p(); + return volume; } /** diff --git a/panda/src/collide/collisionParabola.h b/panda/src/collide/collisionParabola.h index 2f72518ac4..c09a932938 100644 --- a/panda/src/collide/collisionParabola.h +++ b/panda/src/collide/collisionParabola.h @@ -48,7 +48,7 @@ public: virtual PStatCollector &get_volume_pcollector(); virtual PStatCollector &get_test_pcollector(); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; PUBLISHED: INLINE void set_parabola(const LParabola ¶bola); diff --git a/panda/src/collide/collisionPlane.cxx b/panda/src/collide/collisionPlane.cxx index d722adde7b..8a325ea082 100644 --- a/panda/src/collide/collisionPlane.cxx +++ b/panda/src/collide/collisionPlane.cxx @@ -89,7 +89,7 @@ get_test_pcollector() { * */ void CollisionPlane:: -output(ostream &out) const { +output(std::ostream &out) const { out << "cplane, (" << _plane << ")"; } @@ -107,7 +107,7 @@ compute_internal_bounds() const { PT(CollisionEntry) CollisionPlane:: test_intersection_from_sphere(const CollisionEntry &entry) const { const CollisionSphere *sphere; - DCAST_INTO_R(sphere, entry.get_from(), NULL); + DCAST_INTO_R(sphere, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -119,7 +119,7 @@ test_intersection_from_sphere(const CollisionEntry &entry) const { PN_stdfloat dist = dist_to_plane(from_center); if (dist > from_radius) { // No intersection. - return NULL; + return nullptr; } if (collide_cat.is_debug()) { @@ -146,7 +146,7 @@ test_intersection_from_sphere(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionPlane:: test_intersection_from_line(const CollisionEntry &entry) const { const CollisionLine *line; - DCAST_INTO_R(line, entry.get_from(), NULL); + DCAST_INTO_R(line, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -159,7 +159,7 @@ test_intersection_from_line(const CollisionEntry &entry) const { if (_plane.dist_to_plane(from_origin) > 0.0f) { // The line is entirely in front of the plane. - return NULL; + return nullptr; } // The line is entirely behind the plane. @@ -191,7 +191,7 @@ test_intersection_from_line(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionPlane:: test_intersection_from_ray(const CollisionEntry &entry) const { const CollisionRay *ray; - DCAST_INTO_R(ray, entry.get_from(), NULL); + DCAST_INTO_R(ray, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -208,13 +208,13 @@ test_intersection_from_ray(const CollisionEntry &entry) const { } else { if (!_plane.intersects_line(t, from_origin, from_direction)) { // No intersection. The ray is parallel to the plane. - return NULL; + return nullptr; } if (t < 0.0f) { // The intersection point is before the start of the ray, and so the ray // is entirely in front of the plane. - return NULL; + return nullptr; } } @@ -243,7 +243,7 @@ test_intersection_from_ray(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionPlane:: test_intersection_from_segment(const CollisionEntry &entry) const { const CollisionSegment *segment; - DCAST_INTO_R(segment, entry.get_from(), NULL); + DCAST_INTO_R(segment, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -255,7 +255,7 @@ test_intersection_from_segment(const CollisionEntry &entry) const { if (dist_a >= 0.0f && dist_b >= 0.0f) { // Entirely in front of the plane means no intersection. - return NULL; + return nullptr; } if (collide_cat.is_debug()) { @@ -300,7 +300,7 @@ test_intersection_from_segment(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionPlane:: test_intersection_from_tube(const CollisionEntry &entry) const { const CollisionTube *tube; - DCAST_INTO_R(tube, entry.get_from(), NULL); + DCAST_INTO_R(tube, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -315,7 +315,7 @@ test_intersection_from_tube(const CollisionEntry &entry) const { if (dist_a >= from_radius && dist_b >= from_radius) { // Entirely in front of the plane means no intersection. - return NULL; + return nullptr; } if (collide_cat.is_debug()) { @@ -371,7 +371,7 @@ test_intersection_from_tube(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionPlane:: test_intersection_from_parabola(const CollisionEntry &entry) const { const CollisionParabola *parabola; - DCAST_INTO_R(parabola, entry.get_from(), NULL); + DCAST_INTO_R(parabola, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -390,14 +390,14 @@ test_intersection_from_parabola(const CollisionEntry &entry) const { if (!get_plane().intersects_parabola(t1, t2, local_p)) { // No intersection. The infinite parabola is entirely in front of the // plane. - return NULL; + return nullptr; } if (t1 >= parabola->get_t1() && t1 <= parabola->get_t2()) { if (t2 >= parabola->get_t1() && t2 <= parabola->get_t2()) { // Both intersection points are within our segment of the parabola. // Choose the first of the two. - t = min(t1, t2); + t = std::min(t1, t2); } else { // Only t1 is within our segment. t = t1; @@ -409,7 +409,7 @@ test_intersection_from_parabola(const CollisionEntry &entry) const { } else { // Neither intersection point is within our segment. - return NULL; + return nullptr; } } @@ -437,7 +437,7 @@ test_intersection_from_parabola(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionPlane:: test_intersection_from_box(const CollisionEntry &entry) const { const CollisionBox *box; - DCAST_INTO_R(box, entry.get_from(), NULL); + DCAST_INTO_R(box, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -459,7 +459,7 @@ test_intersection_from_box(const CollisionEntry &entry) const { if (depth > 0) { // No collision. - return NULL; + return nullptr; } if (collide_cat.is_debug()) { diff --git a/panda/src/collide/collisionPlane.h b/panda/src/collide/collisionPlane.h index 4130cf2151..bc7602ba8b 100644 --- a/panda/src/collide/collisionPlane.h +++ b/panda/src/collide/collisionPlane.h @@ -42,7 +42,7 @@ public: virtual PStatCollector &get_volume_pcollector(); virtual PStatCollector &get_test_pcollector(); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; INLINE static void flush_level(); diff --git a/panda/src/collide/collisionPolygon.I b/panda/src/collide/collisionPolygon.I index 4a048a3995..6c7785d730 100644 --- a/panda/src/collide/collisionPolygon.I +++ b/panda/src/collide/collisionPolygon.I @@ -57,7 +57,7 @@ CollisionPolygon() { /** * Returns the number of vertices of the CollisionPolygon. */ -INLINE int CollisionPolygon:: +INLINE size_t CollisionPolygon:: get_num_points() const { return _points.size(); } @@ -66,8 +66,8 @@ get_num_points() const { * Returns the nth vertex of the CollisionPolygon, expressed in 3-D space. */ INLINE LPoint3 CollisionPolygon:: -get_point(int n) const { - nassertr(n >= 0 && n < (int)_points.size(), LPoint3::zero()); +get_point(size_t n) const { + nassertr(n < _points.size(), LPoint3::zero()); LMatrix4 to_3d_mat; rederive_to_3d_mat(to_3d_mat); return to_3d(_points[n]._p, to_3d_mat); diff --git a/panda/src/collide/collisionPolygon.cxx b/panda/src/collide/collisionPolygon.cxx index 646a7b9439..24c8230d2f 100644 --- a/panda/src/collide/collisionPolygon.cxx +++ b/panda/src/collide/collisionPolygon.cxx @@ -41,6 +41,9 @@ #include +using std::max; +using std::min; + PStatCollector CollisionPolygon::_volume_pcollector("Collision Volumes:CollisionPolygon"); PStatCollector CollisionPolygon::_test_pcollector("Collision Tests:CollisionPolygon"); TypeHandle CollisionPolygon::_type_handle; @@ -235,7 +238,7 @@ PT(PandaNode) CollisionPolygon:: get_viz(const CullTraverser *trav, const CullTraverserData &data, bool bounds_only) const { const ClipPlaneAttrib *cpa = DCAST(ClipPlaneAttrib, data._state->get_attrib(ClipPlaneAttrib::get_class_slot())); - if (cpa == (const ClipPlaneAttrib *)NULL) { + if (cpa == nullptr) { // Fortunately, the polygon is not clipped. This is the normal, easy // case. return CollisionSolid::get_viz(trav, data, bounds_only); @@ -259,7 +262,7 @@ get_viz(const CullTraverser *trav, const CullTraverserData &data, if (new_points.empty()) { // All points are in front of the clip plane; draw nothing. - return NULL; + return nullptr; } // Draw the clipped polygon. @@ -268,9 +271,9 @@ get_viz(const CullTraverser *trav, const CullTraverserData &data, draw_polygon(viz_geom_node, bounds_viz_geom_node, new_points); if (bounds_only) { - return bounds_viz_geom_node.p(); + return bounds_viz_geom_node; } else { - return viz_geom_node.p(); + return viz_geom_node; } } @@ -296,7 +299,7 @@ get_test_pcollector() { * */ void CollisionPolygon:: -output(ostream &out) const { +output(std::ostream &out) const { out << "cpolygon, (" << get_plane() << "), " << _points.size() << " vertices"; } @@ -305,7 +308,7 @@ output(ostream &out) const { * */ void CollisionPolygon:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << (*this) << "\n"; Points::const_iterator pi; for (pi = _points.begin(); pi != _points.end(); ++pi) { @@ -360,11 +363,11 @@ compute_internal_bounds() const { PT(CollisionEntry) CollisionPolygon:: test_intersection_from_sphere(const CollisionEntry &entry) const { if (_points.size() < 3) { - return NULL; + return nullptr; } const CollisionSphere *sphere; - DCAST_INTO_R(sphere, entry.get_from(), NULL); + DCAST_INTO_R(sphere, entry.get_from(), nullptr); CPT(TransformState) wrt_space = entry.get_wrt_space(); CPT(TransformState) wrt_prev_space = entry.get_wrt_prev_space(); @@ -395,7 +398,7 @@ test_intersection_from_sphere(const CollisionEntry &entry) const { // in the same direction as the plane's normal. PN_stdfloat dot = delta.dot(get_normal()); if (dot > 0.1f) { - return NULL; + return nullptr; } if (IS_NEARLY_ZERO(dot)) { @@ -451,19 +454,19 @@ test_intersection_from_sphere(const CollisionEntry &entry) const { if (!get_plane().intersects_line(dist, from_center, -get_normal())) { // No intersection with plane? This means the plane's effective normal // was within the plane itself. A useless polygon. - return NULL; + return nullptr; } if (dist > from_radius || dist < -from_radius) { // No intersection with the plane. - return NULL; + return nullptr; } LPoint2 p = to_2d(from_center - dist * get_normal()); PN_stdfloat edge_dist = 0.0f; const ClipPlaneAttrib *cpa = entry.get_into_clip_planes(); - if (cpa != (ClipPlaneAttrib *)NULL) { + if (cpa != nullptr) { // We have a clip plane; apply it. Points new_points; if (apply_clip_plane(new_points, cpa, entry.get_into_node_path().get_net_transform())) { @@ -472,7 +475,7 @@ test_intersection_from_sphere(const CollisionEntry &entry) const { } else if (new_points.empty()) { // The polygon is completely clipped. - return NULL; + return nullptr; } else { // Test against the clipped polygon. @@ -489,7 +492,7 @@ test_intersection_from_sphere(const CollisionEntry &entry) const { if (edge_dist > from_radius) { // No intersection; the circle is outside the polygon. - return NULL; + return nullptr; } // The sphere appears to intersect the polygon. If the edge is less than @@ -505,7 +508,7 @@ test_intersection_from_sphere(const CollisionEntry &entry) const { if (dist > max_dist) { // There's no intersection: the sphere is hanging off the edge. - return NULL; + return nullptr; } if (collide_cat.is_debug()) { @@ -541,11 +544,11 @@ test_intersection_from_sphere(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionPolygon:: test_intersection_from_line(const CollisionEntry &entry) const { if (_points.size() < 3) { - return NULL; + return nullptr; } const CollisionLine *line; - DCAST_INTO_R(line, entry.get_from(), NULL); + DCAST_INTO_R(line, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -555,35 +558,35 @@ test_intersection_from_line(const CollisionEntry &entry) const { PN_stdfloat t; if (!get_plane().intersects_line(t, from_origin, from_direction)) { // No intersection. - return NULL; + return nullptr; } LPoint3 plane_point = from_origin + t * from_direction; LPoint2 p = to_2d(plane_point); const ClipPlaneAttrib *cpa = entry.get_into_clip_planes(); - if (cpa != (ClipPlaneAttrib *)NULL) { + if (cpa != nullptr) { // We have a clip plane; apply it. Points new_points; if (apply_clip_plane(new_points, cpa, entry.get_into_node_path().get_net_transform())) { // All points are behind the clip plane. if (!point_is_inside(p, _points)) { - return NULL; + return nullptr; } } else { if (new_points.size() < 3) { - return NULL; + return nullptr; } if (!point_is_inside(p, new_points)) { - return NULL; + return nullptr; } } } else { // No clip plane is in effect. Do the default test. if (!point_is_inside(p, _points)) { - return NULL; + return nullptr; } } @@ -609,11 +612,11 @@ test_intersection_from_line(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionPolygon:: test_intersection_from_ray(const CollisionEntry &entry) const { if (_points.size() < 3) { - return NULL; + return nullptr; } const CollisionRay *ray; - DCAST_INTO_R(ray, entry.get_from(), NULL); + DCAST_INTO_R(ray, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -623,40 +626,40 @@ test_intersection_from_ray(const CollisionEntry &entry) const { PN_stdfloat t; if (!get_plane().intersects_line(t, from_origin, from_direction)) { // No intersection. - return NULL; + return nullptr; } if (t < 0.0f) { // The intersection point is before the start of the ray. - return NULL; + return nullptr; } LPoint3 plane_point = from_origin + t * from_direction; LPoint2 p = to_2d(plane_point); const ClipPlaneAttrib *cpa = entry.get_into_clip_planes(); - if (cpa != (ClipPlaneAttrib *)NULL) { + if (cpa != nullptr) { // We have a clip plane; apply it. Points new_points; if (apply_clip_plane(new_points, cpa, entry.get_into_node_path().get_net_transform())) { // All points are behind the clip plane. if (!point_is_inside(p, _points)) { - return NULL; + return nullptr; } } else { if (new_points.size() < 3) { - return NULL; + return nullptr; } if (!point_is_inside(p, new_points)) { - return NULL; + return nullptr; } } } else { // No clip plane is in effect. Do the default test. if (!point_is_inside(p, _points)) { - return NULL; + return nullptr; } } @@ -682,11 +685,11 @@ test_intersection_from_ray(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionPolygon:: test_intersection_from_segment(const CollisionEntry &entry) const { if (_points.size() < 3) { - return NULL; + return nullptr; } const CollisionSegment *segment; - DCAST_INTO_R(segment, entry.get_from(), NULL); + DCAST_INTO_R(segment, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -697,41 +700,41 @@ test_intersection_from_segment(const CollisionEntry &entry) const { PN_stdfloat t; if (!get_plane().intersects_line(t, from_a, from_direction)) { // No intersection. - return NULL; + return nullptr; } if (t < 0.0f || t > 1.0f) { // The intersection point is before the start of the segment or after the // end of the segment. - return NULL; + return nullptr; } LPoint3 plane_point = from_a + t * from_direction; LPoint2 p = to_2d(plane_point); const ClipPlaneAttrib *cpa = entry.get_into_clip_planes(); - if (cpa != (ClipPlaneAttrib *)NULL) { + if (cpa != nullptr) { // We have a clip plane; apply it. Points new_points; if (apply_clip_plane(new_points, cpa, entry.get_into_node_path().get_net_transform())) { // All points are behind the clip plane. if (!point_is_inside(p, _points)) { - return NULL; + return nullptr; } } else { if (new_points.size() < 3) { - return NULL; + return nullptr; } if (!point_is_inside(p, new_points)) { - return NULL; + return nullptr; } } } else { // No clip plane is in effect. Do the default test. if (!point_is_inside(p, _points)) { - return NULL; + return nullptr; } } @@ -757,11 +760,11 @@ test_intersection_from_segment(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionPolygon:: test_intersection_from_parabola(const CollisionEntry &entry) const { if (_points.size() < 3) { - return NULL; + return nullptr; } const CollisionParabola *parabola; - DCAST_INTO_R(parabola, entry.get_from(), NULL); + DCAST_INTO_R(parabola, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -772,7 +775,7 @@ test_intersection_from_parabola(const CollisionEntry &entry) const { PN_stdfloat t1, t2; if (!get_plane().intersects_parabola(t1, t2, local_p)) { // No intersection. - return NULL; + return nullptr; } PN_stdfloat t; @@ -792,35 +795,35 @@ test_intersection_from_parabola(const CollisionEntry &entry) const { } else { // Neither intersection point is within our segment. - return NULL; + return nullptr; } LPoint3 plane_point = local_p.calc_point(t); LPoint2 p = to_2d(plane_point); const ClipPlaneAttrib *cpa = entry.get_into_clip_planes(); - if (cpa != (ClipPlaneAttrib *)NULL) { + if (cpa != nullptr) { // We have a clip plane; apply it. Points new_points; if (apply_clip_plane(new_points, cpa, entry.get_into_node_path().get_net_transform())) { // All points are behind the clip plane. if (!point_is_inside(p, _points)) { - return NULL; + return nullptr; } } else { if (new_points.size() < 3) { - return NULL; + return nullptr; } if (!point_is_inside(p, new_points)) { - return NULL; + return nullptr; } } } else { // No clip plane is in effect. Do the default test. if (!point_is_inside(p, _points)) { - return NULL; + return nullptr; } } @@ -846,7 +849,7 @@ test_intersection_from_parabola(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionPolygon:: test_intersection_from_box(const CollisionEntry &entry) const { const CollisionBox *box; - DCAST_INTO_R(box, entry.get_from(), NULL); + DCAST_INTO_R(box, entry.get_from(), nullptr); // To make things easier, transform the box into the coordinate space of the // plane. @@ -864,7 +867,7 @@ test_intersection_from_box(const CollisionEntry &entry) const { // Is there a separating axis between the plane and the box? if (cabs(from_center[1]) > cabs(box_x[1]) + cabs(box_y[1]) + cabs(box_z[1])) { // There is one. No collision. - return NULL; + return nullptr; } // Now do the same for each of the box' primary axes. @@ -873,19 +876,19 @@ test_intersection_from_box(const CollisionEntry &entry) const { r1 = cabs(box_x.dot(box_x)) + cabs(box_y.dot(box_x)) + cabs(box_z.dot(box_x)); project(box_x, center, r2); if (cabs(from_center.dot(box_x) - center) > r1 + r2) { - return NULL; + return nullptr; } r1 = cabs(box_x.dot(box_y)) + cabs(box_y.dot(box_y)) + cabs(box_z.dot(box_y)); project(box_y, center, r2); if (cabs(from_center.dot(box_y) - center) > r1 + r2) { - return NULL; + return nullptr; } r1 = cabs(box_x.dot(box_z)) + cabs(box_y.dot(box_z)) + cabs(box_z.dot(box_z)); project(box_z, center, r2); if (cabs(from_center.dot(box_z) - center) > r1 + r2) { - return NULL; + return nullptr; } // Now do the same check for the cross products between the box axes and the @@ -901,7 +904,7 @@ test_intersection_from_box(const CollisionEntry &entry) const { r1 = cabs(box_x.dot(axis)) + cabs(box_y.dot(axis)) + cabs(box_z.dot(axis)); project(axis, center, r2); if (cabs(from_center.dot(axis) - center) > r1 + r2) { - return NULL; + return nullptr; } axis.set(-box_y[1] * pd._v[1], @@ -910,7 +913,7 @@ test_intersection_from_box(const CollisionEntry &entry) const { r1 = cabs(box_x.dot(axis)) + cabs(box_y.dot(axis)) + cabs(box_z.dot(axis)); project(axis, center, r2); if (cabs(from_center.dot(axis) - center) > r1 + r2) { - return NULL; + return nullptr; } axis.set(-box_z[1] * pd._v[1], @@ -919,7 +922,7 @@ test_intersection_from_box(const CollisionEntry &entry) const { r1 = cabs(box_x.dot(axis)) + cabs(box_y.dot(axis)) + cabs(box_z.dot(axis)); project(axis, center, r2); if (cabs(from_center.dot(axis) - center) > r1 + r2) { - return NULL; + return nullptr; } } @@ -958,7 +961,7 @@ fill_viz_geom() { collide_cat.debug() << "Recomputing viz for " << *this << "\n"; } - nassertv(_viz_geom != (GeomNode *)NULL && _bounds_viz_geom != (GeomNode *)NULL); + nassertv(_viz_geom != nullptr && _bounds_viz_geom != nullptr); draw_polygon(_viz_geom, _bounds_viz_geom, _points); } diff --git a/panda/src/collide/collisionPolygon.h b/panda/src/collide/collisionPolygon.h index 464c0e73b6..f7fa771bfa 100644 --- a/panda/src/collide/collisionPolygon.h +++ b/panda/src/collide/collisionPolygon.h @@ -45,8 +45,8 @@ public: PUBLISHED: virtual LPoint3 get_collision_origin() const; - INLINE int get_num_points() const; - INLINE LPoint3 get_point(int n) const; + INLINE size_t get_num_points() const; + INLINE LPoint3 get_point(size_t n) const; MAKE_SEQ(get_points, get_num_points, get_point); @@ -74,8 +74,8 @@ public: virtual PStatCollector &get_volume_pcollector(); virtual PStatCollector &get_test_pcollector(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; INLINE static void flush_level(); diff --git a/panda/src/collide/collisionRay.cxx b/panda/src/collide/collisionRay.cxx index 05aa445aa1..9cbf9223fe 100644 --- a/panda/src/collide/collisionRay.cxx +++ b/panda/src/collide/collisionRay.cxx @@ -72,7 +72,7 @@ get_collision_origin() const { * */ void CollisionRay:: -output(ostream &out) const { +output(std::ostream &out) const { out << "ray, o (" << get_origin() << "), d (" << get_direction() << ")"; } diff --git a/panda/src/collide/collisionRay.h b/panda/src/collide/collisionRay.h index d317761906..99b7446ced 100644 --- a/panda/src/collide/collisionRay.h +++ b/panda/src/collide/collisionRay.h @@ -42,7 +42,7 @@ public: virtual void xform(const LMatrix4 &mat); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; PUBLISHED: INLINE void set_origin(const LPoint3 &origin); diff --git a/panda/src/collide/collisionRecorder.cxx b/panda/src/collide/collisionRecorder.cxx index 09d87a9971..9abd0814a7 100644 --- a/panda/src/collide/collisionRecorder.cxx +++ b/panda/src/collide/collisionRecorder.cxx @@ -25,7 +25,7 @@ CollisionRecorder:: CollisionRecorder() { _num_missed = 0; _num_detected = 0; - _trav = (CollisionTraverser *)NULL; + _trav = nullptr; } /** @@ -33,7 +33,7 @@ CollisionRecorder() { */ CollisionRecorder:: ~CollisionRecorder() { - if (_trav != (CollisionTraverser *)NULL) { + if (_trav != nullptr) { _trav->clear_recorder(); } } @@ -42,7 +42,7 @@ CollisionRecorder:: * */ void CollisionRecorder:: -output(ostream &out) const { +output(std::ostream &out) const { out << "tested " << _num_missed + _num_detected << ", detected " << _num_detected << "\n"; } diff --git a/panda/src/collide/collisionRecorder.h b/panda/src/collide/collisionRecorder.h index a9ceefa250..08a254122c 100644 --- a/panda/src/collide/collisionRecorder.h +++ b/panda/src/collide/collisionRecorder.h @@ -35,7 +35,7 @@ public: virtual ~CollisionRecorder(); PUBLISHED: - void output(ostream &out) const; + void output(std::ostream &out) const; public: virtual void begin_traversal(); diff --git a/panda/src/collide/collisionSegment.cxx b/panda/src/collide/collisionSegment.cxx index 3fa0fe0524..f0ea03f12a 100644 --- a/panda/src/collide/collisionSegment.cxx +++ b/panda/src/collide/collisionSegment.cxx @@ -75,7 +75,7 @@ get_collision_origin() const { * */ void CollisionSegment:: -output(ostream &out) const { +output(std::ostream &out) const { out << "segment, a (" << _a << "), b (" << _b << ")"; } @@ -131,7 +131,7 @@ compute_internal_bounds() const { LPoint3(0.01, -0.01, 0.01), LPoint3(-0.01, -0.01, 0.01)); volume->xform(from_segment); - return volume.p(); + return volume; } /** diff --git a/panda/src/collide/collisionSegment.h b/panda/src/collide/collisionSegment.h index 429eff426d..705855b791 100644 --- a/panda/src/collide/collisionSegment.h +++ b/panda/src/collide/collisionSegment.h @@ -46,7 +46,7 @@ public: virtual void xform(const LMatrix4 &mat); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; PUBLISHED: INLINE void set_point_a(const LPoint3 &a); diff --git a/panda/src/collide/collisionSolid.cxx b/panda/src/collide/collisionSolid.cxx index 5f27903b45..b862ec7c73 100644 --- a/panda/src/collide/collisionSolid.cxx +++ b/panda/src/collide/collisionSolid.cxx @@ -108,7 +108,7 @@ set_bounds(const BoundingVolume &bounding_volume) { PT(CollisionEntry) CollisionSolid:: test_intersection(const CollisionEntry &) const { report_undefined_from_intersection(get_type()); - return NULL; + return nullptr; } /** @@ -134,7 +134,7 @@ PT(PandaNode) CollisionSolid:: get_viz(const CullTraverser *, const CullTraverserData &, bool bounds_only) const { LightMutexHolder holder(_lock); if ((_flags & F_viz_geom_stale) != 0) { - if (_viz_geom == (GeomNode *)NULL) { + if (_viz_geom == nullptr) { ((CollisionSolid *)this)->_viz_geom = new GeomNode("viz"); ((CollisionSolid *)this)->_bounds_viz_geom = new GeomNode("bounds_viz"); } else { @@ -146,9 +146,9 @@ get_viz(const CullTraverser *, const CullTraverserData &, bool bounds_only) cons } if (bounds_only) { - return _bounds_viz_geom.p(); + return _bounds_viz_geom; } else { - return _viz_geom.p(); + return _viz_geom; } } @@ -174,7 +174,7 @@ get_test_pcollector() { * */ void CollisionSolid:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type(); } @@ -182,7 +182,7 @@ output(ostream &out) const { * */ void CollisionSolid:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << (*this) << "\n"; } @@ -202,7 +202,7 @@ PT(CollisionEntry) CollisionSolid:: test_intersection_from_sphere(const CollisionEntry &) const { report_undefined_intersection_test(CollisionSphere::get_class_type(), get_type()); - return NULL; + return nullptr; } /** @@ -213,7 +213,7 @@ PT(CollisionEntry) CollisionSolid:: test_intersection_from_line(const CollisionEntry &) const { report_undefined_intersection_test(CollisionLine::get_class_type(), get_type()); - return NULL; + return nullptr; } /** @@ -224,7 +224,7 @@ PT(CollisionEntry) CollisionSolid:: test_intersection_from_ray(const CollisionEntry &) const { report_undefined_intersection_test(CollisionRay::get_class_type(), get_type()); - return NULL; + return nullptr; } /** @@ -235,7 +235,7 @@ PT(CollisionEntry) CollisionSolid:: test_intersection_from_segment(const CollisionEntry &) const { report_undefined_intersection_test(CollisionSegment::get_class_type(), get_type()); - return NULL; + return nullptr; } /** @@ -246,7 +246,7 @@ PT(CollisionEntry) CollisionSolid:: test_intersection_from_tube(const CollisionEntry &) const { report_undefined_intersection_test(CollisionTube::get_class_type(), get_type()); - return NULL; + return nullptr; } /** @@ -257,7 +257,7 @@ PT(CollisionEntry) CollisionSolid:: test_intersection_from_parabola(const CollisionEntry &) const { report_undefined_intersection_test(CollisionParabola::get_class_type(), get_type()); - return NULL; + return nullptr; } /** @@ -268,7 +268,7 @@ PT(CollisionEntry) CollisionSolid:: test_intersection_from_box(const CollisionEntry &) const { report_undefined_intersection_test(CollisionBox::get_class_type(), get_type()); - return NULL; + return nullptr; } @@ -389,8 +389,8 @@ CPT(RenderState) CollisionSolid:: get_solid_viz_state() { // Once someone asks for this pointer, we hold its reference count and never // free it. - static CPT(RenderState) base_state = (const RenderState *)NULL; - if (base_state == (const RenderState *)NULL) { + static CPT(RenderState) base_state = nullptr; + if (base_state == nullptr) { base_state = RenderState::make (CullFaceAttrib::make(CullFaceAttrib::M_cull_clockwise), RenderModeAttrib::make(RenderModeAttrib::M_filled), @@ -398,24 +398,24 @@ get_solid_viz_state() { } if (!do_is_tangible()) { - static CPT(RenderState) intangible_state = (const RenderState *)NULL; - if (intangible_state == (const RenderState *)NULL) { + static CPT(RenderState) intangible_state = nullptr; + if (intangible_state == nullptr) { intangible_state = base_state->add_attrib (ColorAttrib::make_flat(LColor(1.0f, 0.3, 0.5f, 0.5f))); } return intangible_state; } else if (do_has_effective_normal()) { - static CPT(RenderState) fakenormal_state = (const RenderState *)NULL; - if (fakenormal_state == (const RenderState *)NULL) { + static CPT(RenderState) fakenormal_state = nullptr; + if (fakenormal_state == nullptr) { fakenormal_state = base_state->add_attrib (ColorAttrib::make_flat(LColor(0.5f, 0.5f, 1.0f, 0.5f))); } return fakenormal_state; } else { - static CPT(RenderState) tangible_state = (const RenderState *)NULL; - if (tangible_state == (const RenderState *)NULL) { + static CPT(RenderState) tangible_state = nullptr; + if (tangible_state == nullptr) { tangible_state = base_state->add_attrib (ColorAttrib::make_flat(LColor(1.0f, 1.0f, 1.0f, 0.5f))); } @@ -435,8 +435,8 @@ CPT(RenderState) CollisionSolid:: get_wireframe_viz_state() { // Once someone asks for this pointer, we hold its reference count and never // free it. - static CPT(RenderState) base_state = (const RenderState *)NULL; - if (base_state == (const RenderState *)NULL) { + static CPT(RenderState) base_state = nullptr; + if (base_state == nullptr) { base_state = RenderState::make (CullFaceAttrib::make(CullFaceAttrib::M_cull_none), RenderModeAttrib::make(RenderModeAttrib::M_wireframe), @@ -444,24 +444,24 @@ get_wireframe_viz_state() { } if (!do_is_tangible()) { - static CPT(RenderState) intangible_state = (const RenderState *)NULL; - if (intangible_state == (const RenderState *)NULL) { + static CPT(RenderState) intangible_state = nullptr; + if (intangible_state == nullptr) { intangible_state = base_state->add_attrib (ColorAttrib::make_flat(LColor(1.0f, 1.0f, 0.0f, 1.0f))); } return intangible_state; } else if (do_has_effective_normal()) { - static CPT(RenderState) fakenormal_state = (const RenderState *)NULL; - if (fakenormal_state == (const RenderState *)NULL) { + static CPT(RenderState) fakenormal_state = nullptr; + if (fakenormal_state == nullptr) { fakenormal_state = base_state->add_attrib (ColorAttrib::make_flat(LColor(0.0f, 0.0f, 1.0f, 1.0f))); } return fakenormal_state; } else { - static CPT(RenderState) tangible_state = (const RenderState *)NULL; - if (tangible_state == (const RenderState *)NULL) { + static CPT(RenderState) tangible_state = nullptr; + if (tangible_state == nullptr) { tangible_state = base_state->add_attrib (ColorAttrib::make_flat(LColor(0.0f, 0.0f, 1.0f, 1.0f))); } @@ -480,8 +480,8 @@ CPT(RenderState) CollisionSolid:: get_other_viz_state() { // Once someone asks for this pointer, we hold its reference count and never // free it. - static CPT(RenderState) base_state = (const RenderState *)NULL; - if (base_state == (const RenderState *)NULL) { + static CPT(RenderState) base_state = nullptr; + if (base_state == nullptr) { base_state = RenderState::make (CullFaceAttrib::make(CullFaceAttrib::M_cull_clockwise), RenderModeAttrib::make(RenderModeAttrib::M_filled), @@ -504,8 +504,8 @@ CPT(RenderState) CollisionSolid:: get_solid_bounds_viz_state() { // Once someone asks for this pointer, we hold its reference count and never // free it. - static CPT(RenderState) base_state = (const RenderState *)NULL; - if (base_state == (const RenderState *)NULL) { + static CPT(RenderState) base_state = nullptr; + if (base_state == nullptr) { base_state = RenderState::make (CullFaceAttrib::make(CullFaceAttrib::M_cull_clockwise), RenderModeAttrib::make(RenderModeAttrib::M_filled), @@ -513,24 +513,24 @@ get_solid_bounds_viz_state() { } if (!do_is_tangible()) { - static CPT(RenderState) intangible_state = (const RenderState *)NULL; - if (intangible_state == (const RenderState *)NULL) { + static CPT(RenderState) intangible_state = nullptr; + if (intangible_state == nullptr) { intangible_state = base_state->add_attrib (ColorAttrib::make_flat(LColor(1.0f, 1.0f, 0.5f, 0.3))); } return intangible_state; } else if (do_has_effective_normal()) { - static CPT(RenderState) fakenormal_state = (const RenderState *)NULL; - if (fakenormal_state == (const RenderState *)NULL) { + static CPT(RenderState) fakenormal_state = nullptr; + if (fakenormal_state == nullptr) { fakenormal_state = base_state->add_attrib (ColorAttrib::make_flat(LColor(0.5f, 0.5f, 1.0f, 0.3))); } return fakenormal_state; } else { - static CPT(RenderState) tangible_state = (const RenderState *)NULL; - if (tangible_state == (const RenderState *)NULL) { + static CPT(RenderState) tangible_state = nullptr; + if (tangible_state == nullptr) { tangible_state = base_state->add_attrib (ColorAttrib::make_flat(LColor(1.0f, 1.0f, 0.5f, 0.3))); } @@ -550,8 +550,8 @@ CPT(RenderState) CollisionSolid:: get_wireframe_bounds_viz_state() { // Once someone asks for this pointer, we hold its reference count and never // free it. - static CPT(RenderState) base_state = (const RenderState *)NULL; - if (base_state == (const RenderState *)NULL) { + static CPT(RenderState) base_state = nullptr; + if (base_state == nullptr) { base_state = RenderState::make (CullFaceAttrib::make(CullFaceAttrib::M_cull_none), RenderModeAttrib::make(RenderModeAttrib::M_wireframe), @@ -573,8 +573,8 @@ CPT(RenderState) CollisionSolid:: get_other_bounds_viz_state() { // Once someone asks for this pointer, we hold its reference count and never // free it. - static CPT(RenderState) base_state = (const RenderState *)NULL; - if (base_state == (const RenderState *)NULL) { + static CPT(RenderState) base_state = nullptr; + if (base_state == nullptr) { base_state = RenderState::make (CullFaceAttrib::make(CullFaceAttrib::M_cull_clockwise), RenderModeAttrib::make(RenderModeAttrib::M_filled), diff --git a/panda/src/collide/collisionSolid.h b/panda/src/collide/collisionSolid.h index 4f80cb922a..6b2914e954 100644 --- a/panda/src/collide/collisionSolid.h +++ b/panda/src/collide/collisionSolid.h @@ -89,8 +89,8 @@ public: virtual PStatCollector &get_test_pcollector(); PUBLISHED: - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; protected: INLINE bool do_is_tangible() const; @@ -183,7 +183,7 @@ private: friend class CollisionBox; }; -INLINE ostream &operator << (ostream &out, const CollisionSolid &cs) { +INLINE std::ostream &operator << (std::ostream &out, const CollisionSolid &cs) { cs.output(out); return out; } diff --git a/panda/src/collide/collisionSphere.cxx b/panda/src/collide/collisionSphere.cxx index 139a39a4b1..a07b1fbcbc 100644 --- a/panda/src/collide/collisionSphere.cxx +++ b/panda/src/collide/collisionSphere.cxx @@ -33,6 +33,9 @@ #include "geomTristrips.h" #include "geomVertexWriter.h" +using std::max; +using std::min; + PStatCollector CollisionSphere::_volume_pcollector( "Collision Volumes:CollisionSphere"); PStatCollector CollisionSphere::_test_pcollector( @@ -102,7 +105,7 @@ get_test_pcollector() { * */ void CollisionSphere:: -output(ostream &out) const { +output(std::ostream &out) const { out << "sphere, c (" << get_center() << "), r " << get_radius(); } @@ -120,7 +123,7 @@ compute_internal_bounds() const { PT(CollisionEntry) CollisionSphere:: test_intersection_from_sphere(const CollisionEntry &entry) const { const CollisionSphere *sphere; - DCAST_INTO_R(sphere, entry.get_from(), NULL); + DCAST_INTO_R(sphere, entry.get_from(), nullptr); CPT(TransformState) wrt_space = entry.get_wrt_space(); @@ -152,13 +155,13 @@ test_intersection_from_sphere(const CollisionEntry &entry) const { LVector3 from_direction = from_b - from_a; if (!intersects_line(t1, t2, from_a, from_direction, from_radius)) { // No intersection. - return NULL; + return nullptr; } if (t2 < 0.0 || t1 > 1.0) { // Both intersection points are before the start of the segment or // after the end of the segment. - return NULL; + return nullptr; } // doubles, not floats, to satisfy min and max templates. @@ -176,7 +179,7 @@ test_intersection_from_sphere(const CollisionEntry &entry) const { } } else { // No delta, therefore no intersection. - return NULL; + return nullptr; } } @@ -231,7 +234,7 @@ test_intersection_from_sphere(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionSphere:: test_intersection_from_line(const CollisionEntry &entry) const { const CollisionLine *line; - DCAST_INTO_R(line, entry.get_from(), NULL); + DCAST_INTO_R(line, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -241,7 +244,7 @@ test_intersection_from_line(const CollisionEntry &entry) const { double t1, t2; if (!intersects_line(t1, t2, from_origin, from_direction, 0.0f)) { // No intersection. - return NULL; + return nullptr; } if (collide_cat.is_debug()) { @@ -271,7 +274,7 @@ test_intersection_from_line(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionSphere:: test_intersection_from_box(const CollisionEntry &entry) const { const CollisionBox *box; - DCAST_INTO_R(box, entry.get_from(), NULL); + DCAST_INTO_R(box, entry.get_from(), nullptr); // Instead of transforming the box into the sphere's coordinate space, we do // it the other way around. It's easier that way. @@ -315,7 +318,7 @@ test_intersection_from_box(const CollisionEntry &entry) const { } if (d > radius_sq) { - return NULL; + return nullptr; } if (collide_cat.is_debug()) { @@ -347,7 +350,7 @@ test_intersection_from_box(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionSphere:: test_intersection_from_ray(const CollisionEntry &entry) const { const CollisionRay *ray; - DCAST_INTO_R(ray, entry.get_from(), NULL); + DCAST_INTO_R(ray, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -357,12 +360,12 @@ test_intersection_from_ray(const CollisionEntry &entry) const { double t1, t2; if (!intersects_line(t1, t2, from_origin, from_direction, 0.0f)) { // No intersection. - return NULL; + return nullptr; } if (t2 < 0.0) { // Both intersection points are before the start of the ray. - return NULL; + return nullptr; } t1 = max(t1, 0.0); @@ -394,7 +397,7 @@ test_intersection_from_ray(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionSphere:: test_intersection_from_segment(const CollisionEntry &entry) const { const CollisionSegment *segment; - DCAST_INTO_R(segment, entry.get_from(), NULL); + DCAST_INTO_R(segment, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -405,13 +408,13 @@ test_intersection_from_segment(const CollisionEntry &entry) const { double t1, t2; if (!intersects_line(t1, t2, from_a, from_direction, 0.0f)) { // No intersection. - return NULL; + return nullptr; } if (t2 < 0.0 || t1 > 1.0) { // Both intersection points are before the start of the segment or after // the end of the segment. - return NULL; + return nullptr; } t1 = max(t1, 0.0); @@ -443,7 +446,7 @@ test_intersection_from_segment(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionSphere:: test_intersection_from_tube(const CollisionEntry &entry) const { const CollisionTube *tube; - DCAST_INTO_R(tube, entry.get_from(), NULL); + DCAST_INTO_R(tube, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -458,13 +461,13 @@ test_intersection_from_tube(const CollisionEntry &entry) const { double t1, t2; if (!intersects_line(t1, t2, from_a, from_direction, from_radius)) { // No intersection. - return NULL; + return nullptr; } if (t2 < 0.0 || t1 > 1.0) { // Both intersection points are before the start of the tube or after // the end of the tube. - return NULL; + return nullptr; } PN_stdfloat t = (t1 + t2) * (PN_stdfloat)0.5; @@ -499,7 +502,7 @@ test_intersection_from_tube(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionSphere:: test_intersection_from_parabola(const CollisionEntry &entry) const { const CollisionParabola *parabola; - DCAST_INTO_R(parabola, entry.get_from(), NULL); + DCAST_INTO_R(parabola, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -512,7 +515,7 @@ test_intersection_from_parabola(const CollisionEntry &entry) const { local_p.calc_point(parabola->get_t1()), local_p.calc_point(parabola->get_t2()))) { // No intersection. - return NULL; + return nullptr; } if (collide_cat.is_debug()) { diff --git a/panda/src/collide/collisionSphere.h b/panda/src/collide/collisionSphere.h index 04fa9c4e83..8337644b42 100644 --- a/panda/src/collide/collisionSphere.h +++ b/panda/src/collide/collisionSphere.h @@ -44,7 +44,7 @@ public: virtual PStatCollector &get_volume_pcollector(); virtual PStatCollector &get_test_pcollector(); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; INLINE static void flush_level(); diff --git a/panda/src/collide/collisionTraverser.I b/panda/src/collide/collisionTraverser.I index 4f35be0a9e..dee53e3a53 100644 --- a/panda/src/collide/collisionTraverser.I +++ b/panda/src/collide/collisionTraverser.I @@ -40,7 +40,7 @@ get_respect_prev_transform() const { */ INLINE bool CollisionTraverser:: has_recorder() const { - return _recorder != (CollisionRecorder *)NULL; + return _recorder != nullptr; } /** @@ -58,7 +58,7 @@ get_recorder() const { */ INLINE void CollisionTraverser:: clear_recorder() { - set_recorder((CollisionRecorder *)NULL); + set_recorder(nullptr); } #endif // DO_COLLISION_RECORDING diff --git a/panda/src/collide/collisionTraverser.cxx b/panda/src/collide/collisionTraverser.cxx index 74973d6764..6e8a01d68f 100644 --- a/panda/src/collide/collisionTraverser.cxx +++ b/panda/src/collide/collisionTraverser.cxx @@ -38,6 +38,8 @@ #include +using std::min; + PStatCollector CollisionTraverser::_collisions_pcollector("App:Collisions"); PStatCollector CollisionTraverser::_cnode_volume_pcollector("Collision Volumes:CollisionNode"); @@ -67,13 +69,13 @@ public: * */ CollisionTraverser:: -CollisionTraverser(const string &name) : +CollisionTraverser(const std::string &name) : Namable(name), _this_pcollector(_collisions_pcollector, name) { _respect_prev_transform = respect_prev_transform; #ifdef DO_COLLISION_RECORDING - _recorder = (CollisionRecorder *)NULL; + _recorder = nullptr; #endif } @@ -100,7 +102,7 @@ void CollisionTraverser:: add_collider(const NodePath &collider, CollisionHandler *handler) { nassertv(_ordered_colliders.size() == _colliders.size()); nassertv(!collider.is_empty() && collider.node()->is_collision_node()); - nassertv(handler != (CollisionHandler *)NULL); + nassertv(handler != nullptr); Colliders::iterator ci = _colliders.find(collider); if (ci != _colliders.end()) { @@ -231,7 +233,7 @@ get_handler(const NodePath &collider) const { if (ci != _colliders.end()) { return (*ci).second; } - return NULL; + return nullptr; } /** @@ -370,20 +372,20 @@ void CollisionTraverser:: set_recorder(CollisionRecorder *recorder) { if (recorder != _recorder) { // Remove the old recorder, if any. - if (_recorder != (CollisionRecorder *)NULL) { + if (_recorder != nullptr) { nassertv(_recorder->_trav == this); - _recorder->_trav = (CollisionTraverser *)NULL; + _recorder->_trav = nullptr; } _recorder = recorder; // Tell the new recorder about his new owner. - if (_recorder != (CollisionRecorder *)NULL) { + if (_recorder != nullptr) { nassertv(_recorder->_trav != this); - if (_recorder->_trav != (CollisionTraverser *)NULL) { + if (_recorder->_trav != nullptr) { _recorder->_trav->clear_recorder(); } - nassertv(_recorder->_trav == (CollisionTraverser *)NULL); + nassertv(_recorder->_trav == nullptr); _recorder->_trav = this; } } @@ -421,7 +423,7 @@ hide_collisions() { * */ void CollisionTraverser:: -output(ostream &out) const { +output(std::ostream &out) const { out << "CollisionTraverser, " << _colliders.size() << " colliders and " << _handlers.size() << " handlers.\n"; } @@ -430,7 +432,7 @@ output(ostream &out) const { * */ void CollisionTraverser:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "CollisionTraverser, " << _colliders.size() << " colliders and " << _handlers.size() << " handlers:\n"; @@ -447,7 +449,7 @@ write(ostream &out, int indent_level) const { nassertv(ci != _colliders.end()); CollisionHandler *handler = (*ci).second; - nassertv(handler != (CollisionHandler *)NULL); + nassertv(handler != nullptr); indent(out, indent_level + 2) << cnode_path; @@ -495,7 +497,7 @@ prepare_colliders_single(CollisionTraverser::LevelStatesSingle &level_states, for (i = 0; i < num_colliders; ++i) { indirect[i] = i; } - sort(indirect, indirect + num_colliders, SortByColliderSort(*this)); + std::sort(indirect, indirect + num_colliders, SortByColliderSort(*this)); int num_remaining_colliders = num_colliders; for (i = 0; i < num_colliders; ++i) { @@ -561,7 +563,7 @@ r_traverse_single(CollisionLevelStateSingle &level_state, size_t pass) { CollisionNode *cnode; DCAST_INTO_V(cnode, node); CPT(BoundingVolume) node_bv = cnode->get_bounds(); - const GeometricBoundingVolume *node_gbv = NULL; + const GeometricBoundingVolume *node_gbv = nullptr; if (node_bv->is_of_type(GeometricBoundingVolume::get_class_type())) { DCAST_INTO_V(node_gbv, node_bv); } @@ -606,7 +608,7 @@ r_traverse_single(CollisionLevelStateSingle &level_state, size_t pass) { GeomNode *gnode; DCAST_INTO_V(gnode, node); CPT(BoundingVolume) node_bv = gnode->get_bounds(); - const GeometricBoundingVolume *node_gbv = NULL; + const GeometricBoundingVolume *node_gbv = nullptr; if (node_bv->is_of_type(GeometricBoundingVolume::get_class_type())) { DCAST_INTO_V(node_gbv, node_bv); } @@ -706,7 +708,7 @@ prepare_colliders_double(CollisionTraverser::LevelStatesDouble &level_states, for (i = 0; i < num_colliders; ++i) { indirect[i] = i; } - sort(indirect, indirect + num_colliders, SortByColliderSort(*this)); + std::sort(indirect, indirect + num_colliders, SortByColliderSort(*this)); int num_remaining_colliders = num_colliders; for (i = 0; i < num_colliders; ++i) { @@ -772,7 +774,7 @@ r_traverse_double(CollisionLevelStateDouble &level_state, size_t pass) { CollisionNode *cnode; DCAST_INTO_V(cnode, node); CPT(BoundingVolume) node_bv = cnode->get_bounds(); - const GeometricBoundingVolume *node_gbv = NULL; + const GeometricBoundingVolume *node_gbv = nullptr; if (node_bv->is_of_type(GeometricBoundingVolume::get_class_type())) { DCAST_INTO_V(node_gbv, node_bv); } @@ -817,7 +819,7 @@ r_traverse_double(CollisionLevelStateDouble &level_state, size_t pass) { GeomNode *gnode; DCAST_INTO_V(gnode, node); CPT(BoundingVolume) node_bv = gnode->get_bounds(); - const GeometricBoundingVolume *node_gbv = NULL; + const GeometricBoundingVolume *node_gbv = nullptr; if (node_bv->is_of_type(GeometricBoundingVolume::get_class_type())) { DCAST_INTO_V(node_gbv, node_bv); } @@ -917,7 +919,7 @@ prepare_colliders_quad(CollisionTraverser::LevelStatesQuad &level_states, for (i = 0; i < num_colliders; ++i) { indirect[i] = i; } - sort(indirect, indirect + num_colliders, SortByColliderSort(*this)); + std::sort(indirect, indirect + num_colliders, SortByColliderSort(*this)); int num_remaining_colliders = num_colliders; for (i = 0; i < num_colliders; ++i) { @@ -983,7 +985,7 @@ r_traverse_quad(CollisionLevelStateQuad &level_state, size_t pass) { CollisionNode *cnode; DCAST_INTO_V(cnode, node); CPT(BoundingVolume) node_bv = cnode->get_bounds(); - const GeometricBoundingVolume *node_gbv = NULL; + const GeometricBoundingVolume *node_gbv = nullptr; if (node_bv->is_of_type(GeometricBoundingVolume::get_class_type())) { DCAST_INTO_V(node_gbv, node_bv); } @@ -1028,7 +1030,7 @@ r_traverse_quad(CollisionLevelStateQuad &level_state, size_t pass) { GeomNode *gnode; DCAST_INTO_V(gnode, node); CPT(BoundingVolume) node_bv = gnode->get_bounds(); - const GeometricBoundingVolume *node_gbv = NULL; + const GeometricBoundingVolume *node_gbv = nullptr; if (node_bv->is_of_type(GeometricBoundingVolume::get_class_type())) { DCAST_INTO_V(node_gbv, node_bv); } @@ -1110,8 +1112,8 @@ compare_collider_to_node(CollisionEntry &entry, const GeometricBoundingVolume *from_node_gbv, const GeometricBoundingVolume *into_node_gbv) { bool within_node_bounds = true; - if (from_parent_gbv != (GeometricBoundingVolume *)NULL && - into_node_gbv != (GeometricBoundingVolume *)NULL) { + if (from_parent_gbv != nullptr && + into_node_gbv != nullptr) { within_node_bounds = (into_node_gbv->contains(from_parent_gbv) != 0); _cnode_volume_pcollector.add_level(1); } @@ -1169,8 +1171,8 @@ compare_collider_to_geom_node(CollisionEntry &entry, const GeometricBoundingVolume *from_node_gbv, const GeometricBoundingVolume *into_node_gbv) { bool within_node_bounds = true; - if (from_parent_gbv != (GeometricBoundingVolume *)NULL && - into_node_gbv != (GeometricBoundingVolume *)NULL) { + if (from_parent_gbv != nullptr && + into_node_gbv != nullptr) { within_node_bounds = (into_node_gbv->contains(from_parent_gbv) != 0); _gnode_volume_pcollector.add_level(1); } @@ -1180,11 +1182,11 @@ compare_collider_to_geom_node(CollisionEntry &entry, DCAST_INTO_V(gnode, entry._into_node); int num_geoms = gnode->get_num_geoms(); for (int s = 0; s < num_geoms; ++s) { - entry._into = (CollisionSolid *)NULL; + entry._into = nullptr; const Geom *geom = DCAST(Geom, gnode->get_geom(s)); - if (geom != (Geom *)NULL) { + if (geom != nullptr) { CPT(BoundingVolume) geom_bv = geom->get_bounds(); - const GeometricBoundingVolume *geom_gbv = NULL; + const GeometricBoundingVolume *geom_gbv = nullptr; if (num_geoms > 1 && geom_bv->is_of_type(GeometricBoundingVolume::get_class_type())) { // Only bother to test against each geom's bounding volume if we @@ -1209,8 +1211,8 @@ compare_collider_to_solid(CollisionEntry &entry, const GeometricBoundingVolume *from_node_gbv, const GeometricBoundingVolume *solid_gbv) { bool within_solid_bounds = true; - if (from_node_gbv != (GeometricBoundingVolume *)NULL && - solid_gbv != (GeometricBoundingVolume *)NULL) { + if (from_node_gbv != nullptr && + solid_gbv != nullptr) { within_solid_bounds = (solid_gbv->contains(from_node_gbv) != 0); #ifdef DO_PSTATS ((CollisionSolid *)entry.get_into())->get_volume_pcollector().add_level(1); @@ -1240,8 +1242,8 @@ compare_collider_to_geom(CollisionEntry &entry, const Geom *geom, const GeometricBoundingVolume *from_node_gbv, const GeometricBoundingVolume *geom_gbv) { bool within_geom_bounds = true; - if (from_node_gbv != (GeometricBoundingVolume *)NULL && - geom_gbv != (GeometricBoundingVolume *)NULL) { + if (from_node_gbv != nullptr && + geom_gbv != nullptr) { within_geom_bounds = (geom_gbv->contains(from_node_gbv) != 0); _geom_volume_pcollector.add_level(1); } @@ -1278,7 +1280,7 @@ compare_collider_to_geom(CollisionEntry &entry, const Geom *geom, // in the Geom. if (CollisionPolygon::verify_points(v[0], v[1], v[2])) { bool within_solid_bounds = true; - if (from_node_gbv != (GeometricBoundingVolume *)NULL) { + if (from_node_gbv != nullptr) { PT(BoundingSphere) sphere = new BoundingSphere; sphere->around(v, v + 3); within_solid_bounds = (sphere->contains(from_node_gbv) != 0); @@ -1308,7 +1310,7 @@ compare_collider_to_geom(CollisionEntry &entry, const Geom *geom, // in the Geom. if (CollisionPolygon::verify_points(v[0], v[1], v[2])) { bool within_solid_bounds = true; - if (from_node_gbv != (GeometricBoundingVolume *)NULL) { + if (from_node_gbv != nullptr) { PT(BoundingSphere) sphere = new BoundingSphere; sphere->around(v, v + 3); within_solid_bounds = (sphere->contains(from_node_gbv) != 0); @@ -1389,7 +1391,7 @@ PStatCollector &CollisionTraverser:: get_pass_collector(int pass) { nassertr(pass >= 0, _this_pcollector); while ((int)_pass_collectors.size() <= pass) { - ostringstream name; + std::ostringstream name; name << "pass" << (_pass_collectors.size() + 1); PStatCollector col(_this_pcollector, name.str()); _pass_collectors.push_back(col); diff --git a/panda/src/collide/collisionTraverser.h b/panda/src/collide/collisionTraverser.h index 8aaa0fd475..8a6c912aaf 100644 --- a/panda/src/collide/collisionTraverser.h +++ b/panda/src/collide/collisionTraverser.h @@ -44,7 +44,7 @@ class CollisionEntry; */ class EXPCL_PANDA_COLLIDE CollisionTraverser : public Namable { PUBLISHED: - explicit CollisionTraverser(const string &name = "ctrav"); + explicit CollisionTraverser(const std::string &name = "ctrav"); ~CollisionTraverser(); INLINE void set_respect_prev_transform(bool flag); @@ -76,8 +76,8 @@ PUBLISHED: void hide_collisions(); #endif // DO_COLLISION_RECORDING - void output(ostream &out) const; - void write(ostream &out, int indent_level) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level) const; private: typedef pvector LevelStatesSingle; @@ -111,7 +111,6 @@ private: private: PT(CollisionHandler) _default_handler; - TypeHandle _graph_type; class OrderedColliderDef { public: @@ -164,7 +163,7 @@ private: friend class SortByColliderSort; }; -INLINE ostream &operator << (ostream &out, const CollisionTraverser &trav) { +INLINE std::ostream &operator << (std::ostream &out, const CollisionTraverser &trav) { trav.output(out); return out; } diff --git a/panda/src/collide/collisionTube.cxx b/panda/src/collide/collisionTube.cxx index 8e3b188aab..174935368e 100644 --- a/panda/src/collide/collisionTube.cxx +++ b/panda/src/collide/collisionTube.cxx @@ -104,7 +104,7 @@ get_test_pcollector() { * */ void CollisionTube:: -output(ostream &out) const { +output(std::ostream &out) const { out << "tube, a (" << _a << "), b (" << _b << "), r " << _radius; } @@ -146,7 +146,7 @@ compute_internal_bounds() const { PT(CollisionEntry) CollisionTube:: test_intersection_from_sphere(const CollisionEntry &entry) const { const CollisionSphere *sphere; - DCAST_INTO_R(sphere, entry.get_from(), NULL); + DCAST_INTO_R(sphere, entry.get_from(), nullptr); CPT(TransformState) wrt_space = entry.get_wrt_space(); CPT(TransformState) wrt_prev_space = entry.get_wrt_prev_space(); @@ -173,17 +173,17 @@ test_intersection_from_sphere(const CollisionEntry &entry) const { double t1, t2; if (!intersects_line(t1, t2, from_a, from_direction, from_radius)) { // No intersection. - return NULL; + return nullptr; } if (t2 < 0.0 || t1 > 1.0) { // Both intersection points are before the start of the segment or after // the end of the segment. - return NULL; + return nullptr; } // doubles, not floats, to satisfy min and max templates. - actual_t = min(1.0, max(0.0, t1)); + actual_t = std::min(1.0, std::max(0.0, t1)); contact_point = from_a + actual_t * (from_b - from_a); if (collide_cat.is_debug()) { @@ -224,7 +224,7 @@ test_intersection_from_sphere(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionTube:: test_intersection_from_line(const CollisionEntry &entry) const { const CollisionLine *line; - DCAST_INTO_R(line, entry.get_from(), NULL); + DCAST_INTO_R(line, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -234,7 +234,7 @@ test_intersection_from_line(const CollisionEntry &entry) const { double t1, t2; if (!intersects_line(t1, t2, from_origin, from_direction, 0.0f)) { // No intersection. - return NULL; + return nullptr; } if (collide_cat.is_debug()) { @@ -272,7 +272,7 @@ test_intersection_from_line(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionTube:: test_intersection_from_ray(const CollisionEntry &entry) const { const CollisionRay *ray; - DCAST_INTO_R(ray, entry.get_from(), NULL); + DCAST_INTO_R(ray, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -282,12 +282,12 @@ test_intersection_from_ray(const CollisionEntry &entry) const { double t1, t2; if (!intersects_line(t1, t2, from_origin, from_direction, 0.0f)) { // No intersection. - return NULL; + return nullptr; } if (t2 < 0.0) { // Both intersection points are before the start of the ray. - return NULL; + return nullptr; } if (collide_cat.is_debug()) { @@ -333,7 +333,7 @@ test_intersection_from_ray(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionTube:: test_intersection_from_segment(const CollisionEntry &entry) const { const CollisionSegment *segment; - DCAST_INTO_R(segment, entry.get_from(), NULL); + DCAST_INTO_R(segment, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -344,13 +344,13 @@ test_intersection_from_segment(const CollisionEntry &entry) const { double t1, t2; if (!intersects_line(t1, t2, from_a, from_direction, 0.0f)) { // No intersection. - return NULL; + return nullptr; } if (t2 < 0.0 || t1 > 1.0) { // Both intersection points are before the start of the segment or after // the end of the segment. - return NULL; + return nullptr; } if (collide_cat.is_debug()) { @@ -397,7 +397,7 @@ test_intersection_from_segment(const CollisionEntry &entry) const { PT(CollisionEntry) CollisionTube:: test_intersection_from_parabola(const CollisionEntry &entry) const { const CollisionParabola *parabola; - DCAST_INTO_R(parabola, entry.get_from(), NULL); + DCAST_INTO_R(parabola, entry.get_from(), nullptr); const LMatrix4 &wrt_mat = entry.get_wrt_mat(); @@ -410,7 +410,7 @@ test_intersection_from_parabola(const CollisionEntry &entry) const { local_p.calc_point(parabola->get_t1()), local_p.calc_point(parabola->get_t2()))) { // No intersection. - return NULL; + return nullptr; } if (collide_cat.is_debug()) { @@ -824,7 +824,7 @@ intersects_parabola(double &t, const LParabola ¶bola, return false; } - t = max(t1a, 0.0); + t = std::max(t1a, 0.0); return true; } diff --git a/panda/src/collide/collisionTube.h b/panda/src/collide/collisionTube.h index 52701193eb..1742e24927 100644 --- a/panda/src/collide/collisionTube.h +++ b/panda/src/collide/collisionTube.h @@ -48,7 +48,7 @@ public: virtual PStatCollector &get_volume_pcollector(); virtual PStatCollector &get_test_pcollector(); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; INLINE static void flush_level(); diff --git a/panda/src/collide/collisionVisualizer.cxx b/panda/src/collide/collisionVisualizer.cxx index 204a39b6bd..0cebbeffdf 100644 --- a/panda/src/collide/collisionVisualizer.cxx +++ b/panda/src/collide/collisionVisualizer.cxx @@ -41,7 +41,7 @@ TypeHandle CollisionVisualizer::_type_handle; * */ CollisionVisualizer:: -CollisionVisualizer(const string &name) : PandaNode(name), _lock("CollisionVisualizer") { +CollisionVisualizer(const std::string &name) : PandaNode(name), _lock("CollisionVisualizer") { set_cull_callback(); // We always want to render the CollisionVisualizer node itself (even if it @@ -144,7 +144,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { const SolidInfo &solid_info = (*si).second; bool was_detected = (solid_info._detected_count > 0); PT(PandaNode) node = solid->get_viz(trav, xform_data, !was_detected); - if (node != (PandaNode *)NULL) { + if (node != nullptr) { CullTraverserData next_data(xform_data, node); // We don't want to inherit the render state from above for these @@ -263,7 +263,7 @@ is_renderable() const { * classes to include some information relevant to the class. */ void CollisionVisualizer:: -output(ostream &out) const { +output(std::ostream &out) const { PandaNode::output(out); out << " "; CollisionRecorder::output(out); @@ -296,9 +296,9 @@ collision_tested(const CollisionEntry &entry, bool detected) { nassertv(!solid.is_null()); LightMutexHolder holder(_lock); - VizInfo &viz_info = _data[move(net_transform)]; + VizInfo &viz_info = _data[std::move(net_transform)]; if (detected) { - viz_info._solids[move(solid)]._detected_count++; + viz_info._solids[std::move(solid)]._detected_count++; if (entry.has_surface_point()) { CollisionPoint p; @@ -308,7 +308,7 @@ collision_tested(const CollisionEntry &entry, bool detected) { } } else { - viz_info._solids[move(solid)]._missed_count++; + viz_info._solids[std::move(solid)]._missed_count++; } } @@ -321,8 +321,8 @@ CPT(RenderState) CollisionVisualizer:: get_viz_state() { // Once someone asks for this pointer, we hold its reference count and never // free it. - static CPT(RenderState) state = (const RenderState *)NULL; - if (state == (const RenderState *)NULL) { + static CPT(RenderState) state = nullptr; + if (state == nullptr) { state = RenderState::make (DepthOffsetAttrib::make()); } diff --git a/panda/src/collide/collisionVisualizer.h b/panda/src/collide/collisionVisualizer.h index 88491c4e26..2fb2cb40b2 100644 --- a/panda/src/collide/collisionVisualizer.h +++ b/panda/src/collide/collisionVisualizer.h @@ -34,7 +34,7 @@ */ class EXPCL_PANDA_COLLIDE CollisionVisualizer : public PandaNode, public CollisionRecorder { PUBLISHED: - explicit CollisionVisualizer(const string &name); + explicit CollisionVisualizer(const std::string &name); CollisionVisualizer(const CollisionVisualizer ©); virtual ~CollisionVisualizer(); @@ -55,7 +55,7 @@ public: virtual PandaNode *make_copy() const; virtual bool cull_callback(CullTraverser *trav, CullTraverserData &data); virtual bool is_renderable() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; // from parent class CollisionRecorder. virtual void begin_traversal(); diff --git a/panda/src/cull/cullBinBackToFront.I b/panda/src/cull/cullBinBackToFront.I index 4e77012ac5..fd66f8437b 100644 --- a/panda/src/cull/cullBinBackToFront.I +++ b/panda/src/cull/cullBinBackToFront.I @@ -15,7 +15,7 @@ * */ INLINE CullBinBackToFront:: -CullBinBackToFront(const string &name, GraphicsStateGuardianBase *gsg, +CullBinBackToFront(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector) : CullBin(name, BT_back_to_front, gsg, draw_region_pcollector) { diff --git a/panda/src/cull/cullBinBackToFront.cxx b/panda/src/cull/cullBinBackToFront.cxx index a1a7264af0..00c6ba7c32 100644 --- a/panda/src/cull/cullBinBackToFront.cxx +++ b/panda/src/cull/cullBinBackToFront.cxx @@ -39,7 +39,7 @@ CullBinBackToFront:: * Factory constructor for passing to the CullBinManager. */ CullBin *CullBinBackToFront:: -make_bin(const string &name, GraphicsStateGuardianBase *gsg, +make_bin(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector) { return new CullBinBackToFront(name, gsg, draw_region_pcollector); } @@ -57,10 +57,10 @@ add_object(CullableObject *object, Thread *current_thread) { } const GeometricBoundingVolume *gbv = volume->as_geometric_bounding_volume(); - nassertv(gbv != NULL); + nassertv(gbv != nullptr); LPoint3 center = gbv->get_approx_center(); - nassertv(object->_internal_transform != (const TransformState *)NULL); + nassertv(object->_internal_transform != nullptr); center = center * object->_internal_transform->get_mat(); PN_stdfloat distance = _gsg->compute_distance_to(center); diff --git a/panda/src/cull/cullBinBackToFront.h b/panda/src/cull/cullBinBackToFront.h index 515fafc1a5..cfef2f4267 100644 --- a/panda/src/cull/cullBinBackToFront.h +++ b/panda/src/cull/cullBinBackToFront.h @@ -30,12 +30,12 @@ */ class EXPCL_PANDA_CULL CullBinBackToFront : public CullBin { public: - INLINE CullBinBackToFront(const string &name, + INLINE CullBinBackToFront(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector); virtual ~CullBinBackToFront(); - static CullBin *make_bin(const string &name, + static CullBin *make_bin(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector); diff --git a/panda/src/cull/cullBinFixed.I b/panda/src/cull/cullBinFixed.I index 117512283d..4d35e242a3 100644 --- a/panda/src/cull/cullBinFixed.I +++ b/panda/src/cull/cullBinFixed.I @@ -15,7 +15,7 @@ * */ INLINE CullBinFixed:: -CullBinFixed(const string &name, GraphicsStateGuardianBase *gsg, +CullBinFixed(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector) : CullBin(name, BT_fixed, gsg, draw_region_pcollector) { diff --git a/panda/src/cull/cullBinFixed.cxx b/panda/src/cull/cullBinFixed.cxx index 212bc4f320..557b3435a3 100644 --- a/panda/src/cull/cullBinFixed.cxx +++ b/panda/src/cull/cullBinFixed.cxx @@ -39,7 +39,7 @@ CullBinFixed:: * Factory constructor for passing to the CullBinManager. */ CullBin *CullBinFixed:: -make_bin(const string &name, GraphicsStateGuardianBase *gsg, +make_bin(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector) { return new CullBinFixed(name, gsg, draw_region_pcollector); } @@ -61,7 +61,7 @@ add_object(CullableObject *object, Thread *current_thread) { void CullBinFixed:: finish_cull(SceneSetup *, Thread *current_thread) { PStatTimer timer(_cull_this_pcollector, current_thread); - stable_sort(_objects.begin(), _objects.end()); + std::stable_sort(_objects.begin(), _objects.end()); } /** diff --git a/panda/src/cull/cullBinFixed.h b/panda/src/cull/cullBinFixed.h index f2d1c8fd07..337283e2b3 100644 --- a/panda/src/cull/cullBinFixed.h +++ b/panda/src/cull/cullBinFixed.h @@ -32,12 +32,12 @@ */ class EXPCL_PANDA_CULL CullBinFixed : public CullBin { public: - INLINE CullBinFixed(const string &name, + INLINE CullBinFixed(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector); virtual ~CullBinFixed(); - static CullBin *make_bin(const string &name, + static CullBin *make_bin(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector); diff --git a/panda/src/cull/cullBinFrontToBack.I b/panda/src/cull/cullBinFrontToBack.I index 4605e5e6ef..83c0ab4651 100644 --- a/panda/src/cull/cullBinFrontToBack.I +++ b/panda/src/cull/cullBinFrontToBack.I @@ -15,7 +15,7 @@ * */ INLINE CullBinFrontToBack:: -CullBinFrontToBack(const string &name, GraphicsStateGuardianBase *gsg, +CullBinFrontToBack(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector) : CullBin(name, BT_front_to_back, gsg, draw_region_pcollector) { diff --git a/panda/src/cull/cullBinFrontToBack.cxx b/panda/src/cull/cullBinFrontToBack.cxx index 0fb05a68b5..4337b42d7c 100644 --- a/panda/src/cull/cullBinFrontToBack.cxx +++ b/panda/src/cull/cullBinFrontToBack.cxx @@ -39,7 +39,7 @@ CullBinFrontToBack:: * Factory constructor for passing to the CullBinManager. */ CullBin *CullBinFrontToBack:: -make_bin(const string &name, GraphicsStateGuardianBase *gsg, +make_bin(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector) { return new CullBinFrontToBack(name, gsg, draw_region_pcollector); } @@ -57,10 +57,10 @@ add_object(CullableObject *object, Thread *current_thread) { } const GeometricBoundingVolume *gbv = volume->as_geometric_bounding_volume(); - nassertv(gbv != NULL); + nassertv(gbv != nullptr); LPoint3 center = gbv->get_approx_center(); - nassertv(object->_internal_transform != (const TransformState *)NULL); + nassertv(object->_internal_transform != nullptr); center = center * object->_internal_transform->get_mat(); PN_stdfloat distance = _gsg->compute_distance_to(center); diff --git a/panda/src/cull/cullBinFrontToBack.h b/panda/src/cull/cullBinFrontToBack.h index 6ee0d4424a..b9ba66c043 100644 --- a/panda/src/cull/cullBinFrontToBack.h +++ b/panda/src/cull/cullBinFrontToBack.h @@ -31,12 +31,12 @@ */ class EXPCL_PANDA_CULL CullBinFrontToBack : public CullBin { public: - INLINE CullBinFrontToBack(const string &name, + INLINE CullBinFrontToBack(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector); virtual ~CullBinFrontToBack(); - static CullBin *make_bin(const string &name, + static CullBin *make_bin(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector); diff --git a/panda/src/cull/cullBinStateSorted.I b/panda/src/cull/cullBinStateSorted.I index e035c433bb..1a1637bdf4 100644 --- a/panda/src/cull/cullBinStateSorted.I +++ b/panda/src/cull/cullBinStateSorted.I @@ -15,7 +15,7 @@ * */ INLINE CullBinStateSorted:: -CullBinStateSorted(const string &name, GraphicsStateGuardianBase *gsg, +CullBinStateSorted(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector) : CullBin(name, BT_state_sorted, gsg, draw_region_pcollector), _objects(get_class_type()) @@ -29,8 +29,8 @@ INLINE CullBinStateSorted::ObjectData:: ObjectData(CullableObject *object) : _object(object) { - if (object->_munged_data == NULL) { - _format = NULL; + if (object->_munged_data == nullptr) { + _format = nullptr; } else { _format = object->_munged_data->get_format(); } diff --git a/panda/src/cull/cullBinStateSorted.cxx b/panda/src/cull/cullBinStateSorted.cxx index 04890af48c..ad4d26cd12 100644 --- a/panda/src/cull/cullBinStateSorted.cxx +++ b/panda/src/cull/cullBinStateSorted.cxx @@ -38,7 +38,7 @@ CullBinStateSorted:: * Factory constructor for passing to the CullBinManager. */ CullBin *CullBinStateSorted:: -make_bin(const string &name, GraphicsStateGuardianBase *gsg, +make_bin(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector) { return new CullBinStateSorted(name, gsg, draw_region_pcollector); } diff --git a/panda/src/cull/cullBinStateSorted.h b/panda/src/cull/cullBinStateSorted.h index 6f20882135..f97e41fa48 100644 --- a/panda/src/cull/cullBinStateSorted.h +++ b/panda/src/cull/cullBinStateSorted.h @@ -34,12 +34,12 @@ */ class EXPCL_PANDA_CULL CullBinStateSorted : public CullBin { public: - INLINE CullBinStateSorted(const string &name, + INLINE CullBinStateSorted(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector); virtual ~CullBinStateSorted(); - static CullBin *make_bin(const string &name, + static CullBin *make_bin(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector); diff --git a/panda/src/cull/cullBinUnsorted.I b/panda/src/cull/cullBinUnsorted.I index f9a8d37dc0..2e000b72f0 100644 --- a/panda/src/cull/cullBinUnsorted.I +++ b/panda/src/cull/cullBinUnsorted.I @@ -15,7 +15,7 @@ * */ INLINE CullBinUnsorted:: -CullBinUnsorted(const string &name, GraphicsStateGuardianBase *gsg, +CullBinUnsorted(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector) : CullBin(name, BT_unsorted, gsg, draw_region_pcollector) { diff --git a/panda/src/cull/cullBinUnsorted.cxx b/panda/src/cull/cullBinUnsorted.cxx index 4ef8c35ae6..14766f9bbd 100644 --- a/panda/src/cull/cullBinUnsorted.cxx +++ b/panda/src/cull/cullBinUnsorted.cxx @@ -35,7 +35,7 @@ CullBinUnsorted:: * Factory constructor for passing to the CullBinManager. */ CullBin *CullBinUnsorted:: -make_bin(const string &name, GraphicsStateGuardianBase *gsg, +make_bin(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector) { return new CullBinUnsorted(name, gsg, draw_region_pcollector); } diff --git a/panda/src/cull/cullBinUnsorted.h b/panda/src/cull/cullBinUnsorted.h index 0c682155d8..2dcf60a85f 100644 --- a/panda/src/cull/cullBinUnsorted.h +++ b/panda/src/cull/cullBinUnsorted.h @@ -26,12 +26,12 @@ */ class EXPCL_PANDA_CULL CullBinUnsorted : public CullBin { public: - INLINE CullBinUnsorted(const string &name, + INLINE CullBinUnsorted(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector); ~CullBinUnsorted(); - static CullBin *make_bin(const string &name, + static CullBin *make_bin(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector); diff --git a/panda/src/device/analogNode.I b/panda/src/device/analogNode.I index ec41944491..f02b638603 100644 --- a/panda/src/device/analogNode.I +++ b/panda/src/device/analogNode.I @@ -26,7 +26,7 @@ OutputData() { */ INLINE bool AnalogNode:: is_valid() const { - return (_analog != (ClientAnalogDevice *)NULL) && _analog->is_connected(); + return (_analog != nullptr) && _analog->is_connected(); } /** diff --git a/panda/src/device/analogNode.cxx b/panda/src/device/analogNode.cxx index d577496554..59e57f4179 100644 --- a/panda/src/device/analogNode.cxx +++ b/panda/src/device/analogNode.cxx @@ -23,17 +23,17 @@ TypeHandle AnalogNode::_type_handle; * */ AnalogNode:: -AnalogNode(ClientBase *client, const string &device_name) : +AnalogNode(ClientBase *client, const std::string &device_name) : DataNode(device_name) { _xy_output = define_output("xy", EventStoreVec2::get_class_type()); _xy = new EventStoreVec2(LPoint2(0.0f, 0.0f)); - nassertv(client != (ClientBase *)NULL); + nassertv(client != nullptr); PT(ClientDevice) device = client->get_device(ClientAnalogDevice::get_class_type(), device_name); - if (device == (ClientDevice *)NULL) { + if (device == nullptr) { device_cat.warning() << "Unable to open analog device " << device_name << "\n"; return; @@ -63,10 +63,10 @@ AnalogNode:: * */ void AnalogNode:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { DataNode::write(out, indent_level); - if (_analog != (ClientAnalogDevice *)NULL) { + if (_analog != nullptr) { _analog->acquire(); _analog->write_controls(out, indent_level + 2); _analog->unlock(); diff --git a/panda/src/device/analogNode.h b/panda/src/device/analogNode.h index d62eaa0d3b..11626e0ae8 100644 --- a/panda/src/device/analogNode.h +++ b/panda/src/device/analogNode.h @@ -38,7 +38,7 @@ */ class EXPCL_PANDA_DEVICE AnalogNode : public DataNode { PUBLISHED: - explicit AnalogNode(ClientBase *client, const string &device_name); + explicit AnalogNode(ClientBase *client, const std::string &device_name); virtual ~AnalogNode(); INLINE bool is_valid() const; @@ -54,7 +54,7 @@ PUBLISHED: INLINE bool is_output_flipped(int channel) const; public: - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; private: class OutputData { diff --git a/panda/src/device/buttonNode.I b/panda/src/device/buttonNode.I index 1fa5efd21b..c4ccc2c610 100644 --- a/panda/src/device/buttonNode.I +++ b/panda/src/device/buttonNode.I @@ -17,7 +17,7 @@ */ INLINE bool ButtonNode:: is_valid() const { - return (_button != (ClientButtonDevice *)NULL) && _button->is_connected(); + return (_button != nullptr) && _button->is_connected(); } /** diff --git a/panda/src/device/buttonNode.cxx b/panda/src/device/buttonNode.cxx index e3125a2db3..67803cf658 100644 --- a/panda/src/device/buttonNode.cxx +++ b/panda/src/device/buttonNode.cxx @@ -23,17 +23,17 @@ TypeHandle ButtonNode::_type_handle; * */ ButtonNode:: -ButtonNode(ClientBase *client, const string &device_name) : +ButtonNode(ClientBase *client, const std::string &device_name) : DataNode(device_name) { _button_events_output = define_output("button_events", ButtonEventList::get_class_type()); _button_events = new ButtonEventList; - nassertv(client != (ClientBase *)NULL); + nassertv(client != nullptr); PT(ClientDevice) device = client->get_device(ClientButtonDevice::get_class_type(), device_name); - if (device == (ClientDevice *)NULL) { + if (device == nullptr) { device_cat.warning() << "Unable to open button device " << device_name << "\n"; return; @@ -63,10 +63,10 @@ ButtonNode:: * */ void ButtonNode:: -output(ostream &out) const { +output(std::ostream &out) const { DataNode::output(out); - if (_button != (ClientButtonDevice *)NULL) { + if (_button != nullptr) { out << " ("; _button->acquire(); _button->output_buttons(out); @@ -79,10 +79,10 @@ output(ostream &out) const { * */ void ButtonNode:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { DataNode::write(out, indent_level); - if (_button != (ClientButtonDevice *)NULL) { + if (_button != nullptr) { _button->acquire(); _button->write_buttons(out, indent_level + 2); _button->unlock(); diff --git a/panda/src/device/buttonNode.h b/panda/src/device/buttonNode.h index 6fce65a9e0..02b141fbbf 100644 --- a/panda/src/device/buttonNode.h +++ b/panda/src/device/buttonNode.h @@ -34,7 +34,7 @@ */ class EXPCL_PANDA_DEVICE ButtonNode : public DataNode { PUBLISHED: - explicit ButtonNode(ClientBase *client, const string &device_name); + explicit ButtonNode(ClientBase *client, const std::string &device_name); virtual ~ButtonNode(); INLINE bool is_valid() const; @@ -48,8 +48,8 @@ PUBLISHED: INLINE bool is_button_known(int index) const; public: - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; private: PT(ClientButtonDevice) _button; diff --git a/panda/src/device/clientAnalogDevice.I b/panda/src/device/clientAnalogDevice.I index aad2deafd4..d392d46aba 100644 --- a/panda/src/device/clientAnalogDevice.I +++ b/panda/src/device/clientAnalogDevice.I @@ -25,7 +25,7 @@ AnalogState() : * */ INLINE ClientAnalogDevice:: -ClientAnalogDevice(ClientBase *client, const string &device_name): +ClientAnalogDevice(ClientBase *client, const std::string &device_name): ClientDevice(client, get_class_type(), device_name) { } diff --git a/panda/src/device/clientAnalogDevice.cxx b/panda/src/device/clientAnalogDevice.cxx index 47ddde620b..eb9c72ee06 100644 --- a/panda/src/device/clientAnalogDevice.cxx +++ b/panda/src/device/clientAnalogDevice.cxx @@ -37,7 +37,7 @@ ensure_control_index(int index) { * */ void ClientAnalogDevice:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type() << " " << get_device_name() << ":\n"; write_controls(out, indent_level + 2); } @@ -46,7 +46,7 @@ write(ostream &out, int indent_level) const { * Writes a multi-line description of the current analog control states. */ void ClientAnalogDevice:: -write_controls(ostream &out, int indent_level) const { +write_controls(std::ostream &out, int indent_level) const { bool any_controls = false; Controls::const_iterator ai; for (ai = _controls.begin(); ai != _controls.end(); ++ai) { diff --git a/panda/src/device/clientAnalogDevice.h b/panda/src/device/clientAnalogDevice.h index 95040f49a4..436b399240 100644 --- a/panda/src/device/clientAnalogDevice.h +++ b/panda/src/device/clientAnalogDevice.h @@ -28,7 +28,7 @@ */ class EXPCL_PANDA_DEVICE ClientAnalogDevice : public ClientDevice { protected: - INLINE ClientAnalogDevice(ClientBase *client, const string &device_name); + INLINE ClientAnalogDevice(ClientBase *client, const std::string &device_name); public: INLINE int get_num_controls() const; @@ -37,8 +37,8 @@ public: INLINE double get_control_state(int index) const; INLINE bool is_control_known(int index) const; - virtual void write(ostream &out, int indent_level = 0) const; - void write_controls(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level = 0) const; + void write_controls(std::ostream &out, int indent_level) const; private: void ensure_control_index(int index); diff --git a/panda/src/device/clientBase.cxx b/panda/src/device/clientBase.cxx index 8a061ce5f5..b7c6c3347c 100644 --- a/panda/src/device/clientBase.cxx +++ b/panda/src/device/clientBase.cxx @@ -27,7 +27,7 @@ ClientBase() { _cs = CS_default; #ifdef OLD_HAVE_IPC - _client_thread = (thread *)NULL; + _client_thread = nullptr; _shutdown = false; #endif } @@ -85,7 +85,7 @@ fork_asynchronous_thread(double poll_time) { if (device_cat.is_debug()) { device_cat.debug() << "fork_asynchronous_thread() - forking client thread" - << endl; + << std::endl; } return true; } @@ -113,7 +113,7 @@ fork_asynchronous_thread(double poll_time) { * NULL is returned. */ PT(ClientDevice) ClientBase:: -get_device(TypeHandle device_type, const string &device_name) { +get_device(TypeHandle device_type, const std::string &device_name) { DevicesByName &dbn = _devices[device_type]; DevicesByName::iterator dbni; @@ -126,7 +126,7 @@ get_device(TypeHandle device_type, const string &device_name) { // We need to create a new device for this name. PT(ClientDevice) device = make_device(device_type, device_name); - if (device != (ClientDevice *)NULL) { + if (device != nullptr) { dbn.insert(DevicesByName::value_type(device_name, device)); device->_is_connected = true; } @@ -143,7 +143,7 @@ get_device(TypeHandle device_type, const string &device_name) { * unknown (e.g. it was disconnected previously). */ bool ClientBase:: -disconnect_device(TypeHandle device_type, const string &device_name, +disconnect_device(TypeHandle device_type, const std::string &device_name, ClientDevice *device) { DevicesByName &dbn = _devices[device_type]; @@ -185,9 +185,9 @@ do_poll() { */ void *ClientBase:: st_callback(void *arg) { - nassertr(arg != NULL, NULL); + nassertr(arg != nullptr, nullptr); ((ClientBase *)arg)->callback(); - return NULL; + return nullptr; } /** diff --git a/panda/src/device/clientBase.h b/panda/src/device/clientBase.h index d7ee1cf605..f32b526172 100644 --- a/panda/src/device/clientBase.h +++ b/panda/src/device/clientBase.h @@ -57,20 +57,20 @@ PUBLISHED: public: PT(ClientDevice) get_device(TypeHandle device_type, - const string &device_name); + const std::string &device_name); protected: virtual PT(ClientDevice) make_device(TypeHandle device_type, - const string &device_name)=0; + const std::string &device_name)=0; virtual bool disconnect_device(TypeHandle device_type, - const string &device_name, + const std::string &device_name, ClientDevice *device); virtual void do_poll(); private: - typedef pmap DevicesByName; + typedef pmap DevicesByName; typedef pmap Devices; Devices _devices; diff --git a/panda/src/device/clientButtonDevice.cxx b/panda/src/device/clientButtonDevice.cxx index 60952f6a2c..27451c2887 100644 --- a/panda/src/device/clientButtonDevice.cxx +++ b/panda/src/device/clientButtonDevice.cxx @@ -15,13 +15,15 @@ #include "indent.h" +using std::ostream; + TypeHandle ClientButtonDevice::_type_handle; /** * */ ClientButtonDevice:: -ClientButtonDevice(ClientBase *client, const string &device_name): +ClientButtonDevice(ClientBase *client, const std::string &device_name): ClientDevice(client, get_class_type(), device_name) { _button_events = new ButtonEventList(); diff --git a/panda/src/device/clientButtonDevice.h b/panda/src/device/clientButtonDevice.h index 3c7a285e36..3b089b707b 100644 --- a/panda/src/device/clientButtonDevice.h +++ b/panda/src/device/clientButtonDevice.h @@ -31,7 +31,7 @@ */ class EXPCL_PANDA_DEVICE ClientButtonDevice : public ClientDevice { protected: - ClientButtonDevice(ClientBase *client, const string &device_name); + ClientButtonDevice(ClientBase *client, const std::string &device_name); public: INLINE int get_num_buttons() const; @@ -45,11 +45,11 @@ public: INLINE ButtonEventList *get_button_events() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; - void output_buttons(ostream &out) const; - void write_buttons(ostream &out, int indent_level) const; + void output_buttons(std::ostream &out) const; + void write_buttons(std::ostream &out, int indent_level) const; private: void ensure_button_index(int index); diff --git a/panda/src/device/clientDevice.I b/panda/src/device/clientDevice.I index c4e1e5a7b7..84edaf594f 100644 --- a/panda/src/device/clientDevice.I +++ b/panda/src/device/clientDevice.I @@ -44,7 +44,7 @@ get_device_type() const { * Returns the device name reported to the ClientBase. This has some * implementation-defined meaning to identify particular devices. */ -INLINE const string &ClientDevice:: +INLINE const std::string &ClientDevice:: get_device_name() const { return _device_name; } diff --git a/panda/src/device/clientDevice.cxx b/panda/src/device/clientDevice.cxx index f6bca213e5..6da404eca4 100644 --- a/panda/src/device/clientDevice.cxx +++ b/panda/src/device/clientDevice.cxx @@ -23,7 +23,7 @@ TypeHandle ClientDevice::_type_handle; */ ClientDevice:: ClientDevice(ClientBase *client, TypeHandle device_type, - const string &device_name) : + const std::string &device_name) : _client(client), _device_type(device_type), _device_name(device_name) @@ -87,7 +87,7 @@ poll() { * */ void ClientDevice:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << " " << get_device_name(); } @@ -95,6 +95,6 @@ output(ostream &out) const { * */ void ClientDevice:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << *this << "\n"; } diff --git a/panda/src/device/clientDevice.h b/panda/src/device/clientDevice.h index d8424e9a1f..0e2ad03778 100644 --- a/panda/src/device/clientDevice.h +++ b/panda/src/device/clientDevice.h @@ -32,14 +32,14 @@ class ClientBase; class EXPCL_PANDA_DEVICE ClientDevice : public TypedReferenceCount { protected: ClientDevice(ClientBase *client, TypeHandle device_type, - const string &device_name); + const std::string &device_name); public: virtual ~ClientDevice(); INLINE ClientBase *get_client() const; INLINE TypeHandle get_device_type() const; - INLINE const string &get_device_name() const; + INLINE const std::string &get_device_name() const; INLINE bool is_connected() const; void disconnect(); @@ -48,13 +48,13 @@ public: INLINE void acquire(); INLINE void unlock(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; private: ClientBase *_client; TypeHandle _device_type; - string _device_name; + std::string _device_name; bool _is_connected; #ifdef OLD_HAVE_IPC @@ -81,7 +81,7 @@ private: friend class ClientBase; }; -INLINE ostream &operator <<(ostream &out, const ClientDevice &device) { +INLINE std::ostream &operator <<(std::ostream &out, const ClientDevice &device) { device.output(out); return out; } diff --git a/panda/src/device/clientDialDevice.I b/panda/src/device/clientDialDevice.I index bf7fc3bca7..b0360ec63b 100644 --- a/panda/src/device/clientDialDevice.I +++ b/panda/src/device/clientDialDevice.I @@ -25,7 +25,7 @@ DialState() : * */ INLINE ClientDialDevice:: -ClientDialDevice(ClientBase *client, const string &device_name): +ClientDialDevice(ClientBase *client, const std::string &device_name): ClientDevice(client, get_class_type(), device_name) { } diff --git a/panda/src/device/clientDialDevice.h b/panda/src/device/clientDialDevice.h index 0da5604583..ec1c929abf 100644 --- a/panda/src/device/clientDialDevice.h +++ b/panda/src/device/clientDialDevice.h @@ -29,7 +29,7 @@ */ class EXPCL_PANDA_DEVICE ClientDialDevice : public ClientDevice { protected: - INLINE ClientDialDevice(ClientBase *client, const string &device_name); + INLINE ClientDialDevice(ClientBase *client, const std::string &device_name); public: INLINE int get_num_dials() const; diff --git a/panda/src/device/clientTrackerDevice.I b/panda/src/device/clientTrackerDevice.I index 030c4eea47..f4be74fc4d 100644 --- a/panda/src/device/clientTrackerDevice.I +++ b/panda/src/device/clientTrackerDevice.I @@ -15,7 +15,7 @@ * */ INLINE ClientTrackerDevice:: -ClientTrackerDevice(ClientBase *client, const string &device_name): +ClientTrackerDevice(ClientBase *client, const std::string &device_name): ClientDevice(client, get_class_type(), device_name) { } diff --git a/panda/src/device/clientTrackerDevice.h b/panda/src/device/clientTrackerDevice.h index 468ed342f5..bd134a5e4c 100644 --- a/panda/src/device/clientTrackerDevice.h +++ b/panda/src/device/clientTrackerDevice.h @@ -25,7 +25,7 @@ */ class EXPCL_PANDA_DEVICE ClientTrackerDevice : public ClientDevice { protected: - INLINE ClientTrackerDevice(ClientBase *client, const string &device_name); + INLINE ClientTrackerDevice(ClientBase *client, const std::string &device_name); public: INLINE const TrackerData &get_data() const; diff --git a/panda/src/device/dialNode.I b/panda/src/device/dialNode.I index c342eba997..1f6abdbc64 100644 --- a/panda/src/device/dialNode.I +++ b/panda/src/device/dialNode.I @@ -17,7 +17,7 @@ */ INLINE bool DialNode:: is_valid() const { - return (_dial != (ClientDialDevice *)NULL) && _dial->is_connected(); + return (_dial != nullptr) && _dial->is_connected(); } /** diff --git a/panda/src/device/dialNode.cxx b/panda/src/device/dialNode.cxx index b86305ac00..04f46a7805 100644 --- a/panda/src/device/dialNode.cxx +++ b/panda/src/device/dialNode.cxx @@ -22,14 +22,14 @@ TypeHandle DialNode::_type_handle; * */ DialNode:: -DialNode(ClientBase *client, const string &device_name) : +DialNode(ClientBase *client, const std::string &device_name) : DataNode(device_name) { - nassertv(client != (ClientBase *)NULL); + nassertv(client != nullptr); PT(ClientDevice) device = client->get_device(ClientDialDevice::get_class_type(), device_name); - if (device == (ClientDevice *)NULL) { + if (device == nullptr) { device_cat.warning() << "Unable to open dial device " << device_name << "\n"; return; diff --git a/panda/src/device/dialNode.h b/panda/src/device/dialNode.h index 13e2083efc..6fb65e7763 100644 --- a/panda/src/device/dialNode.h +++ b/panda/src/device/dialNode.h @@ -33,7 +33,7 @@ */ class EXPCL_PANDA_DEVICE DialNode : public DataNode { PUBLISHED: - explicit DialNode(ClientBase *client, const string &device_name); + explicit DialNode(ClientBase *client, const std::string &device_name); virtual ~DialNode(); INLINE bool is_valid() const; diff --git a/panda/src/device/mouseAndKeyboard.cxx b/panda/src/device/mouseAndKeyboard.cxx index 4a431c5e5e..4a8e599afe 100644 --- a/panda/src/device/mouseAndKeyboard.cxx +++ b/panda/src/device/mouseAndKeyboard.cxx @@ -24,7 +24,7 @@ TypeHandle MouseAndKeyboard::_type_handle; * */ MouseAndKeyboard:: -MouseAndKeyboard(GraphicsWindow *window, int device, const string &name) : +MouseAndKeyboard(GraphicsWindow *window, int device, const std::string &name) : DataNode(name), _window(window), _device(device) diff --git a/panda/src/device/mouseAndKeyboard.h b/panda/src/device/mouseAndKeyboard.h index 24a6efe07a..15f7544fb8 100644 --- a/panda/src/device/mouseAndKeyboard.h +++ b/panda/src/device/mouseAndKeyboard.h @@ -40,7 +40,7 @@ */ class EXPCL_PANDA_DEVICE MouseAndKeyboard : public DataNode { PUBLISHED: - explicit MouseAndKeyboard(GraphicsWindow *window, int device, const string &name); + explicit MouseAndKeyboard(GraphicsWindow *window, int device, const std::string &name); void set_source(GraphicsWindow *window, int device); PT(GraphicsWindow) get_source_window() const; diff --git a/panda/src/device/trackerNode.I b/panda/src/device/trackerNode.I index 75d91d1d82..99929d4af2 100644 --- a/panda/src/device/trackerNode.I +++ b/panda/src/device/trackerNode.I @@ -17,7 +17,7 @@ */ INLINE bool TrackerNode:: is_valid() const { - return (_tracker != (ClientTrackerDevice *)NULL) && _tracker->is_connected(); + return (_tracker != nullptr) && _tracker->is_connected(); } diff --git a/panda/src/device/trackerNode.cxx b/panda/src/device/trackerNode.cxx index e4c9356b13..0ec33af92f 100644 --- a/panda/src/device/trackerNode.cxx +++ b/panda/src/device/trackerNode.cxx @@ -21,21 +21,21 @@ TypeHandle TrackerNode::_type_handle; * */ TrackerNode:: -TrackerNode(ClientBase *client, const string &device_name) : +TrackerNode(ClientBase *client, const std::string &device_name) : DataNode(device_name) { _transform_output = define_output("transform", TransformState::get_class_type()); _transform = TransformState::make_identity(); - nassertv(client != (ClientBase *)NULL); + nassertv(client != nullptr); set_tracker_coordinate_system(client->get_coordinate_system()); set_graph_coordinate_system(CS_default); PT(ClientDevice) device = client->get_device(ClientTrackerDevice::get_class_type(), device_name); - if (device == (ClientDevice *)NULL) { + if (device == nullptr) { device_cat.warning() << "Unable to open tracker device " << device_name << "\n"; return; @@ -63,9 +63,9 @@ TrackerNode(ClientTrackerDevice *device) : _transform = TransformState::make_identity(); - nassertv(device != (ClientTrackerDevice *)NULL); + nassertv(device != nullptr); ClientBase *client = device->get_client(); - nassertv(client != (ClientBase *)NULL); + nassertv(client != nullptr); set_tracker_coordinate_system(client->get_coordinate_system()); set_graph_coordinate_system(CS_default); } diff --git a/panda/src/device/trackerNode.h b/panda/src/device/trackerNode.h index 628422324b..29e88047bb 100644 --- a/panda/src/device/trackerNode.h +++ b/panda/src/device/trackerNode.h @@ -31,7 +31,7 @@ */ class EXPCL_PANDA_DEVICE TrackerNode : public DataNode { PUBLISHED: - explicit TrackerNode(ClientBase *client, const string &device_name); + explicit TrackerNode(ClientBase *client, const std::string &device_name); explicit TrackerNode(ClientTrackerDevice *device); virtual ~TrackerNode(); diff --git a/panda/src/device/virtualMouse.cxx b/panda/src/device/virtualMouse.cxx index fc0782828b..cdbf5aa678 100644 --- a/panda/src/device/virtualMouse.cxx +++ b/panda/src/device/virtualMouse.cxx @@ -20,7 +20,7 @@ TypeHandle VirtualMouse::_type_handle; * */ VirtualMouse:: -VirtualMouse(const string &name) : +VirtualMouse(const std::string &name) : DataNode(name) { _pixel_xy_output = define_output("pixel_xy", EventStoreVec2::get_class_type()); diff --git a/panda/src/device/virtualMouse.h b/panda/src/device/virtualMouse.h index 037180305d..2afa1b8d72 100644 --- a/panda/src/device/virtualMouse.h +++ b/panda/src/device/virtualMouse.h @@ -31,7 +31,7 @@ */ class EXPCL_PANDA_DEVICE VirtualMouse : public DataNode { PUBLISHED: - explicit VirtualMouse(const string &name); + explicit VirtualMouse(const std::string &name); void set_mouse_pos(int x, int y); void set_window_size(int width, int height); diff --git a/panda/src/dgraph/dataGraphTraverser.cxx b/panda/src/dgraph/dataGraphTraverser.cxx index 3b3900d8ea..d0f695bc50 100644 --- a/panda/src/dgraph/dataGraphTraverser.cxx +++ b/panda/src/dgraph/dataGraphTraverser.cxx @@ -58,7 +58,7 @@ traverse(PandaNode *node) { // We must start the traversal at the root of the graph. nassertv(data_node->get_num_parents(_current_thread) == 0); - r_transmit(data_node, (DataNodeTransmit *)NULL); + r_transmit(data_node, nullptr); } else { traverse_below(node, DataNodeTransmit()); diff --git a/panda/src/dgraph/dataNode.I b/panda/src/dgraph/dataNode.I index b9bcbb2fa1..a466de9d24 100644 --- a/panda/src/dgraph/dataNode.I +++ b/panda/src/dgraph/dataNode.I @@ -15,7 +15,7 @@ * */ INLINE DataNode:: -DataNode(const string &name) : +DataNode(const std::string &name) : PandaNode(name) { } diff --git a/panda/src/dgraph/dataNode.cxx b/panda/src/dgraph/dataNode.cxx index 564a19f45d..a67c0b0c0d 100644 --- a/panda/src/dgraph/dataNode.cxx +++ b/panda/src/dgraph/dataNode.cxx @@ -16,6 +16,8 @@ #include "config_dgraph.h" #include "dcast.h" +using std::string; + TypeHandle DataNode::_type_handle; /** @@ -100,7 +102,7 @@ transmit_data(DataGraphTraverser *trav, * might expect to receive. */ void DataNode:: -write_inputs(ostream &out) const { +write_inputs(std::ostream &out) const { Wires::const_iterator wi; for (wi = _input_wires.begin(); wi != _input_wires.end(); ++wi) { const string &name = (*wi).first; @@ -114,7 +116,7 @@ write_inputs(ostream &out) const { * might generate. */ void DataNode:: -write_outputs(ostream &out) const { +write_outputs(std::ostream &out) const { Wires::const_iterator wi; for (wi = _output_wires.begin(); wi != _output_wires.end(); ++wi) { const string &name = (*wi).first; @@ -128,7 +130,7 @@ write_outputs(ostream &out) const { * showing between this DataNode and its parent(s). */ void DataNode:: -write_connections(ostream &out) const { +write_connections(std::ostream &out) const { DataConnections::const_iterator ci; for (ci = _data_connections.begin(); ci != _data_connections.end(); ++ci) { const DataConnection &connect = (*ci); diff --git a/panda/src/dgraph/dataNode.h b/panda/src/dgraph/dataNode.h index 0f5e52b0fc..7386b52b9a 100644 --- a/panda/src/dgraph/dataNode.h +++ b/panda/src/dgraph/dataNode.h @@ -51,7 +51,7 @@ class DataNodeTransmit; */ class EXPCL_PANDA_DGRAPH DataNode : public PandaNode { PUBLISHED: - INLINE explicit DataNode(const string &name); + INLINE explicit DataNode(const std::string &name); protected: INLINE DataNode(const DataNode ©); @@ -66,13 +66,13 @@ public: INLINE int get_num_outputs() const; PUBLISHED: - void write_inputs(ostream &out) const; - void write_outputs(ostream &out) const; - void write_connections(ostream &out) const; + void write_inputs(std::ostream &out) const; + void write_outputs(std::ostream &out) const; + void write_connections(std::ostream &out) const; protected: - int define_input(const string &name, TypeHandle data_type); - int define_output(const string &name, TypeHandle data_type); + int define_input(const std::string &name, TypeHandle data_type); + int define_output(const std::string &name, TypeHandle data_type); protected: // Inherited from PandaNode @@ -92,7 +92,7 @@ private: int _index; }; - typedef pmap Wires; + typedef pmap Wires; Wires _input_wires; Wires _output_wires; diff --git a/panda/src/display/callbackGraphicsWindow.I b/panda/src/display/callbackGraphicsWindow.I index 1a1f104a36..3a05f82fdd 100644 --- a/panda/src/display/callbackGraphicsWindow.I +++ b/panda/src/display/callbackGraphicsWindow.I @@ -32,7 +32,7 @@ set_events_callback(CallbackObject *object) { */ INLINE void CallbackGraphicsWindow:: clear_events_callback() { - set_events_callback(NULL); + set_events_callback(nullptr); } /** @@ -66,7 +66,7 @@ set_properties_callback(CallbackObject *object) { */ INLINE void CallbackGraphicsWindow:: clear_properties_callback() { - set_properties_callback(NULL); + set_properties_callback(nullptr); } /** @@ -96,7 +96,7 @@ set_render_callback(CallbackObject *object) { */ INLINE void CallbackGraphicsWindow:: clear_render_callback() { - set_render_callback(NULL); + set_render_callback(nullptr); } /** diff --git a/panda/src/display/callbackGraphicsWindow.cxx b/panda/src/display/callbackGraphicsWindow.cxx index f9c2362ed7..ebe2442d17 100644 --- a/panda/src/display/callbackGraphicsWindow.cxx +++ b/panda/src/display/callbackGraphicsWindow.cxx @@ -24,12 +24,12 @@ TypeHandle CallbackGraphicsWindow::RenderCallbackData::_type_handle; */ CallbackGraphicsWindow:: CallbackGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, GraphicsStateGuardian *gsg) : - GraphicsWindow(engine, pipe, name, fb_prop, win_prop, flags, gsg, NULL) + GraphicsWindow(engine, pipe, name, fb_prop, win_prop, flags, gsg, nullptr) { #ifdef DO_MEMORY_USAGE MemoryUsage::update_type(this, this); @@ -65,7 +65,7 @@ get_input_device(int device) { * Returns the index of the new device. */ int CallbackGraphicsWindow:: -create_input_device(const string &name) { +create_input_device(const std::string &name) { GraphicsWindowInputDevice device = GraphicsWindowInputDevice::pointer_and_keyboard(this, name); return add_input_device(device); @@ -80,7 +80,7 @@ create_input_device(const string &name) { bool CallbackGraphicsWindow:: begin_frame(FrameMode mode, Thread *current_thread) { bool result = false; - if (_render_callback != NULL) { + if (_render_callback != nullptr) { RenderCallbackData data(this, RCT_begin_frame, mode); _render_callback->do_callback(&data); result = data.get_render_flag(); @@ -105,7 +105,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { */ void CallbackGraphicsWindow:: end_frame(FrameMode mode, Thread *current_thread) { - if (_render_callback != NULL) { + if (_render_callback != nullptr) { // In case the callback or the application hosting the OpenGL context // wants to do more rendering, let's give it a blank slate. _gsg->set_state_and_transform(RenderState::make_empty(), _gsg->get_internal_transform()); @@ -138,7 +138,7 @@ end_frame(FrameMode mode, Thread *current_thread) { */ void CallbackGraphicsWindow:: begin_flip() { - if (_render_callback != NULL) { + if (_render_callback != nullptr) { RenderCallbackData data(this, RCT_begin_flip, FM_render); _render_callback->do_callback(&data); } else { @@ -155,7 +155,7 @@ begin_flip() { */ void CallbackGraphicsWindow:: end_flip() { - if (_render_callback != NULL) { + if (_render_callback != nullptr) { RenderCallbackData data(this, RCT_end_flip, FM_render); _render_callback->do_callback(&data); } else { @@ -172,7 +172,7 @@ end_flip() { */ void CallbackGraphicsWindow:: process_events() { - if (_events_callback != NULL) { + if (_events_callback != nullptr) { EventsCallbackData data(this); _events_callback->do_callback(&data); } else { @@ -186,7 +186,7 @@ process_events() { */ void CallbackGraphicsWindow:: set_properties_now(WindowProperties &properties) { - if (_properties_callback != NULL) { + if (_properties_callback != nullptr) { PropertiesCallbackData data(this, properties); _properties_callback->do_callback(&data); } else { diff --git a/panda/src/display/callbackGraphicsWindow.h b/panda/src/display/callbackGraphicsWindow.h index a676dff9f4..fc7d8310f5 100644 --- a/panda/src/display/callbackGraphicsWindow.h +++ b/panda/src/display/callbackGraphicsWindow.h @@ -27,7 +27,7 @@ class EXPCL_PANDA_DISPLAY CallbackGraphicsWindow : public GraphicsWindow { protected: CallbackGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -179,7 +179,7 @@ PUBLISHED: INLINE CallbackObject *get_render_callback() const; GraphicsWindowInputDevice &get_input_device(int device); - int create_input_device(const string &name); + int create_input_device(const std::string &name); public: virtual bool begin_frame(FrameMode mode, Thread *current_thread); diff --git a/panda/src/display/displayInformation.cxx b/panda/src/display/displayInformation.cxx index d690544889..337da59699 100644 --- a/panda/src/display/displayInformation.cxx +++ b/panda/src/display/displayInformation.cxx @@ -46,7 +46,7 @@ operator != (const DisplayMode &other) const { * */ void DisplayMode:: -output(ostream &out) const { +output(std::ostream &out) const { out << width << 'x' << height; if (bits_per_pixel > 0) { out << ' ' << bits_per_pixel << "bpp"; @@ -64,7 +64,7 @@ output(ostream &out) const { */ DisplayInformation:: ~DisplayInformation() { - if (_display_mode_array != NULL) { + if (_display_mode_array != nullptr) { delete[] _display_mode_array; } } @@ -94,7 +94,7 @@ DisplayInformation() { window_height = 0; window_bits_per_pixel = 0; total_display_modes = 0; - display_mode_array = NULL; + display_mode_array = nullptr; video_memory = 0; texture_memory = 0; physical_memory = 0; @@ -148,8 +148,8 @@ DisplayInformation() { _num_cpu_cores = 0; _num_logical_cpus = 0; - _get_memory_information_function = 0; - _update_cpu_frequency_function = 0; + _get_memory_information_function = nullptr; + _update_cpu_frequency_function = nullptr; _os_version_major = -1; _os_version_minor = -1; @@ -489,7 +489,7 @@ get_driver_date_year() { /** * */ -const string &DisplayInformation:: +const std::string &DisplayInformation:: get_cpu_vendor_string() const { return _cpu_vendor_string; } @@ -497,7 +497,7 @@ get_cpu_vendor_string() const { /** * */ -const string &DisplayInformation:: +const std::string &DisplayInformation:: get_cpu_brand_string() const { return _cpu_brand_string; } diff --git a/panda/src/display/displayInformation.h b/panda/src/display/displayInformation.h index 919e400741..2869c8320a 100644 --- a/panda/src/display/displayInformation.h +++ b/panda/src/display/displayInformation.h @@ -27,7 +27,7 @@ PUBLISHED: bool operator == (const DisplayMode &other) const; bool operator != (const DisplayMode &other) const; - void output(ostream &out) const; + void output(std::ostream &out) const; }; /** @@ -94,8 +94,8 @@ PUBLISHED: int get_driver_date_day(); int get_driver_date_year(); - const string &get_cpu_vendor_string() const; - const string &get_cpu_brand_string() const; + const std::string &get_cpu_vendor_string() const; + const std::string &get_cpu_brand_string() const; unsigned int get_cpu_version_information(); unsigned int get_cpu_brand_index(); @@ -155,8 +155,8 @@ public: int _driver_date_year; - string _cpu_vendor_string; - string _cpu_brand_string; + std::string _cpu_vendor_string; + std::string _cpu_brand_string; unsigned int _cpu_version_information; unsigned int _cpu_brand_index; diff --git a/panda/src/display/displayRegion.I b/panda/src/display/displayRegion.I index 8982461879..96f2383bf9 100644 --- a/panda/src/display/displayRegion.I +++ b/panda/src/display/displayRegion.I @@ -306,7 +306,7 @@ set_cull_callback(CallbackObject *object) { */ INLINE void DisplayRegion:: clear_cull_callback() { - set_cull_callback(NULL); + set_cull_callback(nullptr); } /** @@ -354,7 +354,7 @@ set_draw_callback(CallbackObject *object) { */ INLINE void DisplayRegion:: clear_draw_callback() { - set_draw_callback(NULL); + set_draw_callback(nullptr); } /** @@ -479,13 +479,8 @@ INLINE void DisplayRegion:: set_cull_result(PT(CullResult) cull_result, PT(SceneSetup) scene_setup, Thread *current_thread) { CDCullWriter cdata(_cycler_cull, true, current_thread); -#ifdef USE_MOVE_SEMANTICS - cdata->_cull_result = move(cull_result); - cdata->_scene_setup = move(scene_setup); -#else - swap(cdata->_cull_result, cull_result); - swap(cdata->_scene_setup, scene_setup); -#endif + cdata->_cull_result = std::move(cull_result); + cdata->_scene_setup = std::move(scene_setup); } /** @@ -572,22 +567,6 @@ DisplayRegionPipelineReader(DisplayRegion *object, Thread *current_thread) : #endif // _DEBUG } -/** - * Don't attempt to copy these objects. - */ -INLINE DisplayRegionPipelineReader:: -DisplayRegionPipelineReader(const DisplayRegionPipelineReader &) { - nassertv(false); -} - -/** - * Don't attempt to copy these objects. - */ -INLINE void DisplayRegionPipelineReader:: -operator = (const DisplayRegionPipelineReader &) { - nassertv(false); -} - /** * */ @@ -602,8 +581,8 @@ INLINE DisplayRegionPipelineReader:: _object->_cycler.release_read(_cdata); #ifdef _DEBUG - _object = NULL; - _cdata = NULL; + _object = nullptr; + _cdata = nullptr; #endif // _DEBUG } @@ -884,8 +863,8 @@ get_pixel_height(int i) const { return _cdata->_regions[i]._pixels[3] - _cdata->_regions[i]._pixels[2]; } -INLINE ostream & -operator << (ostream &out, const DisplayRegion &dr) { +INLINE std::ostream & +operator << (std::ostream &out, const DisplayRegion &dr) { dr.output(out); return out; } diff --git a/panda/src/display/displayRegion.cxx b/panda/src/display/displayRegion.cxx index 99aea51477..e1765861e1 100644 --- a/panda/src/display/displayRegion.cxx +++ b/panda/src/display/displayRegion.cxx @@ -23,6 +23,8 @@ #include +using std::string; + TypeHandle DisplayRegion::_type_handle; TypeHandle DisplayRegionPipelineReader::_type_handle; @@ -46,25 +48,6 @@ DisplayRegion(GraphicsOutput *window, const LVecBase4 &dimensions) : _window->add_display_region(this); } -/** - * - */ -DisplayRegion:: -DisplayRegion(const DisplayRegion ©) : - _window(NULL), - _cull_region_pcollector("Cull:Invalid"), - _draw_region_pcollector("Draw:Invalid") -{ -} - -/** - * - */ -void DisplayRegion:: -operator = (const DisplayRegion&) { - nassertv(false); -} - /** * */ @@ -75,7 +58,7 @@ DisplayRegion:: // The window pointer should already have been cleared by the time the // DisplayRegion destructs (since the GraphicsOutput class keeps a reference // count on the DisplayRegion). - nassertv(_window == (GraphicsOutput *)NULL); + nassertv(_window == nullptr); } /** @@ -126,7 +109,7 @@ set_dimensions(int i, const LVecBase4 &dimensions) { cdata->_regions[i]._dimensions = dimensions; - if (_window != (GraphicsOutput *)NULL && _window->has_size()) { + if (_window != nullptr && _window->has_size()) { do_compute_pixels(i, _window->get_fb_x_size(), _window->get_fb_y_size(), cdata); } } @@ -137,7 +120,7 @@ set_dimensions(int i, const LVecBase4 &dimensions) { */ GraphicsPipe *DisplayRegion:: get_pipe() const { - return (_window != (GraphicsOutput *)NULL) ? _window->get_pipe() : NULL; + return (_window != nullptr) ? _window->get_pipe() : nullptr; } /** @@ -163,7 +146,7 @@ void DisplayRegion:: set_camera(const NodePath &camera) { CDWriter cdata(_cycler, true); - Camera *camera_node = (Camera *)NULL; + Camera *camera_node = nullptr; if (!camera.is_empty()) { DCAST_INTO_V(camera_node, camera.node()); } @@ -172,12 +155,12 @@ set_camera(const NodePath &camera) { // Note that these operations on the DisplayRegion are not pipelined: they // operate across all pipeline stages. Since we have already asserted we // are running in pipeline stage 0, no problem. - if (cdata->_camera_node != (Camera *)NULL) { + if (cdata->_camera_node != nullptr) { // We need to tell the old camera we're not using him anymore. cdata->_camera_node->remove_display_region(this); } cdata->_camera_node = camera_node; - if (cdata->_camera_node != (Camera *)NULL) { + if (cdata->_camera_node != nullptr) { // Now tell the new camera we are using him. cdata->_camera_node->add_display_region(this); } @@ -326,7 +309,7 @@ set_cull_traverser(CullTraverser *trav) { */ CullTraverser *DisplayRegion:: get_cull_traverser() { - if (_trav == (CullTraverser *)NULL) { + if (_trav == nullptr) { _trav = new CullTraverser; } return _trav; @@ -358,7 +341,7 @@ set_target_tex_page(int page) { * */ void DisplayRegion:: -output(ostream &out) const { +output(std::ostream &out) const { CDReader cdata(_cycler); out << "DisplayRegion(" << cdata->_regions[0]._dimensions << ")=pixels(" << cdata->_regions[0]._pixels << ")"; @@ -375,14 +358,14 @@ output(ostream &out) const { */ Filename DisplayRegion:: make_screenshot_filename(const string &prefix) { - time_t now = time(NULL); + time_t now = time(nullptr); struct tm *ttm = localtime(&now); int frame_count = ClockObject::get_global_clock()->get_frame_count(); static const int buffer_size = 1024; char buffer[buffer_size]; - ostringstream filename_strm; + std::ostringstream filename_strm; size_t i = 0; while (i < screenshot_filename.length()) { @@ -475,7 +458,7 @@ bool DisplayRegion:: get_screenshot(PNMImage &image) { PT(Texture) tex = get_screenshot(); - if (tex == NULL) { + if (tex == nullptr) { return false; } @@ -495,13 +478,21 @@ get_screenshot() { Thread *current_thread = Thread::get_current_thread(); GraphicsOutput *window = get_window(); - nassertr(window != (GraphicsOutput *)NULL, NULL); + nassertr(window != nullptr, nullptr); GraphicsStateGuardian *gsg = window->get_gsg(); - nassertr(gsg != (GraphicsStateGuardian *)NULL, NULL); + nassertr(gsg != nullptr, nullptr); + // Are we on the draw thread? + if (gsg->get_threading_model().get_draw_stage() != current_thread->get_pipeline_stage()) { + // Ask the engine to do on the draw thread. + GraphicsEngine *engine = window->get_engine(); + return engine->do_get_screenshot(this, gsg); + } + + // We are on the draw thread. if (!window->begin_frame(GraphicsOutput::FM_refresh, current_thread)) { - return NULL; + return nullptr; } { @@ -515,7 +506,7 @@ get_screenshot() { RenderBuffer buffer = gsg->get_render_buffer(get_screenshot_buffer_type(), _window->get_fb_properties()); if (!gsg->framebuffer_copy_to_ram(tex, 0, -1, this, buffer)) { - return NULL; + return nullptr; } window->end_frame(GraphicsOutput::FM_refresh, current_thread); @@ -541,8 +532,8 @@ get_screenshot() { PT(PandaNode) DisplayRegion:: make_cull_result_graph() { CullResult *cull_result = get_cull_result(Thread::get_current_thread()); - if (cull_result == (CullResult *)NULL) { - return NULL; + if (cull_result == nullptr) { + return nullptr; } return cull_result->make_result_graph(); } @@ -553,7 +544,7 @@ make_cull_result_graph() { */ void DisplayRegion:: compute_pixels() { - if (_window != (GraphicsOutput *)NULL) { + if (_window != nullptr) { CDWriter cdata(_cycler, false); for (size_t i = 0; i < cdata->_regions.size(); ++i) { do_compute_pixels(i, _window->get_fb_x_size(), _window->get_fb_y_size(), @@ -568,7 +559,7 @@ compute_pixels() { */ void DisplayRegion:: compute_pixels_all_stages() { - if (_window != (GraphicsOutput *)NULL) { + if (_window != nullptr) { OPEN_ITERATE_ALL_STAGES(_cycler) { CDStageWriter cdata(_cycler, pipeline_stage); for (size_t i = 0; i < cdata->_regions.size(); ++i) { @@ -621,7 +612,7 @@ compute_pixels_all_stages(int x_size, int y_size) { */ bool DisplayRegion:: supports_pixel_zoom() const { - if (_window != (GraphicsOutput *)NULL) { + if (_window != nullptr) { if (_window->supports_pixel_zoom()) { return get_clear_color_active() && get_clear_depth_active(); } @@ -636,7 +627,7 @@ supports_pixel_zoom() const { */ void DisplayRegion:: win_display_regions_changed() { - if (_window != (GraphicsOutput *)NULL) { + if (_window != nullptr) { _window->win_display_regions_changed(); } } @@ -659,7 +650,7 @@ do_compute_pixels(int i, int x_size, int y_size, CData *cdata) { region._pixels_i[0] = region._pixels[0]; region._pixels_i[1] = region._pixels[1]; - nassertv(_window != (GraphicsOutput *)NULL); + nassertv(_window != nullptr); if (_window->get_inverted()) { // The window is inverted; compute the DisplayRegion accordingly. region._pixels[2] = int(((1.0f - region._dimensions[3]) * y_size) + 0.5); @@ -687,7 +678,7 @@ do_compute_pixels(int i, int x_size, int y_size, CData *cdata) { void DisplayRegion:: set_active_index(int index) { #ifdef DO_PSTATS - ostringstream strm; + std::ostringstream strm; strm << "dr_" << index; string name = strm.str(); @@ -713,7 +704,7 @@ do_cull(CullHandler *cull_handler, SceneSetup *scene_setup, DisplayRegion::CData:: CData() : _lens_index(0), - _camera_node((Camera *)NULL), + _camera_node(nullptr), _active(true), _sort(0), _stereo_channel(Lens::SC_mono), @@ -764,5 +755,5 @@ make_copy() const { */ GraphicsPipe *DisplayRegionPipelineReader:: get_pipe() const { - return (_object->_window != (GraphicsOutput *)NULL) ? _object->_window->get_pipe() : NULL; + return (_object->_window != nullptr) ? _object->_window->get_pipe() : nullptr; } diff --git a/panda/src/display/displayRegion.h b/panda/src/display/displayRegion.h index 091f17e13f..e97829be2c 100644 --- a/panda/src/display/displayRegion.h +++ b/panda/src/display/displayRegion.h @@ -57,10 +57,8 @@ class CullTraverser; class EXPCL_PANDA_DISPLAY DisplayRegion : public TypedReferenceCount, public DrawableRegion { protected: DisplayRegion(GraphicsOutput *window, const LVecBase4 &dimensions); - -private: - DisplayRegion(const DisplayRegion ©); - void operator = (const DisplayRegion ©); + DisplayRegion(const DisplayRegion ©) = delete; + void operator = (const DisplayRegion ©) = delete; public: virtual ~DisplayRegion(); @@ -152,13 +150,13 @@ PUBLISHED: INLINE LVecBase2i get_pixel_size(int i = 0) const; MAKE_PROPERTY(pixel_size, get_pixel_size); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; static Filename make_screenshot_filename( - const string &prefix = "screenshot"); - Filename save_screenshot_default(const string &prefix = "screenshot"); + const std::string &prefix = "screenshot"); + Filename save_screenshot_default(const std::string &prefix = "screenshot"); bool save_screenshot( - const Filename &filename, const string &image_comment = ""); + const Filename &filename, const std::string &image_comment = ""); bool get_screenshot(PNMImage &image); PT(Texture) get_screenshot(); @@ -310,9 +308,8 @@ private: class EXPCL_PANDA_DISPLAY DisplayRegionPipelineReader { public: INLINE DisplayRegionPipelineReader(DisplayRegion *object, Thread *current_thread); -private: - INLINE DisplayRegionPipelineReader(const DisplayRegionPipelineReader ©); - INLINE void operator = (const DisplayRegionPipelineReader ©); + DisplayRegionPipelineReader(const DisplayRegionPipelineReader ©) = delete; + void operator = (const DisplayRegionPipelineReader ©) = delete; public: INLINE ~DisplayRegionPipelineReader(); @@ -374,7 +371,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const DisplayRegion &dr); +INLINE std::ostream &operator << (std::ostream &out, const DisplayRegion &dr); #include "displayRegion.I" diff --git a/panda/src/display/displayRegionCullCallbackData.cxx b/panda/src/display/displayRegionCullCallbackData.cxx index 39268fbabe..822ecdce7b 100644 --- a/panda/src/display/displayRegionCullCallbackData.cxx +++ b/panda/src/display/displayRegionCullCallbackData.cxx @@ -33,7 +33,7 @@ DisplayRegionCullCallbackData(CullHandler *cull_handler, SceneSetup *scene_setup * */ void DisplayRegionCullCallbackData:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << "(" << (void *)_cull_handler << ", " << (void *)_scene_setup << ")"; } diff --git a/panda/src/display/displayRegionCullCallbackData.h b/panda/src/display/displayRegionCullCallbackData.h index 509f5e2e2c..c8830a52c9 100644 --- a/panda/src/display/displayRegionCullCallbackData.h +++ b/panda/src/display/displayRegionCullCallbackData.h @@ -24,12 +24,12 @@ class SceneSetup; * This specialization on CallbackData is passed when the callback is * initiated from the cull traversal, for a DisplayRegion. */ -class EXPCL_PANDA_PGRAPH DisplayRegionCullCallbackData : public CallbackData { +class EXPCL_PANDA_DISPLAY DisplayRegionCullCallbackData : public CallbackData { public: DisplayRegionCullCallbackData(CullHandler *cull_handler, SceneSetup *scene_setup); PUBLISHED: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; INLINE CullHandler *get_cull_handler() const; INLINE SceneSetup *get_scene_setup() const; diff --git a/panda/src/display/displayRegionDrawCallbackData.cxx b/panda/src/display/displayRegionDrawCallbackData.cxx index e0ecfcbffb..b95a3086e2 100644 --- a/panda/src/display/displayRegionDrawCallbackData.cxx +++ b/panda/src/display/displayRegionDrawCallbackData.cxx @@ -37,7 +37,7 @@ DisplayRegionDrawCallbackData(CullResult *cull_result, SceneSetup *scene_setup) * */ void DisplayRegionDrawCallbackData:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << "(" << (void *)_cull_result << ", " << (void *)_scene_setup << ")"; } @@ -57,7 +57,7 @@ upcall() { DisplayRegion *dr = _scene_setup->get_display_region(); GraphicsStateGuardian *gsg = dr->get_window()->get_gsg(); - if (_cull_result == NULL || _scene_setup == NULL) { + if (_cull_result == nullptr || _scene_setup == nullptr) { // Nothing to see here. } else if (dr->is_stereo()) { diff --git a/panda/src/display/displayRegionDrawCallbackData.h b/panda/src/display/displayRegionDrawCallbackData.h index 55f76baf2e..feea6034b6 100644 --- a/panda/src/display/displayRegionDrawCallbackData.h +++ b/panda/src/display/displayRegionDrawCallbackData.h @@ -24,12 +24,12 @@ class SceneSetup; * This specialization on CallbackData is passed when the callback is * initiated from the draw traversal, for a DisplayRegion. */ -class EXPCL_PANDA_PGRAPH DisplayRegionDrawCallbackData : public CallbackData { +class EXPCL_PANDA_DISPLAY DisplayRegionDrawCallbackData : public CallbackData { public: DisplayRegionDrawCallbackData(CullResult *cull_result, SceneSetup *scene_setup); PUBLISHED: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; INLINE CullResult *get_cull_result() const; INLINE SceneSetup *get_scene_setup() const; diff --git a/panda/src/display/drawableRegion.I b/panda/src/display/drawableRegion.I index 677a345683..71fc1658cc 100644 --- a/panda/src/display/drawableRegion.I +++ b/panda/src/display/drawableRegion.I @@ -242,7 +242,7 @@ INLINE void DrawableRegion:: update_pixel_factor() { PN_stdfloat new_pixel_factor; if (supports_pixel_zoom()) { - new_pixel_factor = (PN_stdfloat)1 / sqrt(max(_pixel_zoom, (PN_stdfloat)1.0)); + new_pixel_factor = (PN_stdfloat)1 / sqrt(std::max(_pixel_zoom, (PN_stdfloat)1.0)); } else { new_pixel_factor = 1; } diff --git a/panda/src/display/frameBufferProperties.I b/panda/src/display/frameBufferProperties.I index 6f2d3257ee..756a98c0be 100644 --- a/panda/src/display/frameBufferProperties.I +++ b/panda/src/display/frameBufferProperties.I @@ -11,21 +11,6 @@ * @date 2003-01-27 */ -/** - * - */ -INLINE FrameBufferProperties:: -FrameBufferProperties(const FrameBufferProperties ©) { - (*this) = copy; -} - -/** - * - */ -INLINE FrameBufferProperties:: -~FrameBufferProperties() { -} - /** * */ @@ -53,8 +38,8 @@ is_stereo() const { /** * */ -INLINE ostream & -operator << (ostream &out, const FrameBufferProperties &properties) { +INLINE std::ostream & +operator << (std::ostream &out, const FrameBufferProperties &properties) { properties.output(out); return out; } @@ -72,7 +57,7 @@ get_depth_bits() const { */ INLINE int FrameBufferProperties:: get_color_bits() const { - return max(_property[FBP_color_bits], + return std::max(_property[FBP_color_bits], _property[FBP_red_bits] + _property[FBP_green_bits] + _property[FBP_blue_bits]); @@ -337,7 +322,7 @@ set_accum_bits(int n) { */ INLINE void FrameBufferProperties:: set_aux_rgba(int n) { - nassertv(n < 4); + nassertv(n <= 4); _property[FBP_aux_rgba] = n; _specified |= (1 << FBP_aux_rgba); } @@ -347,7 +332,7 @@ set_aux_rgba(int n) { */ INLINE void FrameBufferProperties:: set_aux_hrgba(int n) { - nassertv(n < 4); + nassertv(n <= 4); _property[FBP_aux_hrgba] = n; _specified |= (1 << FBP_aux_hrgba); } @@ -357,7 +342,7 @@ set_aux_hrgba(int n) { */ INLINE void FrameBufferProperties:: set_aux_float(int n) { - nassertv(n < 4); + nassertv(n <= 4); _property[FBP_aux_float] = n; _specified |= (1 << FBP_aux_float); } diff --git a/panda/src/display/frameBufferProperties.cxx b/panda/src/display/frameBufferProperties.cxx index ea37cc4381..cb6d14da3f 100644 --- a/panda/src/display/frameBufferProperties.cxx +++ b/panda/src/display/frameBufferProperties.cxx @@ -17,28 +17,6 @@ #include "config_display.h" #include "texture.h" -/** - * - */ -FrameBufferProperties:: -FrameBufferProperties() { - clear(); -} - -/** - * - */ -void FrameBufferProperties:: -operator = (const FrameBufferProperties ©) { - _flags_specified = copy._flags_specified; - _flags = copy._flags; - _specified = copy._specified; - - for (int i = 0; i < FBP_COUNT; ++i) { - _property[i] = copy._property[i]; - } -} - /** * Returns true if this set of properties makes strictly greater or equal * demands of the framebuffer than the other set of framebuffer properties. @@ -235,7 +213,7 @@ add_properties(const FrameBufferProperties &other) { * Generates a string representation. */ void FrameBufferProperties:: -output(ostream &out) const { +output(std::ostream &out) const { if ((_flags & FBF_float_depth) != 0) { out << "float_depth "; } @@ -564,7 +542,7 @@ get_quality(const FrameBufferProperties &reqs) const { for (int prop = FBP_aux_rgba; prop <= FBP_aux_float; ++prop) { int extra = _property[prop] > reqs._property[prop]; if (extra > 0) { - extra = min(extra, 3); + extra = std::min(extra, 3); quality -= extra*50; } } @@ -623,7 +601,7 @@ get_quality(const FrameBufferProperties &reqs) const { * false. */ bool FrameBufferProperties:: -verify_hardware_software(const FrameBufferProperties &props, const string &renderer) const { +verify_hardware_software(const FrameBufferProperties &props, const std::string &renderer) const { if (get_force_hardware() < props.get_force_hardware()) { display_cat.error() diff --git a/panda/src/display/frameBufferProperties.h b/panda/src/display/frameBufferProperties.h index 9ac6c015ea..152f2dccc7 100644 --- a/panda/src/display/frameBufferProperties.h +++ b/panda/src/display/frameBufferProperties.h @@ -63,11 +63,11 @@ private: FBF_all = 0x100-1, }; - int _property[FBP_COUNT]; - int _specified; + int _property[FBP_COUNT] = {0}; + int _specified = 0; - int _flags; - int _flags_specified; + int _flags = 0; + int _flags_specified = 0; PUBLISHED: @@ -145,10 +145,8 @@ PUBLISHED: // Other. - FrameBufferProperties(); - INLINE FrameBufferProperties(const FrameBufferProperties ©); - INLINE ~FrameBufferProperties(); - void operator = (const FrameBufferProperties ©); + constexpr FrameBufferProperties() = default; + static const FrameBufferProperties &get_default(); bool operator == (const FrameBufferProperties &other) const; INLINE bool operator != (const FrameBufferProperties &other) const; @@ -157,7 +155,7 @@ PUBLISHED: void set_all_specified(); bool subsumes(const FrameBufferProperties &other) const; void add_properties(const FrameBufferProperties &other); - void output(ostream &out) const; + void output(std::ostream &out) const; void set_one_bit_per_channel(); INLINE bool is_stereo() const; @@ -167,13 +165,13 @@ PUBLISHED: bool is_basic() const; int get_aux_mask() const; int get_buffer_mask() const; - bool verify_hardware_software(const FrameBufferProperties &props, const string &renderer) const; + bool verify_hardware_software(const FrameBufferProperties &props, const std::string &renderer) const; bool setup_color_texture(Texture *tex) const; bool setup_depth_texture(Texture *tex) const; }; -INLINE ostream &operator << (ostream &out, const FrameBufferProperties &properties); +INLINE std::ostream &operator << (std::ostream &out, const FrameBufferProperties &properties); #include "frameBufferProperties.I" diff --git a/panda/src/display/graphicsBuffer.cxx b/panda/src/display/graphicsBuffer.cxx index bb0b086309..6955305a96 100644 --- a/panda/src/display/graphicsBuffer.cxx +++ b/panda/src/display/graphicsBuffer.cxx @@ -21,7 +21,7 @@ TypeHandle GraphicsBuffer::_type_handle; */ GraphicsBuffer:: GraphicsBuffer(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, GraphicsStateGuardian *gsg, diff --git a/panda/src/display/graphicsBuffer.h b/panda/src/display/graphicsBuffer.h index caff1d9284..5c7e833f57 100644 --- a/panda/src/display/graphicsBuffer.h +++ b/panda/src/display/graphicsBuffer.h @@ -28,7 +28,7 @@ class EXPCL_PANDA_DISPLAY GraphicsBuffer : public GraphicsOutput { protected: GraphicsBuffer(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/display/graphicsDevice.cxx b/panda/src/display/graphicsDevice.cxx index fb74bca7d8..665e12534e 100644 --- a/panda/src/display/graphicsDevice.cxx +++ b/panda/src/display/graphicsDevice.cxx @@ -34,22 +34,6 @@ GraphicsDevice(GraphicsPipe *pipe) { } } -/** - * - */ -GraphicsDevice:: -GraphicsDevice(const GraphicsDevice &) { - nassertv(false); -} - -/** - * - */ -void GraphicsDevice:: -operator = (const GraphicsDevice &) { - nassertv(false); -} - /** * */ diff --git a/panda/src/display/graphicsDevice.h b/panda/src/display/graphicsDevice.h index afb1edb697..532024642a 100644 --- a/panda/src/display/graphicsDevice.h +++ b/panda/src/display/graphicsDevice.h @@ -30,10 +30,8 @@ class GraphicsPipe; class EXPCL_PANDA_DISPLAY GraphicsDevice : public TypedReferenceCount { public: GraphicsDevice(GraphicsPipe *pipe); - -private: - GraphicsDevice(const GraphicsDevice ©); - void operator = (const GraphicsDevice ©); + GraphicsDevice(const GraphicsDevice ©) = delete; + GraphicsDevice &operator = (const GraphicsDevice ©) = delete; PUBLISHED: virtual ~GraphicsDevice(); diff --git a/panda/src/display/graphicsEngine.I b/panda/src/display/graphicsEngine.I index eccf5cfee4..d0a4769a21 100644 --- a/panda/src/display/graphicsEngine.I +++ b/panda/src/display/graphicsEngine.I @@ -104,7 +104,7 @@ close_gsg(GraphicsPipe *pipe, GraphicsStateGuardian *gsg) { * sharing of resources. */ INLINE GraphicsOutput *GraphicsEngine:: -make_buffer(GraphicsOutput *host, const string &name, +make_buffer(GraphicsOutput *host, const std::string &name, int sort, int x_size, int y_size) { GraphicsOutput *result = make_output(host->get_pipe(), name, sort, FrameBufferProperties(), @@ -130,7 +130,7 @@ make_buffer(GraphicsOutput *host, const string &name, * the first parameter. */ INLINE GraphicsOutput *GraphicsEngine:: -make_buffer(GraphicsStateGuardian *gsg, const string &name, +make_buffer(GraphicsStateGuardian *gsg, const std::string &name, int sort, int x_size, int y_size) { FrameBufferProperties fb_props = FrameBufferProperties::get_default(); fb_props.set_back_buffers(0); @@ -144,7 +144,7 @@ make_buffer(GraphicsStateGuardian *gsg, const string &name, WindowProperties::size(x_size, y_size), GraphicsPipe::BF_refuse_window | GraphicsPipe::BF_fb_props_optional, - gsg, NULL); + gsg, nullptr); return result; } @@ -152,7 +152,7 @@ make_buffer(GraphicsStateGuardian *gsg, const string &name, * Syntactic shorthand for make_buffer. */ INLINE GraphicsOutput *GraphicsEngine:: -make_parasite(GraphicsOutput *host, const string &name, +make_parasite(GraphicsOutput *host, const std::string &name, int sort, int x_size, int y_size) { GraphicsOutput *result = make_output(host->get_pipe(), name, sort, FrameBufferProperties(), diff --git a/panda/src/display/graphicsEngine.cxx b/panda/src/display/graphicsEngine.cxx index f65c5377fc..dd637d7a9a 100644 --- a/panda/src/display/graphicsEngine.cxx +++ b/panda/src/display/graphicsEngine.cxx @@ -57,6 +57,8 @@ #include #endif +using std::string; + PT(GraphicsEngine) GraphicsEngine::_global_ptr; PStatCollector GraphicsEngine::_wait_pcollector("Wait:Thread sync"); @@ -147,7 +149,7 @@ GraphicsEngine(Pipeline *pipeline) : _lock("GraphicsEngine::_lock"), _loaded_textures_lock("GraphicsEngine::_loaded_textures_lock") { - if (_pipeline == (Pipeline *)NULL) { + if (_pipeline == nullptr) { _pipeline = Pipeline::get_render_pipeline(); } @@ -288,7 +290,7 @@ make_output(GraphicsPipe *pipe, if ((x_size == 0)&&(y_size == 0)) { flags |= GraphicsPipe::BF_size_track_host; } - if (host != 0) { + if (host != nullptr) { host = host->get_host(); } @@ -296,28 +298,28 @@ make_output(GraphicsPipe *pipe, // call open_windows to get both ready. If that fails, give up on using the // supplied gsg and host. - if (host == (GraphicsOutput *)NULL) { - if (gsg != (GraphicsStateGuardian*)NULL) { + if (host == nullptr) { + if (gsg != nullptr) { if ((!gsg->is_valid())||(gsg->needs_reset())) { open_windows(); } if ((!gsg->is_valid())||(gsg->needs_reset())) { - gsg = NULL; + gsg = nullptr; } } } else { - if ((host->get_gsg()==0)|| + if ((host->get_gsg()==nullptr)|| (!host->is_valid())|| (!host->get_gsg()->is_valid())|| (host->get_gsg()->needs_reset())) { open_windows(); } - if ((host->get_gsg()==0)|| + if ((host->get_gsg()==nullptr)|| (!host->is_valid())|| (!host->get_gsg()->is_valid())|| (host->get_gsg()->needs_reset())) { - host = NULL; - gsg = NULL; + host = nullptr; + gsg = nullptr; } else { gsg = host->get_gsg(); } @@ -325,21 +327,21 @@ make_output(GraphicsPipe *pipe, // Sanity check everything. - nassertr(pipe != (GraphicsPipe *)NULL, NULL); - if (gsg != (GraphicsStateGuardian *)NULL) { - nassertr(pipe == gsg->get_pipe(), NULL); - nassertr(this == gsg->get_engine(), NULL); + nassertr(pipe != nullptr, nullptr); + if (gsg != nullptr) { + nassertr(pipe == gsg->get_pipe(), nullptr); + nassertr(this == gsg->get_engine(), nullptr); } // Are we really asking for a callback window? if ((flags & GraphicsPipe::BF_require_callback_window)!=0) { PT(GraphicsStateGuardian) this_gsg = gsg; - if (this_gsg == (GraphicsStateGuardian *)NULL) { + if (this_gsg == nullptr) { // If we don't already have a GSG, we have to ask the pipe to make a new // one, unencumbered by window dressing. this_gsg = pipe->make_callback_gsg(this); } - if (this_gsg != (GraphicsStateGuardian *)NULL) { + if (this_gsg != nullptr) { CallbackGraphicsWindow *window = new CallbackGraphicsWindow(this, pipe, name, fb_prop, win_prop, flags, this_gsg); window->_sort = sort; do_add_window(window); @@ -350,13 +352,13 @@ make_output(GraphicsPipe *pipe, // Couldn't make a callback window, because the pipe wouldn't make an // unencumbered GSG. - return NULL; + return nullptr; } // Determine if a parasite buffer meets the user's specs. bool can_use_parasite = false; - if ((host != 0)&& + if ((host != nullptr)&& ((flags&GraphicsPipe::BF_require_window)==0)&& ((flags&GraphicsPipe::BF_require_callback_window)==0)&& ((flags&GraphicsPipe::BF_refuse_parasite)==0)&& @@ -406,7 +408,7 @@ make_output(GraphicsPipe *pipe, bool precertify = false; PT(GraphicsOutput) window = pipe->make_output(name, fb_prop, win_prop, flags, this, gsg, host, retry, precertify); - if (window != (GraphicsOutput *)NULL) { + if (window != nullptr) { window->_sort = sort; if (precertify && gsg != nullptr && window->get_gsg() == gsg) { do_add_window(window); @@ -445,8 +447,7 @@ make_output(GraphicsPipe *pipe, } // No good; delete the window and keep trying. - bool removed = remove_window(window); - nassertr(removed, NULL); + remove_window(window); } } @@ -464,7 +465,7 @@ make_output(GraphicsPipe *pipe, // Could not create a window to the user's specs. - return NULL; + return nullptr; } /** @@ -512,7 +513,7 @@ add_window(GraphicsOutput *window, int sort) { */ bool GraphicsEngine:: remove_window(GraphicsOutput *window) { - nassertr(window != NULL, false); + nassertr(window != nullptr, false); Thread *current_thread = Thread::get_current_thread(); // First, make sure we know what this window is. @@ -544,9 +545,9 @@ remove_window(GraphicsOutput *window) { do_remove_window(window, current_thread); GraphicsStateGuardian *gsg = window->get_gsg(); - if (gsg != (GraphicsStateGuardian *)NULL) { + if (gsg != nullptr) { PreparedGraphicsObjects *pgo = gsg->get_prepared_objects(); - if (pgo != (PreparedGraphicsObjects *)NULL) { + if (pgo != nullptr) { // Check to see if any other still-active windows share this context. bool any_common = false; { @@ -554,7 +555,7 @@ remove_window(GraphicsOutput *window) { Windows::iterator wi; for (wi = _windows.begin(); wi != _windows.end() && !any_common; ++wi) { GraphicsStateGuardian *gsg2 = (*wi)->get_gsg(); - if (gsg2 != (GraphicsStateGuardian *)NULL && + if (gsg2 != nullptr && gsg2->get_prepared_objects() == pgo) { any_common = true; } @@ -594,10 +595,10 @@ remove_all_windows() { Windows::iterator wi; for (wi = old_windows.begin(); wi != old_windows.end(); ++wi) { GraphicsOutput *win = (*wi); - nassertv(win != NULL); + nassertv(win != nullptr); do_remove_window(win, current_thread); GraphicsStateGuardian *gsg = win->get_gsg(); - if (gsg != (GraphicsStateGuardian *)NULL) { + if (gsg != nullptr) { gsg->release_all(); } } @@ -670,7 +671,7 @@ get_num_windows() const { */ GraphicsOutput *GraphicsEngine:: get_window(int n) const { - nassertr(n >= 0 && n < (int)_windows.size(), NULL); + nassertr(n >= 0 && n < (int)_windows.size(), nullptr); if (!_windows_sorted) { ((GraphicsEngine *)this)->do_resort_windows(); @@ -731,7 +732,7 @@ render_frame() { Windows::iterator wi; for (wi = _windows.begin(); wi != _windows.end(); ++wi) { GraphicsOutput *win = (*wi); - nassertv(win != NULL); + nassertv(win != nullptr); if (win->get_delete_flag()) { do_remove_window(win, current_thread); @@ -746,7 +747,7 @@ render_frame() { int num_drs = win->get_num_active_display_regions(); for (int i = 0; i < num_drs; ++i) { DisplayRegion *dr = win->get_active_display_region(i); - if (dr != (DisplayRegion *)NULL) { + if (dr != nullptr) { NodePath camera_np = dr->get_camera(current_thread); if (!camera_np.is_empty()) { Camera *camera = DCAST(Camera, camera_np.node()); @@ -1166,7 +1167,7 @@ extract_texture_data(Texture *tex, GraphicsStateGuardian *gsg) { */ void GraphicsEngine:: dispatch_compute(const LVecBase3i &work_groups, const ShaderAttrib *sattr, GraphicsStateGuardian *gsg) { - nassertv(sattr->get_shader() != (Shader *)NULL); + nassertv(sattr->get_shader() != nullptr); nassertv(gsg != nullptr); ReMutexHolder holder(_lock); @@ -1220,7 +1221,7 @@ dispatch_compute(const LVecBase3i &work_groups, const ShaderAttrib *sattr, Graph */ GraphicsEngine *GraphicsEngine:: get_global_ptr() { - if (_global_ptr == NULL) { + if (_global_ptr == nullptr) { _global_ptr = new GraphicsEngine; PandaNode::set_scene_root_func(&scene_root_func); } @@ -1248,6 +1249,43 @@ texture_uploaded(Texture *tex) { // Usually only called by DisplayRegion::do_cull. } +/** + * Called by DisplayRegion::do_get_screenshot + */ +PT(Texture) GraphicsEngine:: +do_get_screenshot(DisplayRegion *region, GraphicsStateGuardian *gsg) { + // A multi-threaded environment. We have to wait until the draw thread + // has finished its current task. + + ReMutexHolder holder(_lock); + + const std::string &draw_name = gsg->get_threading_model().get_draw_name(); + WindowRenderer *wr = get_window_renderer(draw_name, 0); + RenderThread *thread = (RenderThread *)wr; + MutexHolder cv_holder(thread->_cv_mutex); + + while (thread->_thread_state != TS_wait) { + thread->_cv_done.wait(); + } + + // Now that the draw thread is idle, signal it to do the extraction task. + thread->_region = region; + thread->_thread_state = TS_do_screenshot; + thread->_cv_start.notify(); + thread->_cv_mutex.release(); + thread->_cv_mutex.acquire(); + + //XXX is this necessary, or is acquiring the mutex enough? + while (thread->_thread_state != TS_wait) { + thread->_cv_done.wait(); + } + + PT(Texture) tex = std::move(thread->_texture); + thread->_region = nullptr; + thread->_texture = nullptr; + return tex; +} + /** * Fires off a cull traversal using the indicated camera. */ @@ -1261,7 +1299,7 @@ do_cull(CullHandler *cull_handler, SceneSetup *scene_setup, trav->set_cull_handler(cull_handler); trav->set_scene(scene_setup, gsg, dr->get_incomplete_render()); - trav->set_view_frustum(NULL); + trav->set_view_frustum(nullptr); if (view_frustum_cull) { // If we're to be performing view-frustum culling, determine the bounding // volume associated with the current viewing frustum. @@ -1270,8 +1308,8 @@ do_cull(CullHandler *cull_handler, SceneSetup *scene_setup, // lens. PT(BoundingVolume) bv = scene_setup->get_cull_bounds(); - if (bv != (BoundingVolume *)NULL && !bv->is_infinite() && - bv->as_geometric_bounding_volume() != NULL) { + if (bv != nullptr && !bv->is_infinite() && + bv->as_geometric_bounding_volume() != nullptr) { // Transform it into the appropriate coordinate space. PT(GeometricBoundingVolume) local_frustum; local_frustum = bv->make_copy()->as_geometric_bounding_volume(); @@ -1315,7 +1353,7 @@ is_scene_root(const PandaNode *node) { int num_display_regions = win->get_num_active_display_regions(); for (int i = 0; i < num_display_regions; i++) { DisplayRegion *dr = win->get_active_display_region(i); - if (dr != (DisplayRegion *)NULL) { + if (dr != nullptr) { NodePath camera = dr->get_camera(); if (camera.is_empty()) { continue; @@ -1391,7 +1429,7 @@ cull_and_draw_together(GraphicsEngine::Windows wlist, int num_display_regions = win->get_num_active_display_regions(); for (int i = 0; i < num_display_regions; i++) { DisplayRegion *dr = win->get_active_display_region(i); - if (dr != (DisplayRegion *)NULL) { + if (dr != nullptr) { cull_and_draw_together(win, dr, current_thread); } } @@ -1421,7 +1459,7 @@ void GraphicsEngine:: cull_and_draw_together(GraphicsOutput *win, DisplayRegion *dr, Thread *current_thread) { GraphicsStateGuardian *gsg = win->get_gsg(); - nassertv(gsg != (GraphicsStateGuardian *)NULL); + nassertv(gsg != nullptr); PT(SceneSetup) scene_setup; @@ -1437,7 +1475,7 @@ cull_and_draw_together(GraphicsOutput *win, DisplayRegion *dr, scene_setup = setup_scene(gsg, &dr_reader); } - if (scene_setup == (SceneSetup *)NULL) { + if (scene_setup == nullptr) { // Never mind. } else if (dr->is_stereo()) { @@ -1452,7 +1490,7 @@ cull_and_draw_together(GraphicsOutput *win, DisplayRegion *dr, DrawCullHandler cull_handler(gsg); if (gsg->begin_scene()) { CallbackObject *cbobj = dr->get_cull_callback(); - if (cbobj != (CallbackObject *)NULL) { + if (cbobj != nullptr) { // Issue the cull callback on this DisplayRegion. DisplayRegionCullCallbackData cbdata(&cull_handler, scene_setup); cbobj->do_callback(&cbdata); @@ -1512,7 +1550,7 @@ cull_to_bins(GraphicsEngine::Windows wlist, Thread *current_thread) { key._lens_index = dr_reader.get_lens_index(); } - AlreadyCulled::iterator aci = already_culled.insert(AlreadyCulled::value_type(move(key), nullptr)).first; + AlreadyCulled::iterator aci = already_culled.insert(AlreadyCulled::value_type(std::move(key), nullptr)).first; if ((*aci).second == nullptr) { // We have not used this camera already in this thread. Perform // the cull operation. @@ -1538,7 +1576,7 @@ cull_to_bins(GraphicsEngine::Windows wlist, Thread *current_thread) { } // Save the results for next frame. - dr->set_cull_result(MOVE(cull_result), MOVE(scene_setup), current_thread); + dr->set_cull_result(std::move(cull_result), MOVE(scene_setup), current_thread); } } } @@ -1555,7 +1593,7 @@ cull_to_bins(GraphicsOutput *win, GraphicsStateGuardian *gsg, BinCullHandler cull_handler(cull_result); CallbackObject *cbobj = dr->get_cull_callback(); - if (cbobj != (CallbackObject *)NULL) { + if (cbobj != nullptr) { // Issue the cull callback on this DisplayRegion. DisplayRegionCullCallbackData cbdata(&cull_handler, scene_setup); cbobj->do_callback(&cbdata); @@ -1615,7 +1653,7 @@ draw_bins(const GraphicsEngine::Windows &wlist, Thread *current_thread) { int num_display_regions = win->get_num_active_display_regions(); for (int i = 0; i < num_display_regions; ++i) { DisplayRegion *dr = win->get_active_display_region(i); - if (dr != (DisplayRegion *)NULL) { + if (dr != nullptr) { do_draw(win, gsg, dr, current_thread); } } @@ -1848,28 +1886,28 @@ setup_scene(GraphicsStateGuardian *gsg, DisplayRegionPipelineReader *dr) { GraphicsOutput *window = dr->get_window(); // The window pointer shouldn't be NULL, since we presumably got to this // particular DisplayRegion by walking through a list on a window. - nassertr(window != (GraphicsOutput *)NULL, NULL); + nassertr(window != nullptr, nullptr); NodePath camera = dr->get_camera(); if (camera.is_empty()) { // No camera, no draw. - return NULL; + return nullptr; } Camera *camera_node; - DCAST_INTO_R(camera_node, camera.node(), NULL); + DCAST_INTO_R(camera_node, camera.node(), nullptr); if (!camera_node->is_active()) { // Camera inactive, no draw. - return NULL; + return nullptr; } camera_node->cleanup_aux_scene_data(current_thread); int lens_index = dr->get_lens_index(); Lens *lens = camera_node->get_lens(lens_index); - if (lens == (Lens *)NULL || !camera_node->get_lens_active(lens_index)) { + if (lens == nullptr || !camera_node->get_lens_active(lens_index)) { // No lens, no draw. - return NULL; + return nullptr; } NodePath scene_root = camera_node->get_scene(); @@ -1901,7 +1939,7 @@ setup_scene(GraphicsStateGuardian *gsg, DisplayRegionPipelineReader *dr) { << scene_root.get_scale(NodePath()) << "); cannot render.\n"; _singular_warning_this_frame = true; } - return NULL; + return nullptr; } if (world_transform->is_invalid()) { @@ -1912,7 +1950,7 @@ setup_scene(GraphicsStateGuardian *gsg, DisplayRegionPipelineReader *dr) { << camera.get_scale(NodePath()) << "); cannot render.\n"; } _singular_warning_this_frame = true; - return NULL; + return nullptr; } CPT(RenderState) initial_state = camera_node->get_initial_state(); @@ -1976,7 +2014,7 @@ do_draw(GraphicsOutput *win, GraphicsStateGuardian *gsg, DisplayRegion *dr, Thre cbobj = dr_reader.get_draw_callback(); } - if (cbobj != (CallbackObject *)NULL) { + if (cbobj != nullptr) { // Issue the draw callback on this DisplayRegion. // Set the GSG to the initial state. @@ -1993,7 +2031,7 @@ do_draw(GraphicsOutput *win, GraphicsStateGuardian *gsg, DisplayRegion *dr, Thre return; } - if (cull_result == NULL || scene_setup == NULL) { + if (cull_result == nullptr || scene_setup == nullptr) { // Nothing to see here. } else if (dr->is_stereo()) { @@ -2049,7 +2087,7 @@ do_add_window(GraphicsOutput *window) { */ void GraphicsEngine:: do_add_gsg(GraphicsStateGuardian *gsg, GraphicsPipe *pipe) { - nassertv(gsg != NULL); + nassertv(gsg != nullptr); ReMutexHolder holder(_lock); nassertv(gsg->get_pipe() == pipe && gsg->get_engine() == this); @@ -2074,7 +2112,7 @@ do_add_gsg(GraphicsStateGuardian *gsg, GraphicsPipe *pipe) { */ void GraphicsEngine:: do_remove_window(GraphicsOutput *window, Thread *current_thread) { - nassertv(window != NULL); + nassertv(window != nullptr); PT(GraphicsPipe) pipe = window->get_pipe(); window->clear_pipe(); @@ -2285,8 +2323,8 @@ const RenderState *GraphicsEngine:: get_invert_polygon_state() { // Once someone asks for this pointer, we hold its reference count and never // free it. - static CPT(RenderState) state = (const RenderState *)NULL; - if (state == (const RenderState *)NULL) { + static CPT(RenderState) state = nullptr; + if (state == nullptr) { state = RenderState::make(CullFaceAttrib::make_reverse()); } @@ -2303,7 +2341,7 @@ get_invert_polygon_state() { */ GraphicsEngine::WindowRenderer *GraphicsEngine:: get_window_renderer(const string &name, int pipeline_stage) { - nassertr(_lock.debug_is_locked(), NULL); + nassertr(_lock.debug_is_locked(), nullptr); if (name.empty()) { return &_app; @@ -2362,7 +2400,7 @@ add_window(Windows &wlist, GraphicsOutput *window) { */ void GraphicsEngine::WindowRenderer:: remove_window(GraphicsOutput *window) { - nassertv(window != NULL); + nassertv(window != nullptr); LightReMutexHolder holder(_wl_lock); PT(GraphicsOutput) ptwin = window; @@ -2632,6 +2670,11 @@ thread_main() { _result = _gsg->extract_texture_data(_texture); break; + case TS_do_screenshot: + nassertd(_region != nullptr) break; + _texture = _region->get_screenshot(); + break; + case TS_terminate: do_pending(_engine, current_thread); do_close(_engine, current_thread); diff --git a/panda/src/display/graphicsEngine.h b/panda/src/display/graphicsEngine.h index c21bec1d73..3371f20b39 100644 --- a/panda/src/display/graphicsEngine.h +++ b/panda/src/display/graphicsEngine.h @@ -52,7 +52,7 @@ class Texture; */ class EXPCL_PANDA_DISPLAY GraphicsEngine : public ReferenceCount { PUBLISHED: - explicit GraphicsEngine(Pipeline *pipeline = NULL); + explicit GraphicsEngine(Pipeline *pipeline = nullptr); BLOCKING ~GraphicsEngine(); void set_threading_model(const GraphicsThreadingModel &threading_model); @@ -75,21 +75,21 @@ PUBLISHED: MAKE_PROPERTY(default_loader, get_default_loader, set_default_loader); GraphicsOutput *make_output(GraphicsPipe *pipe, - const string &name, int sort, + const std::string &name, int sort, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, - int flags, GraphicsStateGuardian *gsg = NULL, - GraphicsOutput *host = NULL); + int flags, GraphicsStateGuardian *gsg = nullptr, + GraphicsOutput *host = nullptr); // Syntactic shorthand versions of make_output INLINE GraphicsOutput *make_buffer(GraphicsOutput *host, - const string &name, int sort, + const std::string &name, int sort, int x_size, int y_size); INLINE GraphicsOutput *make_buffer(GraphicsStateGuardian *gsg, - const string &name, int sort, + const std::string &name, int sort, int x_size, int y_size); INLINE GraphicsOutput *make_parasite(GraphicsOutput *host, - const string &name, int sort, + const std::string &name, int sort, int x_size, int y_size); bool add_window(GraphicsOutput *window, int sort); @@ -125,11 +125,13 @@ public: TS_do_windows, TS_do_compute, TS_do_extract, + TS_do_screenshot, TS_terminate, TS_done }; void texture_uploaded(Texture *tex); + PT(Texture) do_get_screenshot(DisplayRegion *region, GraphicsStateGuardian *gsg); public: static void do_cull(CullHandler *cull_handler, SceneSetup *scene_setup, @@ -176,7 +178,7 @@ private: void auto_adjust_capabilities(GraphicsStateGuardian *gsg); #ifdef DO_PSTATS - typedef map CyclerTypeCounters; + typedef std::map CyclerTypeCounters; CyclerTypeCounters _all_cycler_types; CyclerTypeCounters _dirty_cycler_types; static void pstats_count_cycler_type(TypeHandle type, int count, void *data); @@ -262,7 +264,7 @@ private: class WindowRenderer { public: - WindowRenderer(const string &name); + WindowRenderer(const std::string &name); void add_gsg(GraphicsStateGuardian *gsg); void add_window(Windows &wlist, GraphicsOutput *window); @@ -293,7 +295,7 @@ private: class RenderThread : public Thread, public WindowRenderer { public: - RenderThread(const string &name, GraphicsEngine *engine); + RenderThread(const std::string &name, GraphicsEngine *engine); virtual void thread_main(); GraphicsEngine *_engine; @@ -304,13 +306,14 @@ private: // These are stored for extract_texture_data and dispatch_compute. GraphicsStateGuardian *_gsg; - Texture *_texture; + PT(Texture) _texture; const RenderState *_state; + DisplayRegion *_region; LVecBase3i _work_groups; bool _result; }; - WindowRenderer *get_window_renderer(const string &name, int pipeline_stage); + WindowRenderer *get_window_renderer(const std::string &name, int pipeline_stage); Pipeline *_pipeline; Windows _windows; @@ -322,7 +325,7 @@ private: pvector _new_windows; WindowRenderer _app; - typedef pmap Threads; + typedef pmap Threads; Threads _threads; GraphicsThreadingModel _threading_model; bool _auto_flip; diff --git a/panda/src/display/graphicsOutput.I b/panda/src/display/graphicsOutput.I index 393dbaadb5..c94c83f54c 100644 --- a/panda/src/display/graphicsOutput.I +++ b/panda/src/display/graphicsOutput.I @@ -48,7 +48,7 @@ get_engine() const { /** * Returns the name that was passed to the GraphicsOutput constructor. */ -INLINE const string &GraphicsOutput:: +INLINE const std::string &GraphicsOutput:: get_name() const { return _name; } @@ -87,7 +87,7 @@ INLINE Texture *GraphicsOutput:: get_texture(int i) const { CDReader cdata(_cycler); if ((i < 0) || (i >= ((int)cdata->_textures.size()))) { - return (Texture *)NULL; + return nullptr; } return cdata->_textures[i]._texture; } @@ -167,8 +167,8 @@ get_y_size() const { */ INLINE LVecBase2i GraphicsOutput:: get_fb_size() const { - return LVecBase2i(max(int(_size.get_x() * get_pixel_factor()), 1), - max(int(_size.get_y() * get_pixel_factor()), 1)); + return LVecBase2i(std::max(int(_size.get_x() * get_pixel_factor()), 1), + std::max(int(_size.get_y() * get_pixel_factor()), 1)); } /** @@ -178,7 +178,7 @@ get_fb_size() const { */ INLINE int GraphicsOutput:: get_fb_x_size() const { - return max(int(_size.get_x() * get_pixel_factor()), 1); + return std::max(int(_size.get_x() * get_pixel_factor()), 1); } /** @@ -188,7 +188,7 @@ get_fb_x_size() const { */ INLINE int GraphicsOutput:: get_fb_y_size() const { - return max(int(_size.get_y() * get_pixel_factor()), 1); + return std::max(int(_size.get_y() * get_pixel_factor()), 1); } /** @@ -200,8 +200,8 @@ INLINE LVecBase2i GraphicsOutput:: get_sbs_left_size() const { PN_stdfloat left_w = _sbs_left_dimensions[1] - _sbs_left_dimensions[0]; PN_stdfloat left_h = _sbs_left_dimensions[3] - _sbs_left_dimensions[2]; - return LVecBase2i(max(int(_size.get_x() * left_w), 1), - max(int(_size.get_y() * left_h), 1)); + return LVecBase2i(std::max(int(_size.get_x() * left_w), 1), + std::max(int(_size.get_y() * left_h), 1)); } /** @@ -212,7 +212,7 @@ get_sbs_left_size() const { INLINE int GraphicsOutput:: get_sbs_left_x_size() const { PN_stdfloat left_w = _sbs_left_dimensions[1] - _sbs_left_dimensions[0]; - return max(int(_size.get_x() * left_w), 1); + return std::max(int(_size.get_x() * left_w), 1); } /** @@ -223,7 +223,7 @@ get_sbs_left_x_size() const { INLINE int GraphicsOutput:: get_sbs_left_y_size() const { PN_stdfloat left_h = _sbs_left_dimensions[3] - _sbs_left_dimensions[2]; - return max(int(_size.get_y() * left_h), 1); + return std::max(int(_size.get_y() * left_h), 1); } /** @@ -235,8 +235,8 @@ INLINE LVecBase2i GraphicsOutput:: get_sbs_right_size() const { PN_stdfloat right_w = _sbs_right_dimensions[1] - _sbs_right_dimensions[0]; PN_stdfloat right_h = _sbs_right_dimensions[3] - _sbs_right_dimensions[2]; - return LVecBase2i(max(int(_size.get_x() * right_w), 1), - max(int(_size.get_y() * right_h), 1)); + return LVecBase2i(std::max(int(_size.get_x() * right_w), 1), + std::max(int(_size.get_y() * right_h), 1)); } /** @@ -247,7 +247,7 @@ get_sbs_right_size() const { INLINE int GraphicsOutput:: get_sbs_right_x_size() const { PN_stdfloat right_w = _sbs_right_dimensions[1] - _sbs_right_dimensions[0]; - return max(int(_size.get_x() * right_w), 1); + return std::max(int(_size.get_x() * right_w), 1); } /** @@ -258,7 +258,7 @@ get_sbs_right_x_size() const { INLINE int GraphicsOutput:: get_sbs_right_y_size() const { PN_stdfloat right_h = _sbs_right_dimensions[3] - _sbs_right_dimensions[2]; - return max(int(_size.get_y() * right_h), 1); + return std::max(int(_size.get_y() * right_h), 1); } /** @@ -602,7 +602,7 @@ get_overlay_display_region() const { * screenshot-extension All other % strings in strftime(). */ INLINE Filename GraphicsOutput:: -make_screenshot_filename(const string &prefix) { +make_screenshot_filename(const std::string &prefix) { return DisplayRegion::make_screenshot_filename(prefix); } @@ -612,7 +612,7 @@ make_screenshot_filename(const string &prefix) { * generated by make_screenshot_filename(). */ INLINE Filename GraphicsOutput:: -save_screenshot_default(const string &prefix) { +save_screenshot_default(const std::string &prefix) { return _overlay_display_region->save_screenshot_default(prefix); } @@ -623,7 +623,7 @@ save_screenshot_default(const string &prefix) { * jpg allows comments). Returns true on success, false on failure. */ INLINE bool GraphicsOutput:: -save_screenshot(const Filename &filename, const string &image_comment) { +save_screenshot(const Filename &filename, const std::string &image_comment) { return _overlay_display_region->save_screenshot(filename, image_comment); } @@ -734,7 +734,7 @@ end_frame_spam(FrameMode mode) { INLINE void GraphicsOutput:: clear_cube_map_selection() { _target_tex_page = -1; - _prev_page_dr = NULL; + _prev_page_dr = nullptr; } /** diff --git a/panda/src/display/graphicsOutput.cxx b/panda/src/display/graphicsOutput.cxx index 4d8a1e27a1..7c6cef51cb 100644 --- a/panda/src/display/graphicsOutput.cxx +++ b/panda/src/display/graphicsOutput.cxx @@ -34,6 +34,8 @@ #include "throw_event.h" #include "config_gobj.h" +using std::string; + TypeHandle GraphicsOutput::_type_handle; PStatCollector GraphicsOutput::_make_current_pcollector("Draw:Make current"); @@ -101,7 +103,7 @@ GraphicsOutput(GraphicsEngine *engine, GraphicsPipe *pipe, _is_valid = false; _flip_ready = false; _target_tex_page = -1; - _prev_page_dr = NULL; + _prev_page_dr = nullptr; _sort = 0; _child_sort = 0; _got_child_sort = false; @@ -159,25 +161,6 @@ GraphicsOutput(GraphicsEngine *engine, GraphicsPipe *pipe, set_clear_color(background_color.get_value()); } -/** - * - */ -GraphicsOutput:: -GraphicsOutput(const GraphicsOutput &) : - _cull_window_pcollector(_cull_pcollector, "Invalid"), - _draw_window_pcollector(_draw_pcollector, "Invalid") -{ - nassertv(false); -} - -/** - * - */ -void GraphicsOutput:: -operator = (const GraphicsOutput &) { - nassertv(false); -} - /** * */ @@ -187,7 +170,7 @@ GraphicsOutput:: nassertv(!is_valid()); // We shouldn't have a GraphicsPipe pointer anymore. - nassertv(_pipe == (GraphicsPipe *)NULL); + nassertv(_pipe == nullptr); // We don't have to destruct our child display regions explicitly, since // they are all reference-counted and will go away when their pointers do. @@ -196,11 +179,11 @@ GraphicsOutput:: for (dri = _total_display_regions.begin(); dri != _total_display_regions.end(); ++dri) { - (*dri)->_window = NULL; + (*dri)->_window = nullptr; } _total_display_regions.clear(); - _overlay_display_region = NULL; + _overlay_display_region = nullptr; } /** @@ -259,7 +242,7 @@ add_render_texture(Texture *tex, RenderTextureMode mode, LightMutexHolder holder(_lock); // Create texture if necessary. - if (tex == (Texture *)NULL) { + if (tex == nullptr) { tex = new Texture(get_name()); tex->set_wrap_u(SamplerState::WM_clamp); tex->set_wrap_v(SamplerState::WM_clamp); @@ -363,7 +346,7 @@ add_render_texture(Texture *tex, RenderTextureMode mode, } } - if (mode == RTM_bind_layered && _gsg != NULL && !_gsg->get_supports_geometry_shaders()) { + if (mode == RTM_bind_layered && _gsg != nullptr && !_gsg->get_supports_geometry_shaders()) { // Layered FBOs require a geometry shader to write to any but the first // layer. display_cat.warning() << @@ -574,8 +557,8 @@ get_delete_flag() const { void GraphicsOutput:: set_sort(int sort) { if (_sort != sort) { - if (_gsg != (GraphicsStateGuardian *)NULL && - _gsg->get_engine() != (GraphicsEngine *)NULL) { + if (_gsg != nullptr && + _gsg->get_engine() != nullptr) { _gsg->get_engine()->set_window_sort(this, sort); } } @@ -725,7 +708,7 @@ remove_all_display_regions() { if (display_region != _overlay_display_region) { // Let's aggressively clean up the display region too. display_region->cleanup(); - display_region->_window = NULL; + display_region->_window = nullptr; } } _total_display_regions.clear(); @@ -781,7 +764,7 @@ get_display_region(int n) const { if (n >= 0 && n < (int)_total_display_regions.size()) { result = _total_display_regions[n]; } else { - result = NULL; + result = nullptr; } } return result; @@ -812,7 +795,7 @@ get_active_display_region(int n) const { if (n >= 0 && n < (int)cdata->_active_display_regions.size()) { return cdata->_active_display_regions[n]; } - return NULL; + return nullptr; } /** @@ -849,7 +832,7 @@ make_texture_buffer(const string &name, int x_size, int y_size, props.set_alpha_bits(1); props.set_depth_bits(1); - if (fbp == NULL) { + if (fbp == nullptr) { fbp = &props; } @@ -857,7 +840,7 @@ make_texture_buffer(const string &name, int x_size, int y_size, if (textures_power_2 != ATS_none) { flags |= GraphicsPipe::BF_size_power_2; } - if (tex != (Texture *)NULL && + if (tex != nullptr && tex->get_texture_type() == Texture::TT_cube_map) { flags |= GraphicsPipe::BF_size_square; } @@ -868,8 +851,8 @@ make_texture_buffer(const string &name, int x_size, int y_size, *fbp, WindowProperties::size(x_size, y_size), flags, get_gsg(), get_host()); - if (buffer != (GraphicsOutput *)NULL) { - if (buffer->get_gsg() == (GraphicsStateGuardian *)NULL || + if (buffer != nullptr) { + if (buffer->get_gsg() == nullptr || buffer->get_gsg()->get_prepared_objects() != get_gsg()->get_prepared_objects()) { // If the newly-created buffer doesn't share texture objects with the // current GSG, then we will have to force the texture copy to go @@ -881,7 +864,7 @@ make_texture_buffer(const string &name, int x_size, int y_size, return buffer; } - return NULL; + return nullptr; } /** @@ -911,10 +894,10 @@ make_cube_map(const string &name, int size, NodePath &camera_rig, // The GSG doesn't support cube mapping; too bad for you. display_cat.warning() << "Cannot make dynamic cube map; GSG does not support cube maps.\n"; - return NULL; + return nullptr; } if (max_dimension > 0) { - size = min(max_dimension, size); + size = std::min(max_dimension, size); } } @@ -972,7 +955,7 @@ make_cube_map(const string &name, int size, NodePath &camera_rig, */ NodePath GraphicsOutput:: get_texture_card() { - if (_texture_card == NULL) { + if (_texture_card == nullptr) { PT(GeomVertexData) vdata = create_texture_card_vdata(get_x_size(), get_y_size()); PT(GeomTristrips) strip = new GeomTristrips(Geom::UH_static); strip->set_shade_model(Geom::SM_uniform); @@ -1091,7 +1074,7 @@ reset_window(bool swapchain) { */ void GraphicsOutput:: clear_pipe() { - _pipe = (GraphicsPipe *)NULL; + _pipe = nullptr; } /** @@ -1116,7 +1099,7 @@ set_size_and_recalc(int x, int y) { (*dri)->compute_pixels_all_stages(fb_x_size, fb_y_size); } - if (_texture_card != NULL && _texture_card->get_num_geoms() > 0) { + if (_texture_card != nullptr && _texture_card->get_num_geoms() > 0) { _texture_card->modify_geom(0)->set_vertex_data(create_texture_card_vdata(x, y)); } } @@ -1137,7 +1120,7 @@ clear(Thread *current_thread) { << get_name() << " " << (void *)this << "\n"; } - nassertv(_gsg != (GraphicsStateGuardian *)NULL); + nassertv(_gsg != nullptr); DisplayRegionPipelineReader dr_reader(_overlay_display_region, current_thread); _gsg->prepare_display_region(&dr_reader); @@ -1201,7 +1184,7 @@ change_scenes(DisplayRegionPipelineReader *new_dr) { // In copy-to-texture mode, copy the just-rendered framebuffer to // the old texture page. - nassertv(old_page_dr != (DisplayRegion *)NULL); + nassertv(old_page_dr != nullptr); if (display_cat.is_debug()) { display_cat.debug() << "Copying texture for " << get_name() << " at scene change.\n"; @@ -1409,7 +1392,7 @@ copy_to_textures() { bool copied = false; DisplayRegion *dr = _overlay_display_region; - if (_prev_page_dr != (DisplayRegion *)NULL) { + if (_prev_page_dr != nullptr) { dr = _prev_page_dr; } @@ -1523,7 +1506,7 @@ do_remove_display_region(DisplayRegion *display_region) { // Let's aggressively clean up the display region too. CDWriter cdata(_cycler, true); display_region->cleanup(); - display_region->_window = NULL; + display_region->_window = nullptr; _total_display_regions.erase(dri); cdata->_active_display_regions_stale = true; @@ -1559,7 +1542,9 @@ do_determine_display_regions(GraphicsOutput::CData *cdata) { } } - stable_sort(cdata->_active_display_regions.begin(), cdata->_active_display_regions.end(), IndirectLess()); + std::stable_sort(cdata->_active_display_regions.begin(), + cdata->_active_display_regions.end(), + IndirectLess()); } /** @@ -1646,8 +1631,8 @@ make_copy() const { /** * */ -ostream & -operator << (ostream &out, GraphicsOutput::FrameMode fm) { +std::ostream & +operator << (std::ostream &out, GraphicsOutput::FrameMode fm) { switch (fm) { case GraphicsOutput::FM_render: return out << "render"; diff --git a/panda/src/display/graphicsOutput.h b/panda/src/display/graphicsOutput.h index 2f9eff8683..acd41e8289 100644 --- a/panda/src/display/graphicsOutput.h +++ b/panda/src/display/graphicsOutput.h @@ -64,16 +64,14 @@ class EXPCL_PANDA_DISPLAY GraphicsOutput : public GraphicsOutputBase, public Dra protected: GraphicsOutput(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, GraphicsStateGuardian *gsg, GraphicsOutput *host, bool default_stereo_flags); - -private: - GraphicsOutput(const GraphicsOutput ©); - void operator = (const GraphicsOutput ©); + GraphicsOutput(const GraphicsOutput ©) = delete; + GraphicsOutput &operator = (const GraphicsOutput ©) = delete; PUBLISHED: enum RenderTextureMode { @@ -115,7 +113,7 @@ PUBLISHED: INLINE GraphicsStateGuardian *get_gsg() const; INLINE GraphicsPipe *get_pipe() const; INLINE GraphicsEngine *get_engine() const; - INLINE const string &get_name() const; + INLINE const std::string &get_name() const; MAKE_PROPERTY(gsg, get_gsg); MAKE_PROPERTY(pipe, get_pipe); MAKE_PROPERTY(engine, get_engine); @@ -226,19 +224,19 @@ PUBLISHED: MAKE_SEQ_PROPERTY(active_display_regions, get_num_active_display_regions, get_active_display_region); GraphicsOutput *make_texture_buffer( - const string &name, int x_size, int y_size, - Texture *tex = NULL, bool to_ram = false, FrameBufferProperties *fbp = NULL); - GraphicsOutput *make_cube_map(const string &name, int size, + const std::string &name, int x_size, int y_size, + Texture *tex = nullptr, bool to_ram = false, FrameBufferProperties *fbp = nullptr); + GraphicsOutput *make_cube_map(const std::string &name, int size, NodePath &camera_rig, DrawMask camera_mask = PandaNode::get_all_camera_mask(), - bool to_ram = false, FrameBufferProperties *fbp = NULL); + bool to_ram = false, FrameBufferProperties *fbp = nullptr); INLINE static Filename make_screenshot_filename( - const string &prefix = "screenshot"); + const std::string &prefix = "screenshot"); INLINE Filename save_screenshot_default( - const string &prefix = "screenshot"); + const std::string &prefix = "screenshot"); INLINE bool save_screenshot( - const Filename &filename, const string &image_comment = ""); + const Filename &filename, const std::string &image_comment = ""); INLINE bool get_screenshot(PNMImage &image); INLINE PT(Texture) get_screenshot(); @@ -316,7 +314,7 @@ private: INLINE void determine_display_regions() const; void do_determine_display_regions(CData *cdata); - static unsigned int parse_color_mask(const string &word); + static unsigned int parse_color_mask(const std::string &word); protected: PT(GraphicsStateGuardian) _gsg; @@ -325,7 +323,7 @@ protected: PT(GraphicsOutput) _host; FrameBufferProperties _fb_properties; bool _stereo; - string _name; + std::string _name; bool _flip_ready; int _target_tex_page; int _target_tex_view; @@ -433,7 +431,7 @@ private: friend class DisplayRegion; }; -EXPCL_PANDA_DISPLAY ostream &operator << (ostream &out, GraphicsOutput::FrameMode mode); +EXPCL_PANDA_DISPLAY std::ostream &operator << (std::ostream &out, GraphicsOutput::FrameMode mode); #include "graphicsOutput.I" diff --git a/panda/src/display/graphicsPipe.cxx b/panda/src/display/graphicsPipe.cxx index ad5d1aea62..937987f567 100644 --- a/panda/src/display/graphicsPipe.cxx +++ b/panda/src/display/graphicsPipe.cxx @@ -60,7 +60,7 @@ union cpuid_info { */ static inline uint32_t get_cpuid_max(uint32_t leaf) { #if defined(__GNUC__) && !defined(__APPLE__) - return __get_cpuid_max(leaf, 0); + return __get_cpuid_max(leaf, nullptr); #elif defined(_MSC_VER) uint32_t p[4] = {0}; __cpuid((int *)p, leaf); @@ -134,8 +134,8 @@ GraphicsPipe() : if (max_cpuid >= 1) { get_cpuid(0, info); - swap(info.ecx, info.edx); - _display_information->_cpu_vendor_string = string(info.str + 4, 12); + std::swap(info.ecx, info.edx); + _display_information->_cpu_vendor_string = std::string(info.str + 4, 12); get_cpuid(1, info); _display_information->_cpu_version_information = info.eax; @@ -158,17 +158,17 @@ GraphicsPipe() : #if defined(IS_OSX) // macOS exposes a lot of useful information through sysctl. size_t len = sizeof(uint64_t); - sysctlbyname("hw.memsize", &_display_information->_physical_memory, &len, NULL, 0); + sysctlbyname("hw.memsize", &_display_information->_physical_memory, &len, nullptr, 0); len = sizeof(uint64_t); - sysctlbyname("hw.cpufrequency", &_display_information->_cpu_frequency, &len, NULL, 0); + sysctlbyname("hw.cpufrequency", &_display_information->_cpu_frequency, &len, nullptr, 0); len = sizeof(uint64_t); - sysctlbyname("hw.cpufrequency", &_display_information->_current_cpu_frequency, &len, NULL, 0); + sysctlbyname("hw.cpufrequency", &_display_information->_current_cpu_frequency, &len, nullptr, 0); len = sizeof(uint64_t); - sysctlbyname("hw.cpufrequency_max", &_display_information->_maximum_cpu_frequency, &len, NULL, 0); + sysctlbyname("hw.cpufrequency_max", &_display_information->_maximum_cpu_frequency, &len, nullptr, 0); len = sizeof(int); - sysctlbyname("hw.physicalcpu", &_display_information->_num_cpu_cores, &len, NULL, 0); + sysctlbyname("hw.physicalcpu", &_display_information->_num_cpu_cores, &len, nullptr, 0); len = sizeof(int); - sysctlbyname("hw.logicalcpu", &_display_information->_num_logical_cpus, &len, NULL, 0); + sysctlbyname("hw.logicalcpu", &_display_information->_num_logical_cpus, &len, nullptr, 0); #elif defined(IS_LINUX) _display_information->_get_memory_information_function = &update_memory_info; @@ -176,9 +176,9 @@ GraphicsPipe() : #elif defined(IS_FREEBSD) size_t len = sizeof(uint64_t); - sysctlbyname("hw.physmem", &_display_information->_physical_memory, &len, NULL, 0); + sysctlbyname("hw.physmem", &_display_information->_physical_memory, &len, nullptr, 0); len = sizeof(uint64_t); - sysctlbyname("vm.swap_total", &_display_information->_page_file_size, &len, NULL, 0); + sysctlbyname("vm.swap_total", &_display_information->_page_file_size, &len, nullptr, 0); #elif defined(_WIN32) MEMORYSTATUSEX status; @@ -228,7 +228,7 @@ GraphicsPipe::get_preferred_window_thread() const { */ PT(GraphicsStateGuardian) GraphicsPipe:: make_callback_gsg(GraphicsEngine *engine) { - return NULL; + return nullptr; } /** @@ -239,7 +239,7 @@ PT(GraphicsDevice) GraphicsPipe:: make_device(void *scrn) { display_cat.error() << "make_device() unimplemented by " << get_type() << "\n"; - return NULL; + return nullptr; } /** @@ -251,7 +251,7 @@ make_device(void *scrn) { */ void GraphicsPipe:: close_gsg(GraphicsStateGuardian *gsg) { - if (gsg != (GraphicsStateGuardian *)NULL) { + if (gsg != nullptr) { gsg->close_gsg(); } } @@ -260,7 +260,7 @@ close_gsg(GraphicsStateGuardian *gsg) { * Creates a new window on the pipe, if possible. */ PT(GraphicsOutput) GraphicsPipe:: -make_output(const string &name, +make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -271,7 +271,7 @@ make_output(const string &name, bool &precertify) { display_cat.error() << get_type() << " cannot create buffers or windows.\n"; - return NULL; + return nullptr; } /** diff --git a/panda/src/display/graphicsPipe.h b/panda/src/display/graphicsPipe.h index f7994b92e1..ef3a3b8496 100644 --- a/panda/src/display/graphicsPipe.h +++ b/panda/src/display/graphicsPipe.h @@ -52,9 +52,8 @@ class DisplayInformation; class EXPCL_PANDA_DISPLAY GraphicsPipe : public TypedReferenceCount { protected: GraphicsPipe(); -private: - GraphicsPipe(const GraphicsPipe ©) DELETED; - GraphicsPipe &operator = (const GraphicsPipe ©) DELETED_ASSIGN; + GraphicsPipe(const GraphicsPipe ©) = delete; + GraphicsPipe &operator = (const GraphicsPipe ©) = delete; PUBLISHED: virtual ~GraphicsPipe(); @@ -100,7 +99,7 @@ PUBLISHED: virtual void lookup_cpu_data(); - virtual string get_interface_name() const=0; + virtual std::string get_interface_name() const=0; MAKE_PROPERTY(interface_name, get_interface_name); public: @@ -111,14 +110,14 @@ public: virtual PreferredWindowThread get_preferred_window_thread() const; INLINE GraphicsDevice *get_device() const; - virtual PT(GraphicsDevice) make_device(void *scrn = NULL); + virtual PT(GraphicsDevice) make_device(void *scrn = nullptr); virtual PT(GraphicsStateGuardian) make_callback_gsg(GraphicsEngine *engine); protected: virtual void close_gsg(GraphicsStateGuardian *gsg); - virtual PT(GraphicsOutput) make_output(const string &name, + virtual PT(GraphicsOutput) make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/display/graphicsPipeSelection.I b/panda/src/display/graphicsPipeSelection.I index 100557bcc5..a3f68e0ec2 100644 --- a/panda/src/display/graphicsPipeSelection.I +++ b/panda/src/display/graphicsPipeSelection.I @@ -26,7 +26,7 @@ get_num_aux_modules() const { */ INLINE GraphicsPipeSelection *GraphicsPipeSelection:: get_global_ptr() { - if (_global_ptr == (GraphicsPipeSelection *)NULL) { + if (_global_ptr == nullptr) { _global_ptr = new GraphicsPipeSelection; } return _global_ptr; diff --git a/panda/src/display/graphicsPipeSelection.cxx b/panda/src/display/graphicsPipeSelection.cxx index 1134cc0553..9c4f52ff63 100644 --- a/panda/src/display/graphicsPipeSelection.cxx +++ b/panda/src/display/graphicsPipeSelection.cxx @@ -23,7 +23,9 @@ #include -GraphicsPipeSelection *GraphicsPipeSelection::_global_ptr = NULL; +using std::string; + +GraphicsPipeSelection *GraphicsPipeSelection::_global_ptr = nullptr; /** * @@ -121,7 +123,7 @@ print_pipe_types() const { load_default_module(); LightMutexHolder holder(_lock); - nout << "Known pipe types:" << endl; + nout << "Known pipe types:" << std::endl; PipeTypes::const_iterator pi; for (pi = _pipe_types.begin(); pi != _pipe_types.end(); ++pi) { const PipeType &pipe_type = (*pi); @@ -171,7 +173,7 @@ make_pipe(const string &type_name, const string &module_name) { } if (type == TypeHandle::none()) { - return NULL; + return nullptr; } return make_pipe(type); @@ -193,7 +195,7 @@ make_pipe(TypeHandle type) { if (ptype._type == type) { // Here's an exact match. PT(GraphicsPipe) pipe = (*ptype._constructor)(); - if (pipe != (GraphicsPipe *)NULL) { + if (pipe != nullptr) { return pipe; } } @@ -205,7 +207,7 @@ make_pipe(TypeHandle type) { if (ptype._type.is_derived_from(type)) { // Here's an approximate match. PT(GraphicsPipe) pipe = (*ptype._constructor)(); - if (pipe != (GraphicsPipe *)NULL) { + if (pipe != nullptr) { return pipe; } } @@ -218,14 +220,14 @@ make_pipe(TypeHandle type) { if (ptype._type.is_derived_from(type)) { // Here's an approximate match. PT(GraphicsPipe) pipe = (*ptype._constructor)(); - if (pipe != (GraphicsPipe *)NULL) { + if (pipe != nullptr) { return pipe; } } } // Couldn't find a matching pipe type. - return NULL; + return nullptr; } /** @@ -242,7 +244,7 @@ make_module_pipe(const string &module_name) { TypeHandle pipe_type = load_named_module(module_name); if (pipe_type == TypeHandle::none()) { - return NULL; + return nullptr; } return make_pipe(pipe_type); @@ -268,7 +270,7 @@ make_default_pipe() { if (cmp_nocase_uh(ptype._type.get_name(), _default_pipe_name) == 0) { // Here's an exact match. PT(GraphicsPipe) pipe = (*ptype._constructor)(); - if (pipe != (GraphicsPipe *)NULL) { + if (pipe != nullptr) { return pipe; } } @@ -282,7 +284,7 @@ make_default_pipe() { if (ptype_name.find(preferred_name) != string::npos) { // Here's a substring match. PT(GraphicsPipe) pipe = (*ptype._constructor)(); - if (pipe != (GraphicsPipe *)NULL) { + if (pipe != nullptr) { return pipe; } } @@ -293,13 +295,13 @@ make_default_pipe() { for (ti = _pipe_types.begin(); ti != _pipe_types.end(); ++ti) { const PipeType &ptype = (*ti); PT(GraphicsPipe) pipe = (*ptype._constructor)(); - if (pipe != (GraphicsPipe *)NULL) { + if (pipe != nullptr) { return pipe; } } // Nothing. Probably the list was empty. - return NULL; + return nullptr; } /** @@ -325,7 +327,7 @@ load_aux_modules() { */ bool GraphicsPipeSelection:: add_pipe_type(TypeHandle type, PipeConstructorFunc *func) { - nassertr(func != NULL, false); + nassertr(func != nullptr, false); if (!type.is_derived_from(GraphicsPipe::get_class_type())) { display_cat->warning() @@ -406,11 +408,11 @@ load_named_module(const string &name) { // We have not yet loaded this module. Load it now. Filename dlname = Filename::dso_filename("lib" + name + ".so"); display_cat.info() - << "loading display module: " << dlname.to_os_specific() << endl; + << "loading display module: " << dlname.to_os_specific() << std::endl; void *handle = load_dso(get_plugin_path().get_value(), dlname); - if (handle == (void *)NULL) { + if (handle == nullptr) { display_cat.warning() - << "Unable to load: " << load_dso_error() << endl; + << "Unable to load: " << load_dso_error() << std::endl; return TypeHandle::none(); } @@ -425,7 +427,7 @@ load_named_module(const string &name) { TypeHandle pipe_type = TypeHandle::none(); - if (dso_symbol == (void *)NULL) { + if (dso_symbol == nullptr) { // Couldn't find the module function. display_cat.warning() << "Unable to find " << symbol_name << " in " << dlname.get_basename() diff --git a/panda/src/display/graphicsPipeSelection.h b/panda/src/display/graphicsPipeSelection.h index d1dc5b641e..c3b61317e9 100644 --- a/panda/src/display/graphicsPipeSelection.h +++ b/panda/src/display/graphicsPipeSelection.h @@ -42,10 +42,10 @@ PUBLISHED: MAKE_SEQ_PROPERTY(pipe_types, get_num_pipe_types, get_pipe_type); void print_pipe_types() const; - PT(GraphicsPipe) make_pipe(const string &type_name, - const string &module_name = string()); + PT(GraphicsPipe) make_pipe(const std::string &type_name, + const std::string &module_name = std::string()); PT(GraphicsPipe) make_pipe(TypeHandle type); - PT(GraphicsPipe) make_module_pipe(const string &module_name); + PT(GraphicsPipe) make_module_pipe(const std::string &module_name); PT(GraphicsPipe) make_default_pipe(); INLINE int get_num_aux_modules() const; @@ -60,15 +60,15 @@ public: private: INLINE void load_default_module() const; void do_load_default_module(); - TypeHandle load_named_module(const string &name); + TypeHandle load_named_module(const std::string &name); class LoadedModule { public: - string _module_name; + std::string _module_name; void *_module_handle; TypeHandle _default_pipe_type; }; - typedef pmap LoadedModules; + typedef pmap LoadedModules; LoadedModules _loaded_modules; LightMutex _loaded_modules_lock; @@ -84,8 +84,8 @@ private: typedef vector_string DisplayModules; DisplayModules _display_modules; - string _default_display_module; - string _default_pipe_name; + std::string _default_display_module; + std::string _default_pipe_name; bool _default_module_loaded; static GraphicsPipeSelection *_global_ptr; diff --git a/panda/src/display/graphicsStateGuardian.I b/panda/src/display/graphicsStateGuardian.I index 94188b85be..f14a0fb087 100644 --- a/panda/src/display/graphicsStateGuardian.I +++ b/panda/src/display/graphicsStateGuardian.I @@ -258,7 +258,7 @@ get_max_vertices_per_primitive() const { INLINE int GraphicsStateGuardian:: get_max_texture_stages() const { if (max_texture_stages > 0) { - return min(_max_texture_stages, (int)max_texture_stages); + return std::min(_max_texture_stages, (int)max_texture_stages); } return _max_texture_stages; } @@ -695,7 +695,7 @@ get_timer_queries_active() const { INLINE int GraphicsStateGuardian:: get_max_color_targets() const { if (max_color_targets > 0) { - return min(_max_color_targets, (int)max_color_targets); + return std::min(_max_color_targets, (int)max_color_targets); } return _max_color_targets; } @@ -767,7 +767,7 @@ get_alpha_scale_via_texture() const { INLINE bool GraphicsStateGuardian:: get_alpha_scale_via_texture(const TextureAttrib *tex_attrib) const { return _alpha_scale_via_texture && - (tex_attrib == (const TextureAttrib *)NULL || + (tex_attrib == nullptr || tex_attrib->get_num_on_stages() < get_max_texture_stages()); } @@ -777,7 +777,7 @@ get_alpha_scale_via_texture(const TextureAttrib *tex_attrib) const { */ INLINE TextureStage *GraphicsStateGuardian:: get_alpha_scale_texture_stage() { - if (_alpha_scale_texture_stage == (TextureStage *)NULL) { + if (_alpha_scale_texture_stage == nullptr) { _alpha_scale_texture_stage = new TextureStage("alpha-scale"); _alpha_scale_texture_stage->set_sort(1000000000); } diff --git a/panda/src/display/graphicsStateGuardian.cxx b/panda/src/display/graphicsStateGuardian.cxx index 5f282b82ce..1050f8372f 100644 --- a/panda/src/display/graphicsStateGuardian.cxx +++ b/panda/src/display/graphicsStateGuardian.cxx @@ -63,6 +63,8 @@ #include #include +using std::string; + PStatCollector GraphicsStateGuardian::_vertex_buffer_switch_pcollector("Buffer switch:Vertex"); PStatCollector GraphicsStateGuardian::_index_buffer_switch_pcollector("Buffer switch:Index"); PStatCollector GraphicsStateGuardian::_shader_buffer_switch_pcollector("Buffer switch:Shader"); @@ -134,7 +136,7 @@ PStatCollector GraphicsStateGuardian::_draw_set_state_stencil_pcollector("Draw:S PStatCollector GraphicsStateGuardian::_draw_set_state_fog_pcollector("Draw:Set State:Fog"); PStatCollector GraphicsStateGuardian::_draw_set_state_scissor_pcollector("Draw:Set State:Scissor"); -PT(TextureStage) GraphicsStateGuardian::_alpha_scale_texture_stage = NULL; +PT(TextureStage) GraphicsStateGuardian::_alpha_scale_texture_stage = nullptr; TypeHandle GraphicsStateGuardian::_type_handle; @@ -158,17 +160,17 @@ GraphicsStateGuardian(CoordinateSystem internal_coordinate_system, set_coordinate_system(get_default_coordinate_system()); - _data_reader = (GeomVertexDataPipelineReader *)NULL; - _current_display_region = (DisplayRegion*)NULL; + _data_reader = nullptr; + _current_display_region = nullptr; _current_stereo_channel = Lens::SC_mono; _current_tex_view_offset = 0; - _current_lens = (Lens *)NULL; + _current_lens = nullptr; _projection_mat = TransformState::make_identity(); _projection_mat_inv = TransformState::make_identity(); _needs_reset = true; _is_valid = false; - _current_properties = NULL; + _current_properties = nullptr; _closing_gsg = false; _active = true; _prepared_objects = new PreparedGraphicsObjects; @@ -317,7 +319,7 @@ GraphicsStateGuardian:: */ GraphicsEngine *GraphicsStateGuardian:: get_engine() const { - nassertr(_engine != (GraphicsEngine *)NULL, GraphicsEngine::get_global_ptr()); + nassertr(_engine != nullptr, GraphicsEngine::get_global_ptr()); return _engine; } @@ -493,7 +495,7 @@ set_flash_texture(Texture *tex) { */ void GraphicsStateGuardian:: clear_flash_texture() { - _flash_texture = NULL; + _flash_texture = nullptr; } #endif // NDEBUG @@ -518,14 +520,14 @@ bool GraphicsStateGuardian:: set_scene(SceneSetup *scene_setup) { _scene_setup = scene_setup; _current_lens = scene_setup->get_lens(); - if (_current_lens == (Lens *)NULL) { + if (_current_lens == nullptr) { return false; } set_coordinate_system(_current_lens->get_coordinate_system()); _projection_mat = calc_projection_mat(_current_lens); - if (_projection_mat == 0) { + if (_projection_mat == nullptr) { return false; } _projection_mat_inv = _projection_mat->get_inverse(); @@ -551,8 +553,8 @@ get_scene() const { * call Texture::prepare(). */ TextureContext *GraphicsStateGuardian:: -prepare_texture(Texture *) { - return (TextureContext *)NULL; +prepare_texture(Texture *, int view) { + return nullptr; } /** @@ -603,7 +605,7 @@ extract_texture_data(Texture *) { */ SamplerContext *GraphicsStateGuardian:: prepare_sampler(const SamplerState &sampler) { - return (SamplerContext *)NULL; + return nullptr; } /** @@ -622,7 +624,7 @@ release_sampler(SamplerContext *) { */ GeomContext *GraphicsStateGuardian:: prepare_geom(Geom *) { - return (GeomContext *)NULL; + return nullptr; } /** @@ -641,7 +643,7 @@ release_geom(GeomContext *) { */ ShaderContext *GraphicsStateGuardian:: prepare_shader(Shader *shader) { - return (ShaderContext *)NULL; + return nullptr; } /** @@ -656,7 +658,7 @@ release_shader(ShaderContext *sc) { */ VertexBufferContext *GraphicsStateGuardian:: prepare_vertex_buffer(GeomVertexArrayData *) { - return (VertexBufferContext *)NULL; + return nullptr; } /** @@ -672,7 +674,7 @@ release_vertex_buffer(VertexBufferContext *) { */ IndexBufferContext *GraphicsStateGuardian:: prepare_index_buffer(GeomPrimitive *) { - return (IndexBufferContext *)NULL; + return nullptr; } /** @@ -688,7 +690,7 @@ release_index_buffer(IndexBufferContext *) { */ BufferContext *GraphicsStateGuardian:: prepare_shader_buffer(ShaderBuffer *) { - return (BufferContext *)NULL; + return nullptr; } /** @@ -712,7 +714,7 @@ release_shader_buffer(BufferContext *) { */ void GraphicsStateGuardian:: begin_occlusion_query() { - nassertv(_current_occlusion_query == (OcclusionQueryContext *)NULL); + nassertv(_current_occlusion_query == nullptr); } /** @@ -723,9 +725,9 @@ begin_occlusion_query() { */ PT(OcclusionQueryContext) GraphicsStateGuardian:: end_occlusion_query() { - nassertr(_current_occlusion_query != (OcclusionQueryContext *)NULL, NULL); + nassertr(_current_occlusion_query != nullptr, nullptr); PT(OcclusionQueryContext) result = _current_occlusion_query; - _current_occlusion_query = NULL; + _current_occlusion_query = nullptr; return result; } @@ -735,7 +737,7 @@ end_occlusion_query() { */ PT(TimerQueryContext) GraphicsStateGuardian:: issue_timer_query(int pstats_index) { - return NULL; + return nullptr; } /** @@ -761,7 +763,7 @@ get_geom_munger(const RenderState *state, Thread *current_thread) { // multiple times during a frame. Also, this might well be the only GSG // in the world anyway. int mi = state->_last_mi; - if (mi >= 0 && mi < mungers.get_num_entries() && mungers.get_key(mi) == _id) { + if (mi >= 0 && (size_t)mi < mungers.get_num_entries() && mungers.get_key(mi) == _id) { PT(GeomMunger) munger = mungers.get_data(mi); if (munger->is_registered()) { return munger; @@ -784,7 +786,7 @@ get_geom_munger(const RenderState *state, Thread *current_thread) { // Nothing in the map; create a new entry. PT(GeomMunger) munger = make_geom_munger(state, current_thread); - nassertr(munger != (GeomMunger *)NULL && munger->is_registered(), munger); + nassertr(munger != nullptr && munger->is_registered(), munger); nassertr(munger->is_of_type(StateMunger::get_class_type()), munger); state->_last_mi = mungers.store(_id, munger); @@ -800,7 +802,7 @@ make_geom_munger(const RenderState *state, Thread *current_thread) { // The default implementation returns no munger at all, but presumably, // every kind of GSG needs some special munging action, so real GSG's will // override this to return something more useful. - return NULL; + return nullptr; } /** @@ -940,7 +942,7 @@ fetch_specified_part(Shader::ShaderMatInput part, InternalName *name, } case Shader::SMO_texpad_x: { Texture *tex = _target_shader->get_shader_input_texture(name); - nassertr(tex != 0, &LMatrix4::zeros_mat()); + nassertr(tex != nullptr, &LMatrix4::zeros_mat()); int sx = tex->get_x_size() - tex->get_pad_x_size(); int sy = tex->get_y_size() - tex->get_pad_y_size(); int sz = tex->get_z_size() - tex->get_pad_z_size(); @@ -952,7 +954,7 @@ fetch_specified_part(Shader::ShaderMatInput part, InternalName *name, } case Shader::SMO_texpix_x: { Texture *tex = _target_shader->get_shader_input_texture(name); - nassertr(tex != 0, &LMatrix4::zeros_mat()); + nassertr(tex != nullptr, &LMatrix4::zeros_mat()); double px = 1.0 / tex->get_x_size(); double py = 1.0 / tex->get_y_size(); double pz = 1.0 / tex->get_z_size(); @@ -1015,7 +1017,7 @@ fetch_specified_part(Shader::ShaderMatInput part, InternalName *name, const FogAttrib *target_fog = (const FogAttrib *) _target_rs->get_attrib_def(FogAttrib::get_class_slot()); Fog *fog = target_fog->get_fog(); - if (fog == (Fog*) NULL) { + if (fog == nullptr) { return &LMatrix4::ones_mat(); } PN_stdfloat start, end; @@ -1027,7 +1029,7 @@ fetch_specified_part(Shader::ShaderMatInput part, InternalName *name, const FogAttrib *target_fog = (const FogAttrib *) _target_rs->get_attrib_def(FogAttrib::get_class_slot()); Fog *fog = target_fog->get_fog(); - if (fog == (Fog*) NULL) { + if (fog == nullptr) { return &LMatrix4::ones_mat(); } LVecBase4 c = fog->get_color(); @@ -1095,7 +1097,7 @@ fetch_specified_part(Shader::ShaderMatInput part, InternalName *name, Spotlight *lt; DCAST_INTO_R(lt, np.node(), &LMatrix4::zeros_mat()); Lens *lens = lt->get_lens(); - nassertr(lens != (Lens *)NULL, &LMatrix4::zeros_mat()); + nassertr(lens != nullptr, &LMatrix4::zeros_mat()); LColor const &c = lt->get_color(); LColor const &s = lt->get_specular_color(); PN_stdfloat cutoff = ccos(deg_2_rad(lens->get_hfov() * 0.5f)); @@ -1517,28 +1519,28 @@ fetch_specified_member(const NodePath &np, CPT_InternalName attrib, LMatrix4 &t) static const CPT_InternalName IN_quadraticAttenuation("quadraticAttenuation"); static const CPT_InternalName IN_shadowViewMatrix("shadowViewMatrix"); - PandaNode *node = NULL; + PandaNode *node = nullptr; if (!np.is_empty()) { node = np.node(); } if (attrib == IN_color) { - if (node == (PandaNode *)NULL) { + if (node == nullptr) { return &LMatrix4::ident_mat(); } Light *light = node->as_light(); - nassertr(light != (Light *)NULL, &LMatrix4::ident_mat()); + nassertr(light != nullptr, &LMatrix4::ident_mat()); LColor c = light->get_color(); c.componentwise_mult(_light_color_scale); t.set_row(3, c); return &t; } else if (attrib == IN_ambient) { - if (node == (PandaNode *)NULL) { + if (node == nullptr) { return &LMatrix4::ident_mat(); } Light *light = node->as_light(); - nassertr(light != (Light *)NULL, &LMatrix4::ident_mat()); + nassertr(light != nullptr, &LMatrix4::ident_mat()); if (node->is_ambient_light()) { LColor c = light->get_color(); c.componentwise_mult(_light_color_scale); @@ -1550,11 +1552,11 @@ fetch_specified_member(const NodePath &np, CPT_InternalName attrib, LMatrix4 &t) return &t; } else if (attrib == IN_diffuse) { - if (node == (PandaNode *)NULL) { + if (node == nullptr) { return &LMatrix4::ident_mat(); } Light *light = node->as_light(); - nassertr(light != (Light *)NULL, &LMatrix4::ones_mat()); + nassertr(light != nullptr, &LMatrix4::ones_mat()); if (node->is_ambient_light()) { // Ambient light has no diffuse color. t.set_row(3, LColor(0.0f, 0.0f, 0.0f, 1.0f)); @@ -1566,11 +1568,11 @@ fetch_specified_member(const NodePath &np, CPT_InternalName attrib, LMatrix4 &t) return &t; } else if (attrib == IN_specular) { - if (node == (PandaNode *)NULL) { + if (node == nullptr) { return &LMatrix4::ident_mat(); } Light *light = node->as_light(); - nassertr(light != (Light *)NULL, &LMatrix4::ones_mat()); + nassertr(light != nullptr, &LMatrix4::ones_mat()); t.set_row(3, light->get_specular_color()); return &t; @@ -1595,7 +1597,7 @@ fetch_specified_member(const NodePath &np, CPT_InternalName attrib, LMatrix4 &t) LightLensNode *light; DCAST_INTO_R(light, node, &LMatrix4::ident_mat()); Lens *lens = light->get_lens(); - nassertr(lens != (Lens *)NULL, &LMatrix4::ident_mat()); + nassertr(lens != nullptr, &LMatrix4::ident_mat()); CPT(TransformState) transform = _scene_setup->get_cs_world_transform()->compose( @@ -1631,7 +1633,7 @@ fetch_specified_member(const NodePath &np, CPT_InternalName attrib, LMatrix4 &t) LightLensNode *light; DCAST_INTO_R(light, node, &LMatrix4::ident_mat()); Lens *lens = light->get_lens(); - nassertr(lens != (Lens *)NULL, &LMatrix4::ident_mat()); + nassertr(lens != nullptr, &LMatrix4::ident_mat()); CPT(TransformState) transform = _scene_setup->get_cs_world_transform()->compose( @@ -1647,7 +1649,7 @@ fetch_specified_member(const NodePath &np, CPT_InternalName attrib, LMatrix4 &t) } } else if (attrib == IN_spotDirection) { - if (node == (PandaNode *)NULL) { + if (node == nullptr) { t.set_row(3, LVector3(0.0f, 0.0f, -1.0f)); return &t; } else if (node->is_ambient_light()) { @@ -1658,7 +1660,7 @@ fetch_specified_member(const NodePath &np, CPT_InternalName attrib, LMatrix4 &t) LightLensNode *light; DCAST_INTO_R(light, node, &LMatrix4::ident_mat()); Lens *lens = light->get_lens(); - nassertr(lens != (Lens *)NULL, &LMatrix4::ident_mat()); + nassertr(lens != nullptr, &LMatrix4::ident_mat()); CPT(TransformState) transform = _scene_setup->get_cs_world_transform()->compose( @@ -1671,12 +1673,12 @@ fetch_specified_member(const NodePath &np, CPT_InternalName attrib, LMatrix4 &t) } } else if (attrib == IN_spotCutoff) { - if (node != (PandaNode *)NULL && + if (node != nullptr && node->is_of_type(Spotlight::get_class_type())) { LightLensNode *light; DCAST_INTO_R(light, node, &LMatrix4::ident_mat()); Lens *lens = light->get_lens(); - nassertr(lens != (Lens *)NULL, &LMatrix4::ident_mat()); + nassertr(lens != nullptr, &LMatrix4::ident_mat()); float cutoff = lens->get_hfov() * 0.5f; t.set_row(3, LVecBase4(cutoff)); @@ -1688,12 +1690,12 @@ fetch_specified_member(const NodePath &np, CPT_InternalName attrib, LMatrix4 &t) } } else if (attrib == IN_spotCosCutoff) { - if (node != (PandaNode *)NULL && + if (node != nullptr && node->is_of_type(Spotlight::get_class_type())) { LightLensNode *light; DCAST_INTO_R(light, node, &LMatrix4::ident_mat()); Lens *lens = light->get_lens(); - nassertr(lens != (Lens *)NULL, &LMatrix4::ident_mat()); + nassertr(lens != nullptr, &LMatrix4::ident_mat()); float cutoff = lens->get_hfov() * 0.5f; t.set_row(3, LVecBase4(ccos(deg_2_rad(cutoff)))); @@ -1705,19 +1707,19 @@ fetch_specified_member(const NodePath &np, CPT_InternalName attrib, LMatrix4 &t) } } else if (attrib == IN_spotExponent) { - if (node == (PandaNode *)NULL) { + if (node == nullptr) { return &LMatrix4::zeros_mat(); } Light *light = node->as_light(); - nassertr(light != (Light *)NULL, &LMatrix4::ident_mat()); + nassertr(light != nullptr, &LMatrix4::ident_mat()); t.set_row(3, LVecBase4(light->get_exponent())); return &t; } else if (attrib == IN_attenuation) { - if (node != (PandaNode *)NULL) { + if (node != nullptr) { Light *light = node->as_light(); - nassertr(light != (Light *)NULL, &LMatrix4::ones_mat()); + nassertr(light != nullptr, &LMatrix4::ones_mat()); t.set_row(3, LVecBase4(light->get_attenuation(), 0)); } else { @@ -1726,31 +1728,31 @@ fetch_specified_member(const NodePath &np, CPT_InternalName attrib, LMatrix4 &t) return &t; } else if (attrib == IN_constantAttenuation) { - if (node == (PandaNode *)NULL) { + if (node == nullptr) { return &LMatrix4::ones_mat(); } Light *light = node->as_light(); - nassertr(light != (Light *)NULL, &LMatrix4::ones_mat()); + nassertr(light != nullptr, &LMatrix4::ones_mat()); t.set_row(3, LVecBase4(light->get_attenuation()[0])); return &t; } else if (attrib == IN_linearAttenuation) { - if (node == (PandaNode *)NULL) { + if (node == nullptr) { return &LMatrix4::zeros_mat(); } Light *light = node->as_light(); - nassertr(light != (Light *)NULL, &LMatrix4::ident_mat()); + nassertr(light != nullptr, &LMatrix4::ident_mat()); t.set_row(3, LVecBase4(light->get_attenuation()[1])); return &t; } else if (attrib == IN_quadraticAttenuation) { - if (node == (PandaNode *)NULL) { + if (node == nullptr) { return &LMatrix4::zeros_mat(); } Light *light = node->as_light(); - nassertr(light != (Light *)NULL, &LMatrix4::ident_mat()); + nassertr(light != nullptr, &LMatrix4::ident_mat()); t.set_row(3, LVecBase4(light->get_attenuation()[2])); return &t; @@ -1761,7 +1763,7 @@ fetch_specified_member(const NodePath &np, CPT_InternalName attrib, LMatrix4 &t) 0.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f); - if (node == (PandaNode *)NULL) { + if (node == nullptr) { return &biasmat; } @@ -1808,7 +1810,7 @@ fetch_specified_texture(Shader::ShaderTexSpec &spec, SamplerState &sampler, if (basename == "shadowMap") { PT(Texture) tex = get_shadow_map(np); - if (tex != (Texture *)NULL) { + if (tex != nullptr) { sampler = tex->get_default_sampler(); } return tex; @@ -1884,11 +1886,11 @@ fetch_specified_texture(Shader::ShaderTexSpec &spec, SamplerState &sampler, break; default: - nassertr(false, NULL); + nassertr(false, nullptr); break; } - return NULL; + return nullptr; } /** @@ -1983,7 +1985,7 @@ clear_state_and_transform() { */ void GraphicsStateGuardian:: remove_window(GraphicsOutputBase *window) { - nassertv(_engine != (GraphicsEngine *)NULL); + nassertv(_engine != nullptr); GraphicsOutput *win; DCAST_INTO_V(win, window); _engine->remove_window(win); @@ -2009,12 +2011,12 @@ prepare_lens() { */ CPT(TransformState) GraphicsStateGuardian:: calc_projection_mat(const Lens *lens) { - if (lens == (Lens *)NULL) { - return NULL; + if (lens == nullptr) { + return nullptr; } if (!lens->is_linear()) { - return NULL; + return nullptr; } return TransformState::make_identity(); @@ -2194,7 +2196,7 @@ flush_timer_queries() { if (_last_num_queried > 0) { // We know how many queries were available last frame, and this usually // stays fairly constant, so use this as a starting point. - int i = min(_last_num_queried, count) - 1; + int i = std::min(_last_num_queried, count) - 1; if (_pending_timer_queries[i]->is_answer_ready()) { first = count; @@ -2295,7 +2297,7 @@ CPT(RenderState) GraphicsStateGuardian:: begin_decal_base_first() { // Turn off writing the depth buffer to render the base geometry. static CPT(RenderState) decal_base_first; - if (decal_base_first == (const RenderState *)NULL) { + if (decal_base_first == nullptr) { decal_base_first = RenderState::make (DepthWriteAttrib::make(DepthWriteAttrib::M_off), RenderState::get_max_priority()); @@ -2314,7 +2316,7 @@ begin_decal_nested() { // We should keep the depth buffer off during this operation, so that decals // on decals will render properly. static CPT(RenderState) decal_nested; - if (decal_nested == (const RenderState *)NULL) { + if (decal_nested == nullptr) { decal_nested = RenderState::make (DepthWriteAttrib::make(DepthWriteAttrib::M_off), RenderState::get_max_priority()); @@ -2338,7 +2340,7 @@ begin_decal_base_second() { // buffer to render the base geometry after the second pass. Also, turn off // texturing since there's no need for it now. static CPT(RenderState) decal_base_second; - if (decal_base_second == (const RenderState *)NULL) { + if (decal_base_second == nullptr) { decal_base_second = RenderState::make (ColorWriteAttrib::make(ColorWriteAttrib::C_off), // On reflection, we need to leave texturing on so the alpha test @@ -2469,7 +2471,7 @@ draw_points(const GeomPrimitivePipelineReader *, bool) { */ void GraphicsStateGuardian:: end_draw_primitives() { - _data_reader = NULL; + _data_reader = nullptr; } /** @@ -2481,7 +2483,7 @@ reset() { _is_valid = false; _state_rs = RenderState::make_empty(); - _target_rs = NULL; + _target_rs = nullptr; _state_mask.clear(); _internal_transform = _cs_transform; _scene_null = new SceneSetup; @@ -2597,7 +2599,7 @@ do_issue_clip_plane() { const ClipPlaneAttrib *target_clip_plane = (const ClipPlaneAttrib *) _target_rs->get_attrib_def(ClipPlaneAttrib::get_class_slot()); - if (target_clip_plane != (ClipPlaneAttrib *)NULL) { + if (target_clip_plane != nullptr) { CPT(ClipPlaneAttrib) new_plane = target_clip_plane->filter_to_max(_max_clip_planes); num_on_planes = new_plane->get_num_on_planes(); @@ -2763,7 +2765,7 @@ do_issue_light() { // LightAttrib guarantees that the on lights are sorted, and that // non-ambient lights come before ambient lights. any_on_lights = target_light->has_any_on_light(); - size_t filtered_lights = min((size_t)_max_lights, target_light->get_num_non_ambient_lights()); + size_t filtered_lights = std::min((size_t)_max_lights, target_light->get_num_non_ambient_lights()); for (size_t li = 0; li < filtered_lights; ++li) { NodePath light = target_light->get_on_light(li); nassertv(!light.is_empty()); @@ -3053,8 +3055,8 @@ determine_target_texture() { const TexGenAttrib *target_tex_gen = (const TexGenAttrib *) _target_rs->get_attrib_def(TexGenAttrib::get_class_slot()); - nassertv(target_texture != (TextureAttrib *)NULL && - target_tex_gen != (TexGenAttrib *)NULL); + nassertv(target_texture != nullptr && + target_tex_gen != nullptr); _target_texture = target_texture; _target_tex_gen = target_tex_gen; @@ -3182,8 +3184,8 @@ determine_light_color_scale() { */ CPT(RenderState) GraphicsStateGuardian:: get_unlit_state() { - static CPT(RenderState) state = NULL; - if (state == (const RenderState *)NULL) { + static CPT(RenderState) state = nullptr; + if (state == nullptr) { state = RenderState::make(LightAttrib::make_all_off()); } return state; @@ -3194,8 +3196,8 @@ get_unlit_state() { */ CPT(RenderState) GraphicsStateGuardian:: get_unclipped_state() { - static CPT(RenderState) state = NULL; - if (state == (const RenderState *)NULL) { + static CPT(RenderState) state = nullptr; + if (state == nullptr) { state = RenderState::make(ClipPlaneAttrib::make_all_off()); } return state; @@ -3206,8 +3208,8 @@ get_unclipped_state() { */ CPT(RenderState) GraphicsStateGuardian:: get_untextured_state() { - static CPT(RenderState) state = NULL; - if (state == (const RenderState *)NULL) { + static CPT(RenderState) state = nullptr; + if (state == nullptr) { state = RenderState::make(TextureAttrib::make_off()); } return state; @@ -3241,7 +3243,7 @@ async_reload_texture(TextureContext *tc) { ((TextureReloadRequest *)task)->get_texture() == tc->get_texture()) { // This texture is already queued to be reloaded. Don't queue it again, // just make sure the priority is updated, and return. - task->set_priority(max(task->get_priority(), priority)); + task->set_priority(std::max(task->get_priority(), priority)); return (AsyncFuture *)task; } } @@ -3498,8 +3500,8 @@ get_driver_shader_version_minor() { return -1; } -ostream & -operator << (ostream &out, GraphicsStateGuardian::ShaderModel sm) { +std::ostream & +operator << (std::ostream &out, GraphicsStateGuardian::ShaderModel sm) { static const char *sm_strings[] = {"none", "1.1", "2.0", "2.x", "3.0", "4.0", "5.0", "5.1"}; nassertr(sm >= 0 && sm <= GraphicsStateGuardian::SM_51, out); out << sm_strings[sm]; diff --git a/panda/src/display/graphicsStateGuardian.h b/panda/src/display/graphicsStateGuardian.h index e508be9c6a..c64bbe692a 100644 --- a/panda/src/display/graphicsStateGuardian.h +++ b/panda/src/display/graphicsStateGuardian.h @@ -228,7 +228,7 @@ PUBLISHED: MAKE_PROPERTY(shader_model, get_shader_model, set_shader_model); virtual int get_supported_geom_rendering() const; - virtual bool get_supports_cg_profile(const string &name) const; + virtual bool get_supports_cg_profile(const std::string &name) const; INLINE bool get_color_scale_via_lighting() const; INLINE bool get_alpha_scale_via_texture() const; @@ -267,11 +267,11 @@ PUBLISHED: #endif PUBLISHED: - virtual bool has_extension(const string &extension) const; + virtual bool has_extension(const std::string &extension) const; - virtual string get_driver_vendor(); - virtual string get_driver_renderer(); - virtual string get_driver_version(); + virtual std::string get_driver_vendor(); + virtual std::string get_driver_renderer(); + virtual std::string get_driver_version(); virtual int get_driver_version_major(); virtual int get_driver_version_minor(); virtual int get_driver_shader_version_major(); @@ -286,11 +286,11 @@ PUBLISHED: MAKE_PROPERTY(driver_shader_version_minor, get_driver_shader_version_minor); bool set_scene(SceneSetup *scene_setup); - virtual SceneSetup *get_scene() const FINAL; + virtual SceneSetup *get_scene() const final; MAKE_PROPERTY(scene, get_scene, set_scene); public: - virtual TextureContext *prepare_texture(Texture *tex); + virtual TextureContext *prepare_texture(Texture *tex, int view); virtual bool update_texture(TextureContext *tc, bool force); virtual void release_texture(TextureContext *tc); virtual bool extract_texture_data(Texture *tex); @@ -430,7 +430,7 @@ public: static void create_gamma_table (PN_stdfloat gamma, unsigned short *red_table, unsigned short *green_table, unsigned short *blue_table); - PT(Texture) get_shadow_map(const NodePath &light_np, GraphicsOutputBase *host=NULL); + PT(Texture) get_shadow_map(const NodePath &light_np, GraphicsOutputBase *host=nullptr); PT(Texture) get_dummy_shadow_map(Texture::TextureType texture_type) const; virtual GraphicsOutput *make_shadow_buffer(LightLensNode *light, Texture *tex, GraphicsOutput *host); @@ -760,7 +760,7 @@ private: friend class GraphicsEngine; }; -EXPCL_PANDA_DISPLAY ostream &operator << (ostream &out, GraphicsStateGuardian::ShaderModel sm); +EXPCL_PANDA_DISPLAY std::ostream &operator << (std::ostream &out, GraphicsStateGuardian::ShaderModel sm); #include "graphicsStateGuardian.I" diff --git a/panda/src/display/graphicsStateGuardian_ext.cxx b/panda/src/display/graphicsStateGuardian_ext.cxx index 0677741ac7..3738ef82b8 100644 --- a/panda/src/display/graphicsStateGuardian_ext.cxx +++ b/panda/src/display/graphicsStateGuardian_ext.cxx @@ -41,8 +41,8 @@ PyObject *Extension:: get_prepared_textures() const { PyObject *list = PyList_New(0); - if (list == NULL) { - return NULL; + if (list == nullptr) { + return nullptr; } _this->traverse_prepared_textures(&traverse_callback, (void *)list); diff --git a/panda/src/display/graphicsThreadingModel.I b/panda/src/display/graphicsThreadingModel.I index bfd0161518..98707b16cb 100644 --- a/panda/src/display/graphicsThreadingModel.I +++ b/panda/src/display/graphicsThreadingModel.I @@ -39,7 +39,7 @@ operator = (const GraphicsThreadingModel ©) { /** * Returns the name of the thread that will handle culling in this model. */ -INLINE const string &GraphicsThreadingModel:: +INLINE const std::string &GraphicsThreadingModel:: get_cull_name() const { return _cull_name; } @@ -50,7 +50,7 @@ get_cull_name() const { * this only has an effect on newly-opened windows. */ INLINE void GraphicsThreadingModel:: -set_cull_name(const string &cull_name) { +set_cull_name(const std::string &cull_name) { _cull_name = cull_name; update_stages(); } @@ -69,7 +69,7 @@ get_cull_stage() const { * Returns the name of the thread that will handle sending the actual graphics * primitives to the graphics API in this model. */ -INLINE const string &GraphicsThreadingModel:: +INLINE const std::string &GraphicsThreadingModel:: get_draw_name() const { return _draw_name; } @@ -80,7 +80,7 @@ get_draw_name() const { * this only has an effect on newly-opened windows. */ INLINE void GraphicsThreadingModel:: -set_draw_name(const string &draw_name) { +set_draw_name(const std::string &draw_name) { _draw_name = draw_name; update_stages(); } @@ -140,12 +140,12 @@ is_default() const { * */ INLINE void GraphicsThreadingModel:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_model(); } -INLINE ostream & -operator << (ostream &out, const GraphicsThreadingModel &threading_model) { +INLINE std::ostream & +operator << (std::ostream &out, const GraphicsThreadingModel &threading_model) { threading_model.output(out); return out; } diff --git a/panda/src/display/graphicsThreadingModel.cxx b/panda/src/display/graphicsThreadingModel.cxx index 113352ecba..22357206da 100644 --- a/panda/src/display/graphicsThreadingModel.cxx +++ b/panda/src/display/graphicsThreadingModel.cxx @@ -13,6 +13,8 @@ #include "graphicsThreadingModel.h" +using std::string; + /** * The threading model accepts a string representing the names of the two * threads that will process cull and draw for the given window, separated by diff --git a/panda/src/display/graphicsThreadingModel.h b/panda/src/display/graphicsThreadingModel.h index 7d189250df..7f0cf519af 100644 --- a/panda/src/display/graphicsThreadingModel.h +++ b/panda/src/display/graphicsThreadingModel.h @@ -22,17 +22,17 @@ */ class EXPCL_PANDA_DISPLAY GraphicsThreadingModel { PUBLISHED: - GraphicsThreadingModel(const string &model = string()); + GraphicsThreadingModel(const std::string &model = std::string()); INLINE GraphicsThreadingModel(const GraphicsThreadingModel ©); INLINE void operator = (const GraphicsThreadingModel ©); - string get_model() const; - INLINE const string &get_cull_name() const; - INLINE void set_cull_name(const string &cull_name); + std::string get_model() const; + INLINE const std::string &get_cull_name() const; + INLINE void set_cull_name(const std::string &cull_name); INLINE int get_cull_stage() const; - INLINE const string &get_draw_name() const; - INLINE void set_draw_name(const string &cull_name); + INLINE const std::string &get_draw_name() const; + INLINE void set_draw_name(const std::string &cull_name); INLINE int get_draw_stage() const; INLINE bool get_cull_sorting() const; @@ -40,20 +40,20 @@ PUBLISHED: INLINE bool is_single_threaded() const; INLINE bool is_default() const; - INLINE void output(ostream &out) const; + INLINE void output(std::ostream &out) const; private: void update_stages(); private: - string _cull_name; + std::string _cull_name; int _cull_stage; - string _draw_name; + std::string _draw_name; int _draw_stage; bool _cull_sorting; }; -INLINE ostream &operator << (ostream &out, const GraphicsThreadingModel &threading_model); +INLINE std::ostream &operator << (std::ostream &out, const GraphicsThreadingModel &threading_model); #include "graphicsThreadingModel.I" diff --git a/panda/src/display/graphicsWindow.cxx b/panda/src/display/graphicsWindow.cxx index 88ee617f40..8d618f3d9b 100644 --- a/panda/src/display/graphicsWindow.cxx +++ b/panda/src/display/graphicsWindow.cxx @@ -21,6 +21,8 @@ #include "throw_event.h" #include "string_utils.h" +using std::string; + TypeHandle GraphicsWindow::_type_handle; /** @@ -294,7 +296,7 @@ has_keyboard(int device) const { */ ButtonMap *GraphicsWindow:: get_keyboard_map() const { - return NULL; + return nullptr; } /** @@ -432,8 +434,8 @@ get_pointer_events(int device) { PT(PointerEventList) result; { LightMutexHolder holder(_input_lock); - nassertr(device >= 0 && device < (int)_input_devices.size(), NULL); - nassertr(_input_devices[device].has_pointer_event(), NULL); + nassertr(device >= 0 && device < (int)_input_devices.size(), nullptr); + nassertr(_input_devices[device].has_pointer_event(), nullptr); result = _input_devices[device].get_pointer_events(); } return result; @@ -648,13 +650,13 @@ close_window() { << "Closing " << get_type() << "\n"; // Tell our parent window (if any) that we're no longer its child. - if (_window_handle != (WindowHandle *)NULL && - _parent_window_handle != (WindowHandle *)NULL) { + if (_window_handle != nullptr && + _parent_window_handle != nullptr) { _parent_window_handle->detach_child(_window_handle); } - _window_handle = NULL; - _parent_window_handle = NULL; + _window_handle = nullptr; + _parent_window_handle = nullptr; _is_valid = false; } diff --git a/panda/src/display/graphicsWindow.h b/panda/src/display/graphicsWindow.h index 86986f52c4..c9c9900d3e 100644 --- a/panda/src/display/graphicsWindow.h +++ b/panda/src/display/graphicsWindow.h @@ -41,7 +41,7 @@ class EXPCL_PANDA_DISPLAY GraphicsWindow : public GraphicsOutput { protected: GraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -65,12 +65,12 @@ PUBLISHED: MAKE_PROPERTY(rejected_properties, get_rejected_properties); MAKE_PROPERTY(closed, is_closed); - void set_window_event(const string &window_event); - string get_window_event() const; + void set_window_event(const std::string &window_event); + std::string get_window_event() const; MAKE_PROPERTY(window_event, get_window_event, set_window_event); - void set_close_request_event(const string &close_request_event); - string get_close_request_event() const; + void set_close_request_event(const std::string &close_request_event); + std::string get_close_request_event() const; MAKE_PROPERTY(close_request_event, get_close_request_event, set_close_request_event); INLINE void set_unexposed_draw(bool unexposed_draw); @@ -82,7 +82,7 @@ PUBLISHED: // Mouse and keyboard routines int get_num_input_devices() const; - string get_input_device_name(int device) const; + std::string get_input_device_name(int device) const; MAKE_SEQ(get_input_device_names, get_num_input_devices, get_input_device_name); bool has_pointer(int device) const; bool has_keyboard(int device) const; @@ -93,7 +93,7 @@ PUBLISHED: void enable_pointer_mode(int device, double speed); void disable_pointer_mode(int device); - MouseData get_pointer(int device) const; + virtual MouseData get_pointer(int device) const; virtual bool move_pointer(int device, int x, int y); virtual void close_ime(); @@ -161,8 +161,8 @@ private: WindowProperties _requested_properties; WindowProperties _rejected_properties; - string _window_event; - string _close_request_event; + std::string _window_event; + std::string _close_request_event; bool _unexposed_draw; #ifdef HAVE_PYTHON diff --git a/panda/src/display/graphicsWindowInputDevice.I b/panda/src/display/graphicsWindowInputDevice.I index 2d69d042d9..446dca6ab6 100644 --- a/panda/src/display/graphicsWindowInputDevice.I +++ b/panda/src/display/graphicsWindowInputDevice.I @@ -23,7 +23,7 @@ GraphicsWindowInputDevice() { /** * */ -INLINE string GraphicsWindowInputDevice:: +INLINE std::string GraphicsWindowInputDevice:: get_name() const { LightMutexHolder holder(_lock); return _name; diff --git a/panda/src/display/graphicsWindowInputDevice.cxx b/panda/src/display/graphicsWindowInputDevice.cxx index 89d6e9d5b4..377f3986e4 100644 --- a/panda/src/display/graphicsWindowInputDevice.cxx +++ b/panda/src/display/graphicsWindowInputDevice.cxx @@ -23,6 +23,8 @@ #include "vector_src.cxx" +using std::string; + /** * Defines a new InputDevice for the window. Most windows will have exactly * one InputDevice: a keyboard/mouse pair. Some may also add joystick data, @@ -141,7 +143,7 @@ get_button_event() { bool GraphicsWindowInputDevice:: has_pointer_event() const { LightMutexHolder holder(_lock); - return (_pointer_events != 0); + return (_pointer_events != nullptr); } /** @@ -151,7 +153,7 @@ PT(PointerEventList) GraphicsWindowInputDevice:: get_pointer_events() { LightMutexHolder holder(_lock); PT(PointerEventList) result = _pointer_events; - _pointer_events = 0; + _pointer_events = nullptr; return result; } @@ -224,7 +226,7 @@ set_pointer(bool inwin, double x, double y, double time) { if (_enable_pointer_events) { int seq = _event_sequence++; - if (_pointer_events == 0) { + if (_pointer_events == nullptr) { _pointer_events = new PointerEventList(); } _pointer_events->add_event(_mouse_data._in_window, @@ -281,7 +283,7 @@ keystroke(int keycode, double time) { * especially Chinese/Japanese/Korean. */ void GraphicsWindowInputDevice:: -candidate(const wstring &candidate_string, size_t highlight_start, +candidate(const std::wstring &candidate_string, size_t highlight_start, size_t highlight_end, size_t cursor_pos) { LightMutexHolder holder(_lock); _button_events.push_back(ButtonEvent(candidate_string, diff --git a/panda/src/display/graphicsWindowInputDevice.h b/panda/src/display/graphicsWindowInputDevice.h index 5cdff54f29..b570b5f384 100644 --- a/panda/src/display/graphicsWindowInputDevice.h +++ b/panda/src/display/graphicsWindowInputDevice.h @@ -38,19 +38,19 @@ class GraphicsWindow; */ class EXPCL_PANDA_DISPLAY GraphicsWindowInputDevice { private: - GraphicsWindowInputDevice(GraphicsWindow *host, const string &name, int flags); + GraphicsWindowInputDevice(GraphicsWindow *host, const std::string &name, int flags); public: - static GraphicsWindowInputDevice pointer_only(GraphicsWindow *host, const string &name); - static GraphicsWindowInputDevice keyboard_only(GraphicsWindow *host, const string &name); - static GraphicsWindowInputDevice pointer_and_keyboard(GraphicsWindow *host, const string &name); + static GraphicsWindowInputDevice pointer_only(GraphicsWindow *host, const std::string &name); + static GraphicsWindowInputDevice keyboard_only(GraphicsWindow *host, const std::string &name); + static GraphicsWindowInputDevice pointer_and_keyboard(GraphicsWindow *host, const std::string &name); INLINE GraphicsWindowInputDevice(); GraphicsWindowInputDevice(const GraphicsWindowInputDevice ©); void operator = (const GraphicsWindowInputDevice ©); ~GraphicsWindowInputDevice(); - INLINE string get_name() const; + INLINE std::string get_name() const; INLINE bool has_pointer() const; INLINE bool has_keyboard() const; @@ -87,7 +87,7 @@ PUBLISHED: void button_resume_down(ButtonHandle button, double time); void button_up(ButtonHandle button, double time); void keystroke(int keycode, double time); - void candidate(const wstring &candidate_string, size_t highlight_start, + void candidate(const std::wstring &candidate_string, size_t highlight_start, size_t highlight_end, size_t cursor_pos); void focus_lost(double time); void raw_button_down(ButtonHandle button, double time); @@ -115,7 +115,7 @@ private: GraphicsWindow *_host; - string _name; + std::string _name; int _flags; int _device_index; int _event_sequence; diff --git a/panda/src/display/graphicsWindowProcCallbackData.cxx b/panda/src/display/graphicsWindowProcCallbackData.cxx index 8bf1da03af..82e57ef382 100644 --- a/panda/src/display/graphicsWindowProcCallbackData.cxx +++ b/panda/src/display/graphicsWindowProcCallbackData.cxx @@ -20,7 +20,7 @@ TypeHandle GraphicsWindowProcCallbackData::_type_handle; * */ void GraphicsWindowProcCallbackData:: -output(ostream &out) const { +output(std::ostream &out) const { #ifdef WIN32 out << get_type() << "(" << (void*)_graphicsWindow << ", " << _hwnd << ", " << _msg << ", " << _wparam << ", " << _lparam << ")"; diff --git a/panda/src/display/graphicsWindowProcCallbackData.h b/panda/src/display/graphicsWindowProcCallbackData.h index d417a3595e..23ae66d9c7 100644 --- a/panda/src/display/graphicsWindowProcCallbackData.h +++ b/panda/src/display/graphicsWindowProcCallbackData.h @@ -39,7 +39,7 @@ public: #endif PUBLISHED: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; #ifdef WIN32 INLINE uintptr_t get_hwnd() const; diff --git a/panda/src/display/graphicsWindow_ext.cxx b/panda/src/display/graphicsWindow_ext.cxx index 06260b4c83..ac06b3565a 100644 --- a/panda/src/display/graphicsWindow_ext.cxx +++ b/panda/src/display/graphicsWindow_ext.cxx @@ -30,7 +30,7 @@ add_python_event_handler(PyObject* handler, PyObject* name){ */ void Extension:: remove_python_event_handler(PyObject* name){ - list toRemove; + std::list toRemove; GraphicsWindow::PythonWinProcClasses::iterator iter; for (iter = _this->_python_window_proc_classes.begin(); iter != _this->_python_window_proc_classes.end(); ++iter) { PythonGraphicsWindowProc* pgwp = (PythonGraphicsWindowProc*)*iter; @@ -43,7 +43,7 @@ remove_python_event_handler(PyObject* name){ } #endif } - list::iterator iter2; + std::list::iterator iter2; for (iter2 = toRemove.begin(); iter2 != toRemove.end(); ++iter2) { PythonGraphicsWindowProc* pgwp = *iter2; _this->remove_window_proc(pgwp); diff --git a/panda/src/display/nativeWindowHandle.cxx b/panda/src/display/nativeWindowHandle.cxx index 7616471172..2ae1973a6f 100644 --- a/panda/src/display/nativeWindowHandle.cxx +++ b/panda/src/display/nativeWindowHandle.cxx @@ -13,6 +13,8 @@ #include "nativeWindowHandle.h" +using std::ostream; + TypeHandle NativeWindowHandle::_type_handle; TypeHandle NativeWindowHandle::IntHandle::_type_handle; TypeHandle NativeWindowHandle::SubprocessHandle::_type_handle; diff --git a/panda/src/display/nativeWindowHandle.h b/panda/src/display/nativeWindowHandle.h index da6096533a..14bab98815 100644 --- a/panda/src/display/nativeWindowHandle.h +++ b/panda/src/display/nativeWindowHandle.h @@ -33,7 +33,7 @@ * This class exists for name scoping only. Don't use the constructor * directly; use one of the make_* methods. */ -class EXPCL_PANDA_DISPLAY NativeWindowHandle : public WindowHandle { +class EXPCL_PANDA_DISPLAY NativeWindowHandle final : public WindowHandle { private: INLINE NativeWindowHandle(); INLINE NativeWindowHandle(const NativeWindowHandle ©); @@ -56,7 +56,7 @@ public: public: INLINE IntHandle(size_t handle); virtual size_t get_int_handle() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; INLINE size_t get_handle() const; @@ -84,7 +84,7 @@ public: class EXPCL_PANDA_DISPLAY SubprocessHandle : public OSHandle { public: INLINE SubprocessHandle(const Filename &filename); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; INLINE const Filename &get_filename() const; @@ -114,7 +114,7 @@ public: public: INLINE X11Handle(X11_Window handle); virtual size_t get_int_handle() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; INLINE X11_Window get_handle() const; @@ -146,7 +146,7 @@ public: public: INLINE WinHandle(HWND handle); virtual size_t get_int_handle() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; INLINE HWND get_handle() const; diff --git a/panda/src/display/parasiteBuffer.cxx b/panda/src/display/parasiteBuffer.cxx index ace66cfdbc..1b23fdb653 100644 --- a/panda/src/display/parasiteBuffer.cxx +++ b/panda/src/display/parasiteBuffer.cxx @@ -21,7 +21,7 @@ TypeHandle ParasiteBuffer::_type_handle; * created instead via the GraphicsEngine::make_parasite() function. */ ParasiteBuffer:: -ParasiteBuffer(GraphicsOutput *host, const string &name, +ParasiteBuffer(GraphicsOutput *host, const std::string &name, int x_size, int y_size, int flags) : GraphicsOutput(host->get_engine(), host->get_pipe(), name, host->get_fb_properties(), @@ -95,7 +95,7 @@ set_size_and_recalc(int x, int y) { y = Texture::down_to_power_2(y); } if (_creation_flags & GraphicsPipe::BF_size_square) { - x = y = min(x, y); + x = y = std::min(x, y); } } @@ -108,7 +108,7 @@ set_size_and_recalc(int x, int y) { */ bool ParasiteBuffer:: flip_ready() const { - nassertr(_host != NULL, false); + nassertr(_host != nullptr, false); return _host->flip_ready(); } @@ -125,7 +125,7 @@ flip_ready() const { */ void ParasiteBuffer:: begin_flip() { - nassertv(_host != NULL); + nassertv(_host != nullptr); _host->begin_flip(); } @@ -140,7 +140,7 @@ begin_flip() { */ void ParasiteBuffer:: ready_flip() { - nassertv(_host != NULL); + nassertv(_host != nullptr); _host->ready_flip(); } @@ -153,7 +153,7 @@ ready_flip() { */ void ParasiteBuffer:: end_flip() { - nassertv(_host != NULL); + nassertv(_host != nullptr); _host->end_flip(); _flip_ready = false; } @@ -180,8 +180,8 @@ begin_frame(FrameMode mode, Thread *current_thread) { } else { if (_host->get_x_size() < get_x_size() || _host->get_y_size() < get_y_size()) { - set_size_and_recalc(min(get_x_size(), _host->get_x_size()), - min(get_y_size(), _host->get_y_size())); + set_size_and_recalc(std::min(get_x_size(), _host->get_x_size()), + std::min(get_y_size(), _host->get_y_size())); } } @@ -198,7 +198,7 @@ void ParasiteBuffer:: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); - nassertv(_gsg != (GraphicsStateGuardian *)NULL); + nassertv(_gsg != nullptr); _host->end_frame(FM_parasite, current_thread); diff --git a/panda/src/display/parasiteBuffer.h b/panda/src/display/parasiteBuffer.h index 421b932584..3c197c068e 100644 --- a/panda/src/display/parasiteBuffer.h +++ b/panda/src/display/parasiteBuffer.h @@ -42,7 +42,7 @@ */ class EXPCL_PANDA_DISPLAY ParasiteBuffer : public GraphicsOutput { public: - ParasiteBuffer(GraphicsOutput *host, const string &name, + ParasiteBuffer(GraphicsOutput *host, const std::string &name, int x_size, int y_size, int flags); PUBLISHED: diff --git a/panda/src/display/standardMunger.cxx b/panda/src/display/standardMunger.cxx index cdc2f0bda3..5d2a3f5102 100644 --- a/panda/src/display/standardMunger.cxx +++ b/panda/src/display/standardMunger.cxx @@ -125,10 +125,10 @@ munge_data_impl(const GeomVertexData *data) { } else if (hardware_animated_vertices && animation.get_animation_type() == AT_panda && - new_data->get_slider_table() == (SliderTable *)NULL) { + new_data->get_slider_table() == nullptr) { // Maybe we can animate the vertices with hardware. const TransformBlendTable *table = new_data->get_transform_blend_table(); - if (table != (TransformBlendTable *)NULL && + if (table != nullptr && table->get_num_transforms() != 0 && table->get_max_simultaneous_transforms() <= get_gsg()->get_max_vertex_transforms()) { diff --git a/panda/src/display/stereoDisplayRegion.cxx b/panda/src/display/stereoDisplayRegion.cxx index 3b3a7cf9f8..5151920cab 100644 --- a/panda/src/display/stereoDisplayRegion.cxx +++ b/panda/src/display/stereoDisplayRegion.cxx @@ -262,7 +262,7 @@ set_target_tex_page(int page) { * */ void StereoDisplayRegion:: -output(ostream &out) const { +output(std::ostream &out) const { out << "StereoDisplayRegion(" << *_left_eye << ")"; } diff --git a/panda/src/display/stereoDisplayRegion.h b/panda/src/display/stereoDisplayRegion.h index b1d27bd361..940d793f4b 100644 --- a/panda/src/display/stereoDisplayRegion.h +++ b/panda/src/display/stereoDisplayRegion.h @@ -58,7 +58,7 @@ PUBLISHED: virtual void set_cull_traverser(CullTraverser *trav); virtual void set_target_tex_page(int page); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; virtual PT(PandaNode) make_cull_result_graph(); INLINE DisplayRegion *get_left_eye(); diff --git a/panda/src/display/subprocessWindow.cxx b/panda/src/display/subprocessWindow.cxx index d001f3b1f6..fe4b2eff5d 100644 --- a/panda/src/display/subprocessWindow.cxx +++ b/panda/src/display/subprocessWindow.cxx @@ -19,6 +19,8 @@ #include "config_display.h" #include "nativeWindowHandle.h" +using std::string; + TypeHandle SubprocessWindow::_type_handle; /** @@ -41,7 +43,7 @@ SubprocessWindow(GraphicsEngine *engine, GraphicsPipe *pipe, // This will be an offscreen buffer that we use to render the actual // contents. - _buffer = NULL; + _buffer = nullptr; // Create a texture to receive the contents of the framebuffer from the // offscreen buffer. @@ -50,7 +52,7 @@ SubprocessWindow(GraphicsEngine *engine, GraphicsPipe *pipe, _fd = -1; _mmap_size = 0; _filename = string(); - _swbuffer = NULL; + _swbuffer = nullptr; _last_event_flags = 0; } @@ -59,8 +61,8 @@ SubprocessWindow(GraphicsEngine *engine, GraphicsPipe *pipe, */ SubprocessWindow:: ~SubprocessWindow() { - nassertv(_buffer == NULL); - nassertv(_swbuffer == NULL); + nassertv(_buffer == nullptr); + nassertv(_swbuffer == nullptr); } /** @@ -74,7 +76,7 @@ void SubprocessWindow:: process_events() { GraphicsWindow::process_events(); - if (_swbuffer != NULL) { + if (_swbuffer != nullptr) { SubprocessWindowBuffer::Event swb_event; while (_swbuffer->get_event(swb_event)) { // Deal with this event. @@ -129,7 +131,7 @@ process_events() { */ bool SubprocessWindow:: begin_frame(FrameMode mode, Thread *current_thread) { - if (_swbuffer == NULL || _buffer == NULL) { + if (_swbuffer == nullptr || _buffer == nullptr) { return false; } @@ -164,8 +166,8 @@ end_frame(FrameMode mode, Thread *current_thread) { */ void SubprocessWindow:: begin_flip() { - nassertv(_buffer != (GraphicsBuffer *)NULL); - if (_swbuffer == NULL) { + nassertv(_buffer != nullptr); + if (_swbuffer == nullptr) { return; } @@ -225,9 +227,9 @@ void SubprocessWindow:: set_properties_now(WindowProperties &properties) { Filename filename; WindowHandle *window_handle = properties.get_parent_window(); - if (window_handle != NULL) { + if (window_handle != nullptr) { WindowHandle::OSHandle *os_handle = window_handle->get_os_handle(); - if (os_handle != NULL) { + if (os_handle != nullptr) { if (os_handle->is_of_type(NativeWindowHandle::SubprocessHandle::get_class_type())) { NativeWindowHandle::SubprocessHandle *subprocess_handle = DCAST(NativeWindowHandle::SubprocessHandle, os_handle); filename = subprocess_handle->get_filename(); @@ -299,30 +301,30 @@ open_window() { */ void SubprocessWindow:: internal_close_window() { - if (_swbuffer != NULL) { + if (_swbuffer != nullptr) { SubprocessWindowBuffer::close_buffer (_fd, _mmap_size, _filename.to_os_specific(), _swbuffer); _fd = -1; _filename = string(); - _swbuffer = NULL; + _swbuffer = nullptr; } - if (_buffer != NULL) { + if (_buffer != nullptr) { _buffer->request_close(); _buffer->process_events(); _engine->remove_window(_buffer); - _buffer = NULL; + _buffer = nullptr; } // Tell our parent window (if any) that we're no longer its child. - if (_window_handle != (WindowHandle *)NULL && - _parent_window_handle != (WindowHandle *)NULL) { + if (_window_handle != nullptr && + _parent_window_handle != nullptr) { _parent_window_handle->detach_child(_window_handle); } - _window_handle = NULL; - _parent_window_handle = NULL; + _window_handle = nullptr; + _parent_window_handle = nullptr; _is_valid = false; } @@ -332,7 +334,7 @@ internal_close_window() { */ bool SubprocessWindow:: internal_open_window() { - nassertr(_buffer == NULL, false); + nassertr(_buffer == nullptr, false); // Create a buffer with the same properties as the window. int flags = _creation_flags; @@ -342,7 +344,7 @@ internal_open_window() { GraphicsOutput *buffer = _engine->make_output(_pipe, _name, 0, _fb_properties, win_props, flags, _gsg, _host); - if (buffer != NULL) { + if (buffer != nullptr) { _buffer = DCAST(GraphicsBuffer, buffer); // However, the buffer is not itself intended to be rendered. We only // render it indirectly, via callbacks in here. @@ -363,9 +365,9 @@ internal_open_window() { _gsg = _buffer->get_gsg(); WindowHandle *window_handle = _properties.get_parent_window(); - if (window_handle != NULL) { + if (window_handle != nullptr) { WindowHandle::OSHandle *os_handle = window_handle->get_os_handle(); - if (os_handle != NULL) { + if (os_handle != nullptr) { if (os_handle->is_of_type(NativeWindowHandle::SubprocessHandle::get_class_type())) { NativeWindowHandle::SubprocessHandle *subprocess_handle = DCAST(NativeWindowHandle::SubprocessHandle, os_handle); _filename = subprocess_handle->get_filename(); @@ -384,7 +386,7 @@ internal_open_window() { _swbuffer = SubprocessWindowBuffer::open_buffer (_fd, _mmap_size, _filename.to_os_specific()); - if (_swbuffer == NULL) { + if (_swbuffer == nullptr) { close(_fd); _fd = -1; _filename = string(); @@ -404,7 +406,7 @@ internal_open_window() { _window_handle = NativeWindowHandle::make_subprocess(_filename); // And tell our parent window that we're now its child. - if (_parent_window_handle != (WindowHandle *)NULL) { + if (_parent_window_handle != nullptr) { _parent_window_handle->attach_child(_window_handle); } diff --git a/panda/src/display/subprocessWindow.h b/panda/src/display/subprocessWindow.h index 8065721f42..1339b8f90d 100644 --- a/panda/src/display/subprocessWindow.h +++ b/panda/src/display/subprocessWindow.h @@ -45,7 +45,7 @@ class SubprocessWindow : public GraphicsWindow { public: SubprocessWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/display/subprocessWindowBuffer.cxx b/panda/src/display/subprocessWindowBuffer.cxx index 36eec2def3..168e7f0758 100644 --- a/panda/src/display/subprocessWindowBuffer.cxx +++ b/panda/src/display/subprocessWindowBuffer.cxx @@ -18,7 +18,9 @@ #include #include -using namespace std; + +using std::cerr; +using std::string; const char SubprocessWindowBuffer:: _magic_number[SubprocessWindowBuffer::magic_number_length] = "pNdaSWB"; @@ -95,12 +97,12 @@ new_buffer(int &fd, size_t &mmap_size, string &filename, mmap_size = 0; fd = -1; - filename = tmpnam(NULL); + filename = tmpnam(nullptr); fd = open(filename.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600); if (fd == -1) { perror(filename.c_str()); - return NULL; + return nullptr; } // Create a temporary object to determine the required size. @@ -115,14 +117,14 @@ new_buffer(int &fd, size_t &mmap_size, string &filename, write(fd, zero, zero_size); } - void *shared_mem = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, + void *shared_mem = mmap(nullptr, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (shared_mem == (void *)-1) { // Failure to map. close(fd); fd = -1; mmap_size = 0; - return NULL; + return nullptr; } // Now create the actual object in the shared-memory buffer. @@ -161,7 +163,7 @@ open_buffer(int &fd, size_t &mmap_size, const string &filename) { fd = open(filename.c_str(), O_RDWR); if (fd == -1) { perror(filename.c_str()); - return NULL; + return nullptr; } // Check that the disk file is large enough. @@ -170,19 +172,19 @@ open_buffer(int &fd, size_t &mmap_size, const string &filename) { cerr << filename << " not large enough.\n"; close(fd); fd = -1; - return NULL; + return nullptr; } // First, map enough memory to read the buffer object. size_t initial_size = sizeof(SubprocessWindowBuffer); - void *shared_mem = mmap(NULL, initial_size, PROT_READ, + void *shared_mem = mmap(nullptr, initial_size, PROT_READ, MAP_SHARED, fd, 0); if (shared_mem == (void *)-1) { perror("mmap"); cerr << "Couldn't map.\n"; close(fd); fd = -1; - return NULL; + return nullptr; } SubprocessWindowBuffer *temp = (SubprocessWindowBuffer *)shared_mem; @@ -191,7 +193,7 @@ open_buffer(int &fd, size_t &mmap_size, const string &filename) { munmap(shared_mem, initial_size); close(fd); fd = -1; - return NULL; + return nullptr; } @@ -204,15 +206,15 @@ open_buffer(int &fd, size_t &mmap_size, const string &filename) { cerr << filename << " not large enough.\n"; close(fd); fd = -1; - return NULL; + return nullptr; } - shared_mem = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, + shared_mem = mmap(nullptr, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (shared_mem == (void *)-1) { perror("mmap"); cerr << "Couldn't map 2.\n"; - return NULL; + return nullptr; } // Now that we've successfully opened and mapped the file, we can safely diff --git a/panda/src/display/subprocessWindowBuffer.h b/panda/src/display/subprocessWindowBuffer.h index 2fecbcadbc..2cadcee8f5 100644 --- a/panda/src/display/subprocessWindowBuffer.h +++ b/panda/src/display/subprocessWindowBuffer.h @@ -17,7 +17,6 @@ #include // perror #include #include -using namespace std; /** * This is a special class that is designed to faciliate SubprocessWindow. @@ -42,16 +41,16 @@ private: public: static SubprocessWindowBuffer *new_buffer(int &fd, size_t &mmap_size, - string &filename, + std::string &filename, int x_size, int y_size); static void destroy_buffer(int fd, size_t mmap_size, - const string &filename, + const std::string &filename, SubprocessWindowBuffer *buffer); static SubprocessWindowBuffer *open_buffer(int &fd, size_t &mmap_size, - const string &filename); + const std::string &filename); static void close_buffer(int fd, size_t mmap_size, - const string &filename, + const std::string &filename, SubprocessWindowBuffer *buffer); bool verify_magic_number() const; diff --git a/panda/src/display/windowHandle.cxx b/panda/src/display/windowHandle.cxx index ecc903595f..0bfec17af7 100644 --- a/panda/src/display/windowHandle.cxx +++ b/panda/src/display/windowHandle.cxx @@ -31,7 +31,7 @@ WindowHandle:: */ void WindowHandle:: send_windows_message(unsigned int msg, int wparam, int lparam) { - if (_keyboard_window != NULL) { + if (_keyboard_window != nullptr) { _keyboard_window->receive_windows_message(msg, wparam, lparam); } } @@ -42,7 +42,7 @@ send_windows_message(unsigned int msg, int wparam, int lparam) { */ size_t WindowHandle:: get_int_handle() const { - if (_os_handle != NULL) { + if (_os_handle != nullptr) { return _os_handle->get_int_handle(); } return 0; @@ -52,8 +52,8 @@ get_int_handle() const { * */ void WindowHandle:: -output(ostream &out) const { - if (_os_handle == NULL) { +output(std::ostream &out) const { + if (_os_handle == nullptr) { out << "(null)"; } else { out << *_os_handle; @@ -75,7 +75,7 @@ attach_child(WindowHandle *child) { void WindowHandle:: detach_child(WindowHandle *child) { if (_keyboard_window == child) { - _keyboard_window = NULL; + _keyboard_window = nullptr; } } @@ -117,6 +117,6 @@ get_int_handle() const { * */ void WindowHandle::OSHandle:: -output(ostream &out) const { +output(std::ostream &out) const { out << "(no type)"; } diff --git a/panda/src/display/windowHandle.h b/panda/src/display/windowHandle.h index 1679e3d95f..7089aa8e28 100644 --- a/panda/src/display/windowHandle.h +++ b/panda/src/display/windowHandle.h @@ -47,7 +47,7 @@ PUBLISHED: size_t get_int_handle() const; - void output(ostream &out) const; + void output(std::ostream &out) const; public: // Callbacks for communication with the parent window. @@ -67,7 +67,7 @@ PUBLISHED: PUBLISHED: virtual ~OSHandle(); virtual size_t get_int_handle() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; public: static TypeHandle get_class_type() { @@ -112,12 +112,12 @@ private: #include "windowHandle.I" -INLINE ostream &operator << (ostream &out, const WindowHandle &handle) { +INLINE std::ostream &operator << (std::ostream &out, const WindowHandle &handle) { handle.output(out); return out; } -INLINE ostream &operator << (ostream &out, const WindowHandle::OSHandle &handle) { +INLINE std::ostream &operator << (std::ostream &out, const WindowHandle::OSHandle &handle) { handle.output(out); return out; } diff --git a/panda/src/display/windowProperties.I b/panda/src/display/windowProperties.I index 9179124705..d134ea2be5 100644 --- a/panda/src/display/windowProperties.I +++ b/panda/src/display/windowProperties.I @@ -182,7 +182,7 @@ clear_size() { * Specifies the title that should be assigned to the window. */ INLINE void WindowProperties:: -set_title(const string &title) { +set_title(const std::string &title) { _title = title; _specified |= S_title; } @@ -190,7 +190,7 @@ set_title(const string &title) { /** * Returns the window's title. */ -INLINE const string &WindowProperties:: +INLINE const std::string &WindowProperties:: get_title() const { nassertr(has_title(), _title); return _title; @@ -210,7 +210,7 @@ has_title() const { INLINE void WindowProperties:: clear_title() { _specified &= ~S_title; - _title = string(); + _title = std::string(); } /** @@ -726,12 +726,12 @@ has_parent_window() const { INLINE void WindowProperties:: clear_parent_window() { _specified &= ~S_parent_window; - _parent_window = NULL; + _parent_window = nullptr; } -INLINE ostream & -operator << (ostream &out, const WindowProperties &properties) { +INLINE std::ostream & +operator << (std::ostream &out, const WindowProperties &properties) { properties.output(out); return out; } diff --git a/panda/src/display/windowProperties.cxx b/panda/src/display/windowProperties.cxx index 298bed4b45..93cd0a7144 100644 --- a/panda/src/display/windowProperties.cxx +++ b/panda/src/display/windowProperties.cxx @@ -15,7 +15,11 @@ #include "config_display.h" #include "nativeWindowHandle.h" -WindowProperties *WindowProperties::_default_properties = NULL; +using std::istream; +using std::ostream; +using std::string; + +WindowProperties *WindowProperties::_default_properties = nullptr; /** * @@ -93,7 +97,7 @@ get_config_properties() { */ WindowProperties WindowProperties:: get_default() { - if (_default_properties != NULL) { + if (_default_properties != nullptr) { return *_default_properties; } else { return get_config_properties(); @@ -110,7 +114,7 @@ get_default() { */ void WindowProperties:: set_default(const WindowProperties &default_properties) { - if (_default_properties == NULL) { + if (_default_properties == nullptr) { _default_properties = new WindowProperties; } (*_default_properties) = default_properties; @@ -122,9 +126,9 @@ set_default(const WindowProperties &default_properties) { */ void WindowProperties:: clear_default() { - if (_default_properties != NULL) { + if (_default_properties != nullptr) { delete _default_properties; - _default_properties = NULL; + _default_properties = nullptr; } } @@ -177,7 +181,7 @@ clear() { _z_order = Z_normal; _flags = 0; _mouse_mode = M_absolute; - _parent_window = NULL; + _parent_window = nullptr; } /** @@ -197,7 +201,7 @@ clear() { void WindowProperties:: set_parent_window(size_t parent) { if (parent == 0) { - set_parent_window((WindowHandle *)NULL); + set_parent_window(nullptr); } else { PT(WindowHandle) handle = NativeWindowHandle::make_int(parent); set_parent_window(handle); @@ -312,7 +316,7 @@ output(ostream &out) const { out << get_mouse_mode() << " "; } if (has_parent_window()) { - if (get_parent_window() == NULL) { + if (get_parent_window() == nullptr) { out << "parent:none "; } else { out << "parent:" << *get_parent_window() << " "; diff --git a/panda/src/display/windowProperties.h b/panda/src/display/windowProperties.h index 16a65c0096..68ba4e7f1d 100644 --- a/panda/src/display/windowProperties.h +++ b/panda/src/display/windowProperties.h @@ -86,8 +86,8 @@ PUBLISHED: MAKE_PROPERTY2(mouse_mode, has_mouse_mode, get_mouse_mode, set_mouse_mode, clear_mouse_mode); - INLINE void set_title(const string &title); - INLINE const string &get_title() const; + INLINE void set_title(const std::string &title); + INLINE const std::string &get_title() const; INLINE bool has_title() const; INLINE void clear_title(); MAKE_PROPERTY2(title, has_title, get_title, set_title, clear_title); @@ -166,7 +166,7 @@ PUBLISHED: MAKE_PROPERTY2(z_order, has_z_order, get_z_order, set_z_order, clear_z_order); void set_parent_window(size_t parent); - INLINE void set_parent_window(WindowHandle *parent_window = NULL); + INLINE void set_parent_window(WindowHandle *parent_window = nullptr); INLINE WindowHandle *get_parent_window() const; INLINE bool has_parent_window() const; INLINE void clear_parent_window(); @@ -175,7 +175,7 @@ PUBLISHED: void add_properties(const WindowProperties &other); - void output(ostream &out) const; + void output(std::ostream &out) const; private: // This bitmask indicates which of the parameters in the properties @@ -216,7 +216,7 @@ private: LPoint2i _origin; LVector2i _size; MouseMode _mouse_mode; - string _title; + std::string _title; Filename _cursor_filename; Filename _icon_filename; ZOrder _z_order; @@ -226,18 +226,18 @@ private: static WindowProperties *_default_properties; }; -EXPCL_PANDA_DISPLAY ostream & -operator << (ostream &out, WindowProperties::ZOrder z_order); -EXPCL_PANDA_DISPLAY istream & -operator >> (istream &in, WindowProperties::ZOrder &z_order); +EXPCL_PANDA_DISPLAY std::ostream & +operator << (std::ostream &out, WindowProperties::ZOrder z_order); +EXPCL_PANDA_DISPLAY std::istream & +operator >> (std::istream &in, WindowProperties::ZOrder &z_order); -EXPCL_PANDA_DISPLAY ostream & -operator << (ostream &out, WindowProperties::MouseMode mode); -EXPCL_PANDA_DISPLAY istream & -operator >> (istream &in, WindowProperties::MouseMode &mode); +EXPCL_PANDA_DISPLAY std::ostream & +operator << (std::ostream &out, WindowProperties::MouseMode mode); +EXPCL_PANDA_DISPLAY std::istream & +operator >> (std::istream &in, WindowProperties::MouseMode &mode); -INLINE ostream &operator << (ostream &out, const WindowProperties &properties); +INLINE std::ostream &operator << (std::ostream &out, const WindowProperties &properties); #include "windowProperties.I" diff --git a/panda/src/distort/nonlinearImager.cxx b/panda/src/distort/nonlinearImager.cxx index fb264061c3..e0f86670a2 100644 --- a/panda/src/distort/nonlinearImager.cxx +++ b/panda/src/distort/nonlinearImager.cxx @@ -28,7 +28,7 @@ */ NonlinearImager:: NonlinearImager() { - _engine = (GraphicsEngine *)NULL; + _engine = nullptr; _stale = true; } @@ -40,7 +40,7 @@ NonlinearImager:: remove_all_screens(); remove_all_viewers(); - if (_recompute_task != (AsyncTask *)NULL) { + if (_recompute_task != nullptr) { AsyncTaskManager *task_mgr = AsyncTaskManager::get_global_ptr(); task_mgr->remove(_recompute_task); } @@ -71,7 +71,7 @@ add_screen(ProjectionScreen *screen) { * The return value is the index number of the new screen. */ int NonlinearImager:: -add_screen(const NodePath &screen, const string &name) { +add_screen(const NodePath &screen, const std::string &name) { nassertr(!screen.is_empty() && screen.node()->is_of_type(ProjectionScreen::get_class_type()), -1); @@ -82,7 +82,7 @@ add_screen(const NodePath &screen, const string &name) { new_screen._screen = screen; new_screen._screen_node = screen_node; new_screen._name = name; - new_screen._buffer = (GraphicsOutput *)NULL; + new_screen._buffer = nullptr; new_screen._tex_width = 256; new_screen._tex_height = 256; new_screen._active = true; @@ -167,7 +167,7 @@ get_screen(int index) const { */ GraphicsOutput *NonlinearImager:: get_buffer(int index) const { - nassertr(index >= 0 && index < (int)_screens.size(), (GraphicsOutput *)NULL); + nassertr(index >= 0 && index < (int)_screens.size(), nullptr); return _screens[index]._buffer; } @@ -188,9 +188,9 @@ set_texture_size(int index, int width, int height) { screen._tex_width = width; screen._tex_height = height; - if (screen._buffer != (GraphicsOutput *)NULL) { + if (screen._buffer != nullptr) { bool removed = _engine->remove_window(screen._buffer); - screen._buffer = (GraphicsOutput *)NULL; + screen._buffer = nullptr; nassertv(removed); } @@ -230,9 +230,9 @@ set_screen_active(int index, bool active) { } // Also remove its buffer. - if (screen._buffer != (GraphicsOutput *)NULL) { + if (screen._buffer != nullptr) { bool removed = _engine->remove_window(screen._buffer); - screen._buffer = (GraphicsOutput *)NULL; + screen._buffer = nullptr; nassertv(removed); } @@ -276,20 +276,20 @@ get_screen_active(int index) const { int NonlinearImager:: add_viewer(DisplayRegion *dr) { GraphicsOutput *window = dr->get_window(); - nassertr(window != (GraphicsOutput *)NULL, -1); + nassertr(window != nullptr, -1); GraphicsStateGuardian *gsg = window->get_gsg(); - nassertr(gsg != (GraphicsStateGuardian *)NULL, -1); + nassertr(gsg != nullptr, -1); GraphicsEngine *engine = gsg->get_engine(); - nassertr(engine != (GraphicsEngine *)NULL, -1); + nassertr(engine != nullptr, -1); nassertr(_viewers.empty() || (engine == _engine), -1); - if (_engine == (GraphicsEngine *)NULL) { + if (_engine == nullptr) { _engine = engine; } - if (_recompute_task == (AsyncTask *)NULL) { + if (_recompute_task == nullptr) { _recompute_task = new GenericAsyncTask("nli_recompute", recompute_callback, (void *)this); AsyncTaskManager *task_mgr = AsyncTaskManager::get_global_ptr(); @@ -310,7 +310,7 @@ add_viewer(DisplayRegion *dr) { // Get the current camera off of the DisplayRegion, if any. viewer._viewer = dr->get_camera(); if (viewer._viewer.is_empty()) { - viewer._viewer_node = (LensNode *)NULL; + viewer._viewer_node = nullptr; } else { viewer._viewer_node = DCAST(LensNode, viewer._viewer.node()); } @@ -463,7 +463,7 @@ get_num_viewers() const { */ DisplayRegion *NonlinearImager:: get_viewer(int index) const { - nassertr(index >= 0 && index < (int)_viewers.size(), (DisplayRegion *)NULL); + nassertr(index >= 0 && index < (int)_viewers.size(), nullptr); return _viewers[index]._dr; } @@ -509,8 +509,8 @@ recompute() { } } - if (viewer._viewer_node != (LensNode *)NULL && - viewer._viewer_node->get_lens() != (Lens *)NULL) { + if (viewer._viewer_node != nullptr && + viewer._viewer_node->get_lens() != nullptr) { viewer._viewer_lens_change = viewer._viewer_node->get_lens()->get_last_change(); } @@ -540,7 +540,7 @@ recompute_if_stale() { size_t vi; for (vi = 0; vi < _viewers.size(); ++vi) { Viewer &viewer = _viewers[vi]; - if (viewer._viewer_node != (LensNode *)NULL) { + if (viewer._viewer_node != nullptr) { UpdateSeq lens_change = viewer._viewer_node->get_lens()->get_last_change(); if (lens_change != viewer._viewer_lens_change) { @@ -588,16 +588,16 @@ recompute_screen(NonlinearImager::Screen &screen, size_t vi) { Viewer &viewer = _viewers[vi]; PT(PandaNode) mesh = screen._screen_node->make_flat_mesh(screen._screen, viewer._viewer); - if (mesh != (PandaNode *)NULL) { + if (mesh != nullptr) { screen._meshes[vi]._mesh = viewer._internal_scene.attach_new_node(mesh); } - if (screen._buffer == (GraphicsOutput *)NULL) { + if (screen._buffer == nullptr) { GraphicsOutput *win = viewer._dr->get_window(); GraphicsOutput *buffer = win->make_texture_buffer - (screen._name, screen._tex_width, screen._tex_height, NULL, false); + (screen._name, screen._tex_width, screen._tex_height, nullptr, false); - if (buffer != (GraphicsOutput *)NULL) { + if (buffer != nullptr) { screen._buffer = buffer; DisplayRegion *dr = buffer->make_display_region(); dr->set_camera(screen._source_camera); @@ -607,7 +607,7 @@ recompute_screen(NonlinearImager::Screen &screen, size_t vi) { } } - if (screen._buffer != (GraphicsOutput *)NULL) { + if (screen._buffer != nullptr) { screen._meshes[vi]._mesh.set_texture(screen._buffer->get_texture()); // We don't really need to set the texture on the dark room screen, since diff --git a/panda/src/distort/nonlinearImager.h b/panda/src/distort/nonlinearImager.h index 621ad0d139..aa07854df7 100644 --- a/panda/src/distort/nonlinearImager.h +++ b/panda/src/distort/nonlinearImager.h @@ -84,7 +84,7 @@ PUBLISHED: ~NonlinearImager(); int add_screen(ProjectionScreen *screen); - int add_screen(const NodePath &screen, const string &name); + int add_screen(const NodePath &screen, const std::string &name); int find_screen(const NodePath &screen) const; void remove_screen(int index); void remove_all_screens(); @@ -146,7 +146,7 @@ private: public: NodePath _screen; PT(ProjectionScreen) _screen_node; - string _name; + std::string _name; PT(GraphicsOutput) _buffer; NodePath _source_camera; int _tex_width, _tex_height; diff --git a/panda/src/distort/projectionScreen.I b/panda/src/distort/projectionScreen.I index b1fa41f7f5..2ff54cfeb5 100644 --- a/panda/src/distort/projectionScreen.I +++ b/panda/src/distort/projectionScreen.I @@ -67,7 +67,7 @@ get_undist_lut() const { * stages of the multitexture pipeline. */ INLINE void ProjectionScreen:: -set_texcoord_name(const string &texcoord_name) { +set_texcoord_name(const std::string &texcoord_name) { _texcoord_name = InternalName::get_texcoord_name(texcoord_name); _stale = true; } @@ -76,7 +76,7 @@ set_texcoord_name(const string &texcoord_name) { * Returns the name of the texture coordinates that will be generated by this * particular ProjectionScreen, as set by set_texcoord_name(). */ -INLINE string ProjectionScreen:: +INLINE std::string ProjectionScreen:: get_texcoord_name() const { return _texcoord_name->get_name(); } diff --git a/panda/src/distort/projectionScreen.cxx b/panda/src/distort/projectionScreen.cxx index 1991bfc120..e3bed91e27 100644 --- a/panda/src/distort/projectionScreen.cxx +++ b/panda/src/distort/projectionScreen.cxx @@ -30,7 +30,7 @@ TypeHandle ProjectionScreen::_type_handle; * */ ProjectionScreen:: -ProjectionScreen(const string &name) : PandaNode(name) +ProjectionScreen(const std::string &name) : PandaNode(name) { set_cull_callback(); @@ -118,7 +118,7 @@ cull_callback(CullTraverser *, CullTraverserData &data) { */ void ProjectionScreen:: set_projector(const NodePath &projector) { - _projector_node = (LensNode *)NULL; + _projector_node = nullptr; _projector = projector; if (!projector.is_empty()) { nassertv(projector.node()->is_of_type(LensNode::get_class_type())); @@ -151,14 +151,14 @@ set_projector(const NodePath &projector) { * fraction, and make the screen smaller by the inverse fraction. */ PT(GeomNode) ProjectionScreen:: -generate_screen(const NodePath &projector, const string &screen_name, +generate_screen(const NodePath &projector, const std::string &screen_name, int num_x_verts, int num_y_verts, PN_stdfloat distance, PN_stdfloat fill_ratio) { nassertr(!projector.is_empty() && projector.node()->is_of_type(LensNode::get_class_type()), - NULL); + nullptr); LensNode *projector_node = DCAST(LensNode, projector.node()); - nassertr(projector_node->get_lens() != NULL, NULL); + nassertr(projector_node->get_lens() != nullptr, nullptr); // First, get the relative coordinate space of the projector. LMatrix4 rel_mat; @@ -204,7 +204,7 @@ generate_screen(const NodePath &projector, const string &screen_name, normal.add_data3(-normalize(norm * rel_mat)); } } - nassertr(vdata->get_num_rows() == num_verts, NULL); + nassertr(vdata->get_num_rows() == num_verts, nullptr); // Now synthesize a triangle mesh. We run triangle strips horizontally // across the grid. @@ -237,7 +237,7 @@ generate_screen(const NodePath &projector, const string &screen_name, * generated child returned by generate_screen(). */ void ProjectionScreen:: -regenerate_screen(const NodePath &projector, const string &screen_name, +regenerate_screen(const NodePath &projector, const std::string &screen_name, int num_x_verts, int num_y_verts, PN_stdfloat distance, PN_stdfloat fill_ratio) { // First, remove all existing children. @@ -265,12 +265,12 @@ regenerate_screen(const NodePath &projector, const string &screen_name, */ PT(PandaNode) ProjectionScreen:: make_flat_mesh(const NodePath &this_np, const NodePath &camera) { - nassertr(!this_np.is_empty() && this_np.node() == this, NULL); + nassertr(!this_np.is_empty() && this_np.node() == this, nullptr); nassertr(!camera.is_empty() && camera.node()->is_of_type(LensNode::get_class_type()), - NULL); + nullptr); LensNode *camera_node = DCAST(LensNode, camera.node()); - nassertr(camera_node->get_lens() != (Lens *)NULL, NULL); + nassertr(camera_node->get_lens() != nullptr, nullptr); // First, ensure the UV's are up-to-date. recompute_if_stale(this_np); @@ -318,8 +318,8 @@ bool ProjectionScreen:: recompute_if_stale(const NodePath &this_np) { nassertr(!this_np.is_empty() && this_np.node() == this, false); - if (_projector_node != (LensNode *)NULL && - _projector_node->get_lens() != (Lens *)NULL) { + if (_projector_node != nullptr && + _projector_node->get_lens() != nullptr) { UpdateSeq lens_change = _projector_node->get_lens()->get_last_change(); if (_stale || lens_change != _projector_lens_change) { recompute(); @@ -346,8 +346,8 @@ recompute_if_stale(const NodePath &this_np) { */ void ProjectionScreen:: do_recompute(const NodePath &this_np) { - if (_projector_node != (LensNode *)NULL && - _projector_node->get_lens() != (Lens *)NULL) { + if (_projector_node != nullptr && + _projector_node->get_lens() != nullptr) { recompute_node(this_np, _rel_top_mat, _computed_rel_top_mat); // Make sure this flag is set to false for next time. @@ -479,7 +479,7 @@ recompute_geom(Geom *geom, const LMatrix4 &rel_mat) { Thread *current_thread = Thread::get_current_thread(); Lens *lens = _projector_node->get_lens(); - nassertv(lens != (Lens *)NULL); + nassertv(lens != nullptr); const LMatrix4 &to_uv = _invert_uvs ? lens_to_uv_inverted : lens_to_uv; @@ -620,7 +620,7 @@ make_mesh_children(PandaNode *new_node, const WorkingNodePath &np, rel_mat, computed_rel_mat); } - if (new_child != NULL) { + if (new_child != nullptr) { // Copy all of the render state (except TransformState) to the new arc. new_child->set_state(child->get_state()); } @@ -650,7 +650,7 @@ make_mesh_geom_node(const WorkingNodePath &np, const NodePath &camera, const Geom *geom = node->get_geom(i); PT(Geom) new_geom = make_mesh_geom(geom, lens_node->get_lens(), rel_mat); - if (new_geom != (Geom *)NULL) { + if (new_geom != nullptr) { new_node->add_geom(new_geom, node->get_geom_state(i)); } } diff --git a/panda/src/distort/projectionScreen.h b/panda/src/distort/projectionScreen.h index 86f9484379..ef90ebb070 100644 --- a/panda/src/distort/projectionScreen.h +++ b/panda/src/distort/projectionScreen.h @@ -47,7 +47,7 @@ class WorkingNodePath; */ class EXPCL_PANDAFX ProjectionScreen : public PandaNode { PUBLISHED: - explicit ProjectionScreen(const string &name = ""); + explicit ProjectionScreen(const std::string &name = ""); virtual ~ProjectionScreen(); protected: @@ -67,16 +67,16 @@ PUBLISHED: INLINE const PfmFile &get_undist_lut() const; PT(GeomNode) generate_screen(const NodePath &projector, - const string &screen_name, + const std::string &screen_name, int num_x_verts, int num_y_verts, PN_stdfloat distance, PN_stdfloat fill_ratio); - void regenerate_screen(const NodePath &projector, const string &screen_name, + void regenerate_screen(const NodePath &projector, const std::string &screen_name, int num_x_verts, int num_y_verts, PN_stdfloat distance, PN_stdfloat fill_ratio); PT(PandaNode) make_flat_mesh(const NodePath &this_np, const NodePath &camera); - INLINE void set_texcoord_name(const string &texcoord_name); - INLINE string get_texcoord_name() const; + INLINE void set_texcoord_name(const std::string &texcoord_name); + INLINE std::string get_texcoord_name() const; INLINE void set_invert_uvs(bool invert_uvs); INLINE bool get_invert_uvs() const; diff --git a/panda/src/downloader/bioPtr.I b/panda/src/downloader/bioPtr.I index a1e1f13e1d..7d1e2b04dc 100644 --- a/panda/src/downloader/bioPtr.I +++ b/panda/src/downloader/bioPtr.I @@ -61,7 +61,7 @@ get_bio() const { /** * Returns the name of the server we are (or should be) connected to. */ -INLINE const string &BioPtr:: +INLINE const std::string &BioPtr:: get_server_name() const { return _server_name; } diff --git a/panda/src/downloader/bioPtr.cxx b/panda/src/downloader/bioPtr.cxx index b86f37f816..eb12b2bd8b 100644 --- a/panda/src/downloader/bioPtr.cxx +++ b/panda/src/downloader/bioPtr.cxx @@ -31,12 +31,14 @@ #include #endif +using std::string; + #ifdef _WIN32 static string format_error() { PVOID buffer; DWORD len; len = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, WSAGetLastError(), 0, (LPTSTR)&buffer, 0, NULL); + nullptr, WSAGetLastError(), 0, (LPTSTR)&buffer, 0, nullptr); if (len == 0) { return string("Unknown error message"); } @@ -88,17 +90,17 @@ BioPtr(const URLSpec &url) : _connecting(false) { // doesn't handle IPv6 properly. _server_name = url.get_server(); _port = url.get_port(); - _bio = NULL; + _bio = nullptr; // These hints tell getaddrinfo what kind of address to return. - struct addrinfo hints, *res = NULL; + struct addrinfo hints, *res = nullptr; memset(&hints, 0, sizeof(hints)); hints.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG; hints.ai_family = support_ipv6 ? AF_UNSPEC : AF_INET; hints.ai_socktype = SOCK_STREAM; // Resolve the hostname or address string. - int result = getaddrinfo(_server_name.c_str(), NULL, &hints, &res); + int result = getaddrinfo(_server_name.c_str(), nullptr, &hints, &res); if (result != 0) { const char *errmsg; #ifndef _WIN32 @@ -113,14 +115,14 @@ BioPtr(const URLSpec &url) : _connecting(false) { << "Failed to resolve " << url.get_server() << ": " << errmsg << "\n"; return; } - nassertv(res != NULL && res->ai_addr != NULL); + nassertv(res != nullptr && res->ai_addr != nullptr); // Store the real resolved address. char buf[48]; buf[0] = 0; #ifdef _WIN32 DWORD bufsize = sizeof(buf); - WSAAddressToStringA(res->ai_addr, res->ai_addrlen, NULL, buf, &bufsize); + WSAAddressToStringA(res->ai_addr, res->ai_addrlen, nullptr, buf, &bufsize); #else if (res->ai_addr->sa_family == AF_INET) { inet_ntop(AF_INET, (char *)&((sockaddr_in *)res->ai_addr)->sin_addr, buf, sizeof(buf)); @@ -143,7 +145,7 @@ BioPtr(const URLSpec &url) : _connecting(false) { if (fd < 0) { downloader_cat.error() << "Failed to create socket: " << format_error() << "\n"; - _bio = NULL; + _bio = nullptr; freeaddrinfo(res); return; } @@ -170,7 +172,7 @@ BioPtr(const URLSpec &url) : _connecting(false) { */ void BioPtr:: set_nbio(bool nbio) { - if (_bio == NULL) { + if (_bio == nullptr) { return; } @@ -186,7 +188,7 @@ set_nbio(bool nbio) { */ bool BioPtr:: connect() { - if (_bio == NULL) { + if (_bio == nullptr) { return false; } @@ -226,7 +228,7 @@ connect() { */ bool BioPtr:: should_retry() const { - return (_bio != NULL) && BIO_should_retry(_bio); + return (_bio != nullptr) && BIO_should_retry(_bio); } /** @@ -234,14 +236,14 @@ should_retry() const { */ BioPtr:: ~BioPtr() { - if (_bio != (BIO *)NULL) { + if (_bio != nullptr) { if (downloader_cat.is_debug() && !_server_name.empty()) { downloader_cat.debug() << "Dropping connection to " << _server_name << " port " << _port << "\n"; } BIO_free_all(_bio); - _bio = (BIO *)NULL; + _bio = nullptr; } } diff --git a/panda/src/downloader/bioPtr.h b/panda/src/downloader/bioPtr.h index 090ae20608..253073f745 100644 --- a/panda/src/downloader/bioPtr.h +++ b/panda/src/downloader/bioPtr.h @@ -39,7 +39,7 @@ class URLSpec; * on these things internally, but the interface doesn't appear to be public; * so we might as well wrap the whole thing at the high level. */ -class EXPCL_PANDAEXPRESS BioPtr : public ReferenceCount { +class EXPCL_PANDA_DOWNLOADER BioPtr : public ReferenceCount { public: INLINE BioPtr(BIO *bio); BioPtr(const URLSpec &url); @@ -57,12 +57,12 @@ public: INLINE void set_bio(BIO *bio); INLINE BIO *get_bio() const; - INLINE const string &get_server_name() const; + INLINE const std::string &get_server_name() const; INLINE int get_port() const; private: BIO *_bio; - string _server_name; + std::string _server_name; int _port; struct sockaddr_storage _addr; socklen_t _addrlen; diff --git a/panda/src/downloader/bioStream.h b/panda/src/downloader/bioStream.h index b47a17020a..0c68ed253d 100644 --- a/panda/src/downloader/bioStream.h +++ b/panda/src/downloader/bioStream.h @@ -29,7 +29,7 @@ * * Seeking is not supported. */ -class EXPCL_PANDAEXPRESS IBioStream : public ISocketStream { +class EXPCL_PANDA_DOWNLOADER IBioStream : public ISocketStream { public: INLINE IBioStream(); INLINE IBioStream(BioPtr *source); @@ -51,7 +51,7 @@ private: * * Seeking is not supported. */ -class EXPCL_PANDAEXPRESS OBioStream : public OSocketStream { +class EXPCL_PANDA_DOWNLOADER OBioStream : public OSocketStream { public: INLINE OBioStream(); INLINE OBioStream(BioPtr *source); @@ -69,7 +69,7 @@ private: * A bi-directional stream object that reads and writes data to an OpenSSL BIO * object. */ -class EXPCL_PANDAEXPRESS BioStream : public SocketStream { +class EXPCL_PANDA_DOWNLOADER BioStream : public SocketStream { public: INLINE BioStream(); INLINE BioStream(BioPtr *source); diff --git a/panda/src/downloader/bioStreamBuf.cxx b/panda/src/downloader/bioStreamBuf.cxx index d0bd04e027..1598b15259 100644 --- a/panda/src/downloader/bioStreamBuf.cxx +++ b/panda/src/downloader/bioStreamBuf.cxx @@ -24,11 +24,6 @@ #undef X509_NAME #endif // WIN32_VC -#ifndef HAVE_STREAMSIZE -// Some compilers (notably SGI) don't define this for us -typedef int streamsize; -#endif /* HAVE_STREAMSIZE */ - /** * */ @@ -194,9 +189,9 @@ underflow() { << _source->get_port() << " (" << read_count << ").\n"; OpenSSLWrapper::get_global_ptr()->notify_ssl_errors(); - SSL *ssl = NULL; + SSL *ssl = nullptr; BIO_get_ssl(*_source, &ssl); - if (ssl != (SSL *)NULL) { + if (ssl != nullptr) { downloader_cat.warning() << "OpenSSL error code: " << SSL_get_error(ssl, read_count) << "\n"; @@ -276,7 +271,7 @@ write_chars(const char *start, size_t length) { fd_set wset; FD_ZERO(&wset); FD_SET(fd, &wset); - select(fd + 1, NULL, &wset, NULL, NULL); + select(fd + 1, nullptr, &wset, nullptr, nullptr); #endif // SIMPLE_THREADS } diff --git a/panda/src/downloader/bioStreamBuf.h b/panda/src/downloader/bioStreamBuf.h index 0378d9db65..9e8fadad0b 100644 --- a/panda/src/downloader/bioStreamBuf.h +++ b/panda/src/downloader/bioStreamBuf.h @@ -25,7 +25,7 @@ /** * The streambuf object that implements IBioStream. */ -class EXPCL_PANDAEXPRESS BioStreamBuf : public streambuf { +class EXPCL_PANDA_DOWNLOADER BioStreamBuf : public std::streambuf { public: BioStreamBuf(); virtual ~BioStreamBuf(); diff --git a/panda/src/downloader/bioStreamPtr.cxx b/panda/src/downloader/bioStreamPtr.cxx index 80d5e4838a..6444703b16 100644 --- a/panda/src/downloader/bioStreamPtr.cxx +++ b/panda/src/downloader/bioStreamPtr.cxx @@ -20,9 +20,9 @@ */ BioStreamPtr:: ~BioStreamPtr() { - if (_stream != (BioStream *)NULL) { + if (_stream != nullptr) { delete _stream; - _stream = (BioStream *)NULL; + _stream = nullptr; } } diff --git a/panda/src/downloader/bioStreamPtr.h b/panda/src/downloader/bioStreamPtr.h index 3f23040d20..5e28fa2ba1 100644 --- a/panda/src/downloader/bioStreamPtr.h +++ b/panda/src/downloader/bioStreamPtr.h @@ -26,7 +26,7 @@ * A wrapper around an BioStream object to make a reference-counting pointer * to it. */ -class EXPCL_PANDAEXPRESS BioStreamPtr : public ReferenceCount { +class EXPCL_PANDA_DOWNLOADER BioStreamPtr : public ReferenceCount { public: INLINE BioStreamPtr(BioStream *stream); virtual ~BioStreamPtr(); diff --git a/panda/src/downloader/chunkedStream.cxx b/panda/src/downloader/chunkedStream.cxx index 2b6f316c0b..279aed870d 100644 --- a/panda/src/downloader/chunkedStream.cxx +++ b/panda/src/downloader/chunkedStream.cxx @@ -21,9 +21,9 @@ */ IChunkedStream:: ~IChunkedStream() { - if (_channel != (HTTPChannel *)NULL) { + if (_channel != nullptr) { _channel->body_stream_destructs(this); - _channel = NULL; + _channel = nullptr; } } diff --git a/panda/src/downloader/chunkedStreamBuf.I b/panda/src/downloader/chunkedStreamBuf.I index b890d7349b..5942bb0f48 100644 --- a/panda/src/downloader/chunkedStreamBuf.I +++ b/panda/src/downloader/chunkedStreamBuf.I @@ -16,7 +16,7 @@ */ INLINE bool ChunkedStreamBuf:: is_closed() const { - return (_source == (BioStreamPtr *)NULL || (*_source)->is_closed()); + return (_source == nullptr || (*_source)->is_closed()); } /** diff --git a/panda/src/downloader/chunkedStreamBuf.cxx b/panda/src/downloader/chunkedStreamBuf.cxx index 9464a9c730..f9580b8e91 100644 --- a/panda/src/downloader/chunkedStreamBuf.cxx +++ b/panda/src/downloader/chunkedStreamBuf.cxx @@ -18,11 +18,6 @@ // This module is not compiled if OpenSSL is not available. #ifdef HAVE_OPENSSL -#ifndef HAVE_STREAMSIZE -// Some compilers (notably SGI) don't define this for us -typedef int streamsize; -#endif /* HAVE_STREAMSIZE */ - /** * */ @@ -71,7 +66,7 @@ open_read(BioStreamPtr *source, HTTPChannel *doc) { _read_state = ISocketStream::RS_reading; _doc = doc; - if (_doc != (HTTPChannel *)NULL) { + if (_doc != nullptr) { _read_index = doc->_read_index; _doc->_transfer_file_size = 0; _doc->_got_transfer_file_size = true; @@ -136,7 +131,7 @@ read_chars(char *start, size_t length) { if (_chunk_remaining != 0) { // Extract some of the bytes remaining in the chunk. - length = min(length, _chunk_remaining); + length = std::min(length, _chunk_remaining); (*_source)->read(start, length); size_t read_count = (*_source)->gcount(); if (!_wanted_nonblocking) { @@ -158,7 +153,7 @@ read_chars(char *start, size_t length) { } // Read the next chunk. - string line; + std::string line; bool got_line = http_getline(line); while (got_line && line.empty()) { // Skip blank lines. There really should be exactly one blank line, but @@ -181,7 +176,7 @@ read_chars(char *start, size_t length) { return 0; } - size_t chunk_size = (size_t)strtol(line.c_str(), NULL, 16); + size_t chunk_size = (size_t)strtol(line.c_str(), nullptr, 16); if (downloader_cat.is_spam()) { downloader_cat.spam() << "Got chunk of size " << chunk_size << " bytes.\n"; @@ -190,7 +185,7 @@ read_chars(char *start, size_t length) { if (chunk_size == 0) { // Last chunk; we're done. _done = true; - if (_doc != (HTTPChannel *)NULL && _read_index == _doc->_read_index) { + if (_doc != nullptr && _read_index == _doc->_read_index) { _doc->_file_size = _doc->_transfer_file_size; _doc->_got_file_size = true; } @@ -198,7 +193,7 @@ read_chars(char *start, size_t length) { return 0; } - if (_doc != (HTTPChannel *)NULL && _read_index == _doc->_read_index) { + if (_doc != nullptr && _read_index == _doc->_read_index) { _doc->_transfer_file_size += chunk_size; } @@ -217,7 +212,7 @@ read_chars(char *start, size_t length) { * received or if the connection has been closed. */ bool ChunkedStreamBuf:: -http_getline(string &str) { +http_getline(std::string &str) { nassertr(!_source.is_null(), false); int ch = (*_source)->get(); while (!(*_source)->eof() && !(*_source)->fail()) { @@ -225,7 +220,7 @@ http_getline(string &str) { case '\n': // end-of-line character, we're done. str = _working_getline; - _working_getline = string(); + _working_getline = std::string(); { // Trim trailing whitespace. We're not required to do this per the // HTTP spec, but let's be generous. diff --git a/panda/src/downloader/chunkedStreamBuf.h b/panda/src/downloader/chunkedStreamBuf.h index 675914772c..fbcde6797d 100644 --- a/panda/src/downloader/chunkedStreamBuf.h +++ b/panda/src/downloader/chunkedStreamBuf.h @@ -26,7 +26,7 @@ /** * The streambuf object that implements IChunkedStream. */ -class ChunkedStreamBuf : public streambuf { +class ChunkedStreamBuf : public std::streambuf { // No need to export from DLL. public: ChunkedStreamBuf(); @@ -43,13 +43,13 @@ protected: private: size_t read_chars(char *start, size_t length); - bool http_getline(string &str); + bool http_getline(std::string &str); PT(BioStreamPtr) _source; size_t _chunk_remaining; bool _done; bool _wanted_nonblocking; - string _working_getline; + std::string _working_getline; ISocketStream::ReadState _read_state; PT(HTTPChannel) _doc; diff --git a/panda/src/downloader/config_downloader.cxx b/panda/src/downloader/config_downloader.cxx index 9c806dba07..4e60b4028c 100644 --- a/panda/src/downloader/config_downloader.cxx +++ b/panda/src/downloader/config_downloader.cxx @@ -19,8 +19,8 @@ #include "pandaSystem.h" -#if !defined(CPPPARSER) && !defined(BUILDING_PANDAEXPRESS) - #error Buildsystem error: BUILDING_PANDAEXPRESS not defined +#if !defined(CPPPARSER) && !defined(BUILDING_PANDA_DOWNLOADER) + #error Buildsystem error: BUILDING_PANDA_DOWNLOADER not defined #endif ConfigureDef(config_downloader); diff --git a/panda/src/downloader/config_downloader.h b/panda/src/downloader/config_downloader.h index 2ffd9be37a..6a6ea1dfb7 100644 --- a/panda/src/downloader/config_downloader.h +++ b/panda/src/downloader/config_downloader.h @@ -24,8 +24,8 @@ #include "configVariableFilename.h" #include "configVariableList.h" -ConfigureDecl(config_downloader, EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS); -NotifyCategoryDecl(downloader, EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS); +ConfigureDecl(config_downloader, EXPCL_PANDA_DOWNLOADER, EXPTP_PANDA_DOWNLOADER); +NotifyCategoryDecl(downloader, EXPCL_PANDA_DOWNLOADER, EXPTP_PANDA_DOWNLOADER); extern ConfigVariableInt downloader_byte_rate; extern ConfigVariableBool download_throttle; @@ -44,9 +44,9 @@ extern ConfigVariableInt http_skip_body_size; extern ConfigVariableDouble http_idle_timeout; extern ConfigVariableInt http_max_connect_count; -extern EXPCL_PANDAEXPRESS ConfigVariableInt tcp_header_size; -extern EXPCL_PANDAEXPRESS ConfigVariableBool support_ipv6; +extern EXPCL_PANDA_DOWNLOADER ConfigVariableInt tcp_header_size; +extern EXPCL_PANDA_DOWNLOADER ConfigVariableBool support_ipv6; -extern EXPCL_PANDAEXPRESS void init_libdownloader(); +extern EXPCL_PANDA_DOWNLOADER void init_libdownloader(); #endif diff --git a/panda/src/downloader/decompressor.cxx b/panda/src/downloader/decompressor.cxx index da78e19fa3..272279047d 100644 --- a/panda/src/downloader/decompressor.cxx +++ b/panda/src/downloader/decompressor.cxx @@ -34,9 +34,9 @@ */ Decompressor:: Decompressor() { - _source = NULL; - _decompress = NULL; - _dest = NULL; + _source = nullptr; + _decompress = nullptr; + _dest = nullptr; } /** @@ -54,7 +54,7 @@ Decompressor:: */ int Decompressor:: initiate(const Filename &source_file) { - string extension = source_file.get_extension(); + std::string extension = source_file.get_extension(); if (extension == "pz" || extension == "gz") { Filename dest_file = source_file; dest_file = source_file.get_fullpath_wo_extension(); @@ -64,7 +64,7 @@ initiate(const Filename &source_file) { if (downloader_cat.is_debug()) { downloader_cat.debug() << "Unknown file extension for decompressor: ." - << extension << endl; + << extension << std::endl; } return EU_error_abort; } @@ -90,14 +90,14 @@ initiate(const Filename &source_file, const Filename &dest_file) { } // Determine source file length - source_pfstream->seekg(0, ios::end); + source_pfstream->seekg(0, std::ios::end); _source_length = source_pfstream->tellg(); if (_source_length == 0) { downloader_cat.warning() << "Zero length file: " << source_file << "\n"; return EU_error_file_empty; } - source_pfstream->seekg(0, ios::beg); + source_pfstream->seekg(0, std::ios::beg); // Open destination file Filename dest_filename(dest_file); @@ -137,7 +137,7 @@ initiate(const Filename &source_file, const Filename &dest_file) { */ int Decompressor:: run() { - if (_decompress == (istream *)NULL) { + if (_decompress == nullptr) { // Hmm, we were already done. return EU_success; } @@ -201,8 +201,8 @@ decompress(const Filename &source_file) { */ bool Decompressor:: decompress(Ramfile &source_and_dest_file) { - istringstream source(source_and_dest_file._data); - ostringstream dest; + std::istringstream source(source_and_dest_file._data); + std::ostringstream dest; IDecompressStream decompress(&source, false); @@ -222,7 +222,7 @@ decompress(Ramfile &source_and_dest_file) { */ PN_stdfloat Decompressor:: get_progress() const { - if (_decompress == (istream *)NULL) { + if (_decompress == nullptr) { // Hmm, we were already done. return 1.0f; } @@ -240,17 +240,17 @@ get_progress() const { */ void Decompressor:: cleanup() { - if (_source != (istream *)NULL) { + if (_source != nullptr) { delete _source; - _source = NULL; + _source = nullptr; } - if (_dest != (ostream *)NULL) { + if (_dest != nullptr) { delete _dest; - _dest = NULL; + _dest = nullptr; } - if (_decompress != (istream *)NULL) { + if (_decompress != nullptr) { delete _decompress; - _decompress = NULL; + _decompress = nullptr; } } diff --git a/panda/src/downloader/decompressor.h b/panda/src/downloader/decompressor.h index fe15352355..16fe2d65fb 100644 --- a/panda/src/downloader/decompressor.h +++ b/panda/src/downloader/decompressor.h @@ -26,7 +26,7 @@ class Ramfile; * This manages run-time decompression of a zlib-compressed stream, as a * background or foreground task. */ -class EXPCL_PANDAEXPRESS Decompressor { +class EXPCL_PANDA_DOWNLOADER Decompressor { PUBLISHED: Decompressor(); ~Decompressor(); @@ -48,9 +48,9 @@ private: Filename _source_filename; - istream *_source; - istream *_decompress; - ostream *_dest; + std::istream *_source; + std::istream *_decompress; + std::ostream *_dest; size_t _source_length; }; diff --git a/panda/src/downloader/documentSpec.I b/panda/src/downloader/documentSpec.I index aeb962671d..3077ac2848 100644 --- a/panda/src/downloader/documentSpec.I +++ b/panda/src/downloader/documentSpec.I @@ -25,7 +25,7 @@ DocumentSpec() { * */ INLINE DocumentSpec:: -DocumentSpec(const string &url) : +DocumentSpec(const std::string &url) : _url(url) { _request_mode = RM_any; @@ -262,16 +262,16 @@ get_cache_control() const { return _cache_control; } -INLINE istream & -operator >> (istream &in, DocumentSpec &doc) { +INLINE std::istream & +operator >> (std::istream &in, DocumentSpec &doc) { if (!doc.input(in)) { - in.clear(ios::failbit | in.rdstate()); + in.clear(std::ios::failbit | in.rdstate()); } return in; } -INLINE ostream & -operator << (ostream &out, const DocumentSpec &doc) { +INLINE std::ostream & +operator << (std::ostream &out, const DocumentSpec &doc) { doc.output(out); return out; } diff --git a/panda/src/downloader/documentSpec.cxx b/panda/src/downloader/documentSpec.cxx index b9ccc7097d..6ca2a9b260 100644 --- a/panda/src/downloader/documentSpec.cxx +++ b/panda/src/downloader/documentSpec.cxx @@ -51,7 +51,7 @@ compare_to(const DocumentSpec &other) const { * output() or write(). Returns true on success, false on failure. */ bool DocumentSpec:: -input(istream &in) { +input(std::istream &in) { // First, clear the spec. (*this) = DocumentSpec(); @@ -64,7 +64,7 @@ input(istream &in) { in >> ch; if (ch == '(') { // Scan the tag, up to but not including the closing paren. - string tag; + std::string tag; in >> ch; while (!in.fail() && !in.eof() && ch != ')') { tag += ch; @@ -80,7 +80,7 @@ input(istream &in) { // Scan the date, up to but not including the closing bracket. if (ch != ']') { - string date; + std::string date; while (!in.fail() && !in.eof() && ch != ']') { date += ch; ch = in.get(); @@ -99,7 +99,7 @@ input(istream &in) { * */ void DocumentSpec:: -output(ostream &out) const { +output(std::ostream &out) const { out << "[ " << get_url(); if (has_tag()) { out << " (" << get_tag() << ")"; @@ -114,7 +114,7 @@ output(ostream &out) const { * */ void DocumentSpec:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "[ " << get_url(); if (has_tag()) { diff --git a/panda/src/downloader/documentSpec.h b/panda/src/downloader/documentSpec.h index 8fd205ef9b..e78b2eca62 100644 --- a/panda/src/downloader/documentSpec.h +++ b/panda/src/downloader/documentSpec.h @@ -27,10 +27,10 @@ * The DocumentSpec may also be used to request a newer document than a * particular one if available, for instance to refresh a cached document. */ -class EXPCL_PANDAEXPRESS DocumentSpec { +class EXPCL_PANDA_DOWNLOADER DocumentSpec { PUBLISHED: INLINE DocumentSpec(); - INLINE DocumentSpec(const string &url); + INLINE DocumentSpec(const std::string &url); INLINE DocumentSpec(const URLSpec &url); INLINE DocumentSpec(const DocumentSpec ©); INLINE void operator = (const DocumentSpec ©); @@ -72,9 +72,9 @@ PUBLISHED: INLINE void set_cache_control(CacheControl cache_control); INLINE CacheControl get_cache_control() const; - bool input(istream &in); - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + bool input(std::istream &in); + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; PUBLISHED: MAKE_PROPERTY(url, get_url, set_url); @@ -98,8 +98,8 @@ private: int _flags; }; -INLINE istream &operator >> (istream &in, DocumentSpec &doc); -INLINE ostream &operator << (ostream &out, const DocumentSpec &doc); +INLINE std::istream &operator >> (std::istream &in, DocumentSpec &doc); +INLINE std::ostream &operator << (std::ostream &out, const DocumentSpec &doc); #include "documentSpec.I" diff --git a/panda/src/downloader/downloadDb.I b/panda/src/downloader/downloadDb.I index a97e1d7595..f2312be537 100644 --- a/panda/src/downloader/downloadDb.I +++ b/panda/src/downloader/downloadDb.I @@ -30,7 +30,7 @@ get_server_num_multifiles() const { /** * */ -INLINE string DownloadDb:: +INLINE std::string DownloadDb:: get_client_multifile_name(int index) const { return _client_db.get_multifile_name(index); } @@ -38,7 +38,7 @@ get_client_multifile_name(int index) const { /** * */ -INLINE string DownloadDb:: +INLINE std::string DownloadDb:: get_server_multifile_name(int index) const { return _server_db.get_multifile_name(index); } @@ -48,7 +48,7 @@ get_server_multifile_name(int index) const { * */ INLINE Phase DownloadDb:: -get_client_multifile_phase(string mfname) const { +get_client_multifile_phase(std::string mfname) const { return (_client_db.get_multifile_record_named(mfname))->_phase; } @@ -56,7 +56,7 @@ get_client_multifile_phase(string mfname) const { * */ INLINE Phase DownloadDb:: -get_server_multifile_phase(string mfname) const { +get_server_multifile_phase(std::string mfname) const { return (_server_db.get_multifile_record_named(mfname))->_phase; } @@ -66,7 +66,7 @@ get_server_multifile_phase(string mfname) const { * */ INLINE int DownloadDb:: -get_client_multifile_size(string mfname) const { +get_client_multifile_size(std::string mfname) const { return (_client_db.get_multifile_record_named(mfname))->_size; } @@ -74,7 +74,7 @@ get_client_multifile_size(string mfname) const { * */ INLINE void DownloadDb:: -set_client_multifile_size(string mfname, int size) { +set_client_multifile_size(std::string mfname, int size) { (_client_db.get_multifile_record_named(mfname))->_size = size; write_client_db(_client_db._filename); } @@ -84,7 +84,7 @@ set_client_multifile_size(string mfname, int size) { * */ INLINE int DownloadDb:: -set_client_multifile_delta_size(string mfname, int size) { +set_client_multifile_delta_size(std::string mfname, int size) { (_client_db.get_multifile_record_named(mfname))->_size += size; write_client_db(_client_db._filename); // Return the new total @@ -97,7 +97,7 @@ set_client_multifile_delta_size(string mfname, int size) { * */ INLINE int DownloadDb:: -get_server_multifile_size(string mfname) const { +get_server_multifile_size(std::string mfname) const { return (_server_db.get_multifile_record_named(mfname))->_size; } @@ -106,7 +106,7 @@ get_server_multifile_size(string mfname) const { * */ INLINE void DownloadDb:: -set_server_multifile_size(string mfname, int size) { +set_server_multifile_size(std::string mfname, int size) { (_server_db.get_multifile_record_named(mfname))->_size = size; } @@ -115,7 +115,7 @@ set_server_multifile_size(string mfname, int size) { * */ INLINE void DownloadDb:: -set_client_multifile_incomplete(string mfname) { +set_client_multifile_incomplete(std::string mfname) { (_client_db.get_multifile_record_named(mfname))->_status = Status_incomplete; write_client_db(_client_db._filename); } @@ -124,7 +124,7 @@ set_client_multifile_incomplete(string mfname) { * */ INLINE void DownloadDb:: -set_client_multifile_complete(string mfname) { +set_client_multifile_complete(std::string mfname) { (_client_db.get_multifile_record_named(mfname))->_status = Status_complete; write_client_db(_client_db._filename); } @@ -133,7 +133,7 @@ set_client_multifile_complete(string mfname) { * */ INLINE void DownloadDb:: -set_client_multifile_decompressed(string mfname) { +set_client_multifile_decompressed(std::string mfname) { (_client_db.get_multifile_record_named(mfname))->_status = Status_decompressed; write_client_db(_client_db._filename); } @@ -142,7 +142,7 @@ set_client_multifile_decompressed(string mfname) { * */ INLINE void DownloadDb:: -set_client_multifile_extracted(string mfname) { +set_client_multifile_extracted(std::string mfname) { (_client_db.get_multifile_record_named(mfname))->_status = Status_extracted; write_client_db(_client_db._filename); } @@ -151,14 +151,14 @@ set_client_multifile_extracted(string mfname) { * */ INLINE int DownloadDb:: -get_server_num_files(string mfname) const { +get_server_num_files(std::string mfname) const { return (_server_db.get_multifile_record_named(mfname))->get_num_files(); } /** * */ -INLINE string DownloadDb:: -get_server_file_name(string mfname, int index) const { +INLINE std::string DownloadDb:: +get_server_file_name(std::string mfname, int index) const { return (_server_db.get_multifile_record_named(mfname))->get_file_name(index); } diff --git a/panda/src/downloader/downloadDb.cxx b/panda/src/downloader/downloadDb.cxx index a210fba8bd..0679614c8b 100644 --- a/panda/src/downloader/downloadDb.cxx +++ b/panda/src/downloader/downloadDb.cxx @@ -20,6 +20,13 @@ #include +using std::endl; +using std::istream; +using std::istringstream; +using std::move; +using std::ostream; +using std::string; + // Defines // Written at the top of the file so we know this is a downloadDb @@ -253,7 +260,7 @@ read_db(Filename &file, bool want_server_info) { file.set_binary(); istream *read_stream = vfs->open_read_file(file, true); - if (read_stream == (istream *)NULL) { + if (read_stream == nullptr) { downloader_cat.error() << "failed to open input file: " << file << endl; diff --git a/panda/src/downloader/downloadDb.h b/panda/src/downloader/downloadDb.h index b7f206c3b6..a6bd580446 100644 --- a/panda/src/downloader/downloadDb.h +++ b/panda/src/downloader/downloadDb.h @@ -59,7 +59,7 @@ MultifileRecord is a Vector * the files on the client system, and another copy for the server, * representing the files the server has available. */ -class EXPCL_PANDAEXPRESS DownloadDb { +class EXPCL_PANDA_DOWNLOADER DownloadDb { PUBLISHED: // Status of a multifile is stored in this enum Note these values are in // increasing order of "doneness" So if you are decompressed, you are @@ -76,9 +76,9 @@ PUBLISHED: explicit DownloadDb(Filename &server_file, Filename &client_file); ~DownloadDb(); - void output(ostream &out) const; - void write(ostream &out) const; - void write_version_map(ostream &out) const; + void output(std::ostream &out) const; + void write(std::ostream &out) const; + void write_version_map(std::ostream &out) const; // Write a database file bool write_client_db(Filename &file); @@ -87,71 +87,71 @@ PUBLISHED: INLINE int get_client_num_multifiles() const; INLINE int get_server_num_multifiles() const; - INLINE string get_client_multifile_name(int index) const; - INLINE string get_server_multifile_name(int index) const; + INLINE std::string get_client_multifile_name(int index) const; + INLINE std::string get_server_multifile_name(int index) const; - INLINE int get_client_multifile_size(string mfname) const; - INLINE void set_client_multifile_size(string mfname, int size); - INLINE int set_client_multifile_delta_size(string mfname, int size); - INLINE int get_server_multifile_size(string mfname) const; - INLINE void set_server_multifile_size(string mfname, int size); + INLINE int get_client_multifile_size(std::string mfname) const; + INLINE void set_client_multifile_size(std::string mfname, int size); + INLINE int set_client_multifile_delta_size(std::string mfname, int size); + INLINE int get_server_multifile_size(std::string mfname) const; + INLINE void set_server_multifile_size(std::string mfname, int size); - INLINE Phase get_client_multifile_phase(string mfname) const; - INLINE Phase get_server_multifile_phase(string mfname) const; + INLINE Phase get_client_multifile_phase(std::string mfname) const; + INLINE Phase get_server_multifile_phase(std::string mfname) const; - INLINE void set_client_multifile_incomplete(string mfname); - INLINE void set_client_multifile_complete(string mfname); - INLINE void set_client_multifile_decompressed(string mfname); - INLINE void set_client_multifile_extracted(string mfname); + INLINE void set_client_multifile_incomplete(std::string mfname); + INLINE void set_client_multifile_complete(std::string mfname); + INLINE void set_client_multifile_decompressed(std::string mfname); + INLINE void set_client_multifile_extracted(std::string mfname); - INLINE int get_server_num_files(string mfname) const; - INLINE string get_server_file_name(string mfname, int index) const; + INLINE int get_server_num_files(std::string mfname) const; + INLINE std::string get_server_file_name(std::string mfname, int index) const; // Queries from the Launcher - bool client_multifile_exists(string mfname) const; - bool client_multifile_complete(string mfname) const; - bool client_multifile_decompressed(string mfname) const; - bool client_multifile_extracted(string mfname) const; + bool client_multifile_exists(std::string mfname) const; + bool client_multifile_complete(std::string mfname) const; + bool client_multifile_decompressed(std::string mfname) const; + bool client_multifile_extracted(std::string mfname) const; // Ask what version (told with the hash) this multifile is - HashVal get_client_multifile_hash(string mfname) const; - void set_client_multifile_hash(string mfname, HashVal val); - HashVal get_server_multifile_hash(string mfname) const; - void set_server_multifile_hash(string mfname, HashVal val); + HashVal get_client_multifile_hash(std::string mfname) const; + void set_client_multifile_hash(std::string mfname, HashVal val); + HashVal get_server_multifile_hash(std::string mfname) const; + void set_server_multifile_hash(std::string mfname, HashVal val); // Operations on multifiles - void delete_client_multifile(string mfname); - void add_client_multifile(string server_mfname); - void expand_client_multifile(string mfname); + void delete_client_multifile(std::string mfname); + void add_client_multifile(std::string server_mfname); + void expand_client_multifile(std::string mfname); // Server side operations to create multifile records void create_new_server_db(); - void server_add_multifile(string mfname, Phase phase, int size, int status); - void server_add_file(string mfname, string fname); + void server_add_multifile(std::string mfname, Phase phase, int size, int status); + void server_add_file(std::string mfname, std::string fname); public: - class EXPCL_PANDAEXPRESS FileRecord : public ReferenceCount { + class EXPCL_PANDA_DOWNLOADER FileRecord : public ReferenceCount { public: FileRecord(); - FileRecord(string name); - void write(ostream &out) const; - string _name; + FileRecord(std::string name); + void write(std::ostream &out) const; + std::string _name; }; typedef pvector< PT(FileRecord) > FileRecords; - class EXPCL_PANDAEXPRESS MultifileRecord : public ReferenceCount { + class EXPCL_PANDA_DOWNLOADER MultifileRecord : public ReferenceCount { public: MultifileRecord(); - MultifileRecord(string name, Phase phase, int size, int status); - void write(ostream &out) const; + MultifileRecord(std::string name, Phase phase, int size, int status); + void write(std::ostream &out) const; int get_num_files() const; - string get_file_name(int index) const; - bool file_exists(string fname) const; - PT(FileRecord) get_file_record_named(string fname) const; + std::string get_file_name(int index) const; + bool file_exists(std::string fname) const; + PT(FileRecord) get_file_record_named(std::string fname) const; void add_file_record(PT(FileRecord) fr); - string _name; + std::string _name; Phase _phase; int _size; int _status; @@ -162,14 +162,14 @@ public: typedef pvector< PT(MultifileRecord) > MultifileRecords; - class EXPCL_PANDAEXPRESS Db { + class EXPCL_PANDA_DOWNLOADER Db { public: Db(); - void write(ostream &out) const; + void write(std::ostream &out) const; int get_num_multifiles() const; - string get_multifile_name(int index) const; - bool multifile_exists(string mfname) const; - PT(MultifileRecord) get_multifile_record_named(string mfname) const; + std::string get_multifile_name(int index) const; + bool multifile_exists(std::string mfname) const; + PT(MultifileRecord) get_multifile_record_named(std::string mfname) const; void add_multifile_record(PT(MultifileRecord) mfr); int parse_header(Datagram dg); int parse_record_header(Datagram dg); @@ -179,7 +179,7 @@ public: bool write(StreamWriter &sw, bool want_server_info); Filename _filename; MultifileRecords _mfile_records; - bool write_header(ostream &write_stream); + bool write_header(std::ostream &write_stream); bool write_bogus_header(StreamWriter &sw); private: int32_t _header_length; @@ -218,7 +218,7 @@ protected: VersionMap _versions; }; -INLINE ostream &operator << (ostream &out, const DownloadDb &dldb) { +INLINE std::ostream &operator << (std::ostream &out, const DownloadDb &dldb) { dldb.output(out); return out; } diff --git a/panda/src/downloader/download_utils.cxx b/panda/src/downloader/download_utils.cxx index e090627362..ebeec3a97c 100644 --- a/panda/src/downloader/download_utils.cxx +++ b/panda/src/downloader/download_utils.cxx @@ -19,13 +19,15 @@ #include "config_downloader.h" #include +using std::ios; + unsigned long check_crc(Filename name) { pifstream read_stream; name.set_binary(); if (!name.open_read(read_stream)) { downloader_cat.error() - << "check_crc() - Failed to open input file: " << name << endl; + << "check_crc() - Failed to open input file: " << name << std::endl; return 0; } @@ -51,7 +53,7 @@ check_adler(Filename name) { name.set_binary(); if (!name.open_read(read_stream)) { downloader_cat.error() - << "check_adler() - Failed to open input file: " << name << endl; + << "check_adler() - Failed to open input file: " << name << std::endl; return 0; } diff --git a/panda/src/downloader/download_utils.h b/panda/src/downloader/download_utils.h index cd27e86666..f3167bf537 100644 --- a/panda/src/downloader/download_utils.h +++ b/panda/src/downloader/download_utils.h @@ -21,8 +21,8 @@ BEGIN_PUBLISH -EXPCL_PANDAEXPRESS unsigned long check_crc(Filename name); -EXPCL_PANDAEXPRESS unsigned long check_adler(Filename name); +EXPCL_PANDA_DOWNLOADER unsigned long check_crc(Filename name); +EXPCL_PANDA_DOWNLOADER unsigned long check_adler(Filename name); END_PUBLISH diff --git a/panda/src/downloader/extractor.cxx b/panda/src/downloader/extractor.cxx index d387b51dd2..a78e9a340d 100644 --- a/panda/src/downloader/extractor.cxx +++ b/panda/src/downloader/extractor.cxx @@ -63,9 +63,9 @@ set_extract_dir(const Filename &extract_dir) { void Extractor:: reset() { if (_initiated) { - if (_read != (istream *)NULL) { + if (_read != nullptr) { Multifile::close_read_subfile(_read); - _read = (istream *)NULL; + _read = nullptr; } _write.close(); _initiated = false; @@ -125,7 +125,7 @@ step() { _subfile_pos = 0; _subfile_length = 0; _total_bytes_extracted = 0; - _read = (istream *)NULL; + _read = nullptr; _initiated = true; } @@ -134,7 +134,7 @@ step() { double finish = now + extractor_step_time; do { - if (_read == (istream *)NULL) { + if (_read == nullptr) { // Time to open the next subfile. if (_request_index >= (int)_requests.size()) { // All done! @@ -167,7 +167,7 @@ step() { _subfile_length = _multifile->get_subfile_length(_subfile_index); _subfile_pos = 0; _read = _multifile->open_read_subfile(_subfile_index); - if (_read == (istream *)NULL) { + if (_read == nullptr) { downloader_cat.error() << "Unable to read subfile " << _multifile->get_subfile_name(_subfile_index) << ".\n"; @@ -183,7 +183,7 @@ step() { << "Finished current subfile.\n"; } Multifile::close_read_subfile(_read); - _read = (istream *)NULL; + _read = nullptr; _write.close(); _request_index++; @@ -192,7 +192,7 @@ step() { static const size_t buffer_size = 1024; char buffer[buffer_size]; - size_t max_bytes = min(buffer_size, _subfile_length - _subfile_pos); + size_t max_bytes = std::min(buffer_size, _subfile_length - _subfile_pos); _read->read(buffer, max_bytes); size_t count = _read->gcount(); while (count != 0) { @@ -217,7 +217,7 @@ step() { return EU_ok; } - max_bytes = min(buffer_size, _subfile_length - _subfile_pos); + max_bytes = std::min(buffer_size, _subfile_length - _subfile_pos); _read->read(buffer, max_bytes); count = _read->gcount(); } diff --git a/panda/src/downloader/extractor.h b/panda/src/downloader/extractor.h index 0747eed350..de89351a88 100644 --- a/panda/src/downloader/extractor.h +++ b/panda/src/downloader/extractor.h @@ -32,7 +32,7 @@ * Multifile. Call run() whenever you have spare cycles until run() returns * EU_success. */ -class EXPCL_PANDAEXPRESS Extractor { +class EXPCL_PANDA_DOWNLOADER Extractor { PUBLISHED: Extractor(); ~Extractor(); @@ -71,7 +71,7 @@ private: size_t _subfile_pos; size_t _subfile_length; size_t _total_bytes_extracted; - istream *_read; + std::istream *_read; pofstream _write; Filename _subfile_filename; }; diff --git a/panda/src/downloader/httpAuthorization.I b/panda/src/downloader/httpAuthorization.I index bc105214df..5c00fa3724 100644 --- a/panda/src/downloader/httpAuthorization.I +++ b/panda/src/downloader/httpAuthorization.I @@ -16,7 +16,7 @@ * supplied string that may have meaning to the user, and describes the * general collection of things protected by this password. */ -const string &HTTPAuthorization:: +const std::string &HTTPAuthorization:: get_realm() const { return _realm; } diff --git a/panda/src/downloader/httpAuthorization.cxx b/panda/src/downloader/httpAuthorization.cxx index d067b96d97..081f16532d 100644 --- a/panda/src/downloader/httpAuthorization.cxx +++ b/panda/src/downloader/httpAuthorization.cxx @@ -17,6 +17,8 @@ #ifdef HAVE_OPENSSL +using std::string; + static const char base64_table[64] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', diff --git a/panda/src/downloader/httpAuthorization.h b/panda/src/downloader/httpAuthorization.h index 4ac0457242..65d49d7366 100644 --- a/panda/src/downloader/httpAuthorization.h +++ b/panda/src/downloader/httpAuthorization.h @@ -33,10 +33,10 @@ class URLSpec; * in the past, which can possibly be re-used for future requests to the same * server. */ -class EXPCL_PANDAEXPRESS HTTPAuthorization : public ReferenceCount { +class EXPCL_PANDA_DOWNLOADER HTTPAuthorization : public ReferenceCount { public: - typedef pmap Tokens; - typedef pmap AuthenticationSchemes; + typedef pmap Tokens; + typedef pmap AuthenticationSchemes; protected: HTTPAuthorization(const Tokens &tokens, const URLSpec &url, @@ -44,28 +44,28 @@ protected: public: virtual ~HTTPAuthorization(); - virtual const string &get_mechanism() const=0; + virtual const std::string &get_mechanism() const=0; virtual bool is_valid(); - INLINE const string &get_realm() const; + INLINE const std::string &get_realm() const; INLINE const vector_string &get_domain() const; - virtual string generate(HTTPEnum::Method method, const string &request_path, - const string &username, const string &body)=0; + virtual std::string generate(HTTPEnum::Method method, const std::string &request_path, + const std::string &username, const std::string &body)=0; static void parse_authentication_schemes(AuthenticationSchemes &schemes, - const string &field_value); + const std::string &field_value); static URLSpec get_canonical_url(const URLSpec &url); - static string base64_encode(const string &s); - static string base64_decode(const string &s); + static std::string base64_encode(const std::string &s); + static std::string base64_decode(const std::string &s); protected: - static size_t scan_quoted_or_unquoted_string(string &result, - const string &source, + static size_t scan_quoted_or_unquoted_string(std::string &result, + const std::string &source, size_t start); protected: - string _realm; + std::string _realm; vector_string _domain; }; diff --git a/panda/src/downloader/httpBasicAuthorization.cxx b/panda/src/downloader/httpBasicAuthorization.cxx index 8e86c25a94..a8abd67979 100644 --- a/panda/src/downloader/httpBasicAuthorization.cxx +++ b/panda/src/downloader/httpBasicAuthorization.cxx @@ -15,6 +15,8 @@ #ifdef HAVE_OPENSSL +using std::string; + const string HTTPBasicAuthorization::_mechanism = "basic"; /** diff --git a/panda/src/downloader/httpBasicAuthorization.h b/panda/src/downloader/httpBasicAuthorization.h index 2d18a29a25..92e85bb3ab 100644 --- a/panda/src/downloader/httpBasicAuthorization.h +++ b/panda/src/downloader/httpBasicAuthorization.h @@ -36,12 +36,12 @@ public: bool is_proxy); virtual ~HTTPBasicAuthorization(); - virtual const string &get_mechanism() const; - virtual string generate(HTTPEnum::Method method, const string &request_path, - const string &username, const string &body); + virtual const std::string &get_mechanism() const; + virtual std::string generate(HTTPEnum::Method method, const std::string &request_path, + const std::string &username, const std::string &body); private: - static const string _mechanism; + static const std::string _mechanism; }; #include "httpBasicAuthorization.I" diff --git a/panda/src/downloader/httpChannel.I b/panda/src/downloader/httpChannel.I index 1a254e478a..1fdd7e32f2 100644 --- a/panda/src/downloader/httpChannel.I +++ b/panda/src/downloader/httpChannel.I @@ -76,7 +76,7 @@ get_http_version() const { * Returns the HTTP version number returned by the server, formatted as a * string, e.g. "HTTP/1.1". */ -INLINE const string &HTTPChannel:: +INLINE const std::string &HTTPChannel:: get_http_version_string() const { return _http_version_string; } @@ -103,7 +103,7 @@ get_status_code() const { * presented to the user to request an associated username and password (which * then should be stored in HTTPClient::set_username()). */ -INLINE const string &HTTPChannel:: +INLINE const std::string &HTTPChannel:: get_www_realm() const { return _www_realm; } @@ -114,7 +114,7 @@ get_www_realm() const { * string may be presented to the user to request an associated username and * password (which then should be stored in HTTPClient::set_username()). */ -INLINE const string &HTTPChannel:: +INLINE const std::string &HTTPChannel:: get_proxy_realm() const { return _proxy_realm; } @@ -431,14 +431,14 @@ get_max_updates_per_second() const { * different types of content, such as JSON. */ INLINE void HTTPChannel:: -set_content_type(string content_type) { +set_content_type(std::string content_type) { _content_type = content_type; } /** * Returns the value of the Content-Type header. */ -INLINE string HTTPChannel:: +INLINE std::string HTTPChannel:: get_content_type() const { return _content_type; } @@ -555,7 +555,7 @@ preserve_status() { */ INLINE void HTTPChannel:: clear_extra_headers() { - _send_extra_headers = string(); + _send_extra_headers = std::string(); } /** @@ -568,7 +568,7 @@ clear_extra_headers() { * request. */ INLINE void HTTPChannel:: -send_extra_header(const string &key, const string &value) { +send_extra_header(const std::string &key, const std::string &value) { _send_extra_headers += key; _send_extra_headers += ": "; _send_extra_headers += value; @@ -581,7 +581,7 @@ send_extra_header(const string &key, const string &value) { */ INLINE bool HTTPChannel:: get_document(const DocumentSpec &url) { - begin_request(HTTPEnum::M_get, url, string(), false, 0, 0); + begin_request(HTTPEnum::M_get, url, std::string(), false, 0, 0); while (run()) { } return is_valid(); @@ -596,7 +596,7 @@ get_document(const DocumentSpec &url) { */ INLINE bool HTTPChannel:: get_subdocument(const DocumentSpec &url, size_t first_byte, size_t last_byte) { - begin_request(HTTPEnum::M_get, url, string(), false, first_byte, last_byte); + begin_request(HTTPEnum::M_get, url, std::string(), false, first_byte, last_byte); while (run()) { } return is_valid(); @@ -610,7 +610,7 @@ get_subdocument(const DocumentSpec &url, size_t first_byte, size_t last_byte) { */ INLINE bool HTTPChannel:: get_header(const DocumentSpec &url) { - begin_request(HTTPEnum::M_head, url, string(), false, 0, 0); + begin_request(HTTPEnum::M_head, url, std::string(), false, 0, 0); while (run()) { } return is_valid(); @@ -620,7 +620,7 @@ get_header(const DocumentSpec &url) { * Posts form data to a particular URL and retrieves the response. */ INLINE bool HTTPChannel:: -post_form(const DocumentSpec &url, const string &body) { +post_form(const DocumentSpec &url, const std::string &body) { begin_request(HTTPEnum::M_post, url, body, false, 0, 0); while (run()) { } @@ -632,7 +632,7 @@ post_form(const DocumentSpec &url, const string &body) { * the server allows this. */ INLINE bool HTTPChannel:: -put_document(const DocumentSpec &url, const string &body) { +put_document(const DocumentSpec &url, const std::string &body) { begin_request(HTTPEnum::M_put, url, body, false, 0, 0); while (run()) { } @@ -644,7 +644,7 @@ put_document(const DocumentSpec &url, const string &body) { */ INLINE bool HTTPChannel:: delete_document(const DocumentSpec &url) { - begin_request(HTTPEnum::M_delete, url, string(), false, 0, 0); + begin_request(HTTPEnum::M_delete, url, std::string(), false, 0, 0); while (run()) { } return is_valid(); @@ -656,7 +656,7 @@ delete_document(const DocumentSpec &url) { */ INLINE bool HTTPChannel:: get_trace(const DocumentSpec &url) { - begin_request(HTTPEnum::M_trace, url, string(), false, 0, 0); + begin_request(HTTPEnum::M_trace, url, std::string(), false, 0, 0); while (run()) { } return is_valid(); @@ -671,7 +671,7 @@ get_trace(const DocumentSpec &url) { */ INLINE bool HTTPChannel:: connect_to(const DocumentSpec &url) { - begin_request(HTTPEnum::M_connect, url, string(), false, 0, 0); + begin_request(HTTPEnum::M_connect, url, std::string(), false, 0, 0); while (run()) { } return is_connection_ready(); @@ -683,7 +683,7 @@ connect_to(const DocumentSpec &url) { */ INLINE bool HTTPChannel:: get_options(const DocumentSpec &url) { - begin_request(HTTPEnum::M_options, url, string(), false, 0, 0); + begin_request(HTTPEnum::M_options, url, std::string(), false, 0, 0); while (run()) { } return is_valid(); @@ -700,7 +700,7 @@ get_options(const DocumentSpec &url) { */ INLINE void HTTPChannel:: begin_get_document(const DocumentSpec &url) { - begin_request(HTTPEnum::M_get, url, string(), true, 0, 0); + begin_request(HTTPEnum::M_get, url, std::string(), true, 0, 0); } /** @@ -713,7 +713,7 @@ begin_get_document(const DocumentSpec &url) { INLINE void HTTPChannel:: begin_get_subdocument(const DocumentSpec &url, size_t first_byte, size_t last_byte) { - begin_request(HTTPEnum::M_get, url, string(), true, first_byte, last_byte); + begin_request(HTTPEnum::M_get, url, std::string(), true, first_byte, last_byte); } /** @@ -722,7 +722,7 @@ begin_get_subdocument(const DocumentSpec &url, size_t first_byte, */ INLINE void HTTPChannel:: begin_get_header(const DocumentSpec &url) { - begin_request(HTTPEnum::M_head, url, string(), true, 0, 0); + begin_request(HTTPEnum::M_head, url, std::string(), true, 0, 0); } /** @@ -735,7 +735,7 @@ begin_get_header(const DocumentSpec &url) { * interim, or your form data may not get posted. */ INLINE void HTTPChannel:: -begin_post_form(const DocumentSpec &url, const string &body) { +begin_post_form(const DocumentSpec &url, const std::string &body) { begin_request(HTTPEnum::M_post, url, body, true, 0, 0); } @@ -753,7 +753,7 @@ begin_post_form(const DocumentSpec &url, const string &body) { */ INLINE void HTTPChannel:: begin_connect_to(const DocumentSpec &url) { - begin_request(HTTPEnum::M_connect, url, string(), true, 0, 0); + begin_request(HTTPEnum::M_connect, url, std::string(), true, 0, 0); } /** diff --git a/panda/src/downloader/httpChannel.cxx b/panda/src/downloader/httpChannel.cxx index 93e04f1432..17c12d806a 100644 --- a/panda/src/downloader/httpChannel.cxx +++ b/panda/src/downloader/httpChannel.cxx @@ -35,6 +35,12 @@ #undef X509_NAME #endif // WIN32_VC +using std::istream; +using std::min; +using std::ostream; +using std::ostringstream; +using std::string; + TypeHandle HTTPChannel::_type_handle; #define _NOTIFY_HTTP_CHANNEL_ID "[" << this << "] " @@ -105,14 +111,14 @@ HTTPChannel(HTTPClient *client) : _done_state = S_new; _started_download = false; _sent_so_far = 0; - _body_stream = NULL; + _body_stream = nullptr; _owns_body_stream = false; - _sbio = NULL; + _sbio = nullptr; _cipher_list = _client->get_cipher_list(); _last_status_code = 0; _last_run_time = 0.0f; - _download_to_ramfile = NULL; - _download_to_stream = NULL; + _download_to_ramfile = nullptr; + _download_to_stream = nullptr; } /** @@ -250,7 +256,7 @@ will_close_connection() const { * requests which can change their minds midstream about how much data they're * sending you. */ -streamsize HTTPChannel:: +std::streamsize HTTPChannel:: get_file_size() const { if (_got_file_size) { return _file_size; @@ -549,7 +555,7 @@ open_read_body() { reset_body_stream(); if ((_state != S_read_header && _state != S_begin_body) || _source.is_null()) { - return NULL; + return nullptr; } string transfer_coding = downcase(get_header_value("Transfer-Encoding")); @@ -588,7 +594,7 @@ open_read_body() { */ void HTTPChannel:: close_read_body(istream *stream) const { - if (stream != (istream *)NULL) { + if (stream != nullptr) { // For some reason--compiler bug in gcc 3.2?--explicitly deleting the // stream pointer does not call the appropriate global delete function; // instead apparently calling the system delete function. So we call the @@ -677,7 +683,7 @@ download_to_file(const Filename &filename, bool subdocument_resumes) { */ bool HTTPChannel:: download_to_ram(Ramfile *ramfile, bool subdocument_resumes) { - nassertr(ramfile != (Ramfile *)NULL, false); + nassertr(ramfile != nullptr, false); reset_download_to(); ramfile->_pos = 0; _download_to_ramfile = ramfile; @@ -762,11 +768,11 @@ download_to_stream(ostream *strm, bool subdocument_resumes) { SocketStream *HTTPChannel:: get_connection() { if (!is_connection_ready()) { - return NULL; + return nullptr; } BioStream *stream = _source->get_stream(); - _source->set_stream(NULL); + _source->set_stream(nullptr); // We're now passing ownership of the connection to the caller. if (downloader_cat.is_debug()) { @@ -814,7 +820,7 @@ body_stream_destructs(ISocketStream *stream) { break; } } - _body_stream = NULL; + _body_stream = nullptr; _owns_body_stream = false; } } @@ -887,7 +893,7 @@ reached_done_state() { } else { // Oops, we have to download the body now. open_read_body(); - if (_body_stream == (ISocketStream *)NULL) { + if (_body_stream == nullptr) { if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID @@ -924,7 +930,7 @@ run_try_next_proxy() { // Now try the next proxy in sequence. _proxy = _proxies[_proxy_next_index]; - _proxy_auth = (HTTPAuthorization *)NULL; + _proxy_auth = nullptr; _proxy_next_index++; close_connection(); reconsider_proxy(); @@ -1023,7 +1029,7 @@ run_connecting_wait() { tv.tv_sec = 0; tv.tv_usec = 0; } - int errcode = select(fd + 1, NULL, &wset, NULL, &tv); + int errcode = select(fd + 1, nullptr, &wset, nullptr, &tv); if (errcode < 0) { downloader_cat.warning() << _NOTIFY_HTTP_CHANNEL_ID @@ -1138,7 +1144,7 @@ run_http_proxy_reading_header() { // 407: not authorized to proxy. Try to get the authorization. string authenticate_request = get_header_value("Proxy-Authenticate"); _proxy_auth = _client->generate_auth(_proxy, true, authenticate_request); - if (_proxy_auth != (HTTPAuthorization *)NULL) { + if (_proxy_auth != nullptr) { _proxy_realm = _proxy_auth->get_realm(); _proxy_username = _client->select_username(_proxy, true, _proxy_realm); if (!_proxy_username.empty()) { @@ -1447,9 +1453,9 @@ run_setup_ssl() { _sbio = BIO_new_ssl(_client->get_ssl_ctx(), true); BIO_push(_sbio, *_bio); - SSL *ssl = NULL; + SSL *ssl = nullptr; BIO_get_ssl(_sbio, &ssl); - nassertr(ssl != (SSL *)NULL, false); + nassertr(ssl != nullptr, false); // We only take one word at a time from the _cipher_list. If that // connection fails, then we take the next word. @@ -1511,7 +1517,7 @@ run_setup_ssl() { const char *name; int pri = 0; name = SSL_get_cipher_list(ssl, pri); - while (name != NULL) { + while (name != nullptr) { downloader_cat.spam() << _NOTIFY_HTTP_CHANNEL_ID << " " << pri + 1 << ". " << name << "\n"; @@ -1585,16 +1591,16 @@ run_ssl_handshake() { return false; } - SSL *ssl = NULL; + SSL *ssl = nullptr; BIO_get_ssl(_sbio, &ssl); - nassertr(ssl != (SSL *)NULL, false); + nassertr(ssl != nullptr, false); if (!_nonblocking) { SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY); } const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl); - if (cipher == (const SSL_CIPHER *)NULL) { + if (cipher == nullptr) { downloader_cat.warning() << _NOTIFY_HTTP_CHANNEL_ID << "No current cipher on SSL connection.\n"; @@ -1609,10 +1615,10 @@ run_ssl_handshake() { // Now that we've made an SSL handshake, we can use the SSL bio to do all of // our communication henceforth. _bio->set_bio(_sbio); - _sbio = NULL; + _sbio = nullptr; X509 *cert = SSL_get_peer_certificate(ssl); - if (cert == (X509 *)NULL) { + if (cert == nullptr) { downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "No certificate was presented by server.\n"; @@ -1637,7 +1643,7 @@ run_ssl_handshake() { if (downloader_cat.is_spam()) { downloader_cat.spam() << _NOTIFY_HTTP_CHANNEL_ID - << "Received certificate from server:\n" << flush; + << "Received certificate from server:\n" << std::flush; X509_print_fp(stderr, cert); fflush(stderr); } @@ -1925,7 +1931,7 @@ run_reading_header() { string authenticate_request = get_header_value("Proxy-Authenticate"); _proxy_auth = _client->generate_auth(_proxy, true, authenticate_request); - if (_proxy_auth != (HTTPAuthorization *)NULL) { + if (_proxy_auth != nullptr) { _proxy_realm = _proxy_auth->get_realm(); _proxy_username = _client->select_username(_proxy, true, _proxy_realm); if (!_proxy_username.empty()) { @@ -1942,7 +1948,7 @@ run_reading_header() { // 401: not authorized to remote server. Try to get the authorization. string authenticate_request = get_header_value("WWW-Authenticate"); _www_auth = _client->generate_auth(_request.get_url(), false, authenticate_request); - if (_www_auth != (HTTPAuthorization *)NULL) { + if (_www_auth != nullptr) { _www_realm = _www_auth->get_realm(); _www_username = _client->select_username(_request.get_url(), false, _www_realm); if (!_www_username.empty()) { @@ -2090,7 +2096,7 @@ run_begin_body() { } else { open_read_body(); - if (_body_stream == (ISocketStream *)NULL) { + if (_body_stream == nullptr) { if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID @@ -2132,7 +2138,7 @@ run_reading_body() { } // Skip the body we've already started. - if (_body_stream == NULL || !_owns_body_stream) { + if (_body_stream == nullptr || !_owns_body_stream) { // Whoops, we're not in skip-body mode. Better reset. if (downloader_cat.is_debug()) { downloader_cat.debug() @@ -2144,14 +2150,14 @@ run_reading_body() { } string line; - getline(*_body_stream, line); + std::getline(*_body_stream, line); while (!_body_stream->fail() && !_body_stream->eof()) { if (downloader_cat.is_spam()) { downloader_cat.spam() << _NOTIFY_HTTP_CHANNEL_ID << "skip: " << line << "\n"; } - getline(*_body_stream, line); + std::getline(*_body_stream, line); } if (!_body_stream->is_closed()) { @@ -2232,7 +2238,7 @@ run_read_trailer() { */ bool HTTPChannel:: run_download_to_file() { - nassertr(_body_stream != (ISocketStream *)NULL && _owns_body_stream, false); + nassertr(_body_stream != nullptr && _owns_body_stream, false); bool do_throttle = _wanted_nonblocking && _download_throttle; @@ -2293,8 +2299,8 @@ run_download_to_file() { */ bool HTTPChannel:: run_download_to_ram() { - nassertr(_body_stream != (ISocketStream *)NULL && _owns_body_stream, false); - nassertr(_download_to_ramfile != (Ramfile *)NULL, false); + nassertr(_body_stream != nullptr && _owns_body_stream, false); + nassertr(_download_to_ramfile != nullptr, false); bool do_throttle = _wanted_nonblocking && _download_throttle; @@ -2343,7 +2349,7 @@ run_download_to_ram() { */ bool HTTPChannel:: run_download_to_stream() { - nassertr(_body_stream != (ISocketStream *)NULL && _owns_body_stream, false); + nassertr(_body_stream != nullptr && _owns_body_stream, false); bool do_throttle = _wanted_nonblocking && _download_throttle; @@ -2448,7 +2454,7 @@ begin_request(HTTPEnum::Method method, const DocumentSpec &url, // Changing the proxy is grounds for dropping the old connection, if any. if (_proxy != new_proxy) { _proxy = new_proxy; - _proxy_auth = (HTTPAuthorization *)NULL; + _proxy_auth = nullptr; if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID @@ -2490,16 +2496,16 @@ begin_request(HTTPEnum::Method method, const DocumentSpec &url, // underneath this. reset_to_new(); _bio = new BioPtr(_request.get_url()); - if (_bio->get_bio() != NULL) { + if (_bio->get_bio() != nullptr) { // Successfully opened the file. _source = new BioStreamPtr(new BioStream(_bio)); _status_entry._status_code = 200; _state = S_start_direct_file_read; // Get the file size. - FILE *fp = NULL; + FILE *fp = nullptr; BIO_get_fp(_bio->get_bio(), &fp); - if (fp != NULL) { + if (fp != nullptr) { if (fseek(fp, 0, SEEK_END) == 0) { _file_size = ftell(fp); _got_file_size = true; @@ -2663,7 +2669,7 @@ open_download_file() { if (_download_dest == DD_file) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); _download_to_stream = vfs->open_write_file(_download_to_filename, false, !_subdocument_resumes); - if (_download_to_stream == NULL) { + if (_download_to_stream == nullptr) { downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Could not open " << _download_to_filename << " for writing.\n"; @@ -2678,7 +2684,7 @@ open_download_file() { // Windows doesn't complain if you try to seek past the end of file--it // happily appends enough zero bytes to make the difference. Blecch. // That means we need to get the file size first to check it ourselves. - _download_to_stream->seekp(0, ios::end); + _download_to_stream->seekp(0, std::ios::end); if (_first_byte_delivered > (size_t)_download_to_stream->tellp()) { downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID @@ -2716,7 +2722,7 @@ open_download_file() { // Windows doesn't complain if you try to seek past the end of file--it // happily appends enough zero bytes to make the difference. Blecch. // That means we need to get the file size first to check it ourselves. - _download_to_stream->seekp(0, ios::end); + _download_to_stream->seekp(0, std::ios::end); if (_first_byte_delivered > (size_t)_download_to_stream->tellp()) { downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID @@ -3339,8 +3345,8 @@ validate_server_name(X509 *cert) { // According to RFC 2818, we should check the DNS name(s) in the // subjectAltName extension first, if that extension exists. STACK_OF(GENERAL_NAME) *subject_alt_names = - (STACK_OF(GENERAL_NAME) *)X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL); - if (subject_alt_names != NULL) { + (STACK_OF(GENERAL_NAME) *)X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr); + if (subject_alt_names != nullptr) { int num_alts = sk_GENERAL_NAME_num(subject_alt_names); for (int i = 0; i < num_alts; ++i) { // Get the ith alt name. @@ -3348,13 +3354,13 @@ validate_server_name(X509 *cert) { sk_GENERAL_NAME_value(subject_alt_names, i); if (alt_name->type == GEN_DNS) { - char *buffer = NULL; + char *buffer = nullptr; int len = ASN1_STRING_to_UTF8((unsigned char**)&buffer, alt_name->d.ia5); if (len > 0) { cert_names.push_back(string(buffer, len)); } - if (buffer != NULL) { + if (buffer != nullptr) { OPENSSL_free(buffer); } } @@ -3365,7 +3371,7 @@ validate_server_name(X509 *cert) { // If there were no DNS names, use the common name instead. X509_NAME *xname = X509_get_subject_name(cert); - if (xname != NULL) { + if (xname != nullptr) { string common_name = get_x509_name_component(xname, NID_commonName); cert_names.push_back(common_name); } @@ -3444,7 +3450,7 @@ string HTTPChannel:: get_x509_name_component(X509_NAME *name, int nid) { ASN1_OBJECT *obj = OBJ_nid2obj(nid); - if (obj == NULL) { + if (obj == nullptr) { // Unknown nid. See opensslobjects.h. return string(); } @@ -3467,7 +3473,7 @@ void HTTPChannel:: make_header() { _proxy_auth = _client->select_auth(_proxy, true, _proxy_realm); _proxy_username = string(); - if (_proxy_auth != (HTTPAuthorization *)NULL) { + if (_proxy_auth != nullptr) { _proxy_realm = _proxy_auth->get_realm(); _proxy_username = _client->select_username(_proxy, true, _proxy_realm); } @@ -3482,7 +3488,7 @@ make_header() { _www_auth = _client->select_auth(_request.get_url(), false, _www_realm); _www_username = string(); - if (_www_auth != (HTTPAuthorization *)NULL) { + if (_www_auth != nullptr) { _www_realm = _www_auth->get_realm(); _www_username = _client->select_username(_request.get_url(), false, _www_realm); } @@ -3642,7 +3648,7 @@ void HTTPChannel:: make_proxy_request_text() { _proxy_request_text = _proxy_header; - if (_proxy_auth != (HTTPAuthorization *)NULL && !_proxy_username.empty()) { + if (_proxy_auth != nullptr && !_proxy_username.empty()) { _proxy_request_text += "Proxy-Authorization: "; _proxy_request_text += _proxy_auth->generate(HTTPEnum::M_connect, _request.get_url().get_server_and_port(), @@ -3662,14 +3668,14 @@ make_request_text() { _request_text = _header; if (_proxy_serves_document && - _proxy_auth != (HTTPAuthorization *)NULL && !_proxy_username.empty()) { + _proxy_auth != nullptr && !_proxy_username.empty()) { _request_text += "Proxy-Authorization: "; _request_text += _proxy_auth->generate(_method, _request.get_url().get_url(), _proxy_username, _body); _request_text += "\r\n"; } - if (_www_auth != (HTTPAuthorization *)NULL && !_www_username.empty()) { + if (_www_auth != nullptr && !_www_username.empty()) { string authorization = _request_text += "Authorization: "; _request_text += @@ -3711,7 +3717,7 @@ reset_url(const URLSpec &old_url, const URLSpec &new_url) { */ void HTTPChannel:: store_header_field(const string &field_name, const string &field_value) { - pair insert_result = + std::pair insert_result = _headers.insert(Headers::value_type(field_name, field_value)); if (!insert_result.second) { @@ -3767,14 +3773,14 @@ reset_download_to() { */ void HTTPChannel:: close_download_stream() { - if (_download_to_stream != NULL) { + if (_download_to_stream != nullptr) { _download_to_stream->flush(); if (_download_dest == DD_file) { VirtualFileSystem::close_write_file(_download_to_stream); } } - _download_to_ramfile = (Ramfile *)NULL; - _download_to_stream = NULL; + _download_to_ramfile = nullptr; + _download_to_stream = nullptr; } @@ -3799,12 +3805,12 @@ reset_to_new() { void HTTPChannel:: reset_body_stream() { if (_owns_body_stream) { - if (_body_stream != (ISocketStream *)NULL) { + if (_body_stream != nullptr) { close_read_body(_body_stream); - nassertv(_body_stream == (ISocketStream *)NULL && !_owns_body_stream); + nassertv(_body_stream == nullptr && !_owns_body_stream); } } else { - _body_stream = NULL; + _body_stream = nullptr; } } diff --git a/panda/src/downloader/httpChannel.h b/panda/src/downloader/httpChannel.h index 7de0e17e83..f2bf891db6 100644 --- a/panda/src/downloader/httpChannel.h +++ b/panda/src/downloader/httpChannel.h @@ -51,7 +51,7 @@ class HTTPClient; * requested from the same HTTPChannel until the first document has been fully * retrieved. */ -class EXPCL_PANDAEXPRESS HTTPChannel : public TypedReferenceCount { +class EXPCL_PANDA_DOWNLOADER HTTPChannel : public TypedReferenceCount { private: HTTPChannel(HTTPClient *client); @@ -100,13 +100,13 @@ PUBLISHED: INLINE const URLSpec &get_url() const; INLINE const DocumentSpec &get_document_spec() const; INLINE HTTPEnum::HTTPVersion get_http_version() const; - INLINE const string &get_http_version_string() const; + INLINE const std::string &get_http_version_string() const; INLINE int get_status_code() const; - string get_status_string() const; - INLINE const string &get_www_realm() const; - INLINE const string &get_proxy_realm() const; + std::string get_status_string() const; + INLINE const std::string &get_www_realm() const; + INLINE const std::string &get_proxy_realm() const; INLINE const URLSpec &get_redirect() const; - string get_header_value(const string &key) const; + std::string get_header_value(const std::string &key) const; INLINE int get_num_redirect_steps() const; INLINE const URLSpec &get_redirect_step(int n) const; @@ -143,11 +143,11 @@ PUBLISHED: INLINE void set_max_updates_per_second(double max_updates_per_second); INLINE double get_max_updates_per_second() const; - INLINE void set_content_type(string content_type); - INLINE string get_content_type() const; + INLINE void set_content_type(std::string content_type); + INLINE std::string get_content_type() const; INLINE void set_expected_file_size(size_t file_size); - streamsize get_file_size() const; + std::streamsize get_file_size() const; INLINE bool is_file_size_known() const; INLINE size_t get_first_byte_requested() const; @@ -155,20 +155,20 @@ PUBLISHED: INLINE size_t get_first_byte_delivered() const; INLINE size_t get_last_byte_delivered() const; - void write_headers(ostream &out) const; + void write_headers(std::ostream &out) const; INLINE void reset(); INLINE void preserve_status(); INLINE void clear_extra_headers(); - INLINE void send_extra_header(const string &key, const string &value); + INLINE void send_extra_header(const std::string &key, const std::string &value); BLOCKING INLINE bool get_document(const DocumentSpec &url); BLOCKING INLINE bool get_subdocument(const DocumentSpec &url, size_t first_byte, size_t last_byte); BLOCKING INLINE bool get_header(const DocumentSpec &url); - BLOCKING INLINE bool post_form(const DocumentSpec &url, const string &body); - BLOCKING INLINE bool put_document(const DocumentSpec &url, const string &body); + BLOCKING INLINE bool post_form(const DocumentSpec &url, const std::string &body); + BLOCKING INLINE bool put_document(const DocumentSpec &url, const std::string &body); BLOCKING INLINE bool delete_document(const DocumentSpec &url); BLOCKING INLINE bool get_trace(const DocumentSpec &url); BLOCKING INLINE bool connect_to(const DocumentSpec &url); @@ -178,16 +178,16 @@ PUBLISHED: INLINE void begin_get_subdocument(const DocumentSpec &url, size_t first_byte, size_t last_byte); INLINE void begin_get_header(const DocumentSpec &url); - INLINE void begin_post_form(const DocumentSpec &url, const string &body); + INLINE void begin_post_form(const DocumentSpec &url, const std::string &body); bool run(); INLINE void begin_connect_to(const DocumentSpec &url); ISocketStream *open_read_body(); - void close_read_body(istream *stream) const; + void close_read_body(std::istream *stream) const; BLOCKING bool download_to_file(const Filename &filename, bool subdocument_resumes = true); BLOCKING bool download_to_ram(Ramfile *ramfile, bool subdocument_resumes = true); - BLOCKING bool download_to_stream(ostream *strm, bool subdocument_resumes = true); + BLOCKING bool download_to_stream(std::ostream *strm, bool subdocument_resumes = true); SocketStream *get_connection(); INLINE size_t get_bytes_downloaded() const; @@ -195,7 +195,7 @@ PUBLISHED: INLINE bool is_download_complete() const; public: - static string downcase(const string &s); + static std::string downcase(const std::string &s); void body_stream_destructs(ISocketStream *stream); private: @@ -227,7 +227,7 @@ private: bool run_download_to_stream(); void begin_request(HTTPEnum::Method method, const DocumentSpec &url, - const string &body, bool nonblocking, + const std::string &body, bool nonblocking, size_t first_byte, size_t last_byte); void reconsider_proxy(); void reset_for_new_request(); @@ -235,32 +235,32 @@ private: void finished_body(bool has_trailer); bool open_download_file(); - bool server_getline(string &str); - bool server_getline_failsafe(string &str); - bool server_get(string &str, size_t num_bytes); - bool server_get_failsafe(string &str, size_t num_bytes); - bool server_send(const string &str, bool secret); - bool parse_http_response(const string &line); + bool server_getline(std::string &str); + bool server_getline_failsafe(std::string &str); + bool server_get(std::string &str, size_t num_bytes); + bool server_get_failsafe(std::string &str, size_t num_bytes); + bool server_send(const std::string &str, bool secret); + bool parse_http_response(const std::string &line); bool parse_http_header(); - bool parse_content_range(const string &content_range); + bool parse_content_range(const std::string &content_range); void check_socket(); void check_preapproved_server_certificate(X509 *cert, bool &cert_preapproved, bool &cert_name_preapproved) const; bool validate_server_name(X509 *cert); - static bool match_cert_name(const string &cert_name, const string &hostname); - static string get_x509_name_component(X509_NAME *name, int nid); + static bool match_cert_name(const std::string &cert_name, const std::string &hostname); + static std::string get_x509_name_component(X509_NAME *name, int nid); void make_header(); void make_proxy_request_text(); void make_request_text(); void reset_url(const URLSpec &old_url, const URLSpec &new_url); - void store_header_field(const string &field_name, const string &field_value); + void store_header_field(const std::string &field_name, const std::string &field_value); #ifndef NDEBUG - static void show_send(const string &message); + static void show_send(const std::string &message); #endif void reset_download_to(); @@ -304,7 +304,7 @@ private: public: INLINE StatusEntry(); int _status_code; - string _status_string; + std::string _status_string; }; typedef pvector Proxies; typedef pvector StatusList; @@ -331,15 +331,15 @@ private: int _bytes_per_update; bool _nonblocking; bool _wanted_nonblocking; - string _send_extra_headers; + std::string _send_extra_headers; DocumentSpec _document_spec; DocumentSpec _request; HTTPEnum::Method _method; - string request_path; - string _header; - string _body; - string _content_type; + std::string request_path; + std::string _header; + std::string _body; + std::string _content_type; bool _want_ssl; bool _proxy_serves_document; bool _proxy_tunnel_now; @@ -360,21 +360,21 @@ private: bool _subdocument_resumes; Filename _download_to_filename; Ramfile *_download_to_ramfile; - ostream *_download_to_stream; + std::ostream *_download_to_stream; int _read_index; HTTPEnum::HTTPVersion _http_version; - string _http_version_string; + std::string _http_version_string; StatusEntry _status_entry; URLSpec _redirect; - string _proxy_realm; - string _proxy_username; + std::string _proxy_realm; + std::string _proxy_username; PT(HTTPAuthorization) _proxy_auth; - string _www_realm; - string _www_username; + std::string _www_realm; + std::string _www_username; PT(HTTPAuthorization) _www_auth; // What type of response do we get to our HTTP request? @@ -388,7 +388,7 @@ private: ResponseType _response_type; // Not a phash_map, to maintain sorted order. - typedef pmap Headers; + typedef pmap Headers; Headers _headers; size_t _expected_file_size; @@ -410,17 +410,17 @@ private: double _started_connecting_time; double _sent_request_time; bool _started_download; - string _proxy_header; - string _proxy_request_text; - string _request_text; - string _working_get; + std::string _proxy_header; + std::string _proxy_request_text; + std::string _request_text; + std::string _working_get; size_t _sent_so_far; - string _current_field_name; - string _current_field_value; + std::string _current_field_name; + std::string _current_field_value; ISocketStream *_body_stream; bool _owns_body_stream; BIO *_sbio; - string _cipher_list; + std::string _cipher_list; pvector _redirect_trail; int _last_status_code; double _last_run_time; @@ -450,7 +450,7 @@ private: friend class HTTPClient; }; -ostream &operator << (ostream &out, HTTPChannel::State state); +std::ostream &operator << (std::ostream &out, HTTPChannel::State state); #include "httpChannel.I" diff --git a/panda/src/downloader/httpClient.I b/panda/src/downloader/httpClient.I index 15047431c2..33b9432f3d 100644 --- a/panda/src/downloader/httpClient.I +++ b/panda/src/downloader/httpClient.I @@ -40,7 +40,7 @@ get_try_all_direct() const { INLINE void HTTPClient:: set_client_certificate_filename(const Filename &filename) { _client_certificate_filename = filename; - _client_certificate_pem = string(); + _client_certificate_pem = std::string(); unload_client_certificate(); } @@ -51,7 +51,7 @@ set_client_certificate_filename(const Filename &filename) { * client certificate. */ INLINE void HTTPClient:: -set_client_certificate_pem(const string &pem) { +set_client_certificate_pem(const std::string &pem) { _client_certificate_pem = pem; _client_certificate_filename = Filename(); unload_client_certificate(); @@ -62,7 +62,7 @@ set_client_certificate_pem(const string &pem) { * named by set_client_certificate_filename() or set_client_certificate_pem(). */ INLINE void HTTPClient:: -set_client_certificate_passphrase(const string &passphrase) { +set_client_certificate_passphrase(const std::string &passphrase) { _client_certificate_passphrase = passphrase; unload_client_certificate(); } @@ -116,7 +116,7 @@ get_verify_ssl() const { * to use the built-in OpenSSL default value. */ INLINE void HTTPClient:: -set_cipher_list(const string &cipher_list) { +set_cipher_list(const std::string &cipher_list) { _cipher_list = cipher_list; } @@ -124,7 +124,7 @@ set_cipher_list(const string &cipher_list) { * Returns the set of ciphers as set by set_cipher_list(). See * set_cipher_list(). */ -INLINE const string &HTTPClient:: +INLINE const std::string &HTTPClient:: get_cipher_list() const { return _cipher_list; } @@ -134,8 +134,8 @@ get_cipher_list() const { * as a convenient place to publish it for access by the scripting language; * C++ code should probably use HTTPAuthorization directly. */ -INLINE string HTTPClient:: -base64_encode(const string &s) { +INLINE std::string HTTPClient:: +base64_encode(const std::string &s) { return HTTPAuthorization::base64_encode(s); } @@ -144,7 +144,7 @@ base64_encode(const string &s) { * as a convenient place to publish it for access by the scripting language; * C++ code should probably use HTTPAuthorization directly. */ -INLINE string HTTPClient:: -base64_decode(const string &s) { +INLINE std::string HTTPClient:: +base64_decode(const std::string &s) { return HTTPAuthorization::base64_decode(s); } diff --git a/panda/src/downloader/httpClient.cxx b/panda/src/downloader/httpClient.cxx index 4770d6916d..1f80bf61fd 100644 --- a/panda/src/downloader/httpClient.cxx +++ b/panda/src/downloader/httpClient.cxx @@ -26,6 +26,8 @@ #include "openSSLWrapper.h" +using std::string; + PT(HTTPClient) HTTPClient::_global_ptr; /** @@ -78,7 +80,7 @@ tokenize(const string &str, vector_string &words, const string &delimiters) { static void ssl_msg_callback(int write_p, int version, int content_type, const void *, size_t len, SSL *, void *) { - ostringstream describe; + std::ostringstream describe; if (write_p) { describe << "sent "; } else { @@ -216,7 +218,7 @@ HTTPClient() { _http_version = HTTPEnum::HV_11; _verify_ssl = verify_ssl ? VS_normal : VS_no_verify; - _ssl_ctx = (SSL_CTX *)NULL; + _ssl_ctx = nullptr; set_proxy_spec(http_proxy); set_direct_host_spec(http_direct_hosts); @@ -241,8 +243,8 @@ HTTPClient() { _client_certificate_passphrase = http_client_certificate_passphrase; _client_certificate_loaded = false; - _client_certificate_pub = NULL; - _client_certificate_priv = NULL; + _client_certificate_pub = nullptr; + _client_certificate_priv = nullptr; int num_server_certs = http_preapproved_server_certificate_filename.get_num_unique_values(); int si; @@ -271,7 +273,7 @@ HTTPClient() { */ HTTPClient:: HTTPClient(const HTTPClient ©) { - _ssl_ctx = (SSL_CTX *)NULL; + _ssl_ctx = nullptr; (*this) = copy; } @@ -295,12 +297,12 @@ operator = (const HTTPClient ©) { */ HTTPClient:: ~HTTPClient() { - if (_ssl_ctx != (SSL_CTX *)NULL) { + if (_ssl_ctx != nullptr) { #if OPENSSL_VERSION_NUMBER < 0x10100000 // Before we can free the context, we must remove the X509_STORE pointer // from it, so it won't be destroyed along with it (this object is shared // among all contexts). - _ssl_ctx->cert_store = NULL; + _ssl_ctx->cert_store = nullptr; #endif SSL_CTX_free(_ssl_ctx); } @@ -701,7 +703,7 @@ set_cookie(const HTTPCookie &cookie) { clear_cookie(cookie); } else { - pair result = _cookies.insert(cookie); + std::pair result = _cookies.insert(cookie); if (!result.second) { // We already had a cookie matching the supplied domainpathname, so // replace it. @@ -778,7 +780,7 @@ copy_cookies_from(const HTTPClient &other) { * host). */ void HTTPClient:: -write_cookies(ostream &out) const { +write_cookies(std::ostream &out) const { Cookies::const_iterator ci; for (ci = _cookies.begin(); ci != _cookies.end(); ++ci) { out << *ci << "\n"; @@ -791,7 +793,7 @@ write_cookies(ostream &out) const { * also removes expired cookies. */ void HTTPClient:: -send_cookies(ostream &out, const URLSpec &url) { +send_cookies(std::ostream &out, const URLSpec &url) { HTTPDate now = HTTPDate::now(); bool any_expired = false; bool first_cookie = true; @@ -866,7 +868,7 @@ load_client_certificate() { ERR_clear_error(); _client_certificate_priv = - PEM_read_bio_PrivateKey(mbio, NULL, NULL, + PEM_read_bio_PrivateKey(mbio, nullptr, nullptr, (char *)_client_certificate_passphrase.c_str()); // Rewind the "file" to the beginning in order to read the public key @@ -875,7 +877,7 @@ load_client_certificate() { ERR_clear_error(); _client_certificate_pub = - PEM_read_bio_X509(mbio, NULL, NULL, NULL); + PEM_read_bio_X509(mbio, nullptr, nullptr, nullptr); BIO_free(mbio); @@ -891,18 +893,18 @@ load_client_certificate() { } if (downloader_cat.is_on(sev)) { - if (_client_certificate_priv != (EVP_PKEY *)NULL && - _client_certificate_pub != (X509 *)NULL) { + if (_client_certificate_priv != nullptr && + _client_certificate_pub != nullptr) { downloader_cat.out(sev) << "Read client certificate from " << source << "\n"; } else { - if (_client_certificate_priv == (EVP_PKEY *)NULL) { + if (_client_certificate_priv == nullptr) { downloader_cat.out(sev) << "Could not read private key from " << source << "\n"; } - if (_client_certificate_pub == (X509 *)NULL) { + if (_client_certificate_pub == nullptr) { downloader_cat.out(sev) << "Could not read public key from " << source << "\n"; } @@ -911,8 +913,8 @@ load_client_certificate() { } } - return (_client_certificate_priv != (EVP_PKEY *)NULL && - _client_certificate_pub != (X509 *)NULL); + return (_client_certificate_priv != nullptr && + _client_certificate_pub != nullptr); } /** @@ -961,10 +963,10 @@ add_preapproved_server_certificate_pem(const URLSpec &url, const string &pem) { BIO *mbio = BIO_new_mem_buf((void *)pem.data(), pem.length()); ERR_clear_error(); - X509 *cert = PEM_read_bio_X509(mbio, NULL, NULL, NULL); + X509 *cert = PEM_read_bio_X509(mbio, nullptr, nullptr, nullptr); BIO_free(mbio); - if (cert == NULL) { + if (cert == nullptr) { downloader_cat.warning() << "Could not parse PEM data\n"; return false; @@ -1003,7 +1005,7 @@ add_preapproved_server_certificate_pem(const URLSpec &url, const string &pem) { bool HTTPClient:: add_preapproved_server_certificate_name(const URLSpec &url, const string &name) { X509_NAME *cert_name = parse_x509_name(name); - if (cert_name == NULL) { + if (cert_name == nullptr) { downloader_cat.warning() << "Could not parse certificate name " << name << "\n"; return false; @@ -1156,7 +1158,7 @@ get_header(const URLSpec &url) { */ HTTPClient *HTTPClient:: get_global_ptr() { - if (_global_ptr == NULL) { + if (_global_ptr == nullptr) { _global_ptr = new HTTPClient; } return _global_ptr; @@ -1168,7 +1170,7 @@ get_global_ptr() { */ SSL_CTX *HTTPClient:: get_ssl_ctx() { - if (_ssl_ctx != (SSL_CTX *)NULL) { + if (_ssl_ctx != nullptr) { return _ssl_ctx; } @@ -1190,7 +1192,7 @@ get_ssl_ctx() { X509_STORE *store = sslw->get_x509_store(); #if OPENSSL_VERSION_NUMBER >= 0x10100000 - if (store != NULL) { + if (store != nullptr) { X509_STORE_up_ref(store); } #endif @@ -1419,7 +1421,7 @@ select_auth(const URLSpec &url, bool is_proxy, const string &last_realm) { } // No matching domains. - return NULL; + return nullptr; } /** @@ -1441,14 +1443,14 @@ generate_auth(const URLSpec &url, bool is_proxy, const string &challenge) { auth = new HTTPDigestAuthorization((*si).second, url, is_proxy); } - if (auth == (HTTPAuthorization *)NULL || !auth->is_valid()) { + if (auth == nullptr || !auth->is_valid()) { si = schemes.find("basic"); if (si != schemes.end()) { auth = new HTTPBasicAuthorization((*si).second, url, is_proxy); } } - if (auth == (HTTPAuthorization *)NULL || !auth->is_valid()) { + if (auth == nullptr || !auth->is_valid()) { downloader_cat.warning() << "Don't know how to use any of the server's available authorization schemes:\n"; for (si = schemes.begin(); si != schemes.end(); ++si) { @@ -1475,14 +1477,14 @@ generate_auth(const URLSpec &url, bool is_proxy, const string &challenge) { */ void HTTPClient:: unload_client_certificate() { - if (_client_certificate_priv != (EVP_PKEY *)NULL) { + if (_client_certificate_priv != nullptr) { EVP_PKEY_free(_client_certificate_priv); - _client_certificate_priv = NULL; + _client_certificate_priv = nullptr; } - if (_client_certificate_pub != (X509 *)NULL) { + if (_client_certificate_pub != nullptr) { X509_free(_client_certificate_pub); - _client_certificate_pub = NULL; + _client_certificate_pub = nullptr; } _client_certificate_loaded = false; @@ -1494,7 +1496,7 @@ unload_client_certificate() { */ X509_NAME *HTTPClient:: parse_x509_name(const string &source) { - X509_NAME *result = NULL; + X509_NAME *result = nullptr; result = X509_NAME_new(); bool added_any = false; @@ -1526,7 +1528,7 @@ parse_x509_name(const string &source) { << "Unknown type " << type << " in X509 name: " << source << "\n"; X509_NAME_free(result); - return NULL; + return nullptr; } string value; @@ -1556,7 +1558,7 @@ parse_x509_name(const string &source) { << "Unable to add " << type << "=" << value << " in X509 name: " << source << "\n"; X509_NAME_free(result); - return NULL; + return nullptr; } added_any = true; } @@ -1567,7 +1569,7 @@ parse_x509_name(const string &source) { downloader_cat.info() << "Invalid empty X509 name: " << source << "\n"; X509_NAME_free(result); - return NULL; + return nullptr; } return result; diff --git a/panda/src/downloader/httpClient.h b/panda/src/downloader/httpClient.h index 1efab58460..93490fe642 100644 --- a/panda/src/downloader/httpClient.h +++ b/panda/src/downloader/httpClient.h @@ -53,7 +53,7 @@ class HTTPChannel; * There is a default, global HTTPClient available in * HTTPClient::get_global_ptr(). */ -class EXPCL_PANDAEXPRESS HTTPClient : public ReferenceCount { +class EXPCL_PANDA_DOWNLOADER HTTPClient : public ReferenceCount { PUBLISHED: HTTPClient(); HTTPClient(const HTTPClient ©); @@ -62,24 +62,24 @@ PUBLISHED: static void init_random_seed(); - void set_proxy_spec(const string &proxy_spec); - string get_proxy_spec() const; + void set_proxy_spec(const std::string &proxy_spec); + std::string get_proxy_spec() const; - void set_direct_host_spec(const string &direct_host_spec); - string get_direct_host_spec() const; + void set_direct_host_spec(const std::string &direct_host_spec); + std::string get_direct_host_spec() const; INLINE void set_try_all_direct(bool try_all_direct); INLINE bool get_try_all_direct() const; void clear_proxy(); - void add_proxy(const string &scheme, const URLSpec &proxy); + void add_proxy(const std::string &scheme, const URLSpec &proxy); void clear_direct_host(); - void add_direct_host(const string &hostname); + void add_direct_host(const std::string &hostname); - string get_proxies_for_url(const URLSpec &url) const; + std::string get_proxies_for_url(const URLSpec &url) const; - void set_username(const string &server, const string &realm, const string &username); - string get_username(const string &server, const string &realm) const; + void set_username(const std::string &server, const std::string &realm, const std::string &username); + std::string get_username(const std::string &server, const std::string &realm) const; void set_cookie(const HTTPCookie &cookie); bool clear_cookie(const HTTPCookie &cookie); @@ -88,24 +88,24 @@ PUBLISHED: HTTPCookie get_cookie(const HTTPCookie &cookie) const; void copy_cookies_from(const HTTPClient &other); - void write_cookies(ostream &out) const; - void send_cookies(ostream &out, const URLSpec &url); + void write_cookies(std::ostream &out) const; + void send_cookies(std::ostream &out, const URLSpec &url); INLINE void set_client_certificate_filename(const Filename &filename); - INLINE void set_client_certificate_pem(const string &pem); - INLINE void set_client_certificate_passphrase(const string &passphrase); + INLINE void set_client_certificate_pem(const std::string &pem); + INLINE void set_client_certificate_passphrase(const std::string &passphrase); bool load_client_certificate(); bool add_preapproved_server_certificate_filename(const URLSpec &url, const Filename &filename); - bool add_preapproved_server_certificate_pem(const URLSpec &url, const string &pem); - bool add_preapproved_server_certificate_name(const URLSpec &url, const string &name); + bool add_preapproved_server_certificate_pem(const URLSpec &url, const std::string &pem); + bool add_preapproved_server_certificate_name(const URLSpec &url, const std::string &name); void clear_preapproved_server_certificates(const URLSpec &url); void clear_all_preapproved_server_certificates(); INLINE void set_http_version(HTTPEnum::HTTPVersion version); INLINE HTTPEnum::HTTPVersion get_http_version() const; - string get_http_version_string() const; - static HTTPEnum::HTTPVersion parse_http_version_string(const string &version); + std::string get_http_version_string() const; + static HTTPEnum::HTTPVersion parse_http_version_string(const std::string &version); bool load_certificates(const Filename &filename); @@ -118,16 +118,16 @@ PUBLISHED: INLINE void set_verify_ssl(VerifySSL verify_ssl); INLINE VerifySSL get_verify_ssl() const; - INLINE void set_cipher_list(const string &cipher_list); - INLINE const string &get_cipher_list() const; + INLINE void set_cipher_list(const std::string &cipher_list); + INLINE const std::string &get_cipher_list() const; PT(HTTPChannel) make_channel(bool persistent_connection); - BLOCKING PT(HTTPChannel) post_form(const URLSpec &url, const string &body); + BLOCKING PT(HTTPChannel) post_form(const URLSpec &url, const std::string &body); BLOCKING PT(HTTPChannel) get_document(const URLSpec &url); BLOCKING PT(HTTPChannel) get_header(const URLSpec &url); - INLINE static string base64_encode(const string &s); - INLINE static string base64_decode(const string &s); + INLINE static std::string base64_encode(const std::string &s); + INLINE static std::string base64_decode(const std::string &s); static HTTPClient *get_global_ptr(); @@ -140,27 +140,27 @@ private: void check_preapproved_server_certificate(const URLSpec &url, X509 *cert, bool &cert_preapproved, bool &cert_name_preapproved) const; - bool get_proxies_for_scheme(const string &scheme, + bool get_proxies_for_scheme(const std::string &scheme, pvector &proxies) const; - void add_http_username(const string &http_username); - string select_username(const URLSpec &url, bool is_proxy, - const string &realm) const; + void add_http_username(const std::string &http_username); + std::string select_username(const URLSpec &url, bool is_proxy, + const std::string &realm) const; HTTPAuthorization *select_auth(const URLSpec &url, bool is_proxy, - const string &last_realm); + const std::string &last_realm); PT(HTTPAuthorization) generate_auth(const URLSpec &url, bool is_proxy, - const string &challenge); + const std::string &challenge); void unload_client_certificate(); - static X509_NAME *parse_x509_name(const string &source); + static X509_NAME *parse_x509_name(const std::string &source); static bool x509_name_subset(X509_NAME *name_a, X509_NAME *name_b); - static void split_whitespace(string &a, string &b, const string &c); + static void split_whitespace(std::string &a, std::string &b, const std::string &c); typedef pvector Proxies; - typedef pmap ProxiesByScheme; + typedef pmap ProxiesByScheme; ProxiesByScheme _proxies_by_scheme; typedef pvector DirectHosts; DirectHosts _direct_hosts; @@ -168,17 +168,17 @@ private: HTTPEnum::HTTPVersion _http_version; VerifySSL _verify_ssl; - string _cipher_list; + std::string _cipher_list; - typedef pmap Usernames; + typedef pmap Usernames; Usernames _usernames; - typedef pmap Realms; + typedef pmap Realms; class Domain { public: Realms _realms; }; - typedef pmap Domains; + typedef pmap Domains; Domains _proxy_domains, _www_domains; // Not a phash_set, since we want this to be maintained in order. @@ -186,8 +186,8 @@ private: Cookies _cookies; Filename _client_certificate_filename; - string _client_certificate_pem; - string _client_certificate_passphrase; + std::string _client_certificate_pem; + std::string _client_certificate_passphrase; SSL_CTX *_ssl_ctx; bool _client_certificate_loaded; @@ -204,7 +204,7 @@ private: ServerCertNames _cert_names; }; - typedef pmap PreapprovedServerCerts; + typedef pmap PreapprovedServerCerts; PreapprovedServerCerts _preapproved_server_certs; static PT(HTTPClient) _global_ptr; diff --git a/panda/src/downloader/httpCookie.I b/panda/src/downloader/httpCookie.I index 163e34652d..6116f6722c 100644 --- a/panda/src/downloader/httpCookie.I +++ b/panda/src/downloader/httpCookie.I @@ -26,7 +26,7 @@ HTTPCookie() : * the string with this constructor. */ INLINE HTTPCookie:: -HTTPCookie(const string &format, const URLSpec &url) { +HTTPCookie(const std::string &format, const URLSpec &url) { parse_set_cookie(format, url); } @@ -36,7 +36,7 @@ HTTPCookie(const string &format, const URLSpec &url) { * the HTTPClient. */ INLINE HTTPCookie:: -HTTPCookie(const string &name, const string &path, const string &domain) : +HTTPCookie(const std::string &name, const std::string &path, const std::string &domain) : _name(name), _path(path), _domain(domain), @@ -55,7 +55,7 @@ INLINE HTTPCookie:: * */ INLINE void HTTPCookie:: -set_name(const string &name) { +set_name(const std::string &name) { _name = name; } @@ -63,7 +63,7 @@ set_name(const string &name) { * Returns the name of the cookie. This is the key value specified by the * server. */ -INLINE const string &HTTPCookie:: +INLINE const std::string &HTTPCookie:: get_name() const { return _name; } @@ -72,7 +72,7 @@ get_name() const { * */ INLINE void HTTPCookie:: -set_value(const string &value) { +set_value(const std::string &value) { _value = value; } @@ -80,7 +80,7 @@ set_value(const string &value) { * Returns the value of the cookie. This is the arbitrary string associated * with the cookie's name, as specified by the server. */ -INLINE const string &HTTPCookie:: +INLINE const std::string &HTTPCookie:: get_value() const { return _value; } @@ -89,14 +89,14 @@ get_value() const { * */ INLINE void HTTPCookie:: -set_domain(const string &domain) { +set_domain(const std::string &domain) { _domain = domain; } /** * */ -INLINE const string &HTTPCookie:: +INLINE const std::string &HTTPCookie:: get_domain() const { return _domain; } @@ -105,7 +105,7 @@ get_domain() const { * */ INLINE void HTTPCookie:: -set_path(const string &path) { +set_path(const std::string &path) { _path = path; } @@ -113,7 +113,7 @@ set_path(const string &path) { * Returns the prefix of the URL paths on the server for which this cookie * will be sent. */ -INLINE const string &HTTPCookie:: +INLINE const std::string &HTTPCookie:: get_path() const { return _path; } @@ -177,7 +177,7 @@ is_expired(const HTTPDate &now) const { return _expires.is_valid() && _expires < now; } -INLINE ostream &operator << (ostream &out, const HTTPCookie &cookie) { +INLINE std::ostream &operator << (std::ostream &out, const HTTPCookie &cookie) { cookie.output(out); return out; } diff --git a/panda/src/downloader/httpCookie.cxx b/panda/src/downloader/httpCookie.cxx index cbe095cd8d..d09f12b856 100644 --- a/panda/src/downloader/httpCookie.cxx +++ b/panda/src/downloader/httpCookie.cxx @@ -18,6 +18,8 @@ #include "ctype.h" #include "httpChannel.h" +using std::string; + /** * The sorting operator allows the cookies to be stored in a single * dictionary; it returns nonequal only if the cookies are different in name, @@ -139,7 +141,7 @@ matches_url(const URLSpec &url) const { * */ void HTTPCookie:: -output(ostream &out) const { +output(std::ostream &out) const { out << _name << "=" << _value << "; path=" << _path << "; domain=" << _domain; diff --git a/panda/src/downloader/httpCookie.h b/panda/src/downloader/httpCookie.h index af460ec3c2..dfbc507215 100644 --- a/panda/src/downloader/httpCookie.h +++ b/panda/src/downloader/httpCookie.h @@ -29,25 +29,25 @@ * A cookie sent from an HTTP server to be stored on the client and returned * when the path and/or domain matches. */ -class EXPCL_PANDAEXPRESS HTTPCookie { +class EXPCL_PANDA_DOWNLOADER HTTPCookie { PUBLISHED: INLINE HTTPCookie(); - INLINE explicit HTTPCookie(const string &format, const URLSpec &url); - INLINE explicit HTTPCookie(const string &name, const string &path, - const string &domain); + INLINE explicit HTTPCookie(const std::string &format, const URLSpec &url); + INLINE explicit HTTPCookie(const std::string &name, const std::string &path, + const std::string &domain); INLINE ~HTTPCookie(); - INLINE void set_name(const string &name); - INLINE const string &get_name() const; + INLINE void set_name(const std::string &name); + INLINE const std::string &get_name() const; - INLINE void set_value(const string &value); - INLINE const string &get_value() const; + INLINE void set_value(const std::string &value); + INLINE const std::string &get_value() const; - INLINE void set_domain(const string &domain); - INLINE const string &get_domain() const; + INLINE void set_domain(const std::string &domain); + INLINE const std::string &get_domain() const; - INLINE void set_path(const string &path); - INLINE const string &get_path() const; + INLINE void set_path(const std::string &path); + INLINE const std::string &get_path() const; INLINE void set_expires(const HTTPDate &expires); INLINE void clear_expires(); @@ -60,24 +60,24 @@ PUBLISHED: bool operator < (const HTTPCookie &other) const; void update_from(const HTTPCookie &other); - bool parse_set_cookie(const string &format, const URLSpec &url); + bool parse_set_cookie(const std::string &format, const URLSpec &url); INLINE bool is_expired(const HTTPDate &now = HTTPDate::now()) const; bool matches_url(const URLSpec &url) const; - void output(ostream &out) const; + void output(std::ostream &out) const; private: - bool parse_cookie_param(const string ¶m, bool first_param); + bool parse_cookie_param(const std::string ¶m, bool first_param); - string _name; - string _value; - string _path; - string _domain; + std::string _name; + std::string _value; + std::string _path; + std::string _domain; HTTPDate _expires; bool _secure; }; -INLINE ostream &operator << (ostream &out, const HTTPCookie &cookie); +INLINE std::ostream &operator << (std::ostream &out, const HTTPCookie &cookie); #include "httpCookie.I" diff --git a/panda/src/downloader/httpDate.I b/panda/src/downloader/httpDate.I index 9b5adbefe4..defbb73c4c 100644 --- a/panda/src/downloader/httpDate.I +++ b/panda/src/downloader/httpDate.I @@ -45,7 +45,7 @@ operator = (const HTTPDate ©) { */ INLINE HTTPDate HTTPDate:: now() { - return HTTPDate(time(NULL)); + return HTTPDate(time(nullptr)); } /** @@ -147,16 +147,16 @@ operator - (const HTTPDate &other) const { } -INLINE istream & -operator >> (istream &in, HTTPDate &date) { +INLINE std::istream & +operator >> (std::istream &in, HTTPDate &date) { if (!date.input(in)) { - in.clear(ios::failbit | in.rdstate()); + in.clear(std::ios::failbit | in.rdstate()); } return in; } -INLINE ostream & -operator << (ostream &out, const HTTPDate &date) { +INLINE std::ostream & +operator << (std::ostream &out, const HTTPDate &date) { date.output(out); return out; } diff --git a/panda/src/downloader/httpDate.cxx b/panda/src/downloader/httpDate.cxx index f3d156fc6a..a651b50f89 100644 --- a/panda/src/downloader/httpDate.cxx +++ b/panda/src/downloader/httpDate.cxx @@ -15,6 +15,10 @@ #include +using std::setfill; +using std::setw; +using std::string; + static const int num_weekdays = 7; static const char * const weekdays[num_weekdays] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" @@ -182,7 +186,7 @@ HTTPDate(const string &format) { if (t.tm_year < 100) { // Two-digit year. Assume it's in the same century, unless that // assumption puts it more than 50 years in the future. - time_t now = time(NULL); + time_t now = time(nullptr); struct tm *tp = gmtime(&now); t.tm_year += 100 * (tp->tm_year / 100); if (t.tm_year - tp->tm_year > 50) { @@ -219,7 +223,7 @@ HTTPDate(const string &format) { if (_time != (time_t)-1) { // Unfortunately, mktime() assumes local time; convert this back to GMT. #if defined(IS_FREEBSD) - time_t now = time(NULL); + time_t now = time(nullptr); struct tm *tp = localtime(&now); _time -= tp->tm_gmtoff; #elif defined(_WIN32) @@ -245,7 +249,7 @@ get_string() const { struct tm *tp = gmtime(&_time); - ostringstream result; + std::ostringstream result; result << weekdays[tp->tm_wday] << ", " << setw(2) << setfill('0') << tp->tm_mday << " " @@ -263,7 +267,7 @@ get_string() const { * */ bool HTTPDate:: -input(istream &in) { +input(std::istream &in) { (*this) = HTTPDate(); // Extract out the quoted date string. @@ -294,7 +298,7 @@ input(istream &in) { * */ void HTTPDate:: -output(ostream &out) const { +output(std::ostream &out) const { // We put quotes around the string on output, so we can reliably detect the // end of the date string on input, above. out << '"' << get_string() << '"'; diff --git a/panda/src/downloader/httpDate.h b/panda/src/downloader/httpDate.h index 9d6011336a..4ee58dcf30 100644 --- a/panda/src/downloader/httpDate.h +++ b/panda/src/downloader/httpDate.h @@ -24,18 +24,18 @@ * conversely, it can accept a time_t value and encode it for output as a * string. */ -class EXPCL_PANDAEXPRESS HTTPDate { +class EXPCL_PANDA_DOWNLOADER HTTPDate { PUBLISHED: INLINE HTTPDate(); INLINE HTTPDate(time_t time); - HTTPDate(const string &format); + HTTPDate(const std::string &format); INLINE HTTPDate(const HTTPDate ©); INLINE void operator = (const HTTPDate ©); INLINE static HTTPDate now(); INLINE bool is_valid() const; - string get_string() const; + std::string get_string() const; INLINE time_t get_time() const; INLINE bool operator == (const HTTPDate &other) const; @@ -51,17 +51,17 @@ PUBLISHED: INLINE HTTPDate operator - (int seconds) const; INLINE int operator - (const HTTPDate &other) const; - bool input(istream &in); - void output(ostream &out) const; + bool input(std::istream &in); + void output(std::ostream &out) const; private: - static string get_token(const string &str, size_t &pos); + static std::string get_token(const std::string &str, size_t &pos); time_t _time; }; -INLINE istream &operator >> (istream &in, HTTPDate &date); -INLINE ostream &operator << (ostream &out, const HTTPDate &date); +INLINE std::istream &operator >> (std::istream &in, HTTPDate &date); +INLINE std::ostream &operator << (std::ostream &out, const HTTPDate &date); #include "httpDate.I" diff --git a/panda/src/downloader/httpDigestAuthorization.cxx b/panda/src/downloader/httpDigestAuthorization.cxx index e8cddbb18b..1e59ea560c 100644 --- a/panda/src/downloader/httpDigestAuthorization.cxx +++ b/panda/src/downloader/httpDigestAuthorization.cxx @@ -21,6 +21,10 @@ #include "openssl/md5.h" #include +using std::ostream; +using std::ostringstream; +using std::string; + const string HTTPDigestAuthorization::_mechanism = "digest"; /** @@ -86,7 +90,7 @@ HTTPDigestAuthorization(const HTTPAuthorization::Tokens &tokens, // Compute an arbitrary client nonce. ostringstream strm; - strm << time(NULL) << ":" << clock() << ":" + strm << time(nullptr) << ":" << clock() << ":" << url.get_url() << ":Panda"; _cnonce = calc_md5(strm.str()); @@ -277,7 +281,7 @@ get_a2(HTTPEnum::Method method, const string &request_path, string HTTPDigestAuthorization:: get_hex_nonce_count() const { ostringstream strm; - strm << hex << setfill('0') << setw(8) << _nonce_count; + strm << std::hex << std::setfill('0') << std::setw(8) << _nonce_count; return strm.str(); } diff --git a/panda/src/downloader/httpDigestAuthorization.h b/panda/src/downloader/httpDigestAuthorization.h index a3b8c7147a..ecd2ab3024 100644 --- a/panda/src/downloader/httpDigestAuthorization.h +++ b/panda/src/downloader/httpDigestAuthorization.h @@ -35,11 +35,11 @@ public: bool is_proxy); virtual ~HTTPDigestAuthorization(); - virtual const string &get_mechanism() const; + virtual const std::string &get_mechanism() const; virtual bool is_valid(); - virtual string generate(HTTPEnum::Method method, const string &request_path, - const string &username, const string &body); + virtual std::string generate(HTTPEnum::Method method, const std::string &request_path, + const std::string &username, const std::string &body); public: enum Algorithm { @@ -55,37 +55,37 @@ public: }; private: - static int match_qop_token(const string &token); + static int match_qop_token(const std::string &token); - string calc_request_digest(const string &username, const string &password, + std::string calc_request_digest(const std::string &username, const std::string &password, HTTPEnum::Method method, - const string &request_path, const string &body); - string calc_h(const string &data) const; - string calc_kd(const string &secret, const string &data) const; - string get_a1(const string &username, const string &password); - string get_a2(HTTPEnum::Method method, const string &request_path, - const string &body); - string get_hex_nonce_count() const; + const std::string &request_path, const std::string &body); + std::string calc_h(const std::string &data) const; + std::string calc_kd(const std::string &secret, const std::string &data) const; + std::string get_a1(const std::string &username, const std::string &password); + std::string get_a2(HTTPEnum::Method method, const std::string &request_path, + const std::string &body); + std::string get_hex_nonce_count() const; - static string calc_md5(const string &source); + static std::string calc_md5(const std::string &source); INLINE static char hexdigit(int value); - string _cnonce; - string _nonce; + std::string _cnonce; + std::string _nonce; int _nonce_count; - string _opaque; + std::string _opaque; Algorithm _algorithm; - string _a1; + std::string _a1; int _qop; Qop _chosen_qop; - static const string _mechanism; + static const std::string _mechanism; }; -ostream &operator << (ostream &out, HTTPDigestAuthorization::Algorithm algorithm); -ostream &operator << (ostream &out, HTTPDigestAuthorization::Qop qop); +std::ostream &operator << (std::ostream &out, HTTPDigestAuthorization::Algorithm algorithm); +std::ostream &operator << (std::ostream &out, HTTPDigestAuthorization::Qop qop); #include "httpDigestAuthorization.I" diff --git a/panda/src/downloader/httpEntityTag.I b/panda/src/downloader/httpEntityTag.I index d713302da2..3cdee7d4f3 100644 --- a/panda/src/downloader/httpEntityTag.I +++ b/panda/src/downloader/httpEntityTag.I @@ -24,7 +24,7 @@ HTTPEntityTag() { * tag string. */ INLINE HTTPEntityTag:: -HTTPEntityTag(bool weak, const string &tag) : +HTTPEntityTag(bool weak, const std::string &tag) : _weak(weak), _tag(tag) { @@ -63,7 +63,7 @@ is_weak() const { /** * Returns the tag as a literal string. */ -INLINE const string &HTTPEntityTag:: +INLINE const std::string &HTTPEntityTag:: get_tag() const { return _tag; } @@ -131,13 +131,13 @@ compare_to(const HTTPEntityTag &other) const { * */ INLINE void HTTPEntityTag:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_string(); } -INLINE ostream & -operator << (ostream &out, const HTTPEntityTag &entityTag) { +INLINE std::ostream & +operator << (std::ostream &out, const HTTPEntityTag &entityTag) { entityTag.output(out); return out; } diff --git a/panda/src/downloader/httpEntityTag.cxx b/panda/src/downloader/httpEntityTag.cxx index 9c756024ee..1d4b79922a 100644 --- a/panda/src/downloader/httpEntityTag.cxx +++ b/panda/src/downloader/httpEntityTag.cxx @@ -13,6 +13,8 @@ #include "httpEntityTag.h" +using std::string; + /** * This constructor accepts a string as formatted from an HTTP server (e.g. @@ -52,7 +54,7 @@ HTTPEntityTag(const string &text) { */ string HTTPEntityTag:: get_string() const { - ostringstream result; + std::ostringstream result; if (_weak) { result << "W/"; } diff --git a/panda/src/downloader/httpEntityTag.h b/panda/src/downloader/httpEntityTag.h index 280ce9d0c9..7388b8621f 100644 --- a/panda/src/downloader/httpEntityTag.h +++ b/panda/src/downloader/httpEntityTag.h @@ -21,17 +21,17 @@ * identify a particular version of a document or resource, particularly * useful for verifying caches. */ -class EXPCL_PANDAEXPRESS HTTPEntityTag { +class EXPCL_PANDA_DOWNLOADER HTTPEntityTag { PUBLISHED: INLINE HTTPEntityTag(); - HTTPEntityTag(const string &text); - INLINE HTTPEntityTag(bool weak, const string &tag); + HTTPEntityTag(const std::string &text); + INLINE HTTPEntityTag(bool weak, const std::string &tag); INLINE HTTPEntityTag(const HTTPEntityTag ©); INLINE void operator = (const HTTPEntityTag ©); INLINE bool is_weak() const; - INLINE const string &get_tag() const; - string get_string() const; + INLINE const std::string &get_tag() const; + std::string get_string() const; INLINE bool strong_equiv(const HTTPEntityTag &other) const; INLINE bool weak_equiv(const HTTPEntityTag &other) const; @@ -41,14 +41,14 @@ PUBLISHED: INLINE bool operator < (const HTTPEntityTag &other) const; INLINE int compare_to(const HTTPEntityTag &other) const; - INLINE void output(ostream &out) const; + INLINE void output(std::ostream &out) const; private: bool _weak; - string _tag; + std::string _tag; }; -INLINE ostream &operator << (ostream &out, const HTTPEntityTag &url); +INLINE std::ostream &operator << (std::ostream &out, const HTTPEntityTag &url); #include "httpEntityTag.I" diff --git a/panda/src/downloader/httpEnum.cxx b/panda/src/downloader/httpEnum.cxx index 1ef09de254..ebe7914110 100644 --- a/panda/src/downloader/httpEnum.cxx +++ b/panda/src/downloader/httpEnum.cxx @@ -18,8 +18,8 @@ /** * */ -ostream & -operator << (ostream &out, HTTPEnum::Method method) { +std::ostream & +operator << (std::ostream &out, HTTPEnum::Method method) { switch (method) { case HTTPEnum::M_options: out << "OPTIONS"; diff --git a/panda/src/downloader/httpEnum.h b/panda/src/downloader/httpEnum.h index 587c5b8b28..1beec15753 100644 --- a/panda/src/downloader/httpEnum.h +++ b/panda/src/downloader/httpEnum.h @@ -26,7 +26,7 @@ * This class is just used as a namespace wrapper for some of the enumerated * types used by various classes within the HTTPClient family. */ -class EXPCL_PANDAEXPRESS HTTPEnum { +class EXPCL_PANDA_DOWNLOADER HTTPEnum { PUBLISHED: enum HTTPVersion { HV_09, // HTTP 0.9 or older @@ -47,7 +47,7 @@ PUBLISHED: }; }; -ostream &operator << (ostream &out, HTTPEnum::Method method); +std::ostream &operator << (std::ostream &out, HTTPEnum::Method method); #endif // HAVE_OPENSSL diff --git a/panda/src/downloader/identityStream.cxx b/panda/src/downloader/identityStream.cxx index f047ac1a6e..335cb9fd23 100644 --- a/panda/src/downloader/identityStream.cxx +++ b/panda/src/downloader/identityStream.cxx @@ -22,9 +22,9 @@ */ IIdentityStream:: ~IIdentityStream() { - if (_channel != (HTTPChannel *)NULL) { + if (_channel != nullptr) { _channel->body_stream_destructs(this); - _channel = NULL; + _channel = nullptr; } } diff --git a/panda/src/downloader/identityStreamBuf.I b/panda/src/downloader/identityStreamBuf.I index 6001a14fc0..b879886dd1 100644 --- a/panda/src/downloader/identityStreamBuf.I +++ b/panda/src/downloader/identityStreamBuf.I @@ -16,7 +16,7 @@ */ INLINE bool IdentityStreamBuf:: is_closed() const { - return (_source == (BioStreamPtr *)NULL || (*_source)->is_closed()); + return (_source == nullptr || (*_source)->is_closed()); } /** diff --git a/panda/src/downloader/identityStreamBuf.cxx b/panda/src/downloader/identityStreamBuf.cxx index a11f1cfda3..852c252f32 100644 --- a/panda/src/downloader/identityStreamBuf.cxx +++ b/panda/src/downloader/identityStreamBuf.cxx @@ -17,11 +17,6 @@ #ifdef HAVE_OPENSSL #include "httpChannel.h" -#ifndef HAVE_STREAMSIZE -// Some compilers (notably SGI) don't define this for us -typedef int streamsize; -#endif /* HAVE_STREAMSIZE */ - /** * */ @@ -145,7 +140,7 @@ read_chars(char *start, size_t length) { // content_length restriction. if (_bytes_remaining != 0) { - length = min(length, _bytes_remaining); + length = std::min(length, _bytes_remaining); (*_source)->read(start, length); read_count = (*_source)->gcount(); if (!_wanted_nonblocking) { diff --git a/panda/src/downloader/identityStreamBuf.h b/panda/src/downloader/identityStreamBuf.h index f9d00a6626..f889bb1714 100644 --- a/panda/src/downloader/identityStreamBuf.h +++ b/panda/src/downloader/identityStreamBuf.h @@ -28,7 +28,7 @@ class HTTPChannel; /** * The streambuf object that implements IIdentityStream. */ -class EXPCL_PANDAEXPRESS IdentityStreamBuf : public streambuf { +class EXPCL_PANDA_DOWNLOADER IdentityStreamBuf : public std::streambuf { public: IdentityStreamBuf(); virtual ~IdentityStreamBuf(); diff --git a/panda/src/downloader/multiplexStream.I b/panda/src/downloader/multiplexStream.I index 1da8528d0b..aff3d4a064 100644 --- a/panda/src/downloader/multiplexStream.I +++ b/panda/src/downloader/multiplexStream.I @@ -15,8 +15,8 @@ * */ INLINE MultiplexStream:: -MultiplexStream() : ostream(&_msb) { - setf(ios::unitbuf); +MultiplexStream() : std::ostream(&_msb) { + setf(std::ios::unitbuf); } /** @@ -24,10 +24,10 @@ MultiplexStream() : ostream(&_msb) { * will receive whatever data is sent to the pipe. */ INLINE void MultiplexStream:: -add_ostream(ostream *out, bool delete_later) { +add_ostream(std::ostream *out, bool delete_later) { _msb.add_output(MultiplexStreamBuf::BT_none, MultiplexStreamBuf::OT_ostream, - out, NULL, delete_later); + out, nullptr, delete_later); } /** @@ -38,7 +38,7 @@ INLINE bool MultiplexStream:: add_stdio_file(FILE *fout, bool close_when_done) { _msb.add_output(MultiplexStreamBuf::BT_line, MultiplexStreamBuf::OT_ostream, - NULL, fout, close_when_done); + nullptr, fout, close_when_done); return true; } @@ -49,7 +49,7 @@ INLINE void MultiplexStream:: add_standard_output() { _msb.add_output(MultiplexStreamBuf::BT_none, MultiplexStreamBuf::OT_ostream, - &cout, NULL, false); + &std::cout, nullptr, false); } /** @@ -64,11 +64,11 @@ add_file(Filename file) { delete out; return false; } - out->setf(ios::unitbuf); + out->setf(std::ios::unitbuf); _msb.add_output(MultiplexStreamBuf::BT_line, MultiplexStreamBuf::OT_ostream, - out, NULL, true); + out, nullptr, true); return true; } diff --git a/panda/src/downloader/multiplexStream.h b/panda/src/downloader/multiplexStream.h index cf421860cf..90b00d1e01 100644 --- a/panda/src/downloader/multiplexStream.h +++ b/panda/src/downloader/multiplexStream.h @@ -28,7 +28,7 @@ * a disk file or to system logging utilities. It's a very handy thing to set * Notify to refer to when running in batch mode. */ -class EXPCL_PANDAEXPRESS MultiplexStream : public ostream { +class EXPCL_PANDA_DOWNLOADER MultiplexStream : public std::ostream { PUBLISHED: INLINE MultiplexStream(); @@ -36,7 +36,7 @@ PUBLISHED: INLINE MultiplexStream(const MultiplexStream ©) = delete; #endif - INLINE void add_ostream(ostream *out, bool delete_later = false); + INLINE void add_ostream(std::ostream *out, bool delete_later = false); INLINE bool add_stdio_file(FILE *file, bool close_when_done); INLINE void add_standard_output(); INLINE bool add_file(Filename file); diff --git a/panda/src/downloader/multiplexStreamBuf.cxx b/panda/src/downloader/multiplexStreamBuf.cxx index 96d4a22755..aa42d33f9e 100644 --- a/panda/src/downloader/multiplexStreamBuf.cxx +++ b/panda/src/downloader/multiplexStreamBuf.cxx @@ -24,10 +24,7 @@ // recursion. #include -#ifndef HAVE_STREAMSIZE -// Some compilers--notably SGI--don't define this for us. -typedef int streamsize; -#endif +using std::string; /** * Closes or deletes the relevant pointers, if _owns_obj is true. @@ -37,12 +34,12 @@ close() { if (_owns_obj) { switch (_output_type) { case OT_ostream: - assert(_out != (ostream *)NULL); + assert(_out != nullptr); delete _out; break; case OT_stdio: - assert(_fout != (FILE *)NULL); + assert(_fout != nullptr); fclose(_fout); break; @@ -59,13 +56,13 @@ void MultiplexStreamBuf::Output:: write_string(const string &str) { switch (_output_type) { case OT_ostream: - assert(_out != (ostream *)NULL); + assert(_out != nullptr); _out->write(str.data(), str.length()); _out->flush(); break; case OT_stdio: - assert(_fout != (FILE *)NULL); + assert(_fout != nullptr); fwrite(str.data(), str.length(), 1, _fout); fflush(_fout); break; @@ -112,7 +109,7 @@ MultiplexStreamBuf:: void MultiplexStreamBuf:: add_output(MultiplexStreamBuf::BufferType buffer_type, MultiplexStreamBuf::OutputType output_type, - ostream *out, FILE *fout, bool owns_obj) { + std::ostream *out, FILE *fout, bool owns_obj) { Output o; o._buffer_type = buffer_type; @@ -122,9 +119,9 @@ add_output(MultiplexStreamBuf::BufferType buffer_type, o._owns_obj = owns_obj; // Ensure that we have the mutex while we fiddle with the list of outputs. - _lock.acquire(); + _lock.lock(); _outputs.push_back(o); - _lock.release(); + _lock.unlock(); } @@ -133,9 +130,9 @@ add_output(MultiplexStreamBuf::BufferType buffer_type, */ void MultiplexStreamBuf:: flush() { - _lock.acquire(); + _lock.lock(); write_chars("", 0, true); - _lock.release(); + _lock.unlock(); } /** @@ -144,9 +141,9 @@ flush() { */ int MultiplexStreamBuf:: overflow(int ch) { - _lock.acquire(); + _lock.lock(); - streamsize n = pptr() - pbase(); + std::streamsize n = pptr() - pbase(); if (n != 0) { write_chars(pbase(), n, false); @@ -159,7 +156,7 @@ overflow(int ch) { write_chars(&c, 1, false); } - _lock.release(); + _lock.unlock(); return 0; } @@ -169,9 +166,9 @@ overflow(int ch) { */ int MultiplexStreamBuf:: sync() { - _lock.acquire(); + _lock.lock(); - streamsize n = pptr() - pbase(); + std::streamsize n = pptr() - pbase(); // We pass in false for the flush value, even though our transmitting // ostream said to sync. This allows us to get better line buffering, since @@ -181,7 +178,7 @@ sync() { write_chars(pbase(), n, false); pbump(-n); - _lock.release(); + _lock.unlock(); return 0; // Return 0 for success, EOF to indicate write full. } diff --git a/panda/src/downloader/multiplexStreamBuf.h b/panda/src/downloader/multiplexStreamBuf.h index d869124116..8126b5894e 100644 --- a/panda/src/downloader/multiplexStreamBuf.h +++ b/panda/src/downloader/multiplexStreamBuf.h @@ -24,7 +24,7 @@ * Used by MultiplexStream to implement an ostream that sends what is written * to it to any number of additional sources, like other ostreams. */ -class EXPCL_PANDAEXPRESS MultiplexStreamBuf : public streambuf { +class EXPCL_PANDA_DOWNLOADER MultiplexStreamBuf : public std::streambuf { public: MultiplexStreamBuf(); virtual ~MultiplexStreamBuf(); @@ -41,8 +41,8 @@ public: }; void add_output(BufferType buffer_type, OutputType output_type, - ostream *out = (ostream *)NULL, - FILE *fout = (FILE *)NULL, + std::ostream *out = nullptr, + FILE *fout = nullptr, bool owns_obj = false); void flush(); @@ -58,11 +58,11 @@ private: class Output { public: void close(); - void write_string(const string &str); + void write_string(const std::string &str); BufferType _buffer_type; OutputType _output_type; - ostream *_out; + std::ostream *_out; FILE *_fout; bool _owns_obj; }; @@ -71,7 +71,7 @@ private: Outputs _outputs; MutexImpl _lock; - string _line_buffer; + std::string _line_buffer; }; #include "multiplexStreamBuf.I" diff --git a/panda/src/downloader/patcher.cxx b/panda/src/downloader/patcher.cxx index 70d0f99ef2..c0b86f2c61 100644 --- a/panda/src/downloader/patcher.cxx +++ b/panda/src/downloader/patcher.cxx @@ -44,7 +44,7 @@ init(PT(Buffer) buffer) { nassertv(!buffer.is_null()); _buffer = buffer; - _patchfile = NULL; + _patchfile = nullptr; _patchfile = new Patchfile(_buffer); } diff --git a/panda/src/downloader/patcher.h b/panda/src/downloader/patcher.h index bf4ffdd351..bc2d30e7bc 100644 --- a/panda/src/downloader/patcher.h +++ b/panda/src/downloader/patcher.h @@ -25,7 +25,7 @@ /** * Applies a patch synchronously */ -class EXPCL_PANDAEXPRESS Patcher { +class EXPCL_PANDA_DOWNLOADER Patcher { PUBLISHED: Patcher(); explicit Patcher(PT(Buffer) buffer); diff --git a/panda/src/downloader/socketStream.I b/panda/src/downloader/socketStream.I index 21026ebdb4..800ed89499 100644 --- a/panda/src/downloader/socketStream.I +++ b/panda/src/downloader/socketStream.I @@ -161,15 +161,15 @@ flush() { * */ INLINE ISocketStream:: -ISocketStream(streambuf *buf) : istream(buf), SSReader(this) { - _channel = NULL; +ISocketStream(std::streambuf *buf) : std::istream(buf), SSReader(this) { + _channel = nullptr; } /** * */ INLINE OSocketStream:: -OSocketStream(streambuf *buf) : ostream(buf), SSWriter(this) { +OSocketStream(std::streambuf *buf) : std::ostream(buf), SSWriter(this) { } /** @@ -185,7 +185,7 @@ flush() { * */ INLINE SocketStream:: -SocketStream(streambuf *buf) : iostream(buf), SSReader(this), SSWriter(this) { +SocketStream(std::streambuf *buf) : std::iostream(buf), SSReader(this), SSWriter(this) { } /** diff --git a/panda/src/downloader/socketStream.cxx b/panda/src/downloader/socketStream.cxx index 4e441f8f2b..eec65d1857 100644 --- a/panda/src/downloader/socketStream.cxx +++ b/panda/src/downloader/socketStream.cxx @@ -23,7 +23,7 @@ * */ SSReader:: -SSReader(istream *stream) : _istream(stream) { +SSReader(std::istream *stream) : _istream(stream) { _data_expected = 0; _tcp_header_size = tcp_header_size; @@ -84,13 +84,13 @@ do_receive_datagram(Datagram &dg) { static const size_t buffer_size = 1024; char buffer[buffer_size]; - size_t read_count = min(_data_expected - _data_so_far.size(), buffer_size); + size_t read_count = std::min(_data_expected - _data_so_far.size(), buffer_size); _istream->read(buffer, read_count); size_t count = _istream->gcount(); while (count != 0) { _data_so_far.insert(_data_so_far.end(), buffer, buffer + count); - read_count = min(_data_expected - _data_so_far.size(), + read_count = std::min(_data_expected - _data_so_far.size(), buffer_size); _istream->read(buffer, read_count); count = _istream->gcount(); @@ -126,7 +126,7 @@ do_receive_datagram(Datagram &dg) { void SSReader:: start_delay(double min_delay, double max_delay) { _min_delay = min_delay; - _delay_variance = max(max_delay - min_delay, 0.0); + _delay_variance = std::max(max_delay - min_delay, 0.0); _delay_active = true; } #endif // SIMULATE_NETWORK_DELAY @@ -194,7 +194,7 @@ get_delayed(Datagram &datagram) { * */ SSWriter:: -SSWriter(ostream *stream) : _ostream(stream) { +SSWriter(std::ostream *stream) : _ostream(stream) { _collect_tcp = collect_tcp; _collect_tcp_interval = collect_tcp_interval; _queued_data_start = 0.0; @@ -248,7 +248,7 @@ send_datagram(const Datagram &dg) { ISocketStream:: ~ISocketStream() { // This should already have been cleared by the subclass destructor. - nassertv(_channel == NULL); + nassertv(_channel == nullptr); } #endif // HAVE_OPENSSL diff --git a/panda/src/downloader/socketStream.h b/panda/src/downloader/socketStream.h index 84ce907a5e..6d52e0e79a 100644 --- a/panda/src/downloader/socketStream.h +++ b/panda/src/downloader/socketStream.h @@ -36,9 +36,9 @@ class HTTPChannel; * class for both ISocketStream and SocketStream; its purpose is to minimize * redundant code between them. Do not use it directly. */ -class EXPCL_PANDAEXPRESS SSReader { +class EXPCL_PANDA_DOWNLOADER SSReader { public: - SSReader(istream *stream); + SSReader(std::istream *stream); virtual ~SSReader(); PUBLISHED: @@ -53,7 +53,7 @@ PUBLISHED: private: bool do_receive_datagram(Datagram &dg); - istream *_istream; + std::istream *_istream; size_t _data_expected; vector_uchar _data_so_far; int _tcp_header_size; @@ -86,9 +86,9 @@ private: * class for both OSocketStream and SocketStream; its purpose is to minimize * redundant code between them. Do not use it directly. */ -class EXPCL_PANDAEXPRESS SSWriter { +class EXPCL_PANDA_DOWNLOADER SSWriter { public: - SSWriter(ostream *stream); + SSWriter(std::ostream *stream); virtual ~SSWriter(); PUBLISHED: @@ -109,7 +109,7 @@ PUBLISHED: INLINE bool flush(); private: - ostream *_ostream; + std::ostream *_ostream; bool _collect_tcp; double _collect_tcp_interval; double _queued_data_start; @@ -122,9 +122,9 @@ private: * after an eof condition to check whether the socket has been closed, or * whether more data may be available later. */ -class EXPCL_PANDAEXPRESS ISocketStream : public istream, public SSReader { +class EXPCL_PANDA_DOWNLOADER ISocketStream : public std::istream, public SSReader { public: - INLINE ISocketStream(streambuf *buf); + INLINE ISocketStream(std::streambuf *buf); virtual ~ISocketStream(); #if _MSC_VER >= 1800 @@ -156,9 +156,9 @@ private: * check whether the socket has been closed, or whether more data may be sent * later. */ -class EXPCL_PANDAEXPRESS OSocketStream : public ostream, public SSWriter { +class EXPCL_PANDA_DOWNLOADER OSocketStream : public std::ostream, public SSWriter { public: - INLINE OSocketStream(streambuf *buf); + INLINE OSocketStream(std::streambuf *buf); #if _MSC_VER >= 1800 INLINE OSocketStream(const OSocketStream ©) = delete; @@ -175,9 +175,9 @@ PUBLISHED: * A base class for iostreams that read and write to a (possibly non-blocking) * socket. */ -class EXPCL_PANDAEXPRESS SocketStream : public iostream, public SSReader, public SSWriter { +class EXPCL_PANDA_DOWNLOADER SocketStream : public std::iostream, public SSReader, public SSWriter { public: - INLINE SocketStream(streambuf *buf); + INLINE SocketStream(std::streambuf *buf); #if _MSC_VER >= 1800 INLINE SocketStream(const SocketStream ©) = delete; diff --git a/panda/src/downloader/stringStream.I b/panda/src/downloader/stringStream.I index 6e1b173c40..7d1e59fc8f 100644 --- a/panda/src/downloader/stringStream.I +++ b/panda/src/downloader/stringStream.I @@ -15,7 +15,7 @@ * */ INLINE StringStream:: -StringStream() : iostream(&_buf) { +StringStream() : std::iostream(&_buf) { } /** @@ -23,7 +23,7 @@ StringStream() : iostream(&_buf) { * data. */ INLINE StringStream:: -StringStream(const string &source) : iostream(&_buf) { +StringStream(const std::string &source) : std::iostream(&_buf) { set_data(source); } @@ -47,21 +47,21 @@ get_data_size() { /** * Returns the contents of the data stream as a string. */ -INLINE string StringStream:: +INLINE std::string StringStream:: get_data() { flush(); const vector_uchar &data = _buf.get_data(); if (!data.empty()) { - return string((char *)&data[0], data.size()); + return std::string((char *)&data[0], data.size()); } - return string(); + return std::string(); } /** * Replaces the contents of the data stream. This implicitly reseeks to 0. */ INLINE void StringStream:: -set_data(const string &data) { +set_data(const std::string &data) { _buf.clear(); if (!data.empty()) { set_data((const unsigned char *)data.data(), data.size()); diff --git a/panda/src/downloader/stringStream.h b/panda/src/downloader/stringStream.h index 2075f817fd..a91dd0eea5 100644 --- a/panda/src/downloader/stringStream.h +++ b/panda/src/downloader/stringStream.h @@ -24,9 +24,9 @@ * buffer, which can be retrieved and/or set as a string in Python 2 or a * bytes object in Python 3. */ -class EXPCL_PANDAEXPRESS StringStream : public iostream { +class EXPCL_PANDA_DOWNLOADER StringStream : public std::iostream { public: - INLINE StringStream(const string &source); + INLINE StringStream(const std::string &source); PUBLISHED: EXTENSION(StringStream(PyObject *source)); @@ -46,8 +46,8 @@ PUBLISHED: public: #ifndef CPPPARSER - INLINE string get_data(); - INLINE void set_data(const string &data); + INLINE std::string get_data(); + INLINE void set_data(const std::string &data); void set_data(const unsigned char *data, size_t size); #endif diff --git a/panda/src/downloader/stringStreamBuf.cxx b/panda/src/downloader/stringStreamBuf.cxx index 4067ca1acb..f9a6cc99f9 100644 --- a/panda/src/downloader/stringStreamBuf.cxx +++ b/panda/src/downloader/stringStreamBuf.cxx @@ -15,6 +15,10 @@ #include "pnotify.h" #include "config_express.h" +using std::ios; +using std::streamoff; +using std::streampos; + /** * */ @@ -82,7 +86,7 @@ read_chars(char *start, size_t length) { return 0; } - length = min(length, _data.size() - _gpos); + length = std::min(length, _data.size() - _gpos); memcpy(start, &_data[_gpos], length); _gpos += length; return length; @@ -102,7 +106,7 @@ write_chars(const char *start, size_t length) { if (_data.size() > _ppos) { // We are overwriting some data. size_t remaining_length = _data.size() - _ppos; - size_t overwrite_length = min(remaining_length, length); + size_t overwrite_length = std::min(remaining_length, length); memcpy(&_data[_ppos], start, overwrite_length); length -= overwrite_length; _ppos += overwrite_length; diff --git a/panda/src/downloader/stringStreamBuf.h b/panda/src/downloader/stringStreamBuf.h index 9ddff66ae7..333e945197 100644 --- a/panda/src/downloader/stringStreamBuf.h +++ b/panda/src/downloader/stringStreamBuf.h @@ -22,7 +22,7 @@ * to a memory buffer, whose contents can be appended to or extracted at any * time by application code. */ -class EXPCL_PANDAEXPRESS StringStreamBuf : public streambuf { +class EXPCL_PANDA_DOWNLOADER StringStreamBuf : public std::streambuf { public: StringStreamBuf(); virtual ~StringStreamBuf(); @@ -36,8 +36,8 @@ public: void write_chars(const char *start, size_t length); protected: - virtual streampos seekoff(streamoff off, ios_seekdir dir, ios_openmode which); - virtual streampos seekpos(streampos pos, ios_openmode which); + virtual std::streampos seekoff(std::streamoff off, ios_seekdir dir, ios_openmode which); + virtual std::streampos seekpos(std::streampos pos, ios_openmode which); virtual int overflow(int c); virtual int sync(); diff --git a/panda/src/downloader/stringStream_ext.cxx b/panda/src/downloader/stringStream_ext.cxx index c9d66ca0a7..631c6f4a04 100644 --- a/panda/src/downloader/stringStream_ext.cxx +++ b/panda/src/downloader/stringStream_ext.cxx @@ -51,7 +51,7 @@ void Extension:: set_data(PyObject *data) { _this->_buf.clear(); - if (data == NULL) { + if (data == nullptr) { return; } diff --git a/panda/src/downloader/urlSpec.I b/panda/src/downloader/urlSpec.I index 7af6f4339b..083b2ca9f5 100644 --- a/panda/src/downloader/urlSpec.I +++ b/panda/src/downloader/urlSpec.I @@ -15,7 +15,7 @@ * */ INLINE URLSpec:: -URLSpec(const string &url, bool server_name_expected) { +URLSpec(const std::string &url, bool server_name_expected) { set_url(url, server_name_expected); } @@ -23,7 +23,7 @@ URLSpec(const string &url, bool server_name_expected) { * */ INLINE void URLSpec:: -operator = (const string &url) { +operator = (const std::string &url) { set_url(url); } @@ -115,7 +115,7 @@ has_query() const { * Returns the authority specified by the URL (this includes username, server, * and/or port), or empty string if no authority is specified. */ -INLINE string URLSpec:: +INLINE std::string URLSpec:: get_authority() const { return _url.substr(_username_start, _port_end - _username_start); } @@ -125,7 +125,7 @@ get_authority() const { * a password, e.g. "username:password", although putting a password on the * URL is probably a bad idea. */ -INLINE string URLSpec:: +INLINE std::string URLSpec:: get_username() const { return _url.substr(_username_start, _username_end - _username_start); } @@ -134,7 +134,7 @@ get_username() const { * Returns the server name specified by the URL, if any. In case of an IPv6 * address, does not include the enclosing brackets. */ -INLINE string URLSpec:: +INLINE std::string URLSpec:: get_server() const { return _url.substr(_server_start, _server_end - _server_start); } @@ -144,7 +144,7 @@ get_server() const { * no port is specified. Compare this with get_port(), which returns a * default port number if no port is specified. */ -INLINE string URLSpec:: +INLINE std::string URLSpec:: get_port_str() const { return _url.substr(_port_start, _port_end - _port_start); } @@ -153,7 +153,7 @@ get_port_str() const { * Returns the query specified by the URL, or empty string if no query is * specified. */ -INLINE string URLSpec:: +INLINE std::string URLSpec:: get_query() const { return _url.substr(_query_start); } @@ -180,7 +180,7 @@ is_ssl() const { /** * Returns the complete URL specification. */ -INLINE const string &URLSpec:: +INLINE const std::string &URLSpec:: get_url() const { return _url; } @@ -189,7 +189,7 @@ get_url() const { * */ INLINE URLSpec:: -operator const string & () const { +operator const std::string & () const { return _url; } @@ -244,16 +244,16 @@ operator [] (size_t n) const { return _url[n]; } -INLINE istream & -operator >> (istream &in, URLSpec &url) { +INLINE std::istream & +operator >> (std::istream &in, URLSpec &url) { if (!url.input(in)) { - in.clear(ios::failbit | in.rdstate()); + in.clear(std::ios::failbit | in.rdstate()); } return in; } -INLINE ostream & -operator << (ostream &out, const URLSpec &url) { +INLINE std::ostream & +operator << (std::ostream &out, const URLSpec &url) { url.output(out); return out; } diff --git a/panda/src/downloader/urlSpec.cxx b/panda/src/downloader/urlSpec.cxx index 09769f3693..1925c6a775 100644 --- a/panda/src/downloader/urlSpec.cxx +++ b/panda/src/downloader/urlSpec.cxx @@ -17,6 +17,13 @@ #include +using std::istream; +using std::ostream; +using std::ostringstream; +using std::setfill; +using std::setw; +using std::string; + /** * */ @@ -711,7 +718,7 @@ output(ostream &out) const { string URLSpec:: quote(const string &source, const string &safe) { ostringstream result; - result << hex << setfill('0'); + result << std::hex << setfill('0'); for (string::const_iterator si = source.begin(); si != source.end(); ++si) { char ch = (*si); @@ -750,7 +757,7 @@ quote(const string &source, const string &safe) { string URLSpec:: quote_plus(const string &source, const string &safe) { ostringstream result; - result << hex << setfill('0'); + result << std::hex << setfill('0'); for (string::const_iterator si = source.begin(); si != source.end(); ++si) { char ch = (*si); diff --git a/panda/src/downloader/urlSpec.h b/panda/src/downloader/urlSpec.h index 592fe22087..df5a7b9bb6 100644 --- a/panda/src/downloader/urlSpec.h +++ b/panda/src/downloader/urlSpec.h @@ -25,12 +25,12 @@ class Filename; * The URLSpec object is similar to a Filename in that it contains logic to * identify the various parts of a URL and return (or modify) them separately. */ -class EXPCL_PANDAEXPRESS URLSpec { +class EXPCL_PANDA_DOWNLOADER URLSpec { PUBLISHED: URLSpec(); - INLINE URLSpec(const string &url, bool server_name_expected = false); + INLINE URLSpec(const std::string &url, bool server_name_expected = false); URLSpec(const URLSpec &url, const Filename &path); - INLINE void operator = (const string &url); + INLINE void operator = (const std::string &url); INLINE bool operator == (const URLSpec &other) const; INLINE bool operator != (const URLSpec &other) const; @@ -46,35 +46,35 @@ PUBLISHED: INLINE bool has_path() const; INLINE bool has_query() const; - string get_scheme() const; - INLINE string get_authority() const; - INLINE string get_username() const; - INLINE string get_server() const; - INLINE string get_port_str() const; + std::string get_scheme() const; + INLINE std::string get_authority() const; + INLINE std::string get_username() const; + INLINE std::string get_server() const; + INLINE std::string get_port_str() const; uint16_t get_port() const; - string get_server_and_port() const; + std::string get_server_and_port() const; bool is_default_port() const; - static int get_default_port_for_scheme(const string &scheme); - string get_path() const; - INLINE string get_query() const; - string get_path_and_query() const; + static int get_default_port_for_scheme(const std::string &scheme); + std::string get_path() const; + INLINE std::string get_query() const; + std::string get_path_and_query() const; INLINE bool is_ssl() const; - INLINE const string &get_url() const; + INLINE const std::string &get_url() const; - void set_scheme(const string &scheme); - void set_authority(const string &authority); - void set_username(const string &username); - void set_server(const string &server); - void set_port(const string &port); + void set_scheme(const std::string &scheme); + void set_authority(const std::string &authority); + void set_username(const std::string &username); + void set_server(const std::string &server); + void set_port(const std::string &port); void set_port(uint16_t port); - void set_server_and_port(const string &server_and_port); - void set_path(const string &path); - void set_query(const string &query); + void set_server_and_port(const std::string &server_and_port); + void set_path(const std::string &path); + void set_query(const std::string &query); - void set_url(const string &url, bool server_name_expected = false); + void set_url(const std::string &url, bool server_name_expected = false); - INLINE operator const string & () const; + INLINE operator const std::string & () const; INLINE const char *c_str() const; INLINE bool empty() const; INLINE operator bool() const; @@ -82,13 +82,13 @@ PUBLISHED: INLINE size_t size() const; INLINE char operator [] (size_t n) const; - bool input(istream &in); - void output(ostream &out) const; + bool input(std::istream &in); + void output(std::ostream &out) const; - static string quote(const string &source, const string &safe = "/"); - static string quote_plus(const string &source, const string &safe = "/"); - static string unquote(const string &source); - static string unquote_plus(const string &source); + static std::string quote(const std::string &source, const std::string &safe = "/"); + static std::string quote_plus(const std::string &source, const std::string &safe = "/"); + static std::string unquote(const std::string &source); + static std::string unquote_plus(const std::string &source); MAKE_PROPERTY(scheme, get_scheme, set_scheme); MAKE_PROPERTY(authority, get_authority, set_authority); @@ -113,7 +113,7 @@ private: F_has_query = 0x0040, }; - string _url; + std::string _url; uint16_t _port; int _flags; @@ -129,8 +129,8 @@ private: size_t _query_start; }; -INLINE istream &operator >> (istream &in, URLSpec &url); -INLINE ostream &operator << (ostream &out, const URLSpec &url); +INLINE std::istream &operator >> (std::istream &in, URLSpec &url); +INLINE std::ostream &operator << (std::ostream &out, const URLSpec &url); #include "urlSpec.I" diff --git a/panda/src/downloader/virtualFileHTTP.cxx b/panda/src/downloader/virtualFileHTTP.cxx index 03bfaa1737..527e9c619b 100644 --- a/panda/src/downloader/virtualFileHTTP.cxx +++ b/panda/src/downloader/virtualFileHTTP.cxx @@ -18,6 +18,10 @@ #ifdef HAVE_OPENSSL +using std::istream; +using std::ostream; +using std::string; + TypeHandle VirtualFileHTTP::_type_handle; @@ -121,7 +125,7 @@ is_regular_file() const { istream *VirtualFileHTTP:: open_read_file(bool auto_unwrap) const { if (_status_only) { - return NULL; + return nullptr; } // We pre-download the file into a StringStream, then return a buffer to @@ -130,7 +134,7 @@ open_read_file(bool auto_unwrap) const { StringStream *strstream = new StringStream; if (!fetch_file(strstream)) { delete strstream; - return NULL; + return nullptr; } return return_file(strstream, auto_unwrap); @@ -178,7 +182,7 @@ return_file(istream *buffer_stream, bool auto_unwrap) const { istream *result = buffer_stream; #ifdef HAVE_ZLIB - if (result != (istream *)NULL && do_unwrap) { + if (result != nullptr && do_unwrap) { // We have to slip in a layer to decompress the file on the fly. IDecompressStream *wrapper = new IDecompressStream(result, true); result = wrapper; @@ -205,7 +209,7 @@ was_read_successful() const { * file. Pass in the stream that was returned by open_read_file(); some * implementations may require this stream to determine the size. */ -streamsize VirtualFileHTTP:: +std::streamsize VirtualFileHTTP:: get_file_size(istream *stream) const { return _channel->get_file_size(); } @@ -214,7 +218,7 @@ get_file_size(istream *stream) const { * Returns the current size on disk (or wherever it is) of the file before it * has been opened. */ -streamsize VirtualFileHTTP:: +std::streamsize VirtualFileHTTP:: get_file_size() const { return _channel->get_file_size(); } diff --git a/panda/src/downloader/virtualFileHTTP.h b/panda/src/downloader/virtualFileHTTP.h index 7b5426566c..eaf63f0465 100644 --- a/panda/src/downloader/virtualFileHTTP.h +++ b/panda/src/downloader/virtualFileHTTP.h @@ -29,7 +29,7 @@ class VirtualFileMountHTTP; * VirtualFileSystem, allowing models etc. to be loaded directly from a web * page. */ -class EXPCL_PANDAEXPRESS VirtualFileHTTP : public VirtualFile { +class EXPCL_PANDA_DOWNLOADER VirtualFileHTTP : public VirtualFile { public: VirtualFileHTTP(VirtualFileMountHTTP *mount, const Filename &local_filename, @@ -45,15 +45,15 @@ public: virtual bool is_regular_file() const; INLINE bool is_implicit_pz_file() const; - virtual istream *open_read_file(bool auto_unwrap) const; + virtual std::istream *open_read_file(bool auto_unwrap) const; virtual bool was_read_successful() const; - virtual streamsize get_file_size(istream *stream) const; - virtual streamsize get_file_size() const; + virtual std::streamsize get_file_size(std::istream *stream) const; + virtual std::streamsize get_file_size() const; virtual time_t get_timestamp() const; private: - bool fetch_file(ostream *buffer_stream) const; - istream *return_file(istream *buffer_stream, bool auto_unwrap) const; + bool fetch_file(std::ostream *buffer_stream) const; + std::istream *return_file(std::istream *buffer_stream, bool auto_unwrap) const; VirtualFileMountHTTP *_mount; Filename _local_filename; diff --git a/panda/src/downloader/virtualFileMountHTTP.cxx b/panda/src/downloader/virtualFileMountHTTP.cxx index 78b06a2f44..09625d53bc 100644 --- a/panda/src/downloader/virtualFileMountHTTP.cxx +++ b/panda/src/downloader/virtualFileMountHTTP.cxx @@ -17,6 +17,8 @@ #ifdef HAVE_OPENSSL +using std::string; + TypeHandle VirtualFileMountHTTP::_type_handle; @@ -166,7 +168,7 @@ make_virtual_file(const Filename &local_filename, new VirtualFileHTTP(this, local_filename, implicit_pz_file, open_flags); vfile->set_original_filename(original_filename); - return vfile.p(); + return vfile; } /** @@ -174,9 +176,9 @@ make_virtual_file(const Filename &local_filename, * istream on success (which you should eventually delete when you are done * reading). Returns NULL on failure. */ -istream *VirtualFileMountHTTP:: +std::istream *VirtualFileMountHTTP:: open_read_file(const Filename &) const { - return NULL; + return nullptr; } /** @@ -184,8 +186,8 @@ open_read_file(const Filename &) const { * file. Pass in the stream that was returned by open_read_file(); some * implementations may require this stream to determine the size. */ -streamsize VirtualFileMountHTTP:: -get_file_size(const Filename &, istream *) const { +std::streamsize VirtualFileMountHTTP:: +get_file_size(const Filename &, std::istream *) const { return 0; } @@ -193,7 +195,7 @@ get_file_size(const Filename &, istream *) const { * Returns the current size on disk (or wherever it is) of the file before it * has been opened. */ -streamsize VirtualFileMountHTTP:: +std::streamsize VirtualFileMountHTTP:: get_file_size(const Filename &) const { return 0; } @@ -227,7 +229,7 @@ scan_directory(vector_string &, const Filename &) const { * */ void VirtualFileMountHTTP:: -output(ostream &out) const { +output(std::ostream &out) const { out << _root; } @@ -238,7 +240,7 @@ output(ostream &out) const { PT(HTTPChannel) VirtualFileMountHTTP:: get_channel() { PT(HTTPChannel) channel; - _channels_lock.acquire(); + _channels_lock.lock(); if (!_channels.empty()) { // If we have some channels sitting around, grab one. Grab the one on the @@ -251,7 +253,7 @@ get_channel() { channel = _http->make_channel(true); } - _channels_lock.release(); + _channels_lock.unlock(); return channel; } @@ -262,9 +264,9 @@ get_channel() { */ void VirtualFileMountHTTP:: recycle_channel(HTTPChannel *channel) { - _channels_lock.acquire(); + _channels_lock.lock(); _channels.push_back(channel); - _channels_lock.release(); + _channels_lock.unlock(); } #endif // HAVE_OPENSSL diff --git a/panda/src/downloader/virtualFileMountHTTP.h b/panda/src/downloader/virtualFileMountHTTP.h index 996905a913..265e785c40 100644 --- a/panda/src/downloader/virtualFileMountHTTP.h +++ b/panda/src/downloader/virtualFileMountHTTP.h @@ -28,7 +28,7 @@ /** * Maps a web page (URL root) into the VirtualFileSystem. */ -class EXPCL_PANDAEXPRESS VirtualFileMountHTTP : public VirtualFileMount { +class EXPCL_PANDA_DOWNLOADER VirtualFileMountHTTP : public VirtualFileMount { PUBLISHED: explicit VirtualFileMountHTTP(const URLSpec &root, HTTPClient *http = HTTPClient::get_global_ptr()); virtual ~VirtualFileMountHTTP(); @@ -48,15 +48,15 @@ public: virtual bool is_directory(const Filename &file) const; virtual bool is_regular_file(const Filename &file) const; - virtual istream *open_read_file(const Filename &file) const; - virtual streamsize get_file_size(const Filename &file, istream *stream) const; - virtual streamsize get_file_size(const Filename &file) const; + virtual std::istream *open_read_file(const Filename &file) const; + virtual std::streamsize get_file_size(const Filename &file, std::istream *stream) const; + virtual std::streamsize get_file_size(const Filename &file) const; virtual time_t get_timestamp(const Filename &file) const; virtual bool scan_directory(vector_string &contents, const Filename &dir) const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; PT(HTTPChannel) get_channel(); void recycle_channel(HTTPChannel *channel); diff --git a/panda/src/downloadertools/apply_patch.cxx b/panda/src/downloadertools/apply_patch.cxx index 908f3c8189..502d67c89b 100644 --- a/panda/src/downloadertools/apply_patch.cxx +++ b/panda/src/downloadertools/apply_patch.cxx @@ -15,6 +15,9 @@ #include "patchfile.h" #include "filename.h" +using std::cerr; +using std::endl; + int main(int argc, char **argv) { preprocess_argv(argc, argv); diff --git a/panda/src/downloadertools/build_patch.cxx b/panda/src/downloadertools/build_patch.cxx index d14e27db9f..5c705bb38d 100644 --- a/panda/src/downloadertools/build_patch.cxx +++ b/panda/src/downloadertools/build_patch.cxx @@ -15,6 +15,9 @@ #include "patchfile.h" #include "filename.h" +using std::cerr; +using std::endl; + void usage() { cerr << "Usage: build_patch [opts] " << endl; diff --git a/panda/src/downloadertools/check_adler.cxx b/panda/src/downloadertools/check_adler.cxx index b53eb2839f..dbea94f8b7 100644 --- a/panda/src/downloadertools/check_adler.cxx +++ b/panda/src/downloadertools/check_adler.cxx @@ -14,13 +14,13 @@ int main(int argc, char *argv[]) { if (argc < 2) { - cerr << "Usage: check_adler " << endl; + std::cerr << "Usage: check_adler " << std::endl; return 1; } Filename source_file = argv[1]; - cout << check_adler(source_file); + std::cout << check_adler(source_file); return 0; } diff --git a/panda/src/downloadertools/check_crc.cxx b/panda/src/downloadertools/check_crc.cxx index 9afadd4fb2..e98de20b57 100644 --- a/panda/src/downloadertools/check_crc.cxx +++ b/panda/src/downloadertools/check_crc.cxx @@ -14,13 +14,13 @@ int main(int argc, char *argv[]) { if (argc < 2) { - cerr << "Usage: check_crc " << endl; + std::cerr << "Usage: check_crc " << std::endl; return 1; } Filename source_file = argv[1]; - cout << check_crc(source_file); + std::cout << check_crc(source_file); return 0; } diff --git a/panda/src/downloadertools/check_md5.cxx b/panda/src/downloadertools/check_md5.cxx index 5b386c7c1e..2cc3ce508e 100644 --- a/panda/src/downloadertools/check_md5.cxx +++ b/panda/src/downloadertools/check_md5.cxx @@ -15,6 +15,9 @@ #include "panda_getopt.h" #include "preprocess_argv.h" +using std::cerr; +using std::cout; + bool output_decimal = false; bool suppress_filename = false; pofstream binary_output; @@ -45,7 +48,7 @@ help() { } void -output_hash(const string &filename, const HashVal &hash) { +output_hash(const std::string &filename, const HashVal &hash) { if (!suppress_filename && !filename.empty()) { cout << filename << " "; } @@ -69,7 +72,7 @@ main(int argc, char **argv) { const char *optstr = "i:db:qh"; bool got_input_string = false; - string input_string; + std::string input_string; Filename binary_output_filename; preprocess_argv(argc, argv); @@ -87,7 +90,7 @@ main(int argc, char **argv) { break; case 'b': - binary_output_filename = Filename::binary_filename(string(optarg)); + binary_output_filename = Filename::binary_filename(std::string(optarg)); break; case 'q': diff --git a/panda/src/downloadertools/multify.cxx b/panda/src/downloadertools/multify.cxx index 8f3df9ce14..bea4c5bedd 100644 --- a/panda/src/downloadertools/multify.cxx +++ b/panda/src/downloadertools/multify.cxx @@ -21,6 +21,11 @@ #include #include +using std::cerr; +using std::cout; +using std::endl; +using std::string; + bool create = false; // -c bool append = false; // -r @@ -245,7 +250,7 @@ const string & get_password() { if (!got_password) { cerr << "Enter password: "; - getline(cin, password); + std::getline(std::cin, password); got_password = true; } @@ -610,7 +615,7 @@ format_timestamp(bool record_timestamp, time_t timestamp) { return " (no date) "; } - time_t now = time(NULL); + time_t now = time(nullptr); struct tm *tm_p = localtime(×tamp); if (timestamp > now || (now - timestamp > 86400 * 365)) { @@ -634,8 +639,8 @@ list_files(const vector_string ¶ms) { // We happen to know that we can read the index without doing a seek. // So this is the only place where we accept a .pz/.gz compressed .mf. VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); - istream *istr = vfs->open_read_file(multifile_name, true); - if (istr == NULL) { + std::istream *istr = vfs->open_read_file(multifile_name, true); + if (istr == nullptr) { cerr << "Unable to open " << multifile_name << " for reading.\n"; return false; } @@ -650,7 +655,7 @@ list_files(const vector_string ¶ms) { int i; if (verbose) { - cout << num_subfiles << " subfiles:\n" << flush; + cout << num_subfiles << " subfiles:\n" << std::flush; for (i = 0; i < num_subfiles; i++) { string subfile_name = multifile->get_subfile_name(i); if (is_named(subfile_name, params)) { diff --git a/panda/src/downloadertools/pdecrypt.cxx b/panda/src/downloadertools/pdecrypt.cxx index 73a242fda1..7763286b09 100644 --- a/panda/src/downloadertools/pdecrypt.cxx +++ b/panda/src/downloadertools/pdecrypt.cxx @@ -17,7 +17,10 @@ #include "panda_getopt.h" #include "preprocess_argv.h" -string password; +using std::cerr; +using std::endl; + +std::string password; bool got_password = false; void @@ -122,7 +125,7 @@ main(int argc, char **argv) { // Prompt for password. if (!got_password) { cerr << "Enter password: "; - getline(cin, password); + std::getline(std::cin, password); got_password = true; } diff --git a/panda/src/downloadertools/pencrypt.cxx b/panda/src/downloadertools/pencrypt.cxx index 5f8774c4d9..e40fbaba2c 100644 --- a/panda/src/downloadertools/pencrypt.cxx +++ b/panda/src/downloadertools/pencrypt.cxx @@ -17,9 +17,12 @@ #include "panda_getopt.h" #include "preprocess_argv.h" -string password; +using std::cerr; +using std::endl; + +std::string password; bool got_password = false; -string algorithm; +std::string algorithm; bool got_algorithm = false; int key_length = -1; bool got_key_length = false; @@ -181,7 +184,7 @@ main(int argc, char **argv) { // Prompt for password. if (!got_password) { cerr << "Enter password: "; - getline(cin, password); + std::getline(std::cin, password); got_password = true; } diff --git a/panda/src/downloadertools/punzip.cxx b/panda/src/downloadertools/punzip.cxx index 5753f7b6ec..84a593c795 100644 --- a/panda/src/downloadertools/punzip.cxx +++ b/panda/src/downloadertools/punzip.cxx @@ -15,6 +15,11 @@ #include "panda_getopt.h" #include "preprocess_argv.h" +using std::cerr; +using std::cin; +using std::cout; +using std::endl; + void usage() { cerr diff --git a/panda/src/downloadertools/pzip.cxx b/panda/src/downloadertools/pzip.cxx index 6364be0130..37c80e7f9f 100644 --- a/panda/src/downloadertools/pzip.cxx +++ b/panda/src/downloadertools/pzip.cxx @@ -15,6 +15,11 @@ #include "panda_getopt.h" #include "preprocess_argv.h" +using std::cerr; +using std::cin; +using std::cout; +using std::endl; + void usage() { cerr diff --git a/panda/src/downloadertools/show_ddb.cxx b/panda/src/downloadertools/show_ddb.cxx index d19c3be9cd..1b1a4abce4 100644 --- a/panda/src/downloadertools/show_ddb.cxx +++ b/panda/src/downloadertools/show_ddb.cxx @@ -18,7 +18,7 @@ int main(int argc, char *argv[]) { if (argc != 3) { - cerr << "Usage: show_ddb server.ddb client.ddb\n"; + std::cerr << "Usage: show_ddb server.ddb client.ddb\n"; return 1; } @@ -26,7 +26,7 @@ main(int argc, char *argv[]) { Filename client_ddb = Filename::from_os_specific(argv[2]); DownloadDb db(server_ddb, client_ddb); - db.write(cout); + db.write(std::cout); return 0; } diff --git a/panda/src/dxgsg9/dxGeomMunger9.I b/panda/src/dxgsg9/dxGeomMunger9.I index eee877c668..cc972bf94b 100644 --- a/panda/src/dxgsg9/dxGeomMunger9.I +++ b/panda/src/dxgsg9/dxGeomMunger9.I @@ -17,20 +17,27 @@ INLINE DXGeomMunger9:: DXGeomMunger9(GraphicsStateGuardian *gsg, const RenderState *state) : StandardMunger(gsg, state, 1, NT_packed_dabc, C_color), - _texture(DCAST(TextureAttrib, state->get_attrib(TextureAttrib::get_class_slot()))), - _tex_gen(DCAST(TexGenAttrib, state->get_attrib(TexGenAttrib::get_class_slot()))) + _texture(nullptr), + _tex_gen(nullptr) { - _filtered_texture = (TextureAttrib *)NULL; + const TextureAttrib *texture = nullptr; + const TexGenAttrib *tex_gen = nullptr; + state->get_attrib(texture); + state->get_attrib(tex_gen); + _texture = texture; + _tex_gen = tex_gen; + + _filtered_texture = nullptr; _reffed_filtered_texture = false; - if (_texture != (TextureAttrib *)NULL) { - _filtered_texture = _texture->filter_to_max(gsg->get_max_texture_stages()); - if (_filtered_texture != _texture) { + if (texture != nullptr) { + _filtered_texture = texture->filter_to_max(gsg->get_max_texture_stages()); + if (_filtered_texture != texture) { _filtered_texture->ref(); _reffed_filtered_texture = true; } } // Set a callback to unregister ourselves when either the Texture or the // TexGen object gets deleted. - _texture.set_callback(this); - _tex_gen.set_callback(this); + _texture.add_callback(this); + _tex_gen.add_callback(this); } diff --git a/panda/src/dxgsg9/dxGeomMunger9.cxx b/panda/src/dxgsg9/dxGeomMunger9.cxx index 44729ae0cd..8aa539c11f 100644 --- a/panda/src/dxgsg9/dxGeomMunger9.cxx +++ b/panda/src/dxgsg9/dxGeomMunger9.cxx @@ -16,7 +16,7 @@ #include "geomVertexWriter.h" #include "config_dxgsg9.h" -GeomMunger *DXGeomMunger9::_deleted_chain = NULL; +GeomMunger *DXGeomMunger9::_deleted_chain = nullptr; TypeHandle DXGeomMunger9::_type_handle; /** @@ -28,6 +28,9 @@ DXGeomMunger9:: unref_delete(_filtered_texture); _reffed_filtered_texture = false; } + + _texture.remove_callback(this); + _tex_gen.remove_callback(this); } /** @@ -69,7 +72,7 @@ munge_format_impl(const GeomVertexFormat *orig, const GeomVertexColumn *normal_type = orig->get_normal_column(); const GeomVertexColumn *color_type = orig->get_color_column(); - if (vertex_type != (const GeomVertexColumn *)NULL) { + if (vertex_type != nullptr) { new_array_format->add_column (InternalName::get_vertex(), 3, NT_float32, vertex_type->get_contents()); @@ -106,13 +109,13 @@ munge_format_impl(const GeomVertexFormat *orig, new_format->remove_column(InternalName::get_transform_blend()); } - if (normal_type != (const GeomVertexColumn *)NULL) { + if (normal_type != nullptr) { new_array_format->add_column (InternalName::get_normal(), 3, NT_float32, C_normal); new_format->remove_column(normal_type->get_name()); } - if (color_type != (const GeomVertexColumn *)NULL) { + if (color_type != nullptr) { new_array_format->add_column (InternalName::get_color(), 1, NT_packed_dabc, C_color); new_format->remove_column(color_type->get_name()); @@ -124,7 +127,7 @@ munge_format_impl(const GeomVertexFormat *orig, // Now set up each of the active texture coordinate stages--or at least // those for which we're not generating texture coordinates automatically. - if (_filtered_texture != (TextureAttrib *)NULL) { + if (_filtered_texture != nullptr) { int num_stages = _filtered_texture->get_num_on_ff_stages(); vector_int ff_tc_index(num_stages, 0); @@ -137,7 +140,7 @@ munge_format_impl(const GeomVertexFormat *orig, int tc_index = _filtered_texture->get_ff_tc_index(si); nassertr(tc_index < num_stages, orig); ff_tc_index[tc_index] = si; - max_tc_index = max(tc_index, max_tc_index); + max_tc_index = std::max(tc_index, max_tc_index); } // Now walk through the texture coordinates in the order they will appear @@ -150,7 +153,7 @@ munge_format_impl(const GeomVertexFormat *orig, const GeomVertexColumn *texcoord_type = orig->get_column(name); - if (texcoord_type != (const GeomVertexColumn *)NULL) { + if (texcoord_type != nullptr) { new_array_format->add_column (name, texcoord_type->get_num_values(), NT_float32, C_texcoord); } else { @@ -198,7 +201,7 @@ premunge_format_impl(const GeomVertexFormat *orig) { const GeomVertexColumn *normal_type = orig->get_normal_column(); const GeomVertexColumn *color_type = orig->get_color_column(); - if (vertex_type != (const GeomVertexColumn *)NULL) { + if (vertex_type != nullptr) { new_array_format->add_column (InternalName::get_vertex(), 3, NT_float32, vertex_type->get_contents()); @@ -209,13 +212,13 @@ premunge_format_impl(const GeomVertexFormat *orig) { return orig; } - if (normal_type != (const GeomVertexColumn *)NULL) { + if (normal_type != nullptr) { new_array_format->add_column (InternalName::get_normal(), 3, NT_float32, C_normal); new_format->remove_column(normal_type->get_name()); } - if (color_type != (const GeomVertexColumn *)NULL) { + if (color_type != nullptr) { new_array_format->add_column (InternalName::get_color(), 1, NT_packed_dabc, C_color); new_format->remove_column(color_type->get_name()); @@ -227,7 +230,7 @@ premunge_format_impl(const GeomVertexFormat *orig) { // Now set up each of the active texture coordinate stages--or at least // those for which we're not generating texture coordinates automatically. - if (_filtered_texture != (TextureAttrib *)NULL) { + if (_filtered_texture != nullptr) { int num_stages = _filtered_texture->get_num_on_ff_stages(); vector_int ff_tc_index(num_stages, 0); @@ -240,7 +243,7 @@ premunge_format_impl(const GeomVertexFormat *orig) { int tc_index = _filtered_texture->get_ff_tc_index(si); nassertr(tc_index < num_stages, orig); ff_tc_index[tc_index] = si; - max_tc_index = max(tc_index, max_tc_index); + max_tc_index = std::max(tc_index, max_tc_index); } // Now walk through the texture coordinates in the order they will appear @@ -253,7 +256,7 @@ premunge_format_impl(const GeomVertexFormat *orig) { const GeomVertexColumn *texcoord_type = orig->get_column(name); - if (texcoord_type != (const GeomVertexColumn *)NULL) { + if (texcoord_type != nullptr) { new_array_format->add_column (name, texcoord_type->get_num_values(), NT_float32, C_texcoord); } else { diff --git a/panda/src/dxgsg9/dxGraphicsDevice9.cxx b/panda/src/dxgsg9/dxGraphicsDevice9.cxx index 6e79bb3c98..3b7f0abd82 100644 --- a/panda/src/dxgsg9/dxGraphicsDevice9.cxx +++ b/panda/src/dxgsg9/dxGraphicsDevice9.cxx @@ -23,8 +23,8 @@ DXGraphicsDevice9(wdxGraphicsPipe9 *pipe) : GraphicsDevice(pipe) { ZeroMemory(&_Scrn,sizeof(_Scrn)); - _d3d_device = NULL; - _swap_chain = NULL; + _d3d_device = nullptr; + _swap_chain = nullptr; } /** diff --git a/panda/src/dxgsg9/dxGraphicsStateGuardian9.I b/panda/src/dxgsg9/dxGraphicsStateGuardian9.I index 94e50a5f7d..7e08862b2d 100644 --- a/panda/src/dxgsg9/dxGraphicsStateGuardian9.I +++ b/panda/src/dxgsg9/dxGraphicsStateGuardian9.I @@ -86,7 +86,7 @@ get_texture_wrap_mode(SamplerState::WrapMode wm) { case SamplerState::WM_border_color: return D3DTADDRESS_BORDER; } - dxgsg9_cat.error() << "Invalid Texture::Mode value" << endl; + dxgsg9_cat.error() << "Invalid Texture::Mode value" << std::endl; return D3DTADDRESS_WRAP; } @@ -103,7 +103,7 @@ get_fog_mode_type(Fog::Mode m) { case Fog::M_exponential_squared: return D3DFOG_EXP2; } - dxgsg9_cat.error() << "Invalid Fog::Mode value" << endl; + dxgsg9_cat.error() << "Invalid Fog::Mode value" << std::endl; return D3DFOG_EXP; } @@ -121,7 +121,7 @@ get_tex_mat_sym(int stage_index) { */ INLINE unsigned char *DXGraphicsStateGuardian9:: get_safe_buffer_start() { - if (_temp_buffer == NULL) { + if (_temp_buffer == nullptr) { // Guarantee we get a buffer of size 0x10000 bytes that begins on an even // multiple of 0x10000. We do this by allocating double the required // buffer, and then pointing to the first multiple of 0x10000 within that diff --git a/panda/src/dxgsg9/dxGraphicsStateGuardian9.cxx b/panda/src/dxgsg9/dxGraphicsStateGuardian9.cxx index 8326068dc1..0e5687d490 100644 --- a/panda/src/dxgsg9/dxGraphicsStateGuardian9.cxx +++ b/panda/src/dxgsg9/dxGraphicsStateGuardian9.cxx @@ -77,15 +77,19 @@ #define SDK_VERSION(major,minor) tostring(major) << "." << tostring(minor) #define DIRECTX_SDK_VERSION SDK_VERSION (_DXSDK_PRODUCT_MAJOR, _DXSDK_PRODUCT_MINOR) << "." << SDK_VERSION (_DXSDK_BUILD_MAJOR, _DXSDK_BUILD_MINOR) +using std::endl; +using std::max; +using std::min; + TypeHandle DXGraphicsStateGuardian9::_type_handle; D3DMATRIX DXGraphicsStateGuardian9::_d3d_ident_mat; -unsigned char *DXGraphicsStateGuardian9::_temp_buffer = NULL; -unsigned char *DXGraphicsStateGuardian9::_safe_buffer_start = NULL; +unsigned char *DXGraphicsStateGuardian9::_temp_buffer = nullptr; +unsigned char *DXGraphicsStateGuardian9::_safe_buffer_start = nullptr; #ifdef HAVE_CG -LPDIRECT3DDEVICE9 DXGraphicsStateGuardian9::_cg_device = NULL; +LPDIRECT3DDEVICE9 DXGraphicsStateGuardian9::_cg_device = nullptr; #endif #define __D3DLIGHT_RANGE_MAX ((PN_stdfloat)sqrt(FLT_MAX)) //for some reason this is missing in dx9 hdrs @@ -108,8 +112,8 @@ DXGraphicsStateGuardian9(GraphicsEngine *engine, GraphicsPipe *pipe) : // tells us otherwise. _is_hardware = true; - _screen = NULL; - _d3d_device = NULL; + _screen = nullptr; + _d3d_device = nullptr; _dx_is_ready = false; _vertex_blending_enabled = false; @@ -117,7 +121,7 @@ DXGraphicsStateGuardian9(GraphicsEngine *engine, GraphicsPipe *pipe) : _tex_stats_retrieval_impossible = false; _supports_render_texture = false; - _active_ibuffer = NULL; + _active_ibuffer = nullptr; // This is a static member, but we initialize it here in the constructor // anyway. It won't hurt if it gets repeatedly initalized. @@ -168,7 +172,7 @@ DXGraphicsStateGuardian9:: } if (IS_VALID_PTR(_d3d_device)) { - _d3d_device->SetTexture(0, NULL); // this frees reference to the old texture + _d3d_device->SetTexture(0, nullptr); // this frees reference to the old texture } free_nondx_resources(); @@ -190,7 +194,7 @@ prepare_texture(Texture *tex, int view) { if (!get_supports_compressed_texture_format(tex->get_ram_image_compression())) { dxgsg9_cat.error() << *dtc->get_texture() << " is stored in an unsupported compressed format.\n"; - return NULL; + return nullptr; } return dtc; @@ -202,7 +206,7 @@ prepare_texture(Texture *tex, int view) { */ void DXGraphicsStateGuardian9:: apply_texture(int i, TextureContext *tc, const SamplerState &sampler) { - if (tc == (TextureContext *)NULL) { + if (tc == nullptr) { // The texture wasn't bound properly or something, so ensure texturing is // disabled and just return. set_texture_stage_state(i, D3DTSS_COLOROP, D3DTOP_DISABLE); @@ -387,7 +391,7 @@ extract_texture_data(Texture *tex) { int num_views = tex->get_num_views(); for (int view = 0; view < num_views; ++view) { TextureContext *tc = tex->prepare_now(view, get_prepared_objects(), this); - nassertr(tc != (TextureContext *)NULL, false); + nassertr(tc != nullptr, false); DXTextureContext9 *dtc = DCAST(DXTextureContext9, tc); if (!dtc->extract_texture_data(*_screen)) { @@ -409,7 +413,7 @@ prepare_shader(Shader *se) { case Shader::SL_GLSL: dxgsg9_cat.error() << "Tried to load GLSL shader, but GLSL shaders not supported by Direct3D 9.\n"; - return NULL; + return nullptr; case Shader::SL_Cg: #ifdef HAVE_CG @@ -418,21 +422,21 @@ prepare_shader(Shader *se) { } else { dxgsg9_cat.error() << "Tried to load Cg shader, but basic shaders not supported.\n"; - return NULL; + return nullptr; } #else dxgsg9_cat.error() << "Tried to load Cg shader, but Cg support not compiled in.\n"; - return NULL; + return nullptr; #endif default: dxgsg9_cat.error() << "Tried to load shader with unsupported shader language!\n"; - return NULL; + return nullptr; } - return NULL; + return nullptr; } /** @@ -476,7 +480,7 @@ prepare_vertex_buffer(GeomVertexArrayData *data) { int attempts = 0; do { - hr = _screen->_d3d_device->CreateVertexBuffer(num_bytes, usage, dvbc->_fvf, pool, &dvbc->_vbuffer, NULL); + hr = _screen->_d3d_device->CreateVertexBuffer(num_bytes, usage, dvbc->_fvf, pool, &dvbc->_vbuffer, nullptr); attempts++; } while (check_dx_allocation(hr, num_bytes, attempts)); @@ -496,10 +500,10 @@ prepare_vertex_buffer(GeomVertexArrayData *data) { dxgsg9_cat.error() << "CreateVertexBuffer failed" << D3DERRORSTRING(hr); - dvbc->_vbuffer = NULL; + dvbc->_vbuffer = nullptr; } - return NULL; + return nullptr; } /** @@ -524,7 +528,7 @@ apply_vertex_buffer(VertexBufferContext *vbc, if ( num_bytes != 0 ) { const unsigned char *client_pointer = reader->get_read_pointer(force); - if (client_pointer == NULL) { + if (client_pointer == nullptr) { return false; } @@ -582,7 +586,7 @@ release_vertex_buffer(VertexBufferContext *vbc) { #endif dvbc->_vbuffer->Release(); - dvbc->_vbuffer = NULL; + dvbc->_vbuffer = nullptr; delete dvbc; } @@ -607,7 +611,7 @@ setup_array_data(DXVertexBufferContext9*& dvbc, // Prepare the buffer object and bind it. VertexBufferContext* vbc = ((GeomVertexArrayData *)array_reader->get_object())->prepare_now(get_prepared_objects(), this); - nassertr(vbc != (VertexBufferContext *)NULL, false); + nassertr(vbc != nullptr, false); if (!apply_vertex_buffer(vbc, array_reader, force)) { return false; } @@ -640,11 +644,11 @@ apply_index_buffer(IndexBufferContext *ibc, const GeomPrimitivePipelineReader *reader, bool force) { DXIndexBufferContext9 *dibc = DCAST(DXIndexBufferContext9, ibc); - if (dibc->_ibuffer == NULL) { + if (dibc->_ibuffer == nullptr) { // Attempt to create a new index buffer. dibc->create_ibuffer(*_screen, reader); - if (dibc->_ibuffer != NULL) { + if (dibc->_ibuffer != nullptr) { if (!dibc->upload_data(reader, force)) { return false; } @@ -655,8 +659,8 @@ apply_index_buffer(IndexBufferContext *ibc, dibc->set_active(true); } else { - _d3d_device->SetIndices(NULL); - _active_ibuffer = NULL; + _d3d_device->SetIndices(nullptr); + _active_ibuffer = nullptr; } } else { @@ -671,7 +675,7 @@ apply_index_buffer(IndexBufferContext *ibc, } dibc->mark_loaded(reader); - _active_ibuffer = NULL; + _active_ibuffer = nullptr; } if (_active_ibuffer != dibc) { @@ -710,7 +714,7 @@ release_index_buffer(IndexBufferContext *ibc) { void DXGraphicsStateGuardian9:: begin_occlusion_query() { nassertv(_supports_occlusion_query); - nassertv(_current_occlusion_query == (OcclusionQueryContext *)NULL); + nassertv(_current_occlusion_query == nullptr); IDirect3DQuery9 *query; HRESULT hr = _d3d_device->CreateQuery(D3DQUERYTYPE_OCCLUSION, &query); @@ -739,8 +743,8 @@ begin_occlusion_query() { */ PT(OcclusionQueryContext) DXGraphicsStateGuardian9:: end_occlusion_query() { - if (_current_occlusion_query == (OcclusionQueryContext *)NULL) { - return NULL; + if (_current_occlusion_query == nullptr) { + return nullptr; } PT(OcclusionQueryContext) result = _current_occlusion_query; @@ -752,7 +756,7 @@ end_occlusion_query() { << "ending occlusion query " << query << "\n"; } - _current_occlusion_query = NULL; + _current_occlusion_query = nullptr; query->Issue(D3DISSUE_END); return result; @@ -808,19 +812,19 @@ clear(DrawableRegion *clearable) { } if ((main_flags | aux_flags) != 0) { - HRESULT hr = _d3d_device->Clear(0, NULL, main_flags | aux_flags, color_clear_value, + HRESULT hr = _d3d_device->Clear(0, nullptr, main_flags | aux_flags, color_clear_value, depth_clear_value, stencil_clear_value); if (FAILED(hr) && main_flags == D3DCLEAR_TARGET && aux_flags != 0) { // Maybe there's a problem with the one or more of the auxiliary // buffers. - hr = _d3d_device->Clear(0, NULL, D3DCLEAR_TARGET, color_clear_value, + hr = _d3d_device->Clear(0, nullptr, D3DCLEAR_TARGET, color_clear_value, depth_clear_value, stencil_clear_value); if (!FAILED(hr)) { // Yep, it worked without them. That's a problem. Which buffer poses // the problem? if (clearable->get_clear_depth_active()) { aux_flags |= D3DCLEAR_ZBUFFER; - HRESULT hr2 = _d3d_device->Clear(0, NULL, D3DCLEAR_ZBUFFER, color_clear_value, + HRESULT hr2 = _d3d_device->Clear(0, nullptr, D3DCLEAR_ZBUFFER, color_clear_value, depth_clear_value, stencil_clear_value); if (FAILED(hr2)) { dxgsg9_cat.error() @@ -831,7 +835,7 @@ clear(DrawableRegion *clearable) { } if (clearable->get_clear_stencil_active()) { aux_flags |= D3DCLEAR_STENCIL; - HRESULT hr2 = _d3d_device->Clear(0, NULL, D3DCLEAR_STENCIL, color_clear_value, + HRESULT hr2 = _d3d_device->Clear(0, nullptr, D3DCLEAR_STENCIL, color_clear_value, stencil_clear_value, stencil_clear_value); if (FAILED(hr2)) { dxgsg9_cat.error() @@ -856,7 +860,7 @@ clear(DrawableRegion *clearable) { */ void DXGraphicsStateGuardian9:: prepare_display_region(DisplayRegionPipelineReader *dr) { - nassertv(dr != (DisplayRegionPipelineReader *)NULL); + nassertv(dr != nullptr); GraphicsStateGuardian::prepare_display_region(dr); int l, u, w, h; @@ -903,12 +907,12 @@ prepare_display_region(DisplayRegionPipelineReader *dr) { */ CPT(TransformState) DXGraphicsStateGuardian9:: calc_projection_mat(const Lens *lens) { - if (lens == (Lens *)NULL) { - return NULL; + if (lens == nullptr) { + return nullptr; } if (!lens->is_linear()) { - return NULL; + return nullptr; } // DirectX also uses a Z range of 0 to 1, whereas the Panda convention is @@ -964,7 +968,7 @@ begin_frame(Thread *current_thread) { GraphicsStateGuardian::begin_frame(current_thread); - if (_d3d_device == NULL) { + if (_d3d_device == nullptr) { dxgsg9_cat.debug() << this << "::begin_frame(): no device.\n"; return false; @@ -1052,18 +1056,18 @@ end_scene() { if (_vertex_array_shader_context != 0) { _vertex_array_shader_context->disable_shader_vertex_arrays(this); - _vertex_array_shader = (Shader *)NULL; - _vertex_array_shader_context = (DXShaderContext9 *)NULL; + _vertex_array_shader = nullptr; + _vertex_array_shader_context = nullptr; } if (_texture_binding_shader_context != 0) { _texture_binding_shader_context->disable_shader_texture_bindings(this); - _texture_binding_shader = (Shader *)NULL; - _texture_binding_shader_context = (DXShaderContext9 *)NULL; + _texture_binding_shader = nullptr; + _texture_binding_shader_context = nullptr; } if (_current_shader_context != 0) { _current_shader_context->unbind(this); - _current_shader = (Shader *)NULL; - _current_shader_context = (DXShaderContext9 *)NULL; + _current_shader = nullptr; + _current_shader_context = nullptr; } _dlights.clear(); @@ -1146,7 +1150,7 @@ begin_draw_primitives(const GeomPipelineReader *geom_reader, if (!GraphicsStateGuardian::begin_draw_primitives(geom_reader, data_reader, force)) { return false; } - nassertr(_data_reader != (GeomVertexDataPipelineReader *)NULL, false); + nassertr(_data_reader != nullptr, false); const GeomVertexFormat *format = _data_reader->get_format(); @@ -1182,7 +1186,7 @@ begin_draw_primitives(const GeomPipelineReader *geom_reader, } const TransformTable *table = data_reader->get_transform_table(); - if (table != (TransformTable *)NULL) { + if (table != nullptr) { for (size_t i = 0; i < table->get_num_transforms(); ++i) { LMatrix4 mat; table->get_transform(i)->mult_matrix(mat, _internal_transform->get_mat()); @@ -1242,7 +1246,7 @@ begin_draw_primitives(const GeomPipelineReader *geom_reader, // Cg shader. if (_vertex_array_shader_context == 0) { disable_standard_vertex_arrays(); - if (!_current_shader_context->update_shader_vertex_arrays(NULL, this, force)) { + if (!_current_shader_context->update_shader_vertex_arrays(nullptr, this, force)) { return false; } } else { @@ -1274,7 +1278,7 @@ update_standard_vertex_arrays(bool force) { int number_of_arrays = _data_reader->get_num_arrays(); for ( int array_index = 0; array_index < number_of_arrays; ++array_index ) { const GeomVertexArrayDataHandle* array_reader = _data_reader->get_array_reader( array_index ); - if ( array_reader == NULL ) { + if ( array_reader == nullptr ) { dxgsg9_cat.error() << "Unable to get reader for array " << array_index << "\n"; return false; } @@ -1317,7 +1321,7 @@ void DXGraphicsStateGuardian9:: disable_standard_vertex_arrays() { for ( int array_index = 0; array_index < _num_bound_streams; ++array_index ) { - _d3d_device->SetStreamSource( array_index, NULL, 0, 0 ); + _d3d_device->SetStreamSource( array_index, nullptr, 0, 0 ); } _num_bound_streams = 0; } @@ -1338,7 +1342,7 @@ draw_triangles(const GeomPrimitivePipelineReader *reader, bool force) { // Indexed, vbuffers. IndexBufferContext *ibc = ((GeomPrimitive *)(reader->get_object()))->prepare_now(get_prepared_objects(), this); - nassertr(ibc != (IndexBufferContext *)NULL, false); + nassertr(ibc != nullptr, false); if (!apply_index_buffer(ibc, reader, force)) { return false; } @@ -1351,12 +1355,12 @@ draw_triangles(const GeomPrimitivePipelineReader *reader, bool force) { #if 0 // Indexed, client arrays. const unsigned char *index_pointer = reader->get_read_pointer(force); - if (index_pointer == NULL) { + if (index_pointer == nullptr) { return false; } D3DFORMAT index_type = get_index_type(reader->get_index_type()); const unsigned char *vertex_pointer = _data_reader->get_array_reader(0)->get_read_pointer(force); - if (vertex_pointer == NULL) { + if (vertex_pointer == nullptr) { return false; } @@ -1375,7 +1379,7 @@ draw_triangles(const GeomPrimitivePipelineReader *reader, bool force) { #if 0 // Nonindexed, client arrays. const unsigned char *vertex_pointer = _data_reader->get_array_reader(0)->get_read_pointer(force); - if (vertex_pointer == NULL) { + if (vertex_pointer == nullptr) { return false; } @@ -1408,7 +1412,7 @@ draw_tristrips(const GeomPrimitivePipelineReader *reader, bool force) { // Indexed, vbuffers, one long triangle strip. IndexBufferContext *ibc = ((GeomPrimitive *)(reader->get_object()))->prepare_now(get_prepared_objects(), this); - nassertr(ibc != (IndexBufferContext *)NULL, false); + nassertr(ibc != nullptr, false); if (!apply_index_buffer(ibc, reader, force)) { return false; } @@ -1421,12 +1425,12 @@ draw_tristrips(const GeomPrimitivePipelineReader *reader, bool force) { #if 0 // Indexed, client arrays, one long triangle strip. const unsigned char *index_pointer = reader->get_read_pointer(force); - if (index_pointer == NULL) { + if (index_pointer == nullptr) { return false; } D3DFORMAT index_type = get_index_type(reader->get_index_type()); const unsigned char *vertex_pointer = _data_reader->get_array_reader(0)->get_read_pointer(force); - if (vertex_pointer == NULL) { + if (vertex_pointer == nullptr) { return false; } @@ -1446,7 +1450,7 @@ draw_tristrips(const GeomPrimitivePipelineReader *reader, bool force) { #if 0 // Indexed, client arrays, one long triangle strip. const unsigned char *vertex_pointer = _data_reader->get_array_reader(0)->get_read_pointer(force); - if (vertex_pointer == NULL) { + if (vertex_pointer == nullptr) { return false; } draw_primitive_up(D3DPT_TRIANGLESTRIP, @@ -1475,7 +1479,7 @@ draw_tristrips(const GeomPrimitivePipelineReader *reader, bool force) { // Indexed, vbuffers, individual triangle strips. IndexBufferContext *ibc = ((GeomPrimitive *)(reader->get_object()))->prepare_now(get_prepared_objects(), this); - nassertr(ibc != (IndexBufferContext *)NULL, false); + nassertr(ibc != nullptr, false); if (!apply_index_buffer(ibc, reader, force)) { return false; } @@ -1496,12 +1500,12 @@ draw_tristrips(const GeomPrimitivePipelineReader *reader, bool force) { // Indexed, client arrays, individual triangle strips. int stride = _data_reader->get_format()->get_array(0)->get_stride(); const unsigned char *index_pointer = reader->get_read_pointer(force); - if (index_pointer == NULL) { + if (index_pointer == nullptr) { return false; } D3DFORMAT index_type = get_index_type(reader->get_index_type()); const unsigned char *vertex_pointer = _data_reader->get_array_reader(0)->get_read_pointer(force); - if (vertex_pointer == NULL) { + if (vertex_pointer == nullptr) { return false; } @@ -1536,7 +1540,7 @@ draw_tristrips(const GeomPrimitivePipelineReader *reader, bool force) { #if 0 // Nonindexed, client arrays, individual triangle strips. const unsigned char *vertex_pointer = _data_reader->get_array_reader(0)->get_read_pointer(force); - if (vertex_pointer == NULL) { + if (vertex_pointer == nullptr) { return false; } int stride = _data_reader->get_format()->get_array(0)->get_stride(); @@ -1582,7 +1586,7 @@ draw_trifans(const GeomPrimitivePipelineReader *reader, bool force) { // Indexed, vbuffers. IndexBufferContext *ibc = ((GeomPrimitive *)(reader->get_object()))->prepare_now(get_prepared_objects(), this); - nassertr(ibc != (IndexBufferContext *)NULL, false); + nassertr(ibc != nullptr, false); if (!apply_index_buffer(ibc, reader, force)) { return false; } @@ -1603,12 +1607,12 @@ draw_trifans(const GeomPrimitivePipelineReader *reader, bool force) { // Indexed, client arrays. int stride = _data_reader->get_format()->get_array(0)->get_stride(); const unsigned char *index_pointer = reader->get_read_pointer(force); - if (index_pointer == NULL) { + if (index_pointer == nullptr) { return false; } D3DFORMAT index_type = get_index_type(reader->get_index_type()); const unsigned char *vertex_pointer = _data_reader->get_array_reader(0)->get_read_pointer(force); - if (vertex_pointer == NULL) { + if (vertex_pointer == nullptr) { return false; } @@ -1643,7 +1647,7 @@ draw_trifans(const GeomPrimitivePipelineReader *reader, bool force) { #if 0 // Nonindexed, client arrays. const unsigned char *vertex_pointer = _data_reader->get_array_reader(0)->get_read_pointer(force); - if (vertex_pointer == NULL) { + if (vertex_pointer == nullptr) { return false; } int stride = _data_reader->get_format()->get_array(0)->get_stride(); @@ -1679,7 +1683,7 @@ draw_lines(const GeomPrimitivePipelineReader *reader, bool force) { // Indexed, vbuffers. IndexBufferContext *ibc = ((GeomPrimitive *)(reader->get_object()))->prepare_now(get_prepared_objects(), this); - nassertr(ibc != (IndexBufferContext *)NULL, false); + nassertr(ibc != nullptr, false); if (!apply_index_buffer(ibc, reader, force)) { return false; } @@ -1692,12 +1696,12 @@ draw_lines(const GeomPrimitivePipelineReader *reader, bool force) { #if 0 // Indexed, client arrays. const unsigned char *index_pointer = reader->get_read_pointer(force); - if (index_pointer == NULL) { + if (index_pointer == nullptr) { return false; } D3DFORMAT index_type = get_index_type(reader->get_index_type()); const unsigned char *vertex_pointer = _data_reader->get_array_reader(0)->get_read_pointer(force); - if (vertex_pointer == NULL) { + if (vertex_pointer == nullptr) { return false; } @@ -1717,7 +1721,7 @@ draw_lines(const GeomPrimitivePipelineReader *reader, bool force) { #if 0 // Nonindexed, client arrays. const unsigned char *vertex_pointer = _data_reader->get_array_reader(0)->get_read_pointer(force); - if (vertex_pointer == NULL) { + if (vertex_pointer == nullptr) { return false; } draw_primitive_up(D3DPT_LINELIST, reader->get_num_primitives(), @@ -1759,7 +1763,7 @@ draw_points(const GeomPrimitivePipelineReader *reader, bool force) { #if 0 // Nonindexed, client arrays. const unsigned char *vertex_pointer = _data_reader->get_array_reader(0)->get_read_pointer(force); - if (vertex_pointer == NULL) { + if (vertex_pointer == nullptr) { return false; } draw_primitive_up(D3DPT_POINTLIST, reader->get_num_primitives(), @@ -1817,7 +1821,7 @@ framebuffer_copy_to_texture(Texture *tex, int view, int z, tex->set_render_to_texture(true); TextureContext *tc = tex->prepare_now(view, get_prepared_objects(), this); - if (tc == (TextureContext *)NULL) { + if (tc == nullptr) { return false; } DXTextureContext9 *dtc = DCAST(DXTextureContext9, tc); @@ -1833,7 +1837,7 @@ framebuffer_copy_to_texture(Texture *tex, int view, int z, // for now. return do_framebuffer_copy_to_ram(tex, view, z, dr, rb, true); } - nassertr(dtc->get_d3d_2d_texture() != NULL, false); + nassertr(dtc->get_d3d_2d_texture() != nullptr, false); IDirect3DSurface9 *tex_level_0; hr = dtc->get_d3d_2d_texture()->GetSurfaceLevel(0, &tex_level_0); @@ -1967,7 +1971,7 @@ do_framebuffer_copy_to_ram(Texture *tex, int view, int z, set_read_buffer(rb); RECT rect; - nassertr(tex != NULL && dr != NULL, false); + nassertr(tex != nullptr && dr != nullptr, false); int xo, yo, w, h; dr->get_region_pixels_i(xo, yo, w, h); @@ -2007,7 +2011,7 @@ do_framebuffer_copy_to_ram(Texture *tex, int view, int z, rect.bottom = yo + h; bool copy_inverted = false; - IDirect3DSurface9 *temp_surface = NULL; + IDirect3DSurface9 *temp_surface = nullptr; HRESULT hr; // Note if you try to grab the backbuffer and full-screen anti-aliasing is @@ -2015,7 +2019,7 @@ do_framebuffer_copy_to_ram(Texture *tex, int view, int z, // it's safer to get the front buffer. if (_cur_read_pixel_buffer & RenderBuffer::T_back) { DWORD render_target_index; - IDirect3DSurface9 *backbuffer = NULL; + IDirect3DSurface9 *backbuffer = nullptr; // GetRenderTarget() seems to be a little more reliable than // GetBackBuffer(). Might just be related to the swap_chain thing. @@ -2041,7 +2045,7 @@ do_framebuffer_copy_to_ram(Texture *tex, int view, int z, surface_description.Format, pool, &temp_surface, - NULL); + nullptr); if (FAILED(hr)) { dxgsg9_cat.error() << "CreateImageSurface failed in copy_pixel_buffer()" @@ -2085,7 +2089,7 @@ do_framebuffer_copy_to_ram(Texture *tex, int view, int z, // For GetFrontBuffer(), we need a temporary surface of type A8R8G8B8. // Unlike GetBackBuffer(), GetFrontBuffer() implicitly performs a copy. - hr = _d3d_device->CreateOffscreenPlainSurface(w, h, D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, &temp_surface, NULL); + hr = _d3d_device->CreateOffscreenPlainSurface(w, h, D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, &temp_surface, nullptr); if (FAILED(hr)) { dxgsg9_cat.error() << "CreateImageSurface failed in copy_pixel_buffer()" @@ -2219,9 +2223,9 @@ reset() { // TransformState::make_identity()); want gsg to pass all state settings // down so any non-matching defaults we set here get overwritten - nassertv(_screen->_d3d9 != NULL); + nassertv(_screen->_d3d9 != nullptr); - if (_d3d_device == NULL) { + if (_d3d_device == nullptr) { return; } @@ -2301,10 +2305,10 @@ reset() { const char *pixel_profile_str = cgGetProfileString(pixel_profile); - if (vertex_profile_str == NULL) { + if (vertex_profile_str == nullptr) { vertex_profile_str = "(null)"; } - if (pixel_profile_str == NULL) { + if (pixel_profile_str == nullptr) { pixel_profile_str = "(null)"; } @@ -2360,7 +2364,7 @@ reset() { _supports_gamma_calibration = ((d3d_caps.Caps2 & D3DCAPS2_CANCALIBRATEGAMMA) != 0); // Test for occlusion query support - hr = _d3d_device->CreateQuery(D3DQUERYTYPE_OCCLUSION, NULL); + hr = _d3d_device->CreateQuery(D3DQUERYTYPE_OCCLUSION, nullptr); _supports_occlusion_query = !FAILED(hr); if (dxgsg9_cat.is_error()) { @@ -2669,12 +2673,12 @@ reset() { // GF2Radeon8500, no on TNT) set_render_state(D3DRS_BLENDOP, D3DBLENDOP_ADD); - _current_shader = (Shader *)NULL; - _current_shader_context = (DXShaderContext9 *)NULL; - _vertex_array_shader = (Shader *)NULL; - _vertex_array_shader_context = (DXShaderContext9 *)NULL; - _texture_binding_shader = (Shader *)NULL; - _texture_binding_shader_context = (DXShaderContext9 *)NULL; + _current_shader = nullptr; + _current_shader_context = nullptr; + _vertex_array_shader = nullptr; + _vertex_array_shader_context = nullptr; + _texture_binding_shader = nullptr; + _texture_binding_shader_context = nullptr; PRINT_REFCNT(dxgsg9, _d3d_device); @@ -2991,7 +2995,7 @@ do_issue_fog() { if (!target_fog->is_off()) { set_render_state(D3DRS_FOGENABLE, TRUE); Fog *fog = target_fog->get_fog(); - nassertv(fog != (Fog *)NULL); + nassertv(fog != nullptr); apply_fog(fog); } else { set_render_state(D3DRS_FOGENABLE, FALSE); @@ -3312,7 +3316,7 @@ bind_light(DirectionalLight *light_obj, const NodePath &light, int light_id) { static PStatCollector _draw_set_state_light_bind_directional_pcollector("Draw:Set State:Light:Bind:Directional"); // PStatTimer timer(_draw_set_state_light_bind_directional_pcollector); - pair lookup = _dlights.insert(DirectionalLights::value_type(light, D3DLIGHT9())); + std::pair lookup = _dlights.insert(DirectionalLights::value_type(light, D3DLIGHT9())); D3DLIGHT9 &fdata = (*lookup.first).second; if (lookup.second) { // Get the light in "world coordinates" (actually, view coordinates). @@ -3364,7 +3368,7 @@ bind_light(DirectionalLight *light_obj, const NodePath &light, int light_id) { void DXGraphicsStateGuardian9:: bind_light(Spotlight *light_obj, const NodePath &light, int light_id) { Lens *lens = light_obj->get_lens(); - nassertv(lens != (Lens *)NULL); + nassertv(lens != nullptr); // Get the light in "world coordinates" (actually, view coordinates). This // means the light in the coordinate space of the camera, converted to DX's @@ -3513,7 +3517,7 @@ do_issue_texture() { update_standard_texture_bindings(); } else { disable_standard_texture_bindings(); - _current_shader_context->update_shader_texture_bindings(NULL,this); + _current_shader_context->update_shader_texture_bindings(nullptr,this); } } else { if (_current_shader_context==0) { @@ -3537,7 +3541,7 @@ disable_standard_texture_bindings() { for (int i = 0; i < _num_active_texture_stages; i++) { HRESULT hr; - hr = _d3d_device -> SetTexture (i, NULL); + hr = _d3d_device -> SetTexture (i, nullptr); if (FAILED (hr)) { dxgsg9_cat.error() << "SetTexture (" @@ -3560,7 +3564,7 @@ update_standard_texture_bindings() { int num_stages = _target_texture->get_num_on_ff_stages(); int num_old_stages = _max_texture_stages; - if (_state_texture != (TextureAttrib *)NULL) { + if (_state_texture != nullptr) { num_old_stages = _state_texture->get_num_on_ff_stages(); } @@ -3579,7 +3583,7 @@ update_standard_texture_bindings() { int texcoord_index = _target_texture->get_ff_tc_index(si); Texture *texture = _target_texture->get_on_texture(stage); - nassertv(texture != (Texture *)NULL); + nassertv(texture != nullptr); const SamplerState &sampler = _target_texture->get_on_sampler(stage); // We always reissue every stage in DX, just in case the texcoord index or @@ -3754,7 +3758,7 @@ update_standard_texture_bindings() { // Disable the texture stages that are no longer used. for (si = num_stages; si < _num_active_texture_stages; si++) { set_texture_stage_state(si, D3DTSS_COLOROP, D3DTOP_DISABLE); - _d3d_device->SetTexture(si, NULL); + _d3d_device->SetTexture(si, nullptr); } // Save the count of texture stages for next time. @@ -4007,16 +4011,16 @@ free_d3d_device() { _dx_is_ready = false; - if (_d3d_device != NULL) { + if (_d3d_device != nullptr) { for(int i = 0; i < D3D_MAXTEXTURESTAGES; i++) { // d3d should release this stuff internally anyway, but whatever - _d3d_device->SetTexture(i, NULL); + _d3d_device->SetTexture(i, nullptr); } } release_all(); - if (_d3d_device != NULL) { + if (_d3d_device != nullptr) { RELEASE(_d3d_device, dxgsg9, "d3dDevice", RELEASE_DOWN_TO_ZERO); } @@ -4252,7 +4256,7 @@ report_texmgr_stats() { */ void DXGraphicsStateGuardian9:: set_context(DXScreenData *new_context) { - nassertv(new_context != NULL); + nassertv(new_context != nullptr); _screen = new_context; _d3d_device = _screen->_d3d_device; //copy this one field for speed of deref _swap_chain = _screen->_swap_chain; //copy this one field for speed of deref @@ -4266,11 +4270,11 @@ set_context(DXScreenData *new_context) { */ void DXGraphicsStateGuardian9:: set_render_target() { - if (_d3d_device == NULL) { + if (_d3d_device == nullptr) { return; } - LPDIRECT3DSURFACE9 back = NULL, stencil = NULL; + LPDIRECT3DSURFACE9 back = nullptr, stencil = nullptr; UINT swap_chain; @@ -4479,7 +4483,7 @@ dx_cleanup() { // Do a safe check for releasing the D3DDEVICE. RefCount should be zero. if // we're called from exit(), _d3d_device may already have been released RELEASE(_d3d_device, dxgsg9, "d3dDevice", RELEASE_DOWN_TO_ZERO); - _screen->_d3d_device = NULL; + _screen->_d3d_device = nullptr; // Releasing pD3D is now the responsibility of the GraphicsPipe destructor } @@ -4548,7 +4552,7 @@ reset_d3d_device(D3DPRESENT_PARAMETERS *presentation_params, // release graphics buffer surfaces { wdxGraphicsBuffer9 *graphics_buffer; - list ::iterator graphics_buffer_iterator; + std::list ::iterator graphics_buffer_iterator; for (graphics_buffer_iterator = _graphics_buffer_list.begin( ); graphics_buffer_iterator != _graphics_buffer_list.end( ); graphics_buffer_iterator++) { @@ -4574,7 +4578,7 @@ reset_d3d_device(D3DPRESENT_PARAMETERS *presentation_params, get_engine()->reset_all_windows(true);// reset with new swapchains by creating if (screen) { - *screen = NULL; + *screen = nullptr; } if (presentation_params != &_screen->_presentation_params) { @@ -4589,7 +4593,7 @@ reset_d3d_device(D3DPRESENT_PARAMETERS *presentation_params, _screen->_swap_chain->Release(); wdxdisplay9_cat.debug() << "swap chain " << _screen->_swap_chain << " is released\n"; - _screen->_swap_chain = NULL; + _screen->_swap_chain = nullptr; hr = _d3d_device->CreateAdditionalSwapChain(presentation_params, &_screen->_swap_chain); } if (SUCCEEDED(hr)) { @@ -4609,7 +4613,7 @@ reset_d3d_device(D3DPRESENT_PARAMETERS *presentation_params, bool DXGraphicsStateGuardian9:: check_cooperative_level() { bool bDoReactivateWindow = false; - if (_d3d_device == NULL) { + if (_d3d_device == nullptr) { return false; } @@ -4669,7 +4673,7 @@ check_cooperative_level() { */ void DXGraphicsStateGuardian9:: show_frame() { - if (_d3d_device == NULL) { + if (_d3d_device == nullptr) { return; } @@ -4679,9 +4683,9 @@ show_frame() { DWORD flags; flags = 0; - hr = _swap_chain->Present((CONST RECT*)NULL, (CONST RECT*)NULL, (HWND)NULL, NULL, flags); + hr = _swap_chain->Present(nullptr, nullptr, (HWND)nullptr, nullptr, flags); } else { - hr = _d3d_device->Present((CONST RECT*)NULL, (CONST RECT*)NULL, (HWND)NULL, NULL); + hr = _d3d_device->Present(nullptr, nullptr, (HWND)nullptr, nullptr); } if (FAILED(hr)) { @@ -5072,7 +5076,7 @@ do_issue_stencil() { const StencilAttrib *stencil = DCAST(StencilAttrib, _target_rs->get_attrib(StencilAttrib::get_class_slot())); - if (stencil != (const StencilAttrib *)NULL) { + if (stencil != nullptr) { // DEBUG if (false) { dxgsg9_cat.debug() << "STENCIL STATE CHANGE\n"; @@ -5135,7 +5139,7 @@ do_issue_stencil() { } if (stencil->get_render_state(StencilAttrib::SRS_clear)) { - _d3d_device->Clear(0, NULL, D3DCLEAR_STENCIL, 0, 0.0f, stencil->get_render_state(StencilAttrib::SRS_clear_value)); + _d3d_device->Clear(0, nullptr, D3DCLEAR_STENCIL, 0, 0.0f, stencil->get_render_state(StencilAttrib::SRS_clear_value)); } } else { @@ -5291,7 +5295,7 @@ get_gamma_table(void) { get = false; if (_gamma_table_initialized == false) { - HDC hdc = GetDC(NULL); + HDC hdc = GetDC(nullptr); if (hdc) { if (GetDeviceGammaRamp (hdc, (LPVOID) _orignial_gamma_table)) { @@ -5299,7 +5303,7 @@ get_gamma_table(void) { get = true; } - ReleaseDC (NULL, hdc); + ReleaseDC (nullptr, hdc); } } @@ -5312,7 +5316,7 @@ get_gamma_table(void) { bool DXGraphicsStateGuardian9:: static_set_gamma(bool restore, PN_stdfloat gamma) { bool set; - HDC hdc = GetDC(NULL); + HDC hdc = GetDC(nullptr); set = false; if (hdc) { @@ -5329,7 +5333,7 @@ static_set_gamma(bool restore, PN_stdfloat gamma) { set = true; } - ReleaseDC (NULL, hdc); + ReleaseDC (nullptr, hdc); } return set; @@ -5363,7 +5367,7 @@ restore_gamma() { */ void DXGraphicsStateGuardian9:: atexit_function(void) { - set_cg_device(NULL); + set_cg_device(nullptr); static_set_gamma(true, 1.0f); } @@ -5372,7 +5376,7 @@ atexit_function(void) { * Profile. */ bool DXGraphicsStateGuardian9:: -get_supports_cg_profile(const string &name) const { +get_supports_cg_profile(const std::string &name) const { #ifndef HAVE_CG return false; #else @@ -5400,7 +5404,7 @@ set_cg_device(LPDIRECT3DDEVICE9 cg_device) { #endif // HAVE_CG } -typedef string KEY; +typedef std::string KEY; typedef struct _KEY_ELEMENT { diff --git a/panda/src/dxgsg9/dxGraphicsStateGuardian9.h b/panda/src/dxgsg9/dxGraphicsStateGuardian9.h index fa31ac12fd..66b2fb82d5 100644 --- a/panda/src/dxgsg9/dxGraphicsStateGuardian9.h +++ b/panda/src/dxgsg9/dxGraphicsStateGuardian9.h @@ -166,7 +166,7 @@ public: static void atexit_function(void); static void set_cg_device(LPDIRECT3DDEVICE9 cg_device); - virtual bool get_supports_cg_profile(const string &name) const; + virtual bool get_supports_cg_profile(const std::string &name) const; protected: @@ -227,7 +227,7 @@ protected: void dx_cleanup(); HRESULT reset_d3d_device(D3DPRESENT_PARAMETERS *p_presentation_params, - DXScreenData **screen = NULL); + DXScreenData **screen = nullptr); bool check_cooperative_level(); @@ -366,7 +366,7 @@ protected: bool _supports_stream_offset; - list _graphics_buffer_list; + std::list _graphics_buffer_list; int _supports_gamma_calibration; diff --git a/panda/src/dxgsg9/dxIndexBufferContext9.cxx b/panda/src/dxgsg9/dxIndexBufferContext9.cxx index a29dff17b3..ae5db21707 100644 --- a/panda/src/dxgsg9/dxIndexBufferContext9.cxx +++ b/panda/src/dxgsg9/dxIndexBufferContext9.cxx @@ -27,7 +27,7 @@ TypeHandle DXIndexBufferContext9::_type_handle; DXIndexBufferContext9:: DXIndexBufferContext9(PreparedGraphicsObjects *pgo, GeomPrimitive *data) : IndexBufferContext(pgo, data), - _ibuffer(NULL), + _ibuffer(nullptr), _managed(-1) { } @@ -62,7 +62,7 @@ evict_lru() { */ void DXIndexBufferContext9:: free_ibuffer(void) { - if (_ibuffer != NULL) { + if (_ibuffer != nullptr) { if (DEBUG_INDEX_BUFFER && dxgsg9_cat.is_debug()) { dxgsg9_cat.debug() << "deleting index buffer " << _ibuffer << "\n"; @@ -74,7 +74,7 @@ free_ibuffer(void) { _ibuffer->Release(); } - _ibuffer = NULL; + _ibuffer = nullptr; } } @@ -118,7 +118,7 @@ allocate_ibuffer(DXScreenData &scrn, do { hr = scrn._d3d_device->CreateIndexBuffer - (data_size, usage, index_type, pool, &_ibuffer, NULL); + (data_size, usage, index_type, pool, &_ibuffer, nullptr); attempts++; } while (scrn._dxgsg9 -> check_dx_allocation (hr, data_size, attempts)); @@ -126,7 +126,7 @@ allocate_ibuffer(DXScreenData &scrn, if (FAILED(hr)) { dxgsg9_cat.warning() << "CreateIndexBuffer failed" << D3DERRORSTRING(hr); - _ibuffer = NULL; + _ibuffer = nullptr; } else { if (DEBUG_INDEX_BUFFER && dxgsg9_cat.is_debug()) { dxgsg9_cat.debug() @@ -162,10 +162,10 @@ upload_data(const GeomPrimitivePipelineReader *reader, bool force) { nassertr(reader->get_object() == get_data(), false); Thread *current_thread = reader->get_current_thread(); - nassertr(_ibuffer != NULL, false); + nassertr(_ibuffer != nullptr, false); const unsigned char *data_pointer = reader->get_read_pointer(force); - if (data_pointer == NULL) { + if (data_pointer == nullptr) { return false; } size_t data_size = (size_t)reader->get_data_size_bytes(); diff --git a/panda/src/dxgsg9/dxInput9.cxx b/panda/src/dxgsg9/dxInput9.cxx index 24e3ea16f3..17d5b2f88e 100644 --- a/panda/src/dxgsg9/dxInput9.cxx +++ b/panda/src/dxgsg9/dxInput9.cxx @@ -17,6 +17,8 @@ #define AXIS_RESOLUTION 2000 // use this many levels of resolution by default (could be more if needed and device supported it) #define AXIS_RANGE_CENTERED // if defined, axis range is centered on 0, instead of starting on 0 +using std::endl; + BOOL CALLBACK EnumGameCtrlsCallback( const DIDEVICEINSTANCE* pdidInstance, VOID* pContext ) { DI_DeviceInfos *pDevInfos = (DI_DeviceInfos *)pContext; @@ -32,9 +34,9 @@ BOOL CALLBACK EnumGameCtrlsCallback( const DIDEVICEINSTANCE* pdidInstance, extern BOOL CALLBACK EnumObjectsCallbackJoystick(const DIDEVICEOBJECTINSTANCE* pdidoi,VOID* pContext); DInput9Info::DInput9Info() { - _pDInput9 = NULL; - _hDInputDLL = NULL; - _JoystickPollTimer = NULL; + _pDInput9 = nullptr; + _hDInputDLL = nullptr; + _JoystickPollTimer = nullptr; } DInput9Info::~DInput9Info() { @@ -48,7 +50,7 @@ DInput9Info::~DInput9Info() { SAFE_RELEASE(_pDInput9); if(_hDInputDLL) { FreeLibrary(_hDInputDLL); - _hDInputDLL=NULL; + _hDInputDLL=nullptr; } } @@ -70,15 +72,15 @@ bool DInput9Info::InitDirectInput() { LPDIRECTINPUT9CREATE pDInputCreate9; pDInputCreate9 = (LPDIRECTINPUT9CREATE) GetProcAddress(_hDInputDLL,DINPUTCREATE); - if(pDInputCreate9 == NULL) { + if(pDInputCreate9 == nullptr) { wdxdisplay_cat.fatal() << "GetProcAddr failed for " << DINPUTCREATE << endl; exit(1); } // Register with the DirectInput subsystem and get a pointer to a // IDirectInput interface we can use. Create a DInput object - if( FAILED( hr = (*pDInputCreate9)(GetModuleHandle(NULL), DIRECTINPUT_VERSION, - IID_IDirectInput9, (VOID**)&_pDInput9, NULL ) ) ) { + if( FAILED( hr = (*pDInputCreate9)(GetModuleHandle(nullptr), DIRECTINPUT_VERSION, + IID_IDirectInput9, (VOID**)&_pDInput9, nullptr ) ) ) { wdxdisplay_cat.error() << DINPUTCREATE << "failed" << D3DERRORSTRING(hr); return false; } @@ -97,7 +99,7 @@ bool DInput9Info::InitDirectInput() { bool DInput9Info::CreateJoystickOrPad(HWND _window) { bool bFoundDev = false; UINT devnum=0; - char *errstr=NULL; + char *errstr=nullptr; // look through the list for the first joystick or gamepad for(;devnum<_DevInfos.size();devnum++) { @@ -116,13 +118,13 @@ bool DInput9Info::CreateJoystickOrPad(HWND _window) { LPDIRECTINPUTDEVICE9 pJoyDevice; // Obtain an interface to the enumerated joystick. - HRESULT hr = _pDInput9->CreateDevice(_DevInfos[devnum].guidInstance, &pJoyDevice, NULL ); + HRESULT hr = _pDInput9->CreateDevice(_DevInfos[devnum].guidInstance, &pJoyDevice, nullptr ); if(FAILED(hr)) { errstr="CreateDevice"; goto handle_error; } - assert(pJoyDevice!=NULL); + assert(pJoyDevice!=nullptr); _DeviceList.push_back(pJoyDevice); // Set the data format to "simple joystick" - a predefined data format A @@ -210,7 +212,7 @@ BOOL CALLBACK EnumObjectsCallbackJoystick( const DIDEVICEOBJECTINSTANCE* pdidoi, bool DInput9Info::ReadJoystick(int devnum, DIJOYSTATE2 &js) { LPDIRECTINPUTDEVICE9 pJoystick = _DeviceList[devnum]; - assert(pJoystick!=NULL); + assert(pJoystick!=nullptr); HRESULT hr; char *errstr; diff --git a/panda/src/dxgsg9/dxInput9.h b/panda/src/dxgsg9/dxInput9.h index 77f3f31a37..9614a2627d 100644 --- a/panda/src/dxgsg9/dxInput9.h +++ b/panda/src/dxgsg9/dxInput9.h @@ -16,8 +16,8 @@ #define DIRECTINPUT_VERSION 0x900 #include -typedef vector DI_DeviceInfos; -typedef vector DI_DeviceObjInfos; +typedef std::vector DI_DeviceInfos; +typedef std::vector DI_DeviceObjInfos; class DInput9Info { public: @@ -33,8 +33,8 @@ public: DI_DeviceInfos _DevInfos; // arrays for all created devices. Should probably put these together in a // struct, along with the data fmt info - vector _DeviceList; - vector _DevCaps; + std::vector _DeviceList; + std::vector _DevCaps; }; #endif diff --git a/panda/src/dxgsg9/dxOcclusionQueryContext9.cxx b/panda/src/dxgsg9/dxOcclusionQueryContext9.cxx index 0999821080..89d584dffd 100644 --- a/panda/src/dxgsg9/dxOcclusionQueryContext9.cxx +++ b/panda/src/dxgsg9/dxOcclusionQueryContext9.cxx @@ -25,7 +25,7 @@ TypeHandle DXOcclusionQueryContext9::_type_handle; DXOcclusionQueryContext9:: ~DXOcclusionQueryContext9() { _query->Release(); - _query = NULL; + _query = nullptr; } /** diff --git a/panda/src/dxgsg9/dxShaderContext9.cxx b/panda/src/dxgsg9/dxShaderContext9.cxx index 9d151ac44a..6513ce8a89 100644 --- a/panda/src/dxgsg9/dxShaderContext9.cxx +++ b/panda/src/dxgsg9/dxShaderContext9.cxx @@ -35,8 +35,8 @@ TypeHandle DXShaderContext9::_type_handle; */ DXShaderContext9:: DXShaderContext9(Shader *s, GSG *gsg) : ShaderContext(s) { - _vertex_element_array = NULL; - _vertex_declaration = NULL; + _vertex_element_array = nullptr; + _vertex_declaration = nullptr; _num_bound_streams = 0; @@ -83,14 +83,14 @@ DXShaderContext9:: ~DXShaderContext9() { release_resources(); - if (_vertex_declaration != NULL) { + if (_vertex_declaration != nullptr) { _vertex_declaration->Release(); - _vertex_declaration = NULL; + _vertex_declaration = nullptr; } - if (_vertex_element_array != NULL) { + if (_vertex_element_array != nullptr) { delete _vertex_element_array; - _vertex_element_array = NULL; + _vertex_element_array = nullptr; } } @@ -200,14 +200,14 @@ issue_parameters(GSG *gsg, int altered) { if (altered & (spec._dep[0] | spec._dep[1])) { const Shader::ShaderPtrData *ptr_data = gsg->fetch_ptr_parameter(spec); - if (ptr_data == NULL) { //the input is not contained in ShaderPtrData + if (ptr_data == nullptr) { //the input is not contained in ShaderPtrData release_resources(); return; } // Calculate how many elements to transfer; no more than it expects, // but certainly no more than we have. - int input_size = min(abs(spec._dim[0] * spec._dim[1] * spec._dim[2]), ptr_data->_size); + int input_size = std::min(abs(spec._dim[0] * spec._dim[1] * spec._dim[2]), (int)ptr_data->_size); CGparameter p = _cg_parameter_map[spec._id._seqno]; switch (ptr_data->_type) { @@ -237,7 +237,7 @@ issue_parameters(GSG *gsg, int altered) { if (altered & (spec._dep[0] | spec._dep[1])) { CGparameter p = _cg_parameter_map[spec._id._seqno]; - if (p == NULL) { + if (p == nullptr) { continue; } const LMatrix4 *val = gsg->fetch_specified_value(spec, altered); @@ -313,7 +313,7 @@ issue_parameters(GSG *gsg, int altered) { } if (FAILED(hr)) { - string name = "unnamed"; + std::string name = "unnamed"; if (spec._arg[0]) { name = spec._arg[0]->get_basename(); @@ -343,7 +343,7 @@ disable_shader_vertex_arrays(GSG *gsg) { LPDIRECT3DDEVICE9 device = gsg->_screen->_d3d_device; for (int array_index = 0; array_index < _num_bound_streams; ++array_index) { - device->SetStreamSource(array_index, NULL, 0, 0); + device->SetStreamSource(array_index, nullptr, 0, 0); } _num_bound_streams = 0; } @@ -377,7 +377,7 @@ update_shader_vertex_arrays(DXShaderContext9 *prev, GSG *gsg, bool force) { // Discard and recreate the VertexElementArray. This thrashes pretty // bad.... - if (_vertex_element_array != NULL) { + if (_vertex_element_array != nullptr) { delete _vertex_element_array; } _vertex_element_array = new VertexElementArray(nvarying + 2); @@ -394,14 +394,14 @@ update_shader_vertex_arrays(DXShaderContext9 *prev, GSG *gsg, bool force) { for (int array_index = 0; array_index < number_of_arrays; ++array_index) { const GeomVertexArrayDataHandle* array_reader = gsg->_data_reader->get_array_reader(array_index); - if (array_reader == NULL) { + if (array_reader == nullptr) { dxgsg9_cat.error() << "Unable to get reader for array " << array_index << "\n"; continue; } for (int var_index = 0; var_index < nvarying; ++var_index) { CGparameter p = _cg_parameter_map[_shader->_var_spec[var_index]._id._seqno]; - if (p == NULL) { + if (p == nullptr) { dxgsg9_cat.info() << "No parameter in map for parameter " << var_index << " (probably optimized away)\n"; @@ -444,7 +444,7 @@ update_shader_vertex_arrays(DXShaderContext9 *prev, GSG *gsg, bool force) { } const char *semantic = cgGetParameterSemantic(p); - if (semantic == NULL) { + if (semantic == nullptr) { dxgsg9_cat.error() << "Unable to retrieve semantic for parameter " << var_index << "\n"; continue; } @@ -564,7 +564,7 @@ update_shader_vertex_arrays(DXShaderContext9 *prev, GSG *gsg, bool force) { _num_bound_streams = number_of_arrays; - if (_vertex_element_array != NULL && + if (_vertex_element_array != nullptr && _vertex_element_array->add_end_vertex_element()) { if (dxgsg9_cat.is_debug()) { // Note that the currently generated vertex declaration works but @@ -580,9 +580,9 @@ update_shader_vertex_arrays(DXShaderContext9 *prev, GSG *gsg, bool force) { } // Discard the old VertexDeclaration. This thrashes pretty bad.... - if (_vertex_declaration != NULL) { + if (_vertex_declaration != nullptr) { _vertex_declaration->Release(); - _vertex_declaration = NULL; + _vertex_declaration = nullptr; } hr = device->CreateVertexDeclaration(_vertex_element_array->_vertex_element_array, @@ -613,14 +613,14 @@ disable_shader_texture_bindings(GSG *gsg) { if (_cg_program) { for (size_t i = 0; i < _shader->_tex_spec.size(); ++i) { CGparameter p = _cg_parameter_map[_shader->_tex_spec[i]._id._seqno]; - if (p == NULL) { + if (p == nullptr) { continue; } int texunit = cgGetParameterResourceIndex(p); HRESULT hr; - hr = gsg->_d3d_device->SetTexture(texunit, NULL); + hr = gsg->_d3d_device->SetTexture(texunit, nullptr); if (FAILED(hr)) { dxgsg9_cat.error() << "SetTexture(" << texunit << ", NULL) failed " @@ -649,7 +649,7 @@ update_shader_texture_bindings(DXShaderContext9 *prev, GSG *gsg) { for (size_t i = 0; i < _shader->_tex_spec.size(); ++i) { Shader::ShaderTexSpec &spec = _shader->_tex_spec[i]; CGparameter p = _cg_parameter_map[spec._id._seqno]; - if (p == NULL) { + if (p == nullptr) { continue; } @@ -671,7 +671,7 @@ update_shader_texture_bindings(DXShaderContext9 *prev, GSG *gsg) { } TextureContext *tc = tex->prepare_now(view, gsg->_prepared_objects, gsg); - if (tc == (TextureContext*)NULL) { + if (tc == nullptr) { continue; } diff --git a/panda/src/dxgsg9/dxShaderContext9.h b/panda/src/dxgsg9/dxShaderContext9.h index 8f0a543e50..b637cb0a81 100644 --- a/panda/src/dxgsg9/dxShaderContext9.h +++ b/panda/src/dxgsg9/dxShaderContext9.h @@ -79,7 +79,7 @@ public: int _num_bound_streams; // FOR DEBUGGING - string _name; + std::string _name; private: #ifdef HAVE_CG diff --git a/panda/src/dxgsg9/dxTextureContext9.cxx b/panda/src/dxgsg9/dxTextureContext9.cxx index c089c26e8a..70c9db7803 100644 --- a/panda/src/dxgsg9/dxTextureContext9.cxx +++ b/panda/src/dxgsg9/dxTextureContext9.cxx @@ -24,6 +24,10 @@ #define DEBUG_SURFACES false #define DEBUG_TEXTURES true +using std::endl; +using std::max; +using std::min; + TypeHandle DXTextureContext9::_type_handle; static const DWORD g_LowByteMask = 0x000000FF; @@ -40,10 +44,10 @@ DXTextureContext9(PreparedGraphicsObjects *pgo, Texture *tex, int view) : << "Creating DX texture [" << tex->get_name() << "], minfilter(" << tex->get_minfilter() << "), magfilter(" << tex->get_magfilter() << "), anisodeg(" << tex->get_anisotropic_degree() << ")\n"; } - _d3d_texture = NULL; - _d3d_2d_texture = NULL; - _d3d_volume_texture = NULL; - _d3d_cube_texture = NULL; + _d3d_texture = nullptr; + _d3d_2d_texture = nullptr; + _d3d_volume_texture = nullptr; + _d3d_cube_texture = nullptr; _has_mipmaps = false; _is_render_target = false; _managed = -1; @@ -686,7 +690,7 @@ create_texture(DXScreenData &scrn) { << "NumColorChannels: " << num_color_channels << "; NumAlphaBits: " << num_alpha_bits << "; targetbpp: " <CreateTexture (target_width, target_height, mip_level_count, usage, - target_pixel_format, pool, &_d3d_2d_texture, NULL); + target_pixel_format, pool, &_d3d_2d_texture, nullptr); _d3d_texture = _d3d_2d_texture; break; case Texture::TT_3d_texture: hr = scrn._d3d_device->CreateVolumeTexture (target_width, target_height, target_depth, mip_level_count, usage, - target_pixel_format, pool, &_d3d_volume_texture, NULL); + target_pixel_format, pool, &_d3d_volume_texture, nullptr); _d3d_texture = _d3d_volume_texture; break; case Texture::TT_cube_map: hr = scrn._d3d_device->CreateCubeTexture (target_width, mip_level_count, usage, - target_pixel_format, pool, &_d3d_cube_texture, NULL); + target_pixel_format, pool, &_d3d_cube_texture, nullptr); _d3d_texture = _d3d_cube_texture; target_height = target_width; @@ -1050,7 +1054,7 @@ create_texture(DXScreenData &scrn) { if (tex->has_ram_image()) { BamCache *cache = BamCache::get_global_ptr(); PT(BamCacheRecord) record = cache->lookup(tex->get_fullpath(), "txo"); - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { record->set_data(tex, tex); cache->store(record); } @@ -1069,9 +1073,9 @@ create_texture(DXScreenData &scrn) { error_exit: RELEASE(_d3d_texture, dxgsg9, "texture", RELEASE_ONCE); - _d3d_2d_texture = NULL; - _d3d_volume_texture = NULL; - _d3d_cube_texture = NULL; + _d3d_2d_texture = nullptr; + _d3d_volume_texture = nullptr; + _d3d_cube_texture = nullptr; return false; } @@ -1101,7 +1105,7 @@ create_simple_texture(DXScreenData &scrn) { hr = scrn._d3d_device->CreateTexture (target_width, target_height, mip_level_count, usage, - target_pixel_format, pool, &_d3d_2d_texture, NULL); + target_pixel_format, pool, &_d3d_2d_texture, nullptr); _d3d_texture = _d3d_2d_texture; if (FAILED(hr)) { dxgsg9_cat.error() @@ -1124,7 +1128,7 @@ create_simple_texture(DXScreenData &scrn) { hr = -1; // hr = fill_d3d_texture_pixels(scrn); - IDirect3DSurface9 *surface = NULL; + IDirect3DSurface9 *surface = nullptr; _d3d_2d_texture->GetSurfaceLevel(0, &surface); RECT source_size; @@ -1135,8 +1139,8 @@ create_simple_texture(DXScreenData &scrn) { DWORD mip_filter = D3DX_FILTER_LINEAR; hr = D3DXLoadSurfaceFromMemory - (surface, (PALETTEENTRY*)NULL, (RECT*)NULL, (LPCVOID)image.p(), - target_pixel_format, target_width * 4, (PALETTEENTRY*)NULL, + (surface, nullptr, nullptr, (LPCVOID)image.p(), + target_pixel_format, target_width * 4, nullptr, &source_size, mip_filter, (D3DCOLOR)0x0); RELEASE(surface, dxgsg9, "create_simple_texture Surface", RELEASE_ONCE); @@ -1156,9 +1160,9 @@ create_simple_texture(DXScreenData &scrn) { error_exit: RELEASE(_d3d_texture, dxgsg9, "texture", RELEASE_ONCE); - _d3d_2d_texture = NULL; - _d3d_volume_texture = NULL; - _d3d_cube_texture = NULL; + _d3d_2d_texture = nullptr; + _d3d_volume_texture = nullptr; + _d3d_cube_texture = nullptr; return false; } @@ -1168,15 +1172,15 @@ create_simple_texture(DXScreenData &scrn) { void DXTextureContext9:: delete_texture() { - if (_d3d_texture == NULL) { + if (_d3d_texture == nullptr) { // don't bother printing the msg below, since we already released it. return; } RELEASE(_d3d_texture, dxgsg9, "texture", RELEASE_ONCE); - _d3d_2d_texture = NULL; - _d3d_volume_texture = NULL; - _d3d_cube_texture = NULL; + _d3d_2d_texture = nullptr; + _d3d_volume_texture = nullptr; + _d3d_cube_texture = nullptr; } /** @@ -1308,7 +1312,7 @@ extract_texture_data(DXScreenData &screen) { surface_description.Format, pool, &destination_surface, - NULL); + nullptr); if (hr == D3D_OK) { if (source_surface && destination_surface) { hr = screen._d3d_device -> GetRenderTargetData (source_surface, destination_surface); @@ -1316,7 +1320,7 @@ extract_texture_data(DXScreenData &screen) { D3DLOCKED_RECT rect; - hr = destination_surface -> LockRect (&rect, NULL, D3DLOCK_READONLY); + hr = destination_surface -> LockRect (&rect, nullptr, D3DLOCK_READONLY); if (hr == D3D_OK) { unsigned int y; @@ -1367,7 +1371,7 @@ extract_texture_data(DXScreenData &screen) { else { for (int n = 0; n < num_levels; ++n) { D3DLOCKED_RECT rect; - hr = _d3d_2d_texture->LockRect(n, &rect, NULL, D3DLOCK_READONLY); + hr = _d3d_2d_texture->LockRect(n, &rect, nullptr, D3DLOCK_READONLY); if (FAILED(hr)) { dxgsg9_cat.error() << "Texture::LockRect() failed! level = " << n << " " << D3DERRORSTRING(hr); @@ -1479,7 +1483,7 @@ d3d_surface_to_texture(RECT &source_rect, IDirect3DSurface9 *d3d_surface, return E_FAIL; } - hr = d3d_surface->LockRect(&locked_rect, (CONST RECT*)NULL, (D3DLOCK_READONLY | D3DLOCK_NO_DIRTY_UPDATE)); + hr = d3d_surface->LockRect(&locked_rect, nullptr, (D3DLOCK_READONLY | D3DLOCK_NO_DIRTY_UPDATE)); if (FAILED(hr)) { dxgsg9_cat.error() << "d3d_surface_to_texture LockRect() failed!" << D3DERRORSTRING(hr); @@ -1723,7 +1727,7 @@ HRESULT DXTextureContext9::fill_d3d_texture_mipmap_pixels(int mip_level, int dep { // This whole function was refactored out of fill_d3d_texture_pixels to make // the code more readable and to avoid code duplication. - IDirect3DSurface9 *mip_surface = NULL; + IDirect3DSurface9 *mip_surface = nullptr; bool using_temp_buffer = false; HRESULT hr = E_FAIL; CPTA_uchar image = get_texture()->get_ram_mipmap_image(mip_level); @@ -1849,8 +1853,8 @@ HRESULT DXTextureContext9::fill_d3d_texture_mipmap_pixels(int mip_level, int dep } else { hr = D3DXLoadSurfaceFromMemory - (mip_surface, (PALETTEENTRY*)NULL, (RECT*)NULL, (LPCVOID)pixels, - source_format, source_row_byte_length, (PALETTEENTRY*)NULL, + (mip_surface, nullptr, nullptr, (LPCVOID)pixels, + source_format, source_row_byte_length, nullptr, &source_size, mip_filter, (D3DCOLOR)0x0); if (FAILED(hr)) { dxgsg9_cat.error() @@ -1922,7 +1926,7 @@ fill_d3d_texture_pixels(DXScreenData &scrn, bool compress_texture) { // turn off depth stencil when clearing texture if it exists depth_stencil_surface = 0; if (device -> GetDepthStencilSurface (&depth_stencil_surface) == D3D_OK) { - if (device -> SetDepthStencilSurface (NULL) == D3D_OK) { + if (device -> SetDepthStencilSurface (nullptr) == D3D_OK) { } } @@ -1935,7 +1939,7 @@ fill_d3d_texture_pixels(DXScreenData &scrn, bool compress_texture) { scaled *= 255; color = D3DCOLOR_RGBA((int)scaled[0], (int)scaled[1], (int)scaled[2], (int)scaled[3]); flags = D3DCLEAR_TARGET; - if (device -> Clear (NULL, NULL, flags, color, 0.0f, 0) == D3D_OK) { + if (device -> Clear (0, nullptr, flags, color, 0.0f, 0) == D3D_OK) { } } @@ -2049,7 +2053,7 @@ fill_d3d_texture_pixels(DXScreenData &scrn, bool compress_texture) { } // mip_filter_flags |= D3DX_FILTER_DITHER; - hr = D3DXFilterTexture(_d3d_texture, (PALETTEENTRY*)NULL, 0, + hr = D3DXFilterTexture(_d3d_texture, nullptr, 0, mip_filter_flags); if (FAILED(hr)) { @@ -2118,7 +2122,7 @@ fill_d3d_volume_texture_pixels(DXScreenData &scrn) { size_t view_size = tex->get_ram_mipmap_view_size(0); image_pixels += view_size * get_view(); - IDirect3DVolume9 *mip_level_0 = NULL; + IDirect3DVolume9 *mip_level_0 = nullptr; bool using_temp_buffer = false; BYTE *pixels = image_pixels; @@ -2212,9 +2216,9 @@ fill_d3d_volume_texture_pixels(DXScreenData &scrn) { GraphicsStateGuardian::_data_transferred_pcollector.add_level(source_page_byte_length * orig_depth); #endif hr = D3DXLoadVolumeFromMemory - (mip_level_0, (PALETTEENTRY*)NULL, (D3DBOX*)NULL, (LPCVOID)pixels, + (mip_level_0, nullptr, nullptr, (LPCVOID)pixels, source_format, source_row_byte_length, source_page_byte_length, - (PALETTEENTRY*)NULL, + nullptr, &source_size, level_0_filter, (D3DCOLOR)0x0); if (FAILED(hr)) { dxgsg9_cat.error() @@ -2236,7 +2240,7 @@ fill_d3d_volume_texture_pixels(DXScreenData &scrn) { // mip_filter_flags| = D3DX_FILTER_DITHER; - hr = D3DXFilterTexture(_d3d_texture, (PALETTEENTRY*)NULL, 0, + hr = D3DXFilterTexture(_d3d_texture, nullptr, 0, mip_filter_flags); if (FAILED(hr)) { dxgsg9_cat.error() diff --git a/panda/src/dxgsg9/dxVertexBufferContext9.cxx b/panda/src/dxgsg9/dxVertexBufferContext9.cxx index 48eb65fc6e..43ef9d51c9 100644 --- a/panda/src/dxgsg9/dxVertexBufferContext9.cxx +++ b/panda/src/dxgsg9/dxVertexBufferContext9.cxx @@ -31,7 +31,7 @@ DXVertexBufferContext9(DXGraphicsStateGuardian9 *dxgsg, PreparedGraphicsObjects *pgo, GeomVertexArrayData *data) : VertexBufferContext(pgo, data), - _vbuffer(NULL) + _vbuffer(nullptr) { // Now fill in the FVF code. const GeomVertexArrayFormat *array_format = data->get_array_format(); @@ -174,9 +174,9 @@ void DXVertexBufferContext9:: evict_lru() { dequeue_lru(); - if ( _vbuffer != NULL ) { + if ( _vbuffer != nullptr ) { _vbuffer->Release(); - _vbuffer = NULL; + _vbuffer = nullptr; } update_data_size_bytes(0); diff --git a/panda/src/dxgsg9/dxgsg9base.h b/panda/src/dxgsg9/dxgsg9base.h index 1566a55ba5..b0e2b9dfef 100644 --- a/panda/src/dxgsg9/dxgsg9base.h +++ b/panda/src/dxgsg9/dxgsg9base.h @@ -56,9 +56,9 @@ #ifndef D3DERRORSTRING #ifdef NDEBUG -#define D3DERRORSTRING(HRESULT) " at (" << __FILE__ << ":" << __LINE__ << "), hr=" << DX_GET_ERROR_STRING_FUNC(HRESULT) << endl // leave out descriptions to shrink release build +#define D3DERRORSTRING(HRESULT) " at (" << __FILE__ << ":" << __LINE__ << "), hr=" << DX_GET_ERROR_STRING_FUNC(HRESULT) << std::endl // leave out descriptions to shrink release build #else -#define D3DERRORSTRING(HRESULT) " at (" << __FILE__ << ":" << __LINE__ << "), hr=" << DX_GET_ERROR_STRING_FUNC(HRESULT) << ": " << DX_GET_ERROR_DESCRIPTION_FUNC(HRESULT) << endl +#define D3DERRORSTRING(HRESULT) " at (" << __FILE__ << ":" << __LINE__ << "), hr=" << DX_GET_ERROR_STRING_FUNC(HRESULT) << ": " << DX_GET_ERROR_DESCRIPTION_FUNC(HRESULT) << std::endl #endif #endif @@ -82,14 +82,14 @@ typedef DWORD DXShaderHandle; var.dwSize = sizeof(type); #define SAFE_DELSHADER(TYPE,HANDLE,PDEVICE) \ - if((HANDLE!=NULL)&&IS_VALID_PTR(PDEVICE)) { PDEVICE->Delete##TYPE##Shader(HANDLE); HANDLE=NULL; } + if((HANDLE!=nullptr)&&IS_VALID_PTR(PDEVICE)) { PDEVICE->Delete##TYPE##Shader(HANDLE); HANDLE=nullptr; } -#define SAFE_DELETE(p) { if(p) { assert(IS_VALID_PTR(p)); delete (p); (p)=NULL; } } -#define SAFE_DELETE_ARRAY(p) { if(p) { assert(IS_VALID_PTR(p)); delete [] (p); (p)=NULL; } } +#define SAFE_DELETE(p) { if(p) { assert(IS_VALID_PTR(p)); delete (p); (p)=nullptr; } } +#define SAFE_DELETE_ARRAY(p) { if(p) { assert(IS_VALID_PTR(p)); delete [] (p); (p)=nullptr; } } // for stuff outside a panda class -#define SAFE_RELEASE(p) { if(p) { assert(IS_VALID_PTR(p)); (p)->Release(); (p)=NULL; } } -#define SAFE_FREELIB(hDLL) { if(hDLL!=NULL) { FreeLibrary(hDLL);hDLL = NULL; } } +#define SAFE_RELEASE(p) { if(p) { assert(IS_VALID_PTR(p)); (p)->Release(); (p)=nullptr; } } +#define SAFE_FREELIB(hDLL) { if(hDLL!=nullptr) { FreeLibrary(hDLL);hDLL = nullptr; } } // this is bDoDownToZero argument to RELEASE() #define RELEASE_DOWN_TO_ZERO true @@ -103,20 +103,20 @@ typedef DWORD DXShaderHandle; ULONG refcnt; \ if(IS_VALID_PTR(OBJECT)) { \ refcnt = (OBJECT)->Release(); \ - MODULE##_cat.debug() << DBGSTR << " released, refcnt = " << refcnt << " at " << __FILE__ << ":" << __LINE__ << endl; \ + MODULE##_cat.debug() << DBGSTR << " released, refcnt = " << refcnt << " at " << __FILE__ << ":" << __LINE__ << std::endl; \ if((bDoDownToZero) && (refcnt>0)) { \ MODULE##_cat.warning() << DBGSTR << " released but still has a non-zero refcnt(" << refcnt << "), multi-releasing it down to zero!\n"; \ do { \ refcnt = (OBJECT)->Release(); \ } while(refcnt>0); \ } \ - (OBJECT) = NULL; \ + (OBJECT) = nullptr; \ } else { \ - MODULE##_cat.debug() << DBGSTR << " not released, ptr == NULL" << endl; \ + MODULE##_cat.debug() << DBGSTR << " not released, ptr == NULL" << std::endl; \ }} #define PRINT_REFCNT(MODULE,p) { ULONG refcnt; (p)->AddRef(); refcnt=(p)->Release(); \ - MODULE##_cat.debug() << #p << " has refcnt = " << refcnt << " at " << __FILE__ << ":" << __LINE__ << endl; } + MODULE##_cat.debug() << #p << " has refcnt = " << refcnt << " at " << __FILE__ << ":" << __LINE__ << std::endl; } #else #define RELEASE(OBJECT,MODULE,DBGSTR,bDoDownToZero) { \ @@ -129,7 +129,7 @@ typedef DWORD DXShaderHandle; refcnt = (OBJECT)->Release(); \ } while(refcnt>0); \ } \ - (OBJECT) = NULL; \ + (OBJECT) = nullptr; \ }} #define PRINT_REFCNT(MODULE,p) diff --git a/panda/src/dxgsg9/wdxGraphicsBuffer9.cxx b/panda/src/dxgsg9/wdxGraphicsBuffer9.cxx index 3cde32fc16..81fce0c90b 100644 --- a/panda/src/dxgsg9/wdxGraphicsBuffer9.cxx +++ b/panda/src/dxgsg9/wdxGraphicsBuffer9.cxx @@ -19,6 +19,9 @@ #define FL << "\n" << __FILE__ << " " << __LINE__ << "\n" +using std::cout; +using std::endl; + TypeHandle wdxGraphicsBuffer9::_type_handle; @@ -27,7 +30,7 @@ TypeHandle wdxGraphicsBuffer9::_type_handle; */ wdxGraphicsBuffer9:: wdxGraphicsBuffer9(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -37,10 +40,10 @@ wdxGraphicsBuffer9(GraphicsEngine *engine, GraphicsPipe *pipe, { // initialize all class members _cube_map_index = -1; - _saved_color_buffer = NULL; - _saved_depth_buffer = NULL; - _color_backing_store = NULL; - _depth_backing_store = NULL; + _saved_color_buffer = nullptr; + _saved_depth_buffer = nullptr; + _color_backing_store = nullptr; + _depth_backing_store = nullptr; // is this correct ??? Since the pbuffer never gets flipped, we get // screenshots from the same buffer we draw into. @@ -94,7 +97,7 @@ wdxGraphicsBuffer9:: // unshare all buffers that are sharing this object's depth buffer { wdxGraphicsBuffer9 *graphics_buffer; - list ::iterator graphics_buffer_iterator; + std::list ::iterator graphics_buffer_iterator; graphics_buffer_iterator = _shared_depth_buffer_list.begin( ); while (graphics_buffer_iterator != _shared_depth_buffer_list.end( )) { @@ -120,7 +123,7 @@ bool wdxGraphicsBuffer9:: begin_frame(FrameMode mode, Thread *current_thread) { begin_frame_spam(mode); - if (_gsg == (GraphicsStateGuardian *)NULL) { + if (_gsg == nullptr) { return false; } if (_dxgsg -> _d3d_device == 0) { @@ -151,7 +154,7 @@ void wdxGraphicsBuffer9:: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); - nassertv(_gsg != (GraphicsStateGuardian *)NULL); + nassertv(_gsg != nullptr); if (mode == FM_render) { copy_to_textures(); @@ -225,7 +228,7 @@ restore_bitplanes() { // clear all render targets, except for the main render target for (int i = 1; i _d3d_device -> SetRenderTarget (i, NULL); + hr = _dxgsg -> _d3d_device -> SetRenderTarget (i, nullptr); if (!SUCCEEDED (hr)) { dxgsg9_cat.error ( ) << "SetRenderTarget " << i << " " << D3DERRORSTRING(hr) FL; } @@ -235,8 +238,8 @@ restore_bitplanes() { if (_saved_depth_buffer) { _saved_depth_buffer->Release(); } - _saved_color_buffer = NULL; - _saved_depth_buffer = NULL; + _saved_color_buffer = nullptr; + _saved_depth_buffer = nullptr; } @@ -335,7 +338,7 @@ rebuild_bitplanes() { if ((_color_backing_store)&& ((bitplane_x != _backing_sizex)||(bitplane_y != _backing_sizey))) { _color_backing_store->Release(); - _color_backing_store = NULL; + _color_backing_store = nullptr; } if (!_color_backing_store) { hr = _dxgsg->_d3d_device->CreateRenderTarget(bitplane_x, bitplane_y, @@ -344,7 +347,7 @@ rebuild_bitplanes() { _saved_color_desc.MultiSampleQuality, FALSE, &_color_backing_store, - NULL); + nullptr); if (!SUCCEEDED(hr)) { dxgsg9_cat.error ( ) << "CreateRenderTarget " << D3DERRORSTRING(hr) FL; } @@ -354,7 +357,7 @@ rebuild_bitplanes() { // Maintain the color texture. if (_color_backing_store) { _color_backing_store->Release(); - _color_backing_store = NULL; + _color_backing_store = nullptr; } color_tex = get_texture(color_tex_index); color_tex->set_size_padded(get_x_size(), get_y_size()); @@ -409,13 +412,13 @@ rebuild_bitplanes() { if ((_depth_backing_store)&& ((bitplane_x != _backing_sizex)||(bitplane_y != _backing_sizey))) { _depth_backing_store->Release(); - _depth_backing_store = NULL; + _depth_backing_store = nullptr; } if (!_depth_backing_store) { hr = _dxgsg -> _d3d_device -> CreateDepthStencilSurface (bitplane_x, bitplane_y, _saved_depth_desc.Format, _saved_depth_desc.MultiSampleType, _saved_depth_desc.MultiSampleQuality, - false, &_depth_backing_store, NULL); + false, &_depth_backing_store, nullptr); if (!SUCCEEDED(hr)) { dxgsg9_cat.error ( ) << "CreateDepthStencilSurface " << D3DERRORSTRING(hr) FL; } @@ -426,7 +429,7 @@ rebuild_bitplanes() { // Maintain the depth texture. if (_depth_backing_store) { _depth_backing_store->Release(); - _depth_backing_store = NULL; + _depth_backing_store = nullptr; } if (_shared_depth_buffer) { @@ -704,7 +707,7 @@ process_events() { // Handle all the messages on the queue in a row. Some of these might be // for another window, but they will get dispatched appropriately. - while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { + while (PeekMessage(&msg, nullptr, 0, 0, PM_NOREMOVE)) { process_1_event(); } } @@ -717,11 +720,11 @@ close_buffer() { if (_color_backing_store) { _color_backing_store->Release(); - _color_backing_store = NULL; + _color_backing_store = nullptr; } if (_depth_backing_store) { _depth_backing_store->Release(); - _depth_backing_store = NULL; + _depth_backing_store = nullptr; } _cube_map_index = -1; @@ -784,7 +787,7 @@ void wdxGraphicsBuffer9:: process_1_event() { MSG msg; - if (!GetMessage(&msg, NULL, 0, 0)) { + if (!GetMessage(&msg, nullptr, 0, 0)) { // WM_QUIT received. We need a cleaner way to deal with this. // DestroyAllWindows(false); exit(msg.wParam); // this will invoke AtExitFn diff --git a/panda/src/dxgsg9/wdxGraphicsBuffer9.h b/panda/src/dxgsg9/wdxGraphicsBuffer9.h index d603a73bf6..747307642b 100644 --- a/panda/src/dxgsg9/wdxGraphicsBuffer9.h +++ b/panda/src/dxgsg9/wdxGraphicsBuffer9.h @@ -29,7 +29,7 @@ class EXPCL_PANDADX wdxGraphicsBuffer9 : public GraphicsBuffer { public: wdxGraphicsBuffer9(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -74,7 +74,7 @@ private: int _backing_sizey; wdxGraphicsBuffer9 *_shared_depth_buffer; - list _shared_depth_buffer_list; + std::list _shared_depth_buffer_list; wdxGraphicsBuffer9 **_this; diff --git a/panda/src/dxgsg9/wdxGraphicsPipe9.cxx b/panda/src/dxgsg9/wdxGraphicsPipe9.cxx index c3c0ee0099..6c85c6652f 100644 --- a/panda/src/dxgsg9/wdxGraphicsPipe9.cxx +++ b/panda/src/dxgsg9/wdxGraphicsPipe9.cxx @@ -17,11 +17,13 @@ #include "wdxGraphicsBuffer9.h" #include "config_dxgsg9.h" +using std::endl; + TypeHandle wdxGraphicsPipe9::_type_handle; static bool MyGetProcAddr(HINSTANCE hDLL, FARPROC *pFn, const char *szExportedFnName) { *pFn = (FARPROC) GetProcAddress(hDLL, szExportedFnName); - if (*pFn == NULL) { + if (*pFn == nullptr) { wdxdisplay9_cat.error() << "GetProcAddr failed for " << szExportedFnName << ", error=" << GetLastError() < 0)|| (fb_prop.get_aux_rgba() > 0)|| (fb_prop.get_aux_float() > 0)) { - return NULL; + return nullptr; } } return new wdxGraphicsWindow9(engine, this, name, fb_prop, win_prop, @@ -130,7 +132,7 @@ make_output(const string &name, ((flags&BF_require_window)!=0)|| ((flags&BF_rtt_cumulative)!=0)|| ((flags&BF_can_bind_every)!=0)) { - return NULL; + return nullptr; } // Early failure - if we are sure that this buffer WONT meet specs, we can // bail out early. @@ -139,13 +141,13 @@ make_output(const string &name, (fb_prop.get_back_buffers() > 0)|| (fb_prop.get_accum_bits() > 0)|| (fb_prop.get_multisamples() > 0)) { - return NULL; + return nullptr; } } // Early success - if we are sure that this buffer WILL meet specs, we can // precertify it. This looks rather overly optimistic -- ie, buggy. - if ((wdxgsg != NULL) && wdxgsg->is_valid() && !wdxgsg->needs_reset() && + if ((wdxgsg != nullptr) && wdxgsg->is_valid() && !wdxgsg->needs_reset() && wdxgsg->get_supports_render_texture()) { precertify = true; } @@ -154,7 +156,7 @@ make_output(const string &name, } // Nothing else left to try. - return NULL; + return nullptr; } /** @@ -165,7 +167,7 @@ make_output(const string &name, bool wdxGraphicsPipe9:: init() { _hDDrawDLL = LoadLibrary("ddraw.dll"); - if (_hDDrawDLL == NULL) { + if (_hDDrawDLL == nullptr) { wdxdisplay9_cat.error() << "LoadLibrary failed for ddraw.dll, error=" << GetLastError() < g_D3DFORMATmap; diff --git a/panda/src/dxgsg9/wdxGraphicsPipe9.h b/panda/src/dxgsg9/wdxGraphicsPipe9.h index 9c06d1476e..2d9eea18b0 100644 --- a/panda/src/dxgsg9/wdxGraphicsPipe9.h +++ b/panda/src/dxgsg9/wdxGraphicsPipe9.h @@ -29,7 +29,7 @@ public: wdxGraphicsPipe9(); virtual ~wdxGraphicsPipe9(); - virtual string get_interface_name() const; + virtual std::string get_interface_name() const; static PT(GraphicsPipe) pipe_constructor(); virtual PT(GraphicsDevice) make_device(void *scrn); @@ -50,7 +50,7 @@ public: bool special_check_fullscreen_resolution(DXScreenData &scrn, UINT x_size,UINT y_size); protected: - virtual PT(GraphicsOutput) make_output(const string &name, + virtual PT(GraphicsOutput) make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/dxgsg9/wdxGraphicsWindow9.cxx b/panda/src/dxgsg9/wdxGraphicsWindow9.cxx index ee19e9137a..3136d75fd0 100644 --- a/panda/src/dxgsg9/wdxGraphicsWindow9.cxx +++ b/panda/src/dxgsg9/wdxGraphicsWindow9.cxx @@ -26,6 +26,8 @@ #include #include +using std::endl; + TypeHandle wdxGraphicsWindow9::_type_handle; /** @@ -33,7 +35,7 @@ TypeHandle wdxGraphicsWindow9::_type_handle; */ wdxGraphicsWindow9:: wdxGraphicsWindow9(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -83,7 +85,7 @@ make_current() { bool wdxGraphicsWindow9:: begin_frame(FrameMode mode, Thread *current_thread) { begin_frame_spam(mode); - if (_gsg == (GraphicsStateGuardian *)NULL) { + if (_gsg == nullptr) { return false; } @@ -126,7 +128,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { void wdxGraphicsWindow9:: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); - nassertv(_gsg != (GraphicsStateGuardian *)NULL); + nassertv(_gsg != nullptr); if (mode == FM_render) { copy_to_textures(); @@ -149,7 +151,7 @@ end_frame(FrameMode mode, Thread *current_thread) { */ void wdxGraphicsWindow9:: end_flip() { - if (_dxgsg != (DXGraphicsStateGuardian9 *)NULL && is_active()) { + if (_dxgsg != nullptr && is_active()) { _dxgsg->show_frame(); } WinGraphicsWindow::end_flip(); @@ -234,11 +236,11 @@ close_window() { << "wdxGraphicsWindow9::close_window() " << this << "\n"; } - if (_gsg != (GraphicsStateGuardian *)NULL) { + if (_gsg != nullptr) { _gsg.clear(); } - DXGraphicsStateGuardian9::set_cg_device(NULL); + DXGraphicsStateGuardian9::set_cg_device(nullptr); _dxgsg->release_swap_chain(&_wcontext); WinGraphicsWindow::close_window(); @@ -291,7 +293,7 @@ open_window() { // case just create an additional swapchain for this window while (true) { - if (_dxgsg->get_pipe()->get_device() == NULL || discard_device) { + if (_dxgsg->get_pipe()->get_device() == nullptr || discard_device) { wdxdisplay9_cat.debug() << "device is null or fullscreen\n"; // If device exists, free it @@ -370,7 +372,7 @@ fullscreen_restored(WindowProperties &properties) { // as soon as the window is restored, even though BeginScene() says we can. // Instead, we have to wait until TestCooperativeLevel() lets us in. We // need to set a flag so we can handle this special case in begin_frame(). - if (_dxgsg != NULL) { + if (_dxgsg != nullptr) { _awaiting_restore = true; } } @@ -384,7 +386,7 @@ handle_reshape() { GdiFlush(); WinGraphicsWindow::handle_reshape(); - if (_dxgsg != NULL && _dxgsg->_d3d_device != NULL) { + if (_dxgsg != nullptr && _dxgsg->_d3d_device != nullptr) { // create the new resized rendertargets WindowProperties props = get_properties(); int x_size = props.get_x_size(); @@ -539,7 +541,7 @@ create_screen_buffers_and_device(DXScreenData &display, bool force_16bpp_zbuffer PRINT_REFCNT(wdxdisplay9, _d3d9); - nassertr(_d3d9 != NULL, false); + nassertr(_d3d9 != nullptr, false); nassertr(pD3DCaps->DevCaps & D3DDEVCAPS_HWRASTERIZATION, false); bool do_sync = sync_video; @@ -601,7 +603,7 @@ create_screen_buffers_and_device(DXScreenData &display, bool force_16bpp_zbuffer while (supported_multisamples > 1){ // need to check both rendertarget and zbuffer fmts hr = _d3d9->CheckDeviceMultiSampleType(adapter, D3DDEVTYPE_HAL, display._display_mode.Format, - is_fullscreen(), D3DMULTISAMPLE_TYPE(supported_multisamples), NULL); + is_fullscreen(), D3DMULTISAMPLE_TYPE(supported_multisamples), nullptr); if (FAILED(hr)) { supported_multisamples--; continue; @@ -609,7 +611,7 @@ create_screen_buffers_and_device(DXScreenData &display, bool force_16bpp_zbuffer if (display._presentation_params.EnableAutoDepthStencil) { hr = _d3d9->CheckDeviceMultiSampleType(adapter, D3DDEVTYPE_HAL, display._presentation_params.AutoDepthStencilFormat, - is_fullscreen(), D3DMULTISAMPLE_TYPE(supported_multisamples), NULL); + is_fullscreen(), D3DMULTISAMPLE_TYPE(supported_multisamples), nullptr); if (FAILED(hr)) { supported_multisamples--; continue; @@ -880,13 +882,13 @@ choose_device() { << ", Driver: " << adapter_info.Driver << ", DriverVersion: (" << HIWORD(DrvVer->HighPart) << "." << LOWORD(DrvVer->HighPart) << "." << HIWORD(DrvVer->LowPart) << "." << LOWORD(DrvVer->LowPart) - << ")\nVendorID: 0x" << hex << adapter_info.VendorId + << ")\nVendorID: 0x" << std::hex << adapter_info.VendorId << " DeviceID: 0x" << adapter_info.DeviceId << " SubsysID: 0x" << adapter_info.SubSysId - << " Revision: 0x" << adapter_info.Revision << dec << endl; + << " Revision: 0x" << adapter_info.Revision << std::dec << endl; HMONITOR _monitor = dxpipe->__d3d9->GetAdapterMonitor(i); - if (_monitor == NULL) { + if (_monitor == nullptr) { wdxdisplay9_cat.info() << "D3D9 Adapter[" << i << "]: seems to be disabled, skipping it\n"; continue; @@ -968,14 +970,14 @@ choose_device() { bool wdxGraphicsWindow9:: consider_device(wdxGraphicsPipe9 *dxpipe, DXDeviceInfo *device_info) { - nassertr(dxpipe != NULL, false); + nassertr(dxpipe != nullptr, false); WindowProperties properties = get_properties(); DWORD dwRenderWidth = properties.get_x_size(); DWORD dwRenderHeight = properties.get_y_size(); HRESULT hr; LPDIRECT3D9 _d3d9 = dxpipe->__d3d9; - nassertr(_dxgsg != NULL, false); + nassertr(_dxgsg != nullptr, false); _wcontext._d3d9 = _d3d9; _wcontext._is_dx9_1 = dxpipe->__is_dx9_1; _wcontext._card_id = device_info->cardID; // could this change by end? @@ -1123,7 +1125,7 @@ bool wdxGraphicsWindow9:: reset_device_resize_window(UINT new_xsize, UINT new_ysize) { bool retval = true; - DXScreenData *screen = NULL; + DXScreenData *screen = nullptr; D3DPRESENT_PARAMETERS d3dpp; memcpy(&d3dpp, &_wcontext._presentation_params, sizeof(D3DPRESENT_PARAMETERS)); _wcontext._presentation_params.BackBufferWidth = new_xsize; @@ -1184,7 +1186,7 @@ init_resized_window() { DWORD newHeight = _wcontext._presentation_params.BackBufferHeight; nassertv((newWidth != 0) && (newHeight != 0)); - nassertv(_wcontext._window != NULL); + nassertv(_wcontext._window != nullptr); if (_wcontext._presentation_params.Windowed) { POINT ul, lr; @@ -1207,7 +1209,7 @@ init_resized_window() { } // clear window to black ASAP - nassertv(_wcontext._window != NULL); + nassertv(_wcontext._window != nullptr); ClearToBlack(_wcontext._window, get_properties()); // clear textures and VB's out of video&AGP mem, so cache is reset @@ -1229,19 +1231,19 @@ init_resized_window() { flags = D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER; clear_color = 0x00000000; - hr = _wcontext._d3d_device-> Clear (0, NULL, flags, clear_color, 0.0f, 0); + hr = _wcontext._d3d_device-> Clear (0, nullptr, flags, clear_color, 0.0f, 0); if (FAILED(hr)) { wdxdisplay9_cat.error() << "Clear failed for device" << D3DERRORSTRING(hr); } - hr = _wcontext._d3d_device-> Present (NULL, NULL, NULL, NULL); + hr = _wcontext._d3d_device-> Present (nullptr, nullptr, nullptr, nullptr); if (FAILED(hr)) { wdxdisplay9_cat.error() << "Present failed for device" << D3DERRORSTRING(hr); } - hr = _wcontext._d3d_device-> Clear (0, NULL, flags, clear_color, 0.0f, 0); + hr = _wcontext._d3d_device-> Clear (0, nullptr, flags, clear_color, 0.0f, 0); if (FAILED(hr)) { wdxdisplay9_cat.error() << "Clear failed for device" diff --git a/panda/src/dxgsg9/wdxGraphicsWindow9.h b/panda/src/dxgsg9/wdxGraphicsWindow9.h index 9bbe8b5eed..391fb9d7e9 100644 --- a/panda/src/dxgsg9/wdxGraphicsWindow9.h +++ b/panda/src/dxgsg9/wdxGraphicsWindow9.h @@ -28,7 +28,7 @@ class wdxGraphicsPipe9; class EXPCL_PANDADX wdxGraphicsWindow9 : public WinGraphicsWindow { public: wdxGraphicsWindow9(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/dxml/config_dxml.cxx b/panda/src/dxml/config_dxml.cxx index 7e25a58c3a..0441f1fdc5 100644 --- a/panda/src/dxml/config_dxml.cxx +++ b/panda/src/dxml/config_dxml.cxx @@ -54,12 +54,12 @@ BEGIN_PUBLISH // Returns the document, or NULL on error. //////////////////////////////////////////////////////////////////// TiXmlDocument * -read_xml_stream(istream &in) { +read_xml_stream(std::istream &in) { TiXmlDocument *doc = new TiXmlDocument; in >> *doc; if (in.fail() && !in.eof()) { delete doc; - return NULL; + return nullptr; } return doc; @@ -72,7 +72,7 @@ BEGIN_PUBLISH // Description: Writes an XML document to the indicated stream. //////////////////////////////////////////////////////////////////// void -write_xml_stream(ostream &out, TiXmlDocument *doc) { +write_xml_stream(std::ostream &out, TiXmlDocument *doc) { out << *doc; } END_PUBLISH @@ -97,13 +97,13 @@ BEGIN_PUBLISH //////////////////////////////////////////////////////////////////// void print_xml_to_file(const Filename &filename, TiXmlNode *xnode) { - string os_name = filename.to_os_specific(); + std::string os_name = filename.to_os_specific(); #ifdef _WIN32 FILE *file; if (fopen_s(&file, os_name.c_str(), "w") != 0) { #else FILE *file = fopen(os_name.c_str(), "w"); - if (file == NULL) { + if (file == nullptr) { #endif dxml_cat.error() << "Failed to open " << filename << " for writing\n"; } diff --git a/panda/src/dxml/config_dxml.h b/panda/src/dxml/config_dxml.h index ca2113f678..7129db67de 100644 --- a/panda/src/dxml/config_dxml.h +++ b/panda/src/dxml/config_dxml.h @@ -35,8 +35,8 @@ extern EXPCL_PANDA_DXML void init_libdxml(); class TiXmlDocument; class TiXmlNode; BEGIN_PUBLISH -EXPCL_PANDA_DXML TiXmlDocument *read_xml_stream(istream &in); -EXPCL_PANDA_DXML void write_xml_stream(ostream &out, TiXmlDocument *doc); +EXPCL_PANDA_DXML TiXmlDocument *read_xml_stream(std::istream &in); +EXPCL_PANDA_DXML void write_xml_stream(std::ostream &out, TiXmlDocument *doc); EXPCL_PANDA_DXML void print_xml(TiXmlNode *xnode); EXPCL_PANDA_DXML void print_xml_to_file(const Filename &filename, TiXmlNode *xnode); END_PUBLISH diff --git a/panda/src/dxml/tinyxml.cpp b/panda/src/dxml/tinyxml.cpp index 05c2cc2af4..be84236496 100644 --- a/panda/src/dxml/tinyxml.cpp +++ b/panda/src/dxml/tinyxml.cpp @@ -42,7 +42,7 @@ bool TiXmlBase::condenseWhiteSpace = true; FILE* TiXmlFOpen( const char* filename, const char* mode ) { #if defined(_MSC_VER) && (_MSC_VER >= 1400 ) - FILE* fp = 0; + FILE* fp = nullptr; /* Addition by drwr for Windows wide-character support */ //errno_t err = fopen_s( &fp, filename, mode ); @@ -65,7 +65,7 @@ FILE* TiXmlFOpen( const char* filename, const char* mode ) if ( !err && fp ) return fp; - return 0; + return nullptr; #else return fopen( filename, mode ); #endif @@ -157,19 +157,19 @@ void TiXmlBase::EncodeString( const TIXML_STRING& str, TIXML_STRING* outString ) TiXmlNode::TiXmlNode( NodeType _type ) : TiXmlBase() { - parent = 0; + parent = nullptr; type = _type; - firstChild = 0; - lastChild = 0; - prev = 0; - next = 0; + firstChild = nullptr; + lastChild = nullptr; + prev = nullptr; + next = nullptr; } TiXmlNode::~TiXmlNode() { TiXmlNode* node = firstChild; - TiXmlNode* temp = 0; + TiXmlNode* temp = nullptr; while ( node ) { @@ -191,7 +191,7 @@ void TiXmlNode::CopyTo( TiXmlNode* target ) const void TiXmlNode::Clear() { TiXmlNode* node = firstChild; - TiXmlNode* temp = 0; + TiXmlNode* temp = nullptr; while ( node ) { @@ -200,27 +200,27 @@ void TiXmlNode::Clear() delete temp; } - firstChild = 0; - lastChild = 0; + firstChild = nullptr; + lastChild = nullptr; } TiXmlNode* TiXmlNode::LinkEndChild( TiXmlNode* node ) { - assert( node->parent == 0 || node->parent == this ); - assert( node->GetDocument() == 0 || node->GetDocument() == this->GetDocument() ); + assert( node->parent == nullptr || node->parent == this ); + assert( node->GetDocument() == nullptr || node->GetDocument() == this->GetDocument() ); if ( node->Type() == TiXmlNode::TINYXML_DOCUMENT ) { delete node; - if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; + if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); + return nullptr; } node->parent = this; node->prev = lastChild; - node->next = 0; + node->next = nullptr; if ( lastChild ) lastChild->next = node; @@ -236,12 +236,12 @@ TiXmlNode* TiXmlNode::InsertEndChild( const TiXmlNode& addThis ) { if ( addThis.Type() == TiXmlNode::TINYXML_DOCUMENT ) { - if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; + if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); + return nullptr; } TiXmlNode* node = addThis.Clone(); if ( !node ) - return 0; + return nullptr; return LinkEndChild( node ); } @@ -250,17 +250,17 @@ TiXmlNode* TiXmlNode::InsertEndChild( const TiXmlNode& addThis ) TiXmlNode* TiXmlNode::InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ) { if ( !beforeThis || beforeThis->parent != this ) { - return 0; + return nullptr; } if ( addThis.Type() == TiXmlNode::TINYXML_DOCUMENT ) { - if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; + if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); + return nullptr; } TiXmlNode* node = addThis.Clone(); if ( !node ) - return 0; + return nullptr; node->parent = this; node->next = beforeThis; @@ -282,17 +282,17 @@ TiXmlNode* TiXmlNode::InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& TiXmlNode* TiXmlNode::InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ) { if ( !afterThis || afterThis->parent != this ) { - return 0; + return nullptr; } if ( addThis.Type() == TiXmlNode::TINYXML_DOCUMENT ) { - if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; + if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); + return nullptr; } TiXmlNode* node = addThis.Clone(); if ( !node ) - return 0; + return nullptr; node->parent = this; node->prev = afterThis; @@ -314,22 +314,22 @@ TiXmlNode* TiXmlNode::InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& a TiXmlNode* TiXmlNode::ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ) { if ( !replaceThis ) - return 0; + return nullptr; if ( replaceThis->parent != this ) - return 0; + return nullptr; if ( withThis.ToDocument() ) { // A document can never be a child. Thanks to Noam. TiXmlDocument* document = GetDocument(); if ( document ) - document->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; + document->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); + return nullptr; } TiXmlNode* node = withThis.Clone(); if ( !node ) - return 0; + return nullptr; node->next = replaceThis->next; node->prev = replaceThis->prev; @@ -384,7 +384,7 @@ const TiXmlNode* TiXmlNode::FirstChild( const char * _value ) const if ( strcmp( node->Value(), _value ) == 0 ) return node; } - return 0; + return nullptr; } @@ -396,7 +396,7 @@ const TiXmlNode* TiXmlNode::LastChild( const char * _value ) const if ( strcmp( node->Value(), _value ) == 0 ) return node; } - return 0; + return nullptr; } @@ -436,7 +436,7 @@ const TiXmlNode* TiXmlNode::NextSibling( const char * _value ) const if ( strcmp( node->Value(), _value ) == 0 ) return node; } - return 0; + return nullptr; } @@ -448,7 +448,7 @@ const TiXmlNode* TiXmlNode::PreviousSibling( const char * _value ) const if ( strcmp( node->Value(), _value ) == 0 ) return node; } - return 0; + return nullptr; } @@ -478,7 +478,7 @@ const TiXmlElement* TiXmlNode::FirstChildElement() const if ( node->ToElement() ) return node->ToElement(); } - return 0; + return nullptr; } @@ -493,7 +493,7 @@ const TiXmlElement* TiXmlNode::FirstChildElement( const char * _value ) const if ( node->ToElement() ) return node->ToElement(); } - return 0; + return nullptr; } @@ -508,7 +508,7 @@ const TiXmlElement* TiXmlNode::NextSiblingElement() const if ( node->ToElement() ) return node->ToElement(); } - return 0; + return nullptr; } @@ -523,7 +523,7 @@ const TiXmlElement* TiXmlNode::NextSiblingElement( const char * _value ) const if ( node->ToElement() ) return node->ToElement(); } - return 0; + return nullptr; } @@ -536,14 +536,14 @@ const TiXmlDocument* TiXmlNode::GetDocument() const if ( node->ToDocument() ) return node->ToDocument(); } - return 0; + return nullptr; } TiXmlElement::TiXmlElement (const char * _value) : TiXmlNode( TiXmlNode::TINYXML_ELEMENT ) { - firstChild = lastChild = 0; + firstChild = lastChild = nullptr; value = _value; } @@ -552,7 +552,7 @@ TiXmlElement::TiXmlElement (const char * _value) TiXmlElement::TiXmlElement( const std::string& _value ) : TiXmlNode( TiXmlNode::TINYXML_ELEMENT ) { - firstChild = lastChild = 0; + firstChild = lastChild = nullptr; value = _value; } #endif @@ -561,7 +561,7 @@ TiXmlElement::TiXmlElement( const std::string& _value ) TiXmlElement::TiXmlElement( const TiXmlElement& copy) : TiXmlNode( TiXmlNode::TINYXML_ELEMENT ) { - firstChild = lastChild = 0; + firstChild = lastChild = nullptr; copy.CopyTo( this ); } @@ -596,7 +596,7 @@ const char* TiXmlElement::Attribute( const char* name ) const const TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) return node->Value(); - return 0; + return nullptr; } @@ -606,7 +606,7 @@ const std::string* TiXmlElement::Attribute( const std::string& name ) const const TiXmlAttribute* attrib = attributeSet.Find( name ); if ( attrib ) return &attrib->ValueStr(); - return 0; + return nullptr; } #endif @@ -614,7 +614,7 @@ const std::string* TiXmlElement::Attribute( const std::string& name ) const const char* TiXmlElement::Attribute( const char* name, int* i ) const { const TiXmlAttribute* attrib = attributeSet.Find( name ); - const char* result = 0; + const char* result = nullptr; if ( attrib ) { result = attrib->Value(); @@ -630,7 +630,7 @@ const char* TiXmlElement::Attribute( const char* name, int* i ) const const std::string* TiXmlElement::Attribute( const std::string& name, int* i ) const { const TiXmlAttribute* attrib = attributeSet.Find( name ); - const std::string* result = 0; + const std::string* result = nullptr; if ( attrib ) { result = &attrib->ValueStr(); @@ -646,7 +646,7 @@ const std::string* TiXmlElement::Attribute( const std::string& name, int* i ) co const char* TiXmlElement::Attribute( const char* name, double* d ) const { const TiXmlAttribute* attrib = attributeSet.Find( name ); - const char* result = 0; + const char* result = nullptr; if ( attrib ) { result = attrib->Value(); @@ -662,7 +662,7 @@ const char* TiXmlElement::Attribute( const char* name, double* d ) const const std::string* TiXmlElement::Attribute( const std::string& name, double* d ) const { const TiXmlAttribute* attrib = attributeSet.Find( name ); - const std::string* result = 0; + const std::string* result = nullptr; if ( attrib ) { result = &attrib->ValueStr(); @@ -835,7 +835,7 @@ void TiXmlElement::CopyTo( TiXmlElement* target ) const // Element class: // Clone the attributes, then clone the children. - const TiXmlAttribute* attribute = 0; + const TiXmlAttribute* attribute = nullptr; for( attribute = attributeSet.First(); attribute; attribute = attribute->Next() ) @@ -843,7 +843,7 @@ void TiXmlElement::CopyTo( TiXmlElement* target ) const target->SetAttribute( attribute->Name(), attribute->Value() ); } - TiXmlNode* node = 0; + TiXmlNode* node = nullptr; for ( node = firstChild; node; node = node->NextSibling() ) { target->LinkEndChild( node->Clone() ); @@ -868,7 +868,7 @@ TiXmlNode* TiXmlElement::Clone() const { TiXmlElement* clone = new TiXmlElement( Value() ); if ( !clone ) - return 0; + return nullptr; CopyTo( clone ); return clone; @@ -884,7 +884,7 @@ const char* TiXmlElement::GetText() const return childText->Value(); } } - return 0; + return nullptr; } @@ -955,7 +955,7 @@ bool TiXmlDocument::LoadFile( const char* _filename, TiXmlEncoding encoding ) } else { - SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); + SetError( TIXML_ERROR_OPENING_FILE, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); return false; } } @@ -964,7 +964,7 @@ bool TiXmlDocument::LoadFile( FILE* file, TiXmlEncoding encoding ) { if ( !file ) { - SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); + SetError( TIXML_ERROR_OPENING_FILE, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); return false; } @@ -981,7 +981,7 @@ bool TiXmlDocument::LoadFile( FILE* file, TiXmlEncoding encoding ) // Strange case, but good to handle up front. if ( length <= 0 ) { - SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); + SetError( TIXML_ERROR_DOCUMENT_EMPTY, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); return false; } @@ -1011,7 +1011,7 @@ bool TiXmlDocument::LoadFile( FILE* file, TiXmlEncoding encoding ) if ( fread( buf, length, 1, file ) != 1 ) { delete [] buf; - SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); + SetError( TIXML_ERROR_OPENING_FILE, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); return false; } @@ -1051,7 +1051,7 @@ bool TiXmlDocument::LoadFile( FILE* file, TiXmlEncoding encoding ) assert( q <= (buf+length) ); *q = 0; - Parse( buf, 0, encoding ); + Parse( buf, nullptr, encoding ); delete [] buf; return !Error(); @@ -1100,7 +1100,7 @@ void TiXmlDocument::CopyTo( TiXmlDocument* target ) const target->errorLocation = errorLocation; target->useMicrosoftBOM = useMicrosoftBOM; - TiXmlNode* node = 0; + TiXmlNode* node = nullptr; for ( node = firstChild; node; node = node->NextSibling() ) { target->LinkEndChild( node->Clone() ); @@ -1112,7 +1112,7 @@ TiXmlNode* TiXmlDocument::Clone() const { TiXmlDocument* clone = new TiXmlDocument(); if ( !clone ) - return 0; + return nullptr; CopyTo( clone ); return clone; @@ -1149,7 +1149,7 @@ const TiXmlAttribute* TiXmlAttribute::Next() const // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( next->value.empty() && next->name.empty() ) - return 0; + return nullptr; return next; } @@ -1169,7 +1169,7 @@ const TiXmlAttribute* TiXmlAttribute::Previous() const // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( prev->value.empty() && prev->name.empty() ) - return 0; + return nullptr; return prev; } @@ -1298,7 +1298,7 @@ TiXmlNode* TiXmlComment::Clone() const TiXmlComment* clone = new TiXmlComment(); if ( !clone ) - return 0; + return nullptr; CopyTo( clone ); return clone; @@ -1341,11 +1341,11 @@ bool TiXmlText::Accept( TiXmlVisitor* visitor ) const TiXmlNode* TiXmlText::Clone() const { - TiXmlText* clone = 0; + TiXmlText* clone = nullptr; clone = new TiXmlText( "" ); if ( !clone ) - return 0; + return nullptr; CopyTo( clone ); return clone; @@ -1433,7 +1433,7 @@ TiXmlNode* TiXmlDeclaration::Clone() const TiXmlDeclaration* clone = new TiXmlDeclaration(); if ( !clone ) - return 0; + return nullptr; CopyTo( clone ); return clone; @@ -1465,7 +1465,7 @@ TiXmlNode* TiXmlUnknown::Clone() const TiXmlUnknown* clone = new TiXmlUnknown(); if ( !clone ) - return 0; + return nullptr; CopyTo( clone ); return clone; @@ -1511,8 +1511,8 @@ void TiXmlAttributeSet::Remove( TiXmlAttribute* removeMe ) { node->prev->next = node->next; node->next->prev = node->prev; - node->next = 0; - node->prev = 0; + node->next = nullptr; + node->prev = nullptr; return; } } @@ -1528,7 +1528,7 @@ TiXmlAttribute* TiXmlAttributeSet::Find( const std::string& name ) const if ( node->name == name ) return node; } - return 0; + return nullptr; } TiXmlAttribute* TiXmlAttributeSet::FindOrCreate( const std::string& _name ) @@ -1551,7 +1551,7 @@ TiXmlAttribute* TiXmlAttributeSet::Find( const char* name ) const if ( strcmp( node->name.c_str(), name ) == 0 ) return node; } - return 0; + return nullptr; } @@ -1574,7 +1574,7 @@ std::istream& operator>> (std::istream & in, TiXmlNode & base) tag.reserve( 8 * 1000 ); base.StreamIn( &in, &tag ); - base.Parse( tag.c_str(), 0, TIXML_DEFAULT_ENCODING ); + base.Parse( tag.c_str(), nullptr, TIXML_DEFAULT_ENCODING ); return in; } #endif @@ -1612,7 +1612,7 @@ TiXmlHandle TiXmlHandle::FirstChild() const if ( child ) return TiXmlHandle( child ); } - return TiXmlHandle( 0 ); + return TiXmlHandle( nullptr ); } @@ -1624,7 +1624,7 @@ TiXmlHandle TiXmlHandle::FirstChild( const char * value ) const if ( child ) return TiXmlHandle( child ); } - return TiXmlHandle( 0 ); + return TiXmlHandle( nullptr ); } @@ -1636,7 +1636,7 @@ TiXmlHandle TiXmlHandle::FirstChildElement() const if ( child ) return TiXmlHandle( child ); } - return TiXmlHandle( 0 ); + return TiXmlHandle( nullptr ); } @@ -1648,7 +1648,7 @@ TiXmlHandle TiXmlHandle::FirstChildElement( const char * value ) const if ( child ) return TiXmlHandle( child ); } - return TiXmlHandle( 0 ); + return TiXmlHandle( nullptr ); } @@ -1667,7 +1667,7 @@ TiXmlHandle TiXmlHandle::Child( int count ) const if ( child ) return TiXmlHandle( child ); } - return TiXmlHandle( 0 ); + return TiXmlHandle( nullptr ); } @@ -1686,7 +1686,7 @@ TiXmlHandle TiXmlHandle::Child( const char* value, int count ) const if ( child ) return TiXmlHandle( child ); } - return TiXmlHandle( 0 ); + return TiXmlHandle( nullptr ); } @@ -1705,7 +1705,7 @@ TiXmlHandle TiXmlHandle::ChildElement( int count ) const if ( child ) return TiXmlHandle( child ); } - return TiXmlHandle( 0 ); + return TiXmlHandle( nullptr ); } @@ -1724,7 +1724,7 @@ TiXmlHandle TiXmlHandle::ChildElement( const char* value, int count ) const if ( child ) return TiXmlHandle( child ); } - return TiXmlHandle( 0 ); + return TiXmlHandle( nullptr ); } @@ -1747,7 +1747,7 @@ bool TiXmlPrinter::VisitEnter( const TiXmlElement& element, const TiXmlAttribute for( const TiXmlAttribute* attrib = firstAttribute; attrib; attrib = attrib->Next() ) { buffer += " "; - attrib->Print( 0, 0, &buffer ); + attrib->Print( nullptr, 0, &buffer ); } if ( !element.FirstChild() ) @@ -1832,7 +1832,7 @@ bool TiXmlPrinter::Visit( const TiXmlText& text ) bool TiXmlPrinter::Visit( const TiXmlDeclaration& declaration ) { DoIndent(); - declaration.Print( 0, 0, &buffer ); + declaration.Print( nullptr, 0, &buffer ); DoLineBreak(); return true; } diff --git a/panda/src/dxml/tinyxmlparser.cpp b/panda/src/dxml/tinyxmlparser.cpp index 666a4f757c..edf757b761 100644 --- a/panda/src/dxml/tinyxmlparser.cpp +++ b/panda/src/dxml/tinyxmlparser.cpp @@ -315,7 +315,7 @@ const char* TiXmlBase::SkipWhiteSpace( const char* p, TiXmlEncoding encoding ) { if ( !p || !*p ) { - return 0; + return nullptr; } if ( encoding == TIXML_ENCODING_UTF8 ) { @@ -432,7 +432,7 @@ const char* TiXmlBase::ReadName( const char* p, TIXML_STRING * name, TiXmlEncodi } return p; } - return 0; + return nullptr; } const char* TiXmlBase::GetEntity( const char* p, char* value, int* length, TiXmlEncoding encoding ) @@ -451,12 +451,12 @@ const char* TiXmlBase::GetEntity( const char* p, char* value, int* length, TiXml if ( *(p+2) == 'x' ) { // Hexadecimal. - if ( !*(p+3) ) return 0; + if ( !*(p+3) ) return nullptr; const char* q = p+3; q = strchr( q, ';' ); - if ( !q || !*q ) return 0; + if ( !q || !*q ) return nullptr; delta = q-p; --q; @@ -470,7 +470,7 @@ const char* TiXmlBase::GetEntity( const char* p, char* value, int* length, TiXml else if ( *q >= 'A' && *q <= 'F' ) ucs += mult * (*q - 'A' + 10 ); else - return 0; + return nullptr; mult *= 16; --q; } @@ -478,12 +478,12 @@ const char* TiXmlBase::GetEntity( const char* p, char* value, int* length, TiXml else { // Decimal. - if ( !*(p+2) ) return 0; + if ( !*(p+2) ) return nullptr; const char* q = p+2; q = strchr( q, ';' ); - if ( !q || !*q ) return 0; + if ( !q || !*q ) return nullptr; delta = q-p; --q; @@ -493,7 +493,7 @@ const char* TiXmlBase::GetEntity( const char* p, char* value, int* length, TiXml if ( *q >= '0' && *q <= '9' ) ucs += mult * (*q - '0'); else - return 0; + return nullptr; mult *= 10; --q; } @@ -649,7 +649,7 @@ void TiXmlDocument::StreamIn( std::istream * in, TIXML_STRING * tag ) if ( !StreamTo( in, '<', tag ) ) { - SetError( TIXML_ERROR_PARSING_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); + SetError( TIXML_ERROR_PARSING_EMPTY, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); return; } @@ -661,7 +661,7 @@ void TiXmlDocument::StreamIn( std::istream * in, TIXML_STRING * tag ) int c = in->get(); if ( c <= 0 ) { - SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); + SetError( TIXML_ERROR_EMBEDDED_NULL, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); break; } (*tag) += (char) c; @@ -677,9 +677,9 @@ void TiXmlDocument::StreamIn( std::istream * in, TIXML_STRING * tag ) if ( node ) { node->StreamIn( in, tag ); - bool isElement = node->ToElement() != 0; + bool isElement = node->ToElement() != nullptr; delete node; - node = 0; + node = nullptr; // If this is the root element, we're done. Parsing will be // done by the >> operator. @@ -690,13 +690,13 @@ void TiXmlDocument::StreamIn( std::istream * in, TIXML_STRING * tag ) } else { - SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN ); + SetError( TIXML_ERROR, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); return; } } } // We should have returned sooner. - SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN ); + SetError( TIXML_ERROR, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); } #endif @@ -710,8 +710,8 @@ const char* TiXmlDocument::Parse( const char* p, TiXmlParsingData* prevData, TiX // here is skipping white space. if ( !p || !*p ) { - SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; + SetError( TIXML_ERROR_DOCUMENT_EMPTY, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); + return nullptr; } // Note that, for a document, this needs to come @@ -747,8 +747,8 @@ const char* TiXmlDocument::Parse( const char* p, TiXmlParsingData* prevData, TiX p = SkipWhiteSpace( p, encoding ); if ( !p ) { - SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); - return 0; + SetError( TIXML_ERROR_DOCUMENT_EMPTY, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); + return nullptr; } while ( p && *p ) @@ -787,8 +787,8 @@ const char* TiXmlDocument::Parse( const char* p, TiXmlParsingData* prevData, TiX // Was this empty? if ( !firstChild ) { - SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, encoding ); - return 0; + SetError( TIXML_ERROR_DOCUMENT_EMPTY, nullptr, nullptr, encoding ); + return nullptr; } // All is well. @@ -817,19 +817,19 @@ void TiXmlDocument::SetError( int err, const char* pError, TiXmlParsingData* dat TiXmlNode* TiXmlNode::Identify( const char* p, TiXmlEncoding encoding ) { - TiXmlNode* returnNode = 0; + TiXmlNode* returnNode = nullptr; p = SkipWhiteSpace( p, encoding ); if( !p || !*p || *p != '<' ) { - return 0; + return nullptr; } p = SkipWhiteSpace( p, encoding ); if ( !p || !*p ) { - return 0; + return nullptr; } // What is this thing? @@ -911,7 +911,7 @@ void TiXmlElement::StreamIn (std::istream * in, TIXML_STRING * tag) { TiXmlDocument* document = GetDocument(); if ( document ) - document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); + document->SetError( TIXML_ERROR_EMBEDDED_NULL, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); return; } (*tag) += (char) c ; @@ -973,7 +973,7 @@ void TiXmlElement::StreamIn (std::istream * in, TIXML_STRING * tag) { TiXmlDocument* document = GetDocument(); if ( document ) - document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); + document->SetError( TIXML_ERROR_EMBEDDED_NULL, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); return; } @@ -1013,7 +1013,7 @@ void TiXmlElement::StreamIn (std::istream * in, TIXML_STRING * tag) { TiXmlDocument* document = GetDocument(); if ( document ) - document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); + document->SetError( TIXML_ERROR_EMBEDDED_NULL, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); return; } assert( c == '>' ); @@ -1031,7 +1031,7 @@ void TiXmlElement::StreamIn (std::istream * in, TIXML_STRING * tag) return; node->StreamIn( in, tag ); delete node; - node = 0; + node = nullptr; // No return: go around from the beginning: text, closing tag, or node. } @@ -1047,8 +1047,8 @@ const char* TiXmlElement::Parse( const char* p, TiXmlParsingData* data, TiXmlEnc if ( !p || !*p ) { - if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, 0, 0, encoding ); - return 0; + if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, nullptr, nullptr, encoding ); + return nullptr; } if ( data ) @@ -1060,7 +1060,7 @@ const char* TiXmlElement::Parse( const char* p, TiXmlParsingData* data, TiXmlEnc if ( *p != '<' ) { if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, p, data, encoding ); - return 0; + return nullptr; } p = SkipWhiteSpace( p+1, encoding ); @@ -1072,7 +1072,7 @@ const char* TiXmlElement::Parse( const char* p, TiXmlParsingData* data, TiXmlEnc if ( !p || !*p ) { if ( document ) document->SetError( TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME, pErr, data, encoding ); - return 0; + return nullptr; } TIXML_STRING endTag ("SetError( TIXML_ERROR_READING_ATTRIBUTES, pErr, data, encoding ); - return 0; + return nullptr; } if ( *p == '/' ) { @@ -1096,7 +1096,7 @@ const char* TiXmlElement::Parse( const char* p, TiXmlParsingData* data, TiXmlEnc if ( *p != '>' ) { if ( document ) document->SetError( TIXML_ERROR_PARSING_EMPTY, p, data, encoding ); - return 0; + return nullptr; } return (p+1); } @@ -1111,7 +1111,7 @@ const char* TiXmlElement::Parse( const char* p, TiXmlParsingData* data, TiXmlEnc // We were looking for the end tag, but found nothing. // Fix for [ 1663758 ] Failure to report error on bad XML if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG, p, data, encoding ); - return 0; + return nullptr; } // We should find the end tag now @@ -1128,12 +1128,12 @@ const char* TiXmlElement::Parse( const char* p, TiXmlParsingData* data, TiXmlEnc return p; } if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG, p, data, encoding ); - return 0; + return nullptr; } else { if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG, p, data, encoding ); - return 0; + return nullptr; } } else @@ -1142,7 +1142,7 @@ const char* TiXmlElement::Parse( const char* p, TiXmlParsingData* data, TiXmlEnc TiXmlAttribute* attrib = new TiXmlAttribute(); if ( !attrib ) { - return 0; + return nullptr; } attrib->SetDocument( document ); @@ -1153,7 +1153,7 @@ const char* TiXmlElement::Parse( const char* p, TiXmlParsingData* data, TiXmlEnc { if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, pErr, data, encoding ); delete attrib; - return 0; + return nullptr; } // Handle the strange case of double attributes: @@ -1166,7 +1166,7 @@ const char* TiXmlElement::Parse( const char* p, TiXmlParsingData* data, TiXmlEnc { if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, pErr, data, encoding ); delete attrib; - return 0; + return nullptr; } attributeSet.Add( attrib ); @@ -1193,7 +1193,7 @@ const char* TiXmlElement::ReadValue( const char* p, TiXmlParsingData* data, TiXm if ( !textNode ) { - return 0; + return nullptr; } if ( TiXmlBase::IsWhiteSpaceCondensed() ) @@ -1231,7 +1231,7 @@ const char* TiXmlElement::ReadValue( const char* p, TiXmlParsingData* data, TiXm } else { - return 0; + return nullptr; } } } @@ -1241,7 +1241,7 @@ const char* TiXmlElement::ReadValue( const char* p, TiXmlParsingData* data, TiXm if ( !p ) { - if ( document ) document->SetError( TIXML_ERROR_READING_ELEMENT_VALUE, 0, 0, encoding ); + if ( document ) document->SetError( TIXML_ERROR_READING_ELEMENT_VALUE, nullptr, nullptr, encoding ); } return p; } @@ -1257,7 +1257,7 @@ void TiXmlUnknown::StreamIn( std::istream * in, TIXML_STRING * tag ) { TiXmlDocument* document = GetDocument(); if ( document ) - document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); + document->SetError( TIXML_ERROR_EMBEDDED_NULL, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); return; } (*tag) += (char) c; @@ -1285,7 +1285,7 @@ const char* TiXmlUnknown::Parse( const char* p, TiXmlParsingData* data, TiXmlEnc if ( !p || !*p || *p != '<' ) { if ( document ) document->SetError( TIXML_ERROR_PARSING_UNKNOWN, p, data, encoding ); - return 0; + return nullptr; } ++p; value = ""; @@ -1298,7 +1298,7 @@ const char* TiXmlUnknown::Parse( const char* p, TiXmlParsingData* data, TiXmlEnc if ( !p ) { - if ( document ) document->SetError( TIXML_ERROR_PARSING_UNKNOWN, 0, 0, encoding ); + if ( document ) document->SetError( TIXML_ERROR_PARSING_UNKNOWN, nullptr, nullptr, encoding ); } if ( *p == '>' ) return p+1; @@ -1315,7 +1315,7 @@ void TiXmlComment::StreamIn( std::istream * in, TIXML_STRING * tag ) { TiXmlDocument* document = GetDocument(); if ( document ) - document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); + document->SetError( TIXML_ERROR_EMBEDDED_NULL, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); return; } @@ -1351,7 +1351,7 @@ const char* TiXmlComment::Parse( const char* p, TiXmlParsingData* data, TiXmlEnc if ( !StringEqual( p, startTag, false, encoding ) ) { document->SetError( TIXML_ERROR_PARSING_COMMENT, p, data, encoding ); - return 0; + return nullptr; } p += strlen( startTag ); @@ -1390,7 +1390,7 @@ const char* TiXmlComment::Parse( const char* p, TiXmlParsingData* data, TiXmlEnc const char* TiXmlAttribute::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ) { p = SkipWhiteSpace( p, encoding ); - if ( !p || !*p ) return 0; + if ( !p || !*p ) return nullptr; if ( data ) { @@ -1403,13 +1403,13 @@ const char* TiXmlAttribute::Parse( const char* p, TiXmlParsingData* data, TiXmlE if ( !p || !*p ) { if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, pErr, data, encoding ); - return 0; + return nullptr; } p = SkipWhiteSpace( p, encoding ); if ( !p || !*p || *p != '=' ) { if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding ); - return 0; + return nullptr; } ++p; // skip '=' @@ -1417,7 +1417,7 @@ const char* TiXmlAttribute::Parse( const char* p, TiXmlParsingData* data, TiXmlE if ( !p || !*p ) { if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding ); - return 0; + return nullptr; } const char* end; @@ -1451,7 +1451,7 @@ const char* TiXmlAttribute::Parse( const char* p, TiXmlParsingData* data, TiXmlE // We did not have an opening quote but seem to have a // closing one. Give up and throw an error. if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data, encoding ); - return 0; + return nullptr; } value += *p; ++p; @@ -1474,7 +1474,7 @@ void TiXmlText::StreamIn( std::istream * in, TIXML_STRING * tag ) { TiXmlDocument* document = GetDocument(); if ( document ) - document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); + document->SetError( TIXML_ERROR_EMBEDDED_NULL, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); return; } @@ -1513,7 +1513,7 @@ const char* TiXmlText::Parse( const char* p, TiXmlParsingData* data, TiXmlEncodi if ( !StringEqual( p, startTag, false, encoding ) ) { document->SetError( TIXML_ERROR_PARSING_CDATA, p, data, encoding ); - return 0; + return nullptr; } p += strlen( startTag ); @@ -1538,7 +1538,7 @@ const char* TiXmlText::Parse( const char* p, TiXmlParsingData* data, TiXmlEncodi p = ReadText( p, &value, ignoreWhite, end, false, encoding ); if ( p ) return p-1; // don't truncate the '<' - return 0; + return nullptr; } } @@ -1552,7 +1552,7 @@ void TiXmlDeclaration::StreamIn( std::istream * in, TIXML_STRING * tag ) { TiXmlDocument* document = GetDocument(); if ( document ) - document->SetError( TIXML_ERROR_EMBEDDED_NULL, 0, 0, TIXML_ENCODING_UNKNOWN ); + document->SetError( TIXML_ERROR_EMBEDDED_NULL, nullptr, nullptr, TIXML_ENCODING_UNKNOWN ); return; } (*tag) += (char) c; @@ -1574,8 +1574,8 @@ const char* TiXmlDeclaration::Parse( const char* p, TiXmlParsingData* data, TiXm TiXmlDocument* document = GetDocument(); if ( !p || !*p || !StringEqual( p, "SetError( TIXML_ERROR_PARSING_DECLARATION, 0, 0, _encoding ); - return 0; + if ( document ) document->SetError( TIXML_ERROR_PARSING_DECLARATION, nullptr, nullptr, _encoding ); + return nullptr; } if ( data ) { @@ -1622,7 +1622,7 @@ const char* TiXmlDeclaration::Parse( const char* p, TiXmlParsingData* data, TiXm ++p; } } - return 0; + return nullptr; } bool TiXmlText::Blank() const diff --git a/panda/src/egg/config_egg.cxx b/panda/src/egg/config_egg.cxx index 65e08efcbc..ec0009819f 100644 --- a/panda/src/egg/config_egg.cxx +++ b/panda/src/egg/config_egg.cxx @@ -58,8 +58,8 @@ #include "dconfig.h" -#if !defined(CPPPARSER) && !defined(BUILDING_PANDAEGG) - #error Buildsystem error: BUILDING_PANDAEGG not defined +#if !defined(CPPPARSER) && !defined(BUILDING_PANDA_EGG) + #error Buildsystem error: BUILDING_PANDA_EGG not defined #endif Configure(config_egg); diff --git a/panda/src/egg/config_egg.h b/panda/src/egg/config_egg.h index 1df45a4359..a9d67f8460 100644 --- a/panda/src/egg/config_egg.h +++ b/panda/src/egg/config_egg.h @@ -22,26 +22,26 @@ #include "configVariableDouble.h" #include "configVariableInt.h" -NotifyCategoryDecl(egg, EXPCL_PANDAEGG, EXPTP_PANDAEGG); +NotifyCategoryDecl(egg, EXPCL_PANDA_EGG, EXPTP_PANDA_EGG); extern ConfigVariableBool egg_support_old_anims; -extern EXPCL_PANDAEGG ConfigVariableBool egg_mesh; -extern EXPCL_PANDAEGG ConfigVariableBool egg_retesselate_coplanar; -extern EXPCL_PANDAEGG ConfigVariableBool egg_unroll_fans; -extern EXPCL_PANDAEGG ConfigVariableBool egg_show_tstrips; -extern EXPCL_PANDAEGG ConfigVariableBool egg_show_qsheets; -extern EXPCL_PANDAEGG ConfigVariableBool egg_show_quads; +extern EXPCL_PANDA_EGG ConfigVariableBool egg_mesh; +extern EXPCL_PANDA_EGG ConfigVariableBool egg_retesselate_coplanar; +extern EXPCL_PANDA_EGG ConfigVariableBool egg_unroll_fans; +extern EXPCL_PANDA_EGG ConfigVariableBool egg_show_tstrips; +extern EXPCL_PANDA_EGG ConfigVariableBool egg_show_qsheets; +extern EXPCL_PANDA_EGG ConfigVariableBool egg_show_quads; #define egg_false_color (egg_show_tstrips | egg_show_qsheets | egg_show_quads) -extern EXPCL_PANDAEGG ConfigVariableBool egg_subdivide_polys; -extern EXPCL_PANDAEGG ConfigVariableBool egg_consider_fans; -extern EXPCL_PANDAEGG ConfigVariableDouble egg_max_tfan_angle; -extern EXPCL_PANDAEGG ConfigVariableInt egg_min_tfan_tris; -extern EXPCL_PANDAEGG ConfigVariableDouble egg_coplanar_threshold; -extern EXPCL_PANDAEGG ConfigVariableInt egg_test_vref_integrity; -extern EXPCL_PANDAEGG ConfigVariableInt egg_recursion_limit; -extern EXPCL_PANDAEGG ConfigVariableInt egg_precision; +extern EXPCL_PANDA_EGG ConfigVariableBool egg_subdivide_polys; +extern EXPCL_PANDA_EGG ConfigVariableBool egg_consider_fans; +extern EXPCL_PANDA_EGG ConfigVariableDouble egg_max_tfan_angle; +extern EXPCL_PANDA_EGG ConfigVariableInt egg_min_tfan_tris; +extern EXPCL_PANDA_EGG ConfigVariableDouble egg_coplanar_threshold; +extern EXPCL_PANDA_EGG ConfigVariableInt egg_test_vref_integrity; +extern EXPCL_PANDA_EGG ConfigVariableInt egg_recursion_limit; +extern EXPCL_PANDA_EGG ConfigVariableInt egg_precision; -extern EXPCL_PANDAEGG void init_libegg(); +extern EXPCL_PANDA_EGG void init_libegg(); #endif diff --git a/panda/src/egg/eggAnimData.I b/panda/src/egg/eggAnimData.I index aec67eb1a3..20b6c6d62c 100644 --- a/panda/src/egg/eggAnimData.I +++ b/panda/src/egg/eggAnimData.I @@ -17,7 +17,7 @@ * */ INLINE EggAnimData:: -EggAnimData(const string &name) : EggNode(name) { +EggAnimData(const std::string &name) : EggNode(name) { _has_fps = false; } diff --git a/panda/src/egg/eggAnimData.h b/panda/src/egg/eggAnimData.h index 1548f3f0b7..9bcb68030b 100644 --- a/panda/src/egg/eggAnimData.h +++ b/panda/src/egg/eggAnimData.h @@ -27,9 +27,9 @@ * A base class for EggSAnimData and EggXfmAnimData, which contain rows and * columns of numbers. */ -class EXPCL_PANDAEGG EggAnimData : public EggNode { +class EXPCL_PANDA_EGG EggAnimData : public EggNode { PUBLISHED: - INLINE explicit EggAnimData(const string &name = ""); + INLINE explicit EggAnimData(const std::string &name = ""); INLINE EggAnimData(const EggAnimData ©); INLINE EggAnimData &operator = (const EggAnimData ©); diff --git a/panda/src/egg/eggAnimPreload.I b/panda/src/egg/eggAnimPreload.I index 7cfb879347..a13a42ba3d 100644 --- a/panda/src/egg/eggAnimPreload.I +++ b/panda/src/egg/eggAnimPreload.I @@ -15,7 +15,7 @@ * */ INLINE EggAnimPreload:: -EggAnimPreload(const string &name) : EggNode(name) { +EggAnimPreload(const std::string &name) : EggNode(name) { _has_fps = false; _has_num_frames = false; } diff --git a/panda/src/egg/eggAnimPreload.cxx b/panda/src/egg/eggAnimPreload.cxx index ff05b12a3c..894df329ce 100644 --- a/panda/src/egg/eggAnimPreload.cxx +++ b/panda/src/egg/eggAnimPreload.cxx @@ -23,7 +23,7 @@ TypeHandle EggAnimPreload::_type_handle; * Egg format. */ void EggAnimPreload:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { test_under_integrity(); write_header(out, indent_level, ""); diff --git a/panda/src/egg/eggAnimPreload.h b/panda/src/egg/eggAnimPreload.h index 9dc2352e5f..e2b52a5c64 100644 --- a/panda/src/egg/eggAnimPreload.h +++ b/panda/src/egg/eggAnimPreload.h @@ -21,9 +21,9 @@ /** * This corresponds to an entry. */ -class EXPCL_PANDAEGG EggAnimPreload : public EggNode { +class EXPCL_PANDA_EGG EggAnimPreload : public EggNode { PUBLISHED: - INLINE explicit EggAnimPreload(const string &name = ""); + INLINE explicit EggAnimPreload(const std::string &name = ""); INLINE EggAnimPreload(const EggAnimPreload ©); INLINE EggAnimPreload &operator = (const EggAnimPreload ©); @@ -37,7 +37,7 @@ PUBLISHED: INLINE bool has_num_frames() const; INLINE int get_num_frames() const; - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; private: double _fps; diff --git a/panda/src/egg/eggAttributes.cxx b/panda/src/egg/eggAttributes.cxx index 4f27c5a8b3..26fe007524 100644 --- a/panda/src/egg/eggAttributes.cxx +++ b/panda/src/egg/eggAttributes.cxx @@ -62,7 +62,7 @@ EggAttributes:: * Writes the attributes to the indicated output stream in Egg format. */ void EggAttributes:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { if (has_normal()) { if (_dnormals.empty()) { indent(out, indent_level) diff --git a/panda/src/egg/eggAttributes.h b/panda/src/egg/eggAttributes.h index 02e9c112ac..d0fa35dfd3 100644 --- a/panda/src/egg/eggAttributes.h +++ b/panda/src/egg/eggAttributes.h @@ -30,7 +30,7 @@ * EggPolygon level with multiple appearances of the EggObject base class. * And making EggObject a virtual base class is just no fun. */ -class EXPCL_PANDAEGG EggAttributes : public MemoryBase { +class EXPCL_PANDA_EGG EggAttributes : public MemoryBase { PUBLISHED: EggAttributes(); EggAttributes(const EggAttributes ©); @@ -51,7 +51,7 @@ PUBLISHED: INLINE bool matches_color(const EggAttributes &other) const; INLINE void copy_color(const EggAttributes &other); - void write(ostream &out, int indent_level) const; + void write(std::ostream &out, int indent_level) const; INLINE bool sorts_less_than(const EggAttributes &other) const; int compare_to(const EggAttributes &other) const; diff --git a/panda/src/egg/eggBin.cxx b/panda/src/egg/eggBin.cxx index 789eaffb21..95a8bdc0a9 100644 --- a/panda/src/egg/eggBin.cxx +++ b/panda/src/egg/eggBin.cxx @@ -21,7 +21,7 @@ TypeHandle EggBin::_type_handle; * */ EggBin:: -EggBin(const string &name) : EggGroup(name) { +EggBin(const std::string &name) : EggGroup(name) { _bin_number = 0; } diff --git a/panda/src/egg/eggBin.h b/panda/src/egg/eggBin.h index 3553f467fb..d6b09dde22 100644 --- a/panda/src/egg/eggBin.h +++ b/panda/src/egg/eggBin.h @@ -23,9 +23,9 @@ * of node that will never be read in from an egg file, but can only exist in * the egg scene graph if it is created via the use of an EggBinMaker. */ -class EXPCL_PANDAEGG EggBin : public EggGroup { +class EXPCL_PANDA_EGG EggBin : public EggGroup { PUBLISHED: - explicit EggBin(const string &name = ""); + explicit EggBin(const std::string &name = ""); EggBin(const EggGroup ©); EggBin(const EggBin ©); diff --git a/panda/src/egg/eggBinMaker.cxx b/panda/src/egg/eggBinMaker.cxx index 294c76de0d..4c0214eb92 100644 --- a/panda/src/egg/eggBinMaker.cxx +++ b/panda/src/egg/eggBinMaker.cxx @@ -112,9 +112,9 @@ collapse_group(const EggGroup *, int) { * May be overridden in derived classes to define a name for each new bin, * based on its bin number, and a sample child. */ -string EggBinMaker:: +std::string EggBinMaker:: get_bin_name(int, const EggNode *) { - return string(); + return std::string(); } /** @@ -128,7 +128,7 @@ get_bin_name(int, const EggNode *) { */ PT(EggBin) EggBinMaker:: make_bin(int, const EggNode *, EggGroup *collapse_from) { - if (collapse_from == (EggGroup *)NULL) { + if (collapse_from == nullptr) { return new EggBin; } else { return new EggBin(*collapse_from); @@ -162,7 +162,7 @@ collect_nodes(EggGroupNode *group) { // If this is the first time this group has been encountered, we need // to create a new entry in _group_nodes for it. - pair result; + std::pair result; result = _group_nodes.insert (GroupNodes::value_type (group, SortedNodes(EggBinMakerCompareNodes(this)))); @@ -243,7 +243,7 @@ make_bins_for_group(EggGroupNode *group, const Bins &bins) { if (group->empty() && bins.size() == 1 && - group->get_parent() != NULL && + group->get_parent() != nullptr && group->is_of_type(EggGroup::get_class_type())) { const Nodes &nodes = bins.front(); nassertv(!nodes.empty()); @@ -268,7 +268,7 @@ make_bins_for_group(EggGroupNode *group, const Bins &bins) { const Nodes &nodes = (*bi); nassertv(!nodes.empty()); int bin_number = get_bin_number(nodes.front()); - PT(EggBin) bin = make_bin(bin_number, nodes.front(), NULL); + PT(EggBin) bin = make_bin(bin_number, nodes.front(), nullptr); setup_bin(bin, nodes); group->add_child(bin); @@ -286,7 +286,7 @@ setup_bin(EggBin *bin, const Nodes &nodes) { int bin_number = get_bin_number(nodes.front()); bin->set_bin_number(bin_number); - string bin_name = get_bin_name(bin_number, nodes.front()); + std::string bin_name = get_bin_name(bin_number, nodes.front()); if (!bin_name.empty()) { bin->set_name(bin_name); } diff --git a/panda/src/egg/eggBinMaker.h b/panda/src/egg/eggBinMaker.h index 2e3da3418f..02f3dbb43f 100644 --- a/panda/src/egg/eggBinMaker.h +++ b/panda/src/egg/eggBinMaker.h @@ -139,7 +139,7 @@ class EggBinMaker; * This is just an STL function object, used to sort nodes within EggBinMaker. * It's part of the private interface; ignore it. */ -class EXPCL_PANDAEGG EggBinMakerCompareNodes { +class EXPCL_PANDA_EGG EggBinMakerCompareNodes { public: EggBinMakerCompareNodes() { // We need to have a default constructor to compile, but it should never @@ -158,7 +158,7 @@ public: * abstract class; to use it you must subclass off of it. See the somewhat * lengthy comment above. */ -class EXPCL_PANDAEGG EggBinMaker : public EggObject { +class EXPCL_PANDA_EGG EggBinMaker : public EggObject { PUBLISHED: EggBinMaker(); ~EggBinMaker(); @@ -177,7 +177,7 @@ PUBLISHED: virtual bool collapse_group(const EggGroup *group, int bin_number); - virtual string + virtual std::string get_bin_name(int bin_number, const EggNode *child); virtual PT(EggBin) diff --git a/panda/src/egg/eggComment.I b/panda/src/egg/eggComment.I index cd26e3b12d..ac99fb54e9 100644 --- a/panda/src/egg/eggComment.I +++ b/panda/src/egg/eggComment.I @@ -15,7 +15,7 @@ * */ INLINE EggComment:: -EggComment(const string &node_name, const string &comment) +EggComment(const std::string &node_name, const std::string &comment) : EggNode(node_name), _comment(comment) { } @@ -31,7 +31,7 @@ EggComment(const EggComment ©) : EggNode(copy), _comment(copy._comment) { * */ INLINE EggComment &EggComment:: -operator = (const string &comment) { +operator = (const std::string &comment) { _comment = comment; return *this; } @@ -51,7 +51,7 @@ operator = (const EggComment ©) { * */ INLINE EggComment:: -operator const string & () const { +operator const std::string & () const { return _comment; } @@ -60,7 +60,7 @@ operator const string & () const { * */ INLINE void EggComment:: -set_comment(const string &comment) { +set_comment(const std::string &comment) { _comment = comment; } @@ -68,7 +68,7 @@ set_comment(const string &comment) { /** * */ -INLINE string EggComment:: +INLINE std::string EggComment:: get_comment() const { return _comment; } diff --git a/panda/src/egg/eggComment.cxx b/panda/src/egg/eggComment.cxx index a55dd0787c..1379623c03 100644 --- a/panda/src/egg/eggComment.cxx +++ b/panda/src/egg/eggComment.cxx @@ -24,7 +24,7 @@ TypeHandle EggComment::_type_handle; * Writes the comment definition to the indicated output stream in Egg format. */ void EggComment:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { write_header(out, indent_level, ""); enquote_string(out, get_comment(), indent_level + 2) << "\n"; indent(out, indent_level) << "}\n"; diff --git a/panda/src/egg/eggComment.h b/panda/src/egg/eggComment.h index 63d5eb82d8..17611ed5d5 100644 --- a/panda/src/egg/eggComment.h +++ b/panda/src/egg/eggComment.h @@ -21,28 +21,28 @@ /** * A comment that appears in an egg file within a entry. */ -class EXPCL_PANDAEGG EggComment : public EggNode { +class EXPCL_PANDA_EGG EggComment : public EggNode { PUBLISHED: - INLINE explicit EggComment(const string &node_name, const string &comment); + INLINE explicit EggComment(const std::string &node_name, const std::string &comment); INLINE EggComment(const EggComment ©); // You can use the string operators to directly set and manipulate the // comment. - INLINE EggComment &operator = (const string &comment); + INLINE EggComment &operator = (const std::string &comment); INLINE EggComment &operator = (const EggComment ©); - INLINE operator const string & () const; + INLINE operator const std::string & () const; // Or, you can set and get it explicitly. - INLINE void set_comment(const string &comment); - INLINE string get_comment() const; + INLINE void set_comment(const std::string &comment); + INLINE std::string get_comment() const; - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; private: - string _comment; + std::string _comment; public: diff --git a/panda/src/egg/eggCompositePrimitive.I b/panda/src/egg/eggCompositePrimitive.I index 9a0d054100..0288f62d97 100644 --- a/panda/src/egg/eggCompositePrimitive.I +++ b/panda/src/egg/eggCompositePrimitive.I @@ -15,7 +15,7 @@ * */ INLINE EggCompositePrimitive:: -EggCompositePrimitive(const string &name) : EggPrimitive(name) { +EggCompositePrimitive(const std::string &name) : EggPrimitive(name) { } /** diff --git a/panda/src/egg/eggCompositePrimitive.cxx b/panda/src/egg/eggCompositePrimitive.cxx index 65c7e338dd..fe42870846 100644 --- a/panda/src/egg/eggCompositePrimitive.cxx +++ b/panda/src/egg/eggCompositePrimitive.cxx @@ -57,7 +57,7 @@ get_shading() const { if (!first_component->has_normal()) { first_component = this; } - for (int i = 1; i < get_num_components(); i++) { + for (size_t i = 1; i < get_num_components(); ++i) { const EggAttributes *component = get_component(i); if (!component->has_normal()) { component = this; @@ -74,7 +74,7 @@ get_shading() const { if (!first_component->has_color()) { first_component = this; } - for (int i = 1; i < get_num_components(); i++) { + for (size_t i = 1; i < get_num_components(); ++i) { const EggAttributes *component = get_component(i); if (!component->has_color()) { component = this; @@ -100,7 +100,7 @@ get_shading() const { PT(EggCompositePrimitive) EggCompositePrimitive:: triangulate_in_place() { EggGroupNode *parent = get_parent(); - nassertr(parent != (EggGroupNode *)NULL, this); + nassertr(parent != nullptr, this); PT(EggCompositePrimitive) save_me = this; parent->remove_child(this); @@ -171,7 +171,7 @@ unify_attributes(EggPrimitive::Shading shading) { } EggVertexPool *vertex_pool = orig_vertex->get_pool(); - nassertv(vertex_pool != (EggVertexPool *)NULL); + nassertv(vertex_pool != nullptr); vertex = vertex_pool->create_unique_vertex(*vertex); vertex->copy_grefs_from(*orig_vertex); replace(pi, vertex); @@ -200,7 +200,7 @@ unify_attributes(EggPrimitive::Shading shading) { vertex->clear_color(); EggVertexPool *vertex_pool = orig_vertex->get_pool(); - nassertv(vertex_pool != (EggVertexPool *)NULL); + nassertv(vertex_pool != nullptr); vertex = vertex_pool->create_unique_vertex(*vertex); vertex->copy_grefs_from(*orig_vertex); replace(pi, vertex); @@ -248,7 +248,7 @@ unify_attributes(EggPrimitive::Shading shading) { } EggVertexPool *vertex_pool = orig_vertex->get_pool(); - nassertv(vertex_pool != (EggVertexPool *)NULL); + nassertv(vertex_pool != nullptr); vertex = vertex_pool->create_unique_vertex(*vertex); vertex->copy_grefs_from(*orig_vertex); replace(pi, vertex); @@ -295,7 +295,7 @@ apply_last_attribute() { // The first component gets applied to the third vertex, and so on from // there. int num_lead_vertices = get_num_lead_vertices(); - for (int i = 0; i < get_num_components(); i++) { + for (size_t i = 0; i < get_num_components(); ++i) { EggAttributes *component = get_component(i); do_apply_flat_attribute(i + num_lead_vertices, component); } @@ -313,7 +313,7 @@ void EggCompositePrimitive:: apply_first_attribute() { // The first component gets applied to the first vertex, and so on from // there. - for (int i = 0; i < get_num_components(); i++) { + for (size_t i = 0; i < get_num_components(); ++i) { EggAttributes *component = get_component(i); do_apply_flat_attribute(i, component); } @@ -330,7 +330,7 @@ post_apply_flat_attribute() { int num_lead_vertices = get_num_lead_vertices(); for (int i = 0; i < (int)size(); i++) { EggVertex *vertex = get_vertex(i); - EggAttributes *component = get_component(max(i - num_lead_vertices, 0)); + EggAttributes *component = get_component(std::max(i - num_lead_vertices, 0)); // Use set_normal() instead of copy_normal(), to avoid getting the // morphs--we don't want them here, since we're just putting a bogus @@ -376,7 +376,7 @@ prepare_add_vertex(EggVertex *vertex, int i, int n) { int num_lead_vertices = get_num_lead_vertices(); if (n >= num_lead_vertices + 1) { - i = max(i - num_lead_vertices, 0); + i = std::max(i - num_lead_vertices, 0); nassertv(i <= (int)_components.size()); _components.insert(_components.begin() + i, new EggAttributes(*this)); } @@ -400,7 +400,7 @@ prepare_remove_vertex(EggVertex *vertex, int i, int n) { int num_lead_vertices = get_num_lead_vertices(); if (n >= num_lead_vertices + 1) { - i = max(i - num_lead_vertices, 0); + i = std::max(i - num_lead_vertices, 0); nassertv(i < (int)_components.size()); delete _components[i]; _components.erase(_components.begin() + i); @@ -428,10 +428,10 @@ do_triangulate(EggGroupNode *container) const { * indicated output stream in Egg format. */ void EggCompositePrimitive:: -write_body(ostream &out, int indent_level) const { +write_body(std::ostream &out, int indent_level) const { EggPrimitive::write_body(out, indent_level); - for (int i = 0; i < get_num_components(); i++) { + for (size_t i = 0; i < get_num_components(); ++i) { const EggAttributes *attrib = get_component(i); if (attrib->compare_to(*this) != 0 && (attrib->has_color() || attrib->has_normal())) { diff --git a/panda/src/egg/eggCompositePrimitive.h b/panda/src/egg/eggCompositePrimitive.h index 9b5e0fa58d..d7e169624b 100644 --- a/panda/src/egg/eggCompositePrimitive.h +++ b/panda/src/egg/eggCompositePrimitive.h @@ -23,9 +23,9 @@ * which include several component triangles, each of which might have its own * color and/or normal. */ -class EXPCL_PANDAEGG EggCompositePrimitive : public EggPrimitive { +class EXPCL_PANDA_EGG EggCompositePrimitive : public EggPrimitive { PUBLISHED: - INLINE explicit EggCompositePrimitive(const string &name = ""); + INLINE explicit EggCompositePrimitive(const std::string &name = ""); INLINE EggCompositePrimitive(const EggCompositePrimitive ©); INLINE EggCompositePrimitive &operator = (const EggCompositePrimitive ©); virtual ~EggCompositePrimitive(); @@ -56,7 +56,7 @@ protected: virtual bool do_triangulate(EggGroupNode *container) const; - void write_body(ostream &out, int indent_level) const; + void write_body(std::ostream &out, int indent_level) const; private: typedef pvector Components; diff --git a/panda/src/egg/eggCoordinateSystem.cxx b/panda/src/egg/eggCoordinateSystem.cxx index 9ef0ce14f9..a646de21c7 100644 --- a/panda/src/egg/eggCoordinateSystem.cxx +++ b/panda/src/egg/eggCoordinateSystem.cxx @@ -23,7 +23,7 @@ TypeHandle EggCoordinateSystem::_type_handle; * Egg format. */ void EggCoordinateSystem:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { if (get_value() != CS_default && get_value() != CS_invalid) { indent(out, indent_level) diff --git a/panda/src/egg/eggCoordinateSystem.h b/panda/src/egg/eggCoordinateSystem.h index bf8469b375..54a76e6f78 100644 --- a/panda/src/egg/eggCoordinateSystem.h +++ b/panda/src/egg/eggCoordinateSystem.h @@ -26,7 +26,7 @@ * with the enum EggData::CoordinateSystem, which is the value contained by * this entry. */ -class EXPCL_PANDAEGG EggCoordinateSystem : public EggNode { +class EXPCL_PANDA_EGG EggCoordinateSystem : public EggNode { PUBLISHED: INLINE EggCoordinateSystem(CoordinateSystem value = CS_default); INLINE EggCoordinateSystem(const EggCoordinateSystem ©); @@ -34,7 +34,7 @@ PUBLISHED: INLINE void set_value(CoordinateSystem value); INLINE CoordinateSystem get_value() const; - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; private: CoordinateSystem _value; diff --git a/panda/src/egg/eggCurve.I b/panda/src/egg/eggCurve.I index e8a665fcda..2fe86edf6d 100644 --- a/panda/src/egg/eggCurve.I +++ b/panda/src/egg/eggCurve.I @@ -15,7 +15,7 @@ * */ INLINE EggCurve:: -EggCurve(const string &name) : EggPrimitive(name) { +EggCurve(const std::string &name) : EggPrimitive(name) { _subdiv = 0; _type = CT_none; } diff --git a/panda/src/egg/eggCurve.cxx b/panda/src/egg/eggCurve.cxx index 932e4a6c9d..1c18a9ac5e 100644 --- a/panda/src/egg/eggCurve.cxx +++ b/panda/src/egg/eggCurve.cxx @@ -25,7 +25,7 @@ TypeHandle EggCurve::_type_handle; * CurveType value. */ EggCurve::CurveType EggCurve:: -string_curve_type(const string &string) { +string_curve_type(const std::string &string) { if (cmp_nocase_uh(string, "xyz") == 0) { return CT_xyz; } else if (cmp_nocase_uh(string, "hpr") == 0) { @@ -40,7 +40,7 @@ string_curve_type(const string &string) { /** * */ -ostream &operator << (ostream &out, EggCurve::CurveType t) { +std::ostream &operator << (std::ostream &out, EggCurve::CurveType t) { switch (t) { case EggCurve::CT_none: return out << "none"; diff --git a/panda/src/egg/eggCurve.h b/panda/src/egg/eggCurve.h index 6ea17bc77a..736869fbdb 100644 --- a/panda/src/egg/eggCurve.h +++ b/panda/src/egg/eggCurve.h @@ -21,9 +21,9 @@ /** * A parametric curve of some kind. See EggNurbsCurve. */ -class EXPCL_PANDAEGG EggCurve : public EggPrimitive { +class EXPCL_PANDA_EGG EggCurve : public EggPrimitive { PUBLISHED: - INLINE explicit EggCurve(const string &name = ""); + INLINE explicit EggCurve(const std::string &name = ""); INLINE EggCurve(const EggCurve ©); INLINE EggCurve &operator = (const EggCurve ©); @@ -40,7 +40,7 @@ PUBLISHED: INLINE void set_curve_type(CurveType type); INLINE CurveType get_curve_type() const; - static CurveType string_curve_type(const string &string); + static CurveType string_curve_type(const std::string &string); private: int _subdiv; @@ -65,7 +65,7 @@ private: static TypeHandle _type_handle; }; -ostream &operator << (ostream &out, EggCurve::CurveType t); +std::ostream &operator << (std::ostream &out, EggCurve::CurveType t); #include "eggCurve.I" diff --git a/panda/src/egg/eggData.cxx b/panda/src/egg/eggData.cxx index 69eb4eb6e6..75c9ad68d0 100644 --- a/panda/src/egg/eggData.cxx +++ b/panda/src/egg/eggData.cxx @@ -26,6 +26,9 @@ #include "lightMutexHolder.h" #include "zStream.h" +using std::istream; +using std::ostream; + extern int eggyyparse(); #include "parserDefs.h" #include "lexerDefs.h" @@ -59,7 +62,7 @@ resolve_egg_filename(Filename &egg_filename, const DSearchPath &searchpath) { * error is the output stream to which to write error messages. */ bool EggData:: -read(Filename filename, string display_name) { +read(Filename filename, std::string display_name) { filename.set_text(); set_egg_filename(filename); @@ -70,14 +73,14 @@ read(Filename filename, string display_name) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); PT(VirtualFile) vfile = vfs->get_file(filename); - if (vfile == NULL) { + if (vfile == nullptr) { egg_cat.error() << "Could not find " << display_name << "\n"; return false; } set_egg_timestamp(vfile->get_timestamp()); istream *file = vfile->open_read_file(true); - if (file == (istream *)NULL) { + if (file == nullptr) { egg_cat.error() << "Unable to open " << display_name << "\n"; return false; } @@ -158,7 +161,7 @@ merge(EggData &other) { bool EggData:: load_externals(const DSearchPath &searchpath) { return - r_load_externals(searchpath, get_coordinate_system(), NULL); + r_load_externals(searchpath, get_coordinate_system(), nullptr); } /** @@ -211,7 +214,7 @@ write_egg(Filename filename) { filename.set_text(); vfs->delete_file(filename); ostream *file = vfs->open_write_file(filename, true, true); - if (file == (ostream *)NULL) { + if (file == nullptr) { egg_cat.error() << "Unable to open " << filename << " for writing.\n"; return false; } @@ -230,8 +233,8 @@ write_egg(ostream &out) { if (egg_precision > 0) { // Change the egg precision as requested. - streamsize orig_precision = out.precision(); - out.precision((streamsize)egg_precision); + std::streamsize orig_precision = out.precision(); + out.precision((std::streamsize)egg_precision); write(out, 0); out.precision(orig_precision); } else { @@ -276,7 +279,7 @@ write(ostream &out, int indent_level) const { PT(EggCoordinateSystem) ecs = new EggCoordinateSystem(_coordsys); ecs->write(out, indent_level); EggGroupNode::write(out, indent_level); - out << flush; + out << std::flush; } diff --git a/panda/src/egg/eggData.h b/panda/src/egg/eggData.h index 5544f28d60..ad5d3a9917 100644 --- a/panda/src/egg/eggData.h +++ b/panda/src/egg/eggData.h @@ -34,7 +34,7 @@ class BamCacheRecord; * begin() and end() calls. The children of the EggData class are the * toplevel nodes in the egg file. */ -class EXPCL_PANDAEGG EggData : public EggGroupNode { +class EXPCL_PANDA_EGG EggData : public EggGroupNode { PUBLISHED: INLINE EggData(); INLINE EggData(const EggData ©); @@ -43,8 +43,8 @@ PUBLISHED: static bool resolve_egg_filename(Filename &egg_filename, const DSearchPath &searchpath = DSearchPath()); - bool read(Filename filename, string display_name = string()); - bool read(istream &in); + bool read(Filename filename, std::string display_name = std::string()); + bool read(std::istream &in); void merge(EggData &other); bool load_externals(const DSearchPath &searchpath = DSearchPath()); @@ -53,7 +53,7 @@ PUBLISHED: int collapse_equivalent_materials(); bool write_egg(Filename filename); - bool write_egg(ostream &out); + bool write_egg(std::ostream &out); INLINE void set_auto_resolve_externals(bool resolve); INLINE bool get_auto_resolve_externals() const; @@ -73,7 +73,7 @@ PUBLISHED: INLINE void strip_normals(); protected: - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; private: void post_read(); diff --git a/panda/src/egg/eggExternalReference.cxx b/panda/src/egg/eggExternalReference.cxx index d70a5003db..e124e05238 100644 --- a/panda/src/egg/eggExternalReference.cxx +++ b/panda/src/egg/eggExternalReference.cxx @@ -24,7 +24,7 @@ TypeHandle EggExternalReference::_type_handle; * */ EggExternalReference:: -EggExternalReference(const string &node_name, const string &filename) +EggExternalReference(const std::string &node_name, const std::string &filename) : EggFilenameNode(node_name, filename) { } @@ -49,7 +49,7 @@ operator = (const EggExternalReference ©) { * Writes the reference to the indicated output stream in Egg format. */ void EggExternalReference:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { write_header(out, indent_level, ""); enquote_string(out, get_filename(), indent_level + 2) << "\n"; indent(out, indent_level) << "}\n"; @@ -58,7 +58,7 @@ write(ostream &out, int indent_level) const { /** * Returns the default extension for this filename type. */ -string EggExternalReference:: +std::string EggExternalReference:: get_default_extension() const { - return string("egg"); + return std::string("egg"); } diff --git a/panda/src/egg/eggExternalReference.h b/panda/src/egg/eggExternalReference.h index 799c794bd1..d19879397d 100644 --- a/panda/src/egg/eggExternalReference.h +++ b/panda/src/egg/eggExternalReference.h @@ -22,15 +22,15 @@ * Defines a reference to another egg file which should be inserted at this * point. */ -class EXPCL_PANDAEGG EggExternalReference : public EggFilenameNode { +class EXPCL_PANDA_EGG EggExternalReference : public EggFilenameNode { PUBLISHED: - explicit EggExternalReference(const string &node_name, const string &filename); + explicit EggExternalReference(const std::string &node_name, const std::string &filename); EggExternalReference(const EggExternalReference ©); EggExternalReference &operator = (const EggExternalReference ©); - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; - virtual string get_default_extension() const; + virtual std::string get_default_extension() const; public: diff --git a/panda/src/egg/eggFilenameNode.I b/panda/src/egg/eggFilenameNode.I index d2aecbb943..c368becdaa 100644 --- a/panda/src/egg/eggFilenameNode.I +++ b/panda/src/egg/eggFilenameNode.I @@ -22,7 +22,7 @@ EggFilenameNode() { * */ INLINE EggFilenameNode:: -EggFilenameNode(const string &node_name, const Filename &filename) : +EggFilenameNode(const std::string &node_name, const Filename &filename) : EggNode(node_name), _filename(filename), _fullpath(filename) diff --git a/panda/src/egg/eggFilenameNode.cxx b/panda/src/egg/eggFilenameNode.cxx index b0a257c9a4..83e26aff5f 100644 --- a/panda/src/egg/eggFilenameNode.cxx +++ b/panda/src/egg/eggFilenameNode.cxx @@ -18,7 +18,7 @@ TypeHandle EggFilenameNode::_type_handle; /** * Returns the default extension for this filename type. */ -string EggFilenameNode:: +std::string EggFilenameNode:: get_default_extension() const { - return string(); + return std::string(); } diff --git a/panda/src/egg/eggFilenameNode.h b/panda/src/egg/eggFilenameNode.h index 46734f6a24..ee98f8d091 100644 --- a/panda/src/egg/eggFilenameNode.h +++ b/panda/src/egg/eggFilenameNode.h @@ -24,14 +24,14 @@ * file relative to the directory the egg file was loaded in. It is a base * class for EggTexture and EggExternalReference. */ -class EXPCL_PANDAEGG EggFilenameNode : public EggNode { +class EXPCL_PANDA_EGG EggFilenameNode : public EggNode { PUBLISHED: INLINE EggFilenameNode(); - INLINE explicit EggFilenameNode(const string &node_name, const Filename &filename); + INLINE explicit EggFilenameNode(const std::string &node_name, const Filename &filename); INLINE EggFilenameNode(const EggFilenameNode ©); INLINE EggFilenameNode &operator = (const EggFilenameNode ©); - virtual string get_default_extension() const; + virtual std::string get_default_extension() const; INLINE const Filename &get_filename() const; INLINE void set_filename(const Filename &filename); diff --git a/panda/src/egg/eggGroup.I b/panda/src/egg/eggGroup.I index d66de55e0f..7809867047 100644 --- a/panda/src/egg/eggGroup.I +++ b/panda/src/egg/eggGroup.I @@ -127,7 +127,7 @@ get_cs_type() const { * */ INLINE void EggGroup:: -set_collision_name(const string &collision_name) { +set_collision_name(const std::string &collision_name) { _collision_name = collision_name; } @@ -150,7 +150,7 @@ has_collision_name() const { /** * */ -INLINE const string &EggGroup:: +INLINE const std::string &EggGroup:: get_collision_name() const { return _collision_name; } @@ -259,7 +259,7 @@ get_switch_fps() const { * */ INLINE void EggGroup:: -add_object_type(const string &object_type) { +add_object_type(const std::string &object_type) { _object_types.push_back(object_type); } @@ -282,9 +282,9 @@ get_num_object_types() const { /** * */ -INLINE string EggGroup:: +INLINE std::string EggGroup:: get_object_type(int index) const { - nassertr(index >= 0 && index < (int)_object_types.size(), string()); + nassertr(index >= 0 && index < (int)_object_types.size(), std::string()); return _object_types[index]; } @@ -686,7 +686,7 @@ set_lod(const EggSwitchCondition &lod) { */ INLINE void EggGroup:: clear_lod() { - _lod = NULL; + _lod = nullptr; } /** @@ -694,7 +694,7 @@ clear_lod() { */ INLINE bool EggGroup:: has_lod() const { - return (_lod != (EggSwitchCondition *)NULL); + return (_lod != nullptr); } /** @@ -717,7 +717,7 @@ get_lod() const { * of any one key's value. */ INLINE void EggGroup:: -set_tag(const string &key, const string &value) { +set_tag(const std::string &key, const std::string &value) { _tag_data[key] = value; } @@ -726,14 +726,14 @@ set_tag(const string &key, const string &value) { * the particular key, if any. If no value has been previously set, returns * the empty string. */ -INLINE string EggGroup:: -get_tag(const string &key) const { +INLINE std::string EggGroup:: +get_tag(const std::string &key) const { TagData::const_iterator ti; ti = _tag_data.find(key); if (ti != _tag_data.end()) { return (*ti).second; } - return string(); + return std::string(); } /** @@ -742,7 +742,7 @@ get_tag(const string &key) const { * set. */ INLINE bool EggGroup:: -has_tag(const string &key) const { +has_tag(const std::string &key) const { TagData::const_iterator ti; ti = _tag_data.find(key); return (ti != _tag_data.end()); @@ -753,7 +753,7 @@ has_tag(const string &key) const { * call to clear_tag(), has_tag() will return false for the indicated key. */ INLINE void EggGroup:: -clear_tag(const string &key) { +clear_tag(const std::string &key) { _tag_data.erase(key); } diff --git a/panda/src/egg/eggGroup.cxx b/panda/src/egg/eggGroup.cxx index 2377006bab..a5ff1dee06 100644 --- a/panda/src/egg/eggGroup.cxx +++ b/panda/src/egg/eggGroup.cxx @@ -22,6 +22,9 @@ #include "lmatrix.h" #include "dcast.h" +using std::ostream; +using std::string; + TypeHandle EggGroup::_type_handle; @@ -772,7 +775,7 @@ get_num_group_refs() const { */ EggGroup *EggGroup:: get_group_ref(int n) const { - nassertr(n >= 0 && n < (int)_group_refs.size(), NULL); + nassertr(n >= 0 && n < (int)_group_refs.size(), nullptr); return _group_refs[n]; } @@ -1069,7 +1072,7 @@ write_vertex_ref(ostream &out, int indent_level) const { indent(out, indent_level + 2) << " membership { " << membership << " }\n"; } - if (pool == (EggVertexPool *)NULL) { + if (pool == nullptr) { indent(out, indent_level + 2) << "// Invalid NULL vertex pool.\n"; } else { @@ -1121,7 +1124,7 @@ adjust_under() { _node_frame_inv = new MatrixFrame(mat); } else { - _node_frame_inv = NULL; + _node_frame_inv = nullptr; } _vertex_to_node = @@ -1144,8 +1147,8 @@ adjust_under() { // frame. _vertex_frame = _node_frame; _vertex_frame_inv = _node_frame_inv; - _vertex_to_node = NULL; - _node_to_vertex = NULL; + _vertex_to_node = nullptr; + _node_to_vertex = nullptr; } } diff --git a/panda/src/egg/eggGroup.h b/panda/src/egg/eggGroup.h index 1266e42a49..14485dcc24 100644 --- a/panda/src/egg/eggGroup.h +++ b/panda/src/egg/eggGroup.h @@ -31,10 +31,10 @@ * The main glue of the egg hierarchy, this corresponds to the , * , and type nodes. */ -class EXPCL_PANDAEGG EggGroup : public EggGroupNode, public EggRenderMode, public EggTransform { +class EXPCL_PANDA_EGG EggGroup : public EggGroupNode, public EggRenderMode, public EggTransform { PUBLISHED: typedef pmap VertexRef; - typedef pmap TagData; + typedef pmap TagData; // These bits are all stored somewhere in _flags. enum GroupType { @@ -132,20 +132,20 @@ PUBLISHED: BO_one_minus_alpha_scale, }; - explicit EggGroup(const string &name = ""); + explicit EggGroup(const std::string &name = ""); EggGroup(const EggGroup ©); EggGroup &operator = (const EggGroup ©); ~EggGroup(); - virtual void write(ostream &out, int indent_level) const; - void write_billboard_flags(ostream &out, int indent_level) const; - void write_collide_flags(ostream &out, int indent_level) const; - void write_model_flags(ostream &out, int indent_level) const; - void write_switch_flags(ostream &out, int indent_level) const; - void write_object_types(ostream &out, int indent_level) const; - void write_decal_flags(ostream &out, int indent_level) const; - void write_tags(ostream &out, int indent_level) const; - void write_render_mode(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; + void write_billboard_flags(std::ostream &out, int indent_level) const; + void write_collide_flags(std::ostream &out, int indent_level) const; + void write_model_flags(std::ostream &out, int indent_level) const; + void write_switch_flags(std::ostream &out, int indent_level) const; + void write_object_types(std::ostream &out, int indent_level) const; + void write_decal_flags(std::ostream &out, int indent_level) const; + void write_tags(std::ostream &out, int indent_level) const; + void write_render_mode(std::ostream &out, int indent_level) const; virtual bool is_joint() const; @@ -177,10 +177,10 @@ PUBLISHED: INLINE void set_collide_flags(int flags); INLINE CollideFlags get_collide_flags() const; - INLINE void set_collision_name(const string &collision_name); + INLINE void set_collision_name(const std::string &collision_name); INLINE void clear_collision_name(); INLINE bool has_collision_name() const; - INLINE const string &get_collision_name() const; + INLINE const std::string &get_collision_name() const; INLINE void set_dcs_type(DCSType type); INLINE DCSType get_dcs_type() const; @@ -195,13 +195,13 @@ PUBLISHED: INLINE void set_switch_fps(double fps); INLINE double get_switch_fps() const; - INLINE void add_object_type(const string &object_type); + INLINE void add_object_type(const std::string &object_type); INLINE void clear_object_types(); INLINE int get_num_object_types() const; - INLINE string get_object_type(int index) const; + INLINE std::string get_object_type(int index) const; MAKE_SEQ(get_object_types, get_num_object_types, get_object_type); - bool has_object_type(const string &object_type) const; - bool remove_object_type(const string &object_type); + bool has_object_type(const std::string &object_type) const; + bool remove_object_type(const std::string &object_type); INLINE void set_model_flag(bool flag); INLINE bool get_model_flag() const; @@ -263,10 +263,10 @@ PUBLISHED: INLINE bool has_lod() const; INLINE const EggSwitchCondition &get_lod() const; - INLINE void set_tag(const string &key, const string &value); - INLINE string get_tag(const string &key) const; - INLINE bool has_tag(const string &key) const; - INLINE void clear_tag(const string &key); + INLINE void set_tag(const std::string &key, const std::string &value); + INLINE std::string get_tag(const std::string &key) const; + INLINE bool has_tag(const std::string &key) const; + INLINE void clear_tag(const std::string &key); INLINE const EggTransform &get_default_pose() const; INLINE EggTransform &modify_default_pose(); @@ -355,20 +355,20 @@ PUBLISHED: void remove_group_ref(int n); void clear_group_refs(); - static GroupType string_group_type(const string &strval); - static DartType string_dart_type(const string &strval); - static DCSType string_dcs_type(const string &strval); - static BillboardType string_billboard_type(const string &strval); - static CollisionSolidType string_cs_type(const string &strval); - static CollideFlags string_collide_flags(const string &strval); - static BlendMode string_blend_mode(const string &strval); - static BlendOperand string_blend_operand(const string &strval); + static GroupType string_group_type(const std::string &strval); + static DartType string_dart_type(const std::string &strval); + static DCSType string_dcs_type(const std::string &strval); + static BillboardType string_billboard_type(const std::string &strval); + static CollisionSolidType string_cs_type(const std::string &strval); + static CollideFlags string_collide_flags(const std::string &strval); + static BlendMode string_blend_mode(const std::string &strval); + static BlendOperand string_blend_operand(const std::string &strval); public: virtual EggTransform *as_transform(); protected: - void write_vertex_ref(ostream &out, int indent_level) const; + void write_vertex_ref(std::ostream &out, int indent_level) const; virtual bool egg_start_parse_body(); virtual void adjust_under(); virtual void r_transform(const LMatrix4d &mat, const LMatrix4d &inv, @@ -417,7 +417,7 @@ private: LColor _blend_color; LPoint3d _billboard_center; vector_string _object_types; - string _collision_name; + std::string _collision_name; double _fps; PT(EggSwitchCondition) _lod; TagData _tag_data; @@ -459,14 +459,14 @@ private: static TypeHandle _type_handle; }; -ostream &operator << (ostream &out, EggGroup::GroupType t); -ostream &operator << (ostream &out, EggGroup::DartType t); -ostream &operator << (ostream &out, EggGroup::DCSType t); -ostream &operator << (ostream &out, EggGroup::BillboardType t); -ostream &operator << (ostream &out, EggGroup::CollisionSolidType t); -ostream &operator << (ostream &out, EggGroup::CollideFlags t); -ostream &operator << (ostream &out, EggGroup::BlendMode t); -ostream &operator << (ostream &out, EggGroup::BlendOperand t); +std::ostream &operator << (std::ostream &out, EggGroup::GroupType t); +std::ostream &operator << (std::ostream &out, EggGroup::DartType t); +std::ostream &operator << (std::ostream &out, EggGroup::DCSType t); +std::ostream &operator << (std::ostream &out, EggGroup::BillboardType t); +std::ostream &operator << (std::ostream &out, EggGroup::CollisionSolidType t); +std::ostream &operator << (std::ostream &out, EggGroup::CollideFlags t); +std::ostream &operator << (std::ostream &out, EggGroup::BlendMode t); +std::ostream &operator << (std::ostream &out, EggGroup::BlendOperand t); #include "eggGroup.I" diff --git a/panda/src/egg/eggGroupNode.cxx b/panda/src/egg/eggGroupNode.cxx index acf509274a..851eba7f48 100644 --- a/panda/src/egg/eggGroupNode.cxx +++ b/panda/src/egg/eggGroupNode.cxx @@ -39,6 +39,8 @@ #include +using std::string; + TypeHandle EggGroupNode::_type_handle; @@ -79,7 +81,7 @@ EggGroupNode:: * Egg format. */ void EggGroupNode:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { iterator i; // Since joints tend to reference vertex pools, which sometimes appear later @@ -230,7 +232,7 @@ get_next_child() { if (_gnc_iterator != end()) { return *_gnc_iterator++; } - return NULL; + return nullptr; } /** @@ -241,7 +243,7 @@ EggNode *EggGroupNode:: add_child(EggNode *node) { test_ref_count_integrity(); PT(EggNode) ptnode = node; - if (node->_parent != NULL) { + if (node->_parent != nullptr) { node->_parent->remove_child(node); } prepare_add_child(node); @@ -300,7 +302,7 @@ find_child(const string &name) const { } } - return NULL; + return nullptr; } /** @@ -738,7 +740,7 @@ triangulate_polygons(int flags) { } } - num_produced += max(0, (int)(_children.size() - children_copy.size())); + num_produced += std::max(0, (int)(_children.size() - children_copy.size())); return num_produced; } @@ -1177,7 +1179,7 @@ rebuild_vertex_pools(EggVertexPools &vertex_pools, unsigned int max_vertices, // vertex pools we've already created already have a copy of each one of // the vertices. bool found_pool = false; - EggVertexPool *best_pool = NULL; + EggVertexPool *best_pool = nullptr; int best_new_vertices = 0; Vertices new_vertices; @@ -1198,7 +1200,7 @@ rebuild_vertex_pools(EggVertexPools &vertex_pools, unsigned int max_vertices, EggVertex *vertex = (*vi); EggVertex *new_vertex = vertex_pool->find_matching_vertex(*vertex); new_vertices.push_back(new_vertex); - if (new_vertex == (EggVertex *)NULL) { + if (new_vertex == nullptr) { ++num_new_vertices; } } @@ -1212,7 +1214,7 @@ rebuild_vertex_pools(EggVertexPools &vertex_pools, unsigned int max_vertices, // We would have to add some vertices to this pool, so this vertex // pool qualifies only if the number of vertices we have to add // would still keep it within our limit. - if (best_pool == (EggVertexPool *)NULL || + if (best_pool == nullptr || num_new_vertices < best_new_vertices) { // This is currently our most favorable vertex pool. best_pool = vertex_pool; @@ -1222,7 +1224,7 @@ rebuild_vertex_pools(EggVertexPools &vertex_pools, unsigned int max_vertices, } if (!found_pool) { - if (best_pool == (EggVertexPool *)NULL) { + if (best_pool == nullptr) { // There was no vertex pool that qualified. We will have to create // a new vertex pool. best_pool = new EggVertexPool(""); @@ -1245,7 +1247,7 @@ rebuild_vertex_pools(EggVertexPools &vertex_pools, unsigned int max_vertices, nassertv(new_vertices.size() == vertices.size()); for (vi = new_vertices.begin(); vi != new_vertices.end(); ++vi) { EggVertex *new_vertex = (*vi); - nassertv(new_vertex != (EggVertex *)NULL); + nassertv(new_vertex != nullptr); prim->add_vertex(new_vertex); } @@ -1545,7 +1547,7 @@ r_load_externals(const DSearchPath &searchpath, CoordinateSystem coordsys, if (ext_data.read(filename)) { // The external file was read correctly. Add its contents into the // tree at this point. - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { record->add_dependent_file(filename); } @@ -1577,11 +1579,11 @@ r_load_externals(const DSearchPath &searchpath, CoordinateSystem coordsys, */ void EggGroupNode:: prepare_add_child(EggNode *node) { - nassertv(node != (EggNode *)NULL); + nassertv(node != nullptr); test_ref_count_integrity(); node->test_ref_count_integrity(); // Make sure the node is not already a child of some other group. - nassertv(node->get_parent() == NULL); + nassertv(node->get_parent() == nullptr); nassertv(node->get_depth() == 0); node->_parent = this; @@ -1599,11 +1601,11 @@ prepare_add_child(EggNode *node) { */ void EggGroupNode:: prepare_remove_child(EggNode *node) { - nassertv(node != (EggNode *)NULL); + nassertv(node != nullptr); // Make sure the node is in fact a child of this group. nassertv(node->get_parent() == this); nassertv(node->get_depth() == get_depth() + 1); - node->_parent = NULL; + node->_parent = nullptr; node->update_under(-(get_depth() + 1)); } @@ -1867,7 +1869,7 @@ do_compute_tangent_binormal(const TBNVertexValue &value, EggVertex new_vertex(*vertex); EggVertexUV *uv_obj = new_vertex.modify_uv_obj(value._uv_name); - nassertv(uv_obj != (EggVertexUV *)NULL); + nassertv(uv_obj != nullptr); uv_obj->set_tangent(tangent); uv_obj->set_binormal(binormal); diff --git a/panda/src/egg/eggGroupNode.h b/panda/src/egg/eggGroupNode.h index 85956cd32b..346c2ed817 100644 --- a/panda/src/egg/eggGroupNode.h +++ b/panda/src/egg/eggGroupNode.h @@ -43,7 +43,7 @@ class DSearchPath; * to manipulate the list. The list may also be operated on (read-only) via * iterators and begin()/end(). */ -class EXPCL_PANDAEGG EggGroupNode : public EggNode { +class EXPCL_PANDA_EGG EggGroupNode : public EggNode { // This is a bit of private interface stuff that must be here as a forward // reference. This allows us to define the EggGroupNode as an STL @@ -58,12 +58,12 @@ private: // Here begins the actual public interface to EggGroupNode. PUBLISHED: - explicit EggGroupNode(const string &name = "") : EggNode(name) { } + explicit EggGroupNode(const std::string &name = "") : EggNode(name) { } EggGroupNode(const EggGroupNode ©); EggGroupNode &operator = (const EggGroupNode ©); virtual ~EggGroupNode(); - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; // The EggGroupNode itself appears to be an STL container of pointers to // EggNodes. The set of children is read-only, however, except through the @@ -114,7 +114,7 @@ PUBLISHED: PT(EggNode) remove_child(EggNode *node); void steal_children(EggGroupNode &other); - EggNode *find_child(const string &name) const; + EggNode *find_child(const std::string &name) const; bool has_absolute_pathnames() const; void resolve_filenames(const DSearchPath &searchpath); @@ -219,7 +219,7 @@ private: INLINE bool operator < (const TBNVertexValue &other) const; LVertexd _pos; LNormald _normal; - string _uv_name; + std::string _uv_name; LTexCoordd _uv; bool _facing; }; diff --git a/panda/src/egg/eggGroupNode_ext.cxx b/panda/src/egg/eggGroupNode_ext.cxx index a0ac3fcb8e..9a42bb8cad 100644 --- a/panda/src/egg/eggGroupNode_ext.cxx +++ b/panda/src/egg/eggGroupNode_ext.cxx @@ -29,8 +29,8 @@ get_children() const { // Create the Python list object. EggGroupNode::size_type len = _this->size(); PyObject *lst = PyList_New(len); - if (lst == NULL) { - return NULL; + if (lst == nullptr) { + return nullptr; } // Fill in the list. diff --git a/panda/src/egg/eggGroupUniquifier.cxx b/panda/src/egg/eggGroupUniquifier.cxx index f19b15e10d..b43529a092 100644 --- a/panda/src/egg/eggGroupUniquifier.cxx +++ b/panda/src/egg/eggGroupUniquifier.cxx @@ -18,6 +18,8 @@ #include +using std::string; + TypeHandle EggGroupUniquifier::_type_handle; @@ -95,7 +97,7 @@ filter_name(EggNode *node) { */ string EggGroupUniquifier:: generate_name(EggNode *node, const string &category, int index) { - ostringstream str; + std::ostringstream str; str << node->get_name() << "_group" << index; return str.str(); } diff --git a/panda/src/egg/eggGroupUniquifier.h b/panda/src/egg/eggGroupUniquifier.h index af9e3b8f77..4c8c142d1a 100644 --- a/panda/src/egg/eggGroupUniquifier.h +++ b/panda/src/egg/eggGroupUniquifier.h @@ -23,14 +23,14 @@ * EggGroup nodes. It's not called automatically; you must invoke it yourself * if you want it. */ -class EXPCL_PANDAEGG EggGroupUniquifier : public EggNameUniquifier { +class EXPCL_PANDA_EGG EggGroupUniquifier : public EggNameUniquifier { PUBLISHED: explicit EggGroupUniquifier(bool filter_names = true); - virtual string get_category(EggNode *node); - virtual string filter_name(EggNode *node); - virtual string generate_name(EggNode *node, - const string &category, int index); + virtual std::string get_category(EggNode *node); + virtual std::string filter_name(EggNode *node); + virtual std::string generate_name(EggNode *node, + const std::string &category, int index); private: bool _filter_names; diff --git a/panda/src/egg/eggLine.I b/panda/src/egg/eggLine.I index 39e894e798..6892c34db0 100644 --- a/panda/src/egg/eggLine.I +++ b/panda/src/egg/eggLine.I @@ -15,7 +15,7 @@ * */ INLINE EggLine:: -EggLine(const string &name) : +EggLine(const std::string &name) : EggCompositePrimitive(name), _has_thick(false) { diff --git a/panda/src/egg/eggLine.cxx b/panda/src/egg/eggLine.cxx index fca1efd7f1..6ba445a5c8 100644 --- a/panda/src/egg/eggLine.cxx +++ b/panda/src/egg/eggLine.cxx @@ -37,7 +37,7 @@ make_copy() const { * Writes the point to the indicated output stream in Egg format. */ void EggLine:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { write_header(out, indent_level, ""); if (has_thick()) { diff --git a/panda/src/egg/eggLine.h b/panda/src/egg/eggLine.h index 4e5eef098c..e4c67ff279 100644 --- a/panda/src/egg/eggLine.h +++ b/panda/src/egg/eggLine.h @@ -22,16 +22,16 @@ * A line segment, or a series of connected line segments, defined by a * entry. */ -class EXPCL_PANDAEGG EggLine : public EggCompositePrimitive { +class EXPCL_PANDA_EGG EggLine : public EggCompositePrimitive { PUBLISHED: - INLINE explicit EggLine(const string &name = ""); + INLINE explicit EggLine(const std::string &name = ""); INLINE EggLine(const EggLine ©); INLINE EggLine &operator = (const EggLine ©); virtual ~EggLine(); virtual EggLine *make_copy() const override; - virtual void write(ostream &out, int indent_level) const override; + virtual void write(std::ostream &out, int indent_level) const override; INLINE bool has_thick() const; INLINE double get_thick() const; diff --git a/panda/src/egg/eggMaterial.cxx b/panda/src/egg/eggMaterial.cxx index 8a77c9c0cc..3d543645a1 100644 --- a/panda/src/egg/eggMaterial.cxx +++ b/panda/src/egg/eggMaterial.cxx @@ -22,7 +22,7 @@ TypeHandle EggMaterial::_type_handle; * */ EggMaterial:: -EggMaterial(const string &mref_name) +EggMaterial(const std::string &mref_name) : EggNode(mref_name) { _flags = 0; @@ -54,7 +54,7 @@ EggMaterial(const EggMaterial ©) * format. */ void EggMaterial:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { write_header(out, indent_level, ""); if (has_base()) { diff --git a/panda/src/egg/eggMaterial.h b/panda/src/egg/eggMaterial.h index c1008ae95c..6d9f979848 100644 --- a/panda/src/egg/eggMaterial.h +++ b/panda/src/egg/eggMaterial.h @@ -23,12 +23,12 @@ /** * */ -class EXPCL_PANDAEGG EggMaterial : public EggNode { +class EXPCL_PANDA_EGG EggMaterial : public EggNode { PUBLISHED: - explicit EggMaterial(const string &mref_name); + explicit EggMaterial(const std::string &mref_name); EggMaterial(const EggMaterial ©); - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; enum Equivalence { E_attributes = 0x001, @@ -151,7 +151,7 @@ private: * Returns true if the two referenced EggMaterial pointers are in sorted * order, false otherwise. */ -class EXPCL_PANDAEGG UniqueEggMaterials { +class EXPCL_PANDA_EGG UniqueEggMaterials { public: INLINE UniqueEggMaterials(int eq = ~0); INLINE bool operator ()(const EggMaterial *t1, const EggMaterial *t2) const; diff --git a/panda/src/egg/eggMaterialCollection.cxx b/panda/src/egg/eggMaterialCollection.cxx index b89f3a1900..527bd7a0a6 100644 --- a/panda/src/egg/eggMaterialCollection.cxx +++ b/panda/src/egg/eggMaterialCollection.cxx @@ -221,7 +221,7 @@ collapse_equivalent_materials(int eq, EggMaterialCollection::MaterialReplacement ++oti) { EggMaterial *tex = (*oti); - pair result = collapser.insert(tex); + std::pair result = collapser.insert(tex); if (!result.second) { // This material is non-unique; another one was already there. EggMaterial *first = *(result.first); @@ -383,7 +383,7 @@ create_unique_material(const EggMaterial ©, int eq) { * matches. */ EggMaterial *EggMaterialCollection:: -find_mref(const string &mref_name) const { +find_mref(const std::string &mref_name) const { // This requires a complete linear traversal, not terribly efficient. OrderedMaterials::const_iterator oti; for (oti = _ordered_materials.begin(); @@ -395,5 +395,5 @@ find_mref(const string &mref_name) const { } } - return (EggMaterial *)NULL; + return nullptr; } diff --git a/panda/src/egg/eggMaterialCollection.h b/panda/src/egg/eggMaterialCollection.h index 1041f2f668..9f4d196b62 100644 --- a/panda/src/egg/eggMaterialCollection.h +++ b/panda/src/egg/eggMaterialCollection.h @@ -27,7 +27,7 @@ * materials from an egg file and sort them all together; it can also manage * the creation of unique materials and the assignment of unique MRef names. */ -class EXPCL_PANDAEGG EggMaterialCollection { +class EXPCL_PANDA_EGG EggMaterialCollection { // This is a bit of private interface stuff that must be here as a forward // reference. This allows us to define the EggMaterialCollection as an STL @@ -90,7 +90,7 @@ PUBLISHED: EggMaterial *create_unique_material(const EggMaterial ©, int eq); // Find a material with a particular MRef name. - EggMaterial *find_mref(const string &mref_name) const; + EggMaterial *find_mref(const std::string &mref_name) const; private: Materials _materials; diff --git a/panda/src/egg/eggMesher.cxx b/panda/src/egg/eggMesher.cxx index 98e583b3e0..da2334cfaa 100644 --- a/panda/src/egg/eggMesher.cxx +++ b/panda/src/egg/eggMesher.cxx @@ -30,7 +30,7 @@ */ EggMesher:: EggMesher() { - _vertex_pool = NULL; + _vertex_pool = nullptr; _strip_index = 0; } @@ -70,7 +70,7 @@ mesh(EggGroupNode *group, bool flat_shaded) { if (child->is_of_type(EggPolygon::get_class_type())) { EggPolygon *poly = DCAST(EggPolygon, child); - if (_vertex_pool == (EggVertexPool *)NULL) { + if (_vertex_pool == nullptr) { _vertex_pool = poly->get_pool(); add_polygon(poly, EggMesherStrip::MO_user); @@ -93,7 +93,7 @@ mesh(EggGroupNode *group, bool flat_shaded) { Strips::iterator si; for (si = _done.begin(); si != _done.end(); ++si) { PT(EggPrimitive) egg_prim = get_prim(*si); - if (egg_prim != (EggPrimitive *)NULL) { + if (egg_prim != nullptr) { output_children->add_child(egg_prim); } } @@ -113,7 +113,7 @@ mesh(EggGroupNode *group, bool flat_shaded) { * */ void EggMesher:: -write(ostream &out) const { +write(std::ostream &out) const { /* out << _edges.size() << " edges:\n"; copy(_edges.begin(), _edges.end(), ostream_iterator(out, "\n")); @@ -164,7 +164,7 @@ clear() { _verts.clear(); _edges.clear(); _strip_index = 0; - _vertex_pool = NULL; + _vertex_pool = nullptr; _color_sheets.clear(); } @@ -197,7 +197,7 @@ add_polygon(const EggPolygon *egg_poly, EggMesherStrip::MesherOrigin origin) { this_poly = DCAST(EggPolygon, *ci); } - if (_vertex_pool == NULL) { + if (_vertex_pool == nullptr) { _vertex_pool = this_poly->get_pool(); } else { nassertr(_vertex_pool == this_poly->get_pool(), false); @@ -557,7 +557,7 @@ build_sheets() { int num_rows_b = 0; int first_row_id_b = first_row_id; double avg_length_b; - if (edge_b != NULL) { + if (edge_b != nullptr) { (*best).measure_sheet(edge_b, true, num_prims_b, num_rows_b, first_row_id_b, 0, 0); first_row_id += num_rows_b; @@ -565,7 +565,7 @@ build_sheets() { } // Which sheet is better? - if (edge_b != NULL && avg_length_b >= avg_length_a) { + if (edge_b != nullptr && avg_length_b >= avg_length_a) { // Sheet b. That's easy. (*best).cut_sheet(first_row_id_b, true, _vertex_pool); @@ -704,8 +704,8 @@ make_quads() { // and pair them up right away. The others we'll get to later. This way, // the uncertain matches won't pollute the quad alignment for everyone else. - typedef pair Pair; - typedef pair Matched; + typedef std::pair Pair; + typedef std::pair Matched; typedef pvector SoulMates; SoulMates soulmates; diff --git a/panda/src/egg/eggMesher.h b/panda/src/egg/eggMesher.h index 740b0d38cc..5d1a3e0070 100644 --- a/panda/src/egg/eggMesher.h +++ b/panda/src/egg/eggMesher.h @@ -36,7 +36,7 @@ public: void mesh(EggGroupNode *group, bool flat_shaded); - void write(ostream &out) const; + void write(std::ostream &out) const; bool _consider_fans; bool _retesselate_coplanar; diff --git a/panda/src/egg/eggMesherEdge.I b/panda/src/egg/eggMesherEdge.I index 9d83e936e0..dbd37f0b70 100644 --- a/panda/src/egg/eggMesherEdge.I +++ b/panda/src/egg/eggMesherEdge.I @@ -17,7 +17,7 @@ */ INLINE EggMesherEdge:: EggMesherEdge(int vi_a, int vi_b) : _vi_a(vi_a), _vi_b(vi_b) { - _opposite = NULL; + _opposite = nullptr; } /** @@ -58,7 +58,7 @@ matches(const EggMesherEdge &other) const { */ INLINE EggMesherEdge *EggMesherEdge:: common_ptr() { - return min(this, _opposite); + return std::min(this, _opposite); } /** diff --git a/panda/src/egg/eggMesherEdge.cxx b/panda/src/egg/eggMesherEdge.cxx index a37d6785f7..f270b30de8 100644 --- a/panda/src/egg/eggMesherEdge.cxx +++ b/panda/src/egg/eggMesherEdge.cxx @@ -52,7 +52,7 @@ change_strip(EggMesherStrip *from, EggMesherStrip *to) { * Formats the edge for output in some sensible way. */ void EggMesherEdge:: -output(ostream &out) const { +output(std::ostream &out) const { out << "Edge [" << _vi_a << " to " << _vi_b << "], " << _strips.size() << " strips:"; @@ -61,7 +61,7 @@ output(ostream &out) const { out << " " << (*si)->_index; } - if (_opposite!=NULL) { + if (_opposite!=nullptr) { out << " opposite " << _opposite->_strips.size() << " strips:"; diff --git a/panda/src/egg/eggMesherEdge.h b/panda/src/egg/eggMesherEdge.h index 82975bd7fb..5ef30c1c69 100644 --- a/panda/src/egg/eggMesherEdge.h +++ b/panda/src/egg/eggMesherEdge.h @@ -47,7 +47,7 @@ public: INLINE double compute_length(const EggVertexPool *vertex_pool) const; INLINE LVecBase3d compute_box(const EggVertexPool *vertex_pool) const; - void output(ostream &out) const; + void output(std::ostream &out) const; int _vi_a, _vi_b; @@ -56,8 +56,8 @@ public: EggMesherEdge *_opposite; }; -INLINE ostream & -operator << (ostream &out, const EggMesherEdge &edge) { +INLINE std::ostream & +operator << (std::ostream &out, const EggMesherEdge &edge) { edge.output(out); return out; } diff --git a/panda/src/egg/eggMesherFanMaker.I b/panda/src/egg/eggMesherFanMaker.I index 3bca4a4560..357708c27f 100644 --- a/panda/src/egg/eggMesherFanMaker.I +++ b/panda/src/egg/eggMesherFanMaker.I @@ -66,8 +66,8 @@ is_coplanar_with(const EggMesherFanMaker &other) const { egg_coplanar_threshold); } -INLINE ostream & -operator << (ostream &out, const EggMesherFanMaker &fm) { +INLINE std::ostream & +operator << (std::ostream &out, const EggMesherFanMaker &fm) { fm.output(out); return out; } diff --git a/panda/src/egg/eggMesherFanMaker.cxx b/panda/src/egg/eggMesherFanMaker.cxx index efbfad25a2..09f91e0f0f 100644 --- a/panda/src/egg/eggMesherFanMaker.cxx +++ b/panda/src/egg/eggMesherFanMaker.cxx @@ -24,7 +24,7 @@ EggMesherFanMaker(int vertex, EggMesherStrip *tri, EggMesher *mesher) { _vertex = vertex; const EggMesherEdge *edge = tri->find_opposite_edge(vertex); - if (edge != (const EggMesherEdge *)NULL) { + if (edge != nullptr) { _edges.push_back(edge); } _strips.push_back(tri); @@ -73,8 +73,8 @@ join(EggMesherFanMaker &other) { const EggMesherEdge *my_back = _edges.back(); const EggMesherEdge *other_front = other._edges.front(); - nassertr(my_back != (EggMesherEdge *)NULL && - other_front != (EggMesherEdge *)NULL, false); + nassertr(my_back != nullptr && + other_front != nullptr, false); int my_back_b = my_back->_vi_b; int other_front_a = other_front->_vi_a; @@ -88,8 +88,8 @@ join(EggMesherFanMaker &other) { const EggMesherEdge *my_front = _edges.front(); const EggMesherEdge *other_back = other._edges.back(); - nassertr(my_front != (EggMesherEdge *)NULL && - other_back != (EggMesherEdge *)NULL, false); + nassertr(my_front != nullptr && + other_back != nullptr, false); int my_front_a = my_front->_vi_a; int other_back_b = other_back->_vi_b; @@ -326,7 +326,7 @@ unroll(Strips::iterator strip_begin, Strips::iterator strip_end, * */ void EggMesherFanMaker:: -output(ostream &out) const { +output(std::ostream &out) const { out << _vertex << ":["; if (!_edges.empty()) { Edges::const_iterator ei; diff --git a/panda/src/egg/eggMesherFanMaker.h b/panda/src/egg/eggMesherFanMaker.h index fcfc65b879..f320b2858b 100644 --- a/panda/src/egg/eggMesherFanMaker.h +++ b/panda/src/egg/eggMesherFanMaker.h @@ -57,7 +57,7 @@ public: Edges::iterator edge_begin, Edges::iterator edge_end, EggGroupNode *unrolled_tris); - void output(ostream &out) const; + void output(std::ostream &out) const; int _vertex; Edges _edges; @@ -66,7 +66,7 @@ public: EggMesher *_mesher; }; -INLINE ostream &operator << (ostream &out, const EggMesherFanMaker &fm); +INLINE std::ostream &operator << (std::ostream &out, const EggMesherFanMaker &fm); #include "eggMesherFanMaker.I" diff --git a/panda/src/egg/eggMesherStrip.cxx b/panda/src/egg/eggMesherStrip.cxx index 5059105ceb..27260b96b0 100644 --- a/panda/src/egg/eggMesherStrip.cxx +++ b/panda/src/egg/eggMesherStrip.cxx @@ -248,15 +248,15 @@ measure_sheet(const EggMesherEdge *edge, int new_row, int &num_prims, // the best. EggMesherEdge::Strips &strips = (*ei)->_strips; - EggMesherStrip *mate = NULL; + EggMesherStrip *mate = nullptr; for (si = strips.begin(); si != strips.end(); ++si) { if ((*si)->_row_id < first_row_id) { - if (mate == NULL || pick_sheet_mate(**si, *mate)) { + if (mate == nullptr || pick_sheet_mate(**si, *mate)) { mate = *si; } } } - if (mate!=NULL) { + if (mate!=nullptr) { mate->measure_sheet(*ei, secondary, num_prims, num_rows, first_row_id, this_row_id, this_row_distance + secondary); @@ -281,15 +281,15 @@ measure_sheet(const EggMesherEdge *edge, int new_row, int &num_prims, // Here's the edge. Same drill as above. EggMesherEdge::Strips &strips = (*ei)->_strips; - EggMesherStrip *mate = NULL; + EggMesherStrip *mate = nullptr; for (si = strips.begin(); si != strips.end(); ++si) { if ((*si)->_row_id < first_row_id) { - if (mate == NULL || pick_sheet_mate(**si, *mate)) { + if (mate == nullptr || pick_sheet_mate(**si, *mate)) { mate = *si; } } } - if (mate != NULL) { + if (mate != nullptr) { mate->measure_sheet(*ei, false, num_prims, num_rows, first_row_id, this_row_id, this_row_distance); } @@ -428,15 +428,15 @@ find_ideal_mate(EggMesherStrip *&mate, EggMesherEdge *&common_edge, const EggVertexPool *vertex_pool) { Edges::iterator ei; - mate = NULL; - common_edge = NULL; + mate = nullptr; + common_edge = nullptr; for (ei = _edges.begin(); ei != _edges.end(); ++ei) { EggMesherEdge::Strips &strips = (*ei)->_strips; EggMesherEdge::Strips::iterator si; for (si = strips.begin(); si != strips.end(); ++si) { if (*si != this) { - if (mate==NULL || pick_mate(**si, *mate, **ei, *common_edge, + if (mate==nullptr || pick_mate(**si, *mate, **ei, *common_edge, vertex_pool)) { mate = *si; common_edge = *ei; @@ -445,7 +445,7 @@ find_ideal_mate(EggMesherStrip *&mate, EggMesherEdge *&common_edge, } } - return (mate!=NULL); + return (mate!=nullptr); } @@ -849,7 +849,7 @@ count_neighbors() const { * Writes all the neighbor indexes to the ostream. */ void EggMesherStrip:: -output_neighbors(ostream &out) const { +output_neighbors(std::ostream &out) const { Edges::const_iterator ei; EggMesherEdge::Strips::const_iterator si; @@ -898,7 +898,7 @@ find_opposite_edge(int vi) const { } } - return NULL; + return nullptr; } /** @@ -918,7 +918,7 @@ find_opposite_edge(const EggMesherEdge *edge) const { } } - return NULL; + return nullptr; } /** @@ -938,7 +938,7 @@ find_adjacent_edge(const EggMesherEdge *edge) const { } } - return NULL; + return nullptr; } /** @@ -1350,7 +1350,7 @@ pick_sheet_mate(const EggMesherStrip &a_strip, * Formats the vertex for output in some sensible way. */ void EggMesherStrip:: -output(ostream &out) const { +output(std::ostream &out) const { switch (_status) { case MS_alive: break; diff --git a/panda/src/egg/eggMesherStrip.h b/panda/src/egg/eggMesherStrip.h index d8a40e3558..6064388ce0 100644 --- a/panda/src/egg/eggMesherStrip.h +++ b/panda/src/egg/eggMesherStrip.h @@ -76,7 +76,7 @@ public: EggMesherStrip &back, const EggVertexPool *vertex_pool); int count_neighbors() const; - void output_neighbors(ostream &out) const; + void output_neighbors(std::ostream &out) const; INLINE bool is_coplanar_with(const EggMesherStrip &other, PN_stdfloat threshold) const; INLINE PN_stdfloat coplanarity(const EggMesherStrip &other) const; @@ -115,7 +115,7 @@ public: bool pick_sheet_mate(const EggMesherStrip &a_strip, const EggMesherStrip &b_strip) const; - void output(ostream &out) const; + void output(std::ostream &out) const; typedef plist Prims; typedef plist Edges; @@ -144,8 +144,8 @@ public: bool _flat_shaded; }; -INLINE ostream & -operator << (ostream &out, const EggMesherStrip &strip) { +INLINE std::ostream & +operator << (std::ostream &out, const EggMesherStrip &strip) { strip.output(out); return out; } diff --git a/panda/src/egg/eggMiscFuncs.cxx b/panda/src/egg/eggMiscFuncs.cxx index 2181622df5..11d684a185 100644 --- a/panda/src/egg/eggMiscFuncs.cxx +++ b/panda/src/egg/eggMiscFuncs.cxx @@ -17,6 +17,9 @@ #include +using std::ostream; +using std::string; + /** * Writes the string to the indicated output stream. If the string contains diff --git a/panda/src/egg/eggMiscFuncs.h b/panda/src/egg/eggMiscFuncs.h index c157e7c9c9..6d51d6abc0 100644 --- a/panda/src/egg/eggMiscFuncs.h +++ b/panda/src/egg/eggMiscFuncs.h @@ -27,8 +27,8 @@ * any characters special to egg, writes quotation marks around it. If * always_quote is true, writes quotation marks regardless. */ -ostream & -enquote_string(ostream &out, const string &str, +std::ostream & +enquote_string(std::ostream &out, const std::string &str, int indent_level = 0, bool always_quote = false); @@ -38,13 +38,13 @@ enquote_string(ostream &out, const string &str, * A helper function to write out a 3x3 transform matrix. */ void -write_transform(ostream &out, const LMatrix3d &mat, int indent_level); +write_transform(std::ostream &out, const LMatrix3d &mat, int indent_level); /** * A helper function to write out a 4x4 transform matrix. */ void -write_transform(ostream &out, const LMatrix4d &mat, int indent_level); +write_transform(std::ostream &out, const LMatrix4d &mat, int indent_level); #include "eggMiscFuncs.I" diff --git a/panda/src/egg/eggMorph.I b/panda/src/egg/eggMorph.I index 6b39b2a13e..c49f36306f 100644 --- a/panda/src/egg/eggMorph.I +++ b/panda/src/egg/eggMorph.I @@ -16,7 +16,7 @@ */ template INLINE EggMorph:: -EggMorph(const string &name, const Parameter &offset) +EggMorph(const std::string &name, const Parameter &offset) : Namable(name), _offset(offset) { } @@ -89,7 +89,7 @@ compare_to(const EggMorph &other, double threshold) const { */ template INLINE void EggMorph:: -output(ostream &out, const string &tag, int num_dimensions) const { +output(std::ostream &out, const std::string &tag, int num_dimensions) const { out << tag << " " << get_name() << " {"; for (int i = 0; i < num_dimensions; ++i) { out << " " << MAYBE_ZERO(_offset[i]); diff --git a/panda/src/egg/eggMorph.h b/panda/src/egg/eggMorph.h index f58a5f56b8..29c42cecab 100644 --- a/panda/src/egg/eggMorph.h +++ b/panda/src/egg/eggMorph.h @@ -29,7 +29,7 @@ template class EggMorph : public Namable { public: - INLINE EggMorph(const string &name, const Parameter &offset); + INLINE EggMorph(const std::string &name, const Parameter &offset); INLINE void set_offset(const Parameter &offset); INLINE const Parameter &get_offset() const; @@ -39,7 +39,7 @@ public: INLINE int compare_to(const EggMorph &other, double threshold) const; - INLINE void output(ostream &out, const string &tag, + INLINE void output(std::ostream &out, const std::string &tag, int num_dimensions) const; private: @@ -49,8 +49,8 @@ private: // I'd love to export these, but it produces a strange linker issue with Mac // OS X's version of GCC. We'll do it only on Windows, then. #ifdef _MSC_VER -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEGG, EXPTP_PANDAEGG, EggMorph); -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEGG, EXPTP_PANDAEGG, EggMorph); +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EGG, EXPTP_PANDA_EGG, EggMorph); +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EGG, EXPTP_PANDA_EGG, EggMorph); #endif typedef EggMorph EggMorphVertex; diff --git a/panda/src/egg/eggMorphList.I b/panda/src/egg/eggMorphList.I index 5b665247da..0a2f337550 100644 --- a/panda/src/egg/eggMorphList.I +++ b/panda/src/egg/eggMorphList.I @@ -97,7 +97,7 @@ compare_to(const EggMorphList &other, double threshold) const { * */ template -INLINE TYPENAME EggMorphList::iterator EggMorphList:: +INLINE typename EggMorphList::iterator EggMorphList:: begin() { return _morphs.begin(); } @@ -106,7 +106,7 @@ begin() { * */ template -INLINE TYPENAME EggMorphList::const_iterator EggMorphList:: +INLINE typename EggMorphList::const_iterator EggMorphList:: begin() const { return _morphs.begin(); } @@ -115,7 +115,7 @@ begin() const { * */ template -INLINE TYPENAME EggMorphList::iterator EggMorphList:: +INLINE typename EggMorphList::iterator EggMorphList:: end() { return _morphs.end(); } @@ -124,7 +124,7 @@ end() { * */ template -INLINE TYPENAME EggMorphList::const_iterator EggMorphList:: +INLINE typename EggMorphList::const_iterator EggMorphList:: end() const { return _morphs.end(); } @@ -133,7 +133,7 @@ end() const { * */ template -INLINE TYPENAME EggMorphList::size_type EggMorphList:: +INLINE typename EggMorphList::size_type EggMorphList:: size() const { return _morphs.size(); } @@ -155,10 +155,10 @@ empty() const { * to *be* a set, but we cannot export STL sets from a Windows DLL. */ template -pair::iterator, bool> EggMorphList:: +std::pair::iterator, bool> EggMorphList:: insert(const MorphType &value) { - pair result; - TYPENAME Morphs::iterator mi; + std::pair result; + typename Morphs::iterator mi; for (mi = _morphs.begin(); mi != _morphs.end(); ++mi) { if ((*mi) == value) { // This value is already present. @@ -189,7 +189,7 @@ clear() { */ template void EggMorphList:: -write(ostream &out, int indent_level, const string &tag, +write(std::ostream &out, int indent_level, const std::string &tag, int num_dimensions) const { const_iterator i; diff --git a/panda/src/egg/eggMorphList.cxx b/panda/src/egg/eggMorphList.cxx index eb5a12a9b1..01172b9f17 100644 --- a/panda/src/egg/eggMorphList.cxx +++ b/panda/src/egg/eggMorphList.cxx @@ -15,20 +15,20 @@ // Continue all of the vector import definitions. -#define EXPCL EXPCL_PANDAEGG -#define EXPTP EXPTP_PANDAEGG +#define EXPCL EXPCL_PANDA_EGG +#define EXPTP EXPTP_PANDA_EGG #define TYPE LVector3d #define NAME vector_LVector3d #include "vector_src.cxx" -#define EXPCL EXPCL_PANDAEGG -#define EXPTP EXPTP_PANDAEGG +#define EXPCL EXPCL_PANDA_EGG +#define EXPTP EXPTP_PANDA_EGG #define TYPE LVector2d #define NAME vector_LVector2d #include "vector_src.cxx" -#define EXPCL EXPCL_PANDAEGG -#define EXPTP EXPTP_PANDAEGG +#define EXPCL EXPCL_PANDA_EGG +#define EXPTP EXPTP_PANDA_EGG #define TYPE LVector4 #define NAME vector_LVector4 #include "vector_src.cxx" diff --git a/panda/src/egg/eggMorphList.h b/panda/src/egg/eggMorphList.h index c6e86388ba..0c890e54f2 100644 --- a/panda/src/egg/eggMorphList.h +++ b/panda/src/egg/eggMorphList.h @@ -31,9 +31,9 @@ private: typedef epvector Morphs; public: - typedef TYPENAME Morphs::iterator iterator; - typedef TYPENAME Morphs::const_iterator const_iterator; - typedef TYPENAME Morphs::size_type size_type; + typedef typename Morphs::iterator iterator; + typedef typename Morphs::const_iterator const_iterator; + typedef typename Morphs::size_type size_type; INLINE EggMorphList(); INLINE EggMorphList(const EggMorphList ©); @@ -53,11 +53,11 @@ public: INLINE size_type size() const; INLINE bool empty() const; - pair insert(const MorphType &value); + std::pair insert(const MorphType &value); INLINE void clear(); - void write(ostream &out, int indent_level, - const string &tag, int num_dimensions) const; + void write(std::ostream &out, int indent_level, + const std::string &tag, int num_dimensions) const; private: Morphs _morphs; diff --git a/panda/src/egg/eggNameUniquifier.cxx b/panda/src/egg/eggNameUniquifier.cxx index 0e50320d45..239a2b692b 100644 --- a/panda/src/egg/eggNameUniquifier.cxx +++ b/panda/src/egg/eggNameUniquifier.cxx @@ -19,6 +19,8 @@ #include "pnotify.h" +using std::string; + TypeHandle EggNameUniquifier::_type_handle; @@ -89,7 +91,7 @@ uniquify(EggNode *node) { EggGroupNode::iterator ci; for (ci = group->begin(); ci != group->end(); ++ci) { EggNode *child = (*ci); - nassertv(child != (EggNode *)NULL); + nassertv(child != nullptr); uniquify(child); } } @@ -104,14 +106,14 @@ get_node(const string &category, const string &name) const { Categories::const_iterator ci; ci = _categories.find(category); if (ci == _categories.end()) { - return (EggNode *)NULL; + return nullptr; } const UsedNames &names = (*ci).second; UsedNames::const_iterator ni; ni = names.find(name); if (ni == names.end()) { - return (EggNode *)NULL; + return nullptr; } return (*ni).second; @@ -173,7 +175,7 @@ string EggNameUniquifier:: generate_name(EggNode *node, const string &category, int index) { string name = filter_name(node); - ostringstream str; + std::ostringstream str; if (name.empty()) { str << category << index; } else { diff --git a/panda/src/egg/eggNameUniquifier.h b/panda/src/egg/eggNameUniquifier.h index d28457a97d..4b1f0f48d0 100644 --- a/panda/src/egg/eggNameUniquifier.h +++ b/panda/src/egg/eggNameUniquifier.h @@ -56,7 +56,7 @@ class EggNode; * hierarchy. It is an abstract class; to use it you must subclass off of it. * See the comment above. */ -class EXPCL_PANDAEGG EggNameUniquifier : public EggObject { +class EXPCL_PANDA_EGG EggNameUniquifier : public EggObject { PUBLISHED: EggNameUniquifier(); ~EggNameUniquifier(); @@ -65,19 +65,19 @@ PUBLISHED: void uniquify(EggNode *node); - EggNode *get_node(const string &category, const string &name) const; - bool has_name(const string &category, const string &name) const; - bool add_name(const string &category, const string &name, - EggNode *node = NULL); + EggNode *get_node(const std::string &category, const std::string &name) const; + bool has_name(const std::string &category, const std::string &name) const; + bool add_name(const std::string &category, const std::string &name, + EggNode *node = nullptr); - virtual string get_category(EggNode *node)=0; - virtual string filter_name(EggNode *node); - virtual string generate_name(EggNode *node, - const string &category, int index); + virtual std::string get_category(EggNode *node)=0; + virtual std::string filter_name(EggNode *node); + virtual std::string generate_name(EggNode *node, + const std::string &category, int index); private: - typedef pmap UsedNames; - typedef pmap Categories; + typedef pmap UsedNames; + typedef pmap Categories; Categories _categories; int _index; diff --git a/panda/src/egg/eggNamedObject.I b/panda/src/egg/eggNamedObject.I index 6227e51696..77bb78194f 100644 --- a/panda/src/egg/eggNamedObject.I +++ b/panda/src/egg/eggNamedObject.I @@ -15,7 +15,7 @@ * */ INLINE EggNamedObject:: -EggNamedObject(const string &name) : Namable(name) { +EggNamedObject(const std::string &name) : Namable(name) { } @@ -37,7 +37,7 @@ operator = (const EggNamedObject ©) { return *this; } -INLINE ostream &operator << (ostream &out, const EggNamedObject &n) { +INLINE std::ostream &operator << (std::ostream &out, const EggNamedObject &n) { n.output(out); return out; } diff --git a/panda/src/egg/eggNamedObject.cxx b/panda/src/egg/eggNamedObject.cxx index 663cfc3ed6..d397e26f91 100644 --- a/panda/src/egg/eggNamedObject.cxx +++ b/panda/src/egg/eggNamedObject.cxx @@ -22,7 +22,7 @@ TypeHandle EggNamedObject::_type_handle; * */ void EggNamedObject:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type(); if (has_name()) { out << " " << get_name(); @@ -36,7 +36,7 @@ output(ostream &out) const { * "". */ void EggNamedObject:: -write_header(ostream &out, int indent_level, const char *egg_keyword) const { +write_header(std::ostream &out, int indent_level, const char *egg_keyword) const { indent(out, indent_level) << egg_keyword << " "; if (has_name()) { diff --git a/panda/src/egg/eggNamedObject.h b/panda/src/egg/eggNamedObject.h index 140c989237..880dd0ca2d 100644 --- a/panda/src/egg/eggNamedObject.h +++ b/panda/src/egg/eggNamedObject.h @@ -23,16 +23,16 @@ /** * This is a fairly low-level base class--any egg object that has a name. */ -class EXPCL_PANDAEGG EggNamedObject : public EggObject, public Namable { +class EXPCL_PANDA_EGG EggNamedObject : public EggObject, public Namable { PUBLISHED: - INLINE explicit EggNamedObject(const string &name = ""); + INLINE explicit EggNamedObject(const std::string &name = ""); INLINE EggNamedObject(const EggNamedObject ©); INLINE EggNamedObject &operator = (const EggNamedObject ©); - void output(ostream &out) const; + void output(std::ostream &out) const; public: - void write_header(ostream &out, int indent_level, + void write_header(std::ostream &out, int indent_level, const char *egg_keyword) const; @@ -55,7 +55,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const EggNamedObject &n); +INLINE std::ostream &operator << (std::ostream &out, const EggNamedObject &n); #include "eggNamedObject.I" diff --git a/panda/src/egg/eggNode.I b/panda/src/egg/eggNode.I index 08f2f8989b..4022139ea5 100644 --- a/panda/src/egg/eggNode.I +++ b/panda/src/egg/eggNode.I @@ -15,8 +15,8 @@ * */ INLINE EggNode:: -EggNode(const string &name) : EggNamedObject(name) { - _parent = NULL; +EggNode(const std::string &name) : EggNamedObject(name) { + _parent = nullptr; _depth = 0; _under_flags = 0; } @@ -26,7 +26,7 @@ EggNode(const string &name) : EggNamedObject(name) { */ INLINE EggNode:: EggNode(const EggNode ©) : EggNamedObject(copy) { - _parent = NULL; + _parent = nullptr; _depth = 0; _under_flags = 0; } @@ -106,7 +106,7 @@ is_local_coord() const { */ INLINE const LMatrix4d &EggNode:: get_vertex_frame() const { - if (_vertex_frame == (LMatrix4d *)NULL) { + if (_vertex_frame == nullptr) { return LMatrix4d::ident_mat(); } else { return *_vertex_frame; @@ -120,7 +120,7 @@ get_vertex_frame() const { */ INLINE const LMatrix4d &EggNode:: get_node_frame() const { - if (_node_frame == (LMatrix4d *)NULL) { + if (_node_frame == nullptr) { return LMatrix4d::ident_mat(); } else { return *_node_frame; @@ -133,7 +133,7 @@ get_node_frame() const { */ INLINE const LMatrix4d &EggNode:: get_vertex_frame_inv() const { - if (_vertex_frame_inv == (LMatrix4d *)NULL) { + if (_vertex_frame_inv == nullptr) { return LMatrix4d::ident_mat(); } else { return *_vertex_frame_inv; @@ -147,7 +147,7 @@ get_vertex_frame_inv() const { */ INLINE const LMatrix4d &EggNode:: get_node_frame_inv() const { - if (_node_frame_inv == (LMatrix4d *)NULL) { + if (_node_frame_inv == nullptr) { return LMatrix4d::ident_mat(); } else { return *_node_frame_inv; @@ -164,7 +164,7 @@ get_node_frame_inv() const { */ INLINE const LMatrix4d &EggNode:: get_vertex_to_node() const { - if (_vertex_to_node == (LMatrix4d *)NULL) { + if (_vertex_to_node == nullptr) { return LMatrix4d::ident_mat(); } else { return *_vertex_to_node; @@ -181,7 +181,7 @@ get_vertex_to_node() const { */ INLINE const LMatrix4d &EggNode:: get_node_to_vertex() const { - if (_node_to_vertex == (LMatrix4d *)NULL) { + if (_node_to_vertex == nullptr) { return LMatrix4d::ident_mat(); } else { return *_node_to_vertex; diff --git a/panda/src/egg/eggNode.cxx b/panda/src/egg/eggNode.cxx index 016ae01994..efca0825c7 100644 --- a/panda/src/egg/eggNode.cxx +++ b/panda/src/egg/eggNode.cxx @@ -34,9 +34,9 @@ int EggNode:: rename_node(vector_string strip_prefix) { int num_renamed = 0; for (unsigned int ni = 0; ni < strip_prefix.size(); ++ni) { - string axe_name = strip_prefix[ni]; + std::string axe_name = strip_prefix[ni]; if (this->get_name().substr(0, axe_name.size()) == axe_name) { - string new_name = this->get_name().substr(axe_name.size()); + std::string new_name = this->get_name().substr(axe_name.size()); // cout << "renaming " << this->get_name() << "->" << new_name << endl; this->set_name(new_name); num_renamed += 1; @@ -83,9 +83,9 @@ is_anim_matrix() const { */ EggRenderMode *EggNode:: determine_alpha_mode() { - if (_parent == (EggGroupNode *)NULL) { + if (_parent == nullptr) { // Too bad; we're done. - return (EggRenderMode *)NULL; + return nullptr; } return _parent->determine_alpha_mode(); } @@ -98,9 +98,9 @@ determine_alpha_mode() { */ EggRenderMode *EggNode:: determine_depth_write_mode() { - if (_parent == (EggGroupNode *)NULL) { + if (_parent == nullptr) { // Too bad; we're done. - return (EggRenderMode *)NULL; + return nullptr; } return _parent->determine_depth_write_mode(); } @@ -113,9 +113,9 @@ determine_depth_write_mode() { */ EggRenderMode *EggNode:: determine_depth_test_mode() { - if (_parent == (EggGroupNode *)NULL) { + if (_parent == nullptr) { // Too bad; we're done. - return (EggRenderMode *)NULL; + return nullptr; } return _parent->determine_depth_test_mode(); } @@ -128,9 +128,9 @@ determine_depth_test_mode() { */ EggRenderMode *EggNode:: determine_visibility_mode() { - if (_parent == (EggGroupNode *)NULL) { + if (_parent == nullptr) { // Too bad; we're done. - return (EggRenderMode *)NULL; + return nullptr; } return _parent->determine_visibility_mode(); } @@ -143,9 +143,9 @@ determine_visibility_mode() { */ EggRenderMode *EggNode:: determine_depth_offset() { - if (_parent == (EggGroupNode *)NULL) { + if (_parent == nullptr) { // Too bad; we're done. - return (EggRenderMode *)NULL; + return nullptr; } return _parent->determine_depth_offset(); } @@ -158,9 +158,9 @@ determine_depth_offset() { */ EggRenderMode *EggNode:: determine_draw_order() { - if (_parent == (EggGroupNode *)NULL) { + if (_parent == nullptr) { // Too bad; we're done. - return (EggRenderMode *)NULL; + return nullptr; } return _parent->determine_draw_order(); } @@ -172,9 +172,9 @@ determine_draw_order() { */ EggRenderMode *EggNode:: determine_bin() { - if (_parent == (EggGroupNode *)NULL) { + if (_parent == nullptr) { // Too bad; we're done. - return (EggRenderMode *)NULL; + return nullptr; } return _parent->determine_bin(); } @@ -189,7 +189,7 @@ determine_bin() { */ bool EggNode:: determine_indexed() { - if (_parent == (EggGroupNode *)NULL) { + if (_parent == nullptr) { // Too bad; we're done. return false; } @@ -206,7 +206,7 @@ determine_indexed() { */ bool EggNode:: determine_decal() { - if (_parent == (EggGroupNode *)NULL) { + if (_parent == nullptr) { // Too bad; we're done. return false; } @@ -221,13 +221,13 @@ determine_decal() { * error or if the object does not support this functionality. */ bool EggNode:: -parse_egg(const string &egg_syntax) { +parse_egg(const std::string &egg_syntax) { EggGroupNode *group = get_parent(); if (is_of_type(EggGroupNode::get_class_type())) { DCAST_INTO_R(group, this, false); } - istringstream in(egg_syntax); + std::istringstream in(egg_syntax); LightMutexHolder holder(egg_lock); @@ -252,7 +252,7 @@ parse_egg(const string &egg_syntax) { */ void EggNode:: test_under_integrity() const { - if (_parent == NULL) { + if (_parent == nullptr) { // If we have no parent, everything should be zero. nassertv(_depth == 0); nassertv(_under_flags == 0); @@ -303,15 +303,15 @@ egg_start_parse_body() { void EggNode:: update_under(int depth_offset) { int depth; - if (_parent == NULL) { + if (_parent == nullptr) { depth = 0; _under_flags = 0; - _vertex_frame = NULL; - _node_frame = NULL; - _vertex_frame_inv = NULL; - _node_frame_inv = NULL; - _vertex_to_node = NULL; - _node_to_vertex = NULL; + _vertex_frame = nullptr; + _node_frame = nullptr; + _vertex_frame_inv = nullptr; + _node_frame_inv = nullptr; + _vertex_to_node = nullptr; + _node_to_vertex = nullptr; } else { _parent->test_ref_count_integrity(); depth = _parent->_depth + 1; diff --git a/panda/src/egg/eggNode.h b/panda/src/egg/eggNode.h index f4a5df934f..c2d811859e 100644 --- a/panda/src/egg/eggNode.h +++ b/panda/src/egg/eggNode.h @@ -32,9 +32,9 @@ class EggTextureCollection; * This includes groups, joints, polygons, vertex pools, etc., but does not * include things like vertices. */ -class EXPCL_PANDAEGG EggNode : public EggNamedObject { +class EXPCL_PANDA_EGG EggNode : public EggNamedObject { PUBLISHED: - INLINE explicit EggNode(const string &name = ""); + INLINE explicit EggNode(const std::string &name = ""); INLINE EggNode(const EggNode ©); INLINE EggNode &operator = (const EggNode ©); @@ -78,8 +78,8 @@ PUBLISHED: virtual bool determine_indexed(); virtual bool determine_decal(); - virtual void write(ostream &out, int indent_level) const=0; - bool parse_egg(const string &egg_syntax); + virtual void write(std::ostream &out, int indent_level) const=0; + bool parse_egg(const std::string &egg_syntax); #ifdef _DEBUG void test_under_integrity() const; diff --git a/panda/src/egg/eggNurbsCurve.I b/panda/src/egg/eggNurbsCurve.I index f426541d55..60f16cc9ca 100644 --- a/panda/src/egg/eggNurbsCurve.I +++ b/panda/src/egg/eggNurbsCurve.I @@ -15,7 +15,7 @@ * */ INLINE EggNurbsCurve:: -EggNurbsCurve(const string &name) : EggCurve(name) { +EggNurbsCurve(const std::string &name) : EggCurve(name) { _order = 0; } diff --git a/panda/src/egg/eggNurbsCurve.cxx b/panda/src/egg/eggNurbsCurve.cxx index 79b1d5011b..f0f18a41b5 100644 --- a/panda/src/egg/eggNurbsCurve.cxx +++ b/panda/src/egg/eggNurbsCurve.cxx @@ -118,7 +118,7 @@ is_closed() const { * Writes the nurbsCurve to the indicated output stream in Egg format. */ void EggNurbsCurve:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { write_header(out, indent_level, ""); if (get_curve_type() != CT_none) { diff --git a/panda/src/egg/eggNurbsCurve.h b/panda/src/egg/eggNurbsCurve.h index b6b5bc4b55..33eeaaae26 100644 --- a/panda/src/egg/eggNurbsCurve.h +++ b/panda/src/egg/eggNurbsCurve.h @@ -23,9 +23,9 @@ /** * A parametric NURBS curve. */ -class EXPCL_PANDAEGG EggNurbsCurve : public EggCurve { +class EXPCL_PANDA_EGG EggNurbsCurve : public EggCurve { PUBLISHED: - INLINE explicit EggNurbsCurve(const string &name = ""); + INLINE explicit EggNurbsCurve(const std::string &name = ""); INLINE EggNurbsCurve(const EggNurbsCurve ©); INLINE EggNurbsCurve &operator = (const EggNurbsCurve ©); @@ -50,7 +50,7 @@ PUBLISHED: INLINE double get_knot(int k) const; MAKE_SEQ(get_knots, get_num_knots, get_knot); - virtual void write(ostream &out, int indent_level) const override; + virtual void write(std::ostream &out, int indent_level) const override; MAKE_PROPERTY(order, get_order, set_order); MAKE_PROPERTY(degree, get_degree); diff --git a/panda/src/egg/eggNurbsSurface.I b/panda/src/egg/eggNurbsSurface.I index 1a23a6074a..cced43e69d 100644 --- a/panda/src/egg/eggNurbsSurface.I +++ b/panda/src/egg/eggNurbsSurface.I @@ -15,7 +15,7 @@ * */ INLINE EggNurbsSurface:: -EggNurbsSurface(const string &name) : EggSurface(name) { +EggNurbsSurface(const std::string &name) : EggSurface(name) { _u_order = 0; _v_order = 0; } diff --git a/panda/src/egg/eggNurbsSurface.cxx b/panda/src/egg/eggNurbsSurface.cxx index c89ebfe157..8dc19be6fb 100644 --- a/panda/src/egg/eggNurbsSurface.cxx +++ b/panda/src/egg/eggNurbsSurface.cxx @@ -168,7 +168,7 @@ is_closed_v() const { * Writes the nurbsSurface to the indicated output stream in Egg format. */ void EggNurbsSurface:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { write_header(out, indent_level, ""); Trims::const_iterator ti; diff --git a/panda/src/egg/eggNurbsSurface.h b/panda/src/egg/eggNurbsSurface.h index ffadc3cab7..329c50920c 100644 --- a/panda/src/egg/eggNurbsSurface.h +++ b/panda/src/egg/eggNurbsSurface.h @@ -24,7 +24,7 @@ /** * A parametric NURBS surface. */ -class EXPCL_PANDAEGG EggNurbsSurface : public EggSurface { +class EXPCL_PANDA_EGG EggNurbsSurface : public EggSurface { PUBLISHED: typedef plist< PT(EggNurbsCurve) > Curves; typedef Curves Loop; @@ -32,7 +32,7 @@ PUBLISHED: typedef Loops Trim; typedef plist Trims; - INLINE explicit EggNurbsSurface(const string &name = ""); + INLINE explicit EggNurbsSurface(const std::string &name = ""); INLINE EggNurbsSurface(const EggNurbsSurface ©); INLINE EggNurbsSurface &operator = (const EggNurbsSurface ©); @@ -75,7 +75,7 @@ PUBLISHED: MAKE_SEQ(get_v_knots, get_num_v_knots, get_v_knot); INLINE EggVertex *get_cv(int ui, int vi) const; - virtual void write(ostream &out, int indent_level) const override; + virtual void write(std::ostream &out, int indent_level) const override; public: Curves _curves_on_surface; diff --git a/panda/src/egg/eggObject.cxx b/panda/src/egg/eggObject.cxx index b75d2ea64f..0d642ee356 100644 --- a/panda/src/egg/eggObject.cxx +++ b/panda/src/egg/eggObject.cxx @@ -96,7 +96,7 @@ get_user_data(TypeHandle type) const { if (ui != _user_data.end()) { return (*ui).second; } - return NULL; + return nullptr; } /** @@ -149,5 +149,5 @@ clear_user_data(TypeHandle type) { */ EggTransform *EggObject:: as_transform() { - return NULL; + return nullptr; } diff --git a/panda/src/egg/eggObject.h b/panda/src/egg/eggObject.h index f293b19503..71c68e51db 100644 --- a/panda/src/egg/eggObject.h +++ b/panda/src/egg/eggObject.h @@ -26,7 +26,7 @@ class EggTransform; * The highest-level base class in the egg directory. (Almost) all things egg * inherit from this. */ -class EXPCL_PANDAEGG EggObject : public TypedReferenceCount { +class EXPCL_PANDA_EGG EggObject : public TypedReferenceCount { PUBLISHED: EggObject(); EggObject(const EggObject ©); diff --git a/panda/src/egg/eggParameters.cxx b/panda/src/egg/eggParameters.cxx index 14b63ba8ea..b9fc709fcd 100644 --- a/panda/src/egg/eggParameters.cxx +++ b/panda/src/egg/eggParameters.cxx @@ -17,26 +17,3 @@ static EggParameters default_egg_parameters; EggParameters *egg_parameters = &default_egg_parameters; - - -/** - * Initializes all the parameters with default values. - */ -EggParameters:: -EggParameters() { - _pos_threshold = 0.0001; - _normal_threshold = 0.0001; - _uv_threshold = 0.0001; - _color_threshold = 1.0/256.0; - - _table_threshold = 0.0001; -} - - -/** - * - */ -EggParameters:: -EggParameters(const EggParameters &other) { - memcpy(this, &other, sizeof(EggParameters)); -} diff --git a/panda/src/egg/eggParameters.h b/panda/src/egg/eggParameters.h index 36bd1e48f6..600de3c17a 100644 --- a/panda/src/egg/eggParameters.h +++ b/panda/src/egg/eggParameters.h @@ -29,32 +29,31 @@ * process it, and write the egg file out again before resetting the * parameters again. */ -class EXPCL_PANDAEGG EggParameters { +class EXPCL_PANDA_EGG EggParameters { public: - EggParameters(); - EggParameters(const EggParameters ©); + constexpr EggParameters() = default; // The per-component difference below which two vertices are deemed to be at // the same position. - double _pos_threshold; + double _pos_threshold = 0.0001; // The per-component difference below which two vertices are deemed to have // the same normal. - double _normal_threshold; + double _normal_threshold = 0.0001; // The per-component difference below which two vertices are deemed to have // the same texture coordinates. - double _uv_threshold; + double _uv_threshold = 0.0001; // The per-component difference below which two vertices are deemed to have // the same color. - PN_stdfloat _color_threshold; + PN_stdfloat _color_threshold = 1.0/256.0; // The per-component difference below which two anim table values are deemed // to be equivalent. - double _table_threshold; + double _table_threshold = 0.0001; }; -extern EXPCL_PANDAEGG EggParameters *egg_parameters; +extern EXPCL_PANDA_EGG EggParameters *egg_parameters; #endif diff --git a/panda/src/egg/eggPatch.I b/panda/src/egg/eggPatch.I index b75db18d2d..7356ec98ef 100644 --- a/panda/src/egg/eggPatch.I +++ b/panda/src/egg/eggPatch.I @@ -15,7 +15,7 @@ * */ INLINE EggPatch:: -EggPatch(const string &name) : EggPrimitive(name) { +EggPatch(const std::string &name) : EggPrimitive(name) { } /** diff --git a/panda/src/egg/eggPatch.cxx b/panda/src/egg/eggPatch.cxx index 0bed947622..f3bbd30444 100644 --- a/panda/src/egg/eggPatch.cxx +++ b/panda/src/egg/eggPatch.cxx @@ -33,7 +33,7 @@ make_copy() const { * Writes the patch to the indicated output stream in Egg format. */ void EggPatch:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { write_header(out, indent_level, ""); write_body(out, indent_level+2); indent(out, indent_level) << "}\n"; diff --git a/panda/src/egg/eggPatch.h b/panda/src/egg/eggPatch.h index 9e93d0ec80..72530df4cb 100644 --- a/panda/src/egg/eggPatch.h +++ b/panda/src/egg/eggPatch.h @@ -22,15 +22,15 @@ * A single "patch", a special primitive to be rendered only with a * tessellation shader. */ -class EXPCL_PANDAEGG EggPatch : public EggPrimitive { +class EXPCL_PANDA_EGG EggPatch : public EggPrimitive { PUBLISHED: - INLINE explicit EggPatch(const string &name = ""); + INLINE explicit EggPatch(const std::string &name = ""); INLINE EggPatch(const EggPatch ©); INLINE EggPatch &operator = (const EggPatch ©); virtual EggPatch *make_copy() const override; - virtual void write(ostream &out, int indent_level) const override; + virtual void write(std::ostream &out, int indent_level) const override; public: static TypeHandle get_class_type() { diff --git a/panda/src/egg/eggPoint.I b/panda/src/egg/eggPoint.I index 6fa3e252ef..722e6b7cc5 100644 --- a/panda/src/egg/eggPoint.I +++ b/panda/src/egg/eggPoint.I @@ -15,7 +15,7 @@ * */ INLINE EggPoint:: -EggPoint(const string &name) : +EggPoint(const std::string &name) : EggPrimitive(name), _flags(0), _thick(1.0) diff --git a/panda/src/egg/eggPoint.cxx b/panda/src/egg/eggPoint.cxx index a344ee59cd..1545b6649d 100644 --- a/panda/src/egg/eggPoint.cxx +++ b/panda/src/egg/eggPoint.cxx @@ -41,7 +41,7 @@ cleanup() { * Writes the point to the indicated output stream in Egg format. */ void EggPoint:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { write_header(out, indent_level, ""); if (has_thick()) { diff --git a/panda/src/egg/eggPoint.h b/panda/src/egg/eggPoint.h index 96e8b63fe6..5c113280c5 100644 --- a/panda/src/egg/eggPoint.h +++ b/panda/src/egg/eggPoint.h @@ -22,9 +22,9 @@ * A single point, or a collection of points as defined by a single * entry. */ -class EXPCL_PANDAEGG EggPoint : public EggPrimitive { +class EXPCL_PANDA_EGG EggPoint : public EggPrimitive { PUBLISHED: - INLINE explicit EggPoint(const string &name = ""); + INLINE explicit EggPoint(const std::string &name = ""); INLINE EggPoint(const EggPoint ©); INLINE EggPoint &operator = (const EggPoint ©); @@ -42,7 +42,7 @@ PUBLISHED: virtual bool cleanup() override; - virtual void write(ostream &out, int indent_level) const override; + virtual void write(std::ostream &out, int indent_level) const override; private: enum Flags { diff --git a/panda/src/egg/eggPolygon.I b/panda/src/egg/eggPolygon.I index 69b6d4b7fe..08811e3f7f 100644 --- a/panda/src/egg/eggPolygon.I +++ b/panda/src/egg/eggPolygon.I @@ -15,7 +15,7 @@ * */ INLINE EggPolygon:: -EggPolygon(const string &name) : EggPrimitive(name) { +EggPolygon(const std::string &name) : EggPrimitive(name) { } /** diff --git a/panda/src/egg/eggPolygon.cxx b/panda/src/egg/eggPolygon.cxx index 2d6a3378c7..5863d988e5 100644 --- a/panda/src/egg/eggPolygon.cxx +++ b/panda/src/egg/eggPolygon.cxx @@ -146,7 +146,7 @@ is_planar() const { PT(EggPolygon) EggPolygon:: triangulate_in_place(bool convex_also) { EggGroupNode *parent = get_parent(); - nassertr(parent != (EggGroupNode *)NULL, this); + nassertr(parent != nullptr, this); PT(EggPolygon) save_me = this; parent->remove_child(this); @@ -159,7 +159,7 @@ triangulate_in_place(bool convex_also) { * Writes the polygon to the indicated output stream in Egg format. */ void EggPolygon:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { write_header(out, indent_level, ""); write_body(out, indent_level+2); indent(out, indent_level) << "}\n"; diff --git a/panda/src/egg/eggPolygon.h b/panda/src/egg/eggPolygon.h index e5be0e25f0..ec3c236644 100644 --- a/panda/src/egg/eggPolygon.h +++ b/panda/src/egg/eggPolygon.h @@ -21,9 +21,9 @@ /** * A single polygon. */ -class EXPCL_PANDAEGG EggPolygon : public EggPrimitive { +class EXPCL_PANDA_EGG EggPolygon : public EggPrimitive { PUBLISHED: - INLINE explicit EggPolygon(const string &name = ""); + INLINE explicit EggPolygon(const std::string &name = ""); INLINE EggPolygon(const EggPolygon ©); INLINE EggPolygon &operator = (const EggPolygon ©); @@ -39,7 +39,7 @@ PUBLISHED: INLINE bool triangulate_into(EggGroupNode *container, bool convex_also) const; PT(EggPolygon) triangulate_in_place(bool convex_also); - virtual void write(ostream &out, int indent_level) const override; + virtual void write(std::ostream &out, int indent_level) const override; private: bool decomp_concave(EggGroupNode *container, int asum, int x, int y) const; diff --git a/panda/src/egg/eggPolysetMaker.cxx b/panda/src/egg/eggPolysetMaker.cxx index ddd2200df6..83d0de6d89 100644 --- a/panda/src/egg/eggPolysetMaker.cxx +++ b/panda/src/egg/eggPolysetMaker.cxx @@ -66,7 +66,7 @@ sorts_less(int bin_number, const EggNode *a, const EggNode *b) { } } if ((_properties & (P_texture)) != 0) { - int num_textures = min(pa->get_num_textures(), pb->get_num_textures()); + int num_textures = std::min(pa->get_num_textures(), pb->get_num_textures()); for (int i = 0; i < num_textures; i++) { EggTexture *a_texture = pa->get_texture(i); EggTexture *b_texture = pb->get_texture(i); diff --git a/panda/src/egg/eggPolysetMaker.h b/panda/src/egg/eggPolysetMaker.h index 5fa5eebc94..a104a41477 100644 --- a/panda/src/egg/eggPolysetMaker.h +++ b/panda/src/egg/eggPolysetMaker.h @@ -29,7 +29,7 @@ * these are not sufficient, you can always rederive your own further * specialization of this class. */ -class EXPCL_PANDAEGG EggPolysetMaker : public EggBinMaker { +class EXPCL_PANDA_EGG EggPolysetMaker : public EggBinMaker { PUBLISHED: // The BinNumber serves to identify why a particular EggBin was created. enum BinNumber { diff --git a/panda/src/egg/eggPoolUniquifier.cxx b/panda/src/egg/eggPoolUniquifier.cxx index 859bd0aff0..86f8eea1e3 100644 --- a/panda/src/egg/eggPoolUniquifier.cxx +++ b/panda/src/egg/eggPoolUniquifier.cxx @@ -33,7 +33,7 @@ EggPoolUniquifier() { * Returns the category name into which the given node should be collected, or * the empty string if the node's name should be left alone. */ -string EggPoolUniquifier:: +std::string EggPoolUniquifier:: get_category(EggNode *node) { if (node->is_of_type(EggTexture::get_class_type())) { return "tex"; @@ -43,5 +43,5 @@ get_category(EggNode *node) { return "vpool"; } - return string(); + return std::string(); } diff --git a/panda/src/egg/eggPoolUniquifier.h b/panda/src/egg/eggPoolUniquifier.h index 0fb7d1b9d5..a5d48f0813 100644 --- a/panda/src/egg/eggPoolUniquifier.h +++ b/panda/src/egg/eggPoolUniquifier.h @@ -23,11 +23,11 @@ * textures, materials, and vertex pools prior to writing out an egg file. * It's automatically called by EggData prior to writing out an egg file. */ -class EXPCL_PANDAEGG EggPoolUniquifier : public EggNameUniquifier { +class EXPCL_PANDA_EGG EggPoolUniquifier : public EggNameUniquifier { PUBLISHED: EggPoolUniquifier(); - virtual string get_category(EggNode *node); + virtual std::string get_category(EggNode *node); public: static TypeHandle get_class_type() { diff --git a/panda/src/egg/eggPrimitive.I b/panda/src/egg/eggPrimitive.I index 8ae8a1eecf..13e994acce 100644 --- a/panda/src/egg/eggPrimitive.I +++ b/panda/src/egg/eggPrimitive.I @@ -15,7 +15,7 @@ * */ INLINE EggPrimitive:: -EggPrimitive(const string &name): EggNode(name) { +EggPrimitive(const std::string &name): EggNode(name) { _bface = false; _connected_shading = S_unknown; } @@ -67,13 +67,13 @@ INLINE EggPrimitive:: * Presently, this is defined as the primitive name itself, unless it begins * with a digit. */ -INLINE string EggPrimitive:: +INLINE std::string EggPrimitive:: get_sort_name() const { - const string &name = get_name(); + const std::string &name = get_name(); if (!name.empty() && !isdigit(name[0])) { return name; } - return string(); + return std::string(); } /** @@ -136,7 +136,7 @@ has_texture() const { INLINE bool EggPrimitive:: has_texture(EggTexture *texture) const { PT_EggTexture t = texture; - return (::find(_textures.begin(), _textures.end(), t) != _textures.end()); + return (std::find(_textures.begin(), _textures.end(), t) != _textures.end()); } /** @@ -148,7 +148,7 @@ has_texture(EggTexture *texture) const { */ INLINE EggTexture *EggPrimitive:: get_texture() const { - return has_texture() ? get_texture(0) : (EggTexture *)NULL; + return has_texture() ? get_texture(0) : nullptr; } /** @@ -184,7 +184,7 @@ get_num_textures() const { */ INLINE EggTexture *EggPrimitive:: get_texture(int n) const { - nassertr(n >= 0 && n < (int)_textures.size(), NULL); + nassertr(n >= 0 && n < (int)_textures.size(), nullptr); return _textures[n]; } @@ -202,7 +202,7 @@ set_material(EggMaterial *material) { */ INLINE void EggPrimitive:: clear_material() { - _material = (EggMaterial *)NULL; + _material = nullptr; } /** @@ -221,7 +221,7 @@ get_material() const { */ INLINE bool EggPrimitive:: has_material() const { - return _material != (EggMaterial *)NULL; + return _material != nullptr; } @@ -299,7 +299,7 @@ size() const { */ INLINE EggVertex *EggPrimitive:: operator [] (int index) const { - nassertr(index >= 0 && index < (int)size(), NULL); + nassertr(index >= 0 && index < (int)size(), nullptr); return *(begin() + index); } @@ -388,7 +388,7 @@ insert_vertex(size_t index, EggVertex *vertex) { */ INLINE EggVertex *EggPrimitive:: get_vertex(size_t index) const { - nassertr(index < size(), NULL); + nassertr(index < size(), nullptr); return *(begin() + index); } @@ -398,5 +398,5 @@ get_vertex(size_t index) const { */ INLINE EggVertexPool *EggPrimitive:: get_pool() const { - return empty() ? (EggVertexPool *)NULL : _vertices.front()->get_pool(); + return empty() ? nullptr : _vertices.front()->get_pool(); } diff --git a/panda/src/egg/eggPrimitive.cxx b/panda/src/egg/eggPrimitive.cxx index e3eb0b16d7..f4985dfc90 100644 --- a/panda/src/egg/eggPrimitive.cxx +++ b/panda/src/egg/eggPrimitive.cxx @@ -37,9 +37,9 @@ determine_alpha_mode() { } EggRenderMode *result = EggNode::determine_alpha_mode(); - if (result == (EggRenderMode *)NULL) { + if (result == nullptr) { int num_textures = get_num_textures(); - for (int i = 0; i < num_textures && result == (EggRenderMode *)NULL; i++) { + for (int i = 0; i < num_textures && result == nullptr; i++) { EggTexture *egg_tex = get_texture(i); // We only want to consider the alpha mode on those textures that can @@ -70,9 +70,9 @@ determine_depth_write_mode() { } EggRenderMode *result = EggNode::determine_depth_write_mode(); - if (result == (EggRenderMode *)NULL) { + if (result == nullptr) { int num_textures = get_num_textures(); - for (int i = 0; i < num_textures && result == (EggRenderMode *)NULL; i++) { + for (int i = 0; i < num_textures && result == nullptr; i++) { if (get_texture(i)->get_depth_write_mode() != DWM_unspecified) { result = get_texture(i); } @@ -94,9 +94,9 @@ determine_depth_test_mode() { } EggRenderMode *result = EggNode::determine_depth_test_mode(); - if (result == (EggRenderMode *)NULL) { + if (result == nullptr) { int num_textures = get_num_textures(); - for (int i = 0; i < num_textures && result == (EggRenderMode *)NULL; i++) { + for (int i = 0; i < num_textures && result == nullptr; i++) { if (get_texture(i)->get_depth_test_mode() != DTM_unspecified) { result = get_texture(i); } @@ -118,9 +118,9 @@ determine_visibility_mode() { } EggRenderMode *result = EggNode::determine_visibility_mode(); - if (result == (EggRenderMode *)NULL) { + if (result == nullptr) { int num_textures = get_num_textures(); - for (int i = 0; i < num_textures && result == (EggRenderMode *)NULL; i++) { + for (int i = 0; i < num_textures && result == nullptr; i++) { if (get_texture(i)->get_visibility_mode() != VM_unspecified) { result = get_texture(i); } @@ -142,9 +142,9 @@ determine_depth_offset() { } EggRenderMode *result = EggNode::determine_depth_offset(); - if (result == (EggRenderMode *)NULL) { + if (result == nullptr) { int num_textures = get_num_textures(); - for (int i = 0; i < num_textures && result == (EggRenderMode *)NULL; i++) { + for (int i = 0; i < num_textures && result == nullptr; i++) { if (get_texture(i)->has_depth_offset()) { result = get_texture(i); } @@ -166,9 +166,9 @@ determine_draw_order() { } EggRenderMode *result = EggNode::determine_draw_order(); - if (result == (EggRenderMode *)NULL) { + if (result == nullptr) { int num_textures = get_num_textures(); - for (int i = 0; i < num_textures && result == (EggRenderMode *)NULL; i++) { + for (int i = 0; i < num_textures && result == nullptr; i++) { if (get_texture(i)->has_draw_order()) { result = get_texture(i); } @@ -190,9 +190,9 @@ determine_bin() { } EggRenderMode *result = EggNode::determine_bin(); - if (result == (EggRenderMode *)NULL) { + if (result == nullptr) { int num_textures = get_num_textures(); - for (int i = 0; i < num_textures && result == (EggRenderMode *)NULL; i++) { + for (int i = 0; i < num_textures && result == nullptr; i++) { if (get_texture(i)->has_bin()) { result = get_texture(i); } @@ -227,7 +227,7 @@ get_shading() const { if (!first_vertex->has_normal()) { first_vertex = this; } - for (int i = 1; i < get_num_vertices(); i++) { + for (size_t i = 1; i < get_num_vertices(); ++i) { const EggAttributes *vertex = get_vertex(i); if (!vertex->has_normal()) { vertex = this; @@ -244,7 +244,7 @@ get_shading() const { if (!first_vertex->has_color()) { first_vertex = this; } - for (int i = 1; i < get_num_vertices(); i++) { + for (size_t i = 1; i < get_num_vertices(); ++i) { const EggAttributes *vertex = get_vertex(i); if (!vertex->has_color()) { vertex = this; @@ -374,7 +374,7 @@ unify_attributes(EggPrimitive::Shading shading) { } EggVertexPool *vertex_pool = orig_vertex->get_pool(); - nassertv(vertex_pool != (EggVertexPool *)NULL); + nassertv(vertex_pool != nullptr); vertex = vertex_pool->create_unique_vertex(*vertex); vertex->copy_grefs_from(*orig_vertex); replace(pi, vertex); @@ -406,7 +406,7 @@ unify_attributes(EggPrimitive::Shading shading) { } EggVertexPool *vertex_pool = orig_vertex->get_pool(); - nassertv(vertex_pool != (EggVertexPool *)NULL); + nassertv(vertex_pool != nullptr); vertex = vertex_pool->create_unique_vertex(*vertex); vertex->copy_grefs_from(*orig_vertex); replace(pi, vertex); @@ -461,9 +461,7 @@ apply_first_attribute() { void EggPrimitive:: post_apply_flat_attribute() { if (!empty()) { - for (int i = 0; i < (int)size(); i++) { - EggVertex *vertex = get_vertex(i); - + for (EggVertex *vertex : _vertices) { // Use set_normal() instead of copy_normal(), to avoid getting the // morphs--we don't want them here, since we're just putting a bogus // value on the normal anyway. @@ -644,7 +642,7 @@ erase(iterator first, iterator last) { EggPrimitive::iterator EggPrimitive:: find(EggVertex *vertex) { PT_EggVertex vpt = vertex; - return ::find(begin(), end(), vpt); + return std::find(begin(), end(), vpt); } @@ -670,7 +668,7 @@ add_vertex(EggVertex *vertex) { EggVertex *EggPrimitive:: remove_vertex(EggVertex *vertex) { PT_EggVertex vpt = vertex; - iterator i = ::find(begin(), end(), vpt); + iterator i = std::find(begin(), end(), vpt); if (i == end()) { return PT_EggVertex(); } else { @@ -823,7 +821,7 @@ prepare_remove_vertex(EggVertex *vertex, int i, int n) { * indicated output stream in Egg format. */ void EggPrimitive:: -write_body(ostream &out, int indent_level) const { +write_body(std::ostream &out, int indent_level) const { test_vref_integrity(); EggAttributes::write(out, indent_level); @@ -854,7 +852,7 @@ write_body(ostream &out, int indent_level) const { EggVertexPool *pool = get_pool(); // Make sure the vertices belong to some vertex pool. - nassertv(pool != NULL); + nassertv(pool != nullptr); // Make sure the vertex pool is named. nassertv(pool->has_name()); @@ -979,7 +977,7 @@ r_apply_texmats(EggTextureCollection &textures) { EggTexture *unique = textures.create_unique_texture(new_texture, ~0); new_textures.push_back(unique); - string uv_name = unique->get_uv_name(); + std::string uv_name = unique->get_uv_name(); // Now apply the matrix to the vertex UV's. Create new vertices as // necessary. @@ -988,7 +986,7 @@ r_apply_texmats(EggTextureCollection &textures) { EggVertex *vertex = get_vertex(i); const EggVertexUV *uv_obj = vertex->get_uv_obj(uv_name); - if (uv_obj != (EggVertexUV *)NULL) { + if (uv_obj != nullptr) { EggVertex new_vertex(*vertex); PT(EggVertexUV) new_uv_obj = new EggVertexUV(*uv_obj); LTexCoord3d uvw = uv_obj->get_uvw() * mat; diff --git a/panda/src/egg/eggPrimitive.h b/panda/src/egg/eggPrimitive.h index 9ec9d9cf79..4b8a035952 100644 --- a/panda/src/egg/eggPrimitive.h +++ b/panda/src/egg/eggPrimitive.h @@ -44,7 +44,7 @@ class EggVertexPool; * can. However, it is necessary that all vertices belong to the same vertex * pool. */ -class EXPCL_PANDAEGG EggPrimitive : public EggNode, public EggAttributes, +class EXPCL_PANDA_EGG EggPrimitive : public EggNode, public EggAttributes, public EggRenderMode { @@ -67,7 +67,7 @@ PUBLISHED: S_per_vertex }; - INLINE explicit EggPrimitive(const string &name = ""); + INLINE explicit EggPrimitive(const std::string &name = ""); INLINE EggPrimitive(const EggPrimitive ©); INLINE EggPrimitive &operator = (const EggPrimitive ©); INLINE ~EggPrimitive(); @@ -82,7 +82,7 @@ PUBLISHED: virtual EggRenderMode *determine_draw_order(); virtual EggRenderMode *determine_bin(); - INLINE string get_sort_name() const; + INLINE std::string get_sort_name() const; virtual Shading get_shading() const; INLINE void clear_connected_shading(); @@ -191,7 +191,7 @@ PUBLISHED: MAKE_SEQ_PROPERTY(vertices, get_num_vertices, get_vertex, set_vertex, remove_vertex, insert_vertex); MAKE_PROPERTY(pool, get_pool); - virtual void write(ostream &out, int indent_level) const=0; + virtual void write(std::ostream &out, int indent_level) const=0; #ifdef _DEBUG void test_vref_integrity() const; @@ -209,7 +209,7 @@ protected: virtual void prepare_remove_vertex(EggVertex *vertex, int i, int n); protected: - void write_body(ostream &out, int indent_level) const; + void write_body(std::ostream &out, int indent_level) const; virtual bool egg_start_parse_body(); virtual void r_transform(const LMatrix4d &mat, const LMatrix4d &inv, diff --git a/panda/src/egg/eggRenderMode.I b/panda/src/egg/eggRenderMode.I index 10d40d01fb..ee21aabf34 100644 --- a/panda/src/egg/eggRenderMode.I +++ b/panda/src/egg/eggRenderMode.I @@ -186,7 +186,7 @@ clear_draw_order() { * CullTraverser) in use for this to work. See also set_draw_order(). */ INLINE void EggRenderMode:: -set_bin(const string &bin) { +set_bin(const std::string &bin) { _bin = bin; } @@ -194,7 +194,7 @@ set_bin(const string &bin) { * Returns the bin name that has been set for this particular object, if any. * See set_bin(). */ -INLINE string EggRenderMode:: +INLINE std::string EggRenderMode:: get_bin() const { return _bin; } @@ -214,7 +214,7 @@ has_bin() const { */ INLINE void EggRenderMode:: clear_bin() { - _bin = string(); + _bin = std::string(); } /** diff --git a/panda/src/egg/eggRenderMode.cxx b/panda/src/egg/eggRenderMode.cxx index 7c7e478a6d..5ac4b05844 100644 --- a/panda/src/egg/eggRenderMode.cxx +++ b/panda/src/egg/eggRenderMode.cxx @@ -16,6 +16,10 @@ #include "string_utils.h" #include "pnotify.h" +using std::istream; +using std::ostream; +using std::string; + TypeHandle EggRenderMode::_type_handle; /** diff --git a/panda/src/egg/eggRenderMode.h b/panda/src/egg/eggRenderMode.h index 66d9a6c645..3730cde3da 100644 --- a/panda/src/egg/eggRenderMode.h +++ b/panda/src/egg/eggRenderMode.h @@ -28,13 +28,13 @@ * EggPolygon level with multiple appearances of the EggObject base class. * And making EggObject a virtual base class is just no fun. */ -class EXPCL_PANDAEGG EggRenderMode { +class EXPCL_PANDA_EGG EggRenderMode { PUBLISHED: EggRenderMode(); INLINE EggRenderMode(const EggRenderMode ©); EggRenderMode &operator = (const EggRenderMode ©); - void write(ostream &out, int indent_level) const; + void write(std::ostream &out, int indent_level) const; enum AlphaMode { // Specifies implementation of transparency. AM_unspecified, @@ -83,8 +83,8 @@ PUBLISHED: INLINE bool has_draw_order() const; INLINE void clear_draw_order(); - INLINE void set_bin(const string &bin); - INLINE string get_bin() const; + INLINE void set_bin(const std::string &bin); + INLINE std::string get_bin() const; INLINE bool has_bin() const; INLINE void clear_bin(); @@ -93,10 +93,10 @@ PUBLISHED: INLINE bool operator != (const EggRenderMode &other) const; bool operator < (const EggRenderMode &other) const; - static AlphaMode string_alpha_mode(const string &string); - static DepthWriteMode string_depth_write_mode(const string &string); - static DepthTestMode string_depth_test_mode(const string &string); - static VisibilityMode string_visibility_mode(const string &string); + static AlphaMode string_alpha_mode(const std::string &string); + static DepthWriteMode string_depth_write_mode(const std::string &string); + static DepthTestMode string_depth_test_mode(const std::string &string); + static VisibilityMode string_visibility_mode(const std::string &string); private: AlphaMode _alpha_mode; @@ -107,7 +107,7 @@ private: bool _has_depth_offset; int _draw_order; bool _has_draw_order; - string _bin; + std::string _bin; public: @@ -122,12 +122,12 @@ private: static TypeHandle _type_handle; }; -EXPCL_PANDAEGG ostream &operator << (ostream &out, EggRenderMode::AlphaMode mode); -EXPCL_PANDAEGG istream &operator >> (istream &in, EggRenderMode::AlphaMode &mode); +EXPCL_PANDA_EGG std::ostream &operator << (std::ostream &out, EggRenderMode::AlphaMode mode); +EXPCL_PANDA_EGG std::istream &operator >> (std::istream &in, EggRenderMode::AlphaMode &mode); -EXPCL_PANDAEGG ostream &operator << (ostream &out, EggRenderMode::DepthWriteMode mode); -EXPCL_PANDAEGG ostream &operator << (ostream &out, EggRenderMode::DepthTestMode mode); -EXPCL_PANDAEGG ostream &operator << (ostream &out, EggRenderMode::VisibilityMode mode); +EXPCL_PANDA_EGG std::ostream &operator << (std::ostream &out, EggRenderMode::DepthWriteMode mode); +EXPCL_PANDA_EGG std::ostream &operator << (std::ostream &out, EggRenderMode::DepthTestMode mode); +EXPCL_PANDA_EGG std::ostream &operator << (std::ostream &out, EggRenderMode::VisibilityMode mode); #include "eggRenderMode.I" diff --git a/panda/src/egg/eggSAnimData.I b/panda/src/egg/eggSAnimData.I index 866fdd753a..e1fe187d54 100644 --- a/panda/src/egg/eggSAnimData.I +++ b/panda/src/egg/eggSAnimData.I @@ -15,7 +15,7 @@ * */ INLINE EggSAnimData:: -EggSAnimData(const string &name) : EggAnimData(name) { +EggSAnimData(const std::string &name) : EggAnimData(name) { } diff --git a/panda/src/egg/eggSAnimData.cxx b/panda/src/egg/eggSAnimData.cxx index 27d3a88ed6..2dd63d24a1 100644 --- a/panda/src/egg/eggSAnimData.cxx +++ b/panda/src/egg/eggSAnimData.cxx @@ -48,7 +48,7 @@ optimize() { * Writes the data to the indicated output stream in Egg format. */ void EggSAnimData:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { if (get_num_rows() <= 1) { // We get a lot of these little tiny tables. For brevity, we'll write // these all on one line, because we can. This just makes it easier for a diff --git a/panda/src/egg/eggSAnimData.h b/panda/src/egg/eggSAnimData.h index 2862b94622..c1c28eb2c5 100644 --- a/panda/src/egg/eggSAnimData.h +++ b/panda/src/egg/eggSAnimData.h @@ -22,9 +22,9 @@ * Corresponding to an entry, this stores a single column of numbers, * for instance for a morph target, or as one column in an EggXfmSAnim. */ -class EXPCL_PANDAEGG EggSAnimData : public EggAnimData { +class EXPCL_PANDA_EGG EggSAnimData : public EggAnimData { PUBLISHED: - INLINE explicit EggSAnimData(const string &name = ""); + INLINE explicit EggSAnimData(const std::string &name = ""); INLINE EggSAnimData(const EggSAnimData ©); INLINE EggSAnimData &operator = (const EggSAnimData ©); @@ -34,7 +34,7 @@ PUBLISHED: void optimize(); - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; public: diff --git a/panda/src/egg/eggSurface.I b/panda/src/egg/eggSurface.I index f7856d3ec7..e03d790408 100644 --- a/panda/src/egg/eggSurface.I +++ b/panda/src/egg/eggSurface.I @@ -15,7 +15,7 @@ * */ INLINE EggSurface:: -EggSurface(const string &name) : EggPrimitive(name) { +EggSurface(const std::string &name) : EggPrimitive(name) { _u_subdiv = 0; _v_subdiv = 0; } diff --git a/panda/src/egg/eggSurface.h b/panda/src/egg/eggSurface.h index 3085cb1c48..19ee6cb907 100644 --- a/panda/src/egg/eggSurface.h +++ b/panda/src/egg/eggSurface.h @@ -21,9 +21,9 @@ /** * A parametric surface of some kind. See EggNurbsSurface. */ -class EXPCL_PANDAEGG EggSurface : public EggPrimitive { +class EXPCL_PANDA_EGG EggSurface : public EggPrimitive { PUBLISHED: - INLINE explicit EggSurface(const string &name = ""); + INLINE explicit EggSurface(const std::string &name = ""); INLINE EggSurface(const EggSurface ©); INLINE EggSurface &operator = (const EggSurface ©); diff --git a/panda/src/egg/eggSwitchCondition.cxx b/panda/src/egg/eggSwitchCondition.cxx index d461c406f7..1515563d50 100644 --- a/panda/src/egg/eggSwitchCondition.cxx +++ b/panda/src/egg/eggSwitchCondition.cxx @@ -45,7 +45,7 @@ make_copy() const { * */ void EggSwitchConditionDistance:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << " {\n"; indent(out, indent_level+2) << " { " << _switch_in << " " << _switch_out; diff --git a/panda/src/egg/eggSwitchCondition.h b/panda/src/egg/eggSwitchCondition.h index a1d16db2ca..ceb15cca51 100644 --- a/panda/src/egg/eggSwitchCondition.h +++ b/panda/src/egg/eggSwitchCondition.h @@ -26,10 +26,10 @@ * different kinds of switching conditions; presently, only a type * is actually supported. */ -class EXPCL_PANDAEGG EggSwitchCondition : public EggObject { +class EXPCL_PANDA_EGG EggSwitchCondition : public EggObject { PUBLISHED: virtual EggSwitchCondition *make_copy() const=0; - virtual void write(ostream &out, int indent_level) const=0; + virtual void write(std::ostream &out, int indent_level) const=0; virtual void transform(const LMatrix4d &mat)=0; @@ -58,13 +58,13 @@ private: * A SwitchCondition that switches the levels-of-detail based on distance from * the camera's eyepoint. */ -class EXPCL_PANDAEGG EggSwitchConditionDistance : public EggSwitchCondition { +class EXPCL_PANDA_EGG EggSwitchConditionDistance : public EggSwitchCondition { PUBLISHED: explicit EggSwitchConditionDistance(double switch_in, double switch_out, const LPoint3d ¢er, double fade = 0.0); virtual EggSwitchCondition *make_copy() const; - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; virtual void transform(const LMatrix4d &mat); diff --git a/panda/src/egg/eggTable.I b/panda/src/egg/eggTable.I index 33fe8b343a..d5822455ff 100644 --- a/panda/src/egg/eggTable.I +++ b/panda/src/egg/eggTable.I @@ -15,7 +15,7 @@ * */ INLINE EggTable:: -EggTable(const string &name) : EggGroupNode(name) { +EggTable(const std::string &name) : EggGroupNode(name) { _type = TT_table; } diff --git a/panda/src/egg/eggTable.cxx b/panda/src/egg/eggTable.cxx index b8372e41af..234c40c5f8 100644 --- a/panda/src/egg/eggTable.cxx +++ b/panda/src/egg/eggTable.cxx @@ -41,7 +41,7 @@ has_transform() const { * Egg format. */ void EggTable:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { test_under_integrity(); switch (get_table_type()) { @@ -69,7 +69,7 @@ write(ostream &out, int indent_level) const { * TableType value. */ EggTable::TableType EggTable:: -string_table_type(const string &string) { +string_table_type(const std::string &string) { if (cmp_nocase_uh(string, "table") == 0) { return TT_table; } else if (cmp_nocase_uh(string, "bundle") == 0) { @@ -137,7 +137,7 @@ r_transform(const LMatrix4d &mat, const LMatrix4d &inv, /** * */ -ostream &operator << (ostream &out, EggTable::TableType t) { +std::ostream &operator << (std::ostream &out, EggTable::TableType t) { switch (t) { case EggTable::TT_invalid: return out << "invalid table"; diff --git a/panda/src/egg/eggTable.h b/panda/src/egg/eggTable.h index e2a55d7a3e..59d76e9a08 100644 --- a/panda/src/egg/eggTable.h +++ b/panda/src/egg/eggTable.h @@ -24,7 +24,7 @@ * EggSAnimData or an EggXfmAnimData, which do. It may also be a parent to * another or , establishing a hierarchy of tables. */ -class EXPCL_PANDAEGG EggTable : public EggGroupNode { +class EXPCL_PANDA_EGG EggTable : public EggGroupNode { PUBLISHED: enum TableType { TT_invalid, @@ -32,7 +32,7 @@ PUBLISHED: TT_bundle, }; - INLINE explicit EggTable(const string &name = ""); + INLINE explicit EggTable(const std::string &name = ""); INLINE EggTable(const EggTable ©); INLINE EggTable &operator = (const EggTable ©); @@ -40,9 +40,9 @@ PUBLISHED: INLINE TableType get_table_type() const; bool has_transform() const; - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; - static TableType string_table_type(const string &string); + static TableType string_table_type(const std::string &string); protected: virtual void r_transform(const LMatrix4d &mat, const LMatrix4d &inv, @@ -71,7 +71,7 @@ private: static TypeHandle _type_handle; }; -ostream &operator << (ostream &out, EggTable::TableType t); +std::ostream &operator << (std::ostream &out, EggTable::TableType t); #include "eggTable.I" diff --git a/panda/src/egg/eggTexture.I b/panda/src/egg/eggTexture.I index 6380934886..7a71261e31 100644 --- a/panda/src/egg/eggTexture.I +++ b/panda/src/egg/eggTexture.I @@ -376,7 +376,7 @@ get_quality_level() const { * Each different TextureStage in the world must be uniquely named. */ INLINE void EggTexture:: -set_stage_name(const string &stage_name) { +set_stage_name(const std::string &stage_name) { _stage_name = stage_name; _flags |= F_has_stage_name; } @@ -386,7 +386,7 @@ set_stage_name(const string &stage_name) { */ INLINE void EggTexture:: clear_stage_name() { - _stage_name = string(); + _stage_name = std::string(); _flags &= ~F_has_stage_name; } @@ -403,7 +403,7 @@ has_stage_name() const { * Returns the stage name that has been specified for this texture, or the * tref name if no texture stage has explicitly been specified. */ -INLINE const string &EggTexture:: +INLINE const std::string &EggTexture:: get_stage_name() const { return has_stage_name() ? _stage_name : get_name(); } @@ -526,7 +526,7 @@ get_border_color() const { * texture coordinates will be used. */ INLINE void EggTexture:: -set_uv_name(const string &uv_name) { +set_uv_name(const std::string &uv_name) { if (uv_name == "default" || uv_name.empty()) { clear_uv_name(); } else { @@ -541,7 +541,7 @@ set_uv_name(const string &uv_name) { */ INLINE void EggTexture:: clear_uv_name() { - _uv_name = string(); + _uv_name = std::string(); _flags &= ~F_has_uv_name; } @@ -558,7 +558,7 @@ has_uv_name() const { * Returns the texcoord name that has been specified for this texture, or the * empty string if no texcoord name has explicitly been specified. */ -INLINE const string &EggTexture:: +INLINE const std::string &EggTexture:: get_uv_name() const { return _uv_name; } diff --git a/panda/src/egg/eggTexture.cxx b/panda/src/egg/eggTexture.cxx index 85327cb915..eb2cfa7342 100644 --- a/panda/src/egg/eggTexture.cxx +++ b/panda/src/egg/eggTexture.cxx @@ -18,6 +18,9 @@ #include "indent.h" #include "string_utils.h" +using std::ostream; +using std::string; + TypeHandle EggTexture::_type_handle; diff --git a/panda/src/egg/eggTexture.h b/panda/src/egg/eggTexture.h index 174b7c99db..55f56f4b3d 100644 --- a/panda/src/egg/eggTexture.h +++ b/panda/src/egg/eggTexture.h @@ -27,14 +27,14 @@ /** * Defines a texture map that may be applied to geometry. */ -class EXPCL_PANDAEGG EggTexture : public EggFilenameNode, public EggRenderMode, public EggTransform { +class EXPCL_PANDA_EGG EggTexture : public EggFilenameNode, public EggRenderMode, public EggTransform { PUBLISHED: - explicit EggTexture(const string &tref_name, const Filename &filename); + explicit EggTexture(const std::string &tref_name, const Filename &filename); EggTexture(const EggTexture ©); EggTexture &operator = (const EggTexture ©); virtual ~EggTexture(); - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; enum Equivalence { E_basename = 0x001, @@ -219,10 +219,10 @@ PUBLISHED: INLINE void set_quality_level(QualityLevel quality_level); INLINE QualityLevel get_quality_level() const; - INLINE void set_stage_name(const string &stage_name); + INLINE void set_stage_name(const std::string &stage_name); INLINE void clear_stage_name(); INLINE bool has_stage_name() const; - INLINE const string &get_stage_name() const; + INLINE const std::string &get_stage_name() const; INLINE void set_priority(int priority); INLINE void clear_priority(); @@ -239,10 +239,10 @@ PUBLISHED: INLINE bool has_border_color() const; INLINE const LColor &get_border_color() const; - INLINE void set_uv_name(const string &uv_name); + INLINE void set_uv_name(const std::string &uv_name); INLINE void clear_uv_name(); INLINE bool has_uv_name() const; - INLINE const string &get_uv_name() const; + INLINE const std::string &get_uv_name() const; INLINE void set_rgb_scale(int rgb_scale); INLINE void clear_rgb_scale(); @@ -297,17 +297,17 @@ PUBLISHED: bool multitexture_over(EggTexture *other); INLINE int get_multitexture_sort() const; - static TextureType string_texture_type(const string &string); - static Format string_format(const string &string); - static CompressionMode string_compression_mode(const string &string); - static WrapMode string_wrap_mode(const string &string); - static FilterType string_filter_type(const string &string); - static EnvType string_env_type(const string &string); - static CombineMode string_combine_mode(const string &string); - static CombineSource string_combine_source(const string &string); - static CombineOperand string_combine_operand(const string &string); - static TexGen string_tex_gen(const string &string); - static QualityLevel string_quality_level(const string &string); + static TextureType string_texture_type(const std::string &string); + static Format string_format(const std::string &string); + static CompressionMode string_compression_mode(const std::string &string); + static WrapMode string_wrap_mode(const std::string &string); + static FilterType string_filter_type(const std::string &string); + static EnvType string_env_type(const std::string &string); + static CombineMode string_combine_mode(const std::string &string); + static CombineSource string_combine_source(const std::string &string); + static CombineOperand string_combine_operand(const std::string &string); + static TexGen string_tex_gen(const std::string &string); + static QualityLevel string_quality_level(const std::string &string); PUBLISHED: MAKE_PROPERTY(texture_type, get_texture_type, set_texture_type); @@ -396,11 +396,11 @@ private: int _num_views; TexGen _tex_gen; QualityLevel _quality_level; - string _stage_name; + std::string _stage_name; int _priority; LColor _color; LColor _border_color; - string _uv_name; + std::string _uv_name; int _rgb_scale; int _alpha_scale; int _flags; @@ -458,7 +458,7 @@ private: * Returns true if the two referenced EggTexture pointers are in sorted order, * false otherwise. */ -class EXPCL_PANDAEGG UniqueEggTextures { +class EXPCL_PANDA_EGG UniqueEggTextures { public: INLINE UniqueEggTextures(int eq = ~0); INLINE bool operator ()(const EggTexture *t1, const EggTexture *t2) const; @@ -466,22 +466,22 @@ public: int _eq; }; -INLINE ostream &operator << (ostream &out, const EggTexture &n) { +INLINE std::ostream &operator << (std::ostream &out, const EggTexture &n) { return out << n.get_filename(); } -EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::TextureType texture_type); -EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::Format format); -EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::CompressionMode mode); -EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::WrapMode mode); -EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::FilterType type); -EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::EnvType type); -EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::CombineMode cm); -EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::CombineChannel cc); -EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::CombineSource cs); -EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::CombineOperand co); -EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::TexGen tex_gen); -EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::QualityLevel quality_level); +EXPCL_PANDA_EGG std::ostream &operator << (std::ostream &out, EggTexture::TextureType texture_type); +EXPCL_PANDA_EGG std::ostream &operator << (std::ostream &out, EggTexture::Format format); +EXPCL_PANDA_EGG std::ostream &operator << (std::ostream &out, EggTexture::CompressionMode mode); +EXPCL_PANDA_EGG std::ostream &operator << (std::ostream &out, EggTexture::WrapMode mode); +EXPCL_PANDA_EGG std::ostream &operator << (std::ostream &out, EggTexture::FilterType type); +EXPCL_PANDA_EGG std::ostream &operator << (std::ostream &out, EggTexture::EnvType type); +EXPCL_PANDA_EGG std::ostream &operator << (std::ostream &out, EggTexture::CombineMode cm); +EXPCL_PANDA_EGG std::ostream &operator << (std::ostream &out, EggTexture::CombineChannel cc); +EXPCL_PANDA_EGG std::ostream &operator << (std::ostream &out, EggTexture::CombineSource cs); +EXPCL_PANDA_EGG std::ostream &operator << (std::ostream &out, EggTexture::CombineOperand co); +EXPCL_PANDA_EGG std::ostream &operator << (std::ostream &out, EggTexture::TexGen tex_gen); +EXPCL_PANDA_EGG std::ostream &operator << (std::ostream &out, EggTexture::QualityLevel quality_level); #include "eggTexture.I" diff --git a/panda/src/egg/eggTextureCollection.cxx b/panda/src/egg/eggTextureCollection.cxx index f53c9d0ddc..0c1b46eea7 100644 --- a/panda/src/egg/eggTextureCollection.cxx +++ b/panda/src/egg/eggTextureCollection.cxx @@ -99,7 +99,7 @@ get_num_textures() const { */ EggTexture *EggTextureCollection:: get_texture(int index) const { - nassertr(index >= 0 && index < (int)_ordered_textures.size(), NULL); + nassertr(index >= 0 && index < (int)_ordered_textures.size(), nullptr); return _ordered_textures[index]; } @@ -271,7 +271,7 @@ collapse_equivalent_textures(int eq, EggTextureCollection::TextureReplacement &r ++oti) { EggTexture *tex = (*oti); - pair result = collapser.insert(tex); + std::pair result = collapser.insert(tex); if (!result.second) { // This texture is non-unique; another one was already there. EggTexture *first = *(result.first); @@ -453,7 +453,7 @@ create_unique_texture(const EggTexture ©, int eq) { * matches. */ EggTexture *EggTextureCollection:: -find_tref(const string &tref_name) const { +find_tref(const std::string &tref_name) const { // This requires a complete linear traversal, not terribly efficient. OrderedTextures::const_iterator oti; for (oti = _ordered_textures.begin(); @@ -465,7 +465,7 @@ find_tref(const string &tref_name) const { } } - return (EggTexture *)NULL; + return nullptr; } /** @@ -485,5 +485,5 @@ find_filename(const Filename &filename) const { } } - return (EggTexture *)NULL; + return nullptr; } diff --git a/panda/src/egg/eggTextureCollection.h b/panda/src/egg/eggTextureCollection.h index e5276eef5c..040a8e0da8 100644 --- a/panda/src/egg/eggTextureCollection.h +++ b/panda/src/egg/eggTextureCollection.h @@ -27,7 +27,7 @@ * from an egg file and sort them all together; it can also manage the * creation of unique textures and the assignment of unique TRef names. */ -class EXPCL_PANDAEGG EggTextureCollection { +class EXPCL_PANDA_EGG EggTextureCollection { // This is a bit of private interface stuff that must be here as a forward // reference. This allows us to define the EggTextureCollection as an STL @@ -98,7 +98,7 @@ PUBLISHED: EggTexture *create_unique_texture(const EggTexture ©, int eq); // Find a texture with a particular TRef name. - EggTexture *find_tref(const string &tref_name) const; + EggTexture *find_tref(const std::string &tref_name) const; // Find a texture with a particular filename. EggTexture *find_filename(const Filename &filename) const; diff --git a/panda/src/egg/eggTransform.I b/panda/src/egg/eggTransform.I index bff92d6194..e6bccb6819 100644 --- a/panda/src/egg/eggTransform.I +++ b/panda/src/egg/eggTransform.I @@ -19,10 +19,10 @@ Component(EggTransform::ComponentType type, double number) : _type(type), _number(number) { - _vec2 = (LVecBase2d *)NULL; - _vec3 = (LVecBase3d *)NULL; - _mat3 = (LMatrix3d *)NULL; - _mat4 = (LMatrix4d *)NULL; + _vec2 = nullptr; + _vec3 = nullptr; + _mat3 = nullptr; + _mat4 = nullptr; } /** @@ -33,20 +33,20 @@ Component(const EggTransform::Component ©) : _type(copy._type), _number(copy._number) { - _vec2 = (LVecBase2d *)NULL; - _vec3 = (LVecBase3d *)NULL; - _mat3 = (LMatrix3d *)NULL; - _mat4 = (LMatrix4d *)NULL; - if (copy._vec2 != (LVecBase2d *)NULL) { + _vec2 = nullptr; + _vec3 = nullptr; + _mat3 = nullptr; + _mat4 = nullptr; + if (copy._vec2 != nullptr) { _vec2 = new LVector2d(*copy._vec2); } - if (copy._vec3 != (LVecBase3d *)NULL) { + if (copy._vec3 != nullptr) { _vec3 = new LVector3d(*copy._vec3); } - if (copy._mat3 != (LMatrix3d *)NULL) { + if (copy._mat3 != nullptr) { _mat3 = new LMatrix3d(*copy._mat3); } - if (copy._mat4 != (LMatrix4d *)NULL) { + if (copy._mat4 != nullptr) { _mat4 = new LMatrix4d(*copy._mat4); } } @@ -58,32 +58,32 @@ INLINE void EggTransform::Component:: operator = (const EggTransform::Component ©) { _type = copy._type; _number = copy._number; - if (_vec2 != (LVecBase2d *)NULL) { + if (_vec2 != nullptr) { delete _vec2; - _vec2 = (LVecBase2d *)NULL; + _vec2 = nullptr; } - if (_vec3 != (LVecBase3d *)NULL) { + if (_vec3 != nullptr) { delete _vec3; - _vec3 = (LVecBase3d *)NULL; + _vec3 = nullptr; } - if (_mat3 != (LMatrix3d *)NULL) { + if (_mat3 != nullptr) { delete _mat3; - _mat3 = (LMatrix3d *)NULL; + _mat3 = nullptr; } - if (_mat4 != (LMatrix4d *)NULL) { + if (_mat4 != nullptr) { delete _mat4; - _mat4 = (LMatrix4d *)NULL; + _mat4 = nullptr; } - if (copy._vec2 != (LVecBase2d *)NULL) { + if (copy._vec2 != nullptr) { _vec2 = new LVecBase2d(*copy._vec2); } - if (copy._vec3 != (LVecBase3d *)NULL) { + if (copy._vec3 != nullptr) { _vec3 = new LVecBase3d(*copy._vec3); } - if (copy._mat3 != (LMatrix3d *)NULL) { + if (copy._mat3 != nullptr) { _mat3 = new LMatrix3d(*copy._mat3); } - if (copy._mat4 != (LMatrix4d *)NULL) { + if (copy._mat4 != nullptr) { _mat4 = new LMatrix4d(*copy._mat4); } } @@ -93,16 +93,16 @@ operator = (const EggTransform::Component ©) { */ INLINE EggTransform::Component:: ~Component() { - if (_vec2 != (LVecBase2d *)NULL) { + if (_vec2 != nullptr) { delete _vec2; } - if (_vec3 != (LVecBase3d *)NULL) { + if (_vec3 != nullptr) { delete _vec3; } - if (_mat3 != (LMatrix3d *)NULL) { + if (_mat3 != nullptr) { delete _mat3; } - if (_mat4 != (LMatrix4d *)NULL) { + if (_mat4 != nullptr) { delete _mat4; } } @@ -259,7 +259,7 @@ get_component_number(int n) const { INLINE const LVecBase2d &EggTransform:: get_component_vec2(int n) const { nassertr(n >= 0 && n < (int)_components.size(), LVector2d::zero()); - nassertr(_components[n]._vec2 != (LVecBase2d *)NULL, LVector2d::zero()); + nassertr(_components[n]._vec2 != nullptr, LVector2d::zero()); return *_components[n]._vec2; } @@ -271,7 +271,7 @@ get_component_vec2(int n) const { INLINE const LVecBase3d &EggTransform:: get_component_vec3(int n) const { nassertr(n >= 0 && n < (int)_components.size(), LVector3d::zero()); - nassertr(_components[n]._vec3 != (LVecBase3d *)NULL, LVector3d::zero()); + nassertr(_components[n]._vec3 != nullptr, LVector3d::zero()); return *_components[n]._vec3; } @@ -282,7 +282,7 @@ get_component_vec3(int n) const { INLINE const LMatrix3d &EggTransform:: get_component_mat3(int n) const { nassertr(n >= 0 && n < (int)_components.size(), LMatrix3d::ident_mat()); - nassertr(_components[n]._mat3 != (LMatrix3d *)NULL, LMatrix3d::ident_mat()); + nassertr(_components[n]._mat3 != nullptr, LMatrix3d::ident_mat()); return *_components[n]._mat3; } @@ -293,7 +293,7 @@ get_component_mat3(int n) const { INLINE const LMatrix4d &EggTransform:: get_component_mat4(int n) const { nassertr(n >= 0 && n < (int)_components.size(), LMatrix4d::ident_mat()); - nassertr(_components[n]._mat4 != (LMatrix4d *)NULL, LMatrix4d::ident_mat()); + nassertr(_components[n]._mat4 != nullptr, LMatrix4d::ident_mat()); return *_components[n]._mat4; } diff --git a/panda/src/egg/eggTransform.cxx b/panda/src/egg/eggTransform.cxx index 67ce77e1bc..65ba63c3e7 100644 --- a/panda/src/egg/eggTransform.cxx +++ b/panda/src/egg/eggTransform.cxx @@ -186,7 +186,7 @@ add_uniform_scale(double scale) { * Writes the transform to the indicated stream in Egg format. */ void EggTransform:: -write(ostream &out, int indent_level, const string &label) const { +write(std::ostream &out, int indent_level, const std::string &label) const { indent(out, indent_level) << label << " {\n"; int num_components = get_num_components(); diff --git a/panda/src/egg/eggTransform.h b/panda/src/egg/eggTransform.h index 857617ff43..671a3b1155 100644 --- a/panda/src/egg/eggTransform.h +++ b/panda/src/egg/eggTransform.h @@ -26,7 +26,7 @@ * This may be either a 3-d transform, and therefore described by a 4x4 * matrix, or a 2-d transform, described by a 3x3 matrix. */ -class EXPCL_PANDAEGG EggTransform { +class EXPCL_PANDA_EGG EggTransform { PUBLISHED: EggTransform(); EggTransform(const EggTransform ©); @@ -82,8 +82,8 @@ PUBLISHED: INLINE const LMatrix3d &get_component_mat3(int n) const; INLINE const LMatrix4d &get_component_mat4(int n) const; - void write(ostream &out, int indent_level, - const string &label) const; + void write(std::ostream &out, int indent_level, + const std::string &label) const; protected: void internal_clear_transform(); diff --git a/panda/src/egg/eggTriangleFan.I b/panda/src/egg/eggTriangleFan.I index 367b956e9e..d2ddbbdeb3 100644 --- a/panda/src/egg/eggTriangleFan.I +++ b/panda/src/egg/eggTriangleFan.I @@ -15,7 +15,7 @@ * */ INLINE EggTriangleFan:: -EggTriangleFan(const string &name) : EggCompositePrimitive(name) { +EggTriangleFan(const std::string &name) : EggCompositePrimitive(name) { } /** diff --git a/panda/src/egg/eggTriangleFan.cxx b/panda/src/egg/eggTriangleFan.cxx index 30d441286a..5287d1c8e9 100644 --- a/panda/src/egg/eggTriangleFan.cxx +++ b/panda/src/egg/eggTriangleFan.cxx @@ -38,7 +38,7 @@ make_copy() const { * Writes the triangle fan to the indicated output stream in Egg format. */ void EggTriangleFan:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { write_header(out, indent_level, ""); write_body(out, indent_level+2); indent(out, indent_level) << "}\n"; @@ -57,7 +57,7 @@ apply_first_attribute() { // In the case of a triangle fan, the first vertex of the fan is the common // vertex, so we consider the second vertex to be the key vertex of the // first triangle, and move from there. - for (int i = 0; i < get_num_components(); i++) { + for (size_t i = 0; i < get_num_components(); ++i) { EggAttributes *component = get_component(i); do_apply_flat_attribute(i + 1, component); } diff --git a/panda/src/egg/eggTriangleFan.h b/panda/src/egg/eggTriangleFan.h index 6435650284..29485b2f5f 100644 --- a/panda/src/egg/eggTriangleFan.h +++ b/panda/src/egg/eggTriangleFan.h @@ -22,16 +22,16 @@ * A connected fan of triangles. This does not normally appear in an egg * file; it is typically generated as a result of meshing. */ -class EXPCL_PANDAEGG EggTriangleFan : public EggCompositePrimitive { +class EXPCL_PANDA_EGG EggTriangleFan : public EggCompositePrimitive { PUBLISHED: - INLINE explicit EggTriangleFan(const string &name = ""); + INLINE explicit EggTriangleFan(const std::string &name = ""); INLINE EggTriangleFan(const EggTriangleFan ©); INLINE EggTriangleFan &operator = (const EggTriangleFan ©); virtual ~EggTriangleFan(); virtual EggTriangleFan *make_copy() const override; - virtual void write(ostream &out, int indent_level) const override; + virtual void write(std::ostream &out, int indent_level) const override; virtual void apply_first_attribute() override; protected: diff --git a/panda/src/egg/eggTriangleStrip.I b/panda/src/egg/eggTriangleStrip.I index 4fcb25b907..5e2e5bd33a 100644 --- a/panda/src/egg/eggTriangleStrip.I +++ b/panda/src/egg/eggTriangleStrip.I @@ -15,7 +15,7 @@ * */ INLINE EggTriangleStrip:: -EggTriangleStrip(const string &name) : EggCompositePrimitive(name) { +EggTriangleStrip(const std::string &name) : EggCompositePrimitive(name) { } /** diff --git a/panda/src/egg/eggTriangleStrip.cxx b/panda/src/egg/eggTriangleStrip.cxx index 5882471c9e..a0aa83b144 100644 --- a/panda/src/egg/eggTriangleStrip.cxx +++ b/panda/src/egg/eggTriangleStrip.cxx @@ -38,7 +38,7 @@ make_copy() const { * Writes the triangle strip to the indicated output stream in Egg format. */ void EggTriangleStrip:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { write_header(out, indent_level, ""); write_body(out, indent_level+2); indent(out, indent_level) << "}\n"; diff --git a/panda/src/egg/eggTriangleStrip.h b/panda/src/egg/eggTriangleStrip.h index fa371d4185..052d174232 100644 --- a/panda/src/egg/eggTriangleStrip.h +++ b/panda/src/egg/eggTriangleStrip.h @@ -22,16 +22,16 @@ * A connected strip of triangles. This does not normally appear in an egg * file; it is typically generated as a result of meshing. */ -class EXPCL_PANDAEGG EggTriangleStrip : public EggCompositePrimitive { +class EXPCL_PANDA_EGG EggTriangleStrip : public EggCompositePrimitive { PUBLISHED: - INLINE explicit EggTriangleStrip(const string &name = ""); + INLINE explicit EggTriangleStrip(const std::string &name = ""); INLINE EggTriangleStrip(const EggTriangleStrip ©); INLINE EggTriangleStrip &operator = (const EggTriangleStrip ©); virtual ~EggTriangleStrip(); virtual EggTriangleStrip *make_copy() const override; - virtual void write(ostream &out, int indent_level) const override; + virtual void write(std::ostream &out, int indent_level) const override; protected: virtual int get_num_lead_vertices() const override; diff --git a/panda/src/egg/eggUserData.h b/panda/src/egg/eggUserData.h index cec2587946..477bebc7c6 100644 --- a/panda/src/egg/eggUserData.h +++ b/panda/src/egg/eggUserData.h @@ -26,7 +26,7 @@ * However, this data will not be written out to the disk when the egg file is * written; it is an in-memory object only. */ -class EXPCL_PANDAEGG EggUserData : public TypedReferenceCount { +class EXPCL_PANDA_EGG EggUserData : public TypedReferenceCount { PUBLISHED: INLINE EggUserData(); INLINE EggUserData(const EggUserData ©); diff --git a/panda/src/egg/eggUtilities.I b/panda/src/egg/eggUtilities.I index 04430db8f5..4efae4df81 100644 --- a/panda/src/egg/eggUtilities.I +++ b/panda/src/egg/eggUtilities.I @@ -57,7 +57,7 @@ split_vertex(EggVertex *vert, const FunctionObject &sequence) { typedef pvector Prims; Prims prims; prims.reserve(vert->pref_size()); - copy(vert->pref_begin(), vert->pref_end(), back_inserter(prims)); + std::copy(vert->pref_begin(), vert->pref_end(), std::back_inserter(prims)); // Now walk through the list of primitives that reference this vertex. Prims::const_iterator pri; @@ -69,7 +69,7 @@ split_vertex(EggVertex *vert, const FunctionObject &sequence) { if (seq != 0) { // Here's a new sequence number! Have we already defined it? - EggVertex *new_vert = NULL; + EggVertex *new_vert = nullptr; Sequences::const_iterator si = _sequences.find(seq); diff --git a/panda/src/egg/eggVertex.cxx b/panda/src/egg/eggVertex.cxx index 7663fd4eb3..cebf9608e7 100644 --- a/panda/src/egg/eggVertex.cxx +++ b/panda/src/egg/eggVertex.cxx @@ -26,6 +26,9 @@ #include #include +using std::ostream; +using std::string; + TypeHandle EggVertex::_type_handle; @@ -34,7 +37,7 @@ TypeHandle EggVertex::_type_handle; */ EggVertex:: EggVertex() { - _pool = NULL; + _pool = nullptr; _forward_reference = false; _index = -1; _external_index = -1; @@ -59,7 +62,7 @@ EggVertex(const EggVertex ©) _uv_map(copy._uv_map), _aux_map(copy._aux_map) { - _pool = NULL; + _pool = nullptr; _forward_reference = false; _index = -1; test_pref_integrity(); @@ -96,7 +99,7 @@ EggVertex:: ~EggVertex() { // We should never destruct a vertex while it still thinks it belongs to a // VertexPool. If we do, we've probably lost a reference count somewhere. - nassertv(_pool == NULL); + nassertv(_pool == nullptr); // Also, a vertex shouldn't be destructed while it's being referenced by a // group or a primitive, for the same reason. @@ -244,7 +247,7 @@ get_uv_obj(const string &name) const { if (ui != _uv_map.end()) { return (*ui).second; } - return NULL; + return nullptr; } /** @@ -259,7 +262,7 @@ get_aux_obj(const string &name) const { if (xi != _aux_map.end()) { return (*xi).second; } - return NULL; + return nullptr; } /** @@ -278,7 +281,7 @@ modify_uv_obj(const string &name) { return (*ui).second; } - return NULL; + return nullptr; } /** @@ -297,7 +300,7 @@ modify_aux_obj(const string &name) { return (*xi).second; } - return NULL; + return nullptr; } /** @@ -346,12 +349,12 @@ clear_aux(const string &name) { PT(EggVertex) EggVertex:: make_average(const EggVertex *first, const EggVertex *second) { PT(EggVertexPool) pool = first->get_pool(); - nassertr(pool == second->get_pool(), NULL); + nassertr(pool == second->get_pool(), nullptr); // If both vertices are in a pool, the new vertex will be part of the pool // as well. PT(EggVertex) middle; - if (pool == NULL) { + if (pool == nullptr) { middle = new EggVertex; } else { middle = pool->make_new_vertex(); @@ -375,7 +378,7 @@ make_average(const EggVertex *first, const EggVertex *second) { const EggVertexUV *first_uv = it->second; const EggVertexUV *second_uv = second->get_uv_obj(it->first); - if (first_uv != NULL && second_uv != NULL) { + if (first_uv != nullptr && second_uv != nullptr) { middle->set_uv_obj(EggVertexUV::make_average(first_uv, second_uv)); } } @@ -386,7 +389,7 @@ make_average(const EggVertex *first, const EggVertex *second) { const EggVertexAux *first_aux = ai->second; const EggVertexAux *second_aux = second->get_aux_obj(ai->first); - if (first_aux != NULL && second_aux != NULL) { + if (first_aux != nullptr && second_aux != nullptr) { middle->set_aux_obj(EggVertexAux::make_average(first_aux, second_aux)); } } @@ -755,7 +758,7 @@ copy_grefs_from(const EggVertex &other) { for (gri = other.gref_begin(); gri != other.gref_end(); ++gri) { EggGroup *group = *gri; - nassertv(group != NULL); + nassertv(group != nullptr); group->ref_vertex(this, group->get_vertex_membership(&other)); } @@ -771,7 +774,7 @@ clear_grefs() { GroupRef::const_iterator gri; for (gri = gref_copy.begin(); gri != gref_copy.end(); ++gri) { EggGroup *group = *gri; - nassertv(group != NULL); + nassertv(group != nullptr); group->unref_vertex(this); } @@ -836,7 +839,7 @@ test_gref_integrity() const { for (gri = gref_begin(); gri != gref_end(); ++gri) { EggGroup *group = *gri; - nassertv(group != NULL); + nassertv(group != nullptr); group->test_ref_count_integrity(); double membership = group->get_vertex_membership(this); @@ -856,7 +859,7 @@ test_pref_integrity() const { for (pri = pref_begin(); pri != pref_end(); ++pri) { EggPrimitive *prim = *pri; - nassertv(prim != NULL); + nassertv(prim != nullptr); prim->test_ref_count_integrity(); EggPrimitive::iterator vi; @@ -872,7 +875,7 @@ test_pref_integrity() const { */ void EggVertex:: output(ostream &out) const { - if (get_pool() == NULL) { + if (get_pool() == nullptr) { out << "(null):" << get_index(); } else { out << get_pool()->get_name() << ":" << get_index(); diff --git a/panda/src/egg/eggVertex.h b/panda/src/egg/eggVertex.h index 4bbbd773d1..55dbc8a3d3 100644 --- a/panda/src/egg/eggVertex.h +++ b/panda/src/egg/eggVertex.h @@ -36,12 +36,12 @@ class EggPrimitive; * Any one-, two-, three-, or four-component vertex, possibly with attributes * such as a normal. */ -class EXPCL_PANDAEGG EggVertex : public EggObject, public EggAttributes { +class EXPCL_PANDA_EGG EggVertex : public EggObject, public EggAttributes { public: typedef pset GroupRef; typedef pmultiset PrimitiveRef; - typedef pmap< string, PT(EggVertexUV) > UVMap; - typedef pmap< string, PT(EggVertexAux) > AuxMap; + typedef pmap< std::string, PT(EggVertexUV) > UVMap; + typedef pmap< std::string, PT(EggVertexAux) > AuxMap; typedef second_of_pair_iterator uv_iterator; typedef uv_iterator const_uv_iterator; @@ -85,26 +85,26 @@ PUBLISHED: INLINE LTexCoordd get_uv() const; INLINE void set_uv(const LTexCoordd &texCoord); INLINE void clear_uv(); - bool has_uv(const string &name) const; - bool has_uvw(const string &name) const; - LTexCoordd get_uv(const string &name) const; - const LTexCoord3d &get_uvw(const string &name) const; - void set_uv(const string &name, const LTexCoordd &texCoord); - void set_uvw(const string &name, const LTexCoord3d &texCoord); - const EggVertexUV *get_uv_obj(const string &name) const; - EggVertexUV *modify_uv_obj(const string &name); + bool has_uv(const std::string &name) const; + bool has_uvw(const std::string &name) const; + LTexCoordd get_uv(const std::string &name) const; + const LTexCoord3d &get_uvw(const std::string &name) const; + void set_uv(const std::string &name, const LTexCoordd &texCoord); + void set_uvw(const std::string &name, const LTexCoord3d &texCoord); + const EggVertexUV *get_uv_obj(const std::string &name) const; + EggVertexUV *modify_uv_obj(const std::string &name); void set_uv_obj(EggVertexUV *vertex_uv); - void clear_uv(const string &name); + void clear_uv(const std::string &name); INLINE bool has_aux() const; INLINE void clear_aux(); - bool has_aux(const string &name) const; - const LVecBase4d &get_aux(const string &name) const; - void set_aux(const string &name, const LVecBase4d &aux); - const EggVertexAux *get_aux_obj(const string &name) const; - EggVertexAux *modify_aux_obj(const string &name); + bool has_aux(const std::string &name) const; + const LVecBase4d &get_aux(const std::string &name) const; + void set_aux(const std::string &name, const LVecBase4d &aux); + const EggVertexAux *get_aux_obj(const std::string &name) const; + EggVertexAux *modify_aux_obj(const std::string &name); void set_aux_obj(EggVertexAux *vertex_aux); - void clear_aux(const string &name); + void clear_aux(const std::string &name); static PT(EggVertex) make_average(const EggVertex *first, const EggVertex *second); @@ -126,7 +126,7 @@ PUBLISHED: INLINE void set_external_index2(int external_index2); INLINE int get_external_index2() const; - void write(ostream &out, int indent_level) const; + void write(std::ostream &out, int indent_level) const; INLINE bool sorts_less_than(const EggVertex &other) const; int compare_to(const EggVertex &other) const; @@ -160,7 +160,7 @@ PUBLISHED: void test_pref_integrity() const { } #endif // _DEBUG - void output(ostream &out) const; + void output(std::ostream &out) const; EggMorphVertexList _dxyzs; @@ -201,7 +201,7 @@ private: friend class EggPrimitive; }; -INLINE ostream &operator << (ostream &out, const EggVertex &vert) { +INLINE std::ostream &operator << (std::ostream &out, const EggVertex &vert) { vert.output(out); return out; } @@ -211,7 +211,7 @@ INLINE ostream &operator << (ostream &out, const EggVertex &vert) { * Returns true if the two referenced EggVertex pointers are in sorted order, * false otherwise. */ -class EXPCL_PANDAEGG UniqueEggVertices { +class EXPCL_PANDA_EGG UniqueEggVertices { public: INLINE bool operator ()(const EggVertex *v1, const EggVertex *v2) const; }; diff --git a/panda/src/egg/eggVertexAux.I b/panda/src/egg/eggVertexAux.I index 40a41e26ac..0ff1966d46 100644 --- a/panda/src/egg/eggVertexAux.I +++ b/panda/src/egg/eggVertexAux.I @@ -15,7 +15,7 @@ * */ INLINE void EggVertexAux:: -set_name(const string &name) { +set_name(const std::string &name) { Namable::set_name(name); } diff --git a/panda/src/egg/eggVertexAux.cxx b/panda/src/egg/eggVertexAux.cxx index ec6528e380..b421c527f6 100644 --- a/panda/src/egg/eggVertexAux.cxx +++ b/panda/src/egg/eggVertexAux.cxx @@ -22,7 +22,7 @@ TypeHandle EggVertexAux::_type_handle; * */ EggVertexAux:: -EggVertexAux(const string &name, const LVecBase4d &aux) : +EggVertexAux(const std::string &name, const LVecBase4d &aux) : EggNamedObject(name), _aux(aux) { @@ -62,7 +62,7 @@ EggVertexAux:: */ PT(EggVertexAux) EggVertexAux:: make_average(const EggVertexAux *first, const EggVertexAux *second) { - nassertr(first->get_name() == second->get_name(), NULL); + nassertr(first->get_name() == second->get_name(), nullptr); LVecBase4d aux = (first->_aux + second->_aux) / 2; return new EggVertexAux(first->get_name(), aux); @@ -72,8 +72,8 @@ make_average(const EggVertexAux *first, const EggVertexAux *second) { * */ void EggVertexAux:: -write(ostream &out, int indent_level) const { - string inline_name = get_name(); +write(std::ostream &out, int indent_level) const { + std::string inline_name = get_name(); if (!inline_name.empty()) { inline_name += ' '; } diff --git a/panda/src/egg/eggVertexAux.h b/panda/src/egg/eggVertexAux.h index b0338cdec3..db8bb67ccc 100644 --- a/panda/src/egg/eggVertexAux.h +++ b/panda/src/egg/eggVertexAux.h @@ -27,14 +27,14 @@ * the vertex data, but will not otherwise interpret it. Presumably, a shader * will process the data later. */ -class EXPCL_PANDAEGG EggVertexAux : public EggNamedObject { +class EXPCL_PANDA_EGG EggVertexAux : public EggNamedObject { PUBLISHED: - explicit EggVertexAux(const string &name, const LVecBase4d &aux); + explicit EggVertexAux(const std::string &name, const LVecBase4d &aux); EggVertexAux(const EggVertexAux ©); EggVertexAux &operator = (const EggVertexAux ©); virtual ~EggVertexAux(); - INLINE void set_name(const string &name); + INLINE void set_name(const std::string &name); INLINE const LVecBase4d &get_aux() const; INLINE void set_aux(const LVecBase4d &aux); @@ -42,7 +42,7 @@ PUBLISHED: static PT(EggVertexAux) make_average(const EggVertexAux *first, const EggVertexAux *second); - void write(ostream &out, int indent_level) const; + void write(std::ostream &out, int indent_level) const; int compare_to(const EggVertexAux &other) const; private: diff --git a/panda/src/egg/eggVertexPool.I b/panda/src/egg/eggVertexPool.I index 3a13278063..8e26c30fb7 100644 --- a/panda/src/egg/eggVertexPool.I +++ b/panda/src/egg/eggVertexPool.I @@ -17,7 +17,7 @@ */ INLINE bool EggVertexPool:: has_vertex(int index) const { - return get_vertex(index) != (EggVertex *)NULL; + return get_vertex(index) != nullptr; } /** diff --git a/panda/src/egg/eggVertexPool.cxx b/panda/src/egg/eggVertexPool.cxx index f1783d8158..8fa3b5e637 100644 --- a/panda/src/egg/eggVertexPool.cxx +++ b/panda/src/egg/eggVertexPool.cxx @@ -20,6 +20,8 @@ #include +using std::string; + TypeHandle EggVertexPool::_type_handle; /** @@ -63,7 +65,7 @@ EggVertexPool:: nassertv(vertex->_pool == this); nassertv(vertex->get_index() == index); - vertex->_pool = NULL; + vertex->_pool = nullptr; vertex->_index = -1; } @@ -114,11 +116,11 @@ get_vertex(int index) const { IndexVertices::const_iterator ivi = _index_vertices.find(index); if (ivi == _index_vertices.end()) { - return NULL; + return nullptr; } else { EggVertex *vertex = (*ivi).second; if (vertex->is_forward_reference()) { - return NULL; + return nullptr; } return vertex; } @@ -133,7 +135,7 @@ get_vertex(int index) const { */ EggVertex *EggVertexPool:: get_forward_vertex(int index) { - nassertr(index >= 0, NULL); + nassertr(index >= 0, nullptr); IndexVertices::const_iterator ivi = _index_vertices.find(index); @@ -176,7 +178,7 @@ get_num_dimensions() const { IndexVertices::const_iterator ivi; for (ivi = _index_vertices.begin(); ivi != _index_vertices.end(); ++ivi) { EggVertex *vertex = (*ivi).second; - num_dimensions = max(num_dimensions, vertex->get_num_dimensions()); + num_dimensions = std::max(num_dimensions, vertex->get_num_dimensions()); } return num_dimensions; @@ -421,13 +423,13 @@ add_vertex(EggVertex *vertex, int index) { PT(EggVertex) vertex_keep = vertex; // Don't try to add a vertex while it still belongs to another pool. - nassertr(vertex->_pool == NULL, NULL); + nassertr(vertex->_pool == nullptr, nullptr); if (index == -1) { index = get_highest_index() + 1; } // Always supply an index number >= 0. - nassertr(index >= 0, NULL); + nassertr(index >= 0, nullptr); // Check for a forward reference. IndexVertices::const_iterator ivi = _index_vertices.find(index); @@ -438,19 +440,19 @@ add_vertex(EggVertex *vertex, int index) { !vertex->is_forward_reference()) { (*orig_vertex) = (*vertex); orig_vertex->_forward_reference = false; - _highest_index = max(_highest_index, index); + _highest_index = std::max(_highest_index, index); return orig_vertex; } // Oops, you duplicated a vertex index. - nassertr(false, NULL); + nassertr(false, nullptr); } _unique_vertices.insert(vertex); _index_vertices[index] = vertex; if (!vertex->is_forward_reference()) { - _highest_index = max(_highest_index, index); + _highest_index = std::max(_highest_index, index); } vertex->_pool = this; @@ -495,7 +497,7 @@ find_matching_vertex(const EggVertex ©) { } // No matching vertex. - return NULL; + return nullptr; } @@ -550,7 +552,7 @@ remove_vertex(EggVertex *vertex) { _unique_vertices.erase(uvi); - vertex->_pool = NULL; + vertex->_pool = nullptr; } /** @@ -572,7 +574,7 @@ remove_unused_vertices() { if (vertex->pref_size() == 0) { // This vertex is not used. Don't add it to the new lists. vertex->clear_grefs(); - vertex->_pool = NULL; + vertex->_pool = nullptr; num_removed++; } else { @@ -598,7 +600,7 @@ remove_unused_vertices() { orig_vertex->test_pref_integrity(); nassertr(vertex->pref_size() == 0, 0); vertex->clear_grefs(); - vertex->_pool = NULL; + vertex->_pool = nullptr; num_removed++; } else { @@ -675,7 +677,7 @@ transform(const LMatrix4d &mat) { typedef pvector Verts; Verts verts; verts.reserve(size()); - copy(begin(), end(), back_inserter(verts)); + std::copy(begin(), end(), std::back_inserter(verts)); Verts::const_iterator vi; for (vi = verts.begin(); vi != verts.end(); ++vi) { @@ -742,7 +744,7 @@ sort_by_external_index() { sorted_vertices.push_back(*i); } - ::sort(sorted_vertices.begin(), sorted_vertices.end(), SortByExternalIndex()); + std::sort(sorted_vertices.begin(), sorted_vertices.end(), SortByExternalIndex()); // Now reassign the indices, and copy them into a new index map. IndexVertices new_index_vertices; @@ -761,7 +763,7 @@ sort_by_external_index() { * Writes the vertex pool to the indicated output stream in Egg format. */ void EggVertexPool:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { write_header(out, indent_level, ""); iterator i; diff --git a/panda/src/egg/eggVertexPool.h b/panda/src/egg/eggVertexPool.h index 2b44ad38d2..8ee26fa35b 100644 --- a/panda/src/egg/eggVertexPool.h +++ b/panda/src/egg/eggVertexPool.h @@ -38,7 +38,7 @@ * list. The list may also be operated on (read-only) via iterators and * begin()/end(). */ -class EXPCL_PANDAEGG EggVertexPool : public EggNode { +class EXPCL_PANDA_EGG EggVertexPool : public EggNode { // This is a bit of private interface stuff that must be here as a forward // reference. This allows us to define the EggVertexPool as an STL @@ -65,7 +65,7 @@ public: // Here begins the actual public interface to EggVertexPool. PUBLISHED: - explicit EggVertexPool(const string &name); + explicit EggVertexPool(const std::string &name); EggVertexPool(const EggVertexPool ©); ~EggVertexPool(); @@ -129,7 +129,7 @@ PUBLISHED: void transform(const LMatrix4d &mat); void sort_by_external_index(); - void write(ostream &out, int indent_level) const; + void write(std::ostream &out, int indent_level) const; protected: virtual void r_transform(const LMatrix4d &mat, const LMatrix4d &inv, diff --git a/panda/src/egg/eggVertexUV.I b/panda/src/egg/eggVertexUV.I index 4eb9983d21..05f6f8609f 100644 --- a/panda/src/egg/eggVertexUV.I +++ b/panda/src/egg/eggVertexUV.I @@ -16,10 +16,10 @@ * Usually this is the same string that is input, but for historical reasons * the texture coordinate name "default" is mapped to the empty string. */ -INLINE string EggVertexUV:: -filter_name(const string &name) { +INLINE std::string EggVertexUV:: +filter_name(const std::string &name) { if (name == "default") { - return string(); + return std::string(); } return name; } @@ -28,7 +28,7 @@ filter_name(const string &name) { * */ INLINE void EggVertexUV:: -set_name(const string &name) { +set_name(const std::string &name) { Namable::set_name(filter_name(name)); } diff --git a/panda/src/egg/eggVertexUV.cxx b/panda/src/egg/eggVertexUV.cxx index ded4e39dd0..49a3c39ace 100644 --- a/panda/src/egg/eggVertexUV.cxx +++ b/panda/src/egg/eggVertexUV.cxx @@ -22,7 +22,7 @@ TypeHandle EggVertexUV::_type_handle; * */ EggVertexUV:: -EggVertexUV(const string &name, const LTexCoordd &uv) : +EggVertexUV(const std::string &name, const LTexCoordd &uv) : EggNamedObject(name), _flags(0), _uvw(uv[0], uv[1], 0.0) @@ -36,7 +36,7 @@ EggVertexUV(const string &name, const LTexCoordd &uv) : * */ EggVertexUV:: -EggVertexUV(const string &name, const LTexCoord3d &uvw) : +EggVertexUV(const std::string &name, const LTexCoord3d &uvw) : EggNamedObject(name), _flags(F_has_w), _uvw(uvw) @@ -88,7 +88,7 @@ EggVertexUV:: */ PT(EggVertexUV) EggVertexUV:: make_average(const EggVertexUV *first, const EggVertexUV *second) { - nassertr(first->get_name() == second->get_name(), NULL); + nassertr(first->get_name() == second->get_name(), nullptr); int flags = first->_flags & second->_flags; LTexCoord3d uvw = (first->_uvw + second->_uvw) / 2; @@ -124,8 +124,8 @@ transform(const LMatrix4d &mat) { * */ void EggVertexUV:: -write(ostream &out, int indent_level) const { - string inline_name = get_name(); +write(std::ostream &out, int indent_level) const { + std::string inline_name = get_name(); if (!inline_name.empty()) { inline_name += ' '; } diff --git a/panda/src/egg/eggVertexUV.h b/panda/src/egg/eggVertexUV.h index 21b6e5b7c2..2ab0447639 100644 --- a/panda/src/egg/eggVertexUV.h +++ b/panda/src/egg/eggVertexUV.h @@ -26,16 +26,16 @@ * multitexturing, there may be multiple sets of UV's on a particular vertex, * each with its own name. */ -class EXPCL_PANDAEGG EggVertexUV : public EggNamedObject { +class EXPCL_PANDA_EGG EggVertexUV : public EggNamedObject { PUBLISHED: - explicit EggVertexUV(const string &name, const LTexCoordd &uv); - explicit EggVertexUV(const string &name, const LTexCoord3d &uvw); + explicit EggVertexUV(const std::string &name, const LTexCoordd &uv); + explicit EggVertexUV(const std::string &name, const LTexCoord3d &uvw); EggVertexUV(const EggVertexUV ©); EggVertexUV &operator = (const EggVertexUV ©); virtual ~EggVertexUV(); - INLINE static string filter_name(const string &name); - INLINE void set_name(const string &name); + INLINE static std::string filter_name(const std::string &name); + INLINE void set_name(const std::string &name); INLINE int get_num_dimensions() const; INLINE bool has_w() const; @@ -59,7 +59,7 @@ PUBLISHED: void transform(const LMatrix4d &mat); - void write(ostream &out, int indent_level) const; + void write(std::ostream &out, int indent_level) const; int compare_to(const EggVertexUV &other) const; EggMorphTexCoordList _duvs; diff --git a/panda/src/egg/eggXfmAnimData.I b/panda/src/egg/eggXfmAnimData.I index 41bbaaa103..92a888a3c6 100644 --- a/panda/src/egg/eggXfmAnimData.I +++ b/panda/src/egg/eggXfmAnimData.I @@ -15,7 +15,7 @@ * */ INLINE EggXfmAnimData:: -EggXfmAnimData(const string &name, CoordinateSystem cs) : EggAnimData(name) { +EggXfmAnimData(const std::string &name, CoordinateSystem cs) : EggAnimData(name) { _coordsys = cs; } @@ -50,7 +50,7 @@ operator = (const EggXfmAnimData ©) { * */ INLINE void EggXfmAnimData:: -set_order(const string &order) { +set_order(const std::string &order) { _order = order; } @@ -73,7 +73,7 @@ has_order() const { /** * */ -INLINE const string &EggXfmAnimData:: +INLINE const std::string &EggXfmAnimData:: get_order() const { if (has_order()) { return _order; @@ -87,7 +87,7 @@ get_order() const { * the order string must be set to in order to use set_value() or add_data() * successfully. */ -INLINE const string &EggXfmAnimData:: +INLINE const std::string &EggXfmAnimData:: get_standard_order() { return EggXfmSAnim::get_standard_order(); } @@ -97,7 +97,7 @@ get_standard_order() { * */ INLINE void EggXfmAnimData:: -set_contents(const string &contents) { +set_contents(const std::string &contents) { _contents = contents; } @@ -120,7 +120,7 @@ has_contents() const { /** * */ -INLINE const string &EggXfmAnimData:: +INLINE const std::string &EggXfmAnimData:: get_contents() const { return _contents; } diff --git a/panda/src/egg/eggXfmAnimData.cxx b/panda/src/egg/eggXfmAnimData.cxx index 62ed89f1c3..73a7128036 100644 --- a/panda/src/egg/eggXfmAnimData.cxx +++ b/panda/src/egg/eggXfmAnimData.cxx @@ -164,7 +164,7 @@ is_anim_matrix() const { * Writes the data to the indicated output stream in Egg format. */ void EggXfmAnimData:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { write_header(out, indent_level, ""); if (has_fps()) { diff --git a/panda/src/egg/eggXfmAnimData.h b/panda/src/egg/eggXfmAnimData.h index dac7762931..1fdaec39fe 100644 --- a/panda/src/egg/eggXfmAnimData.h +++ b/panda/src/egg/eggXfmAnimData.h @@ -26,25 +26,25 @@ * is an older syntax of egg anim table, not often used currently--it's * replaced by EggXfmSAnim. */ -class EXPCL_PANDAEGG EggXfmAnimData : public EggAnimData { +class EXPCL_PANDA_EGG EggXfmAnimData : public EggAnimData { PUBLISHED: - INLINE explicit EggXfmAnimData(const string &name = "", + INLINE explicit EggXfmAnimData(const std::string &name = "", CoordinateSystem cs = CS_default); EggXfmAnimData(const EggXfmSAnim &convert_from); INLINE EggXfmAnimData(const EggXfmAnimData ©); INLINE EggXfmAnimData &operator = (const EggXfmAnimData ©); - INLINE void set_order(const string &order); + INLINE void set_order(const std::string &order); INLINE void clear_order(); INLINE bool has_order() const; - INLINE const string &get_order() const; - INLINE static const string &get_standard_order(); + INLINE const std::string &get_order() const; + INLINE static const std::string &get_standard_order(); - INLINE void set_contents(const string &contents); + INLINE void set_contents(const std::string &contents); INLINE void clear_contents(); INLINE bool has_contents() const; - INLINE const string &get_contents() const; + INLINE const std::string &get_contents() const; INLINE CoordinateSystem get_coordinate_system() const; @@ -55,7 +55,7 @@ PUBLISHED: void get_value(int row, LMatrix4d &mat) const; virtual bool is_anim_matrix() const; - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; protected: virtual void r_transform(const LMatrix4d &mat, const LMatrix4d &inv, @@ -63,8 +63,8 @@ protected: virtual void r_mark_coordsys(CoordinateSystem cs); private: - string _order; - string _contents; + std::string _order; + std::string _contents; CoordinateSystem _coordsys; public: diff --git a/panda/src/egg/eggXfmSAnim.I b/panda/src/egg/eggXfmSAnim.I index a16a7ef2cb..62ba430096 100644 --- a/panda/src/egg/eggXfmSAnim.I +++ b/panda/src/egg/eggXfmSAnim.I @@ -15,7 +15,7 @@ * */ INLINE EggXfmSAnim:: -EggXfmSAnim(const string &name, CoordinateSystem cs) : EggGroupNode(name) { +EggXfmSAnim(const std::string &name, CoordinateSystem cs) : EggGroupNode(name) { _has_fps = false; _coordsys = cs; } @@ -88,7 +88,7 @@ get_fps() const { * */ INLINE void EggXfmSAnim:: -set_order(const string &order) { +set_order(const std::string &order) { _order = order; } @@ -111,7 +111,7 @@ has_order() const { /** * */ -INLINE const string &EggXfmSAnim:: +INLINE const std::string &EggXfmSAnim:: get_order() const { if (has_order()) { return _order; @@ -125,7 +125,7 @@ get_order() const { * the order string must be set to in order to use set_value() or add_data() * successfully. */ -INLINE const string &EggXfmSAnim:: +INLINE const std::string &EggXfmSAnim:: get_standard_order() { return _standard_order; } diff --git a/panda/src/egg/eggXfmSAnim.cxx b/panda/src/egg/eggXfmSAnim.cxx index 167cb531b7..43a784b33f 100644 --- a/panda/src/egg/eggXfmSAnim.cxx +++ b/panda/src/egg/eggXfmSAnim.cxx @@ -23,6 +23,8 @@ #include +using std::string; + TypeHandle EggXfmSAnim::_type_handle; const string EggXfmSAnim::_standard_order = "srpht"; @@ -73,7 +75,7 @@ optimize() { // default value. double value = sanim->get_value(0); double default_value; - if (sanim->has_name() && strchr("ijk", sanim->get_name()[0]) != NULL) { + if (sanim->has_name() && strchr("ijk", sanim->get_name()[0]) != nullptr) { default_value = 1.0; } else { default_value = 0.0; @@ -138,7 +140,7 @@ is_anim_matrix() const { * Writes the data to the indicated output stream in Egg format. */ void EggXfmSAnim:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { test_under_integrity(); write_header(out, indent_level, ""); @@ -169,10 +171,10 @@ write(ostream &out, int indent_level) const { nassertv(sanim->get_name().length() == 1); char name = sanim->get_name()[0]; char *p = (char *)strchr(matrix_component_letters, name); - nassertv(p != (char *)NULL); - if (p != (char *)NULL) { + nassertv(p != nullptr); + if (p != nullptr) { int index = p - matrix_component_letters; - nassertv(tables[index] == (EggSAnimData *)NULL); + nassertv(tables[index] == nullptr); tables[index] = sanim; } } else { @@ -183,7 +185,7 @@ write(ostream &out, int indent_level) const { // Now write out the table children in our normal order. for (int i = 0; i < num_matrix_components; i++) { - if (tables[i] != (EggSAnimData *)NULL) { + if (tables[i] != nullptr) { tables[i]->write(out, indent_level + 2); } } @@ -271,7 +273,7 @@ get_num_rows() const { min_rows = sanim->get_num_rows(); } else { - min_rows = min(min_rows, sanim->get_num_rows()); + min_rows = std::min(min_rows, sanim->get_num_rows()); } } } @@ -400,7 +402,7 @@ set_value(int row, const LMatrix4d &mat) { for (int i = 0; i < num_matrix_components; i++) { string name(1, matrix_component_letters[i]); EggNode *child = find_child(name); - nassertr(child != (EggNode *)NULL && + nassertr(child != nullptr && child->is_of_type(EggSAnimData::get_class_type()), false); EggSAnimData *sanim = DCAST(EggSAnimData, child); @@ -495,7 +497,7 @@ add_data(const LMatrix4d &mat) { for (int i = 0; i < num_matrix_components; i++) { string name(1, matrix_component_letters[i]); EggNode *child = find_child(name); - nassertr(child != (EggNode *)NULL && + nassertr(child != nullptr && child->is_of_type(EggSAnimData::get_class_type()), false); EggSAnimData *sanim = DCAST(EggSAnimData, child); @@ -553,7 +555,7 @@ void EggXfmSAnim:: add_component_data(const string &component_name, double value) { EggNode *child = find_child(component_name); EggSAnimData *sanim; - if (child == (EggNode *)NULL) { + if (child == nullptr) { // We don't have this component yet; create it. sanim = new EggSAnimData(component_name); add_child(sanim); diff --git a/panda/src/egg/eggXfmSAnim.h b/panda/src/egg/eggXfmSAnim.h index eae0349559..1fd37c51ad 100644 --- a/panda/src/egg/eggXfmSAnim.h +++ b/panda/src/egg/eggXfmSAnim.h @@ -25,9 +25,9 @@ class EggXfmAnimData; * It's implemented as a group that can contain any number of EggSAnimData * children. */ -class EXPCL_PANDAEGG EggXfmSAnim : public EggGroupNode { +class EXPCL_PANDA_EGG EggXfmSAnim : public EggGroupNode { PUBLISHED: - INLINE explicit EggXfmSAnim(const string &name = "", + INLINE explicit EggXfmSAnim(const std::string &name = "", CoordinateSystem cs = CS_default); EggXfmSAnim(const EggXfmAnimData &convert_from); @@ -39,11 +39,11 @@ PUBLISHED: INLINE bool has_fps() const; INLINE double get_fps() const; - INLINE void set_order(const string &order); + INLINE void set_order(const std::string &order); INLINE void clear_order(); INLINE bool has_order() const; - INLINE const string &get_order() const; - INLINE static const string &get_standard_order(); + INLINE const std::string &get_order() const; + INLINE static const std::string &get_standard_order(); INLINE CoordinateSystem get_coordinate_system() const; @@ -57,18 +57,18 @@ PUBLISHED: INLINE void clear_data(); bool add_data(const LMatrix4d &mat); - void add_component_data(const string &component_name, double value); + void add_component_data(const std::string &component_name, double value); void add_component_data(int component, double value); virtual bool is_anim_matrix() const; - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; static void compose_with_order(LMatrix4d &mat, const LVecBase3d &scale, const LVecBase3d &shear, const LVecBase3d &hpr, const LVecBase3d &trans, - const string &order, + const std::string &order, CoordinateSystem cs); protected: @@ -84,10 +84,10 @@ private: private: double _fps; bool _has_fps; - string _order; + std::string _order; CoordinateSystem _coordsys; - static const string _standard_order; + static const std::string _standard_order; public: diff --git a/panda/src/egg/lexer.cxx.prebuilt b/panda/src/egg/lexer.cxx.prebuilt index 6f6e8bd56a..9e412bce1f 100644 --- a/panda/src/egg/lexer.cxx.prebuilt +++ b/panda/src/egg/lexer.cxx.prebuilt @@ -963,6 +963,10 @@ char *eggyytext; #include +using std::istream; +using std::ostream; +using std::string; + extern "C" int eggyywrap(void); // declared below. static int yyinput(void); // declared by flex. @@ -1062,17 +1066,17 @@ eggyyerror(const string &msg) { } out << " at line " << line_number << ", column " << col_number << ":\n" - << setiosflags(Notify::get_literal_flag()) + << std::setiosflags(Notify::get_literal_flag()) << current_line << "\n"; indent(out, col_number-1) << "^\n" << msg << "\n\n" - << resetiosflags(Notify::get_literal_flag()) << flush; + << std::resetiosflags(Notify::get_literal_flag()) << std::flush; } error_count++; } void -eggyyerror(ostringstream &strm) { +eggyyerror(std::ostringstream &strm) { string s = strm.str(); eggyyerror(s); } @@ -1088,18 +1092,18 @@ eggyywarning(const string &msg) { } out << " at line " << line_number << ", column " << col_number << ":\n" - << setiosflags(Notify::get_literal_flag()) + << std::setiosflags(Notify::get_literal_flag()) << current_line << "\n"; indent(out, col_number-1) << "^\n" << msg << "\n\n" - << resetiosflags(Notify::get_literal_flag()) << flush; + << std::resetiosflags(Notify::get_literal_flag()) << std::flush; } warning_count++; } void -eggyywarning(ostringstream &strm) { - string s = strm.str(); +eggyywarning(std::ostringstream &strm) { + std::string s = strm.str(); eggyywarning(s); } @@ -1117,7 +1121,7 @@ input_chars(char *buffer, int &result, int max_size) { // from the stream, copy it into the current_line array. This // is because the \n.* rule below, which fills current_line // normally, doesn't catch the first line. - int length = min(max_error_width, result); + int length = std::min(max_error_width, result); strncpy(current_line, buffer, length); current_line[length] = '\0'; line_number++; @@ -1141,7 +1145,7 @@ input_chars(char *buffer, int &result, int max_size) { // Define this macro carefully, since different flex versions call it // with a different type for result. #define YY_INPUT(buffer, result, max_size) { \ - int int_result; \ + int int_result = 0; \ input_chars((buffer), int_result, (max_size)); \ (result) = int_result; \ } @@ -1212,10 +1216,10 @@ eat_c_comment() { c = read_char(line, col); while (c != EOF && !(last_c == '*' && c == '/')) { if (last_c == '/' && c == '*') { - ostringstream errmsg; + std::ostringstream errmsg; errmsg << "This comment contains a nested /* symbol at line " << line << ", column " << col-1 << "--possibly unclosed?" - << ends; + << std::ends; eggyywarning(errmsg); } last_c = c; diff --git a/panda/src/egg/lexer.lxx b/panda/src/egg/lexer.lxx index 1ce4a0006e..e88e5a388f 100644 --- a/panda/src/egg/lexer.lxx +++ b/panda/src/egg/lexer.lxx @@ -18,6 +18,10 @@ #include +using std::istream; +using std::ostream; +using std::string; + extern "C" int eggyywrap(void); // declared below. static int yyinput(void); // declared by flex. @@ -44,7 +48,7 @@ static int error_count = 0; static int warning_count = 0; // This is the pointer to the current input stream. -static istream *input_p = NULL; +static istream *input_p = nullptr; // This is the name of the egg file we're parsing. We keep it so we // can print it out for error messages. @@ -117,17 +121,17 @@ eggyyerror(const string &msg) { } out << " at line " << line_number << ", column " << col_number << ":\n" - << setiosflags(Notify::get_literal_flag()) + << std::setiosflags(Notify::get_literal_flag()) << current_line << "\n"; indent(out, col_number-1) << "^\n" << msg << "\n\n" - << resetiosflags(Notify::get_literal_flag()) << flush; + << std::resetiosflags(Notify::get_literal_flag()) << std::flush; } error_count++; } void -eggyyerror(ostringstream &strm) { +eggyyerror(std::ostringstream &strm) { string s = strm.str(); eggyyerror(s); } @@ -143,17 +147,17 @@ eggyywarning(const string &msg) { } out << " at line " << line_number << ", column " << col_number << ":\n" - << setiosflags(Notify::get_literal_flag()) + << std::setiosflags(Notify::get_literal_flag()) << current_line << "\n"; indent(out, col_number-1) << "^\n" << msg << "\n\n" - << resetiosflags(Notify::get_literal_flag()) << flush; + << std::resetiosflags(Notify::get_literal_flag()) << std::flush; } warning_count++; } void -eggyywarning(ostringstream &strm) { +eggyywarning(std::ostringstream &strm) { string s = strm.str(); eggyywarning(s); } @@ -162,7 +166,7 @@ eggyywarning(ostringstream &strm) { // stdio FILE pointer. This is flex-specific. static void input_chars(char *buffer, int &result, int max_size) { - nassertv(input_p != NULL); + nassertv(input_p != nullptr); if (*input_p) { input_p->read(buffer, max_size); result = input_p->gcount(); @@ -172,7 +176,7 @@ input_chars(char *buffer, int &result, int max_size) { // from the stream, copy it into the current_line array. This // is because the \n.* rule below, which fills current_line // normally, doesn't catch the first line. - int length = min(max_error_width, result); + int length = std::min(max_error_width, result); strncpy(current_line, buffer, length); current_line[length] = '\0'; line_number++; @@ -180,7 +184,7 @@ input_chars(char *buffer, int &result, int max_size) { // Truncate it at the newline. char *end = strchr(current_line, '\n'); - if (end != NULL) { + if (end != nullptr) { *end = '\0'; } } @@ -196,7 +200,7 @@ input_chars(char *buffer, int &result, int max_size) { // Define this macro carefully, since different flex versions call it // with a different type for result. #define YY_INPUT(buffer, result, max_size) { \ - int int_result; \ + int int_result = 0; \ input_chars((buffer), int_result, (max_size)); \ (result) = int_result; \ } @@ -267,10 +271,10 @@ eat_c_comment() { c = read_char(line, col); while (c != EOF && !(last_c == '*' && c == '/')) { if (last_c == '/' && c == '*') { - ostringstream errmsg; + std::ostringstream errmsg; errmsg << "This comment contains a nested /* symbol at line " << line << ", column " << col-1 << "--possibly unclosed?" - << ends; + << std::ends; eggyywarning(errmsg); } last_c = c; @@ -700,7 +704,7 @@ NUMERIC ([+-]?(([0-9]+[.]?)|([0-9]*[.][0-9]+))([eE][+-]?[0-9]+)?) {HEX} { // A hexadecimal integer number. accept(); - eggyylval._ulong = strtoul(yytext+2, NULL, 16); + eggyylval._ulong = strtoul(yytext+2, nullptr, 16); eggyylval._string = yytext; return EGG_ULONG; } @@ -708,7 +712,7 @@ NUMERIC ([+-]?(([0-9]+[.]?)|([0-9]*[.][0-9]+))([eE][+-]?[0-9]+)?) {BINARY} { // A binary integer number. accept(); - eggyylval._ulong = strtoul(yytext+2, NULL, 2); + eggyylval._ulong = strtoul(yytext+2, nullptr, 2); eggyylval._string = yytext; return EGG_ULONG; } @@ -717,7 +721,7 @@ NUMERIC ([+-]?(([0-9]+[.]?)|([0-9]*[.][0-9]+))([eE][+-]?[0-9]+)?) // not-a-number. These sometimes show up in egg files accidentally. accept(); memset(&eggyylval._number, 0, sizeof(eggyylval._number)); - *(unsigned long *)&eggyylval._number = strtoul(yytext+3, NULL, 0); + *(unsigned long *)&eggyylval._number = strtoul(yytext+3, nullptr, 0); eggyylval._string = yytext; return EGG_NUMBER; } diff --git a/panda/src/egg/lexerDefs.h b/panda/src/egg/lexerDefs.h index 0337830028..4e39cb0b10 100644 --- a/panda/src/egg/lexerDefs.h +++ b/panda/src/egg/lexerDefs.h @@ -20,18 +20,18 @@ #include -void egg_init_lexer(istream &in, const string &filename); +void egg_init_lexer(std::istream &in, const std::string &filename); void egg_start_group_body(); void egg_start_texture_body(); void egg_start_primitive_body(); int egg_error_count(); int egg_warning_count(); -void eggyyerror(const string &msg); -void eggyyerror(ostringstream &strm); +void eggyyerror(const std::string &msg); +void eggyyerror(std::ostringstream &strm); -void eggyywarning(const string &msg); -void eggyywarning(ostringstream &strm); +void eggyywarning(const std::string &msg); +void eggyywarning(std::ostringstream &strm); int eggyylex(); diff --git a/panda/src/egg/parser.cxx.prebuilt b/panda/src/egg/parser.cxx.prebuilt index 7791e8de4a..f9a81a30a5 100644 --- a/panda/src/egg/parser.cxx.prebuilt +++ b/panda/src/egg/parser.cxx.prebuilt @@ -129,6 +129,10 @@ #define YYINITDEPTH 1000 #define YYMAXDEPTH 1000 +using std::istream; +using std::ostringstream; +using std::string; + // We need a stack of EggObject pointers. Each time we encounter a // nested EggObject of some kind, we'll allocate a new one of these // and push it onto the stack. At any given time, the top of the @@ -3137,14 +3141,14 @@ yyreduce: if (vertex_index < 0) { ostringstream errmsg; errmsg << "Ignoring invalid vertex index " << vertex_index - << " in vertex pool " << pool->get_name() << ends; + << " in vertex pool " << pool->get_name() << std::ends; eggyywarning(errmsg); vertex_index = -1; } else if (pool->has_vertex(vertex_index)) { ostringstream errmsg; errmsg << "Ignoring duplicate vertex index " << vertex_index - << " in vertex pool " << pool->get_name() << ends; + << " in vertex pool " << pool->get_name() << std::ends; eggyywarning(errmsg); vertex_index = -1; } @@ -4055,7 +4059,7 @@ yyreduce: if (vertex == NULL) { ostringstream errmsg; errmsg << "No vertex " << index << " in pool " << pool->get_name() - << ends; + << std::ends; eggyyerror(errmsg); } else { group->ref_vertex(vertex, membership); @@ -4659,7 +4663,7 @@ yyreduce: if (vertex == NULL) { ostringstream errmsg; errmsg << "No vertex " << index << " in pool " << pool->get_name() - << ends; + << std::ends; eggyyerror(errmsg); } else { prim->add_vertex(vertex); diff --git a/panda/src/egg/parser.yxx b/panda/src/egg/parser.yxx index 02e83f18ec..1ffaa3a078 100644 --- a/panda/src/egg/parser.yxx +++ b/panda/src/egg/parser.yxx @@ -57,6 +57,10 @@ #define YYINITDEPTH 1000 #define YYMAXDEPTH 1000 +using std::istream; +using std::ostringstream; +using std::string; + // We need a stack of EggObject pointers. Each time we encounter a // nested EggObject of some kind, we'll allocate a new one of these // and push it onto the stack. At any given time, the top of the @@ -903,7 +907,7 @@ vertex_pool: VERTEXPOOL required_name { string name = $2; - EggVertexPool *pool = NULL; + EggVertexPool *pool = nullptr; VertexPools::const_iterator vpi = vertex_pools.find(name); if (vpi != vertex_pools.end()) { @@ -971,14 +975,14 @@ vertex: if (vertex_index < 0) { ostringstream errmsg; errmsg << "Ignoring invalid vertex index " << vertex_index - << " in vertex pool " << pool->get_name() << ends; + << " in vertex pool " << pool->get_name() << std::ends; eggyywarning(errmsg); vertex_index = -1; } else if (pool->has_vertex(vertex_index)) { ostringstream errmsg; errmsg << "Ignoring duplicate vertex index " << vertex_index - << " in vertex pool " << pool->get_name() << ends; + << " in vertex pool " << pool->get_name() << std::ends; eggyywarning(errmsg); vertex_index = -1; } @@ -1545,7 +1549,7 @@ group_body: EggGroup *group = DCAST(EggGroup, egg_stack.back()); if (group->get_group_type() != EggGroup::GT_instance) { eggyyerror(" valid only within "); - } else if ($4 != (EggObject *)NULL) { + } else if ($4 != nullptr) { group->add_group_ref(DCAST(EggGroup, $4)); } } @@ -1785,7 +1789,7 @@ matrix4_body: group_vertex_ref: VERTEXREF '{' integer_list group_vertex_membership REF '{' vertex_pool_name '}' '}' { - if ($7 != (EggVertexPool *)NULL) { + if ($7 != nullptr) { EggVertexPool *pool = DCAST(EggVertexPool, $7); EggGroup *group = DCAST(EggGroup, egg_stack.back()); PTA_double nums = $3; @@ -1794,10 +1798,10 @@ group_vertex_ref: for (int i = 0; i < (int)nums.size(); i++) { int index = (int)nums[i]; EggVertex *vertex = pool->get_forward_vertex(index); - if (vertex == NULL) { + if (vertex == nullptr) { ostringstream errmsg; errmsg << "No vertex " << index << " in pool " << pool->get_name() - << ends; + << std::ends; eggyyerror(errmsg); } else { group->ref_vertex(vertex, membership); @@ -2316,7 +2320,7 @@ nurbs_curve_body: primitive_tref_body: texture_name { - if ($1 != (EggTexture *)NULL) { + if ($1 != nullptr) { EggTexture *texture = DCAST(EggTexture, $1); DCAST(EggPrimitive, egg_stack.back())->add_texture(texture); } @@ -2333,7 +2337,7 @@ primitive_tref_body: primitive_texture_body: required_name { - EggTexture *texture = NULL; + EggTexture *texture = nullptr; // Defining a texture on-the-fly. Filename filename = $1; @@ -2345,7 +2349,7 @@ primitive_texture_body: texture = new EggTexture(tref_name, filename); textures[tref_name] = texture; - if (egg_top_node != NULL) { + if (egg_top_node != nullptr) { egg_top_node->add_child(texture); } @@ -2358,7 +2362,7 @@ primitive_texture_body: } } - nassertr(texture != NULL, 0); + nassertr(texture != nullptr, 0); DCAST(EggPrimitive, egg_stack.back())->add_texture(texture); } ; @@ -2373,7 +2377,7 @@ primitive_texture_body: primitive_material_body: material_name { - if ($1 != (EggMaterial *)NULL) { + if ($1 != nullptr) { EggMaterial *material = DCAST(EggMaterial, $1); DCAST(EggPrimitive, egg_stack.back())->set_material(material); } @@ -2466,7 +2470,7 @@ primitive_bface_body: primitive_vertex_ref: VERTEXREF '{' integer_list REF '{' vertex_pool_name '}' '}' { - if ($6 != (EggVertexPool *)NULL) { + if ($6 != nullptr) { EggVertexPool *pool = DCAST(EggVertexPool, $6); EggPrimitive *prim = DCAST(EggPrimitive, egg_stack.back()); PTA_double nums = $3; @@ -2474,10 +2478,10 @@ primitive_vertex_ref: for (int i = 0; i < (int)nums.size(); i++) { int index = (int)nums[i]; EggVertex *vertex = pool->get_forward_vertex(index); - if (vertex == NULL) { + if (vertex == nullptr) { ostringstream errmsg; errmsg << "No vertex " << index << " in pool " << pool->get_name() - << ends; + << std::ends; eggyyerror(errmsg); } else { prim->add_vertex(vertex); diff --git a/panda/src/egg/parserDefs.h b/panda/src/egg/parserDefs.h index b0938d567d..b20cba96db 100644 --- a/panda/src/egg/parserDefs.h +++ b/panda/src/egg/parserDefs.h @@ -29,7 +29,7 @@ class LightMutex; extern LightMutex egg_lock; -void egg_init_parser(istream &in, const string &filename, +void egg_init_parser(std::istream &in, const std::string &filename, EggObject *tos, EggGroupNode *egg_top_node); void egg_cleanup_parser(); @@ -40,11 +40,11 @@ void egg_cleanup_parser(); // that has member functions in a union), so we'll use a class instead. That // means we need to declare it externally, here. -class EXPCL_PANDAEGG EggTokenType { +class EXPCL_PANDA_EGG EggTokenType { public: double _number; unsigned long _ulong; - string _string; + std::string _string; PT(EggObject) _egg; PTA_double _number_list; }; diff --git a/panda/src/egg/pt_EggMaterial.h b/panda/src/egg/pt_EggMaterial.h index 7c5e5f083e..6427434da9 100644 --- a/panda/src/egg/pt_EggMaterial.h +++ b/panda/src/egg/pt_EggMaterial.h @@ -24,9 +24,9 @@ * the template class. It's not strictly necessary, but it doesn't hurt. */ -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEGG, EXPTP_PANDAEGG, PointerToBase) -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEGG, EXPTP_PANDAEGG, PointerTo) -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEGG, EXPTP_PANDAEGG, ConstPointerTo) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EGG, EXPTP_PANDA_EGG, PointerToBase) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EGG, EXPTP_PANDA_EGG, PointerTo) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EGG, EXPTP_PANDA_EGG, ConstPointerTo) typedef PointerTo PT_EggMaterial; typedef ConstPointerTo CPT_EggMaterial; diff --git a/panda/src/egg/pt_EggTexture.h b/panda/src/egg/pt_EggTexture.h index bc61025fb6..5138a7f25b 100644 --- a/panda/src/egg/pt_EggTexture.h +++ b/panda/src/egg/pt_EggTexture.h @@ -24,9 +24,9 @@ * template class. It's not strictly necessary, but it doesn't hurt. */ -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEGG, EXPTP_PANDAEGG, PointerToBase) -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEGG, EXPTP_PANDAEGG, PointerTo) -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEGG, EXPTP_PANDAEGG, ConstPointerTo) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EGG, EXPTP_PANDA_EGG, PointerToBase) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EGG, EXPTP_PANDA_EGG, PointerTo) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EGG, EXPTP_PANDA_EGG, ConstPointerTo) typedef PointerTo PT_EggTexture; typedef ConstPointerTo CPT_EggTexture; diff --git a/panda/src/egg/pt_EggVertex.h b/panda/src/egg/pt_EggVertex.h index 5c2922b51d..8ff72c3a96 100644 --- a/panda/src/egg/pt_EggVertex.h +++ b/panda/src/egg/pt_EggVertex.h @@ -24,9 +24,9 @@ * template class. It's not strictly necessary, but it doesn't hurt. */ -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEGG, EXPTP_PANDAEGG, PointerToBase) -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEGG, EXPTP_PANDAEGG, PointerTo) -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEGG, EXPTP_PANDAEGG, ConstPointerTo) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EGG, EXPTP_PANDA_EGG, PointerToBase) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EGG, EXPTP_PANDA_EGG, PointerTo) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EGG, EXPTP_PANDA_EGG, ConstPointerTo) typedef PointerTo PT_EggVertex; typedef ConstPointerTo CPT_EggVertex; diff --git a/panda/src/egg/test_egg.cxx b/panda/src/egg/test_egg.cxx index ae91d3548d..8023145331 100644 --- a/panda/src/egg/test_egg.cxx +++ b/panda/src/egg/test_egg.cxx @@ -28,7 +28,7 @@ main(int argc, char *argv[]) { if (data.read(egg_filename)) { data.load_externals(DSearchPath(Filename(""))); - data.write_egg(cout); + data.write_egg(std::cout); } else { nout << "Errors.\n"; } diff --git a/panda/src/egg/vector_PT_EggMaterial.h b/panda/src/egg/vector_PT_EggMaterial.h index 0878ba71c0..d1bb90ada9 100644 --- a/panda/src/egg/vector_PT_EggMaterial.h +++ b/panda/src/egg/vector_PT_EggMaterial.h @@ -28,8 +28,8 @@ * file, rather than defining the vector again. */ -#define EXPCL EXPCL_PANDAEGG -#define EXPTP EXPTP_PANDAEGG +#define EXPCL EXPCL_PANDA_EGG +#define EXPTP EXPTP_PANDA_EGG #define TYPE PT_EggMaterial #define NAME vector_PT_EggMaterial diff --git a/panda/src/egg/vector_PT_EggTexture.h b/panda/src/egg/vector_PT_EggTexture.h index 12d5f91212..062d24347c 100644 --- a/panda/src/egg/vector_PT_EggTexture.h +++ b/panda/src/egg/vector_PT_EggTexture.h @@ -28,8 +28,8 @@ * file, rather than defining the vector again. */ -#define EXPCL EXPCL_PANDAEGG -#define EXPTP EXPTP_PANDAEGG +#define EXPCL EXPCL_PANDA_EGG +#define EXPTP EXPTP_PANDA_EGG #define TYPE PT_EggTexture #define NAME vector_PT_EggTexture diff --git a/panda/src/egg/vector_PT_EggVertex.cxx b/panda/src/egg/vector_PT_EggVertex.cxx index 61deffdeac..e02586491c 100644 --- a/panda/src/egg/vector_PT_EggVertex.cxx +++ b/panda/src/egg/vector_PT_EggVertex.cxx @@ -13,8 +13,8 @@ #include "vector_PT_EggVertex.h" -#define EXPCL EXPCL_PANDAEGG -#define EXPTP EXPTP_PANDAEGG +#define EXPCL EXPCL_PANDA_EGG +#define EXPTP EXPTP_PANDA_EGG #define TYPE PT_EggVertex #define NAME vector_PT_EggVertex diff --git a/panda/src/egg/vector_PT_EggVertex.h b/panda/src/egg/vector_PT_EggVertex.h index 8d04bccc17..b8e8290179 100644 --- a/panda/src/egg/vector_PT_EggVertex.h +++ b/panda/src/egg/vector_PT_EggVertex.h @@ -28,8 +28,8 @@ * rather than defining the vector again. */ -#define EXPCL EXPCL_PANDAEGG -#define EXPTP EXPTP_PANDAEGG +#define EXPCL EXPCL_PANDA_EGG +#define EXPTP EXPTP_PANDA_EGG #define TYPE PT_EggVertex #define NAME vector_PT_EggVertex diff --git a/panda/src/egg2pg/animBundleMaker.cxx b/panda/src/egg2pg/animBundleMaker.cxx index 18e7447923..ea5ac4285f 100644 --- a/panda/src/egg2pg/animBundleMaker.cxx +++ b/panda/src/egg2pg/animBundleMaker.cxx @@ -25,6 +25,8 @@ #include "animChannelMatrixXfmTable.h" #include "animChannelScalarTable.h" +using std::min; + /** * */ @@ -167,7 +169,7 @@ inspect_tree(EggNode *egg_node) { */ void AnimBundleMaker:: build_hierarchy(EggTable *egg_table, AnimGroup *parent) { - AnimGroup *this_node = NULL; + AnimGroup *this_node = nullptr; // First, scan the children of egg_table for anim data tables. If any of // them is named "xform", it's a special case--this one stands for the @@ -176,7 +178,7 @@ build_hierarchy(EggTable *egg_table, AnimGroup *parent) { EggTable::const_iterator ci; for (ci = egg_table->begin(); ci != egg_table->end(); ++ci) { if ((*ci)->get_name() == "xform") { - if (this_node == NULL) { + if (this_node == nullptr) { this_node = create_xfm_channel((*ci), egg_table->get_name(), parent); } else { egg2pg_cat.warning() @@ -187,7 +189,7 @@ build_hierarchy(EggTable *egg_table, AnimGroup *parent) { } // If none of them were named "xform", just create a plain old AnimGroup. - if (this_node == NULL) { + if (this_node == nullptr) { this_node = new AnimGroup(parent, egg_table->get_name()); } @@ -212,7 +214,7 @@ build_hierarchy(EggTable *egg_table, AnimGroup *parent) { * structure. */ AnimChannelScalarTable *AnimBundleMaker:: -create_s_channel(EggSAnimData *egg_anim, const string &name, +create_s_channel(EggSAnimData *egg_anim, const std::string &name, AnimGroup *parent) { AnimChannelScalarTable *table = new AnimChannelScalarTable(parent, name); @@ -236,7 +238,7 @@ create_s_channel(EggSAnimData *egg_anim, const string &name, * structure, if possible. */ AnimChannelMatrixXfmTable *AnimBundleMaker:: -create_xfm_channel(EggNode *egg_node, const string &name, +create_xfm_channel(EggNode *egg_node, const std::string &name, AnimGroup *parent) { if (egg_node->is_of_type(EggXfmAnimData::get_class_type())) { EggXfmAnimData *egg_anim = DCAST(EggXfmAnimData, egg_node); @@ -251,7 +253,7 @@ create_xfm_channel(EggNode *egg_node, const string &name, egg2pg_cat.warning() << "Inappropriate node named xform under node " << name << "\n"; - return NULL; + return nullptr; } @@ -260,7 +262,7 @@ create_xfm_channel(EggNode *egg_node, const string &name, * structure. */ AnimChannelMatrixXfmTable *AnimBundleMaker:: -create_xfm_channel(EggXfmSAnim *egg_anim, const string &name, +create_xfm_channel(EggXfmSAnim *egg_anim, const std::string &name, AnimGroup *parent) { // Ensure that the anim table is optimal and that it is standard order. egg_anim->optimize_to_standard_order(); diff --git a/panda/src/egg2pg/animBundleMaker.h b/panda/src/egg2pg/animBundleMaker.h index fa95030718..5f19d92f8d 100644 --- a/panda/src/egg2pg/animBundleMaker.h +++ b/panda/src/egg2pg/animBundleMaker.h @@ -32,7 +32,7 @@ class AnimChannelMatrixXfmTable; * Converts an EggTable hierarchy, beginning with a entry, into an * AnimBundle hierarchy. */ -class EXPCL_PANDAEGG AnimBundleMaker { +class EXPCL_PANDA_EGG2PG AnimBundleMaker { public: explicit AnimBundleMaker(EggTable *root); @@ -45,13 +45,13 @@ private: void build_hierarchy(EggTable *egg_table, AnimGroup *parent); AnimChannelScalarTable * - create_s_channel(EggSAnimData *egg_anim, const string &name, + create_s_channel(EggSAnimData *egg_anim, const std::string &name, AnimGroup *parent); AnimChannelMatrixXfmTable * - create_xfm_channel(EggNode *egg_node, const string &name, + create_xfm_channel(EggNode *egg_node, const std::string &name, AnimGroup *parent); AnimChannelMatrixXfmTable * - create_xfm_channel(EggXfmSAnim *egg_anim, const string &name, + create_xfm_channel(EggXfmSAnim *egg_anim, const std::string &name, AnimGroup *parent); PN_stdfloat _fps; diff --git a/panda/src/egg2pg/characterMaker.cxx b/panda/src/egg2pg/characterMaker.cxx index 99bbf54f47..f087ebf88e 100644 --- a/panda/src/egg2pg/characterMaker.cxx +++ b/panda/src/egg2pg/characterMaker.cxx @@ -34,6 +34,8 @@ #include "eggAnimPreload.h" #include "animPreloadTable.h" +using std::string; + @@ -48,7 +50,7 @@ CharacterMaker(EggGroup *root, EggLoader &loader, bool structured) _character_node = new Character(_egg_root->get_name()); _bundle = _character_node->get_bundle(0); - _morph_root = (PartGroup *)NULL; + _morph_root = nullptr; _skeleton_root = new PartGroup(_bundle, ""); _structured = structured; } @@ -83,7 +85,7 @@ egg_to_part(EggNode *egg_node) const { // return the root of the character. return _bundle; } - nassertr(index < (int)_parts.size(), NULL); + nassertr(index < (int)_parts.size(), nullptr); return _parts[index]; } @@ -140,7 +142,7 @@ part_to_node(PartGroup *part, const string &name) const { if (part->is_character_joint()) { CharacterJoint *joint = DCAST(CharacterJoint, part); - if (joint->_geom_node != (PandaNode *)NULL) { + if (joint->_geom_node != nullptr) { node = joint->_geom_node; } } @@ -169,7 +171,7 @@ part_to_node(PartGroup *part, const string &name) const { */ int CharacterMaker:: create_slider(const string &name) { - if (_morph_root == (PartGroup *)NULL) { + if (_morph_root == nullptr) { _morph_root = new PartGroup(_bundle, "morph"); } CharacterSlider *slider = new CharacterSlider(_morph_root, name); @@ -238,7 +240,7 @@ build_joint_hierarchy(EggNode *egg_node, PartGroup *part, int index) { } PT(AnimPreloadTable) anim_preload = _bundle->modify_anim_preload(); - if (anim_preload == (AnimPreloadTable *)NULL) { + if (anim_preload == nullptr) { anim_preload = new AnimPreloadTable; _bundle->set_anim_preload(anim_preload); } @@ -313,7 +315,7 @@ parent_joint_nodes(PartGroup *part) { if (part->is_character_joint()) { CharacterJoint *joint = DCAST(CharacterJoint, part); PandaNode *joint_node = joint->_geom_node; - if (joint_node != NULL) { + if (joint_node != nullptr) { _character_node->add_child(joint_node); joint->add_net_transform(joint_node); joint_node->set_transform(TransformState::make_mat(joint->_net_transform)); @@ -341,7 +343,7 @@ make_geometry(EggNode *egg_node) { EggGroupNode *bin_home = determine_bin_home(egg_bin); bool is_dynamic; - if (bin_home == (EggGroupNode *)NULL) { + if (bin_home == nullptr) { // This is a dynamic polyset that lives under the character's root // node. bin_home = _egg_root; @@ -387,7 +389,7 @@ determine_primitive_home(EggPrimitive *egg_primitive) { // We need to keep track of the one joint we've encountered so far, to see // if all the vertices are referenced by the same joint. - EggGroupNode *home = NULL; + EggGroupNode *home = nullptr; EggPrimitive::const_iterator vi; for (vi = egg_primitive->begin(); @@ -397,7 +399,7 @@ determine_primitive_home(EggPrimitive *egg_primitive) { if (vertex->gref_size() > 1) { // This vertex is referenced by multiple joints; the primitive is // dynamic. - return NULL; + return nullptr; } if (!vertex->_dxyzs.empty() || @@ -405,14 +407,14 @@ determine_primitive_home(EggPrimitive *egg_primitive) { !vertex->_drgbas.empty()) { // This vertex has some morph slider definitions; therefore, the // primitive is dynamic. - return NULL; + return nullptr; } EggVertex::const_uv_iterator uvi; for (uvi = vertex->uv_begin(); uvi != vertex->uv_end(); ++uvi) { if (!(*uvi)->_duvs.empty()) { // Ditto: the vertex has some UV morphs; therefore the primitive is // dynamic. - return NULL; + return nullptr; } } @@ -423,15 +425,15 @@ determine_primitive_home(EggPrimitive *egg_primitive) { // where it is. vertex_home = egg_primitive->get_parent(); } else { - nassertr(vertex->gref_size() == 1, NULL); + nassertr(vertex->gref_size() == 1, nullptr); // This vertex is referenced exactly once. vertex_home = *vertex->gref_begin(); } - if (home != NULL && home != vertex_home) { + if (home != nullptr && home != vertex_home) { // Oops, two vertices are referenced by different joints! The primitive // is dynamic. - return NULL; + return nullptr; } home = vertex_home; @@ -439,35 +441,35 @@ determine_primitive_home(EggPrimitive *egg_primitive) { // This shouldn't be possible, unless there are no vertices--but we check // for that before calling this function. - nassertr(home != NULL, NULL); + nassertr(home != nullptr, nullptr); // So, all the vertices are assigned to the same group. This means the // polygon belongs entirely to one joint. // If the group is not, in fact, a joint then we return the first joint // above the group. - EggGroup *egg_group = (EggGroup *)NULL; + EggGroup *egg_group = nullptr; if (home->is_of_type(EggGroup::get_class_type())) { egg_group = DCAST(EggGroup, home); } - while (egg_group != (EggGroup *)NULL && + while (egg_group != nullptr && egg_group->get_group_type() != EggGroup::GT_joint && egg_group->get_dart_type() == EggGroup::DT_none) { - nassertr(egg_group->get_parent() != (EggGroupNode *)NULL, NULL); + nassertr(egg_group->get_parent() != nullptr, nullptr); home = egg_group->get_parent(); - egg_group = (EggGroup *)NULL; + egg_group = nullptr; if (home->is_of_type(EggGroup::get_class_type())) { egg_group = DCAST(EggGroup, home); } } - if (egg_group != (EggGroup *)NULL && + if (egg_group != nullptr && egg_group->get_group_type() == EggGroup::GT_joint && !egg_group->has_dcs_type()) { // If the home is a joint without a flag--this is the normal case-- // we'll move the polygon under the character node and animate it from // there explicitly. - return NULL; + return nullptr; } // Otherwise, if the joint *does* have a flag, we'll create static @@ -494,12 +496,12 @@ determine_bin_home(EggBin *egg_bin) { if (!egg_rigid_geometry) { // If we don't have egg-rigid-geometry enabled, then all geometry is // considered dynamic. - return NULL; + return nullptr; } // We need to keep track of the one joint we've encountered so far, to see // if all the vertices are referenced by the same joint. - EggGroupNode *home = NULL; + EggGroupNode *home = nullptr; EggGroupNode::const_iterator ci; for (ci = egg_bin->begin(); ci != egg_bin->end(); ++ci) { @@ -513,7 +515,7 @@ determine_bin_home(EggBin *egg_bin) { if (vertex->gref_size() > 1) { // This vertex is referenced by multiple joints; the primitive is // dynamic. - return NULL; + return nullptr; } if (!vertex->_dxyzs.empty() || @@ -521,14 +523,14 @@ determine_bin_home(EggBin *egg_bin) { !vertex->_drgbas.empty()) { // This vertex has some morph slider definitions; therefore, the // primitive is dynamic. - return NULL; + return nullptr; } EggVertex::const_uv_iterator uvi; for (uvi = vertex->uv_begin(); uvi != vertex->uv_end(); ++uvi) { if (!(*uvi)->_duvs.empty()) { // Ditto: the vertex has some UV morphs; therefore the primitive is // dynamic. - return NULL; + return nullptr; } } @@ -539,15 +541,15 @@ determine_bin_home(EggBin *egg_bin) { // where it is. vertex_home = egg_primitive->get_parent(); } else { - nassertr(vertex->gref_size() == 1, NULL); + nassertr(vertex->gref_size() == 1, nullptr); // This vertex is referenced exactly once. vertex_home = *vertex->gref_begin(); } - if (home != NULL && home != vertex_home) { + if (home != nullptr && home != vertex_home) { // Oops, two vertices are referenced by different joints! The // primitive is dynamic. - return NULL; + return nullptr; } home = vertex_home; @@ -557,29 +559,29 @@ determine_bin_home(EggBin *egg_bin) { // This shouldn't be possible, unless there are no vertices--but we // eliminate invalid primitives before we begin, so all primitives should // have vertices, and all bins should have primitives. - nassertr(home != NULL, NULL); + nassertr(home != nullptr, nullptr); // So, all the vertices are assigned to the same group. This means all the // primitives in the bin belong entirely to one joint. // If the group is not, in fact, a joint then we return the first joint // above the group. - EggGroup *egg_group = (EggGroup *)NULL; + EggGroup *egg_group = nullptr; if (home->is_of_type(EggGroup::get_class_type())) { egg_group = DCAST(EggGroup, home); } - while (egg_group != (EggGroup *)NULL && + while (egg_group != nullptr && egg_group->get_group_type() != EggGroup::GT_joint && egg_group->get_dart_type() == EggGroup::DT_none) { - nassertr(egg_group->get_parent() != (EggGroupNode *)NULL, NULL); + nassertr(egg_group->get_parent() != nullptr, nullptr); home = egg_group->get_parent(); - egg_group = (EggGroup *)NULL; + egg_group = nullptr; if (home->is_of_type(EggGroup::get_class_type())) { egg_group = DCAST(EggGroup, home); } } - if (egg_group != (EggGroup *)NULL && + if (egg_group != nullptr && egg_group->get_group_type() == EggGroup::GT_joint && !egg_group->has_dcs_type()) { // If we have rigid geometry that is assigned to a joint without a @@ -597,7 +599,7 @@ determine_bin_home(EggBin *egg_bin) { * and this may also break up the geometry into more individual pieces, which * is the biggest limiting factor on modern PC graphics cards. */ - return NULL; + return nullptr; } CharacterJoint *joint; @@ -618,7 +620,7 @@ determine_bin_home(EggBin *egg_bin) { */ VertexTransform *CharacterMaker:: get_identity_transform() { - if (_identity_transform == (VertexTransform *)NULL) { + if (_identity_transform == nullptr) { _identity_transform = new UserVertexTransform("root"); } return _identity_transform; diff --git a/panda/src/egg2pg/characterMaker.h b/panda/src/egg2pg/characterMaker.h index b2309c0be7..21163010a9 100644 --- a/panda/src/egg2pg/characterMaker.h +++ b/panda/src/egg2pg/characterMaker.h @@ -42,20 +42,20 @@ class PandaNode; * Converts an EggGroup hierarchy, beginning with a group with set, to * a character node with joints. */ -class EXPCL_PANDAEGG CharacterMaker { +class EXPCL_PANDA_EGG2PG CharacterMaker { public: CharacterMaker(EggGroup *root, EggLoader &loader, bool structured = false); Character *make_node(); - string get_name() const; + std::string get_name() const; PartGroup *egg_to_part(EggNode *egg_node) const; VertexTransform *egg_to_transform(EggNode *egg_node); int egg_to_index(EggNode *egg_node) const; - PandaNode *part_to_node(PartGroup *part, const string &name) const; + PandaNode *part_to_node(PartGroup *part, const std::string &name) const; - int create_slider(const string &name); - VertexSlider *egg_to_slider(const string &name); + int create_slider(const std::string &name); + VertexSlider *egg_to_slider(const std::string &name); private: CharacterJointBundle *make_bundle(); @@ -78,7 +78,7 @@ private: VertexTransforms _vertex_transforms; PT(VertexTransform) _identity_transform; - typedef pmap VertexSliders; + typedef pmap VertexSliders; VertexSliders _vertex_sliders; EggLoader &_loader; diff --git a/panda/src/egg2pg/config_egg2pg.cxx b/panda/src/egg2pg/config_egg2pg.cxx index f864a8f4d8..36247ad2c4 100644 --- a/panda/src/egg2pg/config_egg2pg.cxx +++ b/panda/src/egg2pg/config_egg2pg.cxx @@ -20,8 +20,8 @@ #include "configVariableCore.h" #include "eggRenderState.h" -#if !defined(CPPPARSER) && !defined(BUILDING_PANDAEGG) - #error Buildsystem error: BUILDING_PANDAEGG not defined +#if !defined(CPPPARSER) && !defined(BUILDING_PANDA_EGG2PG) + #error Buildsystem error: BUILDING_PANDA_EGG2PG not defined #endif ConfigureDef(config_egg2pg); diff --git a/panda/src/egg2pg/config_egg2pg.h b/panda/src/egg2pg/config_egg2pg.h index 874d413319..e9e0e202d6 100644 --- a/panda/src/egg2pg/config_egg2pg.h +++ b/panda/src/egg2pg/config_egg2pg.h @@ -25,36 +25,36 @@ #include "configVariableInt.h" #include "dconfig.h" -ConfigureDecl(config_egg2pg, EXPCL_PANDAEGG, EXPTP_PANDAEGG); -NotifyCategoryDecl(egg2pg, EXPCL_PANDAEGG, EXPTP_PANDAEGG); +ConfigureDecl(config_egg2pg, EXPCL_PANDA_EGG2PG, EXPTP_PANDA_EGG2PG); +NotifyCategoryDecl(egg2pg, EXPCL_PANDA_EGG2PG, EXPTP_PANDA_EGG2PG); -extern EXPCL_PANDAEGG ConfigVariableDouble egg_normal_scale; -extern EXPCL_PANDAEGG ConfigVariableBool egg_show_normals; -extern EXPCL_PANDAEGG ConfigVariableEnum egg_coordinate_system; -extern EXPCL_PANDAEGG ConfigVariableBool egg_ignore_mipmaps; -extern EXPCL_PANDAEGG ConfigVariableBool egg_ignore_filters; -extern EXPCL_PANDAEGG ConfigVariableBool egg_ignore_clamp; -extern EXPCL_PANDAEGG ConfigVariableBool egg_ignore_decals; -extern EXPCL_PANDAEGG ConfigVariableBool egg_flatten; -extern EXPCL_PANDAEGG ConfigVariableDouble egg_flatten_radius; -extern EXPCL_PANDAEGG ConfigVariableBool egg_unify; -extern EXPCL_PANDAEGG ConfigVariableBool egg_combine_geoms; -extern EXPCL_PANDAEGG ConfigVariableBool egg_rigid_geometry; -extern EXPCL_PANDAEGG ConfigVariableBool egg_flat_shading; -extern EXPCL_PANDAEGG ConfigVariableBool egg_flat_colors; -extern EXPCL_PANDAEGG ConfigVariableBool egg_load_old_curves; -extern EXPCL_PANDAEGG ConfigVariableBool egg_load_classic_nurbs_curves; -extern EXPCL_PANDAEGG ConfigVariableBool egg_accept_errors; -extern EXPCL_PANDAEGG ConfigVariableBool egg_suppress_hidden; -extern EXPCL_PANDAEGG ConfigVariableEnum egg_alpha_mode; -extern EXPCL_PANDAEGG ConfigVariableInt egg_max_vertices; -extern EXPCL_PANDAEGG ConfigVariableInt egg_max_indices; -extern EXPCL_PANDAEGG ConfigVariableBool egg_emulate_bface; -extern EXPCL_PANDAEGG ConfigVariableBool egg_preload_simple_textures; -extern EXPCL_PANDAEGG ConfigVariableDouble egg_vertex_membership_quantize; -extern EXPCL_PANDAEGG ConfigVariableInt egg_vertex_max_num_joints; -extern EXPCL_PANDAEGG ConfigVariableBool egg_implicit_alpha_binary; +extern EXPCL_PANDA_EGG2PG ConfigVariableDouble egg_normal_scale; +extern EXPCL_PANDA_EGG2PG ConfigVariableBool egg_show_normals; +extern EXPCL_PANDA_EGG2PG ConfigVariableEnum egg_coordinate_system; +extern EXPCL_PANDA_EGG2PG ConfigVariableBool egg_ignore_mipmaps; +extern EXPCL_PANDA_EGG2PG ConfigVariableBool egg_ignore_filters; +extern EXPCL_PANDA_EGG2PG ConfigVariableBool egg_ignore_clamp; +extern EXPCL_PANDA_EGG2PG ConfigVariableBool egg_ignore_decals; +extern EXPCL_PANDA_EGG2PG ConfigVariableBool egg_flatten; +extern EXPCL_PANDA_EGG2PG ConfigVariableDouble egg_flatten_radius; +extern EXPCL_PANDA_EGG2PG ConfigVariableBool egg_unify; +extern EXPCL_PANDA_EGG2PG ConfigVariableBool egg_combine_geoms; +extern EXPCL_PANDA_EGG2PG ConfigVariableBool egg_rigid_geometry; +extern EXPCL_PANDA_EGG2PG ConfigVariableBool egg_flat_shading; +extern EXPCL_PANDA_EGG2PG ConfigVariableBool egg_flat_colors; +extern EXPCL_PANDA_EGG2PG ConfigVariableBool egg_load_old_curves; +extern EXPCL_PANDA_EGG2PG ConfigVariableBool egg_load_classic_nurbs_curves; +extern EXPCL_PANDA_EGG2PG ConfigVariableBool egg_accept_errors; +extern EXPCL_PANDA_EGG2PG ConfigVariableBool egg_suppress_hidden; +extern EXPCL_PANDA_EGG2PG ConfigVariableEnum egg_alpha_mode; +extern EXPCL_PANDA_EGG2PG ConfigVariableInt egg_max_vertices; +extern EXPCL_PANDA_EGG2PG ConfigVariableInt egg_max_indices; +extern EXPCL_PANDA_EGG2PG ConfigVariableBool egg_emulate_bface; +extern EXPCL_PANDA_EGG2PG ConfigVariableBool egg_preload_simple_textures; +extern EXPCL_PANDA_EGG2PG ConfigVariableDouble egg_vertex_membership_quantize; +extern EXPCL_PANDA_EGG2PG ConfigVariableInt egg_vertex_max_num_joints; +extern EXPCL_PANDA_EGG2PG ConfigVariableBool egg_implicit_alpha_binary; -extern EXPCL_PANDAEGG void init_libegg2pg(); +extern EXPCL_PANDA_EGG2PG void init_libegg2pg(); #endif diff --git a/panda/src/egg2pg/eggBinner.cxx b/panda/src/egg2pg/eggBinner.cxx index 66471661f8..9d24341f91 100644 --- a/panda/src/egg2pg/eggBinner.cxx +++ b/panda/src/egg2pg/eggBinner.cxx @@ -76,13 +76,13 @@ get_bin_number(const EggNode *node) { * May be overridden in derived classes to define a name for each new bin, * based on its bin number, and a sample child. */ -string EggBinner:: +std::string EggBinner:: get_bin_name(int bin_number, const EggNode *child) { if (bin_number == BN_polyset || bin_number == BN_patches) { return DCAST(EggPrimitive, child)->get_sort_name(); } - return string(); + return std::string(); } /** diff --git a/panda/src/egg2pg/eggBinner.h b/panda/src/egg2pg/eggBinner.h index a259e522d9..a7e3c10894 100644 --- a/panda/src/egg2pg/eggBinner.h +++ b/panda/src/egg2pg/eggBinner.h @@ -47,7 +47,7 @@ public: virtual int get_bin_number(const EggNode *node); - virtual string + virtual std::string get_bin_name(int bin_number, const EggNode *child); virtual bool diff --git a/panda/src/egg2pg/eggLoader.cxx b/panda/src/egg2pg/eggLoader.cxx index e093990ef9..e26a4120b9 100644 --- a/panda/src/egg2pg/eggLoader.cxx +++ b/panda/src/egg2pg/eggLoader.cxx @@ -100,6 +100,10 @@ #include #include +using std::max; +using std::min; +using std::string; + // This class is used in make_node(EggBin *) to sort LOD instances in order by // switching distance. class LODInstance { @@ -115,7 +119,7 @@ public: LODInstance:: LODInstance(EggNode *egg_node) { - nassertv(egg_node != NULL); + nassertv(egg_node != nullptr); _egg_node = egg_node; // We expect this egg node to be an EggGroup with an LOD specification. @@ -139,7 +143,7 @@ EggLoader() { _data->set_coordinate_system(egg_coordinate_system); _error = false; _dynamic_override = false; - _dynamic_override_char_maker = NULL; + _dynamic_override_char_maker = nullptr; } /** @@ -151,7 +155,7 @@ EggLoader(const EggData *data) : { _error = false; _dynamic_override = false; - _dynamic_override_char_maker = NULL; + _dynamic_override_char_maker = nullptr; } @@ -224,7 +228,7 @@ reparent_decals() { ExtraNodes::const_iterator di; for (di = _decals.begin(); di != _decals.end(); ++di) { PandaNode *node = (*di); - nassertv(node != (PandaNode *)NULL); + nassertv(node != nullptr); // The NodePath interface is best for this. NodePath parent(node); @@ -307,7 +311,7 @@ make_polyset(EggBin *egg_bin, PandaNode *parent, const LMatrix4d *transform, EggGroupNode::const_iterator ci = egg_bin->begin(); nassertv(ci != egg_bin->end()); CPT(EggPrimitive) first_prim = DCAST(EggPrimitive, (*ci)); - nassertv(first_prim != (EggPrimitive *)NULL); + nassertv(first_prim != nullptr); const EggRenderState *render_state; DCAST_INTO_V(render_state, first_prim->get_user_data(EggRenderState::get_class_type())); @@ -390,7 +394,7 @@ make_polyset(EggBin *egg_bin, PandaNode *parent, const LMatrix4d *transform, if (!primitives.empty()) { LMatrix4d mat; - if (transform != NULL) { + if (transform != nullptr) { mat = (*transform); } else { mat = egg_bin->get_vertex_to_node(); @@ -400,7 +404,7 @@ make_polyset(EggBin *egg_bin, PandaNode *parent, const LMatrix4d *transform, PT(GeomVertexData) vertex_data = make_vertex_data(render_state, vertex_pool, egg_bin, mat, blend_table, is_dynamic, character_maker, has_overall_color); - nassertv(vertex_data != (GeomVertexData *)NULL); + nassertv(vertex_data != nullptr); // And create a Geom to hold the primitives. PT(Geom) geom = new Geom(vertex_data); @@ -423,7 +427,7 @@ make_polyset(EggBin *egg_bin, PandaNode *parent, const LMatrix4d *transform, // render_state->_state->write(cerr, 0); // Create a new GeomNode if we haven't already. - if (geom_node == (GeomNode *)NULL) { + if (geom_node == nullptr) { // Now, is our parent node a GeomNode, or just an ordinary PandaNode? // If it's a GeomNode, we can add the new Geom directly to our parent; // otherwise, we need to create a new node. @@ -453,7 +457,7 @@ make_polyset(EggBin *egg_bin, PandaNode *parent, const LMatrix4d *transform, } } - if (geom_node != (GeomNode *)NULL && egg_show_normals) { + if (geom_node != nullptr && egg_show_normals) { // Create some more geometry to visualize each normal. for (vpi = vertex_pools.begin(); vpi != vertex_pools.end(); ++vpi) { EggVertexPool *vertex_pool = (*vpi); @@ -659,11 +663,11 @@ make_nurbs_curve(EggNurbsCurve *egg_curve, PandaNode *parent, return; } - assert(parent != NULL); + assert(parent != nullptr); assert(!parent->is_geom_node()); PT(NurbsCurveEvaluator) nurbs = ::make_nurbs_curve(egg_curve, mat); - if (nurbs == (NurbsCurveEvaluator *)NULL) { + if (nurbs == nullptr) { _error = true; return; } @@ -726,14 +730,14 @@ make_nurbs_curve(EggNurbsCurve *egg_curve, PandaNode *parent, void EggLoader:: make_old_nurbs_curve(EggNurbsCurve *egg_curve, PandaNode *parent, const LMatrix4d &mat) { - assert(parent != NULL); + assert(parent != nullptr); assert(!parent->is_geom_node()); PT(ParametricCurve) curve; curve = new NurbsCurve; NurbsCurveInterface *nurbs = curve->get_nurbs_interface(); - nassertv(nurbs != (NurbsCurveInterface *)NULL); + nassertv(nurbs != nullptr); if (egg_curve->get_order() < 1 || egg_curve->get_order() > 4) { egg2pg_cat.error() @@ -798,11 +802,11 @@ make_old_nurbs_curve(EggNurbsCurve *egg_curve, PandaNode *parent, void EggLoader:: make_nurbs_surface(EggNurbsSurface *egg_surface, PandaNode *parent, const LMatrix4d &mat) { - assert(parent != NULL); + assert(parent != nullptr); assert(!parent->is_geom_node()); PT(NurbsSurfaceEvaluator) nurbs = ::make_nurbs_surface(egg_surface, mat); - if (nurbs == (NurbsSurfaceEvaluator *)NULL) { + if (nurbs == nullptr) { _error = true; return; } @@ -915,7 +919,7 @@ load_texture(TextureDef &def, EggTexture *egg_tex) { // Since some properties of the textures are inferred from the texture files // themselves (if the properties are not explicitly specified in the egg // file), then we add the textures as dependents for the egg file. - if (_record != (BamCacheRecord *)NULL) { + if (_record != nullptr) { _record->add_dependent_file(egg_tex->get_fullpath()); if (egg_tex->has_alpha_filename() && wanted_alpha) { _record->add_dependent_file(egg_tex->get_alpha_fullpath()); @@ -987,7 +991,7 @@ load_texture(TextureDef &def, EggTexture *egg_tex) { break; } - if (tex == (Texture *)NULL) { + if (tex == nullptr) { return false; } @@ -1002,7 +1006,7 @@ load_texture(TextureDef &def, EggTexture *egg_tex) { // See if there is some egg data hanging on the texture. In particular, the // TxaFileFilter might have left that here for us. TypedReferenceCount *aux = tex->get_aux_data("egg"); - if (aux != (TypedReferenceCount *)NULL && + if (aux != nullptr && aux->is_of_type(EggTexture::get_class_type())) { EggTexture *aux_egg_tex = DCAST(EggTexture, aux); @@ -1686,7 +1690,7 @@ make_node(EggNode *egg_node, PandaNode *parent) { return make_node(DCAST(EggGroupNode, egg_node), parent); } - return (PandaNode *)NULL; + return nullptr; } /** @@ -1700,40 +1704,40 @@ make_node(EggBin *egg_bin, PandaNode *parent) { switch (egg_bin->get_bin_number()) { case EggBinner::BN_polyset: case EggBinner::BN_patches: - make_polyset(egg_bin, parent, NULL, _dynamic_override, _dynamic_override_char_maker); - return NULL; + make_polyset(egg_bin, parent, nullptr, _dynamic_override, _dynamic_override_char_maker); + return nullptr; case EggBinner::BN_lod: return make_lod(egg_bin, parent); case EggBinner::BN_nurbs_surface: { - nassertr(!egg_bin->empty(), NULL); + nassertr(!egg_bin->empty(), nullptr); EggNode *child = egg_bin->get_first_child(); EggNurbsSurface *egg_nurbs; - DCAST_INTO_R(egg_nurbs, child, NULL); + DCAST_INTO_R(egg_nurbs, child, nullptr); const LMatrix4d &mat = egg_nurbs->get_vertex_to_node(); make_nurbs_surface(egg_nurbs, parent, mat); } - return NULL; + return nullptr; case EggBinner::BN_nurbs_curve: { - nassertr(!egg_bin->empty(), NULL); + nassertr(!egg_bin->empty(), nullptr); EggNode *child = egg_bin->get_first_child(); EggNurbsCurve *egg_nurbs; - DCAST_INTO_R(egg_nurbs, child, NULL); + DCAST_INTO_R(egg_nurbs, child, nullptr); const LMatrix4d &mat = egg_nurbs->get_vertex_to_node(); make_nurbs_curve(egg_nurbs, parent, mat); } - return NULL; + return nullptr; case EggBinner::BN_none: break; } // Shouldn't get here. - return (PandaNode *)NULL; + return nullptr; } /** @@ -1769,7 +1773,7 @@ make_lod(EggBin *egg_bin, PandaNode *parent) { // All of the children should have the same center, because that's how we // binned them. nassertr(lod_node->get_center().almost_equal - (LCAST(PN_stdfloat, instance._d->_center), 0.01), NULL); + (LCAST(PN_stdfloat, instance._d->_center), 0.01), nullptr); // Tell the LOD node about this child's switching distances. lod_node->add_switch(instance._d->_switch_in, instance._d->_switch_out); @@ -1784,7 +1788,7 @@ make_lod(EggBin *egg_bin, PandaNode *parent) { */ PandaNode *EggLoader:: make_node(EggGroup *egg_group, PandaNode *parent) { - PT(PandaNode) node = NULL; + PT(PandaNode) node = nullptr; if (egg_group->get_dart_type() != EggGroup::DT_none) { // A group with the flag set means to create a character. @@ -1802,7 +1806,7 @@ make_node(EggGroup *egg_group, PandaNode *parent) { for (ci = egg_group->begin(); ci != egg_group->end(); ++ci) { make_node(*ci, node); } - _dynamic_override_char_maker = NULL; + _dynamic_override_char_maker = nullptr; _dynamic_override = false; } @@ -1956,8 +1960,8 @@ make_node(EggGroup *egg_group, PandaNode *parent) { } } - if (node == (PandaNode *)NULL) { - return NULL; + if (node == nullptr) { + return nullptr; } // Associate any instances with this node. @@ -2319,7 +2323,7 @@ make_vertex_data(const EggRenderState *render_state, vertex_data->reserve_num_rows(vertex_pool->size()); vertex_data->set_transform_blend_table(blend_table); - if (slider_table != (SliderTable *)NULL) { + if (slider_table != nullptr) { vertex_data->set_slider_table(SliderTable::register_table(slider_table)); } @@ -2477,7 +2481,7 @@ make_blend_table(EggVertexPool *vertex_pool, EggNode *primitive_home, // If the vertex has no explicit membership, it belongs right where it // is. PT(VertexTransform) vt = character_maker->egg_to_transform(primitive_home); - nassertr(vt != (VertexTransform *)NULL, NULL); + nassertr(vt != nullptr, nullptr); blend.add_transform(vt, 1.0f); } else { // If the vertex does have an explicit membership, ignore its parentage @@ -2492,7 +2496,7 @@ make_blend_table(EggVertexPool *vertex_pool, EggNode *primitive_home, } PT(VertexTransform) vt = character_maker->egg_to_transform(egg_joint); - nassertr(vt != (VertexTransform *)NULL, NULL); + nassertr(vt != nullptr, nullptr); blend.add_transform(vt, membership); } } @@ -2564,7 +2568,7 @@ make_primitive(const EggRenderState *render_state, EggPrimitive *egg_prim, primitive = new GeomPatches(num_vertices, Geom::UH_static); } - if (primitive == (GeomPrimitive *)NULL) { + if (primitive == nullptr) { // Don't know how to make this kind of primitive. egg2pg_cat.warning() << "Ignoring " << egg_prim->get_type() << "\n"; @@ -2584,7 +2588,7 @@ make_primitive(const EggRenderState *render_state, EggPrimitive *egg_prim, // Insert the primitive into the set, but if we already have a primitive of // that type, reset the pointer to that one instead. PrimitiveUnifier pu(primitive); - pair result = + std::pair result = unique_primitives.insert(UniquePrimitives::value_type(pu, primitive)); if (result.second) { @@ -2633,7 +2637,7 @@ set_portal_polygon(EggGroup *egg_group, PortalNode *pnode) { pnode->clear_vertices(); PT(EggPolygon) poly = find_first_polygon(egg_group); - if (poly != (EggPolygon *)NULL) { + if (poly != nullptr) { LMatrix4d mat = poly->get_vertex_to_node(); EggPolygon::const_iterator vi; @@ -2650,7 +2654,7 @@ set_portal_polygon(EggGroup *egg_group, PortalNode *pnode) { void EggLoader:: set_occluder_polygon(EggGroup *egg_group, OccluderNode *pnode) { PT(EggPolygon) poly = find_first_polygon(egg_group); - if (poly != (EggPolygon *)NULL) { + if (poly != nullptr) { if (poly->size() != 4) { egg2pg_cat.error() << "Invalid number of vertices for " << egg_group->get_name() << "\n"; @@ -2693,14 +2697,14 @@ find_first_polygon(EggGroup *egg_group) { if ((*ci)->is_of_type(EggGroup::get_class_type())) { EggGroup *child_group = DCAST(EggGroup, *ci); PT(EggPolygon) found = find_first_polygon(child_group); - if (found != (EggPolygon *)NULL) { + if (found != nullptr) { return found; } } } // We got nothing. - return NULL; + return nullptr; } /** @@ -2712,7 +2716,7 @@ bool EggLoader:: make_sphere(EggGroup *egg_group, EggGroup::CollideFlags flags, LPoint3 ¢er, PN_stdfloat &radius, LColor &color) { EggGroup *geom_group = find_collision_geometry(egg_group, flags); - if (geom_group != (EggGroup *)NULL) { + if (geom_group != nullptr) { // Collect all of the vertices. pset vertices; @@ -2772,7 +2776,7 @@ bool EggLoader:: make_box(EggGroup *egg_group, EggGroup::CollideFlags flags, LPoint3 &min_p, LPoint3 &max_p, LColor &color) { EggGroup *geom_group = find_collision_geometry(egg_group, flags); - if (geom_group != (EggGroup *)NULL) { + if (geom_group != nullptr) { // Collect all of the vertices. pset vertices; @@ -2893,13 +2897,13 @@ void EggLoader:: make_collision_plane(EggGroup *egg_group, CollisionNode *cnode, EggGroup::CollideFlags flags) { EggGroup *geom_group = find_collision_geometry(egg_group, flags); - if (geom_group != (EggGroup *)NULL) { + if (geom_group != nullptr) { EggGroup::const_iterator ci; for (ci = geom_group->begin(); ci != geom_group->end(); ++ci) { if ((*ci)->is_of_type(EggPolygon::get_class_type())) { CollisionPlane *csplane = create_collision_plane(DCAST(EggPolygon, *ci), egg_group); - if (csplane != (CollisionPlane *)NULL) { + if (csplane != nullptr) { apply_collision_flags(csplane, flags); cnode->add_solid(csplane); return; @@ -2929,7 +2933,7 @@ make_collision_floor_mesh(EggGroup *egg_group, CollisionNode *cnode, EggGroup *geom_group = find_collision_geometry(egg_group, flags); - if (geom_group != (EggGroup *)NULL) { + if (geom_group != nullptr) { create_collision_floor_mesh(cnode, geom_group,flags); } } @@ -2943,7 +2947,7 @@ make_collision_polygon(EggGroup *egg_group, CollisionNode *cnode, EggGroup::CollideFlags flags) { EggGroup *geom_group = find_collision_geometry(egg_group, flags); - if (geom_group != (EggGroup *)NULL) { + if (geom_group != nullptr) { EggGroup::const_iterator ci; for (ci = geom_group->begin(); ci != geom_group->end(); ++ci) { if ((*ci)->is_of_type(EggPolygon::get_class_type())) { @@ -2970,7 +2974,7 @@ void EggLoader:: make_collision_polyset(EggGroup *egg_group, CollisionNode *cnode, EggGroup::CollideFlags flags) { EggGroup *geom_group = find_collision_geometry(egg_group, flags); - if (geom_group != (EggGroup *)NULL) { + if (geom_group != nullptr) { EggGroup::const_iterator ci; for (ci = geom_group->begin(); ci != geom_group->end(); ++ci) { if ((*ci)->is_of_type(EggPolygon::get_class_type())) { @@ -3049,7 +3053,7 @@ void EggLoader:: make_collision_tube(EggGroup *egg_group, CollisionNode *cnode, EggGroup::CollideFlags flags) { EggGroup *geom_group = find_collision_geometry(egg_group, flags); - if (geom_group != (EggGroup *)NULL) { + if (geom_group != nullptr) { // Collect all of the vertices. pset vertices; @@ -3284,7 +3288,7 @@ find_collision_geometry(EggGroup *egg_group, EggGroup::CollideFlags flags) { } // We got nothing. - return NULL; + return nullptr; } /** @@ -3296,7 +3300,7 @@ create_collision_plane(EggPolygon *egg_poly, EggGroup *parent_group) { egg2pg_cat.info() << "Ignoring degenerate collision plane in " << parent_group->get_name() << "\n"; - return NULL; + return nullptr; } if (!egg_poly->is_planar()) { @@ -3328,7 +3332,7 @@ create_collision_plane(EggPolygon *egg_poly, EggGroup *parent_group) { } if (vertices.size() < 3) { - return NULL; + return nullptr; } LPlane plane(vertices[0], vertices[1], vertices[2]); return new CollisionPlane(plane); @@ -3792,7 +3796,7 @@ TextureStage::CombineOperand EggLoader:: get_combine_operand(const EggTexture *egg_tex, EggTexture::CombineChannel channel, int n) { switch (egg_tex->get_combine_operand(channel, n)) { - case EggTexture::CS_unspecified: + case EggTexture::CO_unspecified: if (channel == EggTexture::CC_rgb) { // The default operand for RGB is src_color, except for the third // parameter, which defaults to src_alpha. diff --git a/panda/src/egg2pg/eggLoader.h b/panda/src/egg2pg/eggLoader.h index 504028432e..aa36475e05 100644 --- a/panda/src/egg2pg/eggLoader.h +++ b/panda/src/egg2pg/eggLoader.h @@ -147,7 +147,7 @@ private: CharacterMaker *character_maker); void record_morph (GeomVertexArrayFormat *array_format, - CharacterMaker *character_maker, const string &morph_name, + CharacterMaker *character_maker, const std::string &morph_name, InternalName *column_name, int num_components); void make_primitive(const EggRenderState *render_state, @@ -200,11 +200,11 @@ private: void apply_deferred_nodes(PandaNode *node, const DeferredNodeProperty &prop); bool expand_all_object_types(EggNode *egg_node); - bool expand_object_types(EggGroup *egg_group, const pset &expanded, - const pvector &expanded_history); - bool do_expand_object_type(EggGroup *egg_group, const pset &expanded, - const pvector &expanded_history, - const string &object_type); + bool expand_object_types(EggGroup *egg_group, const pset &expanded, + const pvector &expanded_history); + bool do_expand_object_type(EggGroup *egg_group, const pset &expanded, + const pvector &expanded_history, + const std::string &object_type); static TextureStage::CombineMode get_combine_mode(const EggTexture *egg_tex, diff --git a/panda/src/egg2pg/eggRenderState.cxx b/panda/src/egg2pg/eggRenderState.cxx index cb8a9681e3..4c5baf6e3a 100644 --- a/panda/src/egg2pg/eggRenderState.cxx +++ b/panda/src/egg2pg/eggRenderState.cxx @@ -59,54 +59,54 @@ fill_state(EggPrimitive *egg_prim) { bool has_depth_offset = false; int depth_offset = 0; bool has_bin = false; - string bin; + std::string bin; EggRenderMode *render_mode; render_mode = egg_prim->determine_alpha_mode(); - if (render_mode != (EggRenderMode *)NULL) { + if (render_mode != nullptr) { am = render_mode->get_alpha_mode(); } render_mode = egg_prim->determine_depth_write_mode(); - if (render_mode != (EggRenderMode *)NULL) { + if (render_mode != nullptr) { dwm = render_mode->get_depth_write_mode(); } render_mode = egg_prim->determine_depth_test_mode(); - if (render_mode != (EggRenderMode *)NULL) { + if (render_mode != nullptr) { dtm = render_mode->get_depth_test_mode(); } render_mode = egg_prim->determine_visibility_mode(); - if (render_mode != (EggRenderMode *)NULL) { + if (render_mode != nullptr) { vm = render_mode->get_visibility_mode(); } render_mode = egg_prim->determine_draw_order(); - if (render_mode != (EggRenderMode *)NULL) { + if (render_mode != nullptr) { has_draw_order = true; draw_order = render_mode->get_draw_order(); } render_mode = egg_prim->determine_depth_offset(); - if (render_mode != (EggRenderMode *)NULL) { + if (render_mode != nullptr) { has_depth_offset = true; depth_offset = render_mode->get_depth_offset(); } render_mode = egg_prim->determine_bin(); - if (render_mode != (EggRenderMode *)NULL) { + if (render_mode != nullptr) { has_bin = true; bin = render_mode->get_bin(); } // add_attrib(TextureAttrib::make_off()); int num_textures = egg_prim->get_num_textures(); - CPT(RenderAttrib) texture_attrib = NULL; - CPT(RenderAttrib) tex_gen_attrib = NULL; - CPT(RenderAttrib) tex_mat_attrib = NULL; + CPT(RenderAttrib) texture_attrib = nullptr; + CPT(RenderAttrib) tex_gen_attrib = nullptr; + CPT(RenderAttrib) tex_mat_attrib = nullptr; TexMats tex_mats; for (int i = 0; i < num_textures; i++) { PT_EggTexture egg_tex = egg_prim->get_texture(i); const TextureDef &def = _loader._textures[egg_tex]; - if (def._texture != (const RenderAttrib *)NULL) { - if (texture_attrib == (RenderAttrib *)NULL) { + if (def._texture != nullptr) { + if (texture_attrib == nullptr) { texture_attrib = def._texture; } else { texture_attrib = texture_attrib->compose(def._texture); @@ -115,7 +115,7 @@ fill_state(EggPrimitive *egg_prim) { if (egg_tex->affects_polygon_alpha()) { const TextureAttrib *tex_attrib = DCAST(TextureAttrib, def._texture); Texture *tex = tex_attrib->get_texture(); - nassertv(tex != (Texture *)NULL); + nassertv(tex != nullptr); Texture::Format format = tex->get_format(); if (Texture::has_alpha(format) && !Texture::has_binary_alpha(format)) { @@ -139,7 +139,7 @@ fill_state(EggPrimitive *egg_prim) { bool has_tex_gen = false; if (egg_tex->get_tex_gen() != EggTexture::TG_unspecified) { has_tex_gen = true; - if (tex_gen_attrib == (const RenderAttrib *)NULL) { + if (tex_gen_attrib == nullptr) { tex_gen_attrib = TexGenAttrib::make(); } tex_gen_attrib = DCAST(TexGenAttrib, tex_gen_attrib)-> @@ -151,7 +151,7 @@ fill_state(EggPrimitive *egg_prim) { // of textures that share this same set of UV's per each unique texture // matrix. Whew!) CPT(InternalName) uv_name; - if (egg_tex->has_uv_name() && egg_tex->get_uv_name() != string("default")) { + if (egg_tex->has_uv_name() && egg_tex->get_uv_name() != std::string("default")) { uv_name = InternalName::get_texcoord_name(egg_tex->get_uv_name()); } else { uv_name = InternalName::get_texcoord(); @@ -228,15 +228,15 @@ fill_state(EggPrimitive *egg_prim) { } } - if (texture_attrib != (RenderAttrib *)NULL) { + if (texture_attrib != nullptr) { add_attrib(texture_attrib); } - if (tex_gen_attrib != (RenderAttrib *)NULL) { + if (tex_gen_attrib != nullptr) { add_attrib(tex_gen_attrib); } - if (tex_mat_attrib != (RenderAttrib *)NULL) { + if (tex_mat_attrib != nullptr) { add_attrib(tex_mat_attrib); } @@ -580,7 +580,7 @@ apply_tex_mat(CPT(RenderAttrib) tex_mat_attrib, if (egg_tex->has_transform()) { CPT(TransformState) transform = _loader.make_transform(egg_tex); - if (tex_mat_attrib == (const RenderAttrib *)NULL) { + if (tex_mat_attrib == nullptr) { tex_mat_attrib = TexMatrixAttrib::make(); } tex_mat_attrib = DCAST(TexMatrixAttrib, tex_mat_attrib)-> diff --git a/panda/src/egg2pg/eggSaver.cxx b/panda/src/egg2pg/eggSaver.cxx index 63b114ed54..fb6bb3a59b 100644 --- a/panda/src/egg2pg/eggSaver.cxx +++ b/panda/src/egg2pg/eggSaver.cxx @@ -75,6 +75,9 @@ #include "eggTable.h" #include "dcast.h" +using std::pair; +using std::string; + /** * */ @@ -82,7 +85,7 @@ EggSaver:: EggSaver(EggData *data) : _data(data) { - if (_data == NULL) { + if (_data == nullptr) { _data = new EggData; } } @@ -97,13 +100,13 @@ add_node(PandaNode *node) { _data->add_child(_vpool); NodePath root(node); - convert_node(WorkingNodePath(root), _data, false, NULL); + convert_node(WorkingNodePath(root), _data, false, nullptr); // Remove the vertex pool if it has no vertices. if (_vpool->empty()) { _data->remove_child(_vpool); } - _vpool = NULL; + _vpool = nullptr; } /** @@ -117,13 +120,13 @@ add_subgraph(PandaNode *root) { _data->add_child(_vpool); NodePath root_path(root); - recurse_nodes(root_path, _data, false, NULL); + recurse_nodes(root_path, _data, false, nullptr); // Remove the vertex pool if it has no vertices. if (_vpool->empty()) { _data->remove_child(_vpool); } - _vpool = NULL; + _vpool = nullptr; } /** @@ -191,7 +194,7 @@ convert_lod_node(LODNode *node, const WorkingNodePath &node_path, int num_children = node->get_num_children(); int num_switches = node->get_num_switches(); - num_children = min(num_children, num_switches); + num_children = std::min(num_children, num_switches); for (int i = 0; i < num_children; i++) { PandaNode *child = node->get_child(i); @@ -288,7 +291,7 @@ convert_switch_node(SwitchNode *node, const WorkingNodePath &node_path, EggGroupNode * EggSaver::convert_animGroup_node(AnimGroup *animGroup, double fps ) { int num_children = animGroup->get_num_children(); - EggGroupNode *eggNode = NULL; + EggGroupNode *eggNode = nullptr; if (animGroup->is_of_type(AnimBundle::get_class_type())) { EggTable *eggTable = new EggTable(animGroup->get_name()); eggTable ->set_table_type(EggTable::TT_bundle); @@ -319,8 +322,8 @@ EggGroupNode * EggSaver::convert_animGroup_node(AnimGroup *animGroup, double fps for (int i = 0; i < num_children; i++) { AnimGroup *animChild = animGroup->get_child(i); EggGroupNode *eggChildNode = convert_animGroup_node(animChild, fps); - if (eggChildNode!=NULL) { - nassertr(eggNode!=NULL, NULL); + if (eggChildNode!=nullptr) { + nassertr(eggNode!=nullptr, nullptr); eggNode->add_child(eggChildNode); } } @@ -378,7 +381,7 @@ convert_character_bundle(PartGroup *bundleNode, EggGroupNode *egg_parent, Charac joint_group = joint; egg_parent->add_child(joint_group); - if (joint_map != NULL) { + if (joint_map != nullptr) { CharacterJointMap::iterator mi = joint_map->find(character_joint); if (mi != joint_map->end()) { pvector > &joint_vertices = (*mi).second; @@ -560,7 +563,7 @@ convert_collision_node(CollisionNode *node, const WorkingNodePath &node_path, // Get an arbitrary vector on the plane by taking the cross product // with any vector, as long as it is different. LVector3 vec1; - if (abs(normal[2]) > abs(normal[1])) { + if (std::fabs(normal[2]) > std::fabs(normal[1])) { vec1 = normal.cross(LVector3(0, 1, 0)); } else { vec1 = normal.cross(LVector3(0, 0, 1)); @@ -626,7 +629,7 @@ convert_collision_node(CollisionNode *node, const WorkingNodePath &node_path, // Also get an arbitrary vector perpendicular to the tube. LVector3 axis = point_b - point_a; LVector3 sideways; - if (abs(axis[2]) > abs(axis[1])) { + if (std::fabs(axis[2]) > std::fabs(axis[1])) { sideways = axis.cross(LVector3(0, 1, 0)); } else { sideways = axis.cross(LVector3(0, 0, 1)); @@ -789,11 +792,11 @@ convert_primitive(const GeomVertexData *vertex_data, } // Check for a material. - EggMaterial *egg_mat = (EggMaterial *)NULL; + EggMaterial *egg_mat = nullptr; const MaterialAttrib *ma; if (net_state->get_attrib(ma)) { egg_mat = get_egg_material(ma->get_material()); - if (egg_mat != (EggMaterial *)NULL) { + if (egg_mat != nullptr) { egg_prim->set_material(egg_mat); } } @@ -803,9 +806,9 @@ convert_primitive(const GeomVertexData *vertex_data, if (net_state->get_attrib(ta)) { EggTexture *egg_tex = get_egg_texture(ta->get_texture()); - if (egg_tex != (EggTexture *)NULL) { + if (egg_tex != nullptr) { TextureStage *tex_stage = ta->get_on_stage(0); - if (tex_stage != (TextureStage *)NULL) { + if (tex_stage != nullptr) { switch (tex_stage->get_mode()) { case TextureStage::M_modulate: if (has_color_off == true) { @@ -839,7 +842,6 @@ convert_primitive(const GeomVertexData *vertex_data, } // Check the backface flag. - bool bface = false; const CullFaceAttrib *cfa; if (net_state->get_attrib(cfa)) { if (cfa->get_effective_mode() == CullFaceAttrib::M_cull_none) { @@ -861,8 +863,6 @@ convert_primitive(const GeomVertexData *vertex_data, } } - LNormal normal; - LColor color; CPT(TransformBlendTable) transformBlendTable = vertex_data->get_transform_blend_table(); int num_primitives = primitive->get_num_primitives(); @@ -911,7 +911,7 @@ convert_primitive(const GeomVertexData *vertex_data, EggVertex *new_egg_vert = _vpool->create_unique_vertex(egg_vert); if (vertex_data->has_column(InternalName::get_transform_blend()) && - joint_map != NULL && transformBlendTable != NULL) { + joint_map != nullptr && transformBlendTable != nullptr) { reader.set_column(InternalName::get_transform_blend()); int idx = reader.get_data1i(); const TransformBlend &blend = transformBlendTable->get_blend(idx); @@ -1009,7 +1009,7 @@ apply_node_properties(EggGroup *egg_group, PandaNode *node, bool allow_backstage const RenderEffects *effects = node->get_effects(); const RenderEffect *effect = effects->get_effect(BillboardEffect::get_class_type()); - if (effect != (RenderEffect *)NULL) { + if (effect != nullptr) { const BillboardEffect *bbe = DCAST(BillboardEffect, effect); if (bbe->get_axial_rotate()) { egg_group->set_billboard_type(EggGroup::BT_axis); @@ -1151,7 +1151,7 @@ apply_state_properties(EggRenderMode *egg_render_mode, const RenderState *state) */ bool EggSaver:: apply_tags(EggGroup *egg_group, PandaNode *node) { - ostringstream strm; + std::ostringstream strm; char delimiter = '\n'; string delimiter_str(1, delimiter); node->list_tags(strm, delimiter_str); @@ -1201,7 +1201,7 @@ apply_tag(EggGroup *egg_group, PandaNode *node, const string &tag) { */ EggMaterial *EggSaver:: get_egg_material(Material *mat) { - if (mat != (Material *)NULL) { + if (mat != nullptr) { EggMaterial temp(mat->get_name()); if (mat->has_base_color()) { temp.set_base(mat->get_base_color()); @@ -1242,7 +1242,7 @@ get_egg_material(Material *mat) { return _materials.create_unique_material(temp, ~EggMaterial::E_mref_name); } - return NULL; + return nullptr; } /** @@ -1250,7 +1250,7 @@ get_egg_material(Material *mat) { */ EggTexture *EggSaver:: get_egg_texture(Texture *tex) { - if (tex != (Texture *)NULL) { + if (tex != nullptr) { if (tex->has_filename()) { Filename filename = tex->get_filename(); EggTexture temp(filename.get_basename_wo_extension(), filename); @@ -1386,5 +1386,5 @@ get_egg_texture(Texture *tex) { } } - return NULL; + return nullptr; } diff --git a/panda/src/egg2pg/eggSaver.h b/panda/src/egg2pg/eggSaver.h index a361591241..8041d346cc 100644 --- a/panda/src/egg2pg/eggSaver.h +++ b/panda/src/egg2pg/eggSaver.h @@ -52,14 +52,14 @@ class EggVertex; */ class EggSaver { PUBLISHED: - EggSaver(EggData *data = NULL); + EggSaver(EggData *data = nullptr); void add_node(PandaNode *node); void add_subgraph(PandaNode *root); INLINE EggData *get_egg_data() const; private: - typedef pmap > > CharacterJointMap; + typedef pmap > > CharacterJointMap; void convert_node(const WorkingNodePath &node_path, EggGroupNode *egg_parent, bool has_decal, CharacterJointMap *joint_map); @@ -82,7 +82,7 @@ private: EggGroupNode *egg_parent, bool has_decal, CharacterJointMap *joint_map); void convert_geom_node(GeomNode *node, const WorkingNodePath &node_path, - EggGroupNode *egg_parent, bool has_decal, CharacterJointMap *jointMap=NULL); + EggGroupNode *egg_parent, bool has_decal, CharacterJointMap *jointMap=nullptr); void convert_primitive(const GeomVertexData *vertex_data, const GeomPrimitive *primitive, const RenderState *geom_state, @@ -95,7 +95,7 @@ private: bool apply_node_properties(EggGroup *egg_group, PandaNode *node, bool allow_backstage = true); bool apply_state_properties(EggRenderMode *egg_render_mode, const RenderState *state); bool apply_tags(EggGroup *egg_group, PandaNode *node); - bool apply_tag(EggGroup *egg_group, PandaNode *node, const string &tag); + bool apply_tag(EggGroup *egg_group, PandaNode *node, const std::string &tag); EggMaterial *get_egg_material(Material *tex); EggTexture *get_egg_texture(Texture *tex); diff --git a/panda/src/egg2pg/egg_parametrics.cxx b/panda/src/egg2pg/egg_parametrics.cxx index e57f49e297..eb2036d8a7 100644 --- a/panda/src/egg2pg/egg_parametrics.cxx +++ b/panda/src/egg2pg/egg_parametrics.cxx @@ -26,14 +26,14 @@ make_nurbs_surface(EggNurbsSurface *egg_surface, const LMatrix4d &mat) { egg2pg_cat.error() << "Invalid NURBSSurface U order for " << egg_surface->get_name() << ": " << egg_surface->get_u_order() << "\n"; - return NULL; + return nullptr; } if (egg_surface->get_v_order() < 1 || egg_surface->get_v_order() > 4) { egg2pg_cat.error() << "Invalid NURBSSurface V order for " << egg_surface->get_name() << ": " << egg_surface->get_v_order() << "\n"; - return NULL; + return nullptr; } PT(NurbsSurfaceEvaluator) nurbs = new NurbsSurfaceEvaluator; @@ -61,7 +61,7 @@ make_nurbs_surface(EggNurbsSurface *egg_surface, const LMatrix4d &mat) { << "Invalid NURBSSurface number of U knots for " << egg_surface->get_name() << ": got " << num_u_knots << " knots, expected " << nurbs->get_num_u_knots() << "\n"; - return NULL; + return nullptr; } int num_v_knots = egg_surface->get_num_v_knots(); @@ -70,7 +70,7 @@ make_nurbs_surface(EggNurbsSurface *egg_surface, const LMatrix4d &mat) { << "Invalid NURBSSurface number of U knots for " << egg_surface->get_name() << ": got " << num_v_knots << " knots, expected " << nurbs->get_num_v_knots() << "\n"; - return NULL; + return nullptr; } int i; @@ -96,7 +96,7 @@ make_nurbs_curve(EggNurbsCurve *egg_curve, const LMatrix4d &mat) { egg2pg_cat.error() << "Invalid NURBSCurve order for " << egg_curve->get_name() << ": " << egg_curve->get_order() << "\n"; - return NULL; + return nullptr; } PT(NurbsCurveEvaluator) nurbs = new NurbsCurveEvaluator; @@ -119,7 +119,7 @@ make_nurbs_curve(EggNurbsCurve *egg_curve, const LMatrix4d &mat) { << "Invalid NURBSCurve number of knots for " << egg_curve->get_name() << ": got " << num_knots << " knots, expected " << nurbs->get_num_knots() << "\n"; - return NULL; + return nullptr; } for (int i = 0; i < num_knots; i++) { diff --git a/panda/src/egg2pg/egg_parametrics.h b/panda/src/egg2pg/egg_parametrics.h index 639561dc0e..a18ab4db61 100644 --- a/panda/src/egg2pg/egg_parametrics.h +++ b/panda/src/egg2pg/egg_parametrics.h @@ -29,7 +29,7 @@ BEGIN_PUBLISH * the object is invalid. If there is vertex color, it will be applied to * values 0 - 3 of the extended vertex values. */ -EXPCL_PANDAEGG PT(NurbsSurfaceEvaluator) +EXPCL_PANDA_EGG2PG PT(NurbsSurfaceEvaluator) make_nurbs_surface(EggNurbsSurface *egg_surface, const LMatrix4d &mat); /** @@ -38,7 +38,7 @@ make_nurbs_surface(EggNurbsSurface *egg_surface, const LMatrix4d &mat); * object is invalid. If there is vertex color, it will be applied to values * 0 - 3 of the extended vertex values. */ -EXPCL_PANDAEGG PT(NurbsCurveEvaluator) +EXPCL_PANDA_EGG2PG PT(NurbsCurveEvaluator) make_nurbs_curve(EggNurbsCurve *egg_curve, const LMatrix4d &mat); END_PUBLISH diff --git a/panda/src/egg2pg/load_egg_file.cxx b/panda/src/egg2pg/load_egg_file.cxx index 36b60bb92c..f6f3fa8f8b 100644 --- a/panda/src/egg2pg/load_egg_file.cxx +++ b/panda/src/egg2pg/load_egg_file.cxx @@ -28,10 +28,10 @@ load_from_loader(EggLoader &loader) { if (loader._error && !egg_accept_errors) { egg2pg_cat.error() << "Errors in egg file.\n"; - return NULL; + return nullptr; } - if (loader._root != (PandaNode *)NULL && egg_flatten) { + if (loader._root != nullptr && egg_flatten) { SceneGraphReducer gr; int combine_siblings_bits = 0; @@ -76,7 +76,7 @@ load_egg_file(const Filename &filename, CoordinateSystem cs, egg_filename.set_text(); VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { record->add_dependent_file(egg_filename); } @@ -87,18 +87,18 @@ load_egg_file(const Filename &filename, CoordinateSystem cs, loader._record = record; PT(VirtualFile) vfile = vfs->get_file(egg_filename); - if (vfile == NULL) { - return NULL; + if (vfile == nullptr) { + return nullptr; } loader._data->set_egg_timestamp(vfile->get_timestamp()); bool okflag; - istream *istr = vfile->open_read_file(true); - if (istr == (istream *)NULL) { + std::istream *istr = vfile->open_read_file(true); + if (istr == nullptr) { egg2pg_cat.error() << "Couldn't read " << egg_filename << "\n"; - return NULL; + return nullptr; } egg2pg_cat.info() @@ -110,7 +110,7 @@ load_egg_file(const Filename &filename, CoordinateSystem cs, if (!okflag) { egg2pg_cat.error() << "Error reading " << egg_filename << "\n"; - return NULL; + return nullptr; } return load_from_loader(loader); diff --git a/panda/src/egg2pg/load_egg_file.h b/panda/src/egg2pg/load_egg_file.h index 296d1aaa60..9bfafbbcc5 100644 --- a/panda/src/egg2pg/load_egg_file.h +++ b/panda/src/egg2pg/load_egg_file.h @@ -31,16 +31,16 @@ BEGIN_PUBLISH * Also see the EggLoader class, which can exercise a bit more manual control * over the loading process. */ -EXPCL_PANDAEGG PT(PandaNode) +EXPCL_PANDA_EGG2PG PT(PandaNode) load_egg_file(const Filename &filename, CoordinateSystem cs = CS_default, - BamCacheRecord *record = NULL); + BamCacheRecord *record = nullptr); /** * Another convenience function; works like load_egg_file() but starts from an * already-filled EggData structure. The structure is destroyed in the * loading. */ -EXPCL_PANDAEGG PT(PandaNode) +EXPCL_PANDA_EGG2PG PT(PandaNode) load_egg_data(EggData *data, CoordinateSystem cs = CS_default); END_PUBLISH diff --git a/panda/src/egg2pg/loaderFileTypeEgg.cxx b/panda/src/egg2pg/loaderFileTypeEgg.cxx index a5bbd96210..281e2ca51f 100644 --- a/panda/src/egg2pg/loaderFileTypeEgg.cxx +++ b/panda/src/egg2pg/loaderFileTypeEgg.cxx @@ -29,7 +29,7 @@ LoaderFileTypeEgg() { /** * */ -string LoaderFileTypeEgg:: +std::string LoaderFileTypeEgg:: get_name() const { return "Egg"; } @@ -37,7 +37,7 @@ get_name() const { /** * */ -string LoaderFileTypeEgg:: +std::string LoaderFileTypeEgg:: get_extension() const { return "egg"; } diff --git a/panda/src/egg2pg/loaderFileTypeEgg.h b/panda/src/egg2pg/loaderFileTypeEgg.h index b1c9c00e7b..a719fc0323 100644 --- a/panda/src/egg2pg/loaderFileTypeEgg.h +++ b/panda/src/egg2pg/loaderFileTypeEgg.h @@ -21,12 +21,12 @@ /** * This defines the Loader interface to read Egg files. */ -class EXPCL_PANDAEGG LoaderFileTypeEgg : public LoaderFileType { +class EXPCL_PANDA_EGG2PG LoaderFileTypeEgg : public LoaderFileType { public: LoaderFileTypeEgg(); - virtual string get_name() const; - virtual string get_extension() const; + virtual std::string get_name() const; + virtual std::string get_extension() const; virtual bool supports_compressed() const; virtual bool supports_load() const; diff --git a/panda/src/egg2pg/save_egg_file.h b/panda/src/egg2pg/save_egg_file.h index 0c522cffa0..0804cfc01a 100644 --- a/panda/src/egg2pg/save_egg_file.h +++ b/panda/src/egg2pg/save_egg_file.h @@ -25,7 +25,7 @@ BEGIN_PUBLISH * A convenience function; converts the indicated scene graph to an egg file * and writes it to disk. */ -EXPCL_PANDAEGG bool +EXPCL_PANDA_EGG2PG bool save_egg_file(const Filename &filename, PandaNode *node, CoordinateSystem cs = CS_default); @@ -33,7 +33,7 @@ save_egg_file(const Filename &filename, PandaNode *node, * Another convenience function; works like save_egg_file() but populates an * EggData instead of writing the results to disk. */ -EXPCL_PANDAEGG bool +EXPCL_PANDA_EGG2PG bool save_egg_data(EggData *data, PandaNode *node); END_PUBLISH diff --git a/panda/src/egldisplay/config_egldisplay.cxx b/panda/src/egldisplay/config_egldisplay.cxx index 9f9bf13770..f76b1b9d1f 100644 --- a/panda/src/egldisplay/config_egldisplay.cxx +++ b/panda/src/egldisplay/config_egldisplay.cxx @@ -63,7 +63,7 @@ init_libegldisplay() { /** * Returns the given EGL error as string. */ -const string get_egl_error_string(int error) { +const std::string get_egl_error_string(int error) { switch (error) { case 0x3000: return "EGL_SUCCESS"; break; case 0x3001: return "EGL_NOT_INITIALIZED"; break; diff --git a/panda/src/egldisplay/config_egldisplay.h b/panda/src/egldisplay/config_egldisplay.h index 2df5bcc1f4..40e30893b8 100644 --- a/panda/src/egldisplay/config_egldisplay.h +++ b/panda/src/egldisplay/config_egldisplay.h @@ -31,12 +31,12 @@ NotifyCategoryDecl(egldisplay, EXPCL_PANDAGLES2, EXPTP_PANDAGLES2); extern EXPCL_PANDAGLES2 void init_libegldisplay(); - extern EXPCL_PANDAGLES2 const string get_egl_error_string(int error); + extern EXPCL_PANDAGLES2 const std::string get_egl_error_string(int error); #else NotifyCategoryDecl(egldisplay, EXPCL_PANDAGLES, EXPTP_PANDAGLES); extern EXPCL_PANDAGLES void init_libegldisplay(); - extern EXPCL_PANDAGLES const string get_egl_error_string(int error); + extern EXPCL_PANDAGLES const std::string get_egl_error_string(int error); #endif #endif diff --git a/panda/src/egldisplay/eglGraphicsBuffer.cxx b/panda/src/egldisplay/eglGraphicsBuffer.cxx index 14f6121653..a0cf71f1fa 100644 --- a/panda/src/egldisplay/eglGraphicsBuffer.cxx +++ b/panda/src/egldisplay/eglGraphicsBuffer.cxx @@ -26,7 +26,7 @@ TypeHandle eglGraphicsBuffer::_type_handle; */ eglGraphicsBuffer:: eglGraphicsBuffer(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -62,7 +62,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { PStatTimer timer(_make_current_pcollector, current_thread); begin_frame_spam(mode); - if (_gsg == (GraphicsStateGuardian *)NULL) { + if (_gsg == nullptr) { return false; } @@ -105,7 +105,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { void eglGraphicsBuffer:: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); - nassertv(_gsg != (GraphicsStateGuardian *)NULL); + nassertv(_gsg != nullptr); if (mode == FM_render) { copy_to_textures(); @@ -124,7 +124,7 @@ end_frame(FrameMode mode, Thread *current_thread) { */ void eglGraphicsBuffer:: close_buffer() { - if (_gsg != (GraphicsStateGuardian *)NULL) { + if (_gsg != nullptr) { eglGraphicsStateGuardian *eglgsg; DCAST_INTO_V(eglgsg, _gsg); if (!eglMakeCurrent(eglgsg->_egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) { @@ -158,7 +158,7 @@ open_buffer() { eglGraphicsStateGuardian *eglgsg; if (_gsg == 0) { // There is no old gsg. Create a new one. - eglgsg = new eglGraphicsStateGuardian(_engine, _pipe, NULL); + eglgsg = new eglGraphicsStateGuardian(_engine, _pipe, nullptr); eglgsg->choose_pixel_format(_fb_properties, egl_pipe->get_display(), egl_pipe->get_screen(), true, false); _gsg = eglgsg; } else { diff --git a/panda/src/egldisplay/eglGraphicsBuffer.h b/panda/src/egldisplay/eglGraphicsBuffer.h index 0d5d473d36..68697ef94c 100644 --- a/panda/src/egldisplay/eglGraphicsBuffer.h +++ b/panda/src/egldisplay/eglGraphicsBuffer.h @@ -25,7 +25,7 @@ class eglGraphicsBuffer : public GraphicsBuffer { public: eglGraphicsBuffer(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -41,7 +41,6 @@ protected: virtual bool open_buffer(); private: - X11_Display *_display; EGLSurface _pbuffer; EGLDisplay _egl_display; diff --git a/panda/src/egldisplay/eglGraphicsPipe.cxx b/panda/src/egldisplay/eglGraphicsPipe.cxx index 441fc10512..17594f799e 100644 --- a/panda/src/egldisplay/eglGraphicsPipe.cxx +++ b/panda/src/egldisplay/eglGraphicsPipe.cxx @@ -25,9 +25,9 @@ TypeHandle eglGraphicsPipe::_type_handle; * */ eglGraphicsPipe:: -eglGraphicsPipe(const string &display) : x11GraphicsPipe(display) { +eglGraphicsPipe(const std::string &display) : x11GraphicsPipe(display) { _egl_display = eglGetDisplay((NativeDisplayType) _display); - if (!eglInitialize(_egl_display, NULL, NULL)) { + if (!eglInitialize(_egl_display, nullptr, nullptr)) { egldisplay_cat.error() << "Couldn't initialize the EGL display: " << get_egl_error_string(eglGetError()) << "\n"; @@ -59,7 +59,7 @@ eglGraphicsPipe:: * choose between several possible GraphicsPipes available on a particular * platform, so the name should be meaningful and unique for a given platform. */ -string eglGraphicsPipe:: +std::string eglGraphicsPipe:: get_interface_name() const { return "OpenGL ES"; } @@ -77,7 +77,7 @@ pipe_constructor() { * Creates a new window on the pipe, if possible. */ PT(GraphicsOutput) eglGraphicsPipe:: -make_output(const string &name, +make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -88,12 +88,12 @@ make_output(const string &name, bool &precertify) { if (!_is_valid) { - return NULL; + return nullptr; } eglGraphicsStateGuardian *eglgsg = 0; if (gsg != 0) { - DCAST_INTO_R(eglgsg, gsg, NULL); + DCAST_INTO_R(eglgsg, gsg, nullptr); } bool support_rtt; @@ -117,7 +117,7 @@ make_output(const string &name, ((flags&BF_rtt_cumulative)!=0)|| ((flags&BF_can_bind_color)!=0)|| ((flags&BF_can_bind_every)!=0)) { - return NULL; + return nullptr; } return new eglGraphicsWindow(engine, this, name, fb_prop, win_prop, flags, gsg, host); @@ -129,7 +129,7 @@ make_output(const string &name, // (!gl_support_fbo)|| ((flags&BF_require_parasite)!=0)|| ((flags&BF_require_window)!=0)) { - return NULL; + return nullptr; } // Early failure - if we are sure that this buffer WONT meet specs, we can // bail out early. @@ -138,7 +138,7 @@ make_output(const string &name, (fb_prop.get_back_buffers() > 0)|| (fb_prop.get_accum_bits() > 0)|| (fb_prop.get_multisamples() > 0)) { - return NULL; + return nullptr; } } // Early success - if we are sure that this buffer WILL meet specs, we can @@ -166,7 +166,7 @@ make_output(const string &name, ((flags&BF_require_window)!=0)|| ((flags&BF_resizeable)!=0)|| ((flags&BF_size_track_host)!=0)) { - return NULL; + return nullptr; } if (!support_rtt) { @@ -174,7 +174,7 @@ make_output(const string &name, ((flags&BF_can_bind_every)!=0)) { // If we require Render-to-Texture, but can't be sure we support it, // bail. - return NULL; + return nullptr; } } @@ -188,12 +188,12 @@ make_output(const string &name, ((flags&BF_require_window)!=0)|| ((flags&BF_resizeable)!=0)|| ((flags&BF_size_track_host)!=0)) { - return NULL; + return nullptr; } if (((flags&BF_rtt_cumulative)!=0)|| ((flags&BF_can_bind_every)!=0)) { - return NULL; + return nullptr; } return new eglGraphicsPixmap(engine, this, name, fb_prop, win_prop, @@ -201,5 +201,5 @@ make_output(const string &name, } // Nothing else left to try. - return NULL; + return nullptr; } diff --git a/panda/src/egldisplay/eglGraphicsPipe.h b/panda/src/egldisplay/eglGraphicsPipe.h index aea34925e6..aebd9c70e1 100644 --- a/panda/src/egldisplay/eglGraphicsPipe.h +++ b/panda/src/egldisplay/eglGraphicsPipe.h @@ -44,14 +44,14 @@ class eglGraphicsWindow; */ class eglGraphicsPipe : public x11GraphicsPipe { public: - eglGraphicsPipe(const string &display = string()); + eglGraphicsPipe(const std::string &display = std::string()); virtual ~eglGraphicsPipe(); - virtual string get_interface_name() const; + virtual std::string get_interface_name() const; static PT(GraphicsPipe) pipe_constructor(); protected: - virtual PT(GraphicsOutput) make_output(const string &name, + virtual PT(GraphicsOutput) make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/egldisplay/eglGraphicsPixmap.cxx b/panda/src/egldisplay/eglGraphicsPixmap.cxx index ce0abdfdb7..5933416f5c 100644 --- a/panda/src/egldisplay/eglGraphicsPixmap.cxx +++ b/panda/src/egldisplay/eglGraphicsPixmap.cxx @@ -27,7 +27,7 @@ TypeHandle eglGraphicsPixmap::_type_handle; */ eglGraphicsPixmap:: eglGraphicsPixmap(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -67,7 +67,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { PStatTimer timer(_make_current_pcollector, current_thread); begin_frame_spam(mode); - if (_gsg == (GraphicsStateGuardian *)NULL) { + if (_gsg == nullptr) { return false; } @@ -110,7 +110,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { void eglGraphicsPixmap:: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); - nassertv(_gsg != (GraphicsStateGuardian *)NULL); + nassertv(_gsg != nullptr); if (mode == FM_render) { copy_to_textures(); @@ -129,7 +129,7 @@ end_frame(FrameMode mode, Thread *current_thread) { */ void eglGraphicsPixmap:: close_buffer() { - if (_gsg != (GraphicsStateGuardian *)NULL) { + if (_gsg != nullptr) { if (!eglMakeCurrent(_egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) { egldisplay_cat.error() << "Failed to call eglMakeCurrent: " << get_egl_error_string(eglGetError()) << "\n"; @@ -166,7 +166,7 @@ open_buffer() { eglGraphicsStateGuardian *eglgsg; if (_gsg == 0) { // There is no old gsg. Create a new one. - eglgsg = new eglGraphicsStateGuardian(_engine, _pipe, NULL); + eglgsg = new eglGraphicsStateGuardian(_engine, _pipe, nullptr); eglgsg->choose_pixel_format(_fb_properties, _display, egl_pipe->get_screen(), false, true); _gsg = eglgsg; } else { @@ -187,7 +187,7 @@ open_buffer() { } XVisualInfo *visual_info = eglgsg->_visual; - if (visual_info == NULL) { + if (visual_info == nullptr) { // No X visual for this fbconfig; how can we create the pixmap? egldisplay_cat.error() << "No X visual: cannot create pixmap.\n"; @@ -195,7 +195,7 @@ open_buffer() { } _drawable = egl_pipe->get_root(); - if (_host != NULL) { + if (_host != nullptr) { if (_host->is_of_type(eglGraphicsWindow::get_class_type())) { eglGraphicsWindow *win = DCAST(eglGraphicsWindow, _host); _drawable = win->get_xwindow(); @@ -215,7 +215,7 @@ open_buffer() { } nassertr(eglgsg->_fbconfig, false); - _egl_surface = eglCreatePixmapSurface(_egl_display, eglgsg->_fbconfig, (NativePixmapType) _x_pixmap, NULL); + _egl_surface = eglCreatePixmapSurface(_egl_display, eglgsg->_fbconfig, (NativePixmapType) _x_pixmap, nullptr); if (_egl_surface == EGL_NO_SURFACE) { egldisplay_cat.error() diff --git a/panda/src/egldisplay/eglGraphicsPixmap.h b/panda/src/egldisplay/eglGraphicsPixmap.h index cbd132c1ac..ed7e7f90e9 100644 --- a/panda/src/egldisplay/eglGraphicsPixmap.h +++ b/panda/src/egldisplay/eglGraphicsPixmap.h @@ -27,7 +27,7 @@ class eglGraphicsPixmap : public GraphicsBuffer { public: eglGraphicsPixmap(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/egldisplay/eglGraphicsStateGuardian.cxx b/panda/src/egldisplay/eglGraphicsStateGuardian.cxx index 84fc303efb..31c1069d46 100644 --- a/panda/src/egldisplay/eglGraphicsStateGuardian.cxx +++ b/panda/src/egldisplay/eglGraphicsStateGuardian.cxx @@ -40,7 +40,7 @@ eglGraphicsStateGuardian(GraphicsEngine *engine, GraphicsPipe *pipe, _visuals=0; _fbconfig=0; - if (share_with != (eglGraphicsStateGuardian *)NULL) { + if (share_with != nullptr) { _prepared_objects = share_with->get_prepared_objects(); _share_context = share_with->_context; } @@ -51,15 +51,15 @@ eglGraphicsStateGuardian(GraphicsEngine *engine, GraphicsPipe *pipe, */ eglGraphicsStateGuardian:: ~eglGraphicsStateGuardian() { - if (_visuals != (XVisualInfo *)NULL) { + if (_visuals != nullptr) { XFree(_visuals); } - if (_context != (EGLContext)NULL) { + if (_context != (EGLContext)nullptr) { if (!eglDestroyContext(_egl_display, _context)) { egldisplay_cat.error() << "Failed to destroy EGL context: " << get_egl_error_string(eglGetError()) << "\n"; } - _context = (EGLContext)NULL; + _context = (EGLContext)nullptr; } } @@ -157,7 +157,7 @@ choose_pixel_format(const FrameBufferProperties &properties, // First get the number of matching configurations, so we know how much // memory to allocate. int num_configs = 0, returned_configs; - if (!eglChooseConfig(_egl_display, attrib_list, NULL, num_configs, &returned_configs) || returned_configs <= 0) { + if (!eglChooseConfig(_egl_display, attrib_list, nullptr, num_configs, &returned_configs) || returned_configs <= 0) { egldisplay_cat.error() << "eglChooseConfig failed: " << get_egl_error_string(eglGetError()) << "\n"; return; @@ -218,7 +218,7 @@ choose_pixel_format(const FrameBufferProperties &properties, EGLint context_attribs[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE}; _context = eglCreateContext(_egl_display, _fbconfig, _share_context, context_attribs); #else - _context = eglCreateContext(_egl_display, _fbconfig, _share_context, NULL); + _context = eglCreateContext(_egl_display, _fbconfig, _share_context, nullptr); #endif int err = eglGetError(); if (_context && err == EGL_SUCCESS) { @@ -258,8 +258,8 @@ reset() { // If "Mesa" is present, assume software. However, if "Mesa DRI" is found, // it's actually a Mesa-based OpenGL layer running over a hardware driver. if (_gl_renderer == "Software Rasterizer" || - (_gl_renderer.find("Mesa") != string::npos && - _gl_renderer.find("Mesa DRI") == string::npos)) { + (_gl_renderer.find("Mesa") != std::string::npos && + _gl_renderer.find("Mesa DRI") == std::string::npos)) { // It's Mesa, therefore probably a software context. _fbprops.set_force_software(1); _fbprops.set_force_hardware(0); diff --git a/panda/src/egldisplay/eglGraphicsWindow.cxx b/panda/src/egldisplay/eglGraphicsWindow.cxx index b7e7d5dccf..efb550c728 100644 --- a/panda/src/egldisplay/eglGraphicsWindow.cxx +++ b/panda/src/egldisplay/eglGraphicsWindow.cxx @@ -34,7 +34,7 @@ TypeHandle eglGraphicsWindow::_type_handle; */ eglGraphicsWindow:: eglGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -84,7 +84,7 @@ move_pointer(int device, int x, int y) { return true; } else { // Move a raw mouse. - if ((device < 1)||(device >= _input_devices.size())) { + if (device < 1 || (size_t)device >= _input_devices.size()) { return false; } _input_devices[device].set_pointer_in_window(x, y); @@ -104,7 +104,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { PStatTimer timer(_make_current_pcollector, current_thread); begin_frame_spam(mode); - if (_gsg == (GraphicsStateGuardian *)NULL) { + if (_gsg == nullptr) { return false; } if (_awaiting_configure) { @@ -156,7 +156,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { void eglGraphicsWindow:: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); - nassertv(_gsg != (GraphicsStateGuardian *)NULL); + nassertv(_gsg != nullptr); if (mode == FM_render) { // end_render_texture(); @@ -180,7 +180,7 @@ end_frame(FrameMode mode, Thread *current_thread) { */ void eglGraphicsWindow:: end_flip() { - if (_gsg != (GraphicsStateGuardian *)NULL && _flip_ready) { + if (_gsg != nullptr && _flip_ready) { // It doesn't appear to be necessary to ensure the graphics context is // current before flipping the windows, and insisting on doing so can be a @@ -199,7 +199,7 @@ end_flip() { */ void eglGraphicsWindow:: close_window() { - if (_gsg != (GraphicsStateGuardian *)NULL) { + if (_gsg != nullptr) { if (!eglMakeCurrent(_egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) { egldisplay_cat.error() << "Failed to call eglMakeCurrent: " << get_egl_error_string(eglGetError()) << "\n"; @@ -207,9 +207,9 @@ close_window() { _gsg.clear(); } - if (_ic != (XIC)NULL) { + if (_ic != (XIC)nullptr) { XDestroyIC(_ic); - _ic = (XIC)NULL; + _ic = (XIC)nullptr; } if (_egl_surface != 0) { @@ -219,9 +219,9 @@ close_window() { } } - if (_xwindow != (X11_Window)NULL) { + if (_xwindow != (X11_Window)nullptr) { XDestroyWindow(_display, _xwindow); - _xwindow = (X11_Window)NULL; + _xwindow = (X11_Window)nullptr; // This may be necessary if we just closed the last X window in an // application, so the server hears the close request. @@ -243,7 +243,7 @@ open_window() { eglGraphicsStateGuardian *eglgsg; if (_gsg == 0) { // There is no old gsg. Create a new one. - eglgsg = new eglGraphicsStateGuardian(_engine, _pipe, NULL); + eglgsg = new eglGraphicsStateGuardian(_engine, _pipe, nullptr); eglgsg->choose_pixel_format(_fb_properties, egl_pipe->get_display(), egl_pipe->get_screen(), false, false); _gsg = eglgsg; } else { @@ -258,7 +258,7 @@ open_window() { } _visual_info = eglgsg->_visual; - if (_visual_info == NULL) { + if (_visual_info == nullptr) { // No X visual for this fbconfig; how can we open the window? egldisplay_cat.error() << "No X visual: cannot open window.\n"; @@ -271,7 +271,7 @@ open_window() { return false; } - _egl_surface = eglCreateWindowSurface(_egl_display, eglgsg->_fbconfig, (NativeWindowType) _xwindow, NULL); + _egl_surface = eglCreateWindowSurface(_egl_display, eglgsg->_fbconfig, (NativeWindowType) _xwindow, nullptr); if (eglGetError() != EGL_SUCCESS) { egldisplay_cat.error() << "Failed to create window surface.\n"; diff --git a/panda/src/egldisplay/eglGraphicsWindow.h b/panda/src/egldisplay/eglGraphicsWindow.h index 508365cc65..7647605fd3 100644 --- a/panda/src/egldisplay/eglGraphicsWindow.h +++ b/panda/src/egldisplay/eglGraphicsWindow.h @@ -25,7 +25,7 @@ class eglGraphicsWindow : public x11GraphicsWindow { public: eglGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/event/asyncFuture.I b/panda/src/event/asyncFuture.I index a11fb6b36a..bc46e17c9b 100644 --- a/panda/src/event/asyncFuture.I +++ b/panda/src/event/asyncFuture.I @@ -17,8 +17,8 @@ INLINE AsyncFuture:: AsyncFuture() : _manager(nullptr), - _future_state(FS_pending), - _result(nullptr) { + _result(nullptr), + _future_state(FS_pending) { } /** @@ -44,7 +44,7 @@ cancelled() const { * a coroutine task that exits with an exception. */ INLINE void AsyncFuture:: -set_done_event(const string &done_event) { +set_done_event(const std::string &done_event) { nassertv(!done()); _done_event = done_event; } @@ -53,7 +53,7 @@ set_done_event(const string &done_event) { * Returns the event name that will be triggered when the future finishes. * See set_done_event(). */ -INLINE const string &AsyncFuture:: +INLINE const std::string &AsyncFuture:: get_done_event() const { return _done_event; } @@ -89,7 +89,7 @@ get_result(TypedObject *&ptr, ReferenceCount *&ref_ptr) const { * Sets this future's result. Can only be called if done() returns false. */ INLINE void AsyncFuture:: -set_result(nullptr_t) { +set_result(std::nullptr_t) { set_result(nullptr, nullptr); } @@ -129,7 +129,7 @@ gather(Futures futures) { } else if (futures.size() == 1) { return futures[0].p(); } else { - return (AsyncFuture *)new AsyncGatheringFuture(move(futures)); + return (AsyncFuture *)new AsyncGatheringFuture(std::move(futures)); } } diff --git a/panda/src/event/asyncFuture.cxx b/panda/src/event/asyncFuture.cxx index 25ae6bfa1c..16540954ed 100644 --- a/panda/src/event/asyncFuture.cxx +++ b/panda/src/event/asyncFuture.cxx @@ -55,7 +55,7 @@ cancel() { * */ void AsyncFuture:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type(); FutureState state = (FutureState)AtomicAdjust::get(_future_state); switch (state) { @@ -159,7 +159,7 @@ notify_done(bool clean_exit) { if (clean_exit && !_done_event.empty()) { PT_Event event = new Event(_done_event); event->add_parameter(EventParameter(this)); - throw_event(move(event)); + throw_event(std::move(event)); } } @@ -273,9 +273,9 @@ wake_task(AsyncTask *task) { } { - manager->_lock.release(); + manager->_lock.unlock(); task->upon_birth(manager); - manager->_lock.acquire(); + manager->_lock.lock(); nassertv(task->_manager == nullptr && task->_state == AsyncTask::S_inactive); @@ -308,7 +308,7 @@ wake_task(AsyncTask *task) { */ AsyncGatheringFuture:: AsyncGatheringFuture(AsyncFuture::Futures futures) : - _futures(move(futures)), + _futures(std::move(futures)), _num_pending(0) { bool any_pending = false; diff --git a/panda/src/event/asyncFuture.h b/panda/src/event/asyncFuture.h index cbed94b158..27cab7b585 100644 --- a/panda/src/event/asyncFuture.h +++ b/panda/src/event/asyncFuture.h @@ -70,20 +70,20 @@ PUBLISHED: virtual bool cancel(); - INLINE void set_done_event(const string &done_event); - INLINE const string &get_done_event() const; + INLINE void set_done_event(const std::string &done_event); + INLINE const std::string &get_done_event() const; MAKE_PROPERTY(done_event, get_done_event, set_done_event); EXTENSION(PyObject *add_done_callback(PyObject *self, PyObject *fn)); EXTENSION(static PyObject *gather(PyObject *args)); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; BLOCKING void wait(); BLOCKING void wait(double timeout); - INLINE void set_result(nullptr_t); + INLINE void set_result(std::nullptr_t); INLINE void set_result(TypedObject *result); INLINE void set_result(TypedReferenceCount *result); INLINE void set_result(TypedWritableReferenceCount *result); @@ -125,7 +125,7 @@ protected: PT(ReferenceCount) _result_ref; AtomicAdjust::Integer _future_state; - string _done_event; + std::string _done_event; // Tasks and gathering futures waiting for this one to complete. Futures _waiting; @@ -152,7 +152,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const AsyncFuture &fut) { +INLINE std::ostream &operator << (std::ostream &out, const AsyncFuture &fut) { fut.output(out); return out; }; @@ -160,7 +160,7 @@ INLINE ostream &operator << (ostream &out, const AsyncFuture &fut) { /** * Specific future that collects the results of several futures. */ -class EXPCL_PANDA_EVENT AsyncGatheringFuture FINAL : public AsyncFuture { +class EXPCL_PANDA_EVENT AsyncGatheringFuture final : public AsyncFuture { private: AsyncGatheringFuture(AsyncFuture::Futures futures); diff --git a/panda/src/event/asyncFuture_ext.cxx b/panda/src/event/asyncFuture_ext.cxx index 3150c09d7d..00ee3516b1 100644 --- a/panda/src/event/asyncFuture_ext.cxx +++ b/panda/src/event/asyncFuture_ext.cxx @@ -306,7 +306,7 @@ gather(PyObject *args) { return Dtool_Raise_ArgTypeError(item, i, "gather", "coroutine, task or future"); } - AsyncFuture *future = AsyncFuture::gather(move(futures)); + AsyncFuture *future = AsyncFuture::gather(std::move(futures)); if (future != nullptr) { future->ref(); return DTool_CreatePyInstanceTyped((void *)future, Dtool_AsyncFuture, true, false, future->get_type_index()); diff --git a/panda/src/event/asyncTask.I b/panda/src/event/asyncTask.I index 869b0b33f7..c9cdbeb179 100644 --- a/panda/src/event/asyncTask.I +++ b/panda/src/event/asyncTask.I @@ -131,7 +131,7 @@ get_start_frame() const { */ INLINE void AsyncTask:: clear_name() { - set_name(string()); + set_name(std::string()); } /** @@ -147,7 +147,7 @@ get_task_id() const { * Returns the AsyncTaskChain on which this task will be running. Each task * chain runs tasks independently of the others. */ -INLINE const string &AsyncTask:: +INLINE const std::string &AsyncTask:: get_task_chain() const { return _chain_name; } @@ -176,7 +176,7 @@ get_priority() const { * returns S_inactive). */ INLINE void AsyncTask:: -set_done_event(const string &done_event) { +set_done_event(const std::string &done_event) { nassertv(_state == S_inactive); _done_event = done_event; } diff --git a/panda/src/event/asyncTask.cxx b/panda/src/event/asyncTask.cxx index 9f70f0e5ad..806d8e87af 100644 --- a/panda/src/event/asyncTask.cxx +++ b/panda/src/event/asyncTask.cxx @@ -18,6 +18,8 @@ #include "throw_event.h" #include "eventParameter.h" +using std::string; + AtomicAdjust::Integer AsyncTask::_next_task_id; PStatCollector AsyncTask::_show_code_pcollector("App:Show code"); TypeHandle AsyncTask::_type_handle; @@ -34,8 +36,8 @@ AsyncTask(const string &name) : _sort(0), _priority(0), _state(S_inactive), - _servicing_thread(NULL), - _chain(NULL), + _servicing_thread(nullptr), + _chain(nullptr), _start_time(0.0), _start_frame(0), _dt(0.0), @@ -59,7 +61,7 @@ AsyncTask(const string &name) : */ AsyncTask:: ~AsyncTask() { - nassertv(_state == S_inactive && _manager == NULL && _chain == NULL); + nassertv(_state == S_inactive && _manager == nullptr && _chain == nullptr); } /** @@ -100,7 +102,7 @@ remove() { */ double AsyncTask:: get_wake_time() const { - if (_manager != (AsyncTaskManager *)NULL) { + if (_manager != nullptr) { MutexHolder holder(_manager->_lock); if (_state == S_sleeping) { return _wake_time; @@ -122,7 +124,7 @@ get_wake_time() const { */ void AsyncTask:: recalc_wake_time() { - if (_manager != (AsyncTaskManager *)NULL) { + if (_manager != nullptr) { MutexHolder holder(_manager->_lock); if (_state == S_sleeping) { double now = _manager->_clock->get_frame_time(); @@ -144,7 +146,7 @@ recalc_wake_time() { double AsyncTask:: get_elapsed_time() const { nassertr(_state != S_inactive, 0.0); - nassertr(_manager != (AsyncTaskManager *)NULL, 0.0); + nassertr(_manager != nullptr, 0.0); return _manager->_clock->get_frame_time() - _start_time; } @@ -157,7 +159,7 @@ get_elapsed_time() const { int AsyncTask:: get_elapsed_frames() const { nassertr(_state != S_inactive, 0); - nassertr(_manager != (AsyncTaskManager *)NULL, 0); + nassertr(_manager != nullptr, 0); return _manager->_clock->get_frame_count() - _start_frame; } @@ -166,7 +168,7 @@ get_elapsed_frames() const { */ void AsyncTask:: set_name(const string &name) { - if (_manager != (AsyncTaskManager *)NULL) { + if (_manager != nullptr) { MutexHolder holder(_manager->_lock); if (Namable::get_name() != name) { // Changing an active task's name requires moving it around on its name @@ -187,7 +189,7 @@ set_name(const string &name) { size_t end = name.size(); size_t colon = name.find(':'); if (colon != string::npos) { - end = min(end, colon); + end = std::min(end, colon); } // If the name ends with a hyphen followed by a string of digits, we strip @@ -247,7 +249,7 @@ get_name_prefix() const { void AsyncTask:: set_task_chain(const string &chain_name) { if (chain_name != _chain_name) { - if (_manager != (AsyncTaskManager *)NULL) { + if (_manager != nullptr) { MutexHolder holder(_manager->_lock); if (_state == S_active) { // Changing chains on an "active" (i.e. enqueued) task means removing @@ -256,7 +258,7 @@ set_task_chain(const string &chain_name) { PT(AsyncTaskManager) manager = _manager; AsyncTaskChain *chain_a = manager->do_find_task_chain(_chain_name); - nassertv(chain_a != (AsyncTaskChain *)NULL); + nassertv(chain_a != nullptr); chain_a->do_remove(this); _chain_name = chain_name; @@ -290,14 +292,14 @@ set_task_chain(const string &chain_name) { void AsyncTask:: set_sort(int sort) { if (sort != _sort) { - if (_manager != (AsyncTaskManager *)NULL) { + if (_manager != nullptr) { MutexHolder holder(_manager->_lock); if (_state == S_active && _sort >= _chain->_current_sort) { // Changing sort on an "active" (i.e. enqueued) task means removing // it and re-inserting it into the queue. PT(AsyncTask) hold_task = this; AsyncTaskChain *chain = _manager->do_find_task_chain(_chain_name); - nassertv(chain != (AsyncTaskChain *)NULL); + nassertv(chain != nullptr); chain->do_remove(this); _sort = sort; chain->do_add(this); @@ -335,14 +337,14 @@ set_sort(int sort) { void AsyncTask:: set_priority(int priority) { if (priority != _priority) { - if (_manager != (AsyncTaskManager *)NULL) { + if (_manager != nullptr) { MutexHolder holder(_manager->_lock); if (_state == S_active && _sort >= _chain->_current_sort) { // Changing priority on an "active" (i.e. enqueued) task means // removing it and re-inserting it into the queue. PT(AsyncTask) hold_task = this; AsyncTaskChain *chain = _manager->do_find_task_chain(_chain_name); - nassertv(chain != (AsyncTaskChain *)NULL); + nassertv(chain != nullptr); chain->do_remove(this); _priority = priority; chain->do_add(this); @@ -364,7 +366,7 @@ set_priority(int priority) { * */ void AsyncTask:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type(); if (has_name()) { out << " " << get_name(); @@ -378,7 +380,7 @@ output(ostream &out) const { void AsyncTask:: jump_to_task_chain(AsyncTaskManager *manager) { AsyncTaskChain *chain_b = manager->do_find_task_chain(_chain_name); - if (chain_b == (AsyncTaskChain *)NULL) { + if (chain_b == nullptr) { task_cat.warning() << "Creating implicit AsyncTaskChain " << _chain_name << " for " << manager->get_type() << " " @@ -415,7 +417,7 @@ unlock_and_do_task() { #endif // __GNUC__ // It's important to release the lock while the task is being serviced. - _manager->_lock.release(); + _manager->_lock.unlock(); double start = clock->get_real_time(); _task_pcollector.start(); @@ -424,10 +426,10 @@ unlock_and_do_task() { double end = clock->get_real_time(); // Now reacquire the lock (so we can return with the lock held). - _manager->_lock.acquire(); + _manager->_lock.lock(); _dt = end - start; - _max_dt = max(_dt, _max_dt); + _max_dt = std::max(_dt, _max_dt); _total_dt += _dt; _chain->_time_in_frame += _dt; @@ -540,7 +542,7 @@ upon_death(AsyncTaskManager *manager, bool clean_exit) { //NB. done_event is now being thrown in AsyncFuture::notify_done(). // Throw a generic remove event for the manager. - if (manager != (AsyncTaskManager *)NULL) { + if (manager != nullptr) { string remove_name = manager->get_name() + "-removeTask"; PT_Event event = new Event(remove_name); event->add_parameter(EventParameter(this)); diff --git a/panda/src/event/asyncTask.h b/panda/src/event/asyncTask.h index 9712daa0f5..f5871ae2f2 100644 --- a/panda/src/event/asyncTask.h +++ b/panda/src/event/asyncTask.h @@ -31,7 +31,7 @@ class AsyncTaskChain; */ class EXPCL_PANDA_EVENT AsyncTask : public AsyncFuture, public Namable { public: - AsyncTask(const string &name = string()); + AsyncTask(const std::string &name = std::string()); ALLOC_DELETED_CHAIN(AsyncTask); PUBLISHED: @@ -76,14 +76,14 @@ PUBLISHED: INLINE int get_start_frame() const; int get_elapsed_frames() const; - void set_name(const string &name); + void set_name(const std::string &name); INLINE void clear_name(); - string get_name_prefix() const; + std::string get_name_prefix() const; INLINE AtomicAdjust::Integer get_task_id() const; - void set_task_chain(const string &chain_name); - INLINE const string &get_task_chain() const; + void set_task_chain(const std::string &chain_name); + INLINE const std::string &get_task_chain() const; void set_sort(int sort); INLINE int get_sort() const; @@ -91,20 +91,20 @@ PUBLISHED: void set_priority(int priority); INLINE int get_priority() const; - INLINE void set_done_event(const string &done_event); + INLINE void set_done_event(const std::string &done_event); INLINE double get_dt() const; INLINE double get_max_dt() const; INLINE double get_average_dt() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: void jump_to_task_chain(AsyncTaskManager *manager); DoneStatus unlock_and_do_task(); - virtual bool cancel() FINAL; - virtual bool is_task() const FINAL {return true;} + virtual bool cancel() final; + virtual bool is_task() const final {return true;} virtual bool is_runnable(); virtual DoneStatus do_task(); @@ -113,7 +113,7 @@ protected: protected: AtomicAdjust::Integer _task_id; - string _chain_name; + std::string _chain_name; double _delay; bool _has_delay; double _wake_time; @@ -163,7 +163,7 @@ private: friend class AsyncTaskSequence; }; -INLINE ostream &operator << (ostream &out, const AsyncTask &task) { +INLINE std::ostream &operator << (std::ostream &out, const AsyncTask &task) { task.output(out); return out; }; diff --git a/panda/src/event/asyncTaskChain.cxx b/panda/src/event/asyncTaskChain.cxx index bb82e00f92..34e458691e 100644 --- a/panda/src/event/asyncTaskChain.cxx +++ b/panda/src/event/asyncTaskChain.cxx @@ -23,6 +23,11 @@ #include #include // For sprintf/snprintf +using std::max; +using std::ostream; +using std::ostringstream; +using std::string; + TypeHandle AsyncTaskChain::_type_handle; PStatCollector AsyncTaskChain::_task_pcollector("Task"); @@ -404,8 +409,8 @@ write(ostream &out, int indent_level) const { */ void AsyncTaskChain:: do_add(AsyncTask *task) { - nassertv(task->_chain == NULL && - task->_manager == NULL && + nassertv(task->_chain == nullptr && + task->_manager == nullptr && task->_chain_name == get_name() && task->_state == AsyncTask::S_inactive); nassertv(!do_has_task(task)); @@ -596,11 +601,11 @@ do_cleanup() { nassertv(_num_tasks == 0 || _num_tasks == 1); // Now go back and call the upon_death functions. - _manager->_lock.release(); + _manager->_lock.unlock(); for (ti = dead.begin(); ti != dead.end(); ++ti) { (*ti)->upon_death(_manager, false); } - _manager->_lock.acquire(); + _manager->_lock.lock(); if (task_cat.is_spam()) { do_output(task_cat.spam()); @@ -652,7 +657,7 @@ service_one_task(AsyncTaskChain::AsyncTaskChainThread *thread) { pop_heap(_active.begin(), _active.end(), AsyncTaskSortPriority()); _active.pop_back(); - if (thread != (AsyncTaskChain::AsyncTaskChainThread *)NULL) { + if (thread != nullptr) { thread->_servicing = task; } @@ -669,10 +674,10 @@ service_one_task(AsyncTaskChain::AsyncTaskChainThread *thread) { AsyncTask::DoneStatus ds = task->unlock_and_do_task(); - if (thread != (AsyncTaskChain::AsyncTaskChainThread *)NULL) { - thread->_servicing = NULL; + if (thread != nullptr) { + thread->_servicing = nullptr; } - task->_servicing_thread = NULL; + task->_servicing_thread = nullptr; if (task->_chain == this) { if (task->_state == AsyncTask::S_servicing_removed) { @@ -791,9 +796,9 @@ cleanup_task(AsyncTask *task, bool upon_death, bool clean_exit) { task->_manager = nullptr; if (upon_death) { - _manager->_lock.release(); + _manager->_lock.unlock(); task->upon_death(_manager, clean_exit); - _manager->_lock.acquire(); + _manager->_lock.lock(); } } @@ -1031,7 +1036,7 @@ do_stop_threads() { // We have to release the lock while we join, so the threads can wake up // and see that we're shutting down. - _manager->_lock.release(); + _manager->_lock.unlock(); Threads::iterator ti; for (ti = wait_threads.begin(); ti != wait_threads.end(); ++ti) { if (task_cat.is_debug()) { @@ -1046,7 +1051,7 @@ do_stop_threads() { << *Thread::get_current_thread() << "\n"; } } - _manager->_lock.acquire(); + _manager->_lock.lock(); _state = S_initial; @@ -1099,7 +1104,7 @@ do_get_active_tasks() const { Threads::const_iterator thi; for (thi = _threads.begin(); thi != _threads.end(); ++thi) { AsyncTask *task = (*thi)->_servicing; - if (task != (AsyncTask *)NULL) { + if (task != nullptr) { result.add_task(task); } } @@ -1188,7 +1193,7 @@ do_poll() { // in poll(). But it's possible, if someone calls set_num_threads() // while we're processing. _num_busy_threads++; - service_one_task(NULL); + service_one_task(nullptr); _num_busy_threads--; _cvar.notify_all(); @@ -1228,7 +1233,7 @@ cleanup_pickup_mode() { */ void AsyncTaskChain:: do_output(ostream &out) const { - if (_manager != (AsyncTaskManager *)NULL) { + if (_manager != nullptr) { out << _manager->get_type() << " " << _manager->get_name(); } else { out << "(no manager)"; @@ -1288,7 +1293,7 @@ do_write(ostream &out, int indent_level) const { Threads::const_iterator thi; for (thi = _threads.begin(); thi != _threads.end(); ++thi) { AsyncTask *task = (*thi)->_servicing; - if (task != (AsyncTask *)NULL) { + if (task != nullptr) { tasks.push_back(task); } } @@ -1379,7 +1384,7 @@ AsyncTaskChain::AsyncTaskChainThread:: AsyncTaskChainThread(const string &name, AsyncTaskChain *chain) : Thread(name, chain->get_name()), _chain(chain), - _servicing(NULL) + _servicing(nullptr) { } diff --git a/panda/src/event/asyncTaskChain.h b/panda/src/event/asyncTaskChain.h index 5f81f6c3dd..c211b30c85 100644 --- a/panda/src/event/asyncTaskChain.h +++ b/panda/src/event/asyncTaskChain.h @@ -49,7 +49,7 @@ class AsyncTaskManager; */ class EXPCL_PANDA_EVENT AsyncTaskChain : public TypedReferenceCount, public Namable { public: - AsyncTaskChain(AsyncTaskManager *manager, const string &name); + AsyncTaskChain(AsyncTaskManager *manager, const std::string &name); ~AsyncTaskChain(); PUBLISHED: @@ -88,8 +88,8 @@ PUBLISHED: void poll(); double get_next_wake_time() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; protected: class AsyncTaskChainThread; @@ -115,15 +115,15 @@ protected: void cleanup_pickup_mode(); INLINE double do_get_next_wake_time() const; static INLINE double get_wake_time(AsyncTask *task); - void do_output(ostream &out) const; - void do_write(ostream &out, int indent_level) const; + void do_output(std::ostream &out) const; + void do_write(std::ostream &out, int indent_level) const; - void write_task_line(ostream &out, int indent_level, AsyncTask *task, double now) const; + void write_task_line(std::ostream &out, int indent_level, AsyncTask *task, double now) const; protected: class AsyncTaskChainThread : public Thread { public: - AsyncTaskChainThread(const string &name, AsyncTaskChain *chain); + AsyncTaskChainThread(const std::string &name, AsyncTaskChain *chain); virtual void thread_main(); AsyncTaskChain *_chain; @@ -220,7 +220,7 @@ private: friend class AsyncTaskSortWakeTime; }; -INLINE ostream &operator << (ostream &out, const AsyncTaskChain &chain) { +INLINE std::ostream &operator << (std::ostream &out, const AsyncTaskChain &chain) { chain.output(out); return out; }; diff --git a/panda/src/event/asyncTaskCollection.cxx b/panda/src/event/asyncTaskCollection.cxx index 80999362e1..b6fd56fece 100644 --- a/panda/src/event/asyncTaskCollection.cxx +++ b/panda/src/event/asyncTaskCollection.cxx @@ -46,7 +46,7 @@ add_task(AsyncTask *task) { // If the pointer to our internal array is shared by any other // AsyncTaskCollections, we have to copy the array now so we won't // inadvertently modify any of our brethren AsyncTaskCollection objects. - nassertv(task != (AsyncTask *)NULL); + nassertv(task != nullptr); if (_tasks.get_ref_count() > 1) { AsyncTasks old_tasks = _tasks; @@ -174,7 +174,7 @@ clear() { * if no task has that name. */ AsyncTask *AsyncTaskCollection:: -find_task(const string &name) const { +find_task(const std::string &name) const { size_t num_tasks = get_num_tasks(); for (size_t i = 0; i < num_tasks; ++i) { AsyncTask *task = get_task(i); @@ -182,7 +182,7 @@ find_task(const string &name) const { return task; } } - return NULL; + return nullptr; } /** @@ -246,7 +246,7 @@ size() const { * indicated output stream. */ void AsyncTaskCollection:: -output(ostream &out) const { +output(std::ostream &out) const { if (get_num_tasks() == 1) { out << "1 AsyncTask"; } else { @@ -259,7 +259,7 @@ output(ostream &out) const { * indicated output stream. */ void AsyncTaskCollection:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { for (size_t i = 0; i < get_num_tasks(); i++) { indent(out, indent_level) << *get_task(i) << "\n"; } diff --git a/panda/src/event/asyncTaskCollection.h b/panda/src/event/asyncTaskCollection.h index 4ed6f6a59b..a2334df839 100644 --- a/panda/src/event/asyncTaskCollection.h +++ b/panda/src/event/asyncTaskCollection.h @@ -24,7 +24,7 @@ * * TODO: None of this is thread-safe yet. */ -class EXPCL_PANDA_PGRAPH AsyncTaskCollection { +class EXPCL_PANDA_EVENT AsyncTaskCollection { PUBLISHED: AsyncTaskCollection(); AsyncTaskCollection(const AsyncTaskCollection ©); @@ -39,7 +39,7 @@ PUBLISHED: bool has_task(AsyncTask *task) const; void clear(); - AsyncTask *find_task(const string &name) const; + AsyncTask *find_task(const std::string &name) const; size_t get_num_tasks() const; AsyncTask *get_task(size_t index) const; @@ -50,15 +50,15 @@ PUBLISHED: INLINE void operator += (const AsyncTaskCollection &other); INLINE AsyncTaskCollection operator + (const AsyncTaskCollection &other) const; - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; private: typedef PTA(PT(AsyncTask)) AsyncTasks; AsyncTasks _tasks; }; -INLINE ostream &operator << (ostream &out, const AsyncTaskCollection &col) { +INLINE std::ostream &operator << (std::ostream &out, const AsyncTaskCollection &col) { col.output(out); return out; } diff --git a/panda/src/event/asyncTaskManager.I b/panda/src/event/asyncTaskManager.I index c1e5775a55..8cf788dc9e 100644 --- a/panda/src/event/asyncTaskManager.I +++ b/panda/src/event/asyncTaskManager.I @@ -48,7 +48,7 @@ get_num_tasks() const { */ INLINE AsyncTaskManager *AsyncTaskManager:: get_global_ptr() { - if (_global_ptr == (AsyncTaskManager *)NULL) { + if (_global_ptr == nullptr) { make_global_ptr(); } return _global_ptr; diff --git a/panda/src/event/asyncTaskManager.cxx b/panda/src/event/asyncTaskManager.cxx index 5e1bf9601c..b80908ddc5 100644 --- a/panda/src/event/asyncTaskManager.cxx +++ b/panda/src/event/asyncTaskManager.cxx @@ -22,7 +22,9 @@ #include "config_event.h" #include -AsyncTaskManager *AsyncTaskManager::_global_ptr = NULL; +using std::string; + +AsyncTaskManager *AsyncTaskManager::_global_ptr = nullptr; TypeHandle AsyncTaskManager::_type_handle; @@ -114,7 +116,7 @@ get_num_task_chains() const { AsyncTaskChain *AsyncTaskManager:: get_task_chain(int n) const { MutexHolder holder(_lock); - nassertr(n >= 0 && n < (int)_task_chains.size(), NULL); + nassertr(n >= 0 && n < (int)_task_chains.size(), nullptr); return _task_chains[n]; } @@ -196,19 +198,19 @@ add(AsyncTask *task) { } } - nassertv(task->_manager == NULL && + nassertv(task->_manager == nullptr && task->_state == AsyncTask::S_inactive); nassertv(!do_has_task(task)); - _lock.release(); + _lock.unlock(); task->upon_birth(this); - _lock.acquire(); - nassertv(task->_manager == NULL && + _lock.lock(); + nassertv(task->_manager == nullptr && task->_state == AsyncTask::S_inactive); nassertv(!do_has_task(task)); AsyncTaskChain *chain = do_find_task_chain(task->_chain_name); - if (chain == (AsyncTaskChain *)NULL) { + if (chain == nullptr) { task_cat.warning() << "Creating implicit AsyncTaskChain " << task->_chain_name << " for " << get_type() << " " << get_name() << "\n"; @@ -257,7 +259,7 @@ find_task(const string &name) const { return (*tbni); } - return NULL; + return nullptr; } /** @@ -508,7 +510,7 @@ get_next_wake_time() const { got_any = true; next_wake_time = time; } else { - next_wake_time = min(time, next_wake_time); + next_wake_time = std::min(time, next_wake_time); } } } @@ -520,7 +522,7 @@ get_next_wake_time() const { * */ void AsyncTaskManager:: -output(ostream &out) const { +output(std::ostream &out) const { MutexHolder holder(_lock); do_output(out); } @@ -529,7 +531,7 @@ output(ostream &out) const { * */ void AsyncTaskManager:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { MutexHolder holder(_lock); indent(out, indent_level) << get_type() << " " << get_name() << "\n"; @@ -576,7 +578,7 @@ do_find_task_chain(const string &name) { return (*tci); } - return NULL; + return nullptr; } /** @@ -629,7 +631,7 @@ do_has_task(AsyncTask *task) const { * */ void AsyncTaskManager:: -do_output(ostream &out) const { +do_output(std::ostream &out) const { out << get_type() << " " << get_name() << "; " << _num_tasks << " tasks"; } @@ -639,7 +641,7 @@ do_output(ostream &out) const { */ void AsyncTaskManager:: make_global_ptr() { - nassertv(_global_ptr == (AsyncTaskManager *)NULL); + nassertv(_global_ptr == nullptr); _global_ptr = new AsyncTaskManager("TaskManager"); _global_ptr->ref(); diff --git a/panda/src/event/asyncTaskManager.h b/panda/src/event/asyncTaskManager.h index d843508de7..69711ab6f6 100644 --- a/panda/src/event/asyncTaskManager.h +++ b/panda/src/event/asyncTaskManager.h @@ -47,7 +47,7 @@ */ class EXPCL_PANDA_EVENT AsyncTaskManager : public TypedReferenceCount, public Namable { PUBLISHED: - explicit AsyncTaskManager(const string &name); + explicit AsyncTaskManager(const std::string &name); BLOCKING virtual ~AsyncTaskManager(); BLOCKING void cleanup(); @@ -59,15 +59,15 @@ PUBLISHED: int get_num_task_chains() const; AsyncTaskChain *get_task_chain(int n) const; MAKE_SEQ(get_task_chains, get_num_task_chains, get_task_chain); - AsyncTaskChain *make_task_chain(const string &name); - AsyncTaskChain *find_task_chain(const string &name); - BLOCKING bool remove_task_chain(const string &name); + AsyncTaskChain *make_task_chain(const std::string &name); + AsyncTaskChain *find_task_chain(const std::string &name); + BLOCKING bool remove_task_chain(const std::string &name); void add(AsyncTask *task); bool has_task(AsyncTask *task) const; - AsyncTask *find_task(const string &name) const; - AsyncTaskCollection find_tasks(const string &name) const; + AsyncTask *find_task(const std::string &name) const; + AsyncTaskCollection find_tasks(const std::string &name) const; AsyncTaskCollection find_tasks_matching(const GlobPattern &pattern) const; bool remove(AsyncTask *task); @@ -90,21 +90,21 @@ PUBLISHED: double get_next_wake_time() const; MAKE_PROPERTY(next_wake_time, get_next_wake_time); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; INLINE static AsyncTaskManager *get_global_ptr(); protected: - AsyncTaskChain *do_make_task_chain(const string &name); - AsyncTaskChain *do_find_task_chain(const string &name); + AsyncTaskChain *do_make_task_chain(const std::string &name); + AsyncTaskChain *do_find_task_chain(const std::string &name); INLINE void add_task_by_name(AsyncTask *task); void remove_task_by_name(AsyncTask *task); bool do_has_task(AsyncTask *task) const; - virtual void do_output(ostream &out) const; + virtual void do_output(std::ostream &out) const; private: static void make_global_ptr(); @@ -159,7 +159,7 @@ private: friend class PythonTask; }; -INLINE ostream &operator << (ostream &out, const AsyncTaskManager &manager) { +INLINE std::ostream &operator << (std::ostream &out, const AsyncTaskManager &manager) { manager.output(out); return out; }; diff --git a/panda/src/event/asyncTaskSequence.I b/panda/src/event/asyncTaskSequence.I index 28d94f2f75..332303df7a 100644 --- a/panda/src/event/asyncTaskSequence.I +++ b/panda/src/event/asyncTaskSequence.I @@ -34,7 +34,7 @@ get_repeat_count() const { * Returns the index of the task within the sequence that is currently being * executed (or that will be executed at the next epoch). */ -INLINE int AsyncTaskSequence:: +INLINE size_t AsyncTaskSequence:: get_current_task_index() const { return _task_index; } diff --git a/panda/src/event/asyncTaskSequence.cxx b/panda/src/event/asyncTaskSequence.cxx index fe306c26a3..82541ec8da 100644 --- a/panda/src/event/asyncTaskSequence.cxx +++ b/panda/src/event/asyncTaskSequence.cxx @@ -20,7 +20,7 @@ TypeHandle AsyncTaskSequence::_type_handle; * */ AsyncTaskSequence:: -AsyncTaskSequence(const string &name) : +AsyncTaskSequence(const std::string &name) : AsyncTask(name), _repeat_count(0), _task_index(0) @@ -32,7 +32,7 @@ AsyncTaskSequence(const string &name) : */ AsyncTaskSequence:: ~AsyncTaskSequence() { - set_current_task(NULL, true); + set_current_task(nullptr, true); } /** @@ -60,7 +60,7 @@ do_task() { if (_task_index >= get_num_tasks()) { // Ran off the end of the task list. - set_current_task(NULL, true); + set_current_task(nullptr, true); _task_index = 0; if (_task_index >= get_num_tasks()) { return DS_done; @@ -76,7 +76,7 @@ do_task() { AsyncTask *task = get_task(_task_index); set_current_task(task, true); - nassertr(_current_task != (AsyncTask *)NULL, DS_exit); + nassertr(_current_task != nullptr, DS_exit); DoneStatus result = _current_task->do_task(); switch (result) { @@ -127,7 +127,7 @@ void AsyncTaskSequence:: upon_birth(AsyncTaskManager *manager) { AsyncTask::upon_birth(manager); _task_index = 0; - set_current_task(NULL, true); + set_current_task(nullptr, true); } /** @@ -147,7 +147,7 @@ upon_birth(AsyncTaskManager *manager) { void AsyncTaskSequence:: upon_death(AsyncTaskManager *manager, bool clean_exit) { AsyncTask::upon_death(manager, clean_exit); - set_current_task(NULL, clean_exit); + set_current_task(nullptr, clean_exit); } /** @@ -159,22 +159,22 @@ set_current_task(AsyncTask *task, bool clean_exit) { return; } - if (_current_task != (AsyncTask *)NULL) { + if (_current_task != nullptr) { nassertv(_current_task->_state == S_active_nested); - nassertv(_current_task->_manager == _manager || _manager == NULL); + nassertv(_current_task->_manager == _manager || _manager == nullptr); _current_task->_state = S_inactive; - _current_task->_manager = NULL; + _current_task->_manager = nullptr; _current_task->upon_death(_manager, clean_exit); } _current_task = task; - if (_current_task != (AsyncTask *)NULL) { + if (_current_task != nullptr) { nassertv(_current_task->_state == S_inactive); - nassertv(_current_task->_manager == NULL); + nassertv(_current_task->_manager == nullptr); _current_task->upon_birth(_manager); nassertv(_current_task->_state == S_inactive); - nassertv(_current_task->_manager == NULL); + nassertv(_current_task->_manager == nullptr); _current_task->_manager = _manager; _current_task->_state = S_active_nested; diff --git a/panda/src/event/asyncTaskSequence.h b/panda/src/event/asyncTaskSequence.h index de0127a1d8..096d1f6b88 100644 --- a/panda/src/event/asyncTaskSequence.h +++ b/panda/src/event/asyncTaskSequence.h @@ -32,14 +32,14 @@ class AsyncTaskManager; */ class EXPCL_PANDA_EVENT AsyncTaskSequence : public AsyncTask, public AsyncTaskCollection { PUBLISHED: - explicit AsyncTaskSequence(const string &name); + explicit AsyncTaskSequence(const std::string &name); virtual ~AsyncTaskSequence(); ALLOC_DELETED_CHAIN(AsyncTaskSequence); INLINE void set_repeat_count(int repeat_count); INLINE int get_repeat_count() const; - INLINE int get_current_task_index() const; + INLINE size_t get_current_task_index() const; protected: virtual bool is_runnable(); @@ -51,7 +51,7 @@ private: void set_current_task(AsyncTask *task, bool clean_exit); int _repeat_count; - int _task_index; + size_t _task_index; PT(AsyncTask) _current_task; public: diff --git a/panda/src/event/buttonEvent.I b/panda/src/event/buttonEvent.I index 41bea9f2d5..f082a4bee9 100644 --- a/panda/src/event/buttonEvent.I +++ b/panda/src/event/buttonEvent.I @@ -55,7 +55,7 @@ ButtonEvent(int keycode, double time) : * */ INLINE ButtonEvent:: -ButtonEvent(const wstring &candidate_string, size_t highlight_start, +ButtonEvent(const std::wstring &candidate_string, size_t highlight_start, size_t highlight_end, size_t cursor_pos) : _button(ButtonHandle::none()), _keycode(0), diff --git a/panda/src/event/buttonEvent.cxx b/panda/src/event/buttonEvent.cxx index 38dbbffb6a..170812958b 100644 --- a/panda/src/event/buttonEvent.cxx +++ b/panda/src/event/buttonEvent.cxx @@ -21,7 +21,7 @@ * */ void ButtonEvent:: -output(ostream &out) const { +output(std::ostream &out) const { switch (_type) { case T_down: out << "button " << _button << " down"; diff --git a/panda/src/event/buttonEvent.h b/panda/src/event/buttonEvent.h index d2e2b82176..e839924c48 100644 --- a/panda/src/event/buttonEvent.h +++ b/panda/src/event/buttonEvent.h @@ -87,7 +87,7 @@ public: INLINE ButtonEvent(); INLINE ButtonEvent(ButtonHandle button, Type type, double time = ClockObject::get_global_clock()->get_frame_time()); INLINE ButtonEvent(int keycode, double time = ClockObject::get_global_clock()->get_frame_time()); - INLINE ButtonEvent(const wstring &candidate_string, size_t highlight_start, + INLINE ButtonEvent(const std::wstring &candidate_string, size_t highlight_start, size_t highlight_end, size_t cursor_pos); INLINE ButtonEvent(const ButtonEvent ©); INLINE void operator = (const ButtonEvent ©); @@ -98,7 +98,7 @@ public: INLINE bool update_mods(ModifierButtons &mods) const; - void output(ostream &out) const; + void output(std::ostream &out) const; void write_datagram(Datagram &dg) const; void read_datagram(DatagramIterator &scan); @@ -112,7 +112,7 @@ public: int _keycode; // _candidate_string will be filled in if type is T_candidate. - wstring _candidate_string; + std::wstring _candidate_string; size_t _highlight_start; size_t _highlight_end; size_t _cursor_pos; @@ -127,7 +127,7 @@ public: double _time; }; -INLINE ostream &operator << (ostream &out, const ButtonEvent &be) { +INLINE std::ostream &operator << (std::ostream &out, const ButtonEvent &be) { be.output(out); return out; } diff --git a/panda/src/event/buttonEventList.cxx b/panda/src/event/buttonEventList.cxx index 633329a5a1..21c9d45981 100644 --- a/panda/src/event/buttonEventList.cxx +++ b/panda/src/event/buttonEventList.cxx @@ -45,7 +45,7 @@ update_mods(ModifierButtons &mods) const { * */ void ButtonEventList:: -output(ostream &out) const { +output(std::ostream &out) const { if (_events.empty()) { out << "(no buttons)"; } else { @@ -65,7 +65,7 @@ output(ostream &out) const { * */ void ButtonEventList:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << _events.size() << " events:\n"; Events::const_iterator ei; for (ei = _events.begin(); ei != _events.end(); ++ei) { diff --git a/panda/src/event/buttonEventList.h b/panda/src/event/buttonEventList.h index d4f097f98d..c9d9479490 100644 --- a/panda/src/event/buttonEventList.h +++ b/panda/src/event/buttonEventList.h @@ -44,8 +44,8 @@ public: void add_events(const ButtonEventList &other); void update_mods(ModifierButtons &mods) const; - virtual void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; private: typedef pvector Events; @@ -79,7 +79,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const ButtonEventList &buttonlist) { +INLINE std::ostream &operator << (std::ostream &out, const ButtonEventList &buttonlist) { buttonlist.output(out); return out; } diff --git a/panda/src/event/event.I b/panda/src/event/event.I index dd2b0e95f6..fd60e3e10f 100644 --- a/panda/src/event/event.I +++ b/panda/src/event/event.I @@ -15,7 +15,7 @@ * */ INLINE void Event:: -set_name(const string &name) { +set_name(const std::string &name) { _name = name; } @@ -39,13 +39,13 @@ has_name() const { /** * */ -INLINE const string &Event:: +INLINE const std::string &Event:: get_name() const { return _name; } -INLINE ostream &operator << (ostream &out, const Event &n) { +INLINE std::ostream &operator << (std::ostream &out, const Event &n) { n.output(out); return out; } diff --git a/panda/src/event/event.cxx b/panda/src/event/event.cxx index fb510626d2..8a46d2586f 100644 --- a/panda/src/event/event.cxx +++ b/panda/src/event/event.cxx @@ -20,7 +20,7 @@ TypeHandle Event::_type_handle; * */ Event:: -Event(const string &event_name, EventReceiver *receiver) : +Event(const std::string &event_name, EventReceiver *receiver) : _name(event_name) { _receiver = receiver; @@ -86,7 +86,7 @@ get_parameter(int n) const { */ bool Event:: has_receiver() const { - return _receiver != (EventReceiver *)NULL; + return _receiver != nullptr; } /** @@ -110,14 +110,14 @@ set_receiver(EventReceiver *receiver) { */ void Event:: clear_receiver() { - _receiver = (EventReceiver *)NULL; + _receiver = nullptr; } /** * */ void Event:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_name(); out << "("; diff --git a/panda/src/event/event.h b/panda/src/event/event.h index e09c4c2500..beb13f0b11 100644 --- a/panda/src/event/event.h +++ b/panda/src/event/event.h @@ -32,15 +32,15 @@ class EventReceiver; */ class EXPCL_PANDA_EVENT Event : public TypedReferenceCount { PUBLISHED: - Event(const string &event_name, EventReceiver *receiver = NULL); + Event(const std::string &event_name, EventReceiver *receiver = nullptr); Event(const Event ©); void operator = (const Event ©); ~Event(); - INLINE void set_name(const string &name); + INLINE void set_name(const std::string &name); INLINE void clear_name(); INLINE bool has_name() const; - INLINE const string &get_name() const; + INLINE const std::string &get_name() const; void add_parameter(const EventParameter &obj); @@ -53,7 +53,7 @@ PUBLISHED: void set_receiver(EventReceiver *receiver); void clear_receiver(); - void output(ostream &out) const; + void output(std::ostream &out) const; MAKE_PROPERTY(name, get_name, set_name); MAKE_SEQ_PROPERTY(parameters, get_num_parameters, get_parameter); @@ -65,7 +65,7 @@ protected: EventReceiver *_receiver; private: - string _name; + std::string _name; public: static TypeHandle get_class_type() { @@ -85,7 +85,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const Event &n); +INLINE std::ostream &operator << (std::ostream &out, const Event &n); #include "event.I" diff --git a/panda/src/event/eventHandler.cxx b/panda/src/event/eventHandler.cxx index 020ba905d5..f74bd8c519 100644 --- a/panda/src/event/eventHandler.cxx +++ b/panda/src/event/eventHandler.cxx @@ -15,9 +15,11 @@ #include "eventQueue.h" #include "config_event.h" +using std::string; + TypeHandle EventHandler::_type_handle; -EventHandler *EventHandler::_global_event_handler = NULL; +EventHandler *EventHandler::_global_event_handler = nullptr; /** @@ -64,7 +66,7 @@ process_events() { */ void EventHandler:: dispatch_event(const Event *event) { - nassertv(event != (Event *)NULL); + nassertv(event != nullptr); // Is the event name defined in the hook table? It will be if anyone has // ever assigned a hook to this particular event name. @@ -82,7 +84,7 @@ dispatch_event(const Event *event) { event_cat->spam() << "calling callback 0x" << (void*)(*fi) << " for event '" << event->get_name() << "'" - << endl; + << std::endl; } (*fi)(event); } @@ -120,7 +122,7 @@ dispatch_event(const Event *event) { * */ void EventHandler:: -write(ostream &out) const { +write(std::ostream &out) const { Hooks::const_iterator hi; hi = _hooks.begin(); @@ -165,7 +167,7 @@ add_hook(const string &event_name, EventFunction *function) { if (event_cat.is_debug()) { event_cat.debug() << "adding hook for event '" << event_name - << "' with function 0x" << (void*)function << endl; + << "' with function 0x" << (void*)function << std::endl; } assert(!event_name.empty()); assert(function); @@ -357,7 +359,7 @@ make_global_event_handler() { * */ void EventHandler:: -write_hook(ostream &out, const EventHandler::Hooks::value_type &hook) const { +write_hook(std::ostream &out, const EventHandler::Hooks::value_type &hook) const { if (!hook.second.empty()) { out << hook.first << " has " << hook.second.size() << " functions.\n"; } @@ -367,7 +369,7 @@ write_hook(ostream &out, const EventHandler::Hooks::value_type &hook) const { * */ void EventHandler:: -write_cbhook(ostream &out, const EventHandler::CallbackHooks::value_type &hook) const { +write_cbhook(std::ostream &out, const EventHandler::CallbackHooks::value_type &hook) const { if (!hook.second.empty()) { out << hook.first << " has " << hook.second.size() << " callback functions.\n"; } diff --git a/panda/src/event/eventHandler.h b/panda/src/event/eventHandler.h index 39d84475a4..8e616f1581 100644 --- a/panda/src/event/eventHandler.h +++ b/panda/src/event/eventHandler.h @@ -44,29 +44,29 @@ PUBLISHED: explicit EventHandler(EventQueue *ev_queue); ~EventHandler() {} - AsyncFuture *get_future(const string &event_name); + AsyncFuture *get_future(const std::string &event_name); void process_events(); virtual void dispatch_event(const Event *event); - void write(ostream &out) const; + void write(std::ostream &out) const; - INLINE static EventHandler *get_global_event_handler(EventQueue *queue = NULL); + INLINE static EventHandler *get_global_event_handler(EventQueue *queue = nullptr); public: - bool add_hook(const string &event_name, EventFunction *function); - bool add_hook(const string &event_name, EventCallbackFunction *function, + bool add_hook(const std::string &event_name, EventFunction *function); + bool add_hook(const std::string &event_name, EventCallbackFunction *function, void *data); - bool has_hook(const string &event_name) const; - bool has_hook(const string &event_name, EventFunction *function) const; - bool has_hook(const string &event_name, EventCallbackFunction *function, + bool has_hook(const std::string &event_name) const; + bool has_hook(const std::string &event_name, EventFunction *function) const; + bool has_hook(const std::string &event_name, EventCallbackFunction *function, void *data) const; - bool remove_hook(const string &event_name, EventFunction *function); - bool remove_hook(const string &event_name, EventCallbackFunction *function, + bool remove_hook(const std::string &event_name, EventFunction *function); + bool remove_hook(const std::string &event_name, EventCallbackFunction *function, void *data); - bool remove_hooks(const string &event_name); + bool remove_hooks(const std::string &event_name); bool remove_hooks_with(void *data); void remove_all_hooks(); @@ -74,11 +74,11 @@ public: protected: typedef pset Functions; - typedef pmap Hooks; - typedef pair CallbackFunction; + typedef pmap Hooks; + typedef std::pair CallbackFunction; typedef pset CallbackFunctions; - typedef pmap CallbackHooks; - typedef pmap Futures; + typedef pmap CallbackHooks; + typedef pmap Futures; Hooks _hooks; CallbackHooks _cbhooks; @@ -89,8 +89,8 @@ protected: static void make_global_event_handler(); private: - void write_hook(ostream &out, const Hooks::value_type &hook) const; - void write_cbhook(ostream &out, const CallbackHooks::value_type &hook) const; + void write_hook(std::ostream &out, const Hooks::value_type &hook) const; + void write_cbhook(std::ostream &out, const CallbackHooks::value_type &hook) const; public: diff --git a/panda/src/event/eventParameter.I b/panda/src/event/eventParameter.I index 14727106e6..1d3d168344 100644 --- a/panda/src/event/eventParameter.I +++ b/panda/src/event/eventParameter.I @@ -55,13 +55,13 @@ EventParameter(double value) : _ptr(new EventStoreDouble(value)) { } * Defines an EventParameter that stores a string value. */ INLINE EventParameter:: -EventParameter(const string &value) : _ptr(new EventStoreString(value)) { } +EventParameter(const std::string &value) : _ptr(new EventStoreString(value)) { } /** * Defines an EventParameter that stores a wstring value. */ INLINE EventParameter:: -EventParameter(const wstring &value) : _ptr(new EventStoreWstring(value)) { } +EventParameter(const std::wstring &value) : _ptr(new EventStoreWstring(value)) { } /** @@ -93,7 +93,7 @@ INLINE EventParameter:: */ INLINE bool EventParameter:: is_empty() const { - return (_ptr == (TypedWritableReferenceCount *)NULL); + return (_ptr == nullptr); } /** @@ -158,7 +158,7 @@ is_string() const { * Retrieves the value stored in the EventParameter. It is only valid to call * this if is_string() has already returned true. */ -INLINE string EventParameter:: +INLINE std::string EventParameter:: get_string_value() const { nassertr(is_string(), ""); return ((const EventStoreString *)_ptr.p())->get_value(); @@ -179,9 +179,9 @@ is_wstring() const { * Retrieves the value stored in the EventParameter. It is only valid to call * this if is_wstring() has already returned true. */ -INLINE wstring EventParameter:: +INLINE std::wstring EventParameter:: get_wstring_value() const { - nassertr(is_wstring(), wstring()); + nassertr(is_wstring(), std::wstring()); return ((const EventStoreWstring *)_ptr.p())->get_value(); } @@ -205,7 +205,7 @@ is_typed_ref_count() const { */ INLINE TypedReferenceCount *EventParameter:: get_typed_ref_count_value() const { - nassertr(is_typed_ref_count(), NULL); + nassertr(is_typed_ref_count(), nullptr); return ((const EventStoreTypedRefCount *)_ptr.p())->get_value(); } @@ -220,8 +220,8 @@ get_ptr() const { return _ptr; } -INLINE ostream & -operator << (ostream &out, const EventParameter ¶m) { +INLINE std::ostream & +operator << (std::ostream &out, const EventParameter ¶m) { param.output(out); return out; } diff --git a/panda/src/event/eventParameter.cxx b/panda/src/event/eventParameter.cxx index e5e55a1bac..37f6690dae 100644 --- a/panda/src/event/eventParameter.cxx +++ b/panda/src/event/eventParameter.cxx @@ -21,8 +21,8 @@ template class ParamValue; * */ void EventParameter:: -output(ostream &out) const { - if (_ptr == (TypedWritableReferenceCount *)NULL) { +output(std::ostream &out) const { + if (_ptr == nullptr) { out << "(empty)"; } else if (_ptr->is_of_type(ParamValueBase::get_class_type())) { diff --git a/panda/src/event/eventParameter.h b/panda/src/event/eventParameter.h index 65dbf550c8..5f817fc149 100644 --- a/panda/src/event/eventParameter.h +++ b/panda/src/event/eventParameter.h @@ -34,14 +34,14 @@ */ class EXPCL_PANDA_EVENT EventParameter { PUBLISHED: - INLINE EventParameter() DEFAULT_CTOR; - INLINE EventParameter(nullptr_t) {}; + INLINE EventParameter() = default; + INLINE EventParameter(std::nullptr_t) {}; INLINE EventParameter(const TypedWritableReferenceCount *ptr); INLINE EventParameter(const TypedReferenceCount *ptr); INLINE EventParameter(int value); INLINE EventParameter(double value); - INLINE EventParameter(const string &value); - INLINE EventParameter(const wstring &value); + INLINE EventParameter(const std::string &value); + INLINE EventParameter(const std::wstring &value); INLINE EventParameter(const EventParameter ©); INLINE EventParameter &operator = (const EventParameter ©); @@ -57,22 +57,22 @@ PUBLISHED: INLINE bool is_double() const; INLINE double get_double_value() const; INLINE bool is_string() const; - INLINE string get_string_value() const; + INLINE std::string get_string_value() const; INLINE bool is_wstring() const; - INLINE wstring get_wstring_value() const; + INLINE std::wstring get_wstring_value() const; INLINE bool is_typed_ref_count() const; INLINE TypedReferenceCount *get_typed_ref_count_value() const; INLINE TypedWritableReferenceCount *get_ptr() const; - void output(ostream &out) const; + void output(std::ostream &out) const; private: PT(TypedWritableReferenceCount) _ptr; }; -INLINE ostream &operator << (ostream &out, const EventParameter ¶m); +INLINE std::ostream &operator << (std::ostream &out, const EventParameter ¶m); typedef ParamTypedRefCount EventStoreTypedRefCount; diff --git a/panda/src/event/eventQueue.I b/panda/src/event/eventQueue.I index 7887696222..22b97a99d7 100644 --- a/panda/src/event/eventQueue.I +++ b/panda/src/event/eventQueue.I @@ -17,7 +17,7 @@ */ INLINE EventQueue *EventQueue:: get_global_event_queue() { - if (_global_event_queue == NULL) { + if (_global_event_queue == nullptr) { make_global_event_queue(); } return _global_event_queue; diff --git a/panda/src/event/eventQueue.cxx b/panda/src/event/eventQueue.cxx index fa423b0ca9..bbd07a3725 100644 --- a/panda/src/event/eventQueue.cxx +++ b/panda/src/event/eventQueue.cxx @@ -15,7 +15,7 @@ #include "config_event.h" #include "lightMutexHolder.h" -EventQueue *EventQueue::_global_event_queue = NULL; +EventQueue *EventQueue::_global_event_queue = nullptr; /** diff --git a/panda/src/event/genericAsyncTask.cxx b/panda/src/event/genericAsyncTask.cxx index 28cbebe55f..f78fddecc3 100644 --- a/panda/src/event/genericAsyncTask.cxx +++ b/panda/src/event/genericAsyncTask.cxx @@ -20,26 +20,26 @@ TypeHandle GenericAsyncTask::_type_handle; * */ GenericAsyncTask:: -GenericAsyncTask(const string &name) : +GenericAsyncTask(const std::string &name) : AsyncTask(name) { - _function = NULL; - _upon_birth = NULL; - _upon_death = NULL; - _user_data = NULL; + _function = nullptr; + _upon_birth = nullptr; + _upon_death = nullptr; + _user_data = nullptr; } /** * */ GenericAsyncTask:: -GenericAsyncTask(const string &name, GenericAsyncTask::TaskFunc *function, void *user_data) : +GenericAsyncTask(const std::string &name, GenericAsyncTask::TaskFunc *function, void *user_data) : AsyncTask(name), _function(function), _user_data(user_data) { - _upon_birth = NULL; - _upon_death = NULL; + _upon_birth = nullptr; + _upon_death = nullptr; } /** @@ -51,7 +51,7 @@ GenericAsyncTask(const string &name, GenericAsyncTask::TaskFunc *function, void */ bool GenericAsyncTask:: is_runnable() { - return _function != NULL; + return _function != nullptr; } /** @@ -61,7 +61,7 @@ is_runnable() { */ AsyncTask::DoneStatus GenericAsyncTask:: do_task() { - nassertr(_function != NULL, DS_interrupt); + nassertr(_function != nullptr, DS_interrupt); return (*_function)(this, _user_data); } @@ -75,7 +75,7 @@ void GenericAsyncTask:: upon_birth(AsyncTaskManager *manager) { AsyncTask::upon_birth(manager); - if (_upon_birth != NULL) { + if (_upon_birth != nullptr) { (*_upon_birth)(this, _user_data); } } @@ -97,7 +97,7 @@ void GenericAsyncTask:: upon_death(AsyncTaskManager *manager, bool clean_exit) { AsyncTask::upon_death(manager, clean_exit); - if (_upon_death != NULL) { + if (_upon_death != nullptr) { (*_upon_death)(this, clean_exit, _user_data); } } diff --git a/panda/src/event/genericAsyncTask.h b/panda/src/event/genericAsyncTask.h index 9ff7ae272a..f35d780e3b 100644 --- a/panda/src/event/genericAsyncTask.h +++ b/panda/src/event/genericAsyncTask.h @@ -23,14 +23,14 @@ * You can use this when you want to create an AsyncTask without having to * subclass. */ -class EXPCL_PANDA_PIPELINE GenericAsyncTask : public AsyncTask { +class EXPCL_PANDA_EVENT GenericAsyncTask : public AsyncTask { public: typedef DoneStatus TaskFunc(GenericAsyncTask *task, void *user_data); typedef void BirthFunc(GenericAsyncTask *task, void *user_data); typedef void DeathFunc(GenericAsyncTask *task, bool clean_exit, void *user_data); - GenericAsyncTask(const string &name = string()); - GenericAsyncTask(const string &name, TaskFunc *function, void *user_data); + GenericAsyncTask(const std::string &name = std::string()); + GenericAsyncTask(const std::string &name, TaskFunc *function, void *user_data); ALLOC_DELETED_CHAIN(GenericAsyncTask); INLINE void set_function(TaskFunc *function); diff --git a/panda/src/event/pointerEvent.cxx b/panda/src/event/pointerEvent.cxx index 8e64a3c58b..7ee7d3621c 100644 --- a/panda/src/event/pointerEvent.cxx +++ b/panda/src/event/pointerEvent.cxx @@ -19,7 +19,7 @@ * */ void PointerEvent:: -output(ostream &out) const { +output(std::ostream &out) const { out << (_in_window ? "In@" : "Out@") << _xpos << "," << _ypos << " "; } diff --git a/panda/src/event/pointerEvent.h b/panda/src/event/pointerEvent.h index f69d8d4223..d98cc99989 100644 --- a/panda/src/event/pointerEvent.h +++ b/panda/src/event/pointerEvent.h @@ -34,7 +34,7 @@ public: INLINE bool operator != (const PointerEvent &other) const; INLINE bool operator < (const PointerEvent &other) const; - void output(ostream &out) const; + void output(std::ostream &out) const; void write_datagram(Datagram &dg) const; void read_datagram(DatagramIterator &scan); @@ -52,7 +52,7 @@ public: double _time; }; -INLINE ostream &operator << (ostream &out, const PointerEvent &pe) { +INLINE std::ostream &operator << (std::ostream &out, const PointerEvent &pe) { pe.output(out); return out; } diff --git a/panda/src/event/pointerEventList.cxx b/panda/src/event/pointerEventList.cxx index fc376bc886..4c9d8472c2 100644 --- a/panda/src/event/pointerEventList.cxx +++ b/panda/src/event/pointerEventList.cxx @@ -48,7 +48,7 @@ INLINE double normalize_angle(double angle) { * */ void PointerEventList:: -output(ostream &out) const { +output(std::ostream &out) const { if (_events.empty()) { out << "(no pointers)"; } else { @@ -68,7 +68,7 @@ output(ostream &out) const { * */ void PointerEventList:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << _events.size() << " events:\n"; Events::const_iterator ei; for (ei = _events.begin(); ei != _events.end(); ++ei) { @@ -172,7 +172,7 @@ total_turns(double sec) const { * to be in order to be considered significant. */ double PointerEventList:: -match_pattern(const string &ascpat, double rot, double seglen) { +match_pattern(const std::string &ascpat, double rot, double seglen) { // Convert the pattern from ascii to a more usable form. vector_double pattern; parse_pattern(ascpat, pattern); @@ -189,7 +189,7 @@ match_pattern(const string &ascpat, double rot, double seglen) { * Parses a pattern as used by match_pattern. */ void PointerEventList:: -parse_pattern(const string &ascpat, vector_double &pattern) { +parse_pattern(const std::string &ascpat, vector_double &pattern) { int chars = 0; double dir = 180.0; for (size_t i=0; i Events; Events _events; @@ -84,7 +84,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const PointerEventList &pointerlist) { +INLINE std::ostream &operator << (std::ostream &out, const PointerEventList &pointerlist) { pointerlist.output(out); return out; } diff --git a/panda/src/event/pythonTask.cxx b/panda/src/event/pythonTask.cxx index 6a818ad19c..554e1368e7 100644 --- a/panda/src/event/pythonTask.cxx +++ b/panda/src/event/pythonTask.cxx @@ -33,7 +33,7 @@ extern struct Dtool_PyTypedObject Dtool_PythonTask; * */ PythonTask:: -PythonTask(PyObject *func_or_coro, const string &name) : +PythonTask(PyObject *func_or_coro, const std::string &name) : AsyncTask(name), _function(nullptr), _args(nullptr), @@ -134,7 +134,7 @@ set_function(PyObject *function) { void PythonTask:: set_args(PyObject *args, bool append_task) { Py_XDECREF(_args); - _args = NULL; + _args = nullptr; if (args == Py_None) { // None means no arguments; create an empty tuple. @@ -145,7 +145,7 @@ set_args(PyObject *args, bool append_task) { } } - if (_args == NULL) { + if (_args == nullptr) { nassert_raise("Invalid args passed to PythonTask"); _args = PyTuple_New(0); } @@ -213,15 +213,15 @@ set_owner(PyObject *owner) { PyObject *add = PyObject_GetAttrString(owner, "_addTask"); PyObject *clear = PyObject_GetAttrString(owner, "_clearTask"); - if (add == NULL || !PyCallable_Check(add) || - clear == NULL || !PyCallable_Check(clear)) { + if (add == nullptr || !PyCallable_Check(add) || + clear == nullptr || !PyCallable_Check(clear)) { Dtool_Raise_TypeError("owner object should have _addTask and _clearTask methods"); return; } } #endif - if (_owner != NULL && _owner != Py_None && _state != S_inactive) { + if (_owner != nullptr && _owner != Py_None && _state != S_inactive) { unregister_from_owner(); } @@ -318,7 +318,7 @@ __setattr__(PyObject *self, PyObject *attr, PyObject *v) { */ int PythonTask:: __delattr__(PyObject *self, PyObject *attr) { - if (PyObject_GenericSetAttr(self, attr, NULL) == 0) { + if (PyObject_GenericSetAttr(self, attr, nullptr) == 0) { return 0; } @@ -360,7 +360,7 @@ __getattr__(PyObject *attr) const { PyObject *item = PyDict_GetItem(__dict__, attr); - if (item == NULL) { + if (item == nullptr) { // PyDict_GetItem does not raise an exception. #if PY_MAJOR_VERSION < 3 PyErr_Format(PyExc_AttributeError, @@ -371,7 +371,7 @@ __getattr__(PyObject *attr) const { "'PythonTask' object has no attribute '%U'", attr); #endif - return NULL; + return nullptr; } // PyDict_GetItem returns a borrowed reference. @@ -683,7 +683,7 @@ do_python_task() { switch (retval) { case DS_again: Py_XDECREF(_generator); - _generator = NULL; + _generator = nullptr; // Fall through. case DS_done: @@ -724,17 +724,17 @@ do_python_task() { return DS_done; } - ostringstream strm; + std::ostringstream strm; #if PY_MAJOR_VERSION >= 3 PyObject *str = PyObject_ASCII(result); - if (str == NULL) { + if (str == nullptr) { str = PyUnicode_FromString(""); } strm << *this << " returned " << PyUnicode_AsUTF8(str); #else PyObject *str = PyObject_Repr(result); - if (str == NULL) { + if (str == nullptr) { str = PyString_FromString(""); } strm @@ -742,7 +742,7 @@ do_python_task() { #endif Py_DECREF(str); Py_DECREF(result); - string message = strm.str(); + std::string message = strm.str(); nassert_raise(message); return DS_interrupt; @@ -844,7 +844,7 @@ void PythonTask:: call_owner_method(const char *method_name) { if (_owner != Py_None) { PyObject *func = PyObject_GetAttrString(_owner, (char *)method_name); - if (func == (PyObject *)NULL) { + if (func == nullptr) { task_cat.error() << "Owner object added to " << *this << " has no method " << method_name << "().\n"; diff --git a/panda/src/event/pythonTask.h b/panda/src/event/pythonTask.h index 48826769de..3771d46d8b 100644 --- a/panda/src/event/pythonTask.h +++ b/panda/src/event/pythonTask.h @@ -26,9 +26,9 @@ * This class exists to allow association of a Python function or coroutine * with the AsyncTaskManager. */ -class PythonTask FINAL : public AsyncTask { +class PythonTask final : public AsyncTask { PUBLISHED: - PythonTask(PyObject *function = Py_None, const string &name = string()); + PythonTask(PyObject *function = Py_None, const std::string &name = std::string()); virtual ~PythonTask(); ALLOC_DELETED_CHAIN(PythonTask); diff --git a/panda/src/event/test_task.cxx b/panda/src/event/test_task.cxx index 958742f747..e8cc5cb5ef 100644 --- a/panda/src/event/test_task.cxx +++ b/panda/src/event/test_task.cxx @@ -16,9 +16,11 @@ #include "asyncTaskManager.h" #include "perlinNoise2.h" +using std::cerr; + class MyTask : public AsyncTask { public: - MyTask(const string &name, double length, int repeat_count) : + MyTask(const std::string &name, double length, int repeat_count) : AsyncTask(name), _length(length), _repeat_count(repeat_count) @@ -62,12 +64,12 @@ main(int argc, char *argv[]) { cerr << "Making tasks.\n"; for (int yi = 0; yi < grid_size; ++yi) { for (int xi = 0; xi < grid_size; ++xi) { - ostringstream namestrm; + std::ostringstream namestrm; namestrm << "task_" << xi << "_" << yi; - double length = max(length_noise.noise(xi, yi) + 1.0, 0.0); - double delay = max(delay_noise.noise(xi, yi), 0.0) * 3.0; - int repeat_count = (int)floor(max(repeat_count_noise.noise(xi, yi) + 1.0, 0.0) * 1.5); + double length = std::max(length_noise.noise(xi, yi) + 1.0, 0.0); + double delay = std::max(delay_noise.noise(xi, yi), 0.0) * 3.0; + int repeat_count = (int)floor(std::max(repeat_count_noise.noise(xi, yi) + 1.0, 0.0) * 1.5); int sort = (int)floor(sort_noise.noise(xi, yi) * 2.0); int priority = (int)floor(priority_noise.noise(xi, yi) * 5.0); diff --git a/panda/src/event/throw_event.I b/panda/src/event/throw_event.I index 303b356dad..bf3618d38a 100644 --- a/panda/src/event/throw_event.I +++ b/panda/src/event/throw_event.I @@ -17,12 +17,12 @@ throw_event(const CPT_Event &event) { } INLINE void -throw_event(const string &event_name) { +throw_event(const std::string &event_name) { EventQueue::get_global_event_queue()->queue_event(new Event(event_name)); } INLINE void -throw_event(const string &event_name, +throw_event(const std::string &event_name, const EventParameter &p1) { Event *event = new Event(event_name); event->add_parameter(p1); @@ -30,7 +30,7 @@ throw_event(const string &event_name, } INLINE void -throw_event(const string &event_name, +throw_event(const std::string &event_name, const EventParameter &p1, const EventParameter &p2) { Event *event = new Event(event_name); @@ -40,7 +40,7 @@ throw_event(const string &event_name, } INLINE void -throw_event(const string &event_name, +throw_event(const std::string &event_name, const EventParameter &p1, const EventParameter &p2, const EventParameter &p3) { @@ -52,7 +52,7 @@ throw_event(const string &event_name, } INLINE void -throw_event(const string &event_name, +throw_event(const std::string &event_name, const EventParameter &p1, const EventParameter &p2, const EventParameter &p3, @@ -74,13 +74,13 @@ throw_event_directly(EventHandler& handler, INLINE void throw_event_directly(EventHandler& handler, - const string &event_name) { + const std::string &event_name) { handler.dispatch_event(new Event(event_name)); } INLINE void throw_event_directly(EventHandler& handler, - const string &event_name, + const std::string &event_name, const EventParameter &p1) { Event *event = new Event(event_name); event->add_parameter(p1); @@ -89,7 +89,7 @@ throw_event_directly(EventHandler& handler, INLINE void throw_event_directly(EventHandler& handler, - const string &event_name, + const std::string &event_name, const EventParameter &p1, const EventParameter &p2) { Event *event = new Event(event_name); @@ -100,7 +100,7 @@ throw_event_directly(EventHandler& handler, INLINE void throw_event_directly(EventHandler& handler, - const string &event_name, + const std::string &event_name, const EventParameter &p1, const EventParameter &p2, const EventParameter &p3) { diff --git a/panda/src/event/throw_event.h b/panda/src/event/throw_event.h index d1d2554c3a..435a959d64 100644 --- a/panda/src/event/throw_event.h +++ b/panda/src/event/throw_event.h @@ -22,17 +22,17 @@ // A handful of convenience functions to throw events. INLINE void throw_event(const CPT_Event &event); -INLINE void throw_event(const string &event_name); -INLINE void throw_event(const string &event_name, +INLINE void throw_event(const std::string &event_name); +INLINE void throw_event(const std::string &event_name, const EventParameter &p1); -INLINE void throw_event(const string &event_name, +INLINE void throw_event(const std::string &event_name, const EventParameter &p1, const EventParameter &p2); -INLINE void throw_event(const string &event_name, +INLINE void throw_event(const std::string &event_name, const EventParameter &p1, const EventParameter &p2, const EventParameter &p3); -INLINE void throw_event(const string &event_name, +INLINE void throw_event(const std::string &event_name, const EventParameter &p1, const EventParameter &p2, const EventParameter &p3, @@ -43,16 +43,16 @@ INLINE void throw_event(const string &event_name, INLINE void throw_event_directly(EventHandler& handler, const CPT_Event &event); INLINE void throw_event_directly(EventHandler& handler, - const string &event_name); + const std::string &event_name); INLINE void throw_event_directly(EventHandler& handler, - const string &event_name, + const std::string &event_name, const EventParameter &p1); INLINE void throw_event_directly(EventHandler& handler, - const string &event_name, + const std::string &event_name, const EventParameter &p1, const EventParameter &p2); INLINE void throw_event_directly(EventHandler& handler, - const string &event_name, + const std::string &event_name, const EventParameter &p1, const EventParameter &p2, const EventParameter &p3); diff --git a/panda/src/express/buffer.h b/panda/src/express/buffer.h index 255125b21b..74f0f8d2b5 100644 --- a/panda/src/express/buffer.h +++ b/panda/src/express/buffer.h @@ -21,7 +21,7 @@ /** * */ -class EXPCL_PANDAEXPRESS Buffer : public ReferenceCount { +class EXPCL_PANDA_EXPRESS Buffer : public ReferenceCount { public: Buffer(int size); ~Buffer(); diff --git a/panda/src/express/checksumHashGenerator.I b/panda/src/express/checksumHashGenerator.I index a2e9920203..640b02e415 100644 --- a/panda/src/express/checksumHashGenerator.I +++ b/panda/src/express/checksumHashGenerator.I @@ -11,6 +11,14 @@ * @date 2001-05-14 */ +#ifdef _WIN32 +// Needed for PtrToLong, below +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN 1 +#endif +#include +#endif + /** * Adds another integer to the hash so far. This function should be * overridden in base classes; this is the principle implementation of the diff --git a/panda/src/express/checksumHashGenerator.cxx b/panda/src/express/checksumHashGenerator.cxx index fbcf1b7563..0de99789fd 100644 --- a/panda/src/express/checksumHashGenerator.cxx +++ b/panda/src/express/checksumHashGenerator.cxx @@ -17,9 +17,9 @@ * Adds a string to the hash, by breaking it down into a sequence of integers. */ void ChecksumHashGenerator:: -add_string(const string &str) { +add_string(const std::string &str) { add_int(str.length()); - string::const_iterator si; + std::string::const_iterator si; for (si = str.begin(); si != str.end(); ++si) { add_int(*si); } diff --git a/panda/src/express/checksumHashGenerator.h b/panda/src/express/checksumHashGenerator.h index d1ee27afa3..0a7ae11000 100644 --- a/panda/src/express/checksumHashGenerator.h +++ b/panda/src/express/checksumHashGenerator.h @@ -22,14 +22,14 @@ * This is a specific kind of HashGenerator that simply adds up all of the * ints. Nothing fancy, and pretty quick. */ -class EXPCL_PANDAEXPRESS ChecksumHashGenerator : public HashGeneratorBase { +class EXPCL_PANDA_EXPRESS ChecksumHashGenerator : public HashGeneratorBase { public: INLINE void add_int(long num); INLINE void add_bool(bool flag); INLINE void add_fp(float num, float threshold); INLINE void add_fp(double num, double threshold); INLINE void add_pointer(void *ptr); - void add_string(const string &str); + void add_string(const std::string &str); }; #include "checksumHashGenerator.I" diff --git a/panda/src/express/compress_string.cxx b/panda/src/express/compress_string.cxx index 8a32947490..d4c08ddb39 100644 --- a/panda/src/express/compress_string.cxx +++ b/panda/src/express/compress_string.cxx @@ -18,6 +18,12 @@ #include "virtualFileSystem.h" #include "config_express.h" +using std::istream; +using std::istringstream; +using std::ostream; +using std::ostringstream; +using std::string; + /** * Compress the indicated source string at the given compression level (1 * through 9). Returns the compressed string. @@ -64,7 +70,7 @@ decompress_string(const string &source) { * results are written to the dest file, overwriting its contents. The return * value is bool on success, or false on failure. */ -EXPCL_PANDAEXPRESS bool +EXPCL_PANDA_EXPRESS bool compress_file(const Filename &source, const Filename &dest, int compression_level) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); Filename source_filename = source; @@ -73,14 +79,14 @@ compress_file(const Filename &source, const Filename &dest, int compression_leve source_filename.set_binary(); } istream *source_stream = vfs->open_read_file(source_filename, false); - if (source_stream == NULL) { + if (source_stream == nullptr) { express_cat.info() << "Couldn't open file " << source_filename << "\n"; return false; } Filename dest_filename = Filename::binary_filename(dest); ostream *dest_stream = vfs->open_write_file(dest_filename, false, true); - if (dest_stream == NULL) { + if (dest_stream == nullptr) { express_cat.info() << "Couldn't open file " << dest_filename << "\n"; vfs->close_read_file(source_stream); return false; @@ -101,12 +107,12 @@ compress_file(const Filename &source, const Filename &dest, int compression_leve * Note that a decompression error cannot easily be detected, and the output * may simply be a garbage or truncated string. */ -EXPCL_PANDAEXPRESS bool +EXPCL_PANDA_EXPRESS bool decompress_file(const Filename &source, const Filename &dest) { Filename source_filename = Filename::binary_filename(source); VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); istream *source_stream = vfs->open_read_file(source_filename, false); - if (source_stream == NULL) { + if (source_stream == nullptr) { express_cat.info() << "Couldn't open file " << source_filename << "\n"; return false; } @@ -117,7 +123,7 @@ decompress_file(const Filename &source, const Filename &dest) { dest_filename.set_binary(); } ostream *dest_stream = vfs->open_write_file(dest_filename, false, true); - if (dest_stream == NULL) { + if (dest_stream == nullptr) { express_cat.info() << "Couldn't open file " << dest_filename << "\n"; vfs->close_read_file(source_stream); return false; diff --git a/panda/src/express/compress_string.h b/panda/src/express/compress_string.h index 433f1dd3e6..7513dbaddd 100644 --- a/panda/src/express/compress_string.h +++ b/panda/src/express/compress_string.h @@ -22,21 +22,21 @@ BEGIN_PUBLISH -EXPCL_PANDAEXPRESS string -compress_string(const string &source, int compression_level); +EXPCL_PANDA_EXPRESS std::string +compress_string(const std::string &source, int compression_level); -EXPCL_PANDAEXPRESS string -decompress_string(const string &source); +EXPCL_PANDA_EXPRESS std::string +decompress_string(const std::string &source); -EXPCL_PANDAEXPRESS bool +EXPCL_PANDA_EXPRESS bool compress_file(const Filename &source, const Filename &dest, int compression_level); -EXPCL_PANDAEXPRESS bool +EXPCL_PANDA_EXPRESS bool decompress_file(const Filename &source, const Filename &dest); -EXPCL_PANDAEXPRESS bool -compress_stream(istream &source, ostream &dest, int compression_level); -EXPCL_PANDAEXPRESS bool -decompress_stream(istream &source, ostream &dest); +EXPCL_PANDA_EXPRESS bool +compress_stream(std::istream &source, std::ostream &dest, int compression_level); +EXPCL_PANDA_EXPRESS bool +decompress_stream(std::istream &source, std::ostream &dest); END_PUBLISH diff --git a/panda/src/express/config_express.cxx b/panda/src/express/config_express.cxx index d86e300436..3a4343ac32 100644 --- a/panda/src/express/config_express.cxx +++ b/panda/src/express/config_express.cxx @@ -36,8 +36,8 @@ #include "dconfig.h" #include "streamWrapper.h" -#if !defined(CPPPARSER) && !defined(BUILDING_PANDAEXPRESS) - #error Buildsystem error: BUILDING_PANDAEXPRESS not defined +#if !defined(CPPPARSER) && !defined(BUILDING_PANDA_EXPRESS) + #error Buildsystem error: BUILDING_PANDA_EXPRESS not defined #endif ConfigureDef(config_express); @@ -150,9 +150,9 @@ init_libexpress() { bool get_use_high_res_clock() { - static ConfigVariableBool *use_high_res_clock = NULL; + static ConfigVariableBool *use_high_res_clock = nullptr; - if (use_high_res_clock == (ConfigVariableBool *)NULL) { + if (use_high_res_clock == nullptr) { use_high_res_clock = new ConfigVariableBool ("use-high-res-clock", true, PRC_DESC("Set this to false to avoid using the high-precision clock, even if " @@ -164,9 +164,9 @@ get_use_high_res_clock() { bool get_paranoid_clock() { - static ConfigVariableBool *paranoid_clock = NULL; + static ConfigVariableBool *paranoid_clock = nullptr; - if (paranoid_clock == (ConfigVariableBool *)NULL) { + if (paranoid_clock == nullptr) { paranoid_clock = new ConfigVariableBool ("paranoid-clock", false, PRC_DESC("Set this to true to double-check the results of the high-resolution " @@ -178,9 +178,9 @@ get_paranoid_clock() { bool get_verify_dcast() { - static ConfigVariableBool *verify_dcast = NULL; + static ConfigVariableBool *verify_dcast = nullptr; - if (verify_dcast == (ConfigVariableBool *)NULL) { + if (verify_dcast == nullptr) { verify_dcast = new ConfigVariableBool ("verify-dcast", true, PRC_DESC("Set this to true to verify that every attempted DCAST operation in " diff --git a/panda/src/express/config_express.h b/panda/src/express/config_express.h index eabe20f834..13719ad8a3 100644 --- a/panda/src/express/config_express.h +++ b/panda/src/express/config_express.h @@ -28,20 +28,20 @@ #include "executionEnvironment.h" #include "lineStream.h" -ConfigureDecl(config_express, EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS); -NotifyCategoryDecl(express, EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS); -NotifyCategoryDecl(clock, EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS); +ConfigureDecl(config_express, EXPCL_PANDA_EXPRESS, EXPTP_PANDA_EXPRESS); +NotifyCategoryDecl(express, EXPCL_PANDA_EXPRESS, EXPTP_PANDA_EXPRESS); +NotifyCategoryDecl(clock, EXPCL_PANDA_EXPRESS, EXPTP_PANDA_EXPRESS); // Actually, we can't determine this config variable the normal way, because // we must be able to access it at static init time. Instead of declaring it // a global constant, we'll make it a member of MemoryUsage. -// extern EXPCL_PANDAEXPRESS const bool track_memory_usage; +// extern EXPCL_PANDA_EXPRESS const bool track_memory_usage; -EXPCL_PANDAEXPRESS bool get_use_high_res_clock(); -EXPCL_PANDAEXPRESS bool get_paranoid_clock(); -EXPCL_PANDAEXPRESS bool get_paranoid_inheritance(); -EXPCL_PANDAEXPRESS bool get_verify_dcast(); +EXPCL_PANDA_EXPRESS bool get_use_high_res_clock(); +EXPCL_PANDA_EXPRESS bool get_paranoid_clock(); +EXPCL_PANDA_EXPRESS bool get_paranoid_inheritance(); +EXPCL_PANDA_EXPRESS bool get_verify_dcast(); extern ConfigVariableInt patchfile_window_size; extern ConfigVariableInt patchfile_increment_size; @@ -51,14 +51,14 @@ extern ConfigVariableInt patchfile_zone_size; extern ConfigVariableBool keep_temporary_files; extern ConfigVariableBool multifile_always_binary; -extern EXPCL_PANDAEXPRESS ConfigVariableBool collect_tcp; -extern EXPCL_PANDAEXPRESS ConfigVariableDouble collect_tcp_interval; +extern EXPCL_PANDA_EXPRESS ConfigVariableBool collect_tcp; +extern EXPCL_PANDA_EXPRESS ConfigVariableDouble collect_tcp_interval; // Expose the Config variable for Python access. BEGIN_PUBLISH -EXPCL_PANDAEXPRESS DConfig &get_config_express(); +EXPCL_PANDA_EXPRESS DConfig &get_config_express(); END_PUBLISH -extern EXPCL_PANDAEXPRESS void init_libexpress(); +extern EXPCL_PANDA_EXPRESS void init_libexpress(); #endif /* __CONFIG_UTIL_H__ */ diff --git a/panda/src/express/copy_stream.cxx b/panda/src/express/copy_stream.cxx index 77d0e78364..e04e681772 100644 --- a/panda/src/express/copy_stream.cxx +++ b/panda/src/express/copy_stream.cxx @@ -19,7 +19,7 @@ * true on success, false on failure. */ bool -copy_stream(istream &source, ostream &dest) { +copy_stream(std::istream &source, std::ostream &dest) { static const size_t buffer_size = 4096; char buffer[buffer_size]; diff --git a/panda/src/express/copy_stream.h b/panda/src/express/copy_stream.h index b501bb682e..0260c662b0 100644 --- a/panda/src/express/copy_stream.h +++ b/panda/src/express/copy_stream.h @@ -17,8 +17,8 @@ #include "pandabase.h" BEGIN_PUBLISH -EXPCL_PANDAEXPRESS bool -copy_stream(istream &source, ostream &dest); +EXPCL_PANDA_EXPRESS bool +copy_stream(std::istream &source, std::ostream &dest); END_PUBLISH #endif diff --git a/panda/src/express/datagram.I b/panda/src/express/datagram.I index 499bfab48b..98b71820e5 100644 --- a/panda/src/express/datagram.I +++ b/panda/src/express/datagram.I @@ -43,7 +43,7 @@ Datagram(const void *data, size_t size) : */ INLINE Datagram:: Datagram(vector_uchar data) : - _data(move(data)), + _data(std::move(data)), #ifdef STDFLOAT_DOUBLE _stdfloat_double(true) #else @@ -157,9 +157,9 @@ add_float64(PN_float64 value) { INLINE void Datagram:: add_stdfloat(PN_stdfloat value) { if (_stdfloat_double) { - add_float64(value); + add_float64((double)value); } else { - add_float32(value); + add_float32((float)value); } } @@ -241,7 +241,7 @@ add_be_float64(PN_float64 value) { * followed by n bytes. */ INLINE void Datagram:: -add_string(const string &str) { +add_string(const std::string &str) { // The max sendable length for a string is 2^16. nassertv(str.length() <= (uint16_t)0xffff); @@ -257,7 +257,7 @@ add_string(const string &str) { * to allow very long strings. */ INLINE void Datagram:: -add_string32(const string &str) { +add_string32(const std::string &str) { // Strings always are preceded by their length add_uint32((uint32_t)str.length()); @@ -269,7 +269,7 @@ add_string32(const string &str) { * Adds a variable-length string to the datagram, as a NULL-terminated string. */ INLINE void Datagram:: -add_z_string(const string &str) { +add_z_string(const std::string &str) { // We must not have any nested null characters in the string. size_t null_pos = str.find('\0'); // Add the string (sans the null character). @@ -285,7 +285,7 @@ add_z_string(const string &str) { * greater than the requested size, this will silently truncate the string. */ INLINE void Datagram:: -add_fixed_string(const string &str, size_t size) { +add_fixed_string(const std::string &str, size_t size) { if (str.length() < size) { append_data(str.data(), str.length()); pad_bytes(size - str.length()); @@ -306,13 +306,13 @@ append_data(const vector_uchar &data) { /** * Returns the datagram's data as a string. */ -INLINE string Datagram:: +INLINE std::string Datagram:: get_message() const { // Silly special case for gcc 3.2, which can't tolerate string(NULL, 0). if (_data.size() == 0) { - return string(); + return std::string(); } else { - return string((const char *)_data.p(), _data.size()); + return std::string((const char *)_data.p(), _data.size()); } } @@ -378,7 +378,7 @@ get_array() const { */ INLINE PTA_uchar Datagram:: modify_array() { - if (_data == (uchar *)NULL) { + if (_data == nullptr) { // Create a new array. _data = PTA_uchar::empty_array(0); @@ -420,7 +420,7 @@ operator == (const Datagram &other) const { if (_data == other._data) { return true; } - if (_data != (uchar *)NULL && other._data != (uchar *)NULL) { + if (_data != nullptr && other._data != nullptr) { return _data.v() == other._data.v(); } return false; @@ -444,7 +444,7 @@ operator < (const Datagram &other) const { return false; } - if (_data != (uchar *)NULL && other._data != (uchar *)NULL) { + if (_data != nullptr && other._data != nullptr) { // Different pointers, neither NULL. return _data.v() < other._data.v(); } @@ -474,11 +474,11 @@ generic_write_datagram(Datagram &dest, double value) { } INLINE void -generic_write_datagram(Datagram &dest, const string &value) { +generic_write_datagram(Datagram &dest, const std::string &value) { dest.add_string(value); } INLINE void -generic_write_datagram(Datagram &dest, const wstring &value) { +generic_write_datagram(Datagram &dest, const std::wstring &value) { dest.add_wstring(value); } diff --git a/panda/src/express/datagram.cxx b/panda/src/express/datagram.cxx index 1121953948..de7d4089dc 100644 --- a/panda/src/express/datagram.cxx +++ b/panda/src/express/datagram.cxx @@ -41,7 +41,7 @@ clear() { * hex (and ASCII) values. */ void Datagram:: -dump_hex(ostream &out, unsigned int indent) const { +dump_hex(std::ostream &out, unsigned int indent) const { const char *message = (const char *)get_data(); size_t num_bytes = get_length(); for (size_t line = 0; line < num_bytes; line += 16) { @@ -80,13 +80,13 @@ dump_hex(ostream &out, unsigned int indent) const { * Adds a variable-length wstring to the datagram. */ void Datagram:: -add_wstring(const wstring &str) { +add_wstring(const std::wstring &str) { // By convention, wstrings are marked with 32-bit lengths. add_uint32((uint32_t)str.length()); // Now append each character in the string. We store each code little- // endian, for no real good reason. - wstring::const_iterator ci; + std::wstring::const_iterator ci; for (ci = str.begin(); ci != str.end(); ++ci) { add_uint16((uint16_t)*ci); } @@ -99,7 +99,7 @@ void Datagram:: pad_bytes(size_t size) { nassertv((int)size >= 0); - if (_data == (uchar *)NULL) { + if (_data == nullptr) { // Create a new array. _data = PTA_uchar::empty_array(0); @@ -129,7 +129,7 @@ void Datagram:: append_data(const void *data, size_t size) { nassertv((int)size >= 0); - if (_data == (uchar *)NULL) { + if (_data == nullptr) { // Create a new array. _data = PTA_uchar::empty_array(0); @@ -168,7 +168,7 @@ assign(const void *data, size_t size) { * Write a string representation of this instance to . */ void Datagram:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<""<<"Datagram"; #endif //] NDEBUG @@ -178,7 +178,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void Datagram:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, unsigned int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""<<"Datagram:\n"; diff --git a/panda/src/express/datagram.h b/panda/src/express/datagram.h index 00a46ef36f..69dce69e31 100644 --- a/panda/src/express/datagram.h +++ b/panda/src/express/datagram.h @@ -35,16 +35,20 @@ * A Datagram is itself headerless; it is simply a collection of data * elements. */ -class EXPCL_PANDAEXPRESS Datagram : public TypedObject { +class EXPCL_PANDA_EXPRESS Datagram : public TypedObject { PUBLISHED: INLINE Datagram(); INLINE Datagram(const void *data, size_t size); INLINE explicit Datagram(vector_uchar data); - + Datagram(const Datagram ©) = default; + Datagram(Datagram &&from) noexcept = default; virtual ~Datagram(); + Datagram &operator = (const Datagram ©) = default; + Datagram &operator = (Datagram &&from) noexcept = default; + virtual void clear(); - void dump_hex(ostream &out, unsigned int indent=0) const; + void dump_hex(std::ostream &out, unsigned int indent=0) const; INLINE void add_bool(bool value); INLINE void add_int8(int8_t value); @@ -71,11 +75,11 @@ PUBLISHED: INLINE void add_be_float32(PN_float32 value); INLINE void add_be_float64(PN_float64 value); - INLINE void add_string(const string &str); - INLINE void add_string32(const string &str); - INLINE void add_z_string(const string &str); - INLINE void add_fixed_string(const string &str, size_t size); - void add_wstring(const wstring &str); + INLINE void add_string(const std::string &str); + INLINE void add_string32(const std::string &str); + INLINE void add_z_string(const std::string &str); + INLINE void add_fixed_string(const std::string &str, size_t size); + void add_wstring(const std::wstring &str); void pad_bytes(size_t size); void append_data(const void *data, size_t size); @@ -83,7 +87,7 @@ PUBLISHED: void assign(const void *data, size_t size); - INLINE string get_message() const; + INLINE std::string get_message() const; INLINE vector_uchar __bytes__() const; INLINE const void *get_data() const; INLINE size_t get_length() const; @@ -100,8 +104,8 @@ PUBLISHED: INLINE bool operator != (const Datagram &other) const; INLINE bool operator < (const Datagram &other) const; - void output(ostream &out) const; - void write(ostream &out, unsigned int indent=0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, unsigned int indent=0) const; private: PTA_uchar _data; @@ -141,9 +145,9 @@ generic_write_datagram(Datagram &dest, float value); INLINE void generic_write_datagram(Datagram &dest, double value); INLINE void -generic_write_datagram(Datagram &dest, const string &value); +generic_write_datagram(Datagram &dest, const std::string &value); INLINE void -generic_write_datagram(Datagram &dest, const wstring &value); +generic_write_datagram(Datagram &dest, const std::wstring &value); #include "datagram.I" diff --git a/panda/src/express/datagramGenerator.cxx b/panda/src/express/datagramGenerator.cxx index a5e9f52bb8..275a050e88 100644 --- a/panda/src/express/datagramGenerator.cxx +++ b/panda/src/express/datagramGenerator.cxx @@ -44,7 +44,7 @@ save_datagram(SubfileInfo &info) { const Filename &DatagramGenerator:: get_filename() { const FileReference *file = get_file(); - if (file != (FileReference *)NULL) { + if (file != nullptr) { return file->get_filename(); } static const Filename empty_filename; @@ -66,7 +66,7 @@ get_timestamp() const { */ const FileReference *DatagramGenerator:: get_file() { - return NULL; + return nullptr; } /** @@ -75,7 +75,7 @@ get_file() { */ VirtualFile *DatagramGenerator:: get_vfile() { - return NULL; + return nullptr; } /** @@ -86,7 +86,7 @@ get_vfile() { * pointing to the first byte following the datagram returned after a call to * get_datagram(). */ -streampos DatagramGenerator:: +std::streampos DatagramGenerator:: get_file_pos() { return 0; } diff --git a/panda/src/express/datagramGenerator.h b/panda/src/express/datagramGenerator.h index 8d46f9df80..2c68c0199d 100644 --- a/panda/src/express/datagramGenerator.h +++ b/panda/src/express/datagramGenerator.h @@ -27,7 +27,7 @@ class VirtualFile; * This class defines the abstract interace to any source of datagrams, * whether it be from a file or from the net. */ -class EXPCL_PANDAEXPRESS DatagramGenerator { +class EXPCL_PANDA_EXPRESS DatagramGenerator { PUBLISHED: INLINE DatagramGenerator(); virtual ~DatagramGenerator(); @@ -41,7 +41,7 @@ PUBLISHED: virtual time_t get_timestamp() const; virtual const FileReference *get_file(); virtual VirtualFile *get_vfile(); - virtual streampos get_file_pos(); + virtual std::streampos get_file_pos(); }; #include "datagramGenerator.I" diff --git a/panda/src/express/datagramIterator.I b/panda/src/express/datagramIterator.I index 42c25eeed4..763850b60c 100644 --- a/panda/src/express/datagramIterator.I +++ b/panda/src/express/datagramIterator.I @@ -16,7 +16,7 @@ */ INLINE DatagramIterator:: DatagramIterator() : - _datagram((Datagram *)NULL), + _datagram(nullptr), _current_index(0) { } @@ -54,7 +54,7 @@ get_bool() { */ INLINE int8_t DatagramIterator:: get_int8() { - nassertr(_datagram != (const Datagram *)NULL, 0); + nassertr(_datagram != nullptr, 0); // Avoid reading junk data off the end of the datagram: nassertr(_current_index < _datagram->get_length(), 0); // Get the Data: @@ -70,7 +70,7 @@ get_int8() { */ INLINE uint8_t DatagramIterator:: get_uint8() { - nassertr(_datagram != (const Datagram *)NULL, 0); + nassertr(_datagram != nullptr, 0); // Avoid reading junk data off the end of the datagram: nassertr(_current_index < _datagram->get_length(), 0); // Get the Data: @@ -86,7 +86,7 @@ get_uint8() { */ INLINE int16_t DatagramIterator:: get_int16() { - nassertr(_datagram != (const Datagram *)NULL, 0); + nassertr(_datagram != nullptr, 0); nassertr(_current_index < _datagram->get_length(), 0); int16_t tempvar; @@ -105,7 +105,7 @@ get_int16() { */ INLINE int32_t DatagramIterator:: get_int32() { - nassertr(_datagram != (const Datagram *)NULL, 0); + nassertr(_datagram != nullptr, 0); nassertr(_current_index < _datagram->get_length(), 0); int32_t tempvar; @@ -124,7 +124,7 @@ get_int32() { */ INLINE int64_t DatagramIterator:: get_int64() { - nassertr(_datagram != (const Datagram *)NULL, 0); + nassertr(_datagram != nullptr, 0); nassertr(_current_index < _datagram->get_length(), 0); int64_t tempvar; @@ -143,7 +143,7 @@ get_int64() { */ INLINE uint16_t DatagramIterator:: get_uint16() { - nassertr(_datagram != (const Datagram *)NULL, 0); + nassertr(_datagram != nullptr, 0); nassertr(_current_index < _datagram->get_length(), 0); uint16_t tempvar; @@ -162,7 +162,7 @@ get_uint16() { */ INLINE uint32_t DatagramIterator:: get_uint32() { - nassertr(_datagram != (const Datagram *)NULL, 0); + nassertr(_datagram != nullptr, 0); nassertr(_current_index < _datagram->get_length(), 0); uint32_t tempvar; @@ -181,7 +181,7 @@ get_uint32() { */ INLINE uint64_t DatagramIterator:: get_uint64() { - nassertr(_datagram != (const Datagram *)NULL, 0); + nassertr(_datagram != nullptr, 0); nassertr(_current_index < _datagram->get_length(), 0); uint64_t tempvar; @@ -200,7 +200,7 @@ get_uint64() { */ INLINE PN_float32 DatagramIterator:: get_float32() { - nassertr(_datagram != (const Datagram *)NULL, 0.0); + nassertr(_datagram != nullptr, 0.0); nassertr(_current_index < _datagram->get_length(), 0.0); PN_float32 tempvar; @@ -219,7 +219,7 @@ get_float32() { */ INLINE PN_float64 DatagramIterator:: get_float64() { - nassertr(_datagram != (const Datagram *)NULL, 0.0); + nassertr(_datagram != nullptr, 0.0); nassertr(_current_index < _datagram->get_length(), 0.0); PN_float64 tempvar; @@ -240,7 +240,7 @@ get_float64() { */ INLINE PN_stdfloat DatagramIterator:: get_stdfloat() { - nassertr(_datagram != (const Datagram *)NULL, 0.0); + nassertr(_datagram != nullptr, 0.0); if (_datagram->get_stdfloat_double()) { return (PN_stdfloat)get_float64(); } else { @@ -253,7 +253,7 @@ get_stdfloat() { */ INLINE int16_t DatagramIterator:: get_be_int16() { - nassertr(_datagram != (const Datagram *)NULL, 0); + nassertr(_datagram != nullptr, 0); nassertr(_current_index < _datagram->get_length(), 0); int16_t tempvar; @@ -272,7 +272,7 @@ get_be_int16() { */ INLINE int32_t DatagramIterator:: get_be_int32() { - nassertr(_datagram != (const Datagram *)NULL, 0); + nassertr(_datagram != nullptr, 0); nassertr(_current_index < _datagram->get_length(), 0); int32_t tempvar; @@ -291,7 +291,7 @@ get_be_int32() { */ INLINE int64_t DatagramIterator:: get_be_int64() { - nassertr(_datagram != (const Datagram *)NULL, 0); + nassertr(_datagram != nullptr, 0); nassertr(_current_index < _datagram->get_length(), 0); int64_t tempvar; @@ -310,7 +310,7 @@ get_be_int64() { */ INLINE uint16_t DatagramIterator:: get_be_uint16() { - nassertr(_datagram != (const Datagram *)NULL, 0); + nassertr(_datagram != nullptr, 0); nassertr(_current_index < _datagram->get_length(), 0); uint16_t tempvar; @@ -329,7 +329,7 @@ get_be_uint16() { */ INLINE uint32_t DatagramIterator:: get_be_uint32() { - nassertr(_datagram != (const Datagram *)NULL, 0); + nassertr(_datagram != nullptr, 0); nassertr(_current_index < _datagram->get_length(), 0); uint32_t tempvar; @@ -348,7 +348,7 @@ get_be_uint32() { */ INLINE uint64_t DatagramIterator:: get_be_uint64() { - nassertr(_datagram != (const Datagram *)NULL, 0); + nassertr(_datagram != nullptr, 0); nassertr(_current_index < _datagram->get_length(), 0); uint64_t tempvar; @@ -367,7 +367,7 @@ get_be_uint64() { */ INLINE PN_float32 DatagramIterator:: get_be_float32() { - nassertr(_datagram != (const Datagram *)NULL, 0.0); + nassertr(_datagram != nullptr, 0.0); nassertr(_current_index < _datagram->get_length(), 0.0); PN_float32 tempvar; @@ -386,7 +386,7 @@ get_be_float32() { */ INLINE PN_float64 DatagramIterator:: get_be_float64() { - nassertr(_datagram != (const Datagram *)NULL, 0.0); + nassertr(_datagram != nullptr, 0.0); nassertr(_current_index < _datagram->get_length(), 0.0); PN_float64 tempvar; @@ -405,7 +405,7 @@ get_be_float64() { */ INLINE void DatagramIterator:: skip_bytes(size_t size) { - nassertv(_datagram != (const Datagram *)NULL); + nassertv(_datagram != nullptr); nassertv((int)size >= 0); #ifndef NDEBUG if (_current_index + size > _datagram->get_length()) { @@ -424,7 +424,7 @@ skip_bytes(size_t size) { */ INLINE vector_uchar DatagramIterator:: get_remaining_bytes() const { - nassertr(_datagram != (const Datagram *)NULL, vector_uchar()); + nassertr(_datagram != nullptr, vector_uchar()); nassertr(_current_index <= _datagram->get_length(), vector_uchar()); const unsigned char *ptr = (const unsigned char *)_datagram->get_data(); @@ -477,11 +477,11 @@ generic_read_datagram(double &result, DatagramIterator &source) { } INLINE void -generic_read_datagram(string &result, DatagramIterator &source) { +generic_read_datagram(std::string &result, DatagramIterator &source) { result = source.get_string(); } INLINE void -generic_read_datagram(wstring &result, DatagramIterator &source) { +generic_read_datagram(std::wstring &result, DatagramIterator &source) { result = source.get_wstring(); } diff --git a/panda/src/express/datagramIterator.cxx b/panda/src/express/datagramIterator.cxx index 880719f32b..680ead3a66 100644 --- a/panda/src/express/datagramIterator.cxx +++ b/panda/src/express/datagramIterator.cxx @@ -14,6 +14,9 @@ #include "datagramIterator.h" #include "pnotify.h" +using std::string; +using std::wstring; + TypeHandle DatagramIterator::_type_handle; /** @@ -24,7 +27,7 @@ get_string() { // First, get the length of the string uint16_t s_len = get_uint16(); - nassertr(_datagram != (const Datagram *)NULL, ""); + nassertr(_datagram != nullptr, ""); nassertr(_current_index + s_len <= _datagram->get_length(), ""); const char *ptr = (const char *)_datagram->get_data(); @@ -43,7 +46,7 @@ get_string32() { // First, get the length of the string uint32_t s_len = get_uint32(); - nassertr(_datagram != (const Datagram *)NULL, ""); + nassertr(_datagram != nullptr, ""); nassertr(_current_index + s_len <= _datagram->get_length(), ""); const char *ptr = (const char *)_datagram->get_data(); @@ -59,7 +62,7 @@ get_string32() { */ string DatagramIterator:: get_z_string() { - nassertr(_datagram != (const Datagram *)NULL, ""); + nassertr(_datagram != nullptr, ""); // First, determine the length of the string. const char *ptr = (const char *)_datagram->get_data(); @@ -82,7 +85,7 @@ get_z_string() { */ string DatagramIterator:: get_fixed_string(size_t size) { - nassertr(_datagram != (const Datagram *)NULL, ""); + nassertr(_datagram != nullptr, ""); nassertr(_current_index + size <= _datagram->get_length(), ""); const char *ptr = (const char *)_datagram->get_data(); @@ -102,7 +105,7 @@ get_wstring() { // First, get the length of the string uint32_t s_len = get_uint32(); - nassertr(_datagram != (const Datagram *)NULL, wstring()); + nassertr(_datagram != nullptr, wstring()); nassertr(_current_index + s_len * 2 <= _datagram->get_length(), wstring()); wstring result; @@ -122,7 +125,7 @@ get_wstring() { vector_uchar DatagramIterator:: extract_bytes(size_t size) { nassertr((int)size >= 0, vector_uchar()); - nassertr(_datagram != (const Datagram *)NULL, vector_uchar()); + nassertr(_datagram != nullptr, vector_uchar()); nassertr(_current_index + size <= _datagram->get_length(), vector_uchar()); const unsigned char *ptr = (const unsigned char *)_datagram->get_data(); @@ -142,7 +145,7 @@ extract_bytes(size_t size) { size_t DatagramIterator:: extract_bytes(unsigned char *into, size_t size) { nassertr((int)size >= 0, 0); - nassertr(_datagram != (const Datagram *)NULL, 0); + nassertr(_datagram != nullptr, 0); nassertr(_current_index + size <= _datagram->get_length(), 0); const char *ptr = (const char *)_datagram->get_data(); @@ -156,7 +159,7 @@ extract_bytes(unsigned char *into, size_t size) { * Write a string representation of this instance to . */ void DatagramIterator:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<""<<"DatagramIterator"; #endif //] NDEBUG @@ -166,7 +169,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void DatagramIterator:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, unsigned int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""<<"DatagramIterator:\n"; out.width(indent+2); out<<""<<"_current_index "<<_current_index; diff --git a/panda/src/express/datagramIterator.h b/panda/src/express/datagramIterator.h index ec76be3f07..570e34c3c4 100644 --- a/panda/src/express/datagramIterator.h +++ b/panda/src/express/datagramIterator.h @@ -24,7 +24,7 @@ * Datagram. Elements may be retrieved one at a time; it is up to the caller * to know the correct type and order of each element. */ -class EXPCL_PANDAEXPRESS DatagramIterator { +class EXPCL_PANDA_EXPRESS DatagramIterator { public: INLINE void assign(Datagram &datagram, size_t offset = 0); @@ -55,11 +55,11 @@ PUBLISHED: INLINE PN_float32 get_be_float32(); INLINE PN_float64 get_be_float64(); - string get_string(); - string get_string32(); - string get_z_string(); - string get_fixed_string(size_t size); - wstring get_wstring(); + std::string get_string(); + std::string get_string32(); + std::string get_z_string(); + std::string get_fixed_string(size_t size); + std::wstring get_wstring(); INLINE void skip_bytes(size_t size); vector_uchar extract_bytes(size_t size); @@ -71,8 +71,8 @@ PUBLISHED: INLINE const Datagram &get_datagram() const; INLINE size_t get_current_index() const; - void output(ostream &out) const; - void write(ostream &out, unsigned int indent=0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, unsigned int indent=0) const; private: const Datagram *_datagram; @@ -104,9 +104,9 @@ generic_read_datagram(float &result, DatagramIterator &source); INLINE void generic_read_datagram(double &result, DatagramIterator &source); INLINE void -generic_read_datagram(string &result, DatagramIterator &source); +generic_read_datagram(std::string &result, DatagramIterator &source); INLINE void -generic_read_datagram(wstring &result, DatagramIterator &source); +generic_read_datagram(std::wstring &result, DatagramIterator &source); #include "datagramIterator.I" diff --git a/panda/src/express/datagramSink.cxx b/panda/src/express/datagramSink.cxx index 0941ce10fb..bdf2be596c 100644 --- a/panda/src/express/datagramSink.cxx +++ b/panda/src/express/datagramSink.cxx @@ -56,7 +56,7 @@ copy_datagram(SubfileInfo &result, const SubfileInfo &source) { const Filename &DatagramSink:: get_filename() { const FileReference *file = get_file(); - if (file != (FileReference *)NULL) { + if (file != nullptr) { return file->get_filename(); } static const Filename empty_filename; @@ -69,7 +69,7 @@ get_filename() { */ const FileReference *DatagramSink:: get_file() { - return NULL; + return nullptr; } /** @@ -80,7 +80,7 @@ get_file() { * pointing to the first byte following the datagram returned after a call to * put_datagram(). */ -streampos DatagramSink:: +std::streampos DatagramSink:: get_file_pos() { return 0; } diff --git a/panda/src/express/datagramSink.h b/panda/src/express/datagramSink.h index c72cf7595d..697b6a166f 100644 --- a/panda/src/express/datagramSink.h +++ b/panda/src/express/datagramSink.h @@ -26,7 +26,7 @@ class Filename; * This class defines the abstract interface to sending datagrams to any * target, whether it be into a file or across the net */ -class EXPCL_PANDAEXPRESS DatagramSink { +class EXPCL_PANDA_EXPRESS DatagramSink { PUBLISHED: INLINE DatagramSink(); virtual ~DatagramSink(); @@ -39,7 +39,7 @@ PUBLISHED: virtual const Filename &get_filename(); virtual const FileReference *get_file(); - virtual streampos get_file_pos(); + virtual std::streampos get_file_pos(); MAKE_PROPERTY(filename, get_filename); MAKE_PROPERTY(file, get_file); diff --git a/panda/src/express/dcast.T b/panda/src/express/dcast.T index 251f278dce..b457984ec4 100644 --- a/panda/src/express/dcast.T +++ b/panda/src/express/dcast.T @@ -1,24 +1,20 @@ -// Filename: dcast.T -// Created by: drose (06Aug01) -// -//////////////////////////////////////////////////////////////////// -// -// PANDA 3D SOFTWARE -// Copyright (c) Carnegie Mellon University. All rights reserved. -// -// All use of this software is subject to the terms of the revised BSD -// license. You should have received a copy of this license along -// with this source code in a file named "LICENSE." -// -//////////////////////////////////////////////////////////////////// +/** + * PANDA 3D SOFTWARE + * Copyright (c) Carnegie Mellon University. All rights reserved. + * + * All use of this software is subject to the terms of the revised BSD + * license. You should have received a copy of this license along + * with this source code in a file named "LICENSE." + * + * @file dcast.T + * @author drose + * @date 2001-08-06 + */ - -//////////////////////////////////////////////////////////////////// -// Function: _dcast_get_typehandle -// Description: Returns the TypeHandle associated with the type of -// the parameter, if it can be determined. This is a -// support function for _dcast, below. -//////////////////////////////////////////////////////////////////// +/** + * Returns the TypeHandle associated with the type of the parameter, if it can + * be determined. This is a support function for _dcast, below. + */ template INLINE TypeHandle _dcast_get_typehandle(WantType *) { @@ -38,16 +34,13 @@ _dcast_get_typehandle(WantType *) { return handle; } - -//////////////////////////////////////////////////////////////////// -// Function: _dcast -// Description: The implementation of the DCAST macro, this checks -// the actual type of the pointer before performing a -// downcast operation. In NDEBUG mode, it simply -// downcasts. -// -// This flavor of _dcast works on non-const pointers. -//////////////////////////////////////////////////////////////////// +/** + * The implementation of the DCAST macro, this checks the actual type of the + * pointer before performing a downcast operation. In NDEBUG mode, it simply + * downcasts. + * + * This flavor of _dcast works on non-const pointers. + */ template INLINE WantType * _dcast(WantType *, TypedObject *ptr) { @@ -61,15 +54,13 @@ _dcast(WantType *, TypedObject *ptr) { return (WantType *)ptr; } -//////////////////////////////////////////////////////////////////// -// Function: _dcast -// Description: The implementation of the DCAST macro, this checks -// the actual type of the pointer before performing a -// downcast operation. In NDEBUG mode, it simply -// downcasts. -// -// This flavor of _dcast works on const pointers. -//////////////////////////////////////////////////////////////////// +/** + * The implementation of the DCAST macro, this checks the actual type of the + * pointer before performing a downcast operation. In NDEBUG mode, it simply + * downcasts. + * + * This flavor of _dcast works on const pointers. + */ template INLINE const WantType * _dcast(WantType *, const TypedObject *ptr) { @@ -83,12 +74,10 @@ _dcast(WantType *, const TypedObject *ptr) { return (const WantType *)ptr; } -//////////////////////////////////////////////////////////////////// -// Function: _dcast_ref -// Description: Similar to the above, with a pointer reference as the -// first parameter. Just for fiddly compiler reasons; -// the reference isn't used. -//////////////////////////////////////////////////////////////////// +/** + * Similar to the above, with a pointer reference as the first parameter. + * Just for fiddly compiler reasons; the reference isn't used. +*/ template INLINE WantType * _dcast_ref(WantType *&, TypedObject *ptr) { diff --git a/panda/src/express/dcast.cxx b/panda/src/express/dcast.cxx index fcb0e02baf..63265fec6f 100644 --- a/panda/src/express/dcast.cxx +++ b/panda/src/express/dcast.cxx @@ -30,7 +30,7 @@ bool _dcast_verify(TypeHandle want_handle, size_t want_size, const TypedObject *ptr) { if (get_verify_dcast()) { - if (ptr == (const TypedObject *)NULL) { + if (ptr == nullptr) { // This is allowed these days. It used to be an error, but what the // heck. return true; diff --git a/panda/src/express/dcast.h b/panda/src/express/dcast.h index 4ab30bae3d..a234f2bbc7 100644 --- a/panda/src/express/dcast.h +++ b/panda/src/express/dcast.h @@ -64,7 +64,7 @@ INLINE const WantType *_dcast_ref(WantType *&, const TypedObject *ptr); #ifdef DO_DCAST // _dcast_verify performs the actual verification. -EXPCL_PANDAEXPRESS bool +EXPCL_PANDA_EXPRESS bool _dcast_verify(TypeHandle want_handle, size_t want_size, const TypedObject *ptr); #endif // DO_DCAST @@ -72,13 +72,13 @@ _dcast_verify(TypeHandle want_handle, size_t want_size, #define DCAST_INTO_V(to_pointer, from_pointer) \ { \ (to_pointer) = _dcast_ref(to_pointer, from_pointer); \ - nassertv((void *)(to_pointer) != (void *)NULL); \ + nassertv((void *)(to_pointer) != nullptr); \ } #define DCAST_INTO_R(to_pointer, from_pointer, return_value) \ { \ (to_pointer) = _dcast_ref(to_pointer, from_pointer); \ - nassertr((void *)(to_pointer) != (void *)NULL, return_value); \ + nassertr((void *)(to_pointer) != nullptr, return_value); \ } #include "dcast.T" diff --git a/panda/src/express/encrypt_string.cxx b/panda/src/express/encrypt_string.cxx index 0736e30be6..6c400d77f7 100644 --- a/panda/src/express/encrypt_string.cxx +++ b/panda/src/express/encrypt_string.cxx @@ -18,6 +18,12 @@ #include "virtualFileSystem.h" #include "config_express.h" +using std::istream; +using std::istringstream; +using std::ostream; +using std::ostringstream; +using std::string; + /** * Encrypts the indicated source string using the given password, and the * algorithm specified by encryption-algorithm. Returns the encrypted string. @@ -75,7 +81,7 @@ decrypt_string(const string &source, const string &password) { * to the dest file, overwriting its contents. The return value is bool on * success, or false on failure. */ -EXPCL_PANDAEXPRESS bool +EXPCL_PANDA_EXPRESS bool encrypt_file(const Filename &source, const Filename &dest, const string &password, const string &algorithm, int key_length, int iteration_count) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); @@ -85,14 +91,14 @@ encrypt_file(const Filename &source, const Filename &dest, const string &passwor source_filename.set_binary(); } istream *source_stream = vfs->open_read_file(source_filename, true); - if (source_stream == NULL) { + if (source_stream == nullptr) { express_cat.info() << "Couldn't open file " << source_filename << "\n"; return false; } Filename dest_filename = Filename::binary_filename(dest); ostream *dest_stream = vfs->open_write_file(dest_filename, true, true); - if (dest_stream == NULL) { + if (dest_stream == nullptr) { express_cat.info() << "Couldn't open file " << dest_filename << "\n"; vfs->close_read_file(source_stream); return false; @@ -115,12 +121,12 @@ encrypt_file(const Filename &source, const Filename &dest, const string &passwor * Note that a decryption error, including an incorrect password, cannot * easily be detected, and the output may simply be a garbage string. */ -EXPCL_PANDAEXPRESS bool +EXPCL_PANDA_EXPRESS bool decrypt_file(const Filename &source, const Filename &dest, const string &password) { Filename source_filename = Filename::binary_filename(source); VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); istream *source_stream = vfs->open_read_file(source_filename, false); - if (source_stream == NULL) { + if (source_stream == nullptr) { express_cat.info() << "Couldn't open file " << source_filename << "\n"; return false; } @@ -131,7 +137,7 @@ decrypt_file(const Filename &source, const Filename &dest, const string &passwor dest_filename.set_binary(); } ostream *dest_stream = vfs->open_write_file(dest_filename, true, true); - if (dest_stream == NULL) { + if (dest_stream == nullptr) { express_cat.info() << "Couldn't open file " << dest_filename << "\n"; vfs->close_read_file(source_stream); return false; diff --git a/panda/src/express/encrypt_string.h b/panda/src/express/encrypt_string.h index 4e0d12bafb..7b247baefe 100644 --- a/panda/src/express/encrypt_string.h +++ b/panda/src/express/encrypt_string.h @@ -22,26 +22,26 @@ BEGIN_PUBLISH -EXPCL_PANDAEXPRESS string -encrypt_string(const string &source, const string &password, - const string &algorithm = string(), int key_length = -1, +EXPCL_PANDA_EXPRESS std::string +encrypt_string(const std::string &source, const std::string &password, + const std::string &algorithm = std::string(), int key_length = -1, int iteration_count = -1); -EXPCL_PANDAEXPRESS string -decrypt_string(const string &source, const string &password); +EXPCL_PANDA_EXPRESS std::string +decrypt_string(const std::string &source, const std::string &password); -EXPCL_PANDAEXPRESS bool -encrypt_file(const Filename &source, const Filename &dest, const string &password, - const string &algorithm = string(), int key_length = -1, +EXPCL_PANDA_EXPRESS bool +encrypt_file(const Filename &source, const Filename &dest, const std::string &password, + const std::string &algorithm = std::string(), int key_length = -1, int iteration_count = -1); -EXPCL_PANDAEXPRESS bool -decrypt_file(const Filename &source, const Filename &dest, const string &password); +EXPCL_PANDA_EXPRESS bool +decrypt_file(const Filename &source, const Filename &dest, const std::string &password); -EXPCL_PANDAEXPRESS bool -encrypt_stream(istream &source, ostream &dest, const string &password, - const string &algorithm = string(), int key_length = -1, +EXPCL_PANDA_EXPRESS bool +encrypt_stream(std::istream &source, std::ostream &dest, const std::string &password, + const std::string &algorithm = std::string(), int key_length = -1, int iteration_count = -1); -EXPCL_PANDAEXPRESS bool -decrypt_stream(istream &source, ostream &dest, const string &password); +EXPCL_PANDA_EXPRESS bool +decrypt_stream(std::istream &source, std::ostream &dest, const std::string &password); END_PUBLISH diff --git a/panda/src/express/error_utils.cxx b/panda/src/express/error_utils.cxx index bae1da4a31..8509856f18 100644 --- a/panda/src/express/error_utils.cxx +++ b/panda/src/express/error_utils.cxx @@ -21,6 +21,8 @@ #include #endif +using std::string; + /** * */ @@ -191,7 +193,7 @@ string handle_socket_error() { return string(strerror(errno)); #else int err = WSAGetLastError(); - char *errmsg; + const char *errmsg; switch (err) { case 10022: errmsg = "An invalid argument was supplied"; @@ -229,7 +231,7 @@ string handle_socket_error() { errmsg = strerror(errno); default: if (express_cat.is_debug()) - express_cat.debug() << "handle_socket_error - unknown error: " << err << endl; + express_cat.debug() << "handle_socket_error - unknown error: " << err << std::endl; errmsg = "Unknown WSA error"; } @@ -282,12 +284,12 @@ get_network_error() { if (express_cat.is_debug()) express_cat.debug() << "get_network_error() - WSA error = 0 - error : " - << strerror(errno) << endl; + << strerror(errno) << std::endl; return EU_error_abort; default: if (express_cat.is_debug()) express_cat.debug() - << "get_network_error() - unknown error: " << err << endl; + << "get_network_error() - unknown error: " << err << std::endl; return EU_error_abort; } #endif diff --git a/panda/src/express/error_utils.h b/panda/src/express/error_utils.h index 10ed4d4bd8..0d4f22cd3f 100644 --- a/panda/src/express/error_utils.h +++ b/panda/src/express/error_utils.h @@ -74,12 +74,12 @@ enum ErrorUtilCode { EU_error_zlib = -80, }; -EXPCL_PANDAEXPRESS string error_to_text(ErrorUtilCode err); -EXPCL_PANDAEXPRESS int get_write_error(); +EXPCL_PANDA_EXPRESS std::string error_to_text(ErrorUtilCode err); +EXPCL_PANDA_EXPRESS int get_write_error(); #ifdef HAVE_NET -EXPCL_PANDAEXPRESS string handle_socket_error(); -EXPCL_PANDAEXPRESS int get_network_error(); +EXPCL_PANDA_EXPRESS std::string handle_socket_error(); +EXPCL_PANDA_EXPRESS int get_network_error(); #endif END_PUBLISH diff --git a/panda/src/express/fileReference.h b/panda/src/express/fileReference.h index b870121016..d874f26e11 100644 --- a/panda/src/express/fileReference.h +++ b/panda/src/express/fileReference.h @@ -23,7 +23,7 @@ * Keeps a reference-counted pointer to a file on disk. As long as the * FileReference is held, someone presumably has a use for this file. */ -class EXPCL_PANDAEXPRESS FileReference : public TypedReferenceCount { +class EXPCL_PANDA_EXPRESS FileReference : public TypedReferenceCount { PUBLISHED: INLINE FileReference(const Filename &filename); INLINE const Filename &get_filename() const; diff --git a/panda/src/express/hashGeneratorBase.h b/panda/src/express/hashGeneratorBase.h index 86145a74df..d843adb151 100644 --- a/panda/src/express/hashGeneratorBase.h +++ b/panda/src/express/hashGeneratorBase.h @@ -27,7 +27,7 @@ * Thus, a compile-time decision must be made for the kind of HashGenerator * that is appropriate for a particular class. */ -class EXPCL_PANDAEXPRESS HashGeneratorBase { +class EXPCL_PANDA_EXPRESS HashGeneratorBase { public: INLINE HashGeneratorBase(); diff --git a/panda/src/express/hashVal.I b/panda/src/express/hashVal.I index 6519915034..9c67130f52 100644 --- a/panda/src/express/hashVal.I +++ b/panda/src/express/hashVal.I @@ -100,7 +100,7 @@ merge_with(const HashVal &other) { * Outputs the HashVal as four unsigned decimal integers. */ INLINE void HashVal:: -output_dec(ostream &out) const { +output_dec(std::ostream &out) const { out << _hv[0] << " " << _hv[1] << " " << _hv[2] << " " << _hv[3]; } @@ -108,7 +108,7 @@ output_dec(ostream &out) const { * Inputs the HashVal as four unsigned decimal integers. */ INLINE void HashVal:: -input_dec(istream &in) { +input_dec(std::istream &in) { in >> _hv[0] >> _hv[1] >> _hv[2] >> _hv[3]; } @@ -116,7 +116,7 @@ input_dec(istream &in) { * */ INLINE void HashVal:: -output(ostream &out) const { +output(std::ostream &out) const { output_hex(out); } @@ -181,7 +181,7 @@ hash_ramfile(const Ramfile &ramfile) { * functionality) available. */ INLINE void HashVal:: -hash_string(const string &data) { +hash_string(const std::string &data) { hash_buffer(data.data(), data.length()); } @@ -191,7 +191,7 @@ hash_string(const string &data) { * functionality) available. */ INLINE void HashVal:: -hash_bytes(const pvector &data) { +hash_bytes(const vector_uchar &data) { hash_buffer((const char *)&data[0], data.size()); } #endif // HAVE_OPENSSL @@ -221,7 +221,7 @@ fromhex(char digit) { } -INLINE ostream &operator << (ostream &out, const HashVal &hv) { +INLINE std::ostream &operator << (std::ostream &out, const HashVal &hv) { hv.output(out); return out; } diff --git a/panda/src/express/hashVal.cxx b/panda/src/express/hashVal.cxx index aa08714668..3d2e6f42f5 100644 --- a/panda/src/express/hashVal.cxx +++ b/panda/src/express/hashVal.cxx @@ -20,6 +20,12 @@ #include "openssl/md5.h" #endif // HAVE_OPENSSL +using std::istream; +using std::istringstream; +using std::ostream; +using std::ostringstream; +using std::string; + /** * Outputs the HashVal as a 32-digit hexadecimal number. @@ -39,7 +45,7 @@ output_hex(ostream &out) const { */ void HashVal:: input_hex(istream &in) { - in >> ws; + in >> std::ws; char buffer[32]; size_t i = 0; int ch = in.get(); @@ -53,7 +59,7 @@ input_hex(istream &in) { } if (i != 32) { - in.clear(ios::failbit|in.rdstate()); + in.clear(std::ios::failbit|in.rdstate()); return; } @@ -174,7 +180,7 @@ hash_file(const Filename &filename) { Filename bin_filename = Filename::binary_filename(filename); VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); istream *istr = vfs->open_read_file(bin_filename, false); - if (istr == (istream *)NULL) { + if (istr == nullptr) { (*this) = HashVal(); return false; } @@ -203,7 +209,7 @@ hash_stream(istream &stream) { char buffer[buffer_size]; // Seek the stream to the beginning in case it wasn't there already. - stream.seekg(0, ios::beg); + stream.seekg(0, std::ios::beg); stream.read(buffer, buffer_size); size_t count = stream.gcount(); diff --git a/panda/src/express/hashVal.h b/panda/src/express/hashVal.h index a4b3754614..2b1a6b49ed 100644 --- a/panda/src/express/hashVal.h +++ b/panda/src/express/hashVal.h @@ -22,12 +22,13 @@ #include "datagramIterator.h" #include "streamWriter.h" #include "streamReader.h" +#include "vector_uchar.h" /** * Stores a 128-bit value that represents the hashed contents (typically MD5) * of a file or buffer. */ -class EXPCL_PANDAEXPRESS HashVal { +class EXPCL_PANDA_EXPRESS HashVal { PUBLISHED: INLINE HashVal(); INLINE HashVal(const HashVal ©); @@ -40,20 +41,20 @@ PUBLISHED: INLINE void merge_with(const HashVal &other); - INLINE void output_dec(ostream &out) const; - INLINE void input_dec(istream &in); - void output_hex(ostream &out) const; - void input_hex(istream &in); - void output_binary(ostream &out) const; - void input_binary(istream &in); + INLINE void output_dec(std::ostream &out) const; + INLINE void input_dec(std::istream &in); + void output_hex(std::ostream &out) const; + void input_hex(std::istream &in); + void output_binary(std::ostream &out) const; + void input_binary(std::istream &in); - INLINE void output(ostream &out) const; + INLINE void output(std::ostream &out) const; - string as_dec() const; - bool set_from_dec(const string &text); + std::string as_dec() const; + bool set_from_dec(const std::string &text); - string as_hex() const; - bool set_from_hex(const string &text); + std::string as_hex() const; + bool set_from_hex(const std::string &text); vector_uchar as_bin() const; bool set_from_bin(const vector_uchar &text); @@ -65,10 +66,10 @@ PUBLISHED: #ifdef HAVE_OPENSSL bool hash_file(const Filename &filename); - bool hash_stream(istream &stream); + bool hash_stream(std::istream &stream); INLINE void hash_ramfile(const Ramfile &ramfile); - INLINE void hash_string(const string &data); - INLINE void hash_bytes(const pvector &data); + INLINE void hash_string(const std::string &data); + INLINE void hash_bytes(const vector_uchar &data); void hash_buffer(const char *buffer, int length); #endif // HAVE_OPENSSL @@ -81,7 +82,7 @@ private: uint32_t _hv[4]; }; -INLINE ostream &operator << (ostream &out, const HashVal &hv); +INLINE std::ostream &operator << (std::ostream &out, const HashVal &hv); #include "hashVal.I" diff --git a/panda/src/express/make_ca_bundle.cxx b/panda/src/express/make_ca_bundle.cxx index 0794312de1..0773bb88ec 100644 --- a/panda/src/express/make_ca_bundle.cxx +++ b/panda/src/express/make_ca_bundle.cxx @@ -15,13 +15,17 @@ #include "openSSLWrapper.h" #include +using std::cerr; +using std::stringstream; +using std::string; + static const char *source_filename = "ca-bundle.crt"; static const char *target_filename = "ca_bundle_data_src.c"; int main(int argc, char *argv[]) { FILE *fin = fopen(source_filename, "r"); - if (fin == NULL) { + if (fin == nullptr) { cerr << "Couldn't open " << source_filename << " for reading.\n"; return 1; } @@ -33,7 +37,7 @@ main(int argc, char *argv[]) { // function, or it will get confused. ERR_clear_error(); STACK_OF(X509_INFO) *inf; - inf = PEM_X509_INFO_read(fin, NULL, NULL, NULL); + inf = PEM_X509_INFO_read(fin, nullptr, nullptr, nullptr); if (!inf) { // Could not scan certificates. @@ -45,7 +49,7 @@ main(int argc, char *argv[]) { << " entries.\n"; // Now convert the certificates to DER form. - stringstream der_stream; + std::stringstream der_stream; int cert_count = 0; int num_entries = sk_X509_INFO_num(inf); @@ -55,7 +59,7 @@ main(int argc, char *argv[]) { if (itmp->x509) { X509 *cert = itmp->x509; - int der_len = i2d_X509(cert, NULL); + int der_len = i2d_X509(cert, nullptr); unsigned char *der_buf = new unsigned char[der_len]; unsigned char *p = der_buf; i2d_X509(cert, &p); @@ -70,7 +74,7 @@ main(int argc, char *argv[]) { // Now write the data to the .c file, in a compilable form, similar to // bin2c. - ofstream out; + std::ofstream out; Filename target = Filename::text_filename(string(target_filename)); if (!target.open_write(out)) { cerr << "Couldn't open " << target_filename << " for writing.\n"; @@ -78,7 +82,7 @@ main(int argc, char *argv[]) { } der_stream.seekg(0); - istream &in = der_stream; + std::istream &in = der_stream; string table_type = "const unsigned char "; string length_type = "const int "; @@ -99,7 +103,7 @@ main(int argc, char *argv[]) { << " * in DER form, for compiling into OpenSSLWrapper.\n" << " */\n\n" << static_keyword << table_type << table_name << "[] = {"; - out << hex << setfill('0'); + out << std::hex << std::setfill('0'); int count = 0; int col = 0; unsigned int ch; @@ -113,14 +117,14 @@ main(int argc, char *argv[]) { } else { out << ", "; } - out << "0x" << setw(2) << ch; + out << "0x" << std::setw(2) << ch; col++; count++; ch = in.get(); } out << "\n};\n\n" << static_keyword << length_type << table_name << "_len = " - << dec << count << ";\n\n"; + << std::dec << count << ";\n\n"; cerr << "Wrote " << cert_count << " certificates to " << target_filename << "\n"; diff --git a/panda/src/express/memoryInfo.I b/panda/src/express/memoryInfo.I index 4fb25b34ca..2e1a0ba9ac 100644 --- a/panda/src/express/memoryInfo.I +++ b/panda/src/express/memoryInfo.I @@ -16,13 +16,13 @@ * NULL. */ void *MemoryInfo::get_void_ptr() const { - if (_void_ptr != (void *)NULL) { + if (_void_ptr != nullptr) { return _void_ptr; } - if (_ref_ptr == (void *)NULL) { + if (_ref_ptr == nullptr) { return _typed_ptr; } - if (_typed_ptr == (void *)NULL) { + if (_typed_ptr == nullptr) { return _ref_ptr; } return ((void *)_ref_ptr < (void *)_typed_ptr) ? (void *)_ref_ptr : (void *)_typed_ptr; diff --git a/panda/src/express/memoryInfo.cxx b/panda/src/express/memoryInfo.cxx index d12b7313a0..b753caa043 100644 --- a/panda/src/express/memoryInfo.cxx +++ b/panda/src/express/memoryInfo.cxx @@ -23,9 +23,9 @@ */ MemoryInfo:: MemoryInfo() { - _void_ptr = (void *)NULL; - _ref_ptr = (ReferenceCount *)NULL; - _typed_ptr = (TypedObject *)NULL; + _void_ptr = nullptr; + _ref_ptr = nullptr; + _typed_ptr = nullptr; _size = 0; _static_type = TypeHandle::none(); _dynamic_type = TypeHandle::none(); @@ -79,7 +79,7 @@ determine_dynamic_type() { _static_type != TypeHandle::none()) { // See if we know enough now to infer the dynamic type from the pointer. - if (_typed_ptr == (TypedObject *)NULL) { + if (_typed_ptr == nullptr) { // If our static type is known to inherit from TypedReferenceCount, then // we can directly downcast to get the TypedObject pointer. if (_static_type.is_derived_from(TypedReferenceCount::get_class_type())) { @@ -87,7 +87,7 @@ determine_dynamic_type() { } } - if (_typed_ptr != (TypedObject *)NULL) { + if (_typed_ptr != nullptr) { // If we have a TypedObject pointer, we can determine the type. This // might still not return the exact type, particularly if we are being // called within the destructor or constructor of this object. diff --git a/panda/src/express/memoryUsage.cxx b/panda/src/express/memoryUsage.cxx index 178de476fa..b76ae0ed3e 100644 --- a/panda/src/express/memoryUsage.cxx +++ b/panda/src/express/memoryUsage.cxx @@ -27,6 +27,8 @@ #include #include +using std::pair; + MemoryUsage *MemoryUsage::_global_ptr; // This flag is used to protect the operator newdelete handlers against @@ -79,7 +81,7 @@ show() const { #ifdef DO_MEMORY_USAGE // First, copy the relevant information to a vector so we can sort by // counts. Don't use a pvector. - typedef vector CountSorter; + typedef std::vector CountSorter; CountSorter count_sorter; Counts::const_iterator ci; for (ci = _counts.begin(); ci != _counts.end(); ++ci) { @@ -387,7 +389,7 @@ mark_pointer(void *ptr, size_t size, ReferenceCount *ref_ptr) { // We're recording this pointer as now in use. ns_record_void_pointer(ptr, size); - if (ref_ptr != (ReferenceCount *)NULL) { + if (ref_ptr != nullptr) { // Make the pointer typed. This is particularly necessary in case the // ref_ptr is a different value than the base void pointer; this may be // our only opportunity to associate the two pointers. @@ -599,7 +601,7 @@ ns_record_pointer(ReferenceCount *ptr) { // We might already have a ReferenceCount pointer, thanks to a previous // call to mark_pointer(). - nassertv(info->_ref_ptr == NULL || info->_ref_ptr == ptr); + nassertv(info->_ref_ptr == nullptr || info->_ref_ptr == ptr); info->_ref_ptr = ptr; info->_static_type = ReferenceCount::get_class_type(); @@ -765,7 +767,7 @@ ns_remove_pointer(ReferenceCount *ptr) { MemoryInfo *info = (*ti).second; - if (info->_ref_ptr == NULL) { + if (info->_ref_ptr == nullptr) { express_cat.error() << "Pointer " << (void *)ptr << " deleted twice!\n"; return; @@ -777,8 +779,8 @@ ns_remove_pointer(ReferenceCount *ptr) { << "Removing ReferenceCount pointer " << (void *)ptr << "\n"; } - info->_ref_ptr = (ReferenceCount *)NULL; - info->_typed_ptr = (TypedObject *)NULL; + info->_ref_ptr = nullptr; + info->_typed_ptr = nullptr; if (info->_freeze_index == _freeze_index) { double now = TrueClock::get_global_ptr()->get_long_time(); @@ -791,7 +793,7 @@ ns_remove_pointer(ReferenceCount *ptr) { _recursion_protect = false; } - if (ptr != info->_void_ptr || info->_void_ptr == NULL) { + if (ptr != info->_void_ptr || info->_void_ptr == nullptr) { // Remove the entry from the table. // We have to protect modifications to the table from recursive calls by @@ -800,7 +802,7 @@ ns_remove_pointer(ReferenceCount *ptr) { _table.erase(ti); _recursion_protect = false; - if (info->_void_ptr == NULL) { + if (info->_void_ptr == nullptr) { // That was the last entry. Remove it altogether. _total_cpp_size -= info->_size; if (info->_freeze_index == _freeze_index) { @@ -847,7 +849,7 @@ ns_record_void_pointer(void *ptr, size_t size) { MemoryInfo *info = (*insert_result.first).second; // We shouldn't already have a void pointer. - if (info->_void_ptr != (void *)NULL) { + if (info->_void_ptr != nullptr) { express_cat.error() << "Void pointer " << (void *)ptr << " recorded twice!\n"; nassertv(false); @@ -900,14 +902,14 @@ ns_remove_void_pointer(void *ptr) { MemoryInfo *info = (*ti).second; - if (info->_void_ptr == (void *)NULL) { + if (info->_void_ptr == nullptr) { express_cat.error() << "Pointer " << (void *)ptr << " deleted twice!\n"; return; } nassertv(info->_void_ptr == ptr); - if (info->_ref_ptr != (ReferenceCount *)NULL) { + if (info->_ref_ptr != nullptr) { express_cat.error() << "Pointer " << (void *)ptr << " did not destruct before being deleted!\n"; @@ -916,7 +918,7 @@ ns_remove_void_pointer(void *ptr) { } } - info->_void_ptr = NULL; + info->_void_ptr = nullptr; // Remove it from the table. @@ -970,7 +972,7 @@ ns_get_pointers(MemoryUsagePointers &result) { for (si = _info_set.begin(); si != _info_set.end(); ++si) { MemoryInfo *info = (*si); if (info->_freeze_index == _freeze_index && - info->_ref_ptr != (ReferenceCount *)NULL) { + info->_ref_ptr != nullptr) { result.add_entry(info->_ref_ptr, info->_typed_ptr, info->get_type(), now - info->_time); } @@ -997,7 +999,7 @@ ns_get_pointers_of_type(MemoryUsagePointers &result, TypeHandle type) { for (si = _info_set.begin(); si != _info_set.end(); ++si) { MemoryInfo *info = (*si); if (info->_freeze_index == _freeze_index && - info->_ref_ptr != (ReferenceCount *)NULL) { + info->_ref_ptr != nullptr) { TypeHandle info_type = info->get_type(); if (info_type != TypeHandle::none() && info_type.is_derived_from(type)) { @@ -1029,7 +1031,7 @@ ns_get_pointers_of_age(MemoryUsagePointers &result, for (si = _info_set.begin(); si != _info_set.end(); ++si) { MemoryInfo *info = (*si); if (info->_freeze_index == _freeze_index && - info->_ref_ptr != (ReferenceCount *)NULL) { + info->_ref_ptr != nullptr) { double age = now - info->_time; if ((age >= from && age <= to) || (age >= to && age <= from)) { @@ -1071,7 +1073,7 @@ ns_get_pointers_with_zero_count(MemoryUsagePointers &result) { for (si = _info_set.begin(); si != _info_set.end(); ++si) { MemoryInfo *info = (*si); if (info->_freeze_index == _freeze_index && - info->_ref_ptr != (ReferenceCount *)NULL) { + info->_ref_ptr != nullptr) { if (info->_ref_ptr->get_ref_count() == 0) { info->_ref_ptr->ref(); result.add_entry(info->_ref_ptr, info->_typed_ptr, info->get_type(), @@ -1185,7 +1187,7 @@ consolidate_void_ptr(MemoryInfo *info) { return; } - if (info->_typed_ptr == (TypedObject *)NULL) { + if (info->_typed_ptr == nullptr) { // We don't have a typed pointer for this thing yet. return; } @@ -1199,7 +1201,7 @@ consolidate_void_ptr(MemoryInfo *info) { return; } - nassertv(info->_void_ptr == NULL); + nassertv(info->_void_ptr == nullptr); Table::iterator ti; ti = _table.find(typed_ptr); @@ -1212,7 +1214,7 @@ consolidate_void_ptr(MemoryInfo *info) { MemoryInfo *typed_info = (*ti).second; nassertv(typed_info->_void_ptr == typed_ptr && - typed_info->_ref_ptr == NULL); + typed_info->_ref_ptr == nullptr); info->_void_ptr = typed_info->_void_ptr; if (typed_info->is_size_known()) { diff --git a/panda/src/express/memoryUsage.h b/panda/src/express/memoryUsage.h index 9742348cac..0371877ee0 100644 --- a/panda/src/express/memoryUsage.h +++ b/panda/src/express/memoryUsage.h @@ -32,7 +32,7 @@ class MemoryUsagePointers; * When compiled with NDEBUG set, this entire class does nothing and compiles * to a stub. */ -class EXPCL_PANDAEXPRESS MemoryUsage : public MemoryHook { +class EXPCL_PANDA_EXPRESS MemoryUsage : public MemoryHook { public: ALWAYS_INLINE static bool get_track_memory_usage(); @@ -156,12 +156,12 @@ private: * one pointer or the other. We don't store an entry for an object's * TypedObject pointer. */ - typedef map Table; + typedef std::map Table; Table _table; // This table indexes the individual MemoryInfo objects, for unique // iteration. - typedef set InfoSet; + typedef std::set InfoSet; InfoSet _info_set; bool _info_set_dirty; @@ -179,7 +179,7 @@ private: private: // Cannot use a pmap, since that would be recursive! - typedef map Counts; + typedef std::map Counts; Counts _counts; }; TypeHistogram _trend_types; diff --git a/panda/src/express/memoryUsagePointerCounts.I b/panda/src/express/memoryUsagePointerCounts.I index 79aeba084c..0c4f97ae78 100644 --- a/panda/src/express/memoryUsagePointerCounts.I +++ b/panda/src/express/memoryUsagePointerCounts.I @@ -98,8 +98,8 @@ operator < (const MemoryUsagePointerCounts &other) const { return false; } -INLINE ostream & -operator << (ostream &out, const MemoryUsagePointerCounts &c) { +INLINE std::ostream & +operator << (std::ostream &out, const MemoryUsagePointerCounts &c) { c.output(out); return out; } diff --git a/panda/src/express/memoryUsagePointerCounts.cxx b/panda/src/express/memoryUsagePointerCounts.cxx index b91be61bcc..8ce69872d6 100644 --- a/panda/src/express/memoryUsagePointerCounts.cxx +++ b/panda/src/express/memoryUsagePointerCounts.cxx @@ -34,7 +34,7 @@ add_info(MemoryInfo *info) { * */ void MemoryUsagePointerCounts:: -output(ostream &out) const { +output(std::ostream &out) const { #ifdef DO_MEMORY_USAGE out << _count << " pointers"; if (_unknown_size_count < _count) { @@ -56,7 +56,7 @@ output(ostream &out) const { * units. */ void MemoryUsagePointerCounts:: -output_bytes(ostream &out, size_t size) { +output_bytes(std::ostream &out, size_t size) { #ifdef DO_MEMORY_USAGE if (size < 4 * 1024) { out << size << " bytes"; diff --git a/panda/src/express/memoryUsagePointerCounts.h b/panda/src/express/memoryUsagePointerCounts.h index 2d95052ad8..b0a1820a44 100644 --- a/panda/src/express/memoryUsagePointerCounts.h +++ b/panda/src/express/memoryUsagePointerCounts.h @@ -32,7 +32,7 @@ public: INLINE void clear(); void add_info(MemoryInfo *info); - void output(ostream &out) const; + void output(std::ostream &out) const; INLINE bool is_size_unknown() const; INLINE size_t get_size() const; @@ -41,7 +41,7 @@ public: INLINE bool operator < (const MemoryUsagePointerCounts &other) const; private: - static void output_bytes(ostream &out, size_t size); + static void output_bytes(std::ostream &out, size_t size); private: int _count; @@ -49,7 +49,7 @@ private: size_t _size; }; -INLINE ostream &operator << (ostream &out, const MemoryUsagePointerCounts &c); +INLINE std::ostream &operator << (std::ostream &out, const MemoryUsagePointerCounts &c); #include "memoryUsagePointerCounts.I" diff --git a/panda/src/express/memoryUsagePointers.cxx b/panda/src/express/memoryUsagePointers.cxx index dd412958da..065519bc0c 100644 --- a/panda/src/express/memoryUsagePointers.cxx +++ b/panda/src/express/memoryUsagePointers.cxx @@ -111,7 +111,7 @@ get_type(size_t n) const { /** * Returns the type name of the nth pointer, if it is known. */ -string MemoryUsagePointers:: +std::string MemoryUsagePointers:: get_type_name(size_t n) const { #ifdef DO_MEMORY_USAGE nassertr(n < get_num_pointers(), ""); @@ -150,7 +150,7 @@ clear() { * */ void MemoryUsagePointers:: -output(ostream &out) const { +output(std::ostream &out) const { #ifdef DO_MEMORY_USAGE out << _entries.size() << " pointers."; #endif diff --git a/panda/src/express/memoryUsagePointers.h b/panda/src/express/memoryUsagePointers.h index 344c2edc6b..30063cf925 100644 --- a/panda/src/express/memoryUsagePointers.h +++ b/panda/src/express/memoryUsagePointers.h @@ -35,7 +35,7 @@ * This class is just a user interface to talk about pointers stored in a * MemoryUsage object. It doesn't even exist when compiled with NDEBUG. */ -class EXPCL_PANDAEXPRESS MemoryUsagePointers { +class EXPCL_PANDA_EXPRESS MemoryUsagePointers { PUBLISHED: MemoryUsagePointers(); ~MemoryUsagePointers(); @@ -47,7 +47,7 @@ PUBLISHED: MAKE_SEQ(get_typed_pointers, get_num_pointers, get_typed_pointer); TypeHandle get_type(size_t n) const; - string get_type_name(size_t n) const; + std::string get_type_name(size_t n) const; double get_age(size_t n) const; #ifdef DO_MEMORY_USAGE @@ -56,7 +56,7 @@ PUBLISHED: void clear(); - void output(ostream &out) const; + void output(std::ostream &out) const; private: void add_entry(ReferenceCount *ref_ptr, TypedObject *typed_ptr, @@ -86,7 +86,7 @@ private: friend class MemoryUsage; }; -INLINE ostream &operator << (ostream &out, const MemoryUsagePointers &mup) { +INLINE std::ostream &operator << (std::ostream &out, const MemoryUsagePointers &mup) { mup.output(out); return out; } diff --git a/panda/src/express/memoryUsagePointers_ext.cxx b/panda/src/express/memoryUsagePointers_ext.cxx index c1013027ab..27376b9cad 100644 --- a/panda/src/express/memoryUsagePointers_ext.cxx +++ b/panda/src/express/memoryUsagePointers_ext.cxx @@ -36,18 +36,18 @@ get_python_pointer(size_t n) const { ReferenceCount *ref_ptr = _this->get_pointer(n); bool memory_rules = false; - if (ref_ptr != (ReferenceCount *)NULL) { + if (ref_ptr != nullptr) { memory_rules = true; ref_ptr->ref(); } - if (typed_ptr != (TypedObject *)NULL) { + if (typed_ptr != nullptr) { return DTool_CreatePyInstanceTyped(typed_ptr, Dtool_TypedObject, memory_rules, false, typed_ptr->get_type_index()); } - if (ref_ptr == (ReferenceCount *)NULL) { + if (ref_ptr == nullptr) { return Py_BuildValue(""); } diff --git a/panda/src/express/multifile.I b/panda/src/express/multifile.I index a498534726..128eb5297e 100644 --- a/panda/src/express/multifile.I +++ b/panda/src/express/multifile.I @@ -35,7 +35,7 @@ set_multifile_name(const Filename &multifile_name) { */ INLINE bool Multifile:: is_read_valid() const { - return (_read != (IStreamWrapper *)NULL); + return (_read != nullptr); } /** @@ -44,7 +44,7 @@ is_read_valid() const { */ INLINE bool Multifile:: is_write_valid() const { - return (_write != (ostream *)NULL && !_write->fail()); + return (_write != nullptr && !_write->fail()); } /** @@ -143,7 +143,7 @@ get_encryption_flag() const { * implicit call to flush(). */ INLINE void Multifile:: -set_encryption_password(const string &encryption_password) { +set_encryption_password(const std::string &encryption_password) { if (_encryption_password != encryption_password) { if (!_new_subfiles.empty()) { flush(); @@ -156,7 +156,7 @@ set_encryption_password(const string &encryption_password) { * Returns the password that will be used to encrypt subfiles subsequently * added to the multifile. See set_encryption_password(). */ -INLINE const string &Multifile:: +INLINE const std::string &Multifile:: get_encryption_password() const { return _encryption_password; } @@ -176,7 +176,7 @@ get_encryption_password() const { * flush(). */ INLINE void Multifile:: -set_encryption_algorithm(const string &encryption_algorithm) { +set_encryption_algorithm(const std::string &encryption_algorithm) { if (_encryption_algorithm != encryption_algorithm) { if (!_new_subfiles.empty()) { flush(); @@ -189,7 +189,7 @@ set_encryption_algorithm(const string &encryption_algorithm) { * Returns the encryption algorithm that was specified by * set_encryption_algorithm(). */ -INLINE const string &Multifile:: +INLINE const std::string &Multifile:: get_encryption_algorithm() const { return _encryption_algorithm; } @@ -268,7 +268,7 @@ get_encryption_iteration_count() const { * reduced in size after this operation, until the next call to repack(). */ INLINE bool Multifile:: -remove_subfile(const string &subfile_name) { +remove_subfile(const std::string &subfile_name) { int index = find_subfile(subfile_name); if (index >= 0) { remove_subfile(index); @@ -292,16 +292,16 @@ read_subfile(int index) { * Returns a string with the first n bytes written to a Multifile, to identify * it as a Multifile. */ -INLINE string Multifile:: +INLINE std::string Multifile:: get_magic_number() { - return string(_header, _header_size); + return std::string(_header, _header_size); } /** * Returns the string that preceded the Multifile header on the file, if any. * See set_header_prefix(). */ -INLINE const string &Multifile:: +INLINE const std::string &Multifile:: get_header_prefix() const { return _header_prefix; } @@ -310,9 +310,9 @@ get_header_prefix() const { * Converts a size_t address read from the file to a streampos byte address * within the file. */ -INLINE streampos Multifile:: +INLINE std::streampos Multifile:: word_to_streampos(size_t word) const { - return (streampos)word * (streampos)_scale_factor; + return (std::streampos)word * (std::streampos)_scale_factor; } /** @@ -320,16 +320,16 @@ word_to_streampos(size_t word) const { * suitable for writing to the file. */ INLINE size_t Multifile:: -streampos_to_word(streampos fpos) const { - return (size_t)((fpos + (streampos)_scale_factor - (streampos)1) / (streampos)_scale_factor); +streampos_to_word(std::streampos fpos) const { + return (size_t)((fpos + (std::streampos)_scale_factor - (std::streampos)1) / (std::streampos)_scale_factor); } /** * Rounds the streampos byte address up to the next multiple of _scale_factor. * Only multiples of _scale_factor may be written to the file. */ -INLINE streampos Multifile:: -normalize_streampos(streampos fpos) const { +INLINE std::streampos Multifile:: +normalize_streampos(std::streampos fpos) const { return word_to_streampos(streampos_to_word(fpos)); } @@ -354,11 +354,11 @@ Subfile() { _data_start = 0; _data_length = 0; _timestamp = 0; - _source = (istream *)NULL; + _source = nullptr; _flags = 0; _compression_level = 0; #ifdef HAVE_OPENSSL - _pkey = NULL; + _pkey = nullptr; #endif } @@ -418,8 +418,8 @@ is_cert_special() const { * contributes to this Subfile, either in the index record or in the subfile * data. */ -INLINE streampos Multifile::Subfile:: +INLINE std::streampos Multifile::Subfile:: get_last_byte_pos() const { - return max(_index_start + (streampos)_index_length, - _data_start + (streampos)_data_length) - (streampos)1; + return std::max(_index_start + (std::streampos)_index_length, + _data_start + (std::streampos)_data_length) - (std::streampos)1; } diff --git a/panda/src/express/multifile.cxx b/panda/src/express/multifile.cxx index 5a7d86f17b..e625861f87 100644 --- a/panda/src/express/multifile.cxx +++ b/panda/src/express/multifile.cxx @@ -28,6 +28,19 @@ #include "openSSLWrapper.h" +using std::ios; +using std::iostream; +using std::istream; +using std::max; +using std::min; +using std::ostream; +using std::ostringstream; +using std::streamoff; +using std::streampos; +using std::streamsize; +using std::stringstream; +using std::string; + // This sequence of bytes begins each Multifile to identify it as a Multifile. const char Multifile::_header[] = "pmf\0\n\r"; const size_t Multifile::_header_size = 6; @@ -102,8 +115,8 @@ Multifile() : "be loaded quickly, without paying the cost of an expensive hash on " "each subfile in order to decrypt it.")); - _read = (IStreamWrapper *)NULL; - _write = (ostream *)NULL; + _read = nullptr; + _write = nullptr; _offset = 0; _owns_stream = false; _next_index = 0; @@ -136,25 +149,6 @@ Multifile:: close(); } -/** - * Don't try to copy Multifiles. - */ -Multifile:: -Multifile(const Multifile ©) : - _read_filew(_read_file), - _read_write_filew(_read_write_file) -{ - nassertv(false); -} - -/** - * Don't try to copy Multifiles. - */ -void Multifile:: -operator = (const Multifile ©) { - nassertv(false); -} - /** * Opens the named Multifile on disk for reading. The Multifile index is read * in, and the list of subfiles becomes available; individual subfiles may @@ -171,11 +165,11 @@ open_read(const Filename &multifile_name, const streampos &offset) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); PT(VirtualFile) vfile = vfs->get_file(fname); - if (vfile == NULL) { + if (vfile == nullptr) { return false; } istream *multifile_stream = vfile->open_read_file(false); - if (multifile_stream == NULL) { + if (multifile_stream == nullptr) { return false; } @@ -200,7 +194,7 @@ bool Multifile:: open_read(IStreamWrapper *multifile_stream, bool owns_pointer, const streampos &offset) { close(); - _timestamp = time(NULL); + _timestamp = time(nullptr); _timestamp_dirty = true; _read = multifile_stream; _owns_stream = owns_pointer; @@ -225,7 +219,7 @@ open_write(const Filename &multifile_name) { if (!fname.open_write(_write_file, true)) { return false; } - _timestamp = time(NULL); + _timestamp = time(nullptr); _timestamp_dirty = true; _write = &_write_file; _multifile_name = multifile_name; @@ -243,7 +237,7 @@ open_write(const Filename &multifile_name) { bool Multifile:: open_write(ostream *multifile_stream, bool owns_pointer) { close(); - _timestamp = time(NULL); + _timestamp = time(nullptr); _timestamp_dirty = true; _write = multifile_stream; _owns_stream = owns_pointer; @@ -272,7 +266,7 @@ open_read_write(const Filename &multifile_name) { if (exists) { _timestamp = fname.get_timestamp(); } else { - _timestamp = time(NULL); + _timestamp = time(nullptr); } _timestamp_dirty = true; _read = &_read_write_filew; @@ -298,7 +292,7 @@ open_read_write(const Filename &multifile_name) { bool Multifile:: open_read_write(iostream *multifile_stream, bool owns_pointer) { close(); - _timestamp = time(NULL); + _timestamp = time(nullptr); _timestamp_dirty = true; // We don't support locking when opening a file in read-write mode, because @@ -338,15 +332,15 @@ close() { if (_owns_stream) { // We prefer to delete the IStreamWrapper over the ostream, if possible. - if (_read != (IStreamWrapper *)NULL) { + if (_read != nullptr) { delete _read; - } else if (_write != (ostream *)NULL) { + } else if (_write != nullptr) { delete _write; } } - _read = (IStreamWrapper *)NULL; - _write = (ostream *)NULL; + _read = nullptr; + _write = nullptr; _offset = 0; _owns_stream = false; _next_index = 0; @@ -443,7 +437,7 @@ add_subfile(const string &subfile_name, const Filename &filename, add_new_subfile(subfile, compression_level); } - _timestamp = time(NULL); + _timestamp = time(nullptr); _timestamp_dirty = true; return name; @@ -528,7 +522,7 @@ update_subfile(const string &subfile_name, const Filename &filename, add_new_subfile(subfile, compression_level); } - _timestamp = time(NULL); + _timestamp = time(nullptr); _timestamp_dirty = true; return name; @@ -622,9 +616,9 @@ add_signature(const Filename &certificate, const Filename &chain, // Create an in-memory BIO to read the "file" from the buffer. BIO *certificate_mbio = BIO_new_mem_buf((void *)certificate_data.data(), certificate_data.size()); - X509 *x509 = PEM_read_bio_X509(certificate_mbio, NULL, NULL, (void *)""); + X509 *x509 = PEM_read_bio_X509(certificate_mbio, nullptr, nullptr, (void *)""); BIO_free(certificate_mbio); - if (x509 == NULL) { + if (x509 == nullptr) { express_cat.info() << "Could not read certificate in " << certificate << ".\n"; return false; @@ -644,10 +638,10 @@ add_signature(const Filename &certificate, const Filename &chain, } BIO *chain_mbio = BIO_new_mem_buf((void *)chain_data.data(), chain_data.size()); - X509 *c = PEM_read_bio_X509(chain_mbio, NULL, NULL, (void *)""); - while (c != NULL) { + X509 *c = PEM_read_bio_X509(chain_mbio, nullptr, nullptr, (void *)""); + while (c != nullptr) { cert_chain.push_back(c); - c = PEM_read_bio_X509(chain_mbio, NULL, NULL, (void *)""); + c = PEM_read_bio_X509(chain_mbio, nullptr, nullptr, (void *)""); } BIO_free(chain_mbio); @@ -668,10 +662,10 @@ add_signature(const Filename &certificate, const Filename &chain, } BIO *pkey_mbio = BIO_new_mem_buf((void *)pkey_data.data(), pkey_data.size()); - EVP_PKEY *evp_pkey = PEM_read_bio_PrivateKey(pkey_mbio, NULL, NULL, + EVP_PKEY *evp_pkey = PEM_read_bio_PrivateKey(pkey_mbio, nullptr, nullptr, (void *)password.c_str()); BIO_free(pkey_mbio); - if (evp_pkey == NULL) { + if (evp_pkey == nullptr) { express_cat.info() << "Could not read private key in " << pkey << ".\n"; return false; @@ -713,10 +707,10 @@ add_signature(const Filename &composite, const string &password) { // Get the private key. BIO *pkey_mbio = BIO_new_mem_buf((void *)composite_data.data(), composite_data.size()); - EVP_PKEY *evp_pkey = PEM_read_bio_PrivateKey(pkey_mbio, NULL, NULL, + EVP_PKEY *evp_pkey = PEM_read_bio_PrivateKey(pkey_mbio, nullptr, nullptr, (void *)password.c_str()); BIO_free(pkey_mbio); - if (evp_pkey == NULL) { + if (evp_pkey == nullptr) { express_cat.info() << "Could not read private key in " << composite << ".\n"; return false; @@ -726,10 +720,10 @@ add_signature(const Filename &composite, const string &password) { CertChain cert_chain; BIO *chain_mbio = BIO_new_mem_buf((void *)composite_data.data(), composite_data.size()); - X509 *c = PEM_read_bio_X509(chain_mbio, NULL, NULL, (void *)""); - while (c != NULL) { + X509 *c = PEM_read_bio_X509(chain_mbio, nullptr, nullptr, (void *)""); + while (c != nullptr) { cert_chain.push_back(c); - c = PEM_read_bio_X509(chain_mbio, NULL, NULL, (void *)""); + c = PEM_read_bio_X509(chain_mbio, nullptr, nullptr, (void *)""); } BIO_free(chain_mbio); @@ -810,7 +804,7 @@ add_signature(const Multifile::CertChain &cert_chain, EVP_PKEY *pkey) { return false; } - if (pkey == NULL) { + if (pkey == nullptr) { express_cat.info() << "No private key given.\n"; return false; @@ -831,7 +825,7 @@ add_signature(const Multifile::CertChain &cert_chain, EVP_PKEY *pkey) { for (ci = cert_chain.begin(); ci != cert_chain.end(); ++ci) { X509 *cert = (*ci)._cert; - int der_len = i2d_X509(cert, NULL); + int der_len = i2d_X509(cert, nullptr); unsigned char *der_buf = new unsigned char[der_len]; unsigned char *p = der_buf; i2d_X509(cert, &p); @@ -905,7 +899,7 @@ get_signature_subject_name(int n) const { nassertr(!cert_chain.empty(), string()); X509_NAME *xname = X509_get_subject_name(cert_chain[0]._cert); - if (xname != NULL) { + if (xname != nullptr) { // We use "print" to dump the output to a memory BIO. Is there an easier // way to extract the X509_NAME text? Curse these incomplete docs. BIO *mbio = BIO_new(BIO_s_mem()); @@ -949,15 +943,15 @@ get_signature_friendly_name(int n) const { // A complex OpenSSL interface to extract out the name in utf-8. X509_NAME *xname = X509_get_subject_name(cert_chain[0]._cert); - if (xname != NULL) { + if (xname != nullptr) { int pos = X509_NAME_get_index_by_NID(xname, nid, -1); if (pos != -1) { // We just get the first common name. I guess it's possible to have // more than one; not sure what that means in this context. X509_NAME_ENTRY *xentry = X509_NAME_get_entry(xname, pos); - if (xentry != NULL) { + if (xentry != nullptr) { ASN1_STRING *data = X509_NAME_ENTRY_get_data(xentry); - if (data != NULL) { + if (data != nullptr) { // We use "print" to dump the output to a memory BIO. Is there an // easier way to decode the ASN1_STRING? Curse these incomplete // docs. @@ -995,8 +989,8 @@ get_signature_public_key(int n) const { nassertr(!cert_chain.empty(), string()); EVP_PKEY *pkey = X509_get_pubkey(cert_chain[0]._cert); - if (pkey != NULL) { - int key_len = i2d_PublicKey(pkey, NULL); + if (pkey != nullptr) { + int key_len = i2d_PublicKey(pkey, nullptr); unsigned char *key_buf = new unsigned char[key_len]; unsigned char *p = key_buf; i2d_PublicKey(pkey, &p); @@ -1078,9 +1072,9 @@ validate_signature_certificate(int n) const { // Copy our CertChain structure into an X509 pointer and accompanying // STACK_OF(X509) pointer. X509 *x509 = chain[0]._cert; - STACK_OF(X509) *stack = NULL; + STACK_OF(X509) *stack = nullptr; if (chain.size() > 1) { - stack = sk_X509_new(NULL); + stack = sk_X509_new(nullptr); for (size_t n = 1; n < chain.size(); ++n) { sk_X509_push(stack, chain[n]._cert); } @@ -1148,7 +1142,7 @@ flush() { } } - nassertr(_write != (ostream *)NULL, false); + nassertr(_write != nullptr, false); // First, mark out all of the removed subfiles. PendingSubfiles::iterator pi; @@ -1207,14 +1201,14 @@ flush() { for (pi = _new_subfiles.begin(); pi != _new_subfiles.end(); ++pi) { Subfile *subfile = (*pi); - if (_read != (IStreamWrapper *)NULL) { + if (_read != nullptr) { _read->acquire(); _next_index = subfile->write_data(*_write, _read->get_istream(), _next_index, this); _read->release(); } else { - _next_index = subfile->write_data(*_write, NULL, _next_index, this); + _next_index = subfile->write_data(*_write, nullptr, _next_index, this); } nassertr(_next_index == _write->tellp(), false); @@ -1315,7 +1309,7 @@ repack() { } _removed_subfiles.clear(); _new_subfiles.clear(); - copy(_subfiles.begin(), _subfiles.end(), back_inserter(_new_subfiles)); + std::copy(_subfiles.begin(), _subfiles.end(), std::back_inserter(_new_subfiles)); _next_index = 0; _last_index = 0; _last_data_byte = 0; @@ -1467,7 +1461,7 @@ remove_subfile(int index) { _removed_subfiles.push_back(subfile); _subfiles.erase(_subfiles.begin() + index); - _timestamp = time(NULL); + _timestamp = time(nullptr); _timestamp_dirty = true; _needs_repack = true; @@ -1604,18 +1598,18 @@ get_subfile_internal_length(int index) const { */ istream *Multifile:: open_read_subfile(int index) { - nassertr(is_read_valid(), NULL); - nassertr(index >= 0 && index < (int)_subfiles.size(), NULL); + nassertr(is_read_valid(), nullptr); + nassertr(index >= 0 && index < (int)_subfiles.size(), nullptr); Subfile *subfile = _subfiles[index]; - if (subfile->_source != (istream *)NULL || + if (subfile->_source != nullptr || !subfile->_source_filename.empty()) { // The subfile has not yet been copied into the physical Multifile. Force // a flush operation to incorporate it. flush(); // That shouldn't change the subfile index or delete the subfile pointer. - nassertr(subfile == _subfiles[index], NULL); + nassertr(subfile == _subfiles[index], nullptr); } return open_read_subfile(subfile); @@ -1629,7 +1623,7 @@ open_read_subfile(int index) { */ void Multifile:: close_read_subfile(istream *stream) { - if (stream != (istream *)NULL) { + if (stream != nullptr) { // For some reason--compiler bug in gcc 3.2?--explicitly deleting the // stream pointer does not call the appropriate global delete function; // instead apparently calling the system delete function. So we call the @@ -1685,7 +1679,7 @@ extract_subfile_to(int index, ostream &out) { nassertr(index >= 0 && index < (int)_subfiles.size(), false); istream *in = open_read_subfile(index); - if (in == (istream *)NULL) { + if (in == nullptr) { return false; } @@ -1760,7 +1754,7 @@ compare_subfile(int index, const Filename &filename) { } istream *in1 = open_read_subfile(index); - if (in1 == (istream *)NULL) { + if (in1 == nullptr) { return false; } @@ -1882,7 +1876,7 @@ read_subfile(int index, string &result) { // We use a temporary pvector, because dynamic accumulation of a pvector // seems to be many times faster than that of a string, at least on the // Windows implementation of STL. - pvector pv; + vector_uchar pv; if (!read_subfile(index, pv)) { return false; } @@ -1898,7 +1892,7 @@ read_subfile(int index, string &result) { * Fills a pvector with the entire contents of the indicated subfile. */ bool Multifile:: -read_subfile(int index, pvector &result) { +read_subfile(int index, vector_uchar &result) { nassertr(is_read_valid(), false); nassertr(index >= 0 && index < (int)_subfiles.size(), false); result.clear(); @@ -1908,7 +1902,7 @@ read_subfile(int index, pvector &result) { nassertr(index >= 0 && index < (int)_subfiles.size(), false); Subfile *subfile = _subfiles[index]; - if (subfile->_source != (istream *)NULL || + if (subfile->_source != nullptr || !subfile->_source_filename.empty()) { // The subfile has not yet been copied into the physical Multifile. Force // a flush operation to incorporate it. @@ -1925,7 +1919,7 @@ read_subfile(int index, pvector &result) { // If the subfile is encrypted or compressed, we can't read it directly. // Fall back to the generic implementation. istream *in = open_read_subfile(index); - if (in == (istream *)NULL) { + if (in == nullptr) { return false; } @@ -1977,7 +1971,7 @@ read_subfile(int index, pvector &result) { */ streampos Multifile:: pad_to_streampos(streampos fpos) { - nassertr(_write != (ostream *)NULL, fpos); + nassertr(_write != nullptr, fpos); nassertr(_write->tellp() == fpos, fpos); streampos new_fpos = normalize_streampos(fpos); while (fpos < new_fpos) { @@ -2016,7 +2010,7 @@ add_new_subfile(Subfile *subfile, int compression_level) { _needs_repack = true; } - pair insert_result = _subfiles.insert(subfile); + std::pair insert_result = _subfiles.insert(subfile); if (!insert_result.second) { // Hmm, unable to insert. There must already be a subfile by that name. // Remove the old one. @@ -2048,12 +2042,12 @@ add_new_subfile(Subfile *subfile, int compression_level) { */ istream *Multifile:: open_read_subfile(Subfile *subfile) { - nassertr(subfile->_source == (istream *)NULL && - subfile->_source_filename.empty(), NULL); + nassertr(subfile->_source == nullptr && + subfile->_source_filename.empty(), nullptr); // Return an ISubStream object that references into the open Multifile // istream. - nassertr(subfile->_data_start != (streampos)0, NULL); + nassertr(subfile->_data_start != (streampos)0, nullptr); istream *stream = new ISubStream(_read, _offset + subfile->_data_start, _offset + subfile->_data_start + (streampos)subfile->_data_length); @@ -2063,7 +2057,7 @@ open_read_subfile(Subfile *subfile) { express_cat.error() << "OpenSSL not compiled in; cannot read encrypted multifiles.\n"; delete stream; - return NULL; + return nullptr; #else // HAVE_OPENSSL // The subfile is encrypted. So actually, return an IDecryptStream that // wraps around the ISubStream. @@ -2079,7 +2073,7 @@ open_read_subfile(Subfile *subfile) { express_cat.error() << "Unable to decrypt subfile " << subfile->_name << ".\n"; delete stream; - return NULL; + return nullptr; } #endif // HAVE_OPENSSL } @@ -2089,7 +2083,7 @@ open_read_subfile(Subfile *subfile) { express_cat.error() << "zlib not compiled in; cannot read compressed multifiles.\n"; delete stream; - return NULL; + return nullptr; #else // HAVE_ZLIB // Oops, the subfile is compressed. So actually, return an // IDecompressStream that wraps around the ISubStream. @@ -2101,7 +2095,7 @@ open_read_subfile(Subfile *subfile) { if (stream->fail()) { // Hmm, some inexplicable problem. delete stream; - return NULL; + return nullptr; } return stream; @@ -2170,7 +2164,7 @@ clear_subfiles() { */ bool Multifile:: read_index() { - nassertr(_read != (IStreamWrapper *)NULL, false); + nassertr(_read != nullptr, false); // We acquire the IStreamWrapper lock for the duration of this method. _read->acquire(); @@ -2350,7 +2344,7 @@ write_header() { _file_major_ver = _current_major_ver; _file_minor_ver = _current_minor_ver; - nassertr(_write != (ostream *)NULL, false); + nassertr(_write != nullptr, false); nassertr(_write->tellp() == (streampos)0, false); _write->write(_header_prefix.data(), _header_prefix.size()); _write->write(_header, _header_size); @@ -2399,7 +2393,7 @@ check_signatures() { // Extract the signature data and certificate separately. istream *stream = open_read_subfile(subfile); - nassertv(stream != NULL); + nassertv(stream != nullptr); StreamReader reader(*stream); size_t sig_size = reader.get_uint32(); vector_uchar sig_data = reader.extract_bytes(sig_size); @@ -2407,7 +2401,7 @@ check_signatures() { size_t num_certs = reader.get_uint32(); // Read the remaining buffer of certificate data. - pvector buffer; + vector_uchar buffer; bool success = VirtualFile::simple_read_file(stream, buffer); nassertv(success); close_read_subfile(stream); @@ -2415,7 +2409,7 @@ check_signatures() { // Now convert each of the certificates to an X509 object, and store it in // our CertChain. CertChain chain; - EVP_PKEY *pkey = NULL; + EVP_PKEY *pkey = nullptr; if (!buffer.empty()) { #if OPENSSL_VERSION_NUMBER >= 0x00908000L // Beginning in 0.9.8, d2i_X509() accepted a const unsigned char **. @@ -2426,13 +2420,13 @@ check_signatures() { #endif bp = (unsigned char *)&buffer[0]; bp_end = bp + buffer.size(); - X509 *x509 = d2i_X509(NULL, &bp, bp_end - bp); - while (num_certs > 0 && x509 != NULL) { + X509 *x509 = d2i_X509(nullptr, &bp, bp_end - bp); + while (num_certs > 0 && x509 != nullptr) { chain.push_back(CertRecord(x509)); --num_certs; - x509 = d2i_X509(NULL, &bp, bp_end - bp); + x509 = d2i_X509(nullptr, &bp, bp_end - bp); } - if (num_certs != 0 || x509 != NULL) { + if (num_certs != 0 || x509 != nullptr) { express_cat.warning() << "Extra data in signature record.\n"; } @@ -2442,11 +2436,11 @@ check_signatures() { pkey = X509_get_pubkey(chain[0]._cert); } - if (pkey != NULL) { + if (pkey != nullptr) { EVP_MD_CTX *md_ctx = EVP_MD_CTX_create(); EVP_VerifyInit(md_ctx, EVP_sha1()); - nassertv(_read != NULL); + nassertv(_read != nullptr); _read->acquire(); istream *read = _read->get_istream(); @@ -2539,7 +2533,7 @@ read_index(istream &read, streampos fpos, Multifile *multifile) { // And finally, get the rest of the name. char *name_buffer = (char *)PANDA_MALLOC_ARRAY(name_length); - nassertr(name_buffer != (char *)NULL, next_index); + nassertr(name_buffer != nullptr, next_index); for (size_t ni = 0; ni < name_length; ni++) { name_buffer[ni] = read.get() ^ 0xff; } @@ -2627,7 +2621,7 @@ write_data(ostream &write, istream *read, streampos fpos, istream *source = _source; pifstream source_file; - if (source == (istream *)NULL && !_source_filename.empty()) { + if (source == nullptr && !_source_filename.empty()) { // If we have a filename, open it up and read that. if (!_source_filename.open_read(source_file)) { // Unable to open the source file. @@ -2641,10 +2635,10 @@ write_data(ostream &write, istream *read, streampos fpos, } } - if (source == (istream *)NULL) { + if (source == nullptr) { // We don't have any source data. Perhaps we're reading from an already- // packed Subfile (e.g. during repack()). - if (read == (istream *)NULL) { + if (read == nullptr) { // No, we're just screwed. express_cat.info() << "No source for subfile " << _name << ".\n"; @@ -2717,10 +2711,10 @@ write_data(ostream &write, istream *read, streampos fpos, // In order to generate a signature, we need to have a valid read // pointer. - nassertr(read != NULL, fpos); + nassertr(read != nullptr, fpos); // And we also need to have a private key. - nassertr(_pkey != NULL, fpos); + nassertr(_pkey != nullptr, fpos); EVP_MD_CTX *md_ctx = EVP_MD_CTX_create(); EVP_SignInit(md_ctx, EVP_sha1()); @@ -2795,10 +2789,10 @@ write_data(ostream &write, istream *read, streampos fpos, _timestamp = _source_filename.get_timestamp(); } if (_timestamp == 0) { - _timestamp = time(NULL); + _timestamp = time(nullptr); } - _source = (istream *)NULL; + _source = nullptr; _source_filename = Filename(); source_file.close(); diff --git a/panda/src/express/multifile.h b/panda/src/express/multifile.h index d9f7217dfd..540bf434d2 100644 --- a/panda/src/express/multifile.h +++ b/panda/src/express/multifile.h @@ -34,22 +34,21 @@ typedef struct evp_pkey_st EVP_PKEY; /** * A file that contains a set of files. */ -class EXPCL_PANDAEXPRESS Multifile : public ReferenceCount { +class EXPCL_PANDA_EXPRESS Multifile : public ReferenceCount { PUBLISHED: Multifile(); + Multifile(const Multifile ©) = delete; ~Multifile(); -private: - Multifile(const Multifile ©); - void operator = (const Multifile ©); + Multifile &operator = (const Multifile ©) = delete; PUBLISHED: - BLOCKING bool open_read(const Filename &multifile_name, const streampos &offset = 0); - BLOCKING bool open_read(IStreamWrapper *multifile_stream, bool owns_pointer = false, const streampos &offset = 0); + BLOCKING bool open_read(const Filename &multifile_name, const std::streampos &offset = 0); + BLOCKING bool open_read(IStreamWrapper *multifile_stream, bool owns_pointer = false, const std::streampos &offset = 0); BLOCKING bool open_write(const Filename &multifile_name); - BLOCKING bool open_write(ostream *multifile_stream, bool owns_pointer = false); + BLOCKING bool open_write(std::ostream *multifile_stream, bool owns_pointer = false); BLOCKING bool open_read_write(const Filename &multifile_name); - BLOCKING bool open_read_write(iostream *multifile_stream, bool owns_pointer = false); + BLOCKING bool open_read_write(std::iostream *multifile_stream, bool owns_pointer = false); BLOCKING void close(); INLINE const Filename &get_multifile_name() const; @@ -69,37 +68,37 @@ PUBLISHED: INLINE void set_encryption_flag(bool flag); INLINE bool get_encryption_flag() const; - INLINE void set_encryption_password(const string &encryption_password); - INLINE const string &get_encryption_password() const; + INLINE void set_encryption_password(const std::string &encryption_password); + INLINE const std::string &get_encryption_password() const; - INLINE void set_encryption_algorithm(const string &encryption_algorithm); - INLINE const string &get_encryption_algorithm() const; + INLINE void set_encryption_algorithm(const std::string &encryption_algorithm); + INLINE const std::string &get_encryption_algorithm() const; INLINE void set_encryption_key_length(int encryption_key_length); INLINE int get_encryption_key_length() const; INLINE void set_encryption_iteration_count(int encryption_iteration_count); INLINE int get_encryption_iteration_count() const; - string add_subfile(const string &subfile_name, const Filename &filename, + std::string add_subfile(const std::string &subfile_name, const Filename &filename, int compression_level); - string add_subfile(const string &subfile_name, istream *subfile_data, + std::string add_subfile(const std::string &subfile_name, std::istream *subfile_data, int compression_level); - string update_subfile(const string &subfile_name, const Filename &filename, + std::string update_subfile(const std::string &subfile_name, const Filename &filename, int compression_level); #ifdef HAVE_OPENSSL bool add_signature(const Filename &certificate, const Filename &chain, const Filename &pkey, - const string &password = ""); + const std::string &password = ""); bool add_signature(const Filename &composite, - const string &password = ""); + const std::string &password = ""); int get_num_signatures() const; - string get_signature_subject_name(int n) const; - string get_signature_friendly_name(int n) const; - string get_signature_public_key(int n) const; - void print_signature_certificate(int n, ostream &out) const; - void write_signature_certificate(int n, ostream &out) const; + std::string get_signature_subject_name(int n) const; + std::string get_signature_friendly_name(int n) const; + std::string get_signature_public_key(int n) const; + void print_signature_certificate(int n, std::ostream &out) const; + void write_signature_certificate(int n, std::ostream &out) const; int validate_signature_certificate(int n) const; #endif // HAVE_OPENSSL @@ -108,13 +107,13 @@ PUBLISHED: BLOCKING bool repack(); int get_num_subfiles() const; - int find_subfile(const string &subfile_name) const; - bool has_directory(const string &subfile_name) const; + int find_subfile(const std::string &subfile_name) const; + bool has_directory(const std::string &subfile_name) const; bool scan_directory(vector_string &contents, - const string &subfile_name) const; + const std::string &subfile_name) const; void remove_subfile(int index); - INLINE bool remove_subfile(const string &subfile_name); - const string &get_subfile_name(int index) const; + INLINE bool remove_subfile(const std::string &subfile_name); + const std::string &get_subfile_name(int index) const; MAKE_SEQ(get_subfile_names, get_num_subfiles, get_subfile_name); size_t get_subfile_length(int index) const; time_t get_subfile_timestamp(int index) const; @@ -122,25 +121,25 @@ PUBLISHED: bool is_subfile_encrypted(int index) const; bool is_subfile_text(int index) const; - streampos get_index_end() const; - streampos get_subfile_internal_start(int index) const; + std::streampos get_index_end() const; + std::streampos get_subfile_internal_start(int index) const; size_t get_subfile_internal_length(int index) const; BLOCKING INLINE vector_uchar read_subfile(int index); - BLOCKING istream *open_read_subfile(int index); - BLOCKING static void close_read_subfile(istream *stream); + BLOCKING std::istream *open_read_subfile(int index); + BLOCKING static void close_read_subfile(std::istream *stream); BLOCKING bool extract_subfile(int index, const Filename &filename); - BLOCKING bool extract_subfile_to(int index, ostream &out); + BLOCKING bool extract_subfile_to(int index, std::ostream &out); BLOCKING bool compare_subfile(int index, const Filename &filename); - void output(ostream &out) const; - void ls(ostream &out = cout) const; + void output(std::ostream &out) const; + void ls(std::ostream &out = std::cout) const; - static INLINE string get_magic_number(); + static INLINE std::string get_magic_number(); MAKE_PROPERTY(magic_number, get_magic_number); - void set_header_prefix(const string &header_prefix); - INLINE const string &get_header_prefix() const; + void set_header_prefix(const std::string &header_prefix); + INLINE const std::string &get_header_prefix() const; public: #ifdef HAVE_OPENSSL @@ -159,8 +158,8 @@ public: const CertChain &get_signature(int n) const; #endif // HAVE_OPENSSL - bool read_subfile(int index, string &result); - bool read_subfile(int index, pvector &result); + bool read_subfile(int index, std::string &result); + bool read_subfile(int index, vector_uchar &result); private: enum SubfileFlags { @@ -177,28 +176,28 @@ private: public: INLINE Subfile(); INLINE bool operator < (const Subfile &other) const; - streampos read_index(istream &read, streampos fpos, + std::streampos read_index(std::istream &read, std::streampos fpos, Multifile *multfile); - streampos write_index(ostream &write, streampos fpos, + std::streampos write_index(std::ostream &write, std::streampos fpos, Multifile *multifile); - streampos write_data(ostream &write, istream *read, streampos fpos, + std::streampos write_data(std::ostream &write, std::istream *read, std::streampos fpos, Multifile *multifile); - void rewrite_index_data_start(ostream &write, Multifile *multifile); - void rewrite_index_flags(ostream &write); + void rewrite_index_data_start(std::ostream &write, Multifile *multifile); + void rewrite_index_flags(std::ostream &write); INLINE bool is_deleted() const; INLINE bool is_index_invalid() const; INLINE bool is_data_invalid() const; INLINE bool is_cert_special() const; - INLINE streampos get_last_byte_pos() const; + INLINE std::streampos get_last_byte_pos() const; - string _name; - streampos _index_start; + std::string _name; + std::streampos _index_start; size_t _index_length; - streampos _data_start; + std::streampos _data_start; size_t _data_length; size_t _uncompressed_length; time_t _timestamp; - istream *_source; + std::istream *_source; Filename _source_filename; int _flags; int _compression_level; // Not preserved on disk. @@ -207,14 +206,14 @@ private: #endif }; - INLINE streampos word_to_streampos(size_t word) const; - INLINE size_t streampos_to_word(streampos fpos) const; - INLINE streampos normalize_streampos(streampos fpos) const; - streampos pad_to_streampos(streampos fpos); + INLINE std::streampos word_to_streampos(size_t word) const; + INLINE size_t streampos_to_word(std::streampos fpos) const; + INLINE std::streampos normalize_streampos(std::streampos fpos) const; + std::streampos pad_to_streampos(std::streampos fpos); void add_new_subfile(Subfile *subfile, int compression_level); - istream *open_read_subfile(Subfile *subfile); - string standardize_subfile_name(const string &subfile_name) const; + std::istream *open_read_subfile(Subfile *subfile); + std::string standardize_subfile_name(const std::string &subfile_name) const; void clear_subfiles(); bool read_index(); @@ -236,13 +235,13 @@ private: Certificates _signatures; #endif - streampos _offset; + std::streampos _offset; IStreamWrapper *_read; - ostream *_write; + std::ostream *_write; bool _owns_stream; - streampos _next_index; - streampos _last_index; - streampos _last_data_byte; + std::streampos _next_index; + std::streampos _last_index; + std::streampos _last_data_byte; bool _needs_repack; time_t _timestamp; @@ -252,8 +251,8 @@ private: size_t _new_scale_factor; bool _encryption_flag; - string _encryption_password; - string _encryption_algorithm; + std::string _encryption_password; + std::string _encryption_algorithm; int _encryption_key_length; int _encryption_iteration_count; @@ -263,7 +262,7 @@ private: pfstream _read_write_file; StreamWrapper _read_write_filew; Filename _multifile_name; - string _header_prefix; + std::string _header_prefix; int _file_major_ver; int _file_minor_ver; diff --git a/panda/src/express/namable.I b/panda/src/express/namable.I index 75aa846087..d7060ce1c9 100644 --- a/panda/src/express/namable.I +++ b/panda/src/express/namable.I @@ -15,7 +15,7 @@ * */ INLINE Namable:: -Namable(const string &initial_name) : +Namable(const std::string &initial_name) : _name(initial_name) { } @@ -24,7 +24,7 @@ Namable(const string &initial_name) : * */ INLINE void Namable:: -set_name(const string &name) { +set_name(const std::string &name) { _name = name; } @@ -48,7 +48,7 @@ has_name() const { /** * */ -INLINE const string &Namable:: +INLINE const std::string &Namable:: get_name() const { return _name; } @@ -58,12 +58,12 @@ get_name() const { * stream; most Namable derivatives will probably redefine this. */ INLINE void Namable:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_name(); } -INLINE ostream &operator << (ostream &out, const Namable &n) { +INLINE std::ostream &operator << (std::ostream &out, const Namable &n) { n.output(out); return out; } diff --git a/panda/src/express/namable.h b/panda/src/express/namable.h index 19a712d9d3..eb8c0c6e79 100644 --- a/panda/src/express/namable.h +++ b/panda/src/express/namable.h @@ -23,22 +23,22 @@ * A base class for all things which can have a name. The name is either * empty or nonempty, but it is never NULL. */ -class EXPCL_PANDAEXPRESS Namable : public MemoryBase { +class EXPCL_PANDA_EXPRESS Namable : public MemoryBase { PUBLISHED: - INLINE explicit Namable(const string &initial_name = ""); + INLINE explicit Namable(const std::string &initial_name = ""); - INLINE void set_name(const string &name); + INLINE void set_name(const std::string &name); INLINE void clear_name(); INLINE bool has_name() const; - INLINE const string &get_name() const; + INLINE const std::string &get_name() const; MAKE_PROPERTY(name, get_name, set_name); // In the absence of any definition to the contrary, outputting a Namable // will write out its name. - INLINE void output(ostream &out) const; + INLINE void output(std::ostream &out) const; private: - string _name; + std::string _name; public: static TypeHandle get_class_type() { @@ -52,7 +52,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const Namable &n); +INLINE std::ostream &operator << (std::ostream &out, const Namable &n); /** * An STL function object for sorting an array of pointers to Namables into diff --git a/panda/src/express/nodePointerTo.I b/panda/src/express/nodePointerTo.I index 5485adcaaa..6d5d3bd669 100644 --- a/panda/src/express/nodePointerTo.I +++ b/panda/src/express/nodePointerTo.I @@ -33,14 +33,13 @@ NodePointerTo(const NodePointerTo ©) : } #endif // CPPPARSER -#ifdef USE_MOVE_SEMANTICS #ifndef CPPPARSER /** * */ template INLINE NodePointerTo:: -NodePointerTo(NodePointerTo &&from) NOEXCEPT : +NodePointerTo(NodePointerTo &&from) noexcept : NodePointerToBase((NodePointerToBase &&)from) { } @@ -52,19 +51,18 @@ NodePointerTo(NodePointerTo &&from) NOEXCEPT : */ template INLINE NodePointerTo &NodePointerTo:: -operator = (NodePointerTo &&from) NOEXCEPT { - this->reassign(move(from)); +operator = (NodePointerTo &&from) noexcept { + this->reassign(std::move(from)); return *this; } #endif // CPPPARSER -#endif // USE_MOVE_SEMANTICS #ifndef CPPPARSER /** * */ template -INLINE TYPENAME NodePointerTo::To &NodePointerTo:: +INLINE typename NodePointerTo::To &NodePointerTo:: operator *() const { return *((To *)(this->_void_ptr)); } @@ -75,7 +73,7 @@ operator *() const { * */ template -INLINE TYPENAME NodePointerTo::To *NodePointerTo:: +INLINE typename NodePointerTo::To *NodePointerTo:: operator -> () const { return (To *)(this->_void_ptr); } @@ -101,7 +99,7 @@ operator T *() const { * around compiler problems, particularly for implicit upcasts. */ template -INLINE TYPENAME NodePointerTo::To *NodePointerTo:: +INLINE typename NodePointerTo::To *NodePointerTo:: p() const { return (To *)(this->_void_ptr); } @@ -137,8 +135,8 @@ operator = (const NodePointerTo ©) { */ template INLINE NodeConstPointerTo:: -NodeConstPointerTo(const TYPENAME NodeConstPointerTo::To *ptr) : - NodePointerToBase((TYPENAME NodeConstPointerTo::To *)ptr) +NodeConstPointerTo(const typename NodeConstPointerTo::To *ptr) : + NodePointerToBase((typename NodeConstPointerTo::To *)ptr) { } #endif // CPPPARSER @@ -167,14 +165,13 @@ NodeConstPointerTo(const NodeConstPointerTo ©) : } #endif // CPPPARSER -#ifdef USE_MOVE_SEMANTICS #ifndef CPPPARSER /** * */ template INLINE NodeConstPointerTo:: -NodeConstPointerTo(NodePointerTo &&from) NOEXCEPT : +NodeConstPointerTo(NodePointerTo &&from) noexcept : NodePointerToBase((NodePointerToBase &&)from) { } @@ -186,7 +183,7 @@ NodeConstPointerTo(NodePointerTo &&from) NOEXCEPT : */ template INLINE NodeConstPointerTo:: -NodeConstPointerTo(NodeConstPointerTo &&from) NOEXCEPT : +NodeConstPointerTo(NodeConstPointerTo &&from) noexcept : NodePointerToBase((NodePointerToBase &&)from) { } @@ -198,8 +195,8 @@ NodeConstPointerTo(NodeConstPointerTo &&from) NOEXCEPT : */ template INLINE NodeConstPointerTo &NodeConstPointerTo:: -operator = (NodePointerTo &&from) NOEXCEPT { - this->reassign(move(from)); +operator = (NodePointerTo &&from) noexcept { + this->reassign(std::move(from)); return *this; } #endif // CPPPARSER @@ -210,19 +207,18 @@ operator = (NodePointerTo &&from) NOEXCEPT { */ template INLINE NodeConstPointerTo &NodeConstPointerTo:: -operator = (NodeConstPointerTo &&from) NOEXCEPT { - this->reassign(move(from)); +operator = (NodeConstPointerTo &&from) noexcept { + this->reassign(std::move(from)); return *this; } #endif // CPPPARSER -#endif // USE_MOVE_SEMANTICS #ifndef CPPPARSER /** * */ template -INLINE const TYPENAME NodeConstPointerTo::To &NodeConstPointerTo:: +INLINE const typename NodeConstPointerTo::To &NodeConstPointerTo:: operator *() const { return *((To *)(this->_void_ptr)); } @@ -233,7 +229,7 @@ operator *() const { * */ template -INLINE const TYPENAME NodeConstPointerTo::To *NodeConstPointerTo:: +INLINE const typename NodeConstPointerTo::To *NodeConstPointerTo:: operator -> () const { return (To *)(this->_void_ptr); } @@ -260,7 +256,7 @@ operator const T * () const { * work around compiler problems, particularly for implicit upcasts. */ template -INLINE const TYPENAME NodeConstPointerTo::To *NodeConstPointerTo:: +INLINE const typename NodeConstPointerTo::To *NodeConstPointerTo:: p() const { return (To *)(this->_void_ptr); } diff --git a/panda/src/express/nodePointerTo.h b/panda/src/express/nodePointerTo.h index ca9832d424..7b2c189253 100644 --- a/panda/src/express/nodePointerTo.h +++ b/panda/src/express/nodePointerTo.h @@ -28,14 +28,12 @@ public: // By hiding this template from interrogate, we improve compile-time speed // and memory utilization. #ifndef CPPPARSER - typedef TYPENAME NodePointerToBase::To To; - INLINE NodePointerTo(To *ptr = (To *)NULL); + typedef typename NodePointerToBase::To To; + INLINE NodePointerTo(To *ptr = nullptr); INLINE NodePointerTo(const NodePointerTo ©); + INLINE NodePointerTo(NodePointerTo &&from) noexcept; -#ifdef USE_MOVE_SEMANTICS - INLINE NodePointerTo(NodePointerTo &&from) NOEXCEPT; - INLINE NodePointerTo &operator = (NodePointerTo &&from) NOEXCEPT; -#endif + INLINE NodePointerTo &operator = (NodePointerTo &&from) noexcept; INLINE To &operator *() const; INLINE To *operator -> () const; @@ -61,17 +59,15 @@ public: // By hiding this template from interrogate, we improve compile-time speed // and memory utilization. #ifndef CPPPARSER - typedef TYPENAME NodePointerToBase::To To; - INLINE NodeConstPointerTo(const To *ptr = (const To *)NULL); + typedef typename NodePointerToBase::To To; + INLINE NodeConstPointerTo(const To *ptr = nullptr); INLINE NodeConstPointerTo(const NodePointerTo ©); INLINE NodeConstPointerTo(const NodeConstPointerTo ©); + INLINE NodeConstPointerTo(NodePointerTo &&from) noexcept; + INLINE NodeConstPointerTo(NodeConstPointerTo &&from) noexcept; -#ifdef USE_MOVE_SEMANTICS - INLINE NodeConstPointerTo(NodePointerTo &&from) NOEXCEPT; - INLINE NodeConstPointerTo(NodeConstPointerTo &&from) NOEXCEPT; - INLINE NodeConstPointerTo &operator = (NodePointerTo &&from) NOEXCEPT; - INLINE NodeConstPointerTo &operator = (NodeConstPointerTo &&from) NOEXCEPT; -#endif + INLINE NodeConstPointerTo &operator = (NodePointerTo &&from) noexcept; + INLINE NodeConstPointerTo &operator = (NodeConstPointerTo &&from) noexcept; INLINE const To &operator *() const; INLINE const To *operator -> () const; @@ -86,12 +82,12 @@ public: }; template -void swap(NodePointerTo &one, NodePointerTo &two) NOEXCEPT { +void swap(NodePointerTo &one, NodePointerTo &two) noexcept { one.swap(two); } template -void swap(NodeConstPointerTo &one, NodeConstPointerTo &two) NOEXCEPT { +void swap(NodeConstPointerTo &one, NodeConstPointerTo &two) noexcept { one.swap(two); } diff --git a/panda/src/express/nodePointerToBase.I b/panda/src/express/nodePointerToBase.I index 18f04def9a..48a7fe3fff 100644 --- a/panda/src/express/nodePointerToBase.I +++ b/panda/src/express/nodePointerToBase.I @@ -35,18 +35,17 @@ NodePointerToBase(const NodePointerToBase ©) { template INLINE NodePointerToBase:: ~NodePointerToBase() { - reassign((To *)NULL); + reassign(nullptr); } -#ifdef USE_MOVE_SEMANTICS /** * */ template INLINE NodePointerToBase:: -NodePointerToBase(NodePointerToBase &&from) NOEXCEPT { +NodePointerToBase(NodePointerToBase &&from) noexcept { _void_ptr = from._void_ptr; - from._void_ptr = (void *)NULL; + from._void_ptr = nullptr; } /** @@ -57,18 +56,17 @@ NodePointerToBase(NodePointerToBase &&from) NOEXCEPT { */ template INLINE void NodePointerToBase:: -reassign(NodePointerToBase &&from) NOEXCEPT { +reassign(NodePointerToBase &&from) noexcept { To *old_ptr = (To *)this->_void_ptr; this->_void_ptr = from._void_ptr; - from._void_ptr = NULL; + from._void_ptr = nullptr; // Now delete the old pointer. - if (old_ptr != (To *)NULL) { + if (old_ptr != nullptr) { node_unref_delete(old_ptr); } } -#endif // USE_MOVE_SEMANTICS /** * This is the main work of the NodePointerTo family. When the pointer is @@ -85,7 +83,7 @@ reassign(To *ptr) { To *old_ptr = (To *)_void_ptr; _void_ptr = (void *)ptr; - if (ptr != (To *)NULL) { + if (ptr != nullptr) { ptr->node_ref(); #ifdef DO_MEMORY_USAGE if (MemoryUsage::get_track_memory_usage()) { @@ -104,7 +102,7 @@ reassign(To *ptr) { } // Now delete the old pointer. - if (old_ptr != (To *)NULL) { + if (old_ptr != nullptr) { node_unref_delete(old_ptr); } } @@ -127,7 +125,7 @@ reassign(const NodePointerToBase ©) { template INLINE void NodePointerToBase:: clear() { - reassign((To *)NULL); + reassign(nullptr); } /** @@ -136,9 +134,9 @@ clear() { */ template INLINE void NodePointerToBase:: -output(ostream &out) const { +output(std::ostream &out) const { out << _void_ptr; - if (_void_ptr != (void *)NULL) { + if (_void_ptr != nullptr) { out << ":" << ((To *)_void_ptr)->get_node_ref_count() << "/" << ((To *)_void_ptr)->get_ref_count(); } diff --git a/panda/src/express/nodePointerToBase.h b/panda/src/express/nodePointerToBase.h index e7bb9ad526..d4ddd7caad 100644 --- a/panda/src/express/nodePointerToBase.h +++ b/panda/src/express/nodePointerToBase.h @@ -36,11 +36,9 @@ protected: INLINE NodePointerToBase(To *ptr); INLINE NodePointerToBase(const NodePointerToBase ©); INLINE ~NodePointerToBase(); + INLINE NodePointerToBase(NodePointerToBase &&from) noexcept; -#ifdef USE_MOVE_SEMANTICS - INLINE NodePointerToBase(NodePointerToBase &&from) NOEXCEPT; - INLINE void reassign(NodePointerToBase &&from) NOEXCEPT; -#endif + INLINE void reassign(NodePointerToBase &&from) noexcept; void reassign(To *ptr); INLINE void reassign(const NodePointerToBase ©); @@ -51,11 +49,11 @@ protected: PUBLISHED: INLINE void clear(); - void output(ostream &out) const; + void output(std::ostream &out) const; }; template -INLINE ostream &operator <<(ostream &out, const NodePointerToBase &pointer) { +INLINE std::ostream &operator <<(std::ostream &out, const NodePointerToBase &pointer) { pointer.output(out); return out; } diff --git a/panda/src/express/nodeReferenceCount.I b/panda/src/express/nodeReferenceCount.I index 4273f0b78c..d87bc982d8 100644 --- a/panda/src/express/nodeReferenceCount.I +++ b/panda/src/express/nodeReferenceCount.I @@ -52,8 +52,6 @@ NodeReferenceCount(const NodeReferenceCount ©) : ReferenceCount(copy) { */ INLINE void NodeReferenceCount:: operator = (const NodeReferenceCount ©) { - nassertv(this != NULL); - // If this assertion fails, our own pointer was recently deleted. Possibly // you used a real pointer instead of a PointerTo at some point, and the // object was deleted when the PointerTo went out of scope. Maybe you tried @@ -74,8 +72,6 @@ operator = (const NodeReferenceCount ©) { */ INLINE NodeReferenceCount:: ~NodeReferenceCount() { - nassertv(this != NULL); - // If this assertion fails, we're trying to delete an object that was just // deleted. Possibly you used a real pointer instead of a PointerTo at some // point, and the object was deleted when the PointerTo went out of scope. @@ -219,9 +215,9 @@ void NodeRefCountObj:: init_type() { #if defined(HAVE_RTTI) && !defined(__EDG__) // If we have RTTI, we can determine the name of the base type. - string base_name = typeid(Base).name(); + std::string base_name = typeid(Base).name(); #else - string base_name = "unknown"; + std::string base_name = "unknown"; #endif TypeHandle base_type = register_dynamic_type(base_name); diff --git a/panda/src/express/nodeReferenceCount.cxx b/panda/src/express/nodeReferenceCount.cxx index 05c9b6d63f..f965f240a4 100644 --- a/panda/src/express/nodeReferenceCount.cxx +++ b/panda/src/express/nodeReferenceCount.cxx @@ -21,8 +21,6 @@ TypeHandle NodeReferenceCount::_type_handle; */ bool NodeReferenceCount:: do_test_ref_count_integrity() const { - nassertr(this != NULL, false); - // If this assertion fails, we're trying to delete an object that was just // deleted. Possibly you used a real pointer instead of a PointerTo at some // point, and the object was deleted when the PointerTo went out of scope. diff --git a/panda/src/express/nodeReferenceCount.h b/panda/src/express/nodeReferenceCount.h index 2312508f1b..0ece11b90a 100644 --- a/panda/src/express/nodeReferenceCount.h +++ b/panda/src/express/nodeReferenceCount.h @@ -30,7 +30,7 @@ * See also CachedTypedWritableReferenceCount, which is similar in principle, * as well as NodeCachedReferenceCount, which combines both of these. */ -class EXPCL_PANDAEXPRESS NodeReferenceCount : public ReferenceCount { +class EXPCL_PANDA_EXPRESS NodeReferenceCount : public ReferenceCount { protected: INLINE NodeReferenceCount(); INLINE NodeReferenceCount(const NodeReferenceCount ©); diff --git a/panda/src/express/openSSLWrapper.I b/panda/src/express/openSSLWrapper.I index 3d5cf81999..a8b8e396a6 100644 --- a/panda/src/express/openSSLWrapper.I +++ b/panda/src/express/openSSLWrapper.I @@ -21,7 +21,7 @@ * with certificates received from an untrusted source. */ INLINE int OpenSSLWrapper:: -load_certificates_from_pem_ram(const string &data) { +load_certificates_from_pem_ram(const std::string &data) { return load_certificates_from_pem_ram(data.data(), data.size()); } @@ -35,6 +35,6 @@ load_certificates_from_pem_ram(const string &data) { * with certificates received from an untrusted source. */ INLINE int OpenSSLWrapper:: -load_certificates_from_der_ram(const string &data) { +load_certificates_from_der_ram(const std::string &data) { return load_certificates_from_der_ram(data.data(), data.size()); } diff --git a/panda/src/express/openSSLWrapper.cxx b/panda/src/express/openSSLWrapper.cxx index 6492bb1596..d71818e130 100644 --- a/panda/src/express/openSSLWrapper.cxx +++ b/panda/src/express/openSSLWrapper.cxx @@ -18,7 +18,7 @@ #include "virtualFileSystem.h" #include "ca_bundle_data_src.c" -OpenSSLWrapper *OpenSSLWrapper::_global_ptr = NULL; +OpenSSLWrapper *OpenSSLWrapper::_global_ptr = nullptr; /** * @@ -63,7 +63,7 @@ OpenSSLWrapper() { int num_certs = ssl_certificates.get_num_unique_values(); for (int ci = 0; ci < num_certs; ci++) { - string cert_file = ssl_certificates.get_unique_value(ci); + std::string cert_file = ssl_certificates.get_unique_value(ci); Filename filename = Filename::expand_from(cert_file); load_certificates(filename); } @@ -108,7 +108,7 @@ load_certificates(const Filename &filename) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); // First, read the complete file into memory. - string data; + std::string data; if (!vfs->read_file(filename, data, true)) { // Could not find or read file. express_cat.info() @@ -154,7 +154,7 @@ load_certificates_from_pem_ram(const char *data, size_t data_size) { // We have to be sure and clear the OpenSSL error state before we call this // function, or it will get confused. ERR_clear_error(); - inf = PEM_X509_INFO_read_bio(mbio, NULL, NULL, NULL); + inf = PEM_X509_INFO_read_bio(mbio, nullptr, nullptr, nullptr); BIO_free(mbio); if (!inf) { @@ -257,8 +257,8 @@ load_certificates_from_der_ram(const char *data, size_t data_size) { bp = (unsigned char *)data; bp_end = bp + data_size; while (bp < bp_end) { - X509 *x509 = d2i_X509(NULL, &bp, bp_end - bp); - if (x509 == NULL) { + X509 *x509 = d2i_X509(nullptr, &bp, bp_end - bp); + if (x509 == nullptr) { notify_ssl_errors(); break; } @@ -350,7 +350,7 @@ notify_debug_ssl_errors() { */ OpenSSLWrapper *OpenSSLWrapper:: get_global_ptr() { - if (_global_ptr == NULL) { + if (_global_ptr == nullptr) { _global_ptr = new OpenSSLWrapper; } return _global_ptr; diff --git a/panda/src/express/openSSLWrapper.h b/panda/src/express/openSSLWrapper.h index 306039e1c0..1be8eabb2f 100644 --- a/panda/src/express/openSSLWrapper.h +++ b/panda/src/express/openSSLWrapper.h @@ -43,7 +43,7 @@ * the library is properly initialized in the application, and to provide some * hooks into global OpenSSL context data. */ -class EXPCL_PANDAEXPRESS OpenSSLWrapper { +class EXPCL_PANDA_EXPRESS OpenSSLWrapper { private: OpenSSLWrapper(); ~OpenSSLWrapper(); @@ -54,8 +54,8 @@ PUBLISHED: int load_certificates_from_pem_ram(const char *data, size_t data_size); int load_certificates_from_der_ram(const char *data, size_t data_size); - INLINE int load_certificates_from_pem_ram(const string &data); - INLINE int load_certificates_from_der_ram(const string &data); + INLINE int load_certificates_from_pem_ram(const std::string &data); + INLINE int load_certificates_from_der_ram(const std::string &data); X509_STORE *get_x509_store(); diff --git a/panda/src/express/ordered_vector.I b/panda/src/express/ordered_vector.I index 287998b85c..d55a0b98b6 100644 --- a/panda/src/express/ordered_vector.I +++ b/panda/src/express/ordered_vector.I @@ -37,7 +37,7 @@ ordered_vector(const Compare &compare, TypeHandle type_handle) : * Returns the iterator that marks the first element in the ordered vector. */ template -INLINE TYPENAME ordered_vector::ITERATOR ordered_vector:: +INLINE typename ordered_vector::ITERATOR ordered_vector:: begin() { return _vector.begin(); } @@ -46,7 +46,7 @@ begin() { * Returns the iterator that marks the end of the ordered vector. */ template -INLINE TYPENAME ordered_vector::ITERATOR ordered_vector:: +INLINE typename ordered_vector::ITERATOR ordered_vector:: end() { return _vector.end(); } @@ -56,7 +56,7 @@ end() { * when viewed in reverse order. */ template -INLINE TYPENAME ordered_vector::REVERSE_ITERATOR ordered_vector:: +INLINE typename ordered_vector::REVERSE_ITERATOR ordered_vector:: rbegin() { return _vector.rbegin(); } @@ -66,7 +66,7 @@ rbegin() { * in reverse order. */ template -INLINE TYPENAME ordered_vector::REVERSE_ITERATOR ordered_vector:: +INLINE typename ordered_vector::REVERSE_ITERATOR ordered_vector:: rend() { return _vector.rend(); } @@ -75,7 +75,7 @@ rend() { * Returns the iterator that marks the first element in the ordered vector. */ template -INLINE TYPENAME ordered_vector::CONST_ITERATOR ordered_vector:: +INLINE typename ordered_vector::CONST_ITERATOR ordered_vector:: begin() const { return _vector.begin(); } @@ -84,7 +84,7 @@ begin() const { * Returns the iterator that marks the end of the ordered vector. */ template -INLINE TYPENAME ordered_vector::CONST_ITERATOR ordered_vector:: +INLINE typename ordered_vector::CONST_ITERATOR ordered_vector:: end() const { return _vector.end(); } @@ -94,7 +94,7 @@ end() const { * when viewed in reverse order. */ template -INLINE TYPENAME ordered_vector::CONST_REVERSE_ITERATOR ordered_vector:: +INLINE typename ordered_vector::CONST_REVERSE_ITERATOR ordered_vector:: rbegin() const { return _vector.rbegin(); } @@ -104,7 +104,7 @@ rbegin() const { * in reverse order. */ template -INLINE TYPENAME ordered_vector::CONST_REVERSE_ITERATOR ordered_vector:: +INLINE typename ordered_vector::CONST_REVERSE_ITERATOR ordered_vector:: rend() const { return _vector.rend(); } @@ -113,7 +113,7 @@ rend() const { * Returns the iterator that marks the first element in the ordered vector. */ template -INLINE TYPENAME ordered_vector::CONST_ITERATOR ordered_vector:: +INLINE typename ordered_vector::CONST_ITERATOR ordered_vector:: cbegin() const { return _vector.begin(); } @@ -122,7 +122,7 @@ cbegin() const { * Returns the iterator that marks the end of the ordered vector. */ template -INLINE TYPENAME ordered_vector::CONST_ITERATOR ordered_vector:: +INLINE typename ordered_vector::CONST_ITERATOR ordered_vector:: cend() const { return _vector.end(); } @@ -132,7 +132,7 @@ cend() const { * when viewed in reverse order. */ template -INLINE TYPENAME ordered_vector::CONST_REVERSE_ITERATOR ordered_vector:: +INLINE typename ordered_vector::CONST_REVERSE_ITERATOR ordered_vector:: crbegin() const { return _vector.rbegin(); } @@ -142,7 +142,7 @@ crbegin() const { * in reverse order. */ template -INLINE TYPENAME ordered_vector::CONST_REVERSE_ITERATOR ordered_vector:: +INLINE typename ordered_vector::CONST_REVERSE_ITERATOR ordered_vector:: crend() const { return _vector.rend(); } @@ -151,8 +151,8 @@ crend() const { * Returns the nth element. */ template -INLINE TYPENAME ordered_vector::REFERENCE ordered_vector:: -operator [] (TYPENAME ordered_vector::SIZE_TYPE n) { +INLINE typename ordered_vector::REFERENCE ordered_vector:: +operator [] (typename ordered_vector::SIZE_TYPE n) { return _vector[n]; } @@ -160,8 +160,8 @@ operator [] (TYPENAME ordered_vector::SIZE_TYPE n) { * Returns the nth element. */ template -INLINE TYPENAME ordered_vector::CONST_REFERENCE ordered_vector:: -operator [] (TYPENAME ordered_vector::SIZE_TYPE n) const { +INLINE typename ordered_vector::CONST_REFERENCE ordered_vector:: +operator [] (typename ordered_vector::SIZE_TYPE n) const { return _vector[n]; } @@ -169,7 +169,7 @@ operator [] (TYPENAME ordered_vector::SIZE_TYPE n) const { * Returns a reference to the first element. */ template -INLINE TYPENAME ordered_vector::REFERENCE ordered_vector:: +INLINE typename ordered_vector::REFERENCE ordered_vector:: front() { #ifdef _DEBUG assert(!_vector.empty()); @@ -181,7 +181,7 @@ front() { * Returns a const reference to the first element. */ template -INLINE TYPENAME ordered_vector::CONST_REFERENCE ordered_vector:: +INLINE typename ordered_vector::CONST_REFERENCE ordered_vector:: front() const { #ifdef _DEBUG assert(!_vector.empty()); @@ -193,7 +193,7 @@ front() const { * Returns a reference to the first element. */ template -INLINE TYPENAME ordered_vector::REFERENCE ordered_vector:: +INLINE typename ordered_vector::REFERENCE ordered_vector:: back() { #ifdef _DEBUG assert(!_vector.empty()); @@ -205,7 +205,7 @@ back() { * Returns a const reference to the last element. */ template -INLINE TYPENAME ordered_vector::CONST_REFERENCE ordered_vector:: +INLINE typename ordered_vector::CONST_REFERENCE ordered_vector:: back() const { #ifdef _DEBUG assert(!_vector.empty()); @@ -217,7 +217,7 @@ back() const { * Returns the number of elements in the ordered vector. */ template -INLINE TYPENAME ordered_vector::SIZE_TYPE ordered_vector:: +INLINE typename ordered_vector::SIZE_TYPE ordered_vector:: size() const { return _vector.size(); } @@ -227,7 +227,7 @@ size() const { * ordered vector. */ template -INLINE TYPENAME ordered_vector::SIZE_TYPE ordered_vector:: +INLINE typename ordered_vector::SIZE_TYPE ordered_vector:: max_size() const { return _vector.max_size(); } @@ -312,25 +312,25 @@ operator >= (const ordered_vector &other) const { * componet is true if the insert operation has taken place. */ template -INLINE pair::ITERATOR, bool> ordered_vector:: -insert_unique(const TYPENAME ordered_vector::VALUE_TYPE &key) { +INLINE std::pair::ITERATOR, bool> ordered_vector:: +insert_unique(const typename ordered_vector::VALUE_TYPE &key) { TAU_PROFILE("ordered_vector::insert_unique(const value_type &)", " ", TAU_USER); ITERATOR position = find_insert_position(begin(), end(), key); #ifdef NDEBUG - pair bogus_result(end(), false); + std::pair bogus_result(end(), false); nassertr(position >= begin() && position <= end(), bogus_result); #endif // If there's already an equivalent key in the vector, it's at *(position - // 1). if (position != begin() && !_compare(*(position - 1), key)) { - pair result(position - 1, false); + std::pair result(position - 1, false); nassertr(!_compare(key, *(position - 1)), result); return result; } ITERATOR result = _vector.insert(position, key); - return pair(result, true); + return std::pair(result, true); } /** @@ -341,8 +341,8 @@ insert_unique(const TYPENAME ordered_vector::VALUE_TYPE &k * The return value is the iterator referencing the new element. */ template -INLINE TYPENAME ordered_vector::ITERATOR ordered_vector:: -insert_nonunique(const TYPENAME ordered_vector::VALUE_TYPE &key) { +INLINE typename ordered_vector::ITERATOR ordered_vector:: +insert_nonunique(const typename ordered_vector::VALUE_TYPE &key) { TAU_PROFILE("ordered_vector::insert_nonunique(const value_type &)", " ", TAU_USER); ITERATOR position = find_insert_position(begin(), end(), key); nassertr(position >= begin() && position <= end(), end()); @@ -358,9 +358,9 @@ insert_nonunique(const TYPENAME ordered_vector::VALUE_TYPE * sorting position; no checks are made. */ template -INLINE TYPENAME ordered_vector::ITERATOR ordered_vector:: -insert_unverified(TYPENAME ordered_vector::ITERATOR position, - const TYPENAME ordered_vector::VALUE_TYPE &key) { +INLINE typename ordered_vector::ITERATOR ordered_vector:: +insert_unverified(typename ordered_vector::ITERATOR position, + const typename ordered_vector::VALUE_TYPE &key) { TAU_PROFILE("ordered_vector::insert_unverified(iterator, const value_type &)", " ", TAU_USER); ITERATOR result = _vector.insert(position, key); return result; @@ -371,8 +371,8 @@ insert_unverified(TYPENAME ordered_vector::ITERATOR positi * sequential iterator. */ template -INLINE TYPENAME ordered_vector::ITERATOR ordered_vector:: -erase(TYPENAME ordered_vector::ITERATOR position) { +INLINE typename ordered_vector::ITERATOR ordered_vector:: +erase(typename ordered_vector::ITERATOR position) { TAU_PROFILE("ordered_vector::erase(iterator)", " ", TAU_USER); SIZE_TYPE count = position - begin(); _vector.erase(position); @@ -384,10 +384,10 @@ erase(TYPENAME ordered_vector::ITERATOR position) { * elements removed. */ template -INLINE TYPENAME ordered_vector::SIZE_TYPE ordered_vector:: -erase(const TYPENAME ordered_vector::KEY_TYPE &key) { +INLINE typename ordered_vector::SIZE_TYPE ordered_vector:: +erase(const typename ordered_vector::KEY_TYPE &key) { TAU_PROFILE("ordered_vector::erase(const key_type &)", " ", TAU_USER); - pair result = equal_range(key); + std::pair result = equal_range(key); SIZE_TYPE count = result.second - result.first; erase(result.first, result.second); return count; @@ -398,8 +398,8 @@ erase(const TYPENAME ordered_vector::KEY_TYPE &key) { */ template INLINE void ordered_vector:: -erase(TYPENAME ordered_vector::ITERATOR first, - TYPENAME ordered_vector::ITERATOR last) { +erase(typename ordered_vector::ITERATOR first, + typename ordered_vector::ITERATOR last) { TAU_PROFILE("ordered_vector::erase(iterator, iterator)", " ", TAU_USER); _vector.erase(first, last); } @@ -420,8 +420,8 @@ clear() { * matching the key, the particular iterator returned is not defined. */ template -INLINE TYPENAME ordered_vector::ITERATOR ordered_vector:: -find(const TYPENAME ordered_vector::KEY_TYPE &key) { +INLINE typename ordered_vector::ITERATOR ordered_vector:: +find(const typename ordered_vector::KEY_TYPE &key) { TAU_PROFILE("ordered_vector::find(const key_type &)", " ", TAU_USER); return nci(r_find(begin(), end(), end(), key)); } @@ -432,8 +432,8 @@ find(const TYPENAME ordered_vector::KEY_TYPE &key) { * matching the key, the particular iterator returned is not defined. */ template -INLINE TYPENAME ordered_vector::CONST_ITERATOR ordered_vector:: -find(const TYPENAME ordered_vector::KEY_TYPE &key) const { +INLINE typename ordered_vector::CONST_ITERATOR ordered_vector:: +find(const typename ordered_vector::KEY_TYPE &key) const { TAU_PROFILE("ordered_vector::find(const key_type &)", " ", TAU_USER); return r_find(begin(), end(), end(), key); } @@ -452,8 +452,8 @@ find(const TYPENAME ordered_vector::KEY_TYPE &key) const { * not necessarily the converse. */ template -INLINE TYPENAME ordered_vector::ITERATOR ordered_vector:: -find_particular(const TYPENAME ordered_vector::KEY_TYPE &key) { +INLINE typename ordered_vector::ITERATOR ordered_vector:: +find_particular(const typename ordered_vector::KEY_TYPE &key) { TAU_PROFILE("ordered_vector::find_particular(const key_type &)", " ", TAU_USER); return nci(r_find_particular(begin(), end(), end(), key)); } @@ -469,8 +469,8 @@ find_particular(const TYPENAME ordered_vector::KEY_TYPE &k * is not defined. */ template -INLINE TYPENAME ordered_vector::CONST_ITERATOR ordered_vector:: -find_particular(const TYPENAME ordered_vector::KEY_TYPE &key) const { +INLINE typename ordered_vector::CONST_ITERATOR ordered_vector:: +find_particular(const typename ordered_vector::KEY_TYPE &key) const { TAU_PROFILE("ordered_vector::find_particular(const key_type &)", " ", TAU_USER); return r_find_particular(begin(), end(), end(), key); } @@ -480,7 +480,7 @@ find_particular(const TYPENAME ordered_vector::KEY_TYPE &k * the vector. */ template -INLINE TYPENAME ordered_vector::SIZE_TYPE ordered_vector:: +INLINE typename ordered_vector::SIZE_TYPE ordered_vector:: count(const key_type &key) const { TAU_PROFILE("ordered_vector::count(const key_type &)", " ", TAU_USER); return r_count(begin(), end(), key); @@ -491,8 +491,8 @@ count(const key_type &key) const { * all elements are less than key. */ template -INLINE TYPENAME ordered_vector::ITERATOR ordered_vector:: -lower_bound(const TYPENAME ordered_vector::KEY_TYPE &key) { +INLINE typename ordered_vector::ITERATOR ordered_vector:: +lower_bound(const typename ordered_vector::KEY_TYPE &key) { TAU_PROFILE("ordered_vector::lower_bound(const key_type &)", " ", TAU_USER); return nci(r_lower_bound(begin(), end(), key)); } @@ -502,8 +502,8 @@ lower_bound(const TYPENAME ordered_vector::KEY_TYPE &key) * all elements are less than key. */ template -INLINE TYPENAME ordered_vector::CONST_ITERATOR ordered_vector:: -lower_bound(const TYPENAME ordered_vector::KEY_TYPE &key) const { +INLINE typename ordered_vector::CONST_ITERATOR ordered_vector:: +lower_bound(const typename ordered_vector::KEY_TYPE &key) const { TAU_PROFILE("ordered_vector::lower_bound(const key_type &)", " ", TAU_USER); return r_lower_bound(begin(), end(), key); } @@ -513,8 +513,8 @@ lower_bound(const TYPENAME ordered_vector::KEY_TYPE &key) * element is greater than key. */ template -INLINE TYPENAME ordered_vector::ITERATOR ordered_vector:: -upper_bound(const TYPENAME ordered_vector::KEY_TYPE &key) { +INLINE typename ordered_vector::ITERATOR ordered_vector:: +upper_bound(const typename ordered_vector::KEY_TYPE &key) { TAU_PROFILE("ordered_vector::upper_bound(const key_type &)", " ", TAU_USER); return nci(r_upper_bound(begin(), end(), key)); } @@ -524,8 +524,8 @@ upper_bound(const TYPENAME ordered_vector::KEY_TYPE &key) * element is greater than key. */ template -INLINE TYPENAME ordered_vector::CONST_ITERATOR ordered_vector:: -upper_bound(const TYPENAME ordered_vector::KEY_TYPE &key) const { +INLINE typename ordered_vector::CONST_ITERATOR ordered_vector:: +upper_bound(const typename ordered_vector::KEY_TYPE &key) const { TAU_PROFILE("ordered_vector::upper_bound(const key_type &)", " ", TAU_USER); return r_upper_bound(begin(), end(), key); } @@ -534,20 +534,20 @@ upper_bound(const TYPENAME ordered_vector::KEY_TYPE &key) * Returns the pair (lower_bound(key), upper_bound(key)). */ template -INLINE pair::ITERATOR, TYPENAME ordered_vector::ITERATOR> ordered_vector:: -equal_range(const TYPENAME ordered_vector::KEY_TYPE &key) { +INLINE std::pair::ITERATOR, typename ordered_vector::ITERATOR> ordered_vector:: +equal_range(const typename ordered_vector::KEY_TYPE &key) { TAU_PROFILE("ordered_vector::equal_range(const key_type &)", " ", TAU_USER); - pair::CONST_ITERATOR, TYPENAME ordered_vector::CONST_ITERATOR> result; + std::pair::CONST_ITERATOR, typename ordered_vector::CONST_ITERATOR> result; result = r_equal_range(begin(), end(), key); - return pair::ITERATOR, TYPENAME ordered_vector::ITERATOR>(nci(result.first), nci(result.second)); + return std::pair::ITERATOR, typename ordered_vector::ITERATOR>(nci(result.first), nci(result.second)); } /** * Returns the pair (lower_bound(key), upper_bound(key)). */ template -INLINE pair::CONST_ITERATOR, TYPENAME ordered_vector::CONST_ITERATOR> ordered_vector:: -equal_range(const TYPENAME ordered_vector::KEY_TYPE &key) const { +INLINE std::pair::CONST_ITERATOR, typename ordered_vector::CONST_ITERATOR> ordered_vector:: +equal_range(const typename ordered_vector::KEY_TYPE &key) const { TAU_PROFILE("ordered_vector::equal_range(const key_type &)", " ", TAU_USER); return r_equal_range(begin(), end(), key); } @@ -569,7 +569,7 @@ swap(ordered_vector ©) { */ template INLINE void ordered_vector:: -reserve(TYPENAME ordered_vector::SIZE_TYPE n) { +reserve(typename ordered_vector::SIZE_TYPE n) { TAU_PROFILE("ordered_vector::reserve(size_type)", " ", TAU_USER); _vector.reserve(n); } @@ -601,7 +601,7 @@ template INLINE void ordered_vector:: sort_nonunique() { TAU_PROFILE("ordered_vector::sort_nonunique()", " ", TAU_USER); - stable_sort(begin(), end(), _compare); + std::stable_sort(begin(), end(), _compare); } /** @@ -625,7 +625,7 @@ template INLINE void ordered_vector:: push_back(value_type &&key) { TAU_PROFILE("ordered_vector::push_back()", " ", TAU_USER); - _vector.push_back(move(key)); + _vector.push_back(std::move(key)); } /** @@ -666,8 +666,8 @@ resize(SIZE_TYPE n, const VALUE_TYPE &value) { * const flavors of some of these methods. */ template -INLINE TYPENAME ordered_vector::ITERATOR ordered_vector:: -nci(TYPENAME ordered_vector::CONST_ITERATOR i) { +INLINE typename ordered_vector::ITERATOR ordered_vector:: +nci(typename ordered_vector::CONST_ITERATOR i) { return begin() + (i - begin()); } @@ -676,10 +676,10 @@ nci(TYPENAME ordered_vector::CONST_ITERATOR i) { * indicated key, and returns the corresponding iterator. */ template -INLINE TYPENAME ordered_vector::ITERATOR ordered_vector:: -find_insert_position(TYPENAME ordered_vector::ITERATOR first, - TYPENAME ordered_vector::ITERATOR last, - const TYPENAME ordered_vector::KEY_TYPE &key) { +INLINE typename ordered_vector::ITERATOR ordered_vector:: +find_insert_position(typename ordered_vector::ITERATOR first, + typename ordered_vector::ITERATOR last, + const typename ordered_vector::KEY_TYPE &key) { ITERATOR result = r_find_insert_position(first, last, key); return result; } @@ -708,9 +708,9 @@ ov_set(const Compare &compare, TypeHandle type_handle) : * Maps to insert_unique(). */ template -TYPENAME ov_set::ITERATOR ov_set:: -insert(TYPENAME ov_set::ITERATOR position, - const TYPENAME ov_set::VALUE_TYPE &key) { +typename ov_set::ITERATOR ov_set:: +insert(typename ov_set::ITERATOR position, + const typename ov_set::VALUE_TYPE &key) { return ordered_vector::insert_unique(position, key); } @@ -718,8 +718,8 @@ insert(TYPENAME ov_set::ITERATOR position, * Maps to insert_unique(). */ template -INLINE pair::ITERATOR, bool> ov_set:: -insert(const TYPENAME ov_set::VALUE_TYPE &key) { +INLINE std::pair::ITERATOR, bool> ov_set:: +insert(const typename ov_set::VALUE_TYPE &key) { return ordered_vector::insert_unique(key); } @@ -765,9 +765,9 @@ ov_multiset(const Compare &compare, TypeHandle type_handle) : * Maps to insert_nonunique(). */ template -TYPENAME ov_multiset::ITERATOR ov_multiset:: -insert(TYPENAME ov_multiset::ITERATOR position, - const TYPENAME ov_multiset::VALUE_TYPE &key) { +typename ov_multiset::ITERATOR ov_multiset:: +insert(typename ov_multiset::ITERATOR position, + const typename ov_multiset::VALUE_TYPE &key) { return ordered_vector::insert_nonunique(position, key); } @@ -775,8 +775,8 @@ insert(TYPENAME ov_multiset::ITERATOR position, * Maps to insert_nonunique(). */ template -INLINE TYPENAME ov_multiset::ITERATOR ov_multiset:: -insert(const TYPENAME ov_multiset::VALUE_TYPE &key) { +INLINE typename ov_multiset::ITERATOR ov_multiset:: +insert(const typename ov_multiset::VALUE_TYPE &key) { return ordered_vector::insert_nonunique(key); } diff --git a/panda/src/express/ordered_vector.T b/panda/src/express/ordered_vector.T index 7ea866e52f..f41109dab1 100644 --- a/panda/src/express/ordered_vector.T +++ b/panda/src/express/ordered_vector.T @@ -1,36 +1,30 @@ -// Filename: ordered_vector.T -// Created by: drose (20Feb02) -// -//////////////////////////////////////////////////////////////////// -// -// PANDA 3D SOFTWARE -// Copyright (c) Carnegie Mellon University. All rights reserved. -// -// All use of this software is subject to the terms of the revised BSD -// license. You should have received a copy of this license along -// with this source code in a file named "LICENSE." -// -//////////////////////////////////////////////////////////////////// +/** + * PANDA 3D SOFTWARE + * Copyright (c) Carnegie Mellon University. All rights reserved. + * + * All use of this software is subject to the terms of the revised BSD + * license. You should have received a copy of this license along + * with this source code in a file named "LICENSE." + * + * @file ordered_vector.T + * @author drose + * @date 2002-02-02 + */ - -//////////////////////////////////////////////////////////////////// -// Function: ordered_vector::insert_unique -// Access: Public -// Description: Inserts the indicated key into the ordered vector. -// The iterator is a hint to the expected position; if -// this is correct, the insert operation is likely to be -// faster. The return value is the iterator referencing -// the new element. -// -// This flavor of insert does not allow multiple copies -// of the same key to be inserted. If the key is -// already present, it is not inserted, and the iterator -// referencing the original value is returned. -//////////////////////////////////////////////////////////////////// +/** + * Inserts the indicated key into the ordered vector. The iterator is a hint + * to the expected position; if this is correct, the insert operation is + * likely to be faster. The return value is the iterator referencing the new + * element. + * + * This flavor of insert does not allow multiple copies of the same key to be + * inserted. If the key is already present, it is not inserted, and the + * iterator referencing the original value is returned. + */ template -TYPENAME ordered_vector::ITERATOR ordered_vector:: -insert_unique(TYPENAME ordered_vector::ITERATOR position, - const TYPENAME ordered_vector::VALUE_TYPE &key) { +typename ordered_vector::ITERATOR ordered_vector:: +insert_unique(typename ordered_vector::ITERATOR position, + const typename ordered_vector::VALUE_TYPE &key) { TAU_PROFILE("ordered_vector::insert_unique(iterator, const value_type &)", " ", TAU_USER); if (position != end()) { // If we're not inserting at the end, the element we're @@ -62,22 +56,20 @@ insert_unique(TYPENAME ordered_vector::ITERATOR position, return result; } -//////////////////////////////////////////////////////////////////// -// Function: ordered_vector::insert_nonunique -// Access: Public -// Description: Inserts the indicated key into the ordered vector. -// The iterator is a hint to the expected position; if -// this is correct, the insert operation is likely to be -// faster. The return value is the iterator referencing -// the new element. -// -// This flavor of insert allows multiple copies of the -// same key to be inserted. -//////////////////////////////////////////////////////////////////// + +/** + * Inserts the indicated key into the ordered vector. The iterator is a hint + * to the expected position; if this is correct, the insert operation is + * likely to be faster. The return value is the iterator referencing the new + * element. + * + * This flavor of insert allows multiple copies of the + * same key to be inserted. + */ template -TYPENAME ordered_vector::ITERATOR ordered_vector:: -insert_nonunique(TYPENAME ordered_vector::ITERATOR position, - const TYPENAME ordered_vector::VALUE_TYPE &key) { +typename ordered_vector::ITERATOR ordered_vector:: +insert_nonunique(typename ordered_vector::ITERATOR position, + const typename ordered_vector::VALUE_TYPE &key) { TAU_PROFILE("ordered_vector::insert_nonunique(iterator, const value_type &)", " ", TAU_USER); if (position != end()) { // If we're not inserting at the end, the element we're @@ -100,13 +92,10 @@ insert_nonunique(TYPENAME ordered_vector::ITERATOR positio return result; } -//////////////////////////////////////////////////////////////////// -// Function: ordered_vector::verify_list_unique -// Access: Public -// Description: Ensures that the indicated range of elements is -// sorted correctly. Returns true if this is the case; -// otherwise, returns false. -//////////////////////////////////////////////////////////////////// +/** + * Ensures that the indicated range of elements is sorted correctly. Returns + * true if this is the case; otherwise, returns false. + */ template bool ordered_vector:: verify_list_unique() const { @@ -127,13 +116,10 @@ verify_list_unique() const { return true; } -//////////////////////////////////////////////////////////////////// -// Function: ordered_vector::verify_list_nonunique -// Access: Public -// Description: Ensures that the indicated range of elements is -// sorted correctly. Returns true if this is the case; -// otherwise, returns false. -//////////////////////////////////////////////////////////////////// +/** + * Ensures that the indicated range of elements is sorted correctly. Returns + * true if this is the case; otherwise, returns false. + */ template bool ordered_vector:: verify_list_nonunique() const { @@ -155,17 +141,14 @@ verify_list_nonunique() const { } -//////////////////////////////////////////////////////////////////// -// Function: ordered_vector::r_find_insert_position -// Access: Private -// Description: The recursive implementation of -// find_insert_position(). -//////////////////////////////////////////////////////////////////// +/** + * The recursive implementation of find_insert_position(). + */ template -TYPENAME ordered_vector::ITERATOR ordered_vector:: -r_find_insert_position(TYPENAME ordered_vector::ITERATOR first, - TYPENAME ordered_vector::ITERATOR last, - const TYPENAME ordered_vector::KEY_TYPE &key) { +typename ordered_vector::ITERATOR ordered_vector:: +r_find_insert_position(typename ordered_vector::ITERATOR first, + typename ordered_vector::ITERATOR last, + const typename ordered_vector::KEY_TYPE &key) { if (first == last) { // The list is empty; the insert position is the last of the list. return last; @@ -184,17 +167,15 @@ r_find_insert_position(TYPENAME ordered_vector::ITERATOR f } } -//////////////////////////////////////////////////////////////////// -// Function: ordered_vector::r_find -// Access: Private -// Description: The recursive implementation of find(). -//////////////////////////////////////////////////////////////////// +/** + * The recursive implementation of find(). + */ template -TYPENAME ordered_vector::CONST_ITERATOR ordered_vector:: -r_find(TYPENAME ordered_vector::CONST_ITERATOR first, - TYPENAME ordered_vector::CONST_ITERATOR last, - TYPENAME ordered_vector::CONST_ITERATOR not_found, - const TYPENAME ordered_vector::KEY_TYPE &key) const { +typename ordered_vector::CONST_ITERATOR ordered_vector:: +r_find(typename ordered_vector::CONST_ITERATOR first, + typename ordered_vector::CONST_ITERATOR last, + typename ordered_vector::CONST_ITERATOR not_found, + const typename ordered_vector::KEY_TYPE &key) const { if (first == last) { // The list is empty; the key is not on the list. return not_found; @@ -217,17 +198,15 @@ r_find(TYPENAME ordered_vector::CONST_ITERATOR first, } } -//////////////////////////////////////////////////////////////////// -// Function: ordered_vector::r_find_particular -// Access: Private -// Description: The recursive implementation of find_particular(). -//////////////////////////////////////////////////////////////////// +/** + * The recursive implementation of find_particular(). + */ template -TYPENAME ordered_vector::CONST_ITERATOR ordered_vector:: -r_find_particular(TYPENAME ordered_vector::CONST_ITERATOR first, - TYPENAME ordered_vector::CONST_ITERATOR last, - TYPENAME ordered_vector::CONST_ITERATOR not_found, - const TYPENAME ordered_vector::KEY_TYPE &key) const { +typename ordered_vector::CONST_ITERATOR ordered_vector:: +r_find_particular(typename ordered_vector::CONST_ITERATOR first, + typename ordered_vector::CONST_ITERATOR last, + typename ordered_vector::CONST_ITERATOR not_found, + const typename ordered_vector::KEY_TYPE &key) const { if (first == last) { // The list is empty; the key is not on the list. return not_found; @@ -270,16 +249,14 @@ r_find_particular(TYPENAME ordered_vector::CONST_ITERATOR } } -//////////////////////////////////////////////////////////////////// -// Function: ordered_vector::r_count -// Access: Private -// Description: The recursive implementation of count(). -//////////////////////////////////////////////////////////////////// +/** + * The recursive implementation of count(). + */ template -TYPENAME ordered_vector::SIZE_TYPE ordered_vector:: -r_count(TYPENAME ordered_vector::CONST_ITERATOR first, - TYPENAME ordered_vector::CONST_ITERATOR last, - const TYPENAME ordered_vector::KEY_TYPE &key) const { +typename ordered_vector::SIZE_TYPE ordered_vector:: +r_count(typename ordered_vector::CONST_ITERATOR first, + typename ordered_vector::CONST_ITERATOR last, + const typename ordered_vector::KEY_TYPE &key) const { if (first == last) { // The list is empty; the key is not on the list. @@ -305,16 +282,14 @@ r_count(TYPENAME ordered_vector::CONST_ITERATOR first, } } -//////////////////////////////////////////////////////////////////// -// Function: ordered_vector::r_lower_bound -// Access: Private -// Description: The recursive implementation of lower_bound(). -//////////////////////////////////////////////////////////////////// +/** + * The recursive implementation of lower_bound(). + */ template -TYPENAME ordered_vector::CONST_ITERATOR ordered_vector:: -r_lower_bound(TYPENAME ordered_vector::CONST_ITERATOR first, - TYPENAME ordered_vector::CONST_ITERATOR last, - const TYPENAME ordered_vector::KEY_TYPE &key) const { +typename ordered_vector::CONST_ITERATOR ordered_vector:: +r_lower_bound(typename ordered_vector::CONST_ITERATOR first, + typename ordered_vector::CONST_ITERATOR last, + const typename ordered_vector::KEY_TYPE &key) const { if (first == last) { // The list is empty; the key is not on the list. return last; @@ -338,16 +313,14 @@ r_lower_bound(TYPENAME ordered_vector::CONST_ITERATOR firs } } -//////////////////////////////////////////////////////////////////// -// Function: ordered_vector::r_upper_bound -// Access: Private -// Description: The recursive implementation of upper_bound(). -//////////////////////////////////////////////////////////////////// +/** + * The recursive implementation of upper_bound(). + */ template -TYPENAME ordered_vector::CONST_ITERATOR ordered_vector:: -r_upper_bound(TYPENAME ordered_vector::CONST_ITERATOR first, - TYPENAME ordered_vector::CONST_ITERATOR last, - const TYPENAME ordered_vector::KEY_TYPE &key) const { +typename ordered_vector::CONST_ITERATOR ordered_vector:: +r_upper_bound(typename ordered_vector::CONST_ITERATOR first, + typename ordered_vector::CONST_ITERATOR last, + const typename ordered_vector::KEY_TYPE &key) const { if (first == last) { // The list is empty; the key is not on the list. return last; @@ -371,17 +344,15 @@ r_upper_bound(TYPENAME ordered_vector::CONST_ITERATOR firs } } -//////////////////////////////////////////////////////////////////// -// Function: ordered_vector::r_equal_range -// Access: Private -// Description: The recursive implementation of equal_range(). -//////////////////////////////////////////////////////////////////// +/** + * The recursive implementation of equal_range(). + */ template -pair::CONST_ITERATOR, TYPENAME ordered_vector::CONST_ITERATOR> ordered_vector:: -r_equal_range(TYPENAME ordered_vector::CONST_ITERATOR first, - TYPENAME ordered_vector::CONST_ITERATOR last, - const TYPENAME ordered_vector::KEY_TYPE &key) const { - typedef pair::CONST_ITERATOR, TYPENAME ordered_vector::CONST_ITERATOR> pair_type; +std::pair::CONST_ITERATOR, typename ordered_vector::CONST_ITERATOR> ordered_vector:: +r_equal_range(typename ordered_vector::CONST_ITERATOR first, + typename ordered_vector::CONST_ITERATOR last, + const typename ordered_vector::KEY_TYPE &key) const { + typedef std::pair::CONST_ITERATOR, typename ordered_vector::CONST_ITERATOR> pair_type; if (first == last) { // The list is empty; the key is not on the list. diff --git a/panda/src/express/ordered_vector.h b/panda/src/express/ordered_vector.h index e9e3a03693..1a4869b91a 100644 --- a/panda/src/express/ordered_vector.h +++ b/panda/src/express/ordered_vector.h @@ -19,15 +19,15 @@ // memory foot pront and user time by a bunch on pc cygwin from 3 minutes to // 17 seconds ?? really need to explore interigate to figure out what is going // on .. -template, class Vector = pvector > class ov_multiset +template, class Vector = pvector > class ov_multiset { }; -template, class Vector = pvector > class ov_set +template, class Vector = pvector > class ov_set { }; -template, class Vector = pvector > class ordered_vector +template, class Vector = pvector > class ordered_vector { }; @@ -91,7 +91,7 @@ template, class Vector = pvector > cla * * (4) Random access into the set is easy with the [] operator. */ -template, class Vector = pvector > +template, class Vector = pvector > class ordered_vector { public: // Typedefs @@ -105,13 +105,13 @@ public: // Be careful when using the non-const iterators that you do not disturb the // sorted order of the vector, or that if you do, you call sort() when you // are done. - typedef TYPENAME Vector::iterator ITERATOR; - typedef TYPENAME Vector::const_iterator CONST_ITERATOR; - typedef TYPENAME Vector::reverse_iterator REVERSE_ITERATOR; - typedef TYPENAME Vector::const_reverse_iterator CONST_REVERSE_ITERATOR; + typedef typename Vector::iterator ITERATOR; + typedef typename Vector::const_iterator CONST_ITERATOR; + typedef typename Vector::reverse_iterator REVERSE_ITERATOR; + typedef typename Vector::const_reverse_iterator CONST_REVERSE_ITERATOR; - typedef TYPENAME Vector::difference_type DIFFERENCE_TYPE; - typedef TYPENAME Vector::size_type SIZE_TYPE; + typedef typename Vector::difference_type DIFFERENCE_TYPE; + typedef typename Vector::size_type SIZE_TYPE; // Since the #define symbols do not actually expand to the correct names, we // have to re-typedef them so callers can reference them by their correct, @@ -179,7 +179,7 @@ public: // Insert operations. ITERATOR insert_unique(ITERATOR position, const VALUE_TYPE &key); ITERATOR insert_nonunique(ITERATOR position, const VALUE_TYPE &key); - INLINE pair insert_unique(const VALUE_TYPE &key); + INLINE std::pair insert_unique(const VALUE_TYPE &key); INLINE ITERATOR insert_nonunique(const VALUE_TYPE &key); INLINE ITERATOR insert_unverified(ITERATOR position, const VALUE_TYPE &key); @@ -200,8 +200,8 @@ public: INLINE CONST_ITERATOR lower_bound(const KEY_TYPE &key) const; INLINE ITERATOR upper_bound(const KEY_TYPE &key); INLINE CONST_ITERATOR upper_bound(const KEY_TYPE &key) const; - INLINE pair equal_range(const KEY_TYPE &key); - INLINE pair equal_range(const KEY_TYPE &key) const; + INLINE std::pair equal_range(const KEY_TYPE &key); + INLINE std::pair equal_range(const KEY_TYPE &key) const; // Special operations. INLINE void swap(ordered_vector &other); @@ -235,7 +235,7 @@ private: const KEY_TYPE &key) const; CONST_ITERATOR r_upper_bound(CONST_ITERATOR first, CONST_ITERATOR last, const KEY_TYPE &key) const; - pair + std::pair r_equal_range(CONST_ITERATOR first, CONST_ITERATOR last, const KEY_TYPE &key) const; @@ -265,18 +265,18 @@ private: * A specialization of ordered_vector that emulates a standard STL set: one * copy of each element is allowed. */ -template, class Vector = pvector > +template, class Vector = pvector > class ov_set : public ordered_vector { public: - typedef TYPENAME ordered_vector::ITERATOR ITERATOR; - typedef TYPENAME ordered_vector::VALUE_TYPE VALUE_TYPE; + typedef typename ordered_vector::ITERATOR ITERATOR; + typedef typename ordered_vector::VALUE_TYPE VALUE_TYPE; INLINE ov_set(TypeHandle type_handle = ov_set_type_handle); INLINE ov_set(const Compare &compare, TypeHandle type_handle = ov_set_type_handle); INLINE ITERATOR insert(ITERATOR position, const VALUE_TYPE &key0); - INLINE pair insert(const VALUE_TYPE &key0); + INLINE std::pair insert(const VALUE_TYPE &key0); INLINE void sort(); INLINE bool verify_list() const; @@ -286,11 +286,11 @@ public: * A specialization of ordered_vector that emulates a standard STL set: many * copies of each element are allowed. */ -template, class Vector = pvector > +template, class Vector = pvector > class ov_multiset : public ordered_vector { public: - typedef TYPENAME ordered_vector::ITERATOR ITERATOR; - typedef TYPENAME ordered_vector::VALUE_TYPE VALUE_TYPE; + typedef typename ordered_vector::ITERATOR ITERATOR; + typedef typename ordered_vector::VALUE_TYPE VALUE_TYPE; INLINE ov_multiset(TypeHandle type_handle = ov_set_type_handle); INLINE ov_multiset(const Compare &compare, diff --git a/panda/src/express/pStatCollectorForwardBase.h b/panda/src/express/pStatCollectorForwardBase.h index 79e53d8060..dcc2fa73da 100644 --- a/panda/src/express/pStatCollectorForwardBase.h +++ b/panda/src/express/pStatCollectorForwardBase.h @@ -25,7 +25,7 @@ * This is subclassed as PStatCollectorForward, which defines the actual * functionality. */ -class EXPCL_PANDAEXPRESS PStatCollectorForwardBase : public ReferenceCount { +class EXPCL_PANDA_EXPRESS PStatCollectorForwardBase : public ReferenceCount { PUBLISHED: #ifdef DO_PSTATS virtual ~PStatCollectorForwardBase(); diff --git a/panda/src/express/password_hash.cxx b/panda/src/express/password_hash.cxx index a3385013df..b061904965 100644 --- a/panda/src/express/password_hash.cxx +++ b/panda/src/express/password_hash.cxx @@ -21,6 +21,8 @@ #include "openssl/evp.h" #include "memoryHook.h" +using std::string; + /** * Generates a non-reversible hash of a particular length based on an * arbitrary password and a random salt. This is much stronger than the diff --git a/panda/src/express/password_hash.h b/panda/src/express/password_hash.h index 8006d8d9ea..f6091b8103 100644 --- a/panda/src/express/password_hash.h +++ b/panda/src/express/password_hash.h @@ -22,9 +22,9 @@ BEGIN_PUBLISH -EXPCL_PANDAEXPRESS string password_hash(const string &password, - const string &salt, - int iters, int keylen); +EXPCL_PANDA_EXPRESS std::string password_hash(const std::string &password, + const std::string &salt, + int iters, int keylen); END_PUBLISH diff --git a/panda/src/express/patchfile.I b/panda/src/express/patchfile.I index 600c7e92ca..bea1547c28 100644 --- a/panda/src/express/patchfile.I +++ b/panda/src/express/patchfile.I @@ -21,7 +21,7 @@ INLINE PN_stdfloat Patchfile:: get_progress() const { if (!_initiated) { express_cat.warning() - << "Patchfile::get_progress() - Patch has not been initiated" << endl; + << "Patchfile::get_progress() - Patch has not been initiated" << std::endl; return 0.0f; } nassertr(_total_bytes_to_process > 0, 0.0f); diff --git a/panda/src/express/patchfile.cxx b/panda/src/express/patchfile.cxx index 73b04139a0..a527d78a02 100644 --- a/panda/src/express/patchfile.cxx +++ b/panda/src/express/patchfile.cxx @@ -32,9 +32,17 @@ #endif // HAVE_TAR #ifdef HAVE_TAR -istream *Patchfile::_tar_istream = NULL; +istream *Patchfile::_tar_istream = nullptr; #endif // HAVE_TAR +using std::endl; +using std::ios; +using std::istream; +using std::min; +using std::ostream; +using std::streampos; +using std::string; + // this actually slows things down... #define // USE_MD5_FOR_HASHTABLE_INDEX_VALUES @@ -99,7 +107,7 @@ void Patchfile:: init(PT(Buffer) buffer) { _rename_output_to_orig = false; _delete_patchfile = false; - _hash_table = NULL; + _hash_table = nullptr; _initiated = false; nassertv(!buffer.is_null()); _buffer = buffer; @@ -107,8 +115,8 @@ init(PT(Buffer) buffer) { _version_number = 0; _allow_multifile = true; - _patch_stream = NULL; - _origfile_stream = NULL; + _patch_stream = nullptr; + _origfile_stream = nullptr; reset_footprint_length(); } @@ -118,7 +126,7 @@ init(PT(Buffer) buffer) { */ Patchfile:: ~Patchfile() { - if (_hash_table != (uint32_t *)NULL) { + if (_hash_table != nullptr) { PANDA_FREE_ARRAY(_hash_table); } @@ -126,8 +134,8 @@ Patchfile:: cleanup(); } - nassertv(_patch_stream == NULL); - nassertv(_origfile_stream == NULL); + nassertv(_patch_stream == nullptr); + nassertv(_origfile_stream == nullptr); } /** @@ -144,13 +152,13 @@ cleanup() { // close files VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); - if (_origfile_stream != NULL) { + if (_origfile_stream != nullptr) { vfs->close_read_file(_origfile_stream); - _origfile_stream = NULL; + _origfile_stream = nullptr; } - if (_patch_stream != NULL) { + if (_patch_stream != nullptr) { vfs->close_read_file(_patch_stream); - _patch_stream = NULL; + _patch_stream = nullptr; } _write_stream.close(); @@ -195,11 +203,11 @@ initiate(const Filename &patch_file, const Filename &orig_file, VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); // Open the original file for read - nassertr(_origfile_stream == NULL, EU_error_abort); + nassertr(_origfile_stream == nullptr, EU_error_abort); _orig_file = orig_file; _orig_file.set_binary(); _origfile_stream = vfs->open_read_file(_orig_file, false); - if (_origfile_stream == NULL) { + if (_origfile_stream == nullptr) { express_cat.error() << "Patchfile::initiate() - Failed to open file: " << _orig_file << endl; return get_write_error(); @@ -241,10 +249,10 @@ read_header(const Filename &patch_file) { } int result = internal_read_header(patch_file); - if (_patch_stream != NULL) { + if (_patch_stream != nullptr) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->close_read_file(_patch_stream); - _patch_stream = NULL; + _patch_stream = nullptr; } return result; } @@ -272,8 +280,8 @@ run() { return EU_error_abort; } - nassertr(_patch_stream != NULL, EU_error_abort); - nassertr(_origfile_stream != NULL, EU_error_abort); + nassertr(_patch_stream != nullptr, EU_error_abort); + nassertr(_origfile_stream != nullptr, EU_error_abort); StreamReader patch_reader(*_patch_stream); buflen = _buffer->get_length(); @@ -399,10 +407,10 @@ run() { MD5_actual.hash_file(_output_file); if (_MD5_ofResult != MD5_actual) { // Whoops, patching screwed up somehow. - if (_origfile_stream != NULL) { + if (_origfile_stream != nullptr) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->close_read_file(_origfile_stream); - _origfile_stream = NULL; + _origfile_stream = nullptr; } _write_stream.close(); @@ -520,11 +528,11 @@ int Patchfile:: internal_read_header(const Filename &patch_file) { // Open the patch file for read VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); - nassertr(_patch_stream == NULL, EU_error_abort); + nassertr(_patch_stream == nullptr, EU_error_abort); _patch_file = patch_file; _patch_file.set_binary(); _patch_stream = vfs->open_read_file(_patch_file, true); - if (_patch_stream == NULL) { + if (_patch_stream == nullptr) { express_cat.error() << "Patchfile::initiate() - Failed to open file: " << _patch_file << endl; return get_write_error(); @@ -840,7 +848,7 @@ emit_add_and_copy(ostream &write_stream, emit_COPY(write_stream, max_write, copy_pos); copy_pos += max_write; copy_length -= max_write; - emit_ADD(write_stream, 0, NULL); + emit_ADD(write_stream, 0, nullptr); } emit_COPY(write_stream, copy_length, copy_pos); @@ -946,7 +954,7 @@ void Patchfile:: write_terminator(ostream &write_stream) { cache_flush(write_stream); // write terminator (null ADD, null COPY) - emit_ADD(write_stream, 0, NULL); + emit_ADD(write_stream, 0, nullptr); emit_COPY(write_stream, 0, 0); } @@ -987,7 +995,7 @@ compute_file_patches(ostream &write_stream, stream_new.read(buffer_new, result_file_length); // allocate hashlink tables - if (_hash_table == (uint32_t *)NULL) { + if (_hash_table == nullptr) { if (express_cat.is_debug()) { express_cat.debug() << "Allocating hashtable of size " << _HASHTABLESIZE << " * 4\n"; @@ -1103,7 +1111,7 @@ compute_mf_patches(ostream &write_stream, index_orig, index_new)) { return false; } - nassertr(_add_pos + _cache_add_data.size() + _cache_copy_length == offset_new + mf_new.get_index_end(), false); + nassertr(_add_pos + _cache_add_data.size() + _cache_copy_length == offset_new + (uint32_t)mf_new.get_index_end(), false); } // Now walk through each subfile in the new multifile. If a particular @@ -1112,7 +1120,7 @@ compute_mf_patches(ostream &write_stream, // removed, we simply don't add it (we'll never even notice this case). int new_num_subfiles = mf_new.get_num_subfiles(); for (int ni = 0; ni < new_num_subfiles; ++ni) { - nassertr(_add_pos + _cache_add_data.size() + _cache_copy_length == offset_new + mf_new.get_subfile_internal_start(ni), false); + nassertr(_add_pos + _cache_add_data.size() + _cache_copy_length == offset_new + (uint32_t)mf_new.get_subfile_internal_start(ni), false); string name = mf_new.get_subfile_name(ni); int oi = mf_orig.find_subfile(name); @@ -1166,10 +1174,10 @@ read_tar(TarDef &tar, istream &stream) { tt.writefunc = tar_writefunc; stream.seekg(0, ios::beg); - nassertr(_tar_istream == NULL, false); + nassertr(_tar_istream == nullptr, false); _tar_istream = &stream; if (tar_open(&tfile, (char *)"dummy", &tt, O_RDONLY, 0, 0) != 0) { - _tar_istream = NULL; + _tar_istream = nullptr; return false; } @@ -1205,7 +1213,7 @@ read_tar(TarDef &tar, istream &stream) { tar.push_back(subfile); tar_close(tfile); - _tar_istream = NULL; + _tar_istream = nullptr; return (flag == 1); } #endif // HAVE_TAR @@ -1326,7 +1334,7 @@ tar_closefunc(int) { */ ssize_t Patchfile:: tar_readfunc(int, void *buffer, size_t nbytes) { - nassertr(_tar_istream != NULL, 0); + nassertr(_tar_istream != nullptr, 0); _tar_istream->read((char *)buffer, nbytes); return (ssize_t)_tar_istream->gcount(); } @@ -1436,8 +1444,8 @@ do_compute_patches(const Filename &file_orig, const Filename &file_new, #endif // HAVE_TAR if (_allow_multifile) { - if (strstr(file_orig.get_basename().c_str(), ".mf") != NULL || - strstr(file_new.get_basename().c_str(), ".mf") != NULL) { + if (strstr(file_orig.get_basename().c_str(), ".mf") != nullptr || + strstr(file_new.get_basename().c_str(), ".mf") != nullptr) { // Read the first n bytes of both files for the Multifile magic number. string magic_number = Multifile::get_magic_number(); char *buffer = (char *)PANDA_MALLOC_ARRAY(magic_number.size()); @@ -1456,8 +1464,8 @@ do_compute_patches(const Filename &file_orig, const Filename &file_new, PANDA_FREE_ARRAY(buffer); } #ifdef HAVE_TAR - if (strstr(file_orig.get_basename().c_str(), ".tar") != NULL || - strstr(file_new.get_basename().c_str(), ".tar") != NULL) { + if (strstr(file_orig.get_basename().c_str(), ".tar") != nullptr || + strstr(file_new.get_basename().c_str(), ".tar") != nullptr) { if (read_tar(tar_orig, stream_orig) && read_tar(tar_new, stream_new)) { is_tarfile = true; @@ -1509,7 +1517,7 @@ patch_subfile(ostream &write_stream, const Filename &filename, IStreamWrapper &stream_orig, streampos orig_start, streampos orig_end, IStreamWrapper &stream_new, streampos new_start, streampos new_end) { - nassertr(_add_pos + _cache_add_data.size() + _cache_copy_length == offset_new + new_start, false); + nassertr(_add_pos + _cache_add_data.size() + _cache_copy_length == offset_new + (uint32_t)new_start, false); size_t new_size = new_end - new_start; size_t orig_size = orig_end - orig_start; @@ -1534,7 +1542,7 @@ patch_subfile(ostream &write_stream, express_cat.debug() << "Keeping subfile " << filename << "\n"; } - cache_add_and_copy(write_stream, 0, NULL, + cache_add_and_copy(write_stream, 0, nullptr, orig_size, offset_orig + orig_start); } else { diff --git a/panda/src/express/patchfile.h b/panda/src/express/patchfile.h index c32c1d59e7..d052ef8386 100644 --- a/panda/src/express/patchfile.h +++ b/panda/src/express/patchfile.h @@ -36,7 +36,7 @@ /** * */ -class EXPCL_PANDAEXPRESS Patchfile { +class EXPCL_PANDA_EXPRESS Patchfile { PUBLISHED: Patchfile(); explicit Patchfile(PT(Buffer) buffer); @@ -88,49 +88,49 @@ private: uint32_t calc_match_length(const char* buf1, const char* buf2, uint32_t max_length, uint32_t min_length); - void emit_ADD(ostream &write_stream, uint32_t length, const char* buffer); - void emit_COPY(ostream &write_stream, uint32_t length, uint32_t COPY_pos); - void emit_add_and_copy(ostream &write_stream, + void emit_ADD(std::ostream &write_stream, uint32_t length, const char* buffer); + void emit_COPY(std::ostream &write_stream, uint32_t length, uint32_t COPY_pos); + void emit_add_and_copy(std::ostream &write_stream, uint32_t add_length, const char *add_buffer, uint32_t copy_length, uint32_t copy_pos); - void cache_add_and_copy(ostream &write_stream, + void cache_add_and_copy(std::ostream &write_stream, uint32_t add_length, const char *add_buffer, uint32_t copy_length, uint32_t copy_pos); - void cache_flush(ostream &write_stream); + void cache_flush(std::ostream &write_stream); - void write_header(ostream &write_stream, - istream &stream_orig, istream &stream_new); - void write_terminator(ostream &write_stream); + void write_header(std::ostream &write_stream, + std::istream &stream_orig, std::istream &stream_new); + void write_terminator(std::ostream &write_stream); - bool compute_file_patches(ostream &write_stream, + bool compute_file_patches(std::ostream &write_stream, uint32_t offset_orig, uint32_t offset_new, - istream &stream_orig, istream &stream_new); - bool compute_mf_patches(ostream &write_stream, + std::istream &stream_orig, std::istream &stream_new); + bool compute_mf_patches(std::ostream &write_stream, uint32_t offset_orig, uint32_t offset_new, - istream &stream_orig, istream &stream_new); + std::istream &stream_orig, std::istream &stream_new); #ifdef HAVE_TAR class TarSubfile { public: inline bool operator < (const TarSubfile &other) const { return _name < other._name; } - string _name; - streampos _header_start; - streampos _data_start; - streampos _data_end; - streampos _end; + std::string _name; + std::streampos _header_start; + std::streampos _data_start; + std::streampos _data_end; + std::streampos _end; }; typedef ov_set TarDef; - bool read_tar(TarDef &tar, istream &stream); - bool compute_tar_patches(ostream &write_stream, + bool read_tar(TarDef &tar, std::istream &stream); + bool compute_tar_patches(std::ostream &write_stream, uint32_t offset_orig, uint32_t offset_new, - istream &stream_orig, istream &stream_new, + std::istream &stream_orig, std::istream &stream_new, TarDef &tar_orig, TarDef &tar_new); // Because this is static, we can only call read_tar() one at a time--no // threads, please. - static istream *_tar_istream; + static std::istream *_tar_istream; static int tar_openfunc(const char *filename, int oflags, ...); static int tar_closefunc(int fd); @@ -139,15 +139,15 @@ private: #endif // HAVE_TAR bool do_compute_patches(const Filename &file_orig, const Filename &file_new, - ostream &write_stream, + std::ostream &write_stream, uint32_t offset_orig, uint32_t offset_new, - istream &stream_orig, istream &stream_new); + std::istream &stream_orig, std::istream &stream_new); - bool patch_subfile(ostream &write_stream, + bool patch_subfile(std::ostream &write_stream, uint32_t offset_orig, uint32_t offset_new, const Filename &filename, - IStreamWrapper &stream_orig, streampos orig_start, streampos orig_end, - IStreamWrapper &stream_new, streampos new_start, streampos new_end); + IStreamWrapper &stream_orig, std::streampos orig_start, std::streampos orig_end, + IStreamWrapper &stream_new, std::streampos new_start, std::streampos new_end); static const uint32_t _HASH_BITS; static const uint32_t _HASHTABLESIZE; @@ -164,7 +164,7 @@ private: uint32_t _add_pos; uint32_t _last_copy_pos; - string _cache_add_data; + std::string _cache_add_data; uint32_t _cache_copy_start; uint32_t _cache_copy_length; @@ -183,9 +183,9 @@ private: uint32_t _total_bytes_to_process; uint32_t _total_bytes_processed; - istream *_patch_stream; + std::istream *_patch_stream; pofstream _write_stream; - istream *_origfile_stream; + std::istream *_origfile_stream; Filename _patch_file; Filename _orig_file; diff --git a/panda/src/express/pointerTo.I b/panda/src/express/pointerTo.I index 62962a83e3..8c7aa38a4e 100644 --- a/panda/src/express/pointerTo.I +++ b/panda/src/express/pointerTo.I @@ -16,7 +16,7 @@ */ template ALWAYS_INLINE PointerTo:: -PointerTo(To *ptr) NOEXCEPT : PointerToBase(ptr) { +PointerTo(To *ptr) noexcept : PointerToBase(ptr) { } /** @@ -29,14 +29,25 @@ PointerTo(const PointerTo ©) : { } -#ifdef USE_MOVE_SEMANTICS /** * */ template INLINE PointerTo:: -PointerTo(PointerTo &&from) NOEXCEPT : - PointerToBase(move(from)) +PointerTo(PointerTo &&from) noexcept : + PointerToBase(std::move(from)) +{ +} + +#ifndef CPPPARSER +/** + * + */ +template +template +ALWAYS_INLINE PointerTo:: +PointerTo(Y *ptr) noexcept : + PointerToBase(ptr) { } @@ -44,19 +55,65 @@ PointerTo(PointerTo &&from) NOEXCEPT : * */ template -INLINE PointerTo &PointerTo:: -operator = (PointerTo &&from) NOEXCEPT { - this->reassign(move(from)); - return *this; +template +ALWAYS_INLINE PointerTo:: +PointerTo(const PointerTo &r) noexcept : + PointerToBase(r.p()) +{ } -#endif // USE_MOVE_SEMANTICS /** * */ template -CONSTEXPR TYPENAME PointerTo::To &PointerTo:: -operator *() const NOEXCEPT { +template +ALWAYS_INLINE PointerTo:: +PointerTo(PointerTo &&r) noexcept : + PointerToBase(std::move(r)) +{ +} +#endif // !CPPPARSER + +/** + * + */ +template +INLINE PointerTo &PointerTo:: +operator = (PointerTo &&from) noexcept { + this->reassign(std::move(from)); + return *this; +} + +#ifndef CPPPARSER +/** + * + */ +template +template +ALWAYS_INLINE PointerTo &PointerTo:: +operator = (const PointerTo &r) noexcept { + this->reassign(r.p()); + return *this; +} + +/** + * + */ +template +template +ALWAYS_INLINE PointerTo &PointerTo:: +operator = (PointerTo &&r) noexcept { + this->reassign(std::move(r)); + return *this; +} +#endif // !CPPPARSER + +/** + * + */ +template +constexpr typename PointerTo::To &PointerTo:: +operator *() const noexcept { return *((To *)(this->_void_ptr)); } @@ -64,8 +121,8 @@ operator *() const NOEXCEPT { * */ template -CONSTEXPR TYPENAME PointerTo::To *PointerTo:: -operator -> () const NOEXCEPT { +constexpr typename PointerTo::To *PointerTo:: +operator -> () const noexcept { return (To *)(this->_void_ptr); } @@ -76,8 +133,8 @@ operator -> () const NOEXCEPT { * goes because either will be correct. */ template -CONSTEXPR PointerTo:: -operator T * () const NOEXCEPT { +constexpr PointerTo:: +operator T * () const noexcept { return (To *)(this->_void_ptr); } @@ -99,8 +156,8 @@ cheat() { * compiler problems, particularly for implicit upcasts. */ template -CONSTEXPR TYPENAME PointerTo::To *PointerTo:: -p() const NOEXCEPT { +constexpr typename PointerTo::To *PointerTo:: +p() const noexcept { return (To *)(this->_void_ptr); } @@ -129,8 +186,8 @@ operator = (const PointerTo ©) { */ template ALWAYS_INLINE ConstPointerTo:: -ConstPointerTo(const TYPENAME ConstPointerTo::To *ptr) NOEXCEPT : - PointerToBase((TYPENAME ConstPointerTo::To *)ptr) +ConstPointerTo(const typename ConstPointerTo::To *ptr) noexcept : + PointerToBase((typename ConstPointerTo::To *)ptr) { } @@ -154,14 +211,13 @@ ConstPointerTo(const ConstPointerTo ©) : { } -#ifdef USE_MOVE_SEMANTICS /** * */ template INLINE ConstPointerTo:: -ConstPointerTo(PointerTo &&from) NOEXCEPT : - PointerToBase(move(from)) +ConstPointerTo(PointerTo &&from) noexcept : + PointerToBase(std::move(from)) { } @@ -170,18 +226,75 @@ ConstPointerTo(PointerTo &&from) NOEXCEPT : */ template INLINE ConstPointerTo:: -ConstPointerTo(ConstPointerTo &&from) NOEXCEPT : - PointerToBase(move(from)) +ConstPointerTo(ConstPointerTo &&from) noexcept : + PointerToBase(std::move(from)) +{ +} + +#ifndef CPPPARSER +/** + * + */ +template +template +ALWAYS_INLINE ConstPointerTo:: +ConstPointerTo(const Y *ptr) noexcept : + PointerToBase((Y *)ptr) { } +/** + * + */ +template +template +ALWAYS_INLINE ConstPointerTo:: +ConstPointerTo(const PointerTo &r) noexcept : + PointerToBase(r.p()) +{ +} + +/** + * + */ +template +template +ALWAYS_INLINE ConstPointerTo:: +ConstPointerTo(const ConstPointerTo &r) noexcept : + PointerToBase((Y *)r.p()) +{ +} + +/** + * + */ +template +template +ALWAYS_INLINE ConstPointerTo:: +ConstPointerTo(PointerTo &&r) noexcept : + PointerToBase(std::move(r)) +{ +} + +/** + * + */ +template +template +ALWAYS_INLINE ConstPointerTo:: +ConstPointerTo(ConstPointerTo &&r) noexcept : + PointerToBase(std::move(r)) +{ +} +#endif // !CPPPARSER + /** * */ template INLINE ConstPointerTo &ConstPointerTo:: -operator = (PointerTo &&from) NOEXCEPT { - this->reassign(move(from)); +operator = (PointerTo &&from) noexcept { + this->reassign(std::move(from)); return *this; } @@ -190,18 +303,63 @@ operator = (PointerTo &&from) NOEXCEPT { */ template INLINE ConstPointerTo &ConstPointerTo:: -operator = (ConstPointerTo &&from) NOEXCEPT { - this->reassign(move(from)); +operator = (ConstPointerTo &&from) noexcept { + this->reassign(std::move(from)); + return *this; +} + +#ifndef CPPPARSER +/** + * + */ +template +template +ALWAYS_INLINE ConstPointerTo &ConstPointerTo:: +operator = (const PointerTo &r) noexcept { + this->reassign(r.p()); return *this; } -#endif // USE_MOVE_SEMANTICS /** * */ template -CONSTEXPR const TYPENAME ConstPointerTo::To &ConstPointerTo:: -operator *() const NOEXCEPT { +template +ALWAYS_INLINE ConstPointerTo &ConstPointerTo:: +operator = (const ConstPointerTo &r) noexcept { + this->reassign((Y *)r.p()); + return *this; +} + +/** + * + */ +template +template +ALWAYS_INLINE ConstPointerTo &ConstPointerTo:: +operator = (PointerTo &&r) noexcept { + this->reassign(std::move(r)); + return *this; +} + +/** + * + */ +template +template +ALWAYS_INLINE ConstPointerTo &ConstPointerTo:: +operator = (ConstPointerTo &&r) noexcept { + this->reassign(std::move(r)); + return *this; +} +#endif // !CPPPARSER + +/** + * + */ +template +constexpr const typename ConstPointerTo::To &ConstPointerTo:: +operator *() const noexcept { return *((To *)(this->_void_ptr)); } @@ -209,8 +367,8 @@ operator *() const NOEXCEPT { * */ template -CONSTEXPR const TYPENAME ConstPointerTo::To *ConstPointerTo:: -operator -> () const NOEXCEPT { +constexpr const typename ConstPointerTo::To *ConstPointerTo:: +operator -> () const noexcept { return (To *)(this->_void_ptr); } @@ -221,8 +379,8 @@ operator -> () const NOEXCEPT { * don't care which way it goes because either will be correct. */ template -CONSTEXPR ConstPointerTo:: -operator const T * () const NOEXCEPT { +constexpr ConstPointerTo:: +operator const T * () const noexcept { return (To *)(this->_void_ptr); } @@ -244,8 +402,8 @@ cheat() { * around compiler problems, particularly for implicit upcasts. */ template -CONSTEXPR const TYPENAME ConstPointerTo::To *ConstPointerTo:: -p() const NOEXCEPT { +constexpr const typename ConstPointerTo::To *ConstPointerTo:: +p() const noexcept { return (To *)(this->_void_ptr); } diff --git a/panda/src/express/pointerTo.h b/panda/src/express/pointerTo.h index 62abdf8e57..e9250a2f8a 100644 --- a/panda/src/express/pointerTo.h +++ b/panda/src/express/pointerTo.h @@ -68,22 +68,34 @@ template class PointerTo : public PointerToBase { public: - typedef TYPENAME PointerToBase::To To; + typedef typename PointerToBase::To To; PUBLISHED: - ALWAYS_INLINE_CONSTEXPR PointerTo() NOEXCEPT DEFAULT_CTOR; - ALWAYS_INLINE PointerTo(To *ptr) NOEXCEPT; + ALWAYS_INLINE constexpr PointerTo() noexcept = default; + ALWAYS_INLINE explicit constexpr PointerTo(std::nullptr_t) noexcept {} + ALWAYS_INLINE PointerTo(To *ptr) noexcept; INLINE PointerTo(const PointerTo ©); public: -#ifdef USE_MOVE_SEMANTICS - INLINE PointerTo(PointerTo &&from) NOEXCEPT; - INLINE PointerTo &operator = (PointerTo &&from) NOEXCEPT; -#endif + INLINE PointerTo(PointerTo &&from) noexcept; - CONSTEXPR To &operator *() const NOEXCEPT; - CONSTEXPR To *operator -> () const NOEXCEPT; + template + ALWAYS_INLINE explicit PointerTo(Y *ptr) noexcept; + template + ALWAYS_INLINE PointerTo(const PointerTo &r) noexcept; + template + ALWAYS_INLINE PointerTo(PointerTo &&r) noexcept; + + INLINE PointerTo &operator = (PointerTo &&from) noexcept; + + template + ALWAYS_INLINE PointerTo &operator = (const PointerTo &r) noexcept; + template + ALWAYS_INLINE PointerTo &operator = (PointerTo &&r) noexcept; + + constexpr To &operator *() const noexcept; + constexpr To *operator -> () const noexcept; // MSVC.NET 2005 insists that we use T *, and not To *, here. - CONSTEXPR operator T *() const NOEXCEPT; + constexpr operator T *() const noexcept; INLINE T *&cheat(); @@ -100,7 +112,7 @@ PUBLISHED: // the DCAST macro defined in typedObject.h instead, e.g. DCAST(MyType, // ptr). This provides a clean downcast that doesn't require .p() or any // double-casting, and it can be run-time checked for correctness. - CONSTEXPR To *p() const NOEXCEPT; + constexpr To *p() const noexcept; INLINE PointerTo &operator = (To *ptr); INLINE PointerTo &operator = (const PointerTo ©); @@ -131,29 +143,49 @@ PUBLISHED: template class ConstPointerTo : public PointerToBase { public: - typedef TYPENAME PointerToBase::To To; + typedef typename PointerToBase::To To; PUBLISHED: - ALWAYS_INLINE_CONSTEXPR ConstPointerTo() NOEXCEPT DEFAULT_CTOR; - ALWAYS_INLINE ConstPointerTo(const To *ptr) NOEXCEPT; + ALWAYS_INLINE constexpr ConstPointerTo() noexcept = default; + ALWAYS_INLINE explicit constexpr ConstPointerTo(std::nullptr_t) noexcept {} + ALWAYS_INLINE ConstPointerTo(const To *ptr) noexcept; INLINE ConstPointerTo(const PointerTo ©); INLINE ConstPointerTo(const ConstPointerTo ©); public: -#ifdef USE_MOVE_SEMANTICS - INLINE ConstPointerTo(PointerTo &&from) NOEXCEPT; - INLINE ConstPointerTo(ConstPointerTo &&from) NOEXCEPT; - INLINE ConstPointerTo &operator = (PointerTo &&from) NOEXCEPT; - INLINE ConstPointerTo &operator = (ConstPointerTo &&from) NOEXCEPT; -#endif + INLINE ConstPointerTo(PointerTo &&from) noexcept; + INLINE ConstPointerTo(ConstPointerTo &&from) noexcept; - CONSTEXPR const To &operator *() const NOEXCEPT; - CONSTEXPR const To *operator -> () const NOEXCEPT; - CONSTEXPR operator const T *() const NOEXCEPT; + template + ALWAYS_INLINE explicit ConstPointerTo(const Y *ptr) noexcept; + template + ALWAYS_INLINE ConstPointerTo(const PointerTo &r) noexcept; + template + ALWAYS_INLINE ConstPointerTo(const ConstPointerTo &r) noexcept; + template + ALWAYS_INLINE ConstPointerTo(PointerTo &&r) noexcept; + template + ALWAYS_INLINE ConstPointerTo(ConstPointerTo &&r) noexcept; + + INLINE ConstPointerTo &operator = (PointerTo &&from) noexcept; + INLINE ConstPointerTo &operator = (ConstPointerTo &&from) noexcept; + + template + ALWAYS_INLINE ConstPointerTo &operator = (const PointerTo &r) noexcept; + template + ALWAYS_INLINE ConstPointerTo &operator = (const ConstPointerTo &r) noexcept; + template + ALWAYS_INLINE ConstPointerTo &operator = (PointerTo &&r) noexcept; + template + ALWAYS_INLINE ConstPointerTo &operator = (ConstPointerTo &&r) noexcept; + + constexpr const To &operator *() const noexcept; + constexpr const To *operator -> () const noexcept; + constexpr operator const T *() const noexcept; INLINE const T *&cheat(); PUBLISHED: - CONSTEXPR const To *p() const NOEXCEPT; + constexpr const To *p() const noexcept; INLINE ConstPointerTo &operator = (const To *ptr); INLINE ConstPointerTo &operator = (const PointerTo ©); @@ -173,12 +205,12 @@ PUBLISHED: // PointerTo objects without incurring the cost of unnecessary reference count // changes. The performance difference is dramatic! template -void swap(PointerTo &one, PointerTo &two) NOEXCEPT { +void swap(PointerTo &one, PointerTo &two) noexcept { one.swap(two); } template -void swap(ConstPointerTo &one, ConstPointerTo &two) NOEXCEPT { +void swap(ConstPointerTo &one, ConstPointerTo &two) noexcept { one.swap(two); } diff --git a/panda/src/express/pointerToArray.I b/panda/src/express/pointerToArray.I index 535de63d01..5fb560b695 100644 --- a/panda/src/express/pointerToArray.I +++ b/panda/src/express/pointerToArray.I @@ -25,7 +25,7 @@ pvector ConstPointerToArray::_empty_array; template INLINE PointerToArray:: PointerToArray(TypeHandle type_handle) : - PointerToArrayBase((ReferenceCountedVector *)NULL), + PointerToArrayBase(nullptr), _type_handle(type_handle) { } @@ -79,39 +79,35 @@ PointerToArray(const Element *begin, const Element *end, TypeHandle type_handle) { } -#ifdef USE_MOVE_SEMANTICS /** * */ template INLINE PointerToArray:: -PointerToArray(PointerToArray &&from) NOEXCEPT : - PointerToArrayBase(move(from)), +PointerToArray(PointerToArray &&from) noexcept : + PointerToArrayBase(std::move(from)), _type_handle(from._type_handle) { } -#endif // USE_MOVE_SEMANTICS -#ifdef USE_MOVE_SEMANTICS /** * Initializes the PTA from a vector. */ template INLINE PointerToArray:: PointerToArray(pvector &&from, TypeHandle type_handle) : - PointerToArrayBase(new ReferenceCountedVector(move(from))), + PointerToArrayBase(new ReferenceCountedVector(std::move(from))), _type_handle(type_handle) { } -#endif // USE_MOVE_SEMANTICS /** * */ template -INLINE TYPENAME PointerToArray::iterator PointerToArray:: +INLINE typename PointerToArray::iterator PointerToArray:: begin() const { - if ((this->_void_ptr) == NULL) { + if ((this->_void_ptr) == nullptr) { return _empty_array.begin(); } return ((To *)(this->_void_ptr))->begin(); @@ -121,9 +117,9 @@ begin() const { * */ template -INLINE TYPENAME PointerToArray::iterator PointerToArray:: +INLINE typename PointerToArray::iterator PointerToArray:: end() const { - if ((this->_void_ptr) == NULL) { + if ((this->_void_ptr) == nullptr) { return _empty_array.begin(); } return ((To *)(this->_void_ptr))->end(); @@ -133,9 +129,9 @@ end() const { * */ template -INLINE TYPENAME PointerToArray::reverse_iterator PointerToArray:: +INLINE typename PointerToArray::reverse_iterator PointerToArray:: rbegin() const { - if ((this->_void_ptr) == NULL) { + if ((this->_void_ptr) == nullptr) { return _empty_array.rbegin(); } return ((To *)(this->_void_ptr))->rbegin(); @@ -145,9 +141,9 @@ rbegin() const { * */ template -INLINE TYPENAME PointerToArray::reverse_iterator PointerToArray:: +INLINE typename PointerToArray::reverse_iterator PointerToArray:: rend() const { - if ((this->_void_ptr) == NULL) { + if ((this->_void_ptr) == nullptr) { return _empty_array.rbegin(); } return ((To *)(this->_void_ptr))->rend(); @@ -157,18 +153,18 @@ rend() const { * */ template -INLINE TYPENAME PointerToArray::size_type PointerToArray:: +INLINE typename PointerToArray::size_type PointerToArray:: size() const { - return ((this->_void_ptr) == NULL) ? 0 : ((To *)(this->_void_ptr))->size(); + return ((this->_void_ptr) == nullptr) ? 0 : ((To *)(this->_void_ptr))->size(); } /** * */ template -INLINE TYPENAME PointerToArray::size_type PointerToArray:: +INLINE typename PointerToArray::size_type PointerToArray:: max_size() const { - nassertd((this->_void_ptr) != NULL) { + nassertd((this->_void_ptr) != nullptr) { ((PointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } return ((To *)(this->_void_ptr))->max_size(); @@ -180,7 +176,7 @@ max_size() const { template INLINE bool PointerToArray:: empty() const { - return ((this->_void_ptr) == NULL) ? true : ((To *)(this->_void_ptr))->empty(); + return ((this->_void_ptr) == nullptr) ? true : ((To *)(this->_void_ptr))->empty(); } /** @@ -188,8 +184,8 @@ empty() const { */ template INLINE void PointerToArray:: -reserve(TYPENAME PointerToArray::size_type n) { - if ((this->_void_ptr) == NULL) { +reserve(typename PointerToArray::size_type n) { + if ((this->_void_ptr) == nullptr) { ((PointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } ((To *)(this->_void_ptr))->reserve(n); @@ -200,8 +196,8 @@ reserve(TYPENAME PointerToArray::size_type n) { */ template INLINE void PointerToArray:: -resize(TYPENAME PointerToArray::size_type n) { - if ((this->_void_ptr) == NULL) { +resize(typename PointerToArray::size_type n) { + if ((this->_void_ptr) == nullptr) { ((PointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } ((To *)(this->_void_ptr))->resize(n); @@ -211,9 +207,9 @@ resize(TYPENAME PointerToArray::size_type n) { * */ template -INLINE TYPENAME PointerToArray::size_type PointerToArray:: +INLINE typename PointerToArray::size_type PointerToArray:: capacity() const { - nassertr((this->_void_ptr) != NULL, 0); + nassertr((this->_void_ptr) != nullptr, 0); return ((To *)(this->_void_ptr))->capacity(); } @@ -221,9 +217,9 @@ capacity() const { * */ template -INLINE TYPENAME PointerToArray::reference PointerToArray:: +INLINE typename PointerToArray::reference PointerToArray:: front() const { - nassertd((this->_void_ptr) != NULL) { + nassertd((this->_void_ptr) != nullptr) { ((PointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } nassertd(!((To *)(this->_void_ptr))->empty()) { @@ -236,9 +232,9 @@ front() const { * */ template -INLINE TYPENAME PointerToArray::reference PointerToArray:: +INLINE typename PointerToArray::reference PointerToArray:: back() const { - nassertd((this->_void_ptr) != NULL) { + nassertd((this->_void_ptr) != nullptr) { ((PointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } nassertd(!((To *)(this->_void_ptr))->empty()) { @@ -251,9 +247,9 @@ back() const { * */ template -INLINE TYPENAME PointerToArray::iterator PointerToArray:: +INLINE typename PointerToArray::iterator PointerToArray:: insert(iterator position, const Element &x) { - if ((this->_void_ptr) == NULL) { + if ((this->_void_ptr) == nullptr) { ((PointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); position = end(); } @@ -268,7 +264,7 @@ insert(iterator position, const Element &x) { template INLINE void PointerToArray:: insert(iterator position, size_type n, const Element &x) { - if ((this->_void_ptr) == NULL) { + if ((this->_void_ptr) == nullptr) { ((PointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); position = end(); } @@ -283,7 +279,7 @@ insert(iterator position, size_type n, const Element &x) { template INLINE void PointerToArray:: erase(iterator position) { - nassertv((this->_void_ptr) != NULL); + nassertv((this->_void_ptr) != nullptr); nassertv(position >= ((To *)(this->_void_ptr))->begin() && position <= ((To *)(this->_void_ptr))->end()); ((To *)(this->_void_ptr))->erase(position); @@ -295,7 +291,7 @@ erase(iterator position) { template INLINE void PointerToArray:: erase(iterator first, iterator last) { - nassertv((this->_void_ptr) != NULL); + nassertv((this->_void_ptr) != nullptr); nassertv(first >= ((To *)(this->_void_ptr))->begin() && first <= ((To *)(this->_void_ptr))->end()); nassertv(last >= ((To *)(this->_void_ptr))->begin() && last <= ((To *)(this->_void_ptr))->end()); ((To *)(this->_void_ptr))->erase(first, last); @@ -306,9 +302,9 @@ erase(iterator first, iterator last) { * */ template -INLINE TYPENAME PointerToArray::reference PointerToArray:: +INLINE typename PointerToArray::reference PointerToArray:: operator [](size_type n) const { - nassertd((this->_void_ptr) != NULL) { + nassertd((this->_void_ptr) != nullptr) { ((PointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } nassertd(!((To *)(this->_void_ptr))->empty()) { @@ -322,7 +318,7 @@ operator [](size_type n) const { * */ template -INLINE TYPENAME PointerToArray::reference PointerToArray:: +INLINE typename PointerToArray::reference PointerToArray:: operator [](int n) const { return operator[]((size_type)n); } @@ -334,7 +330,7 @@ operator [](int n) const { template INLINE void PointerToArray:: push_back(const Element &x) { - if ((this->_void_ptr) == NULL) { + if ((this->_void_ptr) == nullptr) { ((PointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } ((To *)(this->_void_ptr))->push_back(x); @@ -346,7 +342,7 @@ push_back(const Element &x) { template INLINE void PointerToArray:: pop_back() { - nassertd((this->_void_ptr) != NULL) { + nassertd((this->_void_ptr) != nullptr) { ((PointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } nassertv(!((To *)(this->_void_ptr))->empty()); @@ -360,7 +356,7 @@ pop_back() { template INLINE void PointerToArray:: make_empty() { - nassertd((this->_void_ptr) != NULL) { + nassertd((this->_void_ptr) != nullptr) { ((PointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } nassertv(!((To *)(this->_void_ptr))->empty()); @@ -377,7 +373,7 @@ template INLINE PointerToArray:: operator Element *() const { To *vec = (To *)(this->_void_ptr); - return ((vec == NULL)||(vec->empty())) ? (Element *)NULL : &(vec->front()); + return ((vec == nullptr)||(vec->empty())) ? nullptr : &(vec->front()); } /** @@ -388,7 +384,7 @@ template INLINE Element *PointerToArray:: p() const { To *vec = (To *)(this->_void_ptr); - return ((vec == NULL)||(vec->empty())) ? (Element *)NULL : &(vec->front()); + return ((vec == nullptr)||(vec->empty())) ? nullptr : &(vec->front()); } /** @@ -398,7 +394,7 @@ p() const { template INLINE pvector &PointerToArray:: v() const { - if ((this->_void_ptr) == NULL) { + if ((this->_void_ptr) == nullptr) { ((PointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } return *((To *)(this->_void_ptr)); @@ -447,7 +443,7 @@ set_element(size_type n, const Element &value) { * string. */ template -INLINE string PointerToArray:: +INLINE std::string PointerToArray:: get_data() const { return get_subdata(0, size()); } @@ -461,7 +457,7 @@ get_data() const { */ template INLINE void PointerToArray:: -set_data(const string &data) { +set_data(const std::string &data) { set_subdata(0, size(), data); } @@ -473,12 +469,12 @@ set_data(const string &data) { * through element (n + count - 1)--as a block of raw data in a string. */ template -INLINE string PointerToArray:: +INLINE std::string PointerToArray:: get_subdata(size_type n, size_type count) const { - n = min(n, size()); - count = max(count, n); - count = min(count, size() - n); - return string((const char *)(p() + n), sizeof(Element) * count); + n = std::min(n, size()); + count = std::max(count, n); + count = std::min(count, size() - n); + return std::string((const char *)(p() + n), sizeof(Element) * count); } /** @@ -493,10 +489,10 @@ get_subdata(size_type n, size_type count) const { */ template INLINE void PointerToArray:: -set_subdata(size_type n, size_type count, const string &data) { +set_subdata(size_type n, size_type count, const std::string &data) { nassertv((data.length() % sizeof(Element)) == 0); nassertv(n <= size() && n + count <= size()); - if ((this->_void_ptr) == NULL) { + if ((this->_void_ptr) == nullptr) { ((PointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } size_type ncount = data.length() / sizeof(Element); @@ -538,7 +534,7 @@ set_void_ptr(void *p) { template INLINE int PointerToArray:: get_ref_count() const { - return ((this->_void_ptr) == NULL) ? 0 : ((To *)(this->_void_ptr))->get_ref_count(); + return ((this->_void_ptr) == nullptr) ? 0 : ((To *)(this->_void_ptr))->get_ref_count(); } /** @@ -547,7 +543,7 @@ get_ref_count() const { template INLINE void PointerToArray:: ref() const { - if ((this->_void_ptr) == NULL) { + if ((this->_void_ptr) == nullptr) { ((PointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } ((To *)(this->_void_ptr))->ref(); @@ -559,7 +555,7 @@ ref() const { template INLINE bool PointerToArray:: unref() const { - nassertr((this->_void_ptr) != NULL, true); + nassertr((this->_void_ptr) != nullptr, true); return ((To *)(this->_void_ptr))->unref(); } @@ -569,7 +565,7 @@ unref() const { template INLINE int PointerToArray:: get_node_ref_count() const { - return ((this->_void_ptr) == NULL) ? 0 : ((To *)(this->_void_ptr))->get_node_ref_count(); + return ((this->_void_ptr) == nullptr) ? 0 : ((To *)(this->_void_ptr))->get_node_ref_count(); } /** @@ -578,7 +574,7 @@ get_node_ref_count() const { template INLINE void PointerToArray:: node_ref() const { - if ((this->_void_ptr) == NULL) { + if ((this->_void_ptr) == nullptr) { ((PointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } ((To *)(this->_void_ptr))->node_ref(); @@ -590,7 +586,7 @@ node_ref() const { template INLINE bool PointerToArray:: node_unref() const { - nassertr((this->_void_ptr) != NULL, true); + nassertr((this->_void_ptr) != nullptr, true); return ((To *)(this->_void_ptr))->node_unref(); } @@ -628,18 +624,16 @@ operator = (const PointerToArray ©) { return *this; } -#ifdef USE_MOVE_SEMANTICS /** * */ template INLINE PointerToArray &PointerToArray:: -operator = (PointerToArray &&from) NOEXCEPT { +operator = (PointerToArray &&from) noexcept { _type_handle = from._type_handle; - ((PointerToArray *)this)->reassign(move(from)); + ((PointerToArray *)this)->reassign(std::move(from)); return *this; } -#endif // USE_MOVE_SEMANTICS /** * To empty the PTA, use the clear() method, since assignment to NULL is @@ -648,7 +642,7 @@ operator = (PointerToArray &&from) NOEXCEPT { template INLINE void PointerToArray:: clear() { - ((PointerToArray *)this)->reassign((ReferenceCountedVector *)NULL); + ((PointerToArray *)this)->reassign(nullptr); } @@ -659,7 +653,7 @@ clear() { template INLINE ConstPointerToArray:: ConstPointerToArray(TypeHandle type_handle) : - PointerToArrayBase((ReferenceCountedVector *)NULL), + PointerToArrayBase(nullptr), _type_handle(type_handle) { } @@ -697,52 +691,46 @@ ConstPointerToArray(const ConstPointerToArray ©) : { } -#ifdef USE_MOVE_SEMANTICS /** * */ template INLINE ConstPointerToArray:: -ConstPointerToArray(PointerToArray &&from) NOEXCEPT : - PointerToArrayBase(move(from)), +ConstPointerToArray(PointerToArray &&from) noexcept : + PointerToArrayBase(std::move(from)), _type_handle(from._type_handle) { } -#endif // USE_MOVE_SEMANTICS -#ifdef USE_MOVE_SEMANTICS /** * */ template INLINE ConstPointerToArray:: -ConstPointerToArray(ConstPointerToArray &&from) NOEXCEPT : - PointerToArrayBase(move(from)), +ConstPointerToArray(ConstPointerToArray &&from) noexcept : + PointerToArrayBase(std::move(from)), _type_handle(from._type_handle) { } -#endif // USE_MOVE_SEMANTICS -#ifdef USE_MOVE_SEMANTICS /** * Initializes the PTA from a vector. */ template INLINE ConstPointerToArray:: ConstPointerToArray(pvector &&from, TypeHandle type_handle) : - PointerToArrayBase(new ReferenceCountedVector(move(from))), + PointerToArrayBase(new ReferenceCountedVector(std::move(from))), _type_handle(type_handle) { } -#endif // USE_MOVE_SEMANTICS /** * */ template -INLINE TYPENAME ConstPointerToArray::iterator ConstPointerToArray:: +INLINE typename ConstPointerToArray::iterator ConstPointerToArray:: begin() const { - if ((this->_void_ptr) == NULL) { + if ((this->_void_ptr) == nullptr) { return _empty_array.begin(); } return ((To *)(this->_void_ptr))->begin(); @@ -752,9 +740,9 @@ begin() const { * */ template -INLINE TYPENAME ConstPointerToArray::iterator ConstPointerToArray:: +INLINE typename ConstPointerToArray::iterator ConstPointerToArray:: end() const { - if ((this->_void_ptr) == NULL) { + if ((this->_void_ptr) == nullptr) { return _empty_array.begin(); } return ((To *)(this->_void_ptr))->end(); @@ -764,9 +752,9 @@ end() const { * */ template -INLINE TYPENAME ConstPointerToArray::reverse_iterator ConstPointerToArray:: +INLINE typename ConstPointerToArray::reverse_iterator ConstPointerToArray:: rbegin() const { - if ((this->_void_ptr) == NULL) { + if ((this->_void_ptr) == nullptr) { return _empty_array.rbegin(); } return ((To *)(this->_void_ptr))->rbegin(); @@ -776,9 +764,9 @@ rbegin() const { * */ template -INLINE TYPENAME ConstPointerToArray::reverse_iterator ConstPointerToArray:: +INLINE typename ConstPointerToArray::reverse_iterator ConstPointerToArray:: rend() const { - if ((this->_void_ptr) == NULL) { + if ((this->_void_ptr) == nullptr) { return _empty_array.rbegin(); } return ((To *)(this->_void_ptr))->rend(); @@ -788,18 +776,18 @@ rend() const { * */ template -INLINE TYPENAME ConstPointerToArray::size_type ConstPointerToArray:: +INLINE typename ConstPointerToArray::size_type ConstPointerToArray:: size() const { - return ((this->_void_ptr) == NULL) ? 0 : ((To *)(this->_void_ptr))->size(); + return ((this->_void_ptr) == nullptr) ? 0 : ((To *)(this->_void_ptr))->size(); } /** * */ template -INLINE TYPENAME ConstPointerToArray::size_type ConstPointerToArray:: +INLINE typename ConstPointerToArray::size_type ConstPointerToArray:: max_size() const { - nassertd((this->_void_ptr) != NULL) { + nassertd((this->_void_ptr) != nullptr) { ((ConstPointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } return ((To *)(this->_void_ptr))->max_size(); @@ -811,16 +799,16 @@ max_size() const { template INLINE bool ConstPointerToArray:: empty() const { - return ((this->_void_ptr) == NULL) ? true : ((To *)(this->_void_ptr))->empty(); + return ((this->_void_ptr) == nullptr) ? true : ((To *)(this->_void_ptr))->empty(); } /** * */ template -INLINE TYPENAME ConstPointerToArray::size_type ConstPointerToArray:: +INLINE typename ConstPointerToArray::size_type ConstPointerToArray:: capacity() const { - nassertd((this->_void_ptr) != NULL) { + nassertd((this->_void_ptr) != nullptr) { ((ConstPointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } return ((To *)(this->_void_ptr))->capacity(); @@ -830,9 +818,9 @@ capacity() const { * */ template -INLINE TYPENAME ConstPointerToArray::reference ConstPointerToArray:: +INLINE typename ConstPointerToArray::reference ConstPointerToArray:: front() const { - nassertd((this->_void_ptr) != NULL) { + nassertd((this->_void_ptr) != nullptr) { ((ConstPointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } nassertd(!((To *)(this->_void_ptr))->empty()) { @@ -845,9 +833,9 @@ front() const { * */ template -INLINE TYPENAME ConstPointerToArray::reference ConstPointerToArray:: +INLINE typename ConstPointerToArray::reference ConstPointerToArray:: back() const { - nassertd((this->_void_ptr) != NULL) { + nassertd((this->_void_ptr) != nullptr) { ((ConstPointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } nassertd(!((To *)(this->_void_ptr))->empty()) { @@ -861,9 +849,9 @@ back() const { * */ template -INLINE TYPENAME ConstPointerToArray::reference ConstPointerToArray:: +INLINE typename ConstPointerToArray::reference ConstPointerToArray:: operator [](size_type n) const { - nassertd((this->_void_ptr) != NULL) { + nassertd((this->_void_ptr) != nullptr) { ((ConstPointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } nassertd(!((To *)(this->_void_ptr))->empty()) { @@ -877,7 +865,7 @@ operator [](size_type n) const { * */ template -INLINE TYPENAME ConstPointerToArray::reference ConstPointerToArray:: +INLINE typename ConstPointerToArray::reference ConstPointerToArray:: operator [](int n) const { return operator[]((size_type)n); } @@ -893,7 +881,7 @@ template INLINE ConstPointerToArray:: operator const Element *() const { const To *vec = (const To *)(this->_void_ptr); - return ((vec == NULL)||(vec->empty())) ? (const Element *)NULL : &(vec->front()); + return ((vec == nullptr)||(vec->empty())) ? nullptr : &(vec->front()); } /** @@ -904,7 +892,7 @@ template INLINE const Element *ConstPointerToArray:: p() const { const To *vec = (const To *)(this->_void_ptr); - return ((vec == NULL)||(vec->empty())) ? (const Element *)NULL : &(vec->front()); + return ((vec == nullptr)||(vec->empty())) ? nullptr : &(vec->front()); } /** @@ -914,7 +902,7 @@ p() const { template INLINE const pvector &ConstPointerToArray:: v() const { - nassertd((this->_void_ptr) != NULL) { + nassertd((this->_void_ptr) != nullptr) { ((ConstPointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } return *(const To *)(this->_void_ptr); @@ -962,7 +950,7 @@ get_element(size_type n) const { * string. */ template -INLINE string ConstPointerToArray:: +INLINE std::string ConstPointerToArray:: get_data() const { return get_subdata(0, size()); } @@ -975,12 +963,12 @@ get_data() const { * through element (n + count - 1)--as a block of raw data in a string. */ template -INLINE string ConstPointerToArray:: +INLINE std::string ConstPointerToArray:: get_subdata(size_type n, size_type count) const { - n = min(n, size()); - count = max(count, n); - count = min(count, size() - n); - return string((const char *)(p() + n), sizeof(Element) * count); + n = std::min(n, size()); + count = std::max(count, n); + count = std::min(count, size() - n); + return std::string((const char *)(p() + n), sizeof(Element) * count); } /** @@ -989,7 +977,7 @@ get_subdata(size_type n, size_type count) const { template INLINE int ConstPointerToArray:: get_ref_count() const { - return ((this->_void_ptr) == NULL) ? 0 : ((To *)(this->_void_ptr))->get_ref_count(); + return ((this->_void_ptr) == nullptr) ? 0 : ((To *)(this->_void_ptr))->get_ref_count(); } /** @@ -998,7 +986,7 @@ get_ref_count() const { template INLINE void ConstPointerToArray:: ref() const { - if ((this->_void_ptr) == NULL) { + if ((this->_void_ptr) == nullptr) { ((ConstPointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } ((To *)(this->_void_ptr))->ref(); @@ -1010,7 +998,7 @@ ref() const { template INLINE bool ConstPointerToArray:: unref() const { - nassertr((this->_void_ptr) != NULL, true); + nassertr((this->_void_ptr) != nullptr, true); return ((To *)(this->_void_ptr))->unref(); } @@ -1020,7 +1008,7 @@ unref() const { template INLINE int ConstPointerToArray:: get_node_ref_count() const { - return ((this->_void_ptr) == NULL) ? 0 : ((To *)(this->_void_ptr))->get_node_ref_count(); + return ((this->_void_ptr) == nullptr) ? 0 : ((To *)(this->_void_ptr))->get_node_ref_count(); } /** @@ -1029,7 +1017,7 @@ get_node_ref_count() const { template INLINE void ConstPointerToArray:: node_ref() const { - if ((this->_void_ptr) == NULL) { + if ((this->_void_ptr) == nullptr) { ((ConstPointerToArray *)this)->reassign(new ReferenceCountedVector(_type_handle)); } ((To *)(this->_void_ptr))->node_ref(); @@ -1041,7 +1029,7 @@ node_ref() const { template INLINE bool ConstPointerToArray:: node_unref() const { - nassertr((this->_void_ptr) != NULL, true); + nassertr((this->_void_ptr) != nullptr, true); return ((To *)(this->_void_ptr))->node_unref(); } @@ -1090,31 +1078,27 @@ operator = (const ConstPointerToArray ©) { return *this; } -#ifdef USE_MOVE_SEMANTICS /** * */ template INLINE ConstPointerToArray &ConstPointerToArray:: -operator = (PointerToArray &&from) NOEXCEPT { +operator = (PointerToArray &&from) noexcept { _type_handle = from._type_handle; - ((ConstPointerToArray *)this)->reassign(move(from)); + ((ConstPointerToArray *)this)->reassign(std::move(from)); return *this; } -#endif // USE_MOVE_SEMANTICS -#ifdef USE_MOVE_SEMANTICS /** * */ template INLINE ConstPointerToArray &ConstPointerToArray:: -operator = (ConstPointerToArray &&from) NOEXCEPT { +operator = (ConstPointerToArray &&from) noexcept { _type_handle = from._type_handle; - ((ConstPointerToArray *)this)->reassign(move(from)); + ((ConstPointerToArray *)this)->reassign(std::move(from)); return *this; } -#endif // USE_MOVE_SEMANTICS /** * To empty the PTA, use the clear() method, since assignment to NULL is @@ -1123,7 +1107,7 @@ operator = (ConstPointerToArray &&from) NOEXCEPT { template INLINE void ConstPointerToArray:: clear() { - ((ConstPointerToArray *)this)->reassign((ReferenceCountedVector *)NULL); + ((ConstPointerToArray *)this)->reassign(nullptr); } #endif // CPPPARSER diff --git a/panda/src/express/pointerToArray.h b/panda/src/express/pointerToArray.h index 4e8a052e0f..7ff07a5ef1 100644 --- a/panda/src/express/pointerToArray.h +++ b/panda/src/express/pointerToArray.h @@ -91,13 +91,15 @@ public: // subset of this class. So we define just the exportable interface here. #ifdef CPPPARSER PUBLISHED: - typedef TYPENAME pvector::size_type size_type; + typedef typename pvector::size_type size_type; INLINE PointerToArray(TypeHandle type_handle = get_type_handle(Element)); INLINE static PointerToArray empty_array(size_type n, TypeHandle type_handle = get_type_handle(Element)); INLINE PointerToArray(const PointerToArray ©); EXTENSION(PointerToArray(PyObject *self, PyObject *source)); + INLINE void clear(); + INLINE size_type size() const; INLINE void push_back(const Element &x); INLINE void pop_back(); @@ -108,7 +110,7 @@ PUBLISHED: EXTENSION(PyObject *get_data() const); EXTENSION(void set_data(PyObject *data)); EXTENSION(PyObject *get_subdata(size_type n, size_type count) const); - INLINE void set_subdata(size_type n, size_type count, const string &data); + INLINE void set_subdata(size_type n, size_type count, const std::string &data); INLINE int get_ref_count() const; INLINE int get_node_ref_count() const; @@ -121,16 +123,16 @@ PUBLISHED: #else // CPPPARSER // This is the actual, complete interface. - typedef TYPENAME PointerToArrayBase::To To; - typedef TYPENAME pvector::value_type value_type; - typedef TYPENAME pvector::reference reference; - typedef TYPENAME pvector::const_reference const_reference; - typedef TYPENAME pvector::iterator iterator; - typedef TYPENAME pvector::const_iterator const_iterator; - typedef TYPENAME pvector::reverse_iterator reverse_iterator; - typedef TYPENAME pvector::const_reverse_iterator const_reverse_iterator; - typedef TYPENAME pvector::difference_type difference_type; - typedef TYPENAME pvector::size_type size_type; + typedef typename PointerToArrayBase::To To; + typedef typename pvector::value_type value_type; + typedef typename pvector::reference reference; + typedef typename pvector::const_reference const_reference; + typedef typename pvector::iterator iterator; + typedef typename pvector::const_iterator const_iterator; + typedef typename pvector::reverse_iterator reverse_iterator; + typedef typename pvector::const_reverse_iterator const_reverse_iterator; + typedef typename pvector::difference_type difference_type; + typedef typename pvector::size_type size_type; public: INLINE PointerToArray(TypeHandle type_handle = get_type_handle(Element)); @@ -138,11 +140,8 @@ public: INLINE PointerToArray(size_type n, const Element &value, TypeHandle type_handle = get_type_handle(Element)); INLINE PointerToArray(const Element *begin, const Element *end, TypeHandle type_handle = get_type_handle(Element)); INLINE PointerToArray(const PointerToArray ©); - -#ifdef USE_MOVE_SEMANTICS - INLINE PointerToArray(PointerToArray &&from) NOEXCEPT; + INLINE PointerToArray(PointerToArray &&from) noexcept; INLINE explicit PointerToArray(pvector &&from, TypeHandle type_handle = get_type_handle(Element)); -#endif public: // Duplicating the interface of vector. The following member functions are @@ -151,8 +150,8 @@ public: INLINE iterator begin() const; INLINE iterator end() const; - INLINE TYPENAME PointerToArray::reverse_iterator rbegin() const; - INLINE TYPENAME PointerToArray::reverse_iterator rend() const; + INLINE typename PointerToArray::reverse_iterator rbegin() const; + INLINE typename PointerToArray::reverse_iterator rend() const; // Equality and comparison operators are pointerwise for PointerToArrays, // not elementwise as in vector. @@ -160,6 +159,8 @@ public: INLINE size_type max_size() const; INLINE bool empty() const; + INLINE void clear(); + // Functions specific to vectors. INLINE void reserve(size_type n); INLINE void resize(size_type n); @@ -195,10 +196,10 @@ public: // Methods to help out Python and other high-level languages. INLINE const Element &get_element(size_type n) const; INLINE void set_element(size_type n, const Element &value); - INLINE string get_data() const; - INLINE void set_data(const string &data); - INLINE string get_subdata(size_type n, size_type count) const; - INLINE void set_subdata(size_type n, size_type count, const string &data); + INLINE std::string get_data() const; + INLINE void set_data(const std::string &data); + INLINE std::string get_subdata(size_type n, size_type count) const; + INLINE void set_subdata(size_type n, size_type count, const std::string &data); // These functions are only to be used in Reading through BamReader. They // are designed to work in pairs, so that you register what is returned by @@ -219,29 +220,25 @@ public: INLINE size_t count(const Element &) const; +#endif // CPPPARSER + +public: // Reassignment is by pointer, not memberwise as with a vector. INLINE PointerToArray & operator = (ReferenceCountedVector *ptr); INLINE PointerToArray & operator = (const PointerToArray ©); - -#ifdef USE_MOVE_SEMANTICS INLINE PointerToArray & - operator = (PointerToArray &&from) NOEXCEPT; -#endif - - INLINE void clear(); + operator = (PointerToArray &&from) noexcept; private: TypeHandle _type_handle; -private: // This static empty array is kept around just so we can return something // meaningful when begin() or end() is called and we have a NULL pointer. // It might not be shared properly between different .so's, since it's a // static member of a template class, but we don't really care. static pvector _empty_array; -#endif // CPPPARSER friend class ConstPointerToArray; }; @@ -262,7 +259,9 @@ PUBLISHED: INLINE ConstPointerToArray(const PointerToArray ©); INLINE ConstPointerToArray(const ConstPointerToArray ©); - typedef TYPENAME pvector::size_type size_type; + INLINE void clear(); + + typedef typename pvector::size_type size_type; INLINE size_type size() const; INLINE const Element &get_element(size_type n) const; EXTENSION(const Element &__getitem__(size_type n) const); @@ -280,38 +279,35 @@ PUBLISHED: #else // CPPPARSER // This is the actual, complete interface. - typedef TYPENAME PointerToArrayBase::To To; - typedef TYPENAME pvector::value_type value_type; - typedef TYPENAME pvector::const_reference reference; - typedef TYPENAME pvector::const_reference const_reference; - typedef TYPENAME pvector::const_iterator iterator; - typedef TYPENAME pvector::const_iterator const_iterator; + typedef typename PointerToArrayBase::To To; + typedef typename pvector::value_type value_type; + typedef typename pvector::const_reference reference; + typedef typename pvector::const_reference const_reference; + typedef typename pvector::const_iterator iterator; + typedef typename pvector::const_iterator const_iterator; #if defined(WIN32_VC) || defined(WIN64_VC) // VC++ seems to break the const_reverse_iterator definition somehow. - typedef TYPENAME pvector::reverse_iterator reverse_iterator; + typedef typename pvector::reverse_iterator reverse_iterator; #else - typedef TYPENAME pvector::const_reverse_iterator reverse_iterator; + typedef typename pvector::const_reverse_iterator reverse_iterator; #endif - typedef TYPENAME pvector::const_reverse_iterator const_reverse_iterator; - typedef TYPENAME pvector::difference_type difference_type; - typedef TYPENAME pvector::size_type size_type; + typedef typename pvector::const_reverse_iterator const_reverse_iterator; + typedef typename pvector::difference_type difference_type; + typedef typename pvector::size_type size_type; INLINE ConstPointerToArray(const Element *begin, const Element *end, TypeHandle type_handle = get_type_handle(Element)); INLINE ConstPointerToArray(const PointerToArray ©); INLINE ConstPointerToArray(const ConstPointerToArray ©); - -#ifdef USE_MOVE_SEMANTICS - INLINE ConstPointerToArray(PointerToArray &&from) NOEXCEPT; - INLINE ConstPointerToArray(ConstPointerToArray &&from) NOEXCEPT; + INLINE ConstPointerToArray(PointerToArray &&from) noexcept; + INLINE ConstPointerToArray(ConstPointerToArray &&from) noexcept; INLINE explicit ConstPointerToArray(pvector &&from, TypeHandle type_handle = get_type_handle(Element)); -#endif // Duplicating the interface of vector. INLINE iterator begin() const; INLINE iterator end() const; - INLINE TYPENAME ConstPointerToArray::reverse_iterator rbegin() const; - INLINE TYPENAME ConstPointerToArray::reverse_iterator rend() const; + INLINE typename ConstPointerToArray::reverse_iterator rbegin() const; + INLINE typename ConstPointerToArray::reverse_iterator rend() const; // Equality and comparison operators are pointerwise for PointerToArrays, // not elementwise as in vector. @@ -320,6 +316,8 @@ PUBLISHED: INLINE size_type max_size() const; INLINE bool empty() const; + INLINE void clear(); + // Functions specific to vectors. INLINE size_type capacity() const; INLINE reference front() const; @@ -338,8 +336,8 @@ PUBLISHED: // Methods to help out Python and other high-level languages. INLINE const Element &get_element(size_type n) const; - INLINE string get_data() const; - INLINE string get_subdata(size_type n, size_type count) const; + INLINE std::string get_data() const; + INLINE std::string get_subdata(size_type n, size_type count) const; INLINE int get_ref_count() const; INLINE void ref() const; @@ -351,6 +349,9 @@ PUBLISHED: INLINE size_t count(const Element &) const; +#endif // CPPPARSER + +public: // Reassignment is by pointer, not memberwise as with a vector. INLINE ConstPointerToArray & operator = (ReferenceCountedVector *ptr); @@ -358,26 +359,19 @@ PUBLISHED: operator = (const PointerToArray ©); INLINE ConstPointerToArray & operator = (const ConstPointerToArray ©); - -#ifdef USE_MOVE_SEMANTICS INLINE ConstPointerToArray & - operator = (PointerToArray &&from) NOEXCEPT; + operator = (PointerToArray &&from) noexcept; INLINE ConstPointerToArray & - operator = (ConstPointerToArray &&from) NOEXCEPT; -#endif - - INLINE void clear(); + operator = (ConstPointerToArray &&from) noexcept; private: TypeHandle _type_handle; -private: // This static empty array is kept around just so we can return something // meangful when begin() or end() is called and we have a NULL pointer. It // might not be shared properly between different .so's, since it's a static // member of a template class, but we don't really care. static pvector _empty_array; -#endif // CPPPARSER friend class PointerToArray; }; diff --git a/panda/src/express/pointerToArrayBase.I b/panda/src/express/pointerToArrayBase.I index de8c17d843..d22b113ac5 100644 --- a/panda/src/express/pointerToArrayBase.I +++ b/panda/src/express/pointerToArrayBase.I @@ -24,7 +24,7 @@ ReferenceCountedVector(TypeHandle type_handle) : pvector(type_handle) { */ template INLINE ReferenceCountedVector:: -ReferenceCountedVector(TYPENAME ReferenceCountedVector::size_type initial_size, TypeHandle type_handle) : +ReferenceCountedVector(typename ReferenceCountedVector::size_type initial_size, TypeHandle type_handle) : pvector(initial_size, type_handle) { } @@ -45,7 +45,7 @@ ReferenceCountedVector(const Element *begin, const Element *end, TypeHandle type template INLINE ReferenceCountedVector:: ReferenceCountedVector(pvector &&from) : - pvector(move(from)) + pvector(std::move(from)) { } @@ -53,7 +53,7 @@ ReferenceCountedVector(pvector &&from) : * */ template -INLINE TYPENAME ReferenceCountedVector::size_type ReferenceCountedVector:: +INLINE typename ReferenceCountedVector::size_type ReferenceCountedVector:: size() const { return pvector::size(); } @@ -62,7 +62,7 @@ size() const { * */ template -INLINE TYPENAME ReferenceCountedVector::iterator ReferenceCountedVector:: +INLINE typename ReferenceCountedVector::iterator ReferenceCountedVector:: insert(iterator position, const Element &x) { return pvector::insert(position, x); } @@ -132,17 +132,15 @@ PointerToArrayBase(const PointerToArrayBase ©) : { } -#ifdef USE_MOVE_SEMANTICS /** * */ template INLINE PointerToArrayBase:: -PointerToArrayBase(PointerToArrayBase &&from) NOEXCEPT : - PointerToBase >(move(from)) +PointerToArrayBase(PointerToArrayBase &&from) noexcept : + PointerToBase >(std::move(from)) { } -#endif // USE_MOVE_SEMANTICS /** * diff --git a/panda/src/express/pointerToArrayBase.cxx b/panda/src/express/pointerToArrayBase.cxx index 86366ae892..4faeda50bf 100644 --- a/panda/src/express/pointerToArrayBase.cxx +++ b/panda/src/express/pointerToArrayBase.cxx @@ -13,4 +13,4 @@ #include "pointerToArrayBase.h" -EXPCL_PANDAEXPRESS PTASetLevelFunc *pta_set_level = NULL; +EXPCL_PANDA_EXPRESS PTASetLevelFunc *pta_set_level = nullptr; diff --git a/panda/src/express/pointerToArrayBase.h b/panda/src/express/pointerToArrayBase.h index 8c33f69be2..3c985ff379 100644 --- a/panda/src/express/pointerToArrayBase.h +++ b/panda/src/express/pointerToArrayBase.h @@ -37,8 +37,8 @@ template class ReferenceCountedVector : public NodeReferenceCount, public pvector { public: - typedef TYPENAME pvector::iterator iterator; - typedef TYPENAME pvector::size_type size_type; + typedef typename pvector::iterator iterator; + typedef typename pvector::size_type size_type; INLINE ReferenceCountedVector(TypeHandle type_handle); INLINE ReferenceCountedVector(size_type initial_size, TypeHandle type_handle); @@ -68,15 +68,12 @@ public: template class PointerToArrayBase : public PointerToBase > { public: - typedef TYPENAME PointerToBase >::To To; + typedef typename PointerToBase >::To To; protected: INLINE PointerToArrayBase(ReferenceCountedVector *ptr); INLINE PointerToArrayBase(const PointerToArrayBase ©); - -#ifdef USE_MOVE_SEMANTICS - INLINE PointerToArrayBase(PointerToArrayBase &&from) NOEXCEPT; -#endif + INLINE PointerToArrayBase(PointerToArrayBase &&from) noexcept; PUBLISHED: INLINE ~PointerToArrayBase(); diff --git a/panda/src/express/pointerToArray_ext.I b/panda/src/express/pointerToArray_ext.I index 644b5f0645..ee4c10e155 100644 --- a/panda/src/express/pointerToArray_ext.I +++ b/panda/src/express/pointerToArray_ext.I @@ -37,17 +37,19 @@ INLINE void set_matrix_view(Py_buffer &view, int flags, int length, int size, bo mat_size = sizeof(UnalignedLMatrix4f); } else if (size == 4 && double_prec) { mat_size = sizeof(UnalignedLMatrix4d); + } else { + assert(false); } view.len = length * mat_size; view.readonly = (read_only ? 1 : 0); view.itemsize = item_size; - view.format = NULL; + view.format = nullptr; if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) { view.format = (char*) format; } view.ndim = 3; - view.shape = NULL; + view.shape = nullptr; if ((flags & PyBUF_ND) == PyBUF_ND) { // This leaks, which sucks, but __releasebuffer__ doesn't give us the same // pointer, so we would need to store it elsewhere if we wanted to delete @@ -58,7 +60,7 @@ INLINE void set_matrix_view(Py_buffer &view, int flags, int length, int size, bo shape[2] = size; view.shape = shape; } - view.strides = NULL; + view.strides = nullptr; if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) { Py_ssize_t* strides = new Py_ssize_t[3]; strides[0] = mat_size; @@ -66,7 +68,7 @@ INLINE void set_matrix_view(Py_buffer &view, int flags, int length, int size, bo strides[2] = item_size; view.strides = strides; } - view.suboffsets = NULL; + view.suboffsets = nullptr; } /** @@ -99,7 +101,7 @@ __init__(PyObject *self, PyObject *source) { // from Python. PyObject *dict = DtoolInstance_TYPE(self)->_PyType.tp_dict; PyObject *push_back = PyDict_GetItemString(dict, "push_back"); - if (push_back == NULL) { + if (push_back == nullptr) { PyErr_BadArgument(); return; } @@ -111,12 +113,12 @@ __init__(PyObject *self, PyObject *source) { this->_this->reserve(size); for (Py_ssize_t i = 0; i < size; ++i) { PyObject *item = PySequence_GetItem(source, i); - if (item == NULL) { + if (item == nullptr) { return; } - PyObject *result = PyObject_CallFunctionObjArgs(push_back, self, item, NULL); + PyObject *result = PyObject_CallFunctionObjArgs(push_back, self, item, nullptr); Py_DECREF(item); - if (result == NULL) { + if (result == nullptr) { // Unable to add item--probably it wasn't of the appropriate type. PyErr_Print(); PyErr_Format(PyExc_TypeError, @@ -246,9 +248,9 @@ set_data(PyObject *data) { template INLINE PyObject *Extension >:: get_subdata(size_t n, size_t count) const { - n = min(n, this->_this->size()); - count = max(count, n); - count = min(count, this->_this->size() - n); + n = std::min(n, this->_this->size()); + count = std::max(count, n); + count = std::min(count, this->_this->size() - n); #if PY_MAJOR_VERSION >= 3 return PyBytes_FromStringAndSize((char *)(this->_this->p() + n), sizeof(Element) * count); #else @@ -291,9 +293,9 @@ get_data() const { template INLINE PyObject *Extension >:: get_subdata(size_t n, size_t count) const { - n = min(n, this->_this->size()); - count = max(count, n); - count = min(count, this->_this->size() - n); + n = std::min(n, this->_this->size()); + count = std::max(count, n); + count = std::min(count, this->_this->size() - n); #if PY_MAJOR_VERSION >= 3 return PyBytes_FromStringAndSize((char *)(this->_this->p() + n), sizeof(Element) * count); #else @@ -310,12 +312,12 @@ INLINE int Extension >:: __getbuffer__(PyObject *self, Py_buffer *view, int flags) { #if PY_VERSION_HEX >= 0x02060000 const char *format = get_format_code(Element); - if (format == NULL) { + if (format == nullptr) { // Not supported. return -1; } - if (self != NULL) { + if (self != nullptr) { Py_INCREF(self); } view->obj = self; @@ -323,23 +325,23 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) { view->len = this->_this->size() * sizeof(Element); view->readonly = 0; view->itemsize = sizeof(Element); - view->format = NULL; + view->format = nullptr; if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) { view->format = (char*) format; } view->ndim = 1; - view->shape = NULL; + view->shape = nullptr; if ((flags & PyBUF_ND) == PyBUF_ND) { // This leaks, which sucks, but __releasebuffer__ doesn't give us the same // pointer, so we would need to store it elsewhere if we wanted to delete // it there. Eh, it's just an int, who cares. view->shape = new Py_ssize_t(this->_this->size()); } - view->strides = NULL; + view->strides = nullptr; if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) { view->strides = &(view->itemsize); } - view->suboffsets = NULL; + view->suboffsets = nullptr; // Store a reference to ourselves on the Py_buffer object as a reminder that // we have increased our refcount. @@ -360,7 +362,7 @@ template<> INLINE int Extension >:: __getbuffer__(PyObject *self, Py_buffer *view, int flags) { #if PY_VERSION_HEX >= 0x02060000 - if (self != NULL) { + if (self != nullptr) { Py_INCREF(self); } view->obj = self; @@ -386,7 +388,7 @@ template<> INLINE int Extension >:: __getbuffer__(PyObject *self, Py_buffer *view, int flags) { #if PY_VERSION_HEX >= 0x02060000 - if (self != NULL) { + if (self != nullptr) { Py_INCREF(self); } view->obj = self; @@ -412,7 +414,7 @@ template<> INLINE int Extension >:: __getbuffer__(PyObject *self, Py_buffer *view, int flags) { #if PY_VERSION_HEX >= 0x02060000 - if (self != NULL) { + if (self != nullptr) { Py_INCREF(self); } view->obj = self; @@ -438,7 +440,7 @@ template<> INLINE int Extension >:: __getbuffer__(PyObject *self, Py_buffer *view, int flags) { #if PY_VERSION_HEX >= 0x02060000 - if (self != NULL) { + if (self != nullptr) { Py_INCREF(self); } view->obj = self; @@ -464,10 +466,10 @@ INLINE void Extension >:: __releasebuffer__(PyObject *self, Py_buffer *view) const { #if PY_VERSION_HEX >= 0x02060000 // Note: PyBuffer_Release automatically decrements view->obj. - if (view->internal != NULL) { + if (view->internal != nullptr) { // Oh, right, let's not forget to unref this. unref_delete((const PointerToArray *)view->internal); - view->internal = NULL; + view->internal = nullptr; } #endif } @@ -487,12 +489,12 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const { } const char *format = get_format_code(Element); - if (format == NULL) { + if (format == nullptr) { // Not supported. return -1; } - if (self != NULL) { + if (self != nullptr) { Py_INCREF(self); } view->obj = self; @@ -500,23 +502,23 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const { view->len = this->_this->size() * sizeof(Element); view->readonly = 1; view->itemsize = sizeof(Element); - view->format = NULL; + view->format = nullptr; if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) { view->format = (char*) format; } view->ndim = 1; - view->shape = NULL; + view->shape = nullptr; if ((flags & PyBUF_ND) == PyBUF_ND) { // This leaks, which sucks, but __releasebuffer__ doesn't give us the same // pointer, so we would need to store it elsewhere if we wanted to delete // it there. Eh, it's just an int, who cares. view->shape = new Py_ssize_t(this->_this->size()); } - view->strides = NULL; + view->strides = nullptr; if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) { view->strides = &(view->itemsize); } - view->suboffsets = NULL; + view->suboffsets = nullptr; // Store a reference to ourselves on the Py_buffer object as a reminder that // we have increased our refcount. @@ -541,7 +543,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const { "Object is not writable."); return -1; } - if (self != NULL) { + if (self != nullptr) { Py_INCREF(self); } view->obj = self; @@ -571,7 +573,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const { "Object is not writable."); return -1; } - if (self != NULL) { + if (self != nullptr) { Py_INCREF(self); } view->obj = self; @@ -601,7 +603,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const { "Object is not writable."); return -1; } - if (self != NULL) { + if (self != nullptr) { Py_INCREF(self); } view->obj = self; @@ -631,7 +633,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const { "Object is not writable."); return -1; } - if (self != NULL) { + if (self != nullptr) { Py_INCREF(self); } view->obj = self; @@ -657,10 +659,10 @@ INLINE void Extension >:: __releasebuffer__(PyObject *self, Py_buffer *view) const { #if PY_VERSION_HEX >= 0x02060000 // Note: PyBuffer_Release automatically decrements obj->view. - if (view->internal != NULL) { + if (view->internal != nullptr) { // Oh, right, let's not forget to unref this. unref_delete((const PointerToArray *)view->internal); - view->internal = NULL; + view->internal = nullptr; } #endif } diff --git a/panda/src/express/pointerToArray_ext.h b/panda/src/express/pointerToArray_ext.h index 469b449fed..2daf885943 100644 --- a/panda/src/express/pointerToArray_ext.h +++ b/panda/src/express/pointerToArray_ext.h @@ -125,7 +125,7 @@ template class EXPORT_THIS Extension; template INLINE const char *_get_format_code(const T *) { - return NULL; + return nullptr; } define_format_code("c", char); diff --git a/panda/src/express/pointerToBase.I b/panda/src/express/pointerToBase.I index bf4ff877f0..819e16efec 100644 --- a/panda/src/express/pointerToBase.I +++ b/panda/src/express/pointerToBase.I @@ -18,7 +18,7 @@ template INLINE PointerToBase:: PointerToBase(To *ptr) { _void_ptr = (void *)ptr; - if (ptr != (To *)NULL) { + if (ptr != nullptr) { ptr->ref(); #ifdef DO_MEMORY_USAGE update_type(ptr); @@ -33,7 +33,7 @@ template INLINE PointerToBase:: PointerToBase(const PointerToBase ©) { _void_ptr = copy._void_ptr; - if (_void_ptr != NULL) { + if (_void_ptr != nullptr) { To *ptr = (To *)_void_ptr; ptr->ref(); } @@ -44,22 +44,36 @@ PointerToBase(const PointerToBase ©) { */ template INLINE PointerToBase:: -~PointerToBase() { - if (_void_ptr != NULL) { - unref_delete((To *)_void_ptr); - _void_ptr = NULL; - } +PointerToBase(PointerToBase &&from) noexcept { + _void_ptr = from._void_ptr; + from._void_ptr = nullptr; +} + +/** + * + */ +template +template +INLINE PointerToBase:: +PointerToBase(PointerToBase &&r) noexcept { + // If this next line gives an error, you are trying to convert a PointerTo + // from an incompatible type of another PointerTo. + To *ptr = (Y *)r._void_ptr; + + this->_void_ptr = ptr; + r._void_ptr = nullptr; } -#ifdef USE_MOVE_SEMANTICS /** * */ template INLINE PointerToBase:: -PointerToBase(PointerToBase &&from) NOEXCEPT { - _void_ptr = from._void_ptr; - from._void_ptr = (void *)NULL; +~PointerToBase() { + if (_void_ptr != nullptr) { + unref_delete((To *)_void_ptr); + _void_ptr = nullptr; + } } /** @@ -70,21 +84,45 @@ PointerToBase(PointerToBase &&from) NOEXCEPT { */ template INLINE void PointerToBase:: -reassign(PointerToBase &&from) NOEXCEPT { +reassign(PointerToBase &&from) noexcept { // Protect against self-move-assignment. if (from._void_ptr != this->_void_ptr) { To *old_ptr = (To *)this->_void_ptr; this->_void_ptr = from._void_ptr; - from._void_ptr = NULL; + from._void_ptr = nullptr; // Now delete the old pointer. - if (old_ptr != (To *)NULL) { + if (old_ptr != nullptr) { + unref_delete(old_ptr); + } + } +} + +/** + * Like above, but casts from a compatible pointer type. + */ +template +template +INLINE void PointerToBase:: +reassign(PointerToBase &&from) noexcept { + // Protect against self-move-assignment. + if (from._void_ptr != this->_void_ptr) { + To *old_ptr = (To *)this->_void_ptr; + + // If there is a compile error on this line, it means you tried to assign + // an incompatible type. + To *new_ptr = (Y *)from._void_ptr; + + this->_void_ptr = new_ptr; + from._void_ptr = nullptr; + + // Now delete the old pointer. + if (old_ptr != nullptr) { unref_delete(old_ptr); } } } -#endif // USE_MOVE_SEMANTICS /** * This is the main work of the PointerTo family. When the pointer is @@ -169,7 +207,7 @@ update_type(To *ptr) { template ALWAYS_INLINE void PointerToBase:: clear() { - reassign((To *)NULL); + reassign(nullptr); } /** @@ -178,9 +216,9 @@ clear() { */ template INLINE void PointerToBase:: -output(ostream &out) const { +output(std::ostream &out) const { out << _void_ptr; - if (_void_ptr != (void *)NULL) { + if (_void_ptr != nullptr) { out << ":" << ((To *)_void_ptr)->get_ref_count(); } } diff --git a/panda/src/express/pointerToBase.h b/panda/src/express/pointerToBase.h index 919f596c33..959574aba7 100644 --- a/panda/src/express/pointerToBase.h +++ b/panda/src/express/pointerToBase.h @@ -31,32 +31,37 @@ public: typedef T To; protected: - ALWAYS_INLINE_CONSTEXPR PointerToBase() NOEXCEPT DEFAULT_CTOR; + ALWAYS_INLINE constexpr PointerToBase() noexcept = default; INLINE PointerToBase(To *ptr); INLINE PointerToBase(const PointerToBase ©); - INLINE ~PointerToBase(); + INLINE PointerToBase(PointerToBase &&from) noexcept; + template + INLINE PointerToBase(PointerToBase &&r) noexcept; -#ifdef USE_MOVE_SEMANTICS - INLINE PointerToBase(PointerToBase &&from) NOEXCEPT; - INLINE void reassign(PointerToBase &&from) NOEXCEPT; -#endif + INLINE ~PointerToBase(); INLINE void reassign(To *ptr); INLINE void reassign(const PointerToBase ©); + INLINE void reassign(PointerToBase &&from) noexcept; + template + INLINE void reassign(PointerToBase &&from) noexcept; INLINE void update_type(To *ptr); // No assignment or retrieval functions are declared in PointerToBase, // because we will have to specialize on const vs. non-const later. + // This is needed to be able to access the privates of other instantiations. + template friend class PointerToBase; + PUBLISHED: ALWAYS_INLINE void clear(); - void output(ostream &out) const; + void output(std::ostream &out) const; }; template -INLINE ostream &operator <<(ostream &out, const PointerToBase &pointer) { +INLINE std::ostream &operator <<(std::ostream &out, const PointerToBase &pointer) { pointer.output(out); return out; } diff --git a/panda/src/express/pointerToVoid.I b/panda/src/express/pointerToVoid.I index ee3a36e303..c6f981a7fb 100644 --- a/panda/src/express/pointerToVoid.I +++ b/panda/src/express/pointerToVoid.I @@ -14,8 +14,8 @@ /** * */ -CONSTEXPR PointerToVoid:: -PointerToVoid() NOEXCEPT : _void_ptr(nullptr) { +constexpr PointerToVoid:: +PointerToVoid() noexcept : _void_ptr(nullptr) { } /** @@ -30,7 +30,7 @@ PointerToVoid() NOEXCEPT : _void_ptr(nullptr) { * Returns true if the PointerTo is a NULL pointer, false otherwise. (Direct * comparison to a NULL pointer also works.) */ -CONSTEXPR bool PointerToVoid:: +constexpr bool PointerToVoid:: is_null() const { return _void_ptr == nullptr; } @@ -82,7 +82,7 @@ operator != (const PointerToVoid &other) const { * For internal use only. Use the global swap() function instead. */ INLINE void PointerToVoid:: -swap(PointerToVoid &other) NOEXCEPT { +swap(PointerToVoid &other) noexcept { AtomicAdjust::Pointer temp = _void_ptr; _void_ptr = other._void_ptr; other._void_ptr = temp; diff --git a/panda/src/express/pointerToVoid.h b/panda/src/express/pointerToVoid.h index 0d2c1d33e9..1f5fadd492 100644 --- a/panda/src/express/pointerToVoid.h +++ b/panda/src/express/pointerToVoid.h @@ -30,16 +30,16 @@ * * This is the base class for PointerToBase. */ -class EXPCL_PANDAEXPRESS PointerToVoid : public MemoryBase { +class EXPCL_PANDA_EXPRESS PointerToVoid : public MemoryBase { protected: - CONSTEXPR PointerToVoid() NOEXCEPT; + constexpr PointerToVoid() noexcept; //INLINE ~PointerToVoid(); private: - PointerToVoid(const PointerToVoid ©) DELETED; + PointerToVoid(const PointerToVoid ©) = delete; PUBLISHED: - CONSTEXPR bool is_null() const; + constexpr bool is_null() const; INLINE size_t get_hash() const; public: @@ -51,7 +51,7 @@ public: INLINE bool operator == (const PointerToVoid &other) const; INLINE bool operator != (const PointerToVoid &other) const; - INLINE void swap(PointerToVoid &other) NOEXCEPT; + INLINE void swap(PointerToVoid &other) noexcept; protected: // Within the PointerToVoid class, we only store a void pointer. This is diff --git a/panda/src/express/profileTimer.I b/panda/src/express/profileTimer.I index 107f86f6af..bd5102e6de 100644 --- a/panda/src/express/profileTimer.I +++ b/panda/src/express/profileTimer.I @@ -28,7 +28,7 @@ getTime() { INLINE void ProfileTimer:: mark(const char* tag) { if (!_entries) { - cerr << "ProfileTimer::mark !_entries" << endl; + std::cerr << "ProfileTimer::mark !_entries" << std::endl; exit(1); } if (_entryCount < _maxEntries-1) { diff --git a/panda/src/express/profileTimer.cxx b/panda/src/express/profileTimer.cxx index 41d1ac8f89..dfad4b03b4 100644 --- a/panda/src/express/profileTimer.cxx +++ b/panda/src/express/profileTimer.cxx @@ -13,18 +13,19 @@ #include "pmap.h" -using namespace std; +using std::ostream; +using std::string; // See ProfileTimer.h for documentation. -EXPCL_PANDAEXPRESS ProfileTimer Skyler_timer_global=ProfileTimer("startup"); +EXPCL_PANDA_EXPRESS ProfileTimer Skyler_timer_global=ProfileTimer("startup"); ProfileTimer* ProfileTimer::_head; ProfileTimer:: ProfileTimer(const char* name, int maxEntries) : - _entries(0), + _entries(nullptr), _autoTimerCount(0) { // Keep a list of the ProfileTimers, so we can print them: _next=_head; @@ -120,16 +121,16 @@ consolidateTo(ostream &out) const { { pmap::const_iterator i=entries.begin(); for (;i!=entries.end(); ++i) { - out << " " << setw(50) << i->first << ": " - << setiosflags(ios::fixed) << setprecision(6) << setw(10) << i->second << "\n"; + out << " " << std::setw(50) << i->first << ": " + << std::setiosflags(std::ios::fixed) << std::setprecision(6) << std::setw(10) << i->second << "\n"; total+=i->second; } } out << "\n [Total Time: " - << setiosflags(ios::fixed) << setprecision(6) << total + << std::setiosflags(std::ios::fixed) << std::setprecision(6) << total << " seconds]\n" << "-------------------------------------------------------------------\n"; - out << endl; + out << std::endl; } void ProfileTimer:: @@ -150,15 +151,15 @@ printTo(ostream &out) const { int i; for (i=0; i<_entryCount; ++i) { TimerEntry& te=_entries[i]; - out << " " << setw(50) << te._tag << ": " - << setiosflags(ios::fixed) << setprecision(6) << setw(10) << te._time << "\n"; + out << " " << std::setw(50) << te._tag << ": " + << std::setiosflags(std::ios::fixed) << std::setprecision(6) << std::setw(10) << te._time << "\n"; total+=te._time; } out << "\n [Total Time: " - << setiosflags(ios::fixed) << setprecision(6) << total + << std::setiosflags(std::ios::fixed) << std::setprecision(6) << total << " seconds]\n" << "-------------------------------------------------------------------\n"; - out << endl; + out << std::endl; } ProfileTimer::AutoTimer::AutoTimer(ProfileTimer& profile, const char* tag) : diff --git a/panda/src/express/profileTimer.h b/panda/src/express/profileTimer.h index 94eb39bd01..39ab65c588 100644 --- a/panda/src/express/profileTimer.h +++ b/panda/src/express/profileTimer.h @@ -37,7 +37,7 @@ seconds of each other, I don't think you'll get very good results. */ -class EXPCL_PANDAEXPRESS ProfileTimer { +class EXPCL_PANDA_EXPRESS ProfileTimer { enum { MaxEntriesDefault=4096 }; PUBLISHED: explicit ProfileTimer(const char* name=0, int maxEntries=MaxEntriesDefault); @@ -54,10 +54,10 @@ PUBLISHED: // Don't call any of the following during timing: (Because they are slow, // not because anything will break). double getTotalTime() const; - static void consolidateAllTo(ostream &out=cout); - void consolidateTo(ostream &out=cout) const; - static void printAllTo(ostream &out=cout); - void printTo(ostream &out=cout) const; + static void consolidateAllTo(std::ostream &out=std::cout); + void consolidateTo(std::ostream &out=std::cout) const; + static void printAllTo(std::ostream &out=std::cout); + void printTo(std::ostream &out=std::cout) const; public: /* @@ -67,7 +67,7 @@ public: ... } */ - class EXPCL_PANDAEXPRESS AutoTimer { + class EXPCL_PANDA_EXPRESS AutoTimer { public: AutoTimer(ProfileTimer& profile, const char* tag); ~AutoTimer(); diff --git a/panda/src/express/pta_double.h b/panda/src/express/pta_double.h index 4db51677eb..0edd1c4b89 100644 --- a/panda/src/express/pta_double.h +++ b/panda/src/express/pta_double.h @@ -26,10 +26,10 @@ * defining the pta again. */ -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS, PointerToBase >) -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS, PointerToArrayBase) -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS, PointerToArray) -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS, ConstPointerToArray) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EXPRESS, EXPTP_PANDA_EXPRESS, PointerToBase >) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EXPRESS, EXPTP_PANDA_EXPRESS, PointerToArrayBase) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EXPRESS, EXPTP_PANDA_EXPRESS, PointerToArray) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EXPRESS, EXPTP_PANDA_EXPRESS, ConstPointerToArray) typedef PointerToArray PTA_double; typedef ConstPointerToArray CPTA_double; diff --git a/panda/src/express/pta_float.h b/panda/src/express/pta_float.h index fd84774654..2f3b32efb4 100644 --- a/panda/src/express/pta_float.h +++ b/panda/src/express/pta_float.h @@ -26,10 +26,10 @@ * defining the pta again. */ -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS, PointerToBase >) -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS, PointerToArrayBase) -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS, PointerToArray) -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS, ConstPointerToArray) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EXPRESS, EXPTP_PANDA_EXPRESS, PointerToBase >) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EXPRESS, EXPTP_PANDA_EXPRESS, PointerToArrayBase) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EXPRESS, EXPTP_PANDA_EXPRESS, PointerToArray) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EXPRESS, EXPTP_PANDA_EXPRESS, ConstPointerToArray) typedef PointerToArray PTA_float; typedef ConstPointerToArray CPTA_float; diff --git a/panda/src/express/pta_int.h b/panda/src/express/pta_int.h index 93ed0bb900..fda34e3fde 100644 --- a/panda/src/express/pta_int.h +++ b/panda/src/express/pta_int.h @@ -26,10 +26,10 @@ * pta again. */ -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS, PointerToBase >) -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS, PointerToArrayBase) -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS, PointerToArray) -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS, ConstPointerToArray) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EXPRESS, EXPTP_PANDA_EXPRESS, PointerToBase >) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EXPRESS, EXPTP_PANDA_EXPRESS, PointerToArrayBase) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EXPRESS, EXPTP_PANDA_EXPRESS, PointerToArray) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EXPRESS, EXPTP_PANDA_EXPRESS, ConstPointerToArray) typedef PointerToArray PTA_int; typedef ConstPointerToArray CPTA_int; diff --git a/panda/src/express/pta_uchar.h b/panda/src/express/pta_uchar.h index 1552c6bcab..860e877042 100644 --- a/panda/src/express/pta_uchar.h +++ b/panda/src/express/pta_uchar.h @@ -21,7 +21,7 @@ /** * A pta of uchars. This class is defined once here, and exported to - * PANDAEXPRESS.DLL; other packages that want to use a pta of this type + * PANDA_EXPRESS.DLL; other packages that want to use a pta of this type * (whether they need to export it or not) should include this header file, * rather than defining the pta again. */ @@ -29,10 +29,10 @@ #if !defined(__clang__) && __GNUC__ == 4 && __GNUC_MINOR__ < 7 // GCC 4.6 has a weird bug related to this type. #else -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS, PointerToBase >) -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS, PointerToArrayBase) -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS, PointerToArray) -EXPORT_TEMPLATE_CLASS(EXPCL_PANDAEXPRESS, EXPTP_PANDAEXPRESS, ConstPointerToArray) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EXPRESS, EXPTP_PANDA_EXPRESS, PointerToBase >) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EXPRESS, EXPTP_PANDA_EXPRESS, PointerToArrayBase) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EXPRESS, EXPTP_PANDA_EXPRESS, PointerToArray) +EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_EXPRESS, EXPTP_PANDA_EXPRESS, ConstPointerToArray) #endif typedef PointerToArray PTA_uchar; diff --git a/panda/src/express/ramfile.I b/panda/src/express/ramfile.I index 797eab3c1b..cd045a3d3d 100644 --- a/panda/src/express/ramfile.I +++ b/panda/src/express/ramfile.I @@ -41,7 +41,7 @@ tell() const { * Returns the entire buffer contents as a string, regardless of the current * data pointer. */ -INLINE const string &Ramfile:: +INLINE const std::string &Ramfile:: get_data() const { return _data; } diff --git a/panda/src/express/ramfile.cxx b/panda/src/express/ramfile.cxx index cc12e239c7..c1994df34c 100644 --- a/panda/src/express/ramfile.cxx +++ b/panda/src/express/ramfile.cxx @@ -21,10 +21,10 @@ * The interface here is intentionally designed to be similar to that for * Python's file.read() function. */ -string Ramfile:: +std::string Ramfile:: read(size_t length) { size_t orig_pos = _pos; - _pos = min(_pos + length, _data.length()); + _pos = std::min(_pos + length, _data.length()); return _data.substr(orig_pos, length); } @@ -36,7 +36,7 @@ read(size_t length) { * The interface here is intentionally designed to be similar to that for * Python's file.readline() function. */ -string Ramfile:: +std::string Ramfile:: readline() { size_t start = _pos; while (_pos < _data.length() && _data[_pos] != '\n') { diff --git a/panda/src/express/ramfile.h b/panda/src/express/ramfile.h index a4dbd17727..b115383aa0 100644 --- a/panda/src/express/ramfile.h +++ b/panda/src/express/ramfile.h @@ -22,7 +22,7 @@ /** * An in-memory buffer specifically designed for downloading files to memory. */ -class EXPCL_PANDAEXPRESS Ramfile { +class EXPCL_PANDA_EXPRESS Ramfile { PUBLISHED: INLINE Ramfile(); @@ -37,12 +37,12 @@ PUBLISHED: INLINE void clear(); public: - string read(size_t length); - string readline(); - INLINE const string &get_data() const; + std::string read(size_t length); + std::string readline(); + INLINE const std::string &get_data() const; size_t _pos; - string _data; + std::string _data; friend class Extension; }; diff --git a/panda/src/express/ramfile_ext.cxx b/panda/src/express/ramfile_ext.cxx index 6de3e62bfd..fc1047487c 100644 --- a/panda/src/express/ramfile_ext.cxx +++ b/panda/src/express/ramfile_ext.cxx @@ -23,8 +23,8 @@ PyObject *Extension:: read(size_t length) { size_t data_length = _this->get_data_size(); const char *data = _this->_data.data() + _this->_pos; - length = min(length, data_length - _this->_pos); - _this->_pos = min(_this->_pos + length, data_length); + length = std::min(length, data_length - _this->_pos); + _this->_pos = std::min(_this->_pos + length, data_length); #if PY_MAJOR_VERSION >= 3 return PyBytes_FromStringAndSize((char *)data, length); @@ -43,7 +43,7 @@ read(size_t length) { */ PyObject *Extension:: readline() { - string line = _this->readline(); + std::string line = _this->readline(); #if PY_MAJOR_VERSION >= 3 return PyBytes_FromStringAndSize(line.data(), line.size()); #else @@ -58,11 +58,11 @@ readline() { PyObject *Extension:: readlines() { PyObject *lst = PyList_New(0); - if (lst == NULL) { - return NULL; + if (lst == nullptr) { + return nullptr; } - string line = _this->readline(); + std::string line = _this->readline(); while (!line.empty()) { #if PY_MAJOR_VERSION >= 3 PyObject *py_line = PyBytes_FromStringAndSize(line.data(), line.size()); diff --git a/panda/src/express/referenceCount.I b/panda/src/express/referenceCount.I index c1d54da5da..bb4ac1fc18 100644 --- a/panda/src/express/referenceCount.I +++ b/panda/src/express/referenceCount.I @@ -28,7 +28,7 @@ TypeHandle RefCountObj::_type_handle; */ INLINE ReferenceCount:: ReferenceCount() { - _weak_list = (WeakReferenceList *)NULL; + _weak_list = nullptr; _ref_count = 0; #ifdef DO_MEMORY_USAGE MemoryUsage::record_pointer(this); @@ -45,7 +45,7 @@ ReferenceCount() { */ INLINE ReferenceCount:: ReferenceCount(const ReferenceCount &) { - _weak_list = (WeakReferenceList *)NULL; + _weak_list = nullptr; _ref_count = 0; #ifdef DO_MEMORY_USAGE MemoryUsage::record_pointer(this); @@ -63,8 +63,6 @@ ReferenceCount(const ReferenceCount &) { */ INLINE void ReferenceCount:: operator = (const ReferenceCount &) { - nassertv(this != NULL); - // If this assertion fails, our own pointer was recently deleted. Possibly // you used a real pointer instead of a PointerTo at some point, and the // object was deleted when the PointerTo went out of scope. Maybe you tried @@ -80,8 +78,6 @@ operator = (const ReferenceCount &) { ReferenceCount:: ~ReferenceCount() { TAU_PROFILE("ReferenceCount::~ReferenceCount()", " ", TAU_USER); - nassertv(this != NULL); - // If this assertion fails, we're trying to delete an object that was just // deleted. Possibly you used a real pointer instead of a PointerTo at some // point, and the object was deleted when the PointerTo went out of scope. @@ -112,9 +108,9 @@ ReferenceCount:: nassertv(_ref_count == 0 || _ref_count == local_ref_count); // Tell our weak reference holders that we're going away now. - if (_weak_list != (WeakReferenceList *)NULL) { - delete (WeakReferenceList *)_weak_list; - _weak_list = (WeakReferenceList *)NULL; + if (_weak_list != nullptr) { + ((WeakReferenceList *)_weak_list)->mark_deleted(); + _weak_list = nullptr; } #ifndef NDEBUG @@ -246,17 +242,20 @@ local_object() { */ INLINE bool ReferenceCount:: has_weak_list() const { - return _weak_list != (WeakReferenceList *)NULL; + return _weak_list != nullptr; } /** * Returns the WeakReferenceList associated with this ReferenceCount object. * If there has never been a WeakReferenceList associated with this object, * creates one now. + * + * The returned object will be deleted automatically when all weak and strong + * references to the object have gone. */ INLINE WeakReferenceList *ReferenceCount:: get_weak_list() const { - if (AtomicAdjust::get_ptr(_weak_list) == (WeakReferenceList *)NULL) { + if (AtomicAdjust::get_ptr(_weak_list) == nullptr) { ((ReferenceCount *)this)->create_weak_list(); } return (WeakReferenceList *)AtomicAdjust::get_ptr(_weak_list); @@ -264,14 +263,21 @@ get_weak_list() const { /** * Adds the indicated PointerToVoid as a weak reference to this object. + * Returns an object that will persist as long as any reference (strong or + * weak) exists, for calling unref() or checking whether the object still + * exists. */ -INLINE void ReferenceCount:: -weak_ref(WeakPointerToVoid *ptv) { +INLINE WeakReferenceList *ReferenceCount:: +weak_ref() { TAU_PROFILE("void ReferenceCount::weak_ref()", " ", TAU_USER); #ifdef _DEBUG - nassertv(test_ref_count_integrity()); + nassertr(test_ref_count_integrity(), nullptr); +#else + nassertr(_ref_count != deleted_ref_count, nullptr); #endif - get_weak_list()->add_reference(ptv); + WeakReferenceList *weak_ref = get_weak_list(); + weak_ref->ref(); + return weak_ref; } /** @@ -279,13 +285,36 @@ weak_ref(WeakPointerToVoid *ptv) { * must have previously been added via a call to weak_ref(). */ INLINE void ReferenceCount:: -weak_unref(WeakPointerToVoid *ptv) { +weak_unref() { TAU_PROFILE("void ReferenceCount::weak_unref()", " ", TAU_USER); #ifdef _DEBUG nassertv(test_ref_count_integrity()); #endif - nassertv(has_weak_list()); - ((WeakReferenceList *)_weak_list)->clear_reference(ptv); + WeakReferenceList *weak_list = (WeakReferenceList *)_weak_list; + nassertv(weak_list != nullptr); + bool nonzero = weak_list->unref(); + nassertv(nonzero); +} + +/** + * Atomically increases the reference count of this object if it is not zero. + * Do not use this. This exists only to implement a special case for weak + * pointers. + * @return true if the reference count was incremented, false if it was zero. + */ +INLINE bool ReferenceCount:: +ref_if_nonzero() const { +#ifdef _DEBUG + test_ref_count_integrity(); +#endif + AtomicAdjust::Integer ref_count; + do { + ref_count = AtomicAdjust::get(_ref_count); + if (ref_count <= 0) { + return false; + } + } while (ref_count != AtomicAdjust::compare_and_exchange(_ref_count, ref_count, ref_count + 1)); + return true; } /** @@ -382,9 +411,9 @@ void RefCountObj:: init_type() { #if defined(HAVE_RTTI) && !defined(__EDG__) // If we have RTTI, we can determine the name of the base type. - string base_name = typeid(Base).name(); + std::string base_name = typeid(Base).name(); #else - string base_name = "unknown"; + std::string base_name = "unknown"; #endif TypeHandle base_type = register_dynamic_type(base_name); diff --git a/panda/src/express/referenceCount.cxx b/panda/src/express/referenceCount.cxx index f5d988cf8e..f446b3be46 100644 --- a/panda/src/express/referenceCount.cxx +++ b/panda/src/express/referenceCount.cxx @@ -23,8 +23,6 @@ TypeHandle ReferenceCount::_type_handle; */ bool ReferenceCount:: do_test_ref_count_integrity() const { - nassertr(this != NULL, false); - // If this assertion fails, we're trying to delete an object that was just // deleted. Possibly you used a real pointer instead of a PointerTo at some // point, and the object was deleted when the PointerTo went out of scope. @@ -58,8 +56,8 @@ void ReferenceCount:: create_weak_list() { WeakReferenceList *weak_list = new WeakReferenceList; void *orig = - AtomicAdjust::compare_and_exchange_ptr(_weak_list, NULL, weak_list); - if (orig != (void *)NULL) { + AtomicAdjust::compare_and_exchange_ptr(_weak_list, nullptr, weak_list); + if (orig != nullptr) { // Someone else created it first. delete weak_list; } diff --git a/panda/src/express/referenceCount.h b/panda/src/express/referenceCount.h index 72425dcd8d..46f0231117 100644 --- a/panda/src/express/referenceCount.h +++ b/panda/src/express/referenceCount.h @@ -35,7 +35,7 @@ * ReferenceCount works in conjunction with PointerTo to automatically delete * objects when the last pointer to them goes away. */ -class EXPCL_PANDAEXPRESS ReferenceCount : public MemoryBase { +class EXPCL_PANDA_EXPRESS ReferenceCount : public MemoryBase { protected: INLINE ReferenceCount(); INLINE ReferenceCount(const ReferenceCount &); @@ -60,8 +60,10 @@ public: INLINE bool has_weak_list() const; INLINE WeakReferenceList *get_weak_list() const; - INLINE void weak_ref(WeakPointerToVoid *ptv); - INLINE void weak_unref(WeakPointerToVoid *ptv); + INLINE WeakReferenceList *weak_ref(); + INLINE void weak_unref(); + + INLINE bool ref_if_nonzero() const; protected: bool do_test_ref_count_integrity() const; diff --git a/panda/src/express/subStream.I b/panda/src/express/subStream.I index 346b66d46a..30f8ecce60 100644 --- a/panda/src/express/subStream.I +++ b/panda/src/express/subStream.I @@ -15,14 +15,14 @@ * */ INLINE ISubStream:: -ISubStream() : istream(&_buf) { +ISubStream() : std::istream(&_buf) { } /** * */ INLINE ISubStream:: -ISubStream(IStreamWrapper *source, streampos start, streampos end) : istream(&_buf) { +ISubStream(IStreamWrapper *source, std::streampos start, std::streampos end) : std::istream(&_buf) { open(source, start, end); } @@ -36,9 +36,9 @@ ISubStream(IStreamWrapper *source, streampos start, streampos end) : istream(&_b * end of the source stream. */ INLINE ISubStream &ISubStream:: -open(IStreamWrapper *source, streampos start, streampos end) { +open(IStreamWrapper *source, std::streampos start, std::streampos end) { clear((ios_iostate)0); - _buf.open(source, NULL, start, end, false); + _buf.open(source, nullptr, start, end, false); return *this; } @@ -56,14 +56,14 @@ close() { * */ INLINE OSubStream:: -OSubStream() : ostream(&_buf) { +OSubStream() : std::ostream(&_buf) { } /** * */ INLINE OSubStream:: -OSubStream(OStreamWrapper *dest, streampos start, streampos end, bool append) : ostream(&_buf) { +OSubStream(OStreamWrapper *dest, std::streampos start, std::streampos end, bool append) : std::ostream(&_buf) { open(dest, start, end, append); } @@ -77,9 +77,9 @@ OSubStream(OStreamWrapper *dest, streampos start, streampos end, bool append) : * end of the dest stream. */ INLINE OSubStream &OSubStream:: -open(OStreamWrapper *dest, streampos start, streampos end, bool append) { +open(OStreamWrapper *dest, std::streampos start, std::streampos end, bool append) { clear((ios_iostate)0); - _buf.open(NULL, dest, start, end, append); + _buf.open(nullptr, dest, start, end, append); return *this; } @@ -97,14 +97,14 @@ close() { * */ INLINE SubStream:: -SubStream() : iostream(&_buf) { +SubStream() : std::iostream(&_buf) { } /** * */ INLINE SubStream:: -SubStream(StreamWrapper *nested, streampos start, streampos end, bool append) : iostream(&_buf) { +SubStream(StreamWrapper *nested, std::streampos start, std::streampos end, bool append) : std::iostream(&_buf) { open(nested, start, end, append); } @@ -117,7 +117,7 @@ SubStream(StreamWrapper *nested, streampos start, streampos end, bool append) : * of the nested stream. */ INLINE SubStream &SubStream:: -open(StreamWrapper *nested, streampos start, streampos end, bool append) { +open(StreamWrapper *nested, std::streampos start, std::streampos end, bool append) { clear((ios_iostate)0); _buf.open(nested, nested, start, end, append); return *this; diff --git a/panda/src/express/subStream.h b/panda/src/express/subStream.h index 3d071b9c7f..82bf222e2f 100644 --- a/panda/src/express/subStream.h +++ b/panda/src/express/subStream.h @@ -27,16 +27,16 @@ * The source stream must be one that we can randomly seek within. The * resulting ISubStream will also support arbitrary seeks. */ -class EXPCL_PANDAEXPRESS ISubStream : public istream { +class EXPCL_PANDA_EXPRESS ISubStream : public std::istream { PUBLISHED: INLINE ISubStream(); - INLINE explicit ISubStream(IStreamWrapper *source, streampos start, streampos end); + INLINE explicit ISubStream(IStreamWrapper *source, std::streampos start, std::streampos end); #if _MSC_VER >= 1800 INLINE ISubStream(const ISubStream ©) = delete; #endif - INLINE ISubStream &open(IStreamWrapper *source, streampos start, streampos end); + INLINE ISubStream &open(IStreamWrapper *source, std::streampos start, std::streampos end); INLINE ISubStream &close(); private: @@ -52,16 +52,16 @@ private: * The dest stream must be one that we can randomly seek within. The * resulting OSubStream will also support arbitrary seeks. */ -class EXPCL_PANDAEXPRESS OSubStream : public ostream { +class EXPCL_PANDA_EXPRESS OSubStream : public std::ostream { PUBLISHED: INLINE OSubStream(); - INLINE explicit OSubStream(OStreamWrapper *dest, streampos start, streampos end, bool append = false); + INLINE explicit OSubStream(OStreamWrapper *dest, std::streampos start, std::streampos end, bool append = false); #if _MSC_VER >= 1800 INLINE OSubStream(const OSubStream ©) = delete; #endif - INLINE OSubStream &open(OStreamWrapper *dest, streampos start, streampos end, bool append = false); + INLINE OSubStream &open(OStreamWrapper *dest, std::streampos start, std::streampos end, bool append = false); INLINE OSubStream &close(); private: @@ -71,16 +71,16 @@ private: /** * Combined ISubStream and OSubStream for bidirectional I/O. */ -class EXPCL_PANDAEXPRESS SubStream : public iostream { +class EXPCL_PANDA_EXPRESS SubStream : public std::iostream { PUBLISHED: INLINE SubStream(); - INLINE explicit SubStream(StreamWrapper *nested, streampos start, streampos end, bool append = false); + INLINE explicit SubStream(StreamWrapper *nested, std::streampos start, std::streampos end, bool append = false); #if _MSC_VER >= 1800 INLINE SubStream(const SubStream ©) = delete; #endif - INLINE SubStream &open(StreamWrapper *nested, streampos start, streampos end, bool append = false); + INLINE SubStream &open(StreamWrapper *nested, std::streampos start, std::streampos end, bool append = false); INLINE SubStream &close(); private: diff --git a/panda/src/express/subStreamBuf.cxx b/panda/src/express/subStreamBuf.cxx index 61a349b215..4d773e359f 100644 --- a/panda/src/express/subStreamBuf.cxx +++ b/panda/src/express/subStreamBuf.cxx @@ -15,10 +15,10 @@ #include "pnotify.h" #include "memoryHook.h" -#ifndef HAVE_STREAMSIZE -// Some compilers (notably SGI) don't define this for us -typedef int streamsize; -#endif /* HAVE_STREAMSIZE */ +using std::ios; +using std::streamoff; +using std::streampos; +using std::streamsize; static const size_t substream_buffer_size = 4096; @@ -27,8 +27,8 @@ static const size_t substream_buffer_size = 4096; */ SubStreamBuf:: SubStreamBuf() { - _source = (IStreamWrapper *)NULL; - _dest = (OStreamWrapper *)NULL; + _source = nullptr; + _dest = nullptr; // _start is the streampos of the first byte of the SubStream within its // parent stream. @@ -98,8 +98,8 @@ close() { // Make sure the write buffer is flushed. sync(); - _source = (IStreamWrapper *)NULL; - _dest = (OStreamWrapper *)NULL; + _source = nullptr; + _dest = nullptr; _start = 0; _end = 0; @@ -251,7 +251,7 @@ overflow(int ch) { } } - nassertr(_dest != NULL, EOF); + nassertr(_dest != nullptr, EOF); bool fail = false; if (_append) { _dest->seek_eof_write(pbase(), n, fail); @@ -291,7 +291,7 @@ sync() { size_t n = pptr() - pbase(); if (n != 0) { - nassertr(_dest != NULL, EOF); + nassertr(_dest != nullptr, EOF); bool fail = false; if (_append) { _dest->seek_eof_write(pbase(), n, fail); @@ -340,7 +340,7 @@ underflow() { nassertr(egptr() - gptr() == num_bytes, EOF); } - nassertr(_source != NULL, EOF); + nassertr(_source != nullptr, EOF); streamsize read_count; bool eof; _source->seek_read(_gpos, gptr(), num_bytes, read_count, eof); diff --git a/panda/src/express/subStreamBuf.h b/panda/src/express/subStreamBuf.h index bfa94e2e6e..779f43d94c 100644 --- a/panda/src/express/subStreamBuf.h +++ b/panda/src/express/subStreamBuf.h @@ -20,16 +20,16 @@ /** * The streambuf object that implements ISubStream. */ -class EXPCL_PANDAEXPRESS SubStreamBuf : public streambuf { +class EXPCL_PANDA_EXPRESS SubStreamBuf : public std::streambuf { public: SubStreamBuf(); virtual ~SubStreamBuf(); - void open(IStreamWrapper *source, OStreamWrapper *dest, streampos start, streampos end, bool append); + void open(IStreamWrapper *source, OStreamWrapper *dest, std::streampos start, std::streampos end, bool append); void close(); - virtual streampos seekoff(streamoff off, ios_seekdir dir, ios_openmode which); - virtual streampos seekpos(streampos pos, ios_openmode which); + virtual std::streampos seekoff(std::streamoff off, ios_seekdir dir, ios_openmode which); + virtual std::streampos seekpos(std::streampos pos, ios_openmode which); protected: virtual int overflow(int c); @@ -39,11 +39,11 @@ protected: private: IStreamWrapper *_source; OStreamWrapper *_dest; - streampos _start; - streampos _end; + std::streampos _start; + std::streampos _end; bool _append; - streampos _gpos; - streampos _ppos; + std::streampos _gpos; + std::streampos _ppos; char *_buffer; }; diff --git a/panda/src/express/subfileInfo.I b/panda/src/express/subfileInfo.I index d34fe7af97..a0a7826f97 100644 --- a/panda/src/express/subfileInfo.I +++ b/panda/src/express/subfileInfo.I @@ -25,7 +25,7 @@ SubfileInfo() : * */ INLINE SubfileInfo:: -SubfileInfo(const FileReference *file, streampos start, streamsize size) : +SubfileInfo(const FileReference *file, std::streampos start, std::streamsize size) : _file(file), _start(start), _size(size) @@ -36,7 +36,7 @@ SubfileInfo(const FileReference *file, streampos start, streamsize size) : * */ INLINE SubfileInfo:: -SubfileInfo(const Filename &filename, streampos start, streamsize size) : +SubfileInfo(const Filename &filename, std::streampos start, std::streamsize size) : _file(new FileReference(filename)), _start(start), _size(size) @@ -70,7 +70,7 @@ operator = (const SubfileInfo ©) { */ INLINE bool SubfileInfo:: is_empty() const { - return _file == (FileReference *)NULL; + return _file == nullptr; } /** @@ -86,7 +86,7 @@ get_file() const { */ INLINE const Filename &SubfileInfo:: get_filename() const { - if (_file != (FileReference *)NULL) { + if (_file != nullptr) { return _file->get_filename(); } static const Filename empty_filename; @@ -96,7 +96,7 @@ get_filename() const { /** * Returns the offset within the file at which this file data begins. */ -INLINE streampos SubfileInfo:: +INLINE std::streampos SubfileInfo:: get_start() const { return _start; } @@ -105,13 +105,13 @@ get_start() const { * Returns the number of consecutive bytes, beginning at get_start(), that * correspond to this file data. */ -INLINE streamsize SubfileInfo:: +INLINE std::streamsize SubfileInfo:: get_size() const { return _size; } -INLINE ostream & -operator << (ostream &out, const SubfileInfo &info) { +INLINE std::ostream & +operator << (std::ostream &out, const SubfileInfo &info) { info.output(out); return out; } diff --git a/panda/src/express/subfileInfo.cxx b/panda/src/express/subfileInfo.cxx index 07ab4fc7f8..55631b25af 100644 --- a/panda/src/express/subfileInfo.cxx +++ b/panda/src/express/subfileInfo.cxx @@ -17,6 +17,6 @@ * */ void SubfileInfo:: -output(ostream &out) const { +output(std::ostream &out) const { out << "SubfileInfo(" << get_filename() << ", " << _start << ", " << _size << ")"; } diff --git a/panda/src/express/subfileInfo.h b/panda/src/express/subfileInfo.h index de2f85fa3e..133c557ad1 100644 --- a/panda/src/express/subfileInfo.h +++ b/panda/src/express/subfileInfo.h @@ -23,11 +23,11 @@ * disk. Generally, the filename is understood as a physical file on disk, * and not to be looked up via the vfs. */ -class EXPCL_PANDAEXPRESS SubfileInfo { +class EXPCL_PANDA_EXPRESS SubfileInfo { PUBLISHED: INLINE SubfileInfo(); - INLINE explicit SubfileInfo(const FileReference *file, streampos start, streamsize size); - INLINE explicit SubfileInfo(const Filename &filename, streampos start, streamsize size); + INLINE explicit SubfileInfo(const FileReference *file, std::streampos start, std::streamsize size); + INLINE explicit SubfileInfo(const Filename &filename, std::streampos start, std::streamsize size); INLINE SubfileInfo(const SubfileInfo ©); INLINE void operator = (const SubfileInfo ©); @@ -35,18 +35,18 @@ PUBLISHED: INLINE const FileReference *get_file() const; INLINE const Filename &get_filename() const; - INLINE streampos get_start() const; - INLINE streamsize get_size() const; + INLINE std::streampos get_start() const; + INLINE std::streamsize get_size() const; - void output(ostream &out) const; + void output(std::ostream &out) const; private: CPT(FileReference) _file; - streampos _start; - streamsize _size; + std::streampos _start; + std::streamsize _size; }; -INLINE ostream &operator << (ostream &out, const SubfileInfo &info); +INLINE std::ostream &operator << (std::ostream &out, const SubfileInfo &info); #include "subfileInfo.I" diff --git a/panda/src/express/temporaryFile.h b/panda/src/express/temporaryFile.h index 8bc66da12b..a8537430e9 100644 --- a/panda/src/express/temporaryFile.h +++ b/panda/src/express/temporaryFile.h @@ -23,7 +23,7 @@ * the file in question when it is deleted. It is not responsible for * creating, opening, or closing the file, however. */ -class EXPCL_PANDAEXPRESS TemporaryFile : public FileReference { +class EXPCL_PANDA_EXPRESS TemporaryFile : public FileReference { PUBLISHED: INLINE explicit TemporaryFile(const Filename &filename); virtual ~TemporaryFile(); diff --git a/panda/src/express/test_ordered_vector.cxx b/panda/src/express/test_ordered_vector.cxx index 1ed3ba9c96..18c0ab6d1d 100644 --- a/panda/src/express/test_ordered_vector.cxx +++ b/panda/src/express/test_ordered_vector.cxx @@ -13,11 +13,13 @@ #include "ordered_vector.h" +using std::cerr; + typedef ov_multiset myvec; void search(myvec &v, int element) { - pair result; + std::pair result; result = v.equal_range(element); size_t count = v.count(element); diff --git a/panda/src/express/test_types.cxx b/panda/src/express/test_types.cxx index 7cc5cf6e61..1bc9bfefd7 100644 --- a/panda/src/express/test_types.cxx +++ b/panda/src/express/test_types.cxx @@ -19,6 +19,9 @@ #include "pnotify.h" +using std::cerr; +using std::string; + class ThatThingie : public TypedObject, public ReferenceCount { public: ThatThingie(const string &name) : _name(name) { diff --git a/panda/src/express/test_zstream.cxx b/panda/src/express/test_zstream.cxx index 34212eb2df..6040aa3ca7 100644 --- a/panda/src/express/test_zstream.cxx +++ b/panda/src/express/test_zstream.cxx @@ -17,6 +17,10 @@ #include +using std::cerr; +using std::cout; +using std::istream; + void stream_decompress(istream &source) { IDecompressStream zstream(&source, false); @@ -42,7 +46,7 @@ stream_compress(istream &source) { void zlib_decompress(istream &source) { // First, read the entire contents into a buffer. - string data; + std::string data; int ch = source.get(); while (!source.eof() && !source.fail()) { @@ -82,7 +86,7 @@ zlib_decompress(istream &source) { void zlib_compress(istream &source) { // First, read the entire contents into a buffer. - string data; + std::string data; int ch = source.get(); while (!source.eof() && !source.fail()) { diff --git a/panda/src/express/threadSafePointerTo.I b/panda/src/express/threadSafePointerTo.I index 7525fd4e4c..ef2b8db410 100644 --- a/panda/src/express/threadSafePointerTo.I +++ b/panda/src/express/threadSafePointerTo.I @@ -41,7 +41,7 @@ INLINE ThreadSafePointerTo:: * */ template -INLINE TYPENAME ThreadSafePointerTo::To &ThreadSafePointerTo:: +INLINE typename ThreadSafePointerTo::To &ThreadSafePointerTo:: operator *() const { return *((To *)AtomicAdjust::get_ptr(this->_void_ptr)); } @@ -50,7 +50,7 @@ operator *() const { * */ template -INLINE TYPENAME ThreadSafePointerTo::To *ThreadSafePointerTo:: +INLINE typename ThreadSafePointerTo::To *ThreadSafePointerTo:: operator -> () const { return (To *)AtomicAdjust::get_ptr(this->_void_ptr); } @@ -72,7 +72,7 @@ operator T * () const { * work around compiler problems, particularly for implicit upcasts. */ template -INLINE TYPENAME ThreadSafePointerTo::To *ThreadSafePointerTo:: +INLINE typename ThreadSafePointerTo::To *ThreadSafePointerTo:: p() const { return (To *)AtomicAdjust::get_ptr(this->_void_ptr); } @@ -102,8 +102,8 @@ operator = (const ThreadSafePointerTo ©) { */ template INLINE ThreadSafeConstPointerTo:: -ThreadSafeConstPointerTo(const TYPENAME ThreadSafeConstPointerTo::To *ptr) : - ThreadSafePointerToBase((TYPENAME ThreadSafeConstPointerTo::To *)ptr) +ThreadSafeConstPointerTo(const typename ThreadSafeConstPointerTo::To *ptr) : + ThreadSafePointerToBase((typename ThreadSafeConstPointerTo::To *)ptr) { } @@ -139,7 +139,7 @@ ThreadSafeConstPointerTo(const ThreadSafeConstPointerTo ©) : * */ template -INLINE const TYPENAME ThreadSafeConstPointerTo::To &ThreadSafeConstPointerTo:: +INLINE const typename ThreadSafeConstPointerTo::To &ThreadSafeConstPointerTo:: operator *() const { return *((To *)AtomicAdjust::get_ptr(this->_void_ptr)); } @@ -148,7 +148,7 @@ operator *() const { * */ template -INLINE const TYPENAME ThreadSafeConstPointerTo::To *ThreadSafeConstPointerTo:: +INLINE const typename ThreadSafeConstPointerTo::To *ThreadSafeConstPointerTo:: operator -> () const { return (To *)AtomicAdjust::get_ptr(this->_void_ptr); } @@ -171,7 +171,7 @@ operator const T * () const { * to work around compiler problems, particularly for implicit upcasts. */ template -INLINE const TYPENAME ThreadSafeConstPointerTo::To *ThreadSafeConstPointerTo:: +INLINE const typename ThreadSafeConstPointerTo::To *ThreadSafeConstPointerTo:: p() const { return (To *)AtomicAdjust::get_ptr(this->_void_ptr); } diff --git a/panda/src/express/threadSafePointerTo.h b/panda/src/express/threadSafePointerTo.h index 56eeed1651..88699fa23a 100644 --- a/panda/src/express/threadSafePointerTo.h +++ b/panda/src/express/threadSafePointerTo.h @@ -26,9 +26,9 @@ template class ThreadSafePointerTo : public ThreadSafePointerToBase { public: - typedef TYPENAME ThreadSafePointerToBase::To To; + typedef typename ThreadSafePointerToBase::To To; PUBLISHED: - INLINE ThreadSafePointerTo(To *ptr = (To *)NULL); + INLINE ThreadSafePointerTo(To *ptr = nullptr); INLINE ThreadSafePointerTo(const ThreadSafePointerTo ©); INLINE ~ThreadSafePointerTo(); @@ -71,9 +71,9 @@ PUBLISHED: template class ThreadSafeConstPointerTo : public ThreadSafePointerToBase { public: - typedef TYPENAME ThreadSafePointerToBase::To To; + typedef typename ThreadSafePointerToBase::To To; PUBLISHED: - INLINE ThreadSafeConstPointerTo(const To *ptr = (const To *)NULL); + INLINE ThreadSafeConstPointerTo(const To *ptr = nullptr); INLINE ThreadSafeConstPointerTo(const ThreadSafePointerTo ©); INLINE ThreadSafeConstPointerTo(const ThreadSafeConstPointerTo ©); INLINE ~ThreadSafeConstPointerTo(); diff --git a/panda/src/express/threadSafePointerToBase.I b/panda/src/express/threadSafePointerToBase.I index 4d200a483a..bee16180b1 100644 --- a/panda/src/express/threadSafePointerToBase.I +++ b/panda/src/express/threadSafePointerToBase.I @@ -35,7 +35,7 @@ ThreadSafePointerToBase(const ThreadSafePointerToBase ©) { template INLINE ThreadSafePointerToBase:: ~ThreadSafePointerToBase() { - reassign((To *)NULL); + reassign(nullptr); } /** @@ -65,7 +65,7 @@ reassign(To *ptr) { _void_ptr = ptr; #endif // HAVE_THREADS - if (ptr != (To *)NULL) { + if (ptr != nullptr) { ptr->ref(); #ifdef DO_MEMORY_USAGE if (MemoryUsage::get_track_memory_usage()) { @@ -75,7 +75,7 @@ reassign(To *ptr) { } // Now delete the old pointer. - if (old_ptr != (To *)NULL) { + if (old_ptr != nullptr) { unref_delete(old_ptr); } } @@ -115,7 +115,7 @@ update_type(To *ptr) { template INLINE void ThreadSafePointerToBase:: clear() { - reassign((To *)NULL); + reassign(nullptr); } /** @@ -124,9 +124,9 @@ clear() { */ template INLINE void ThreadSafePointerToBase:: -output(ostream &out) const { +output(std::ostream &out) const { out << _void_ptr; - if (_void_ptr != (void *)NULL) { + if (_void_ptr != nullptr) { out << ":" << ((To *)_void_ptr)->get_ref_count(); } } diff --git a/panda/src/express/threadSafePointerToBase.h b/panda/src/express/threadSafePointerToBase.h index 78c6d75cca..764e538d2b 100644 --- a/panda/src/express/threadSafePointerToBase.h +++ b/panda/src/express/threadSafePointerToBase.h @@ -49,11 +49,11 @@ protected: PUBLISHED: INLINE void clear(); - void output(ostream &out) const; + void output(std::ostream &out) const; }; template -INLINE ostream &operator <<(ostream &out, const ThreadSafePointerToBase &pointer) { +INLINE std::ostream &operator <<(std::ostream &out, const ThreadSafePointerToBase &pointer) { pointer.output(out); return out; } diff --git a/panda/src/express/trueClock.I b/panda/src/express/trueClock.I index da51e8628f..3b7a80f66d 100644 --- a/panda/src/express/trueClock.I +++ b/panda/src/express/trueClock.I @@ -21,7 +21,7 @@ get_short_time() { bool is_paranoid_clock = get_paranoid_clock(); if (is_paranoid_clock) { - _lock.acquire(); + _lock.lock(); } double time = get_short_raw_time(); @@ -30,7 +30,7 @@ get_short_time() { // Check for rollforwards, rollbacks, and compensate for Speed Gear type // programs by verifying against the time of day clock. time = correct_time(time); - _lock.release(); + _lock.unlock(); } return time; @@ -66,7 +66,7 @@ get_error_count() const { */ INLINE TrueClock *TrueClock:: get_global_ptr() { - if (_global_ptr == (TrueClock *)NULL) { + if (_global_ptr == nullptr) { _global_ptr = new TrueClock; } return _global_ptr; diff --git a/panda/src/express/trueClock.cxx b/panda/src/express/trueClock.cxx index d2104f0ae0..f60ddc22dc 100644 --- a/panda/src/express/trueClock.cxx +++ b/panda/src/express/trueClock.cxx @@ -17,7 +17,10 @@ #include // for fabs() -TrueClock *TrueClock::_global_ptr = NULL; +using std::max; +using std::min; + +TrueClock *TrueClock::_global_ptr = nullptr; #if defined(WIN32_VC) || defined(WIN64_VC) @@ -169,7 +172,7 @@ TrueClock() { if (_has_high_res) { if (int_frequency <= 0) { clock_cat.error() - << "TrueClock::get_real_time() - frequency is negative!" << endl; + << "TrueClock::get_real_time() - frequency is negative!" << std::endl; _has_high_res = false; } else { @@ -198,7 +201,7 @@ TrueClock() { if (!_has_high_res) { clock_cat.warning() - << "No high resolution clock available." << endl; + << "No high resolution clock available." << std::endl; } } @@ -501,7 +504,7 @@ get_long_time() { #ifdef GETTIMEOFDAY_ONE_PARAM result = gettimeofday(&tv); #else - result = gettimeofday(&tv, (struct timezone *)NULL); + result = gettimeofday(&tv, nullptr); #endif if (result < 0) { @@ -527,7 +530,7 @@ get_short_raw_time() { #ifdef GETTIMEOFDAY_ONE_PARAM result = gettimeofday(&tv); #else - result = gettimeofday(&tv, (struct timezone *)NULL); + result = gettimeofday(&tv, nullptr); #endif if (result < 0) { @@ -561,7 +564,7 @@ TrueClock() { #ifdef GETTIMEOFDAY_ONE_PARAM result = gettimeofday(&tv); #else - result = gettimeofday(&tv, (struct timezone *)NULL); + result = gettimeofday(&tv, nullptr); #endif if (result < 0) { diff --git a/panda/src/express/trueClock.h b/panda/src/express/trueClock.h index 45ab097e8b..b6255f211a 100644 --- a/panda/src/express/trueClock.h +++ b/panda/src/express/trueClock.h @@ -30,7 +30,7 @@ * zero, this value can only be meaningfully used to measure elapsed time, by * sampling it at two different times and subtracting. */ -class EXPCL_PANDAEXPRESS TrueClock { +class EXPCL_PANDA_EXPRESS TrueClock { PUBLISHED: // get_long_time() returns the most accurate timer we have over a long // interval. It may not be very precise for measuring short intervals, but diff --git a/panda/src/express/typedReferenceCount.h b/panda/src/express/typedReferenceCount.h index 3f2daaab61..77cc5c3866 100644 --- a/panda/src/express/typedReferenceCount.h +++ b/panda/src/express/typedReferenceCount.h @@ -28,7 +28,7 @@ * * See also TypedObject for detailed instructions. */ -class EXPCL_PANDAEXPRESS TypedReferenceCount : public TypedObject, public ReferenceCount { +class EXPCL_PANDA_EXPRESS TypedReferenceCount : public TypedObject, public ReferenceCount { public: INLINE TypedReferenceCount(); INLINE TypedReferenceCount(const TypedReferenceCount ©); diff --git a/panda/src/express/virtualFile.I b/panda/src/express/virtualFile.I index f9fee3c999..64fa9f7d00 100644 --- a/panda/src/express/virtualFile.I +++ b/panda/src/express/virtualFile.I @@ -31,9 +31,9 @@ get_original_filename() const { /** * Returns the entire contents of the file as a string. */ -INLINE string VirtualFile:: +INLINE std::string VirtualFile:: read_file(bool auto_unwrap) const { - string result; + std::string result; read_file(result, auto_unwrap); return result; } @@ -42,7 +42,7 @@ read_file(bool auto_unwrap) const { * Writes the entire contents of the file as a string, if it is writable. */ INLINE bool VirtualFile:: -write_file(const string &data, bool auto_wrap) { +write_file(const std::string &data, bool auto_wrap) { return write_file((const unsigned char *)data.data(), data.size(), auto_wrap); } @@ -57,8 +57,8 @@ set_original_filename(const Filename &filename) { } -INLINE ostream & -operator << (ostream &out, const VirtualFile &file) { +INLINE std::ostream & +operator << (std::ostream &out, const VirtualFile &file) { file.output(out); return out; } diff --git a/panda/src/express/virtualFile.cxx b/panda/src/express/virtualFile.cxx index 1d12b7f250..e388d7c704 100644 --- a/panda/src/express/virtualFile.cxx +++ b/panda/src/express/virtualFile.cxx @@ -18,6 +18,11 @@ #include "pvector.h" #include +using std::iostream; +using std::istream; +using std::ostream; +using std::string; + TypeHandle VirtualFile::_type_handle; /** @@ -108,8 +113,8 @@ scan_directory() const { // Copy the set of nested mount points to a sorted list so we can search it // quickly. ov_set mount_points; - copy(mount_points_flat.begin(), mount_points_flat.end(), - back_inserter(mount_points)); + std::copy(mount_points_flat.begin(), mount_points_flat.end(), + std::back_inserter(mount_points)); mount_points.sort(); @@ -130,7 +135,7 @@ scan_directory() const { if (!scan_local_directory(file_list, mount_points)) { // Not a directory, or unable to read directory. if (file_list->get_num_files() == 0) { - return NULL; + return nullptr; } // We couldn't read the physical directory, but we do have some mounted @@ -155,7 +160,7 @@ output(ostream &out) const { void VirtualFile:: ls(ostream &out) const { CPT(VirtualFileList) contents = scan_directory(); - if (contents == (VirtualFileList *)NULL) { + if (contents == nullptr) { if (!is_directory()) { out << get_filename() << "\n"; } else { @@ -191,7 +196,7 @@ ls_all(ostream &out) const { */ istream *VirtualFile:: open_read_file(bool auto_unwrap) const { - return NULL; + return nullptr; } /** @@ -224,7 +229,7 @@ was_read_successful() const { */ ostream *VirtualFile:: open_write_file(bool auto_wrap, bool truncate) { - return NULL; + return nullptr; } /** @@ -234,7 +239,7 @@ open_write_file(bool auto_wrap, bool truncate) { */ ostream *VirtualFile:: open_append_file() { - return NULL; + return nullptr; } /** @@ -255,7 +260,7 @@ close_write_file(ostream *stream) { */ iostream *VirtualFile:: open_read_write_file(bool truncate) { - return NULL; + return nullptr; } /** @@ -265,7 +270,7 @@ open_read_write_file(bool truncate) { */ iostream *VirtualFile:: open_read_append_file() { - return NULL; + return nullptr; } /** @@ -284,7 +289,7 @@ close_read_write_file(iostream *stream) { * file. Pass in the stream that was returned by open_read_file(); some * implementations may require this stream to determine the size. */ -streamsize VirtualFile:: +std::streamsize VirtualFile:: get_file_size(istream *stream) const { return get_file_size(); } @@ -293,7 +298,7 @@ get_file_size(istream *stream) const { * Returns the current size on disk (or wherever it is) of the file before it * has been opened. */ -streamsize VirtualFile:: +std::streamsize VirtualFile:: get_file_size() const { return 0; } @@ -351,7 +356,7 @@ bool VirtualFile:: read_file(string &result, bool auto_unwrap) const { result = string(); - pvector pv; + vector_uchar pv; if (!read_file(pv, auto_unwrap)) { return false; } @@ -368,7 +373,7 @@ read_file(string &result, bool auto_unwrap) const { * regular file. Returns true on success, false otherwise. */ bool VirtualFile:: -read_file(pvector &result, bool auto_unwrap) const { +read_file(vector_uchar &result, bool auto_unwrap) const { return false; } @@ -387,7 +392,7 @@ write_file(const unsigned char *data, size_t data_size, bool auto_wrap) { * entry, the data read from the file will be appended onto it. */ bool VirtualFile:: -simple_read_file(istream *in, pvector &result) { +simple_read_file(istream *in, vector_uchar &result) { static const size_t buffer_size = 4096; char buffer[buffer_size]; @@ -408,18 +413,18 @@ simple_read_file(istream *in, pvector &result) { * max_bytes bytes from the file. */ bool VirtualFile:: -simple_read_file(istream *in, pvector &result, size_t max_bytes) { +simple_read_file(istream *in, vector_uchar &result, size_t max_bytes) { static const size_t buffer_size = 4096; char buffer[buffer_size]; - in->read(buffer, min(buffer_size, max_bytes)); + in->read(buffer, std::min(buffer_size, max_bytes)); size_t count = in->gcount(); while (count != 0) { thread_consider_yield(); nassertr(count <= max_bytes, false); result.insert(result.end(), buffer, buffer + count); max_bytes -= count; - in->read(buffer, min(buffer_size, max_bytes)); + in->read(buffer, std::min(buffer_size, max_bytes)); count = in->gcount(); } @@ -443,7 +448,7 @@ scan_local_directory(VirtualFileList *, const ov_set &) const { void VirtualFile:: r_ls_all(ostream &out, const Filename &root) const { CPT(VirtualFileList) contents = scan_directory(); - if (contents == (VirtualFileList *)NULL) { + if (contents == nullptr) { return; } diff --git a/panda/src/express/virtualFile.h b/panda/src/express/virtualFile.h index 5322fce670..2198e2dde3 100644 --- a/panda/src/express/virtualFile.h +++ b/panda/src/express/virtualFile.h @@ -21,7 +21,7 @@ #include "pointerTo.h" #include "typedReferenceCount.h" #include "ordered_vector.h" -#include "pvector.h" +#include "vector_uchar.h" class VirtualFileMount; class VirtualFileList; @@ -32,7 +32,7 @@ class VirtualFileSystem; * The abstract base class for a file or directory within the * VirtualFileSystem. */ -class EXPCL_PANDAEXPRESS VirtualFile : public TypedReferenceCount { +class EXPCL_PANDA_EXPRESS VirtualFile : public TypedReferenceCount { public: INLINE VirtualFile(); @@ -52,51 +52,51 @@ PUBLISHED: BLOCKING PT(VirtualFileList) scan_directory() const; - void output(ostream &out) const; - BLOCKING void ls(ostream &out = cout) const; - BLOCKING void ls_all(ostream &out = cout) const; + void output(std::ostream &out) const; + BLOCKING void ls(std::ostream &out = std::cout) const; + BLOCKING void ls_all(std::ostream &out = std::cout) const; EXTENSION(PyObject *read_file(bool auto_unwrap) const); - BLOCKING virtual istream *open_read_file(bool auto_unwrap) const; - BLOCKING virtual void close_read_file(istream *stream) const; + BLOCKING virtual std::istream *open_read_file(bool auto_unwrap) const; + BLOCKING virtual void close_read_file(std::istream *stream) const; virtual bool was_read_successful() const; EXTENSION(PyObject *write_file(PyObject *data, bool auto_wrap)); - BLOCKING virtual ostream *open_write_file(bool auto_wrap, bool truncate); - BLOCKING virtual ostream *open_append_file(); - BLOCKING virtual void close_write_file(ostream *stream); + BLOCKING virtual std::ostream *open_write_file(bool auto_wrap, bool truncate); + BLOCKING virtual std::ostream *open_append_file(); + BLOCKING virtual void close_write_file(std::ostream *stream); - BLOCKING virtual iostream *open_read_write_file(bool truncate); - BLOCKING virtual iostream *open_read_append_file(); - BLOCKING virtual void close_read_write_file(iostream *stream); + BLOCKING virtual std::iostream *open_read_write_file(bool truncate); + BLOCKING virtual std::iostream *open_read_append_file(); + BLOCKING virtual void close_read_write_file(std::iostream *stream); - BLOCKING virtual streamsize get_file_size(istream *stream) const; - BLOCKING virtual streamsize get_file_size() const; + BLOCKING virtual std::streamsize get_file_size(std::istream *stream) const; + BLOCKING virtual std::streamsize get_file_size() const; BLOCKING virtual time_t get_timestamp() const; virtual bool get_system_info(SubfileInfo &info); public: - virtual bool atomic_compare_and_exchange_contents(string &orig_contents, const string &old_contents, const string &new_contents); - virtual bool atomic_read_contents(string &contents) const; + virtual bool atomic_compare_and_exchange_contents(std::string &orig_contents, const std::string &old_contents, const std::string &new_contents); + virtual bool atomic_read_contents(std::string &contents) const; - INLINE string read_file(bool auto_unwrap) const; - INLINE bool write_file(const string &data, bool auto_wrap); + INLINE std::string read_file(bool auto_unwrap) const; + INLINE bool write_file(const std::string &data, bool auto_wrap); INLINE void set_original_filename(const Filename &filename); - bool read_file(string &result, bool auto_unwrap) const; - virtual bool read_file(pvector &result, bool auto_unwrap) const; + bool read_file(std::string &result, bool auto_unwrap) const; + virtual bool read_file(vector_uchar &result, bool auto_unwrap) const; virtual bool write_file(const unsigned char *data, size_t data_size, bool auto_wrap); - static bool simple_read_file(istream *stream, pvector &result); - static bool simple_read_file(istream *stream, pvector &result, size_t max_bytes); + static bool simple_read_file(std::istream *stream, vector_uchar &result); + static bool simple_read_file(std::istream *stream, vector_uchar &result, size_t max_bytes); protected: virtual bool scan_local_directory(VirtualFileList *file_list, - const ov_set &mount_points) const; + const ov_set &mount_points) const; private: - void r_ls_all(ostream &out, const Filename &root) const; + void r_ls_all(std::ostream &out, const Filename &root) const; Filename _original_filename; @@ -121,7 +121,7 @@ private: friend class VirtualFileComposite; }; -INLINE ostream &operator << (ostream &out, const VirtualFile &file); +INLINE std::ostream &operator << (std::ostream &out, const VirtualFile &file); #include "virtualFile.I" diff --git a/panda/src/express/virtualFileComposite.cxx b/panda/src/express/virtualFileComposite.cxx index 30a5cbb0d9..63c4f8d569 100644 --- a/panda/src/express/virtualFileComposite.cxx +++ b/panda/src/express/virtualFileComposite.cxx @@ -57,7 +57,7 @@ is_directory() const { */ bool VirtualFileComposite:: scan_local_directory(VirtualFileList *file_list, - const ov_set &mount_points) const { + const ov_set &mount_points) const { bool any_ok = false; Components::const_iterator ci; for (ci = _components.begin(); ci != _components.end(); ++ci) { diff --git a/panda/src/express/virtualFileComposite.h b/panda/src/express/virtualFileComposite.h index d7e39ed302..3e41e36fef 100644 --- a/panda/src/express/virtualFileComposite.h +++ b/panda/src/express/virtualFileComposite.h @@ -23,7 +23,7 @@ * one directory on different mount points. The resulting directory appears * to be the union of all the individual simple directories. */ -class EXPCL_PANDAEXPRESS VirtualFileComposite : public VirtualFile { +class EXPCL_PANDA_EXPRESS VirtualFileComposite : public VirtualFile { public: INLINE VirtualFileComposite(VirtualFileSystem *file_system, const Filename &filename); @@ -38,7 +38,7 @@ public: protected: virtual bool scan_local_directory(VirtualFileList *file_list, - const ov_set &mount_points) const; + const ov_set &mount_points) const; private: VirtualFileSystem *_file_system; diff --git a/panda/src/express/virtualFileList.I b/panda/src/express/virtualFileList.I index efd87c2711..14b29361b3 100644 --- a/panda/src/express/virtualFileList.I +++ b/panda/src/express/virtualFileList.I @@ -46,7 +46,7 @@ get_num_files() const { */ INLINE VirtualFile *VirtualFileList:: get_file(size_t n) const { - nassertr(n < _files.size(), NULL); + nassertr(n < _files.size(), nullptr); return _files[n]; } @@ -55,7 +55,7 @@ get_file(size_t n) const { */ INLINE VirtualFile *VirtualFileList:: operator [](size_t n) const { - nassertr(n < _files.size(), NULL); + nassertr(n < _files.size(), nullptr); return _files[n]; } diff --git a/panda/src/express/virtualFileList.h b/panda/src/express/virtualFileList.h index 6f01172a7a..4f900d6a50 100644 --- a/panda/src/express/virtualFileList.h +++ b/panda/src/express/virtualFileList.h @@ -22,7 +22,7 @@ /** * A list of VirtualFiles, as returned by VirtualFile::scan_directory(). */ -class EXPCL_PANDAEXPRESS VirtualFileList : public ReferenceCount { +class EXPCL_PANDA_EXPRESS VirtualFileList : public ReferenceCount { public: INLINE VirtualFileList(); diff --git a/panda/src/express/virtualFileMount.I b/panda/src/express/virtualFileMount.I index 81e22016bf..31da104cf8 100644 --- a/panda/src/express/virtualFileMount.I +++ b/panda/src/express/virtualFileMount.I @@ -16,7 +16,7 @@ */ INLINE VirtualFileMount:: VirtualFileMount() : - _file_system(NULL), + _file_system(nullptr), _mount_flags(0) { } @@ -49,8 +49,8 @@ get_mount_flags() const { } -INLINE ostream & -operator << (ostream &out, const VirtualFileMount &mount) { +INLINE std::ostream & +operator << (std::ostream &out, const VirtualFileMount &mount) { mount.output(out); return out; } diff --git a/panda/src/express/virtualFileMount.cxx b/panda/src/express/virtualFileMount.cxx index 89e8ddfc24..0bfc9fc3e3 100644 --- a/panda/src/express/virtualFileMount.cxx +++ b/panda/src/express/virtualFileMount.cxx @@ -16,6 +16,11 @@ #include "virtualFileSystem.h" #include "zStream.h" +using std::iostream; +using std::istream; +using std::ostream; +using std::string; + TypeHandle VirtualFileMount::_type_handle; @@ -24,7 +29,7 @@ TypeHandle VirtualFileMount::_type_handle; */ VirtualFileMount:: ~VirtualFileMount() { - nassertv(_file_system == NULL); + nassertv(_file_system == nullptr); } /** @@ -53,7 +58,7 @@ make_virtual_file(const Filename &local_filename, make_directory(local); } - return file.p(); + return file; } /** @@ -124,17 +129,17 @@ is_writable(const Filename &file) const { */ bool VirtualFileMount:: read_file(const Filename &file, bool do_uncompress, - pvector &result) const { + vector_uchar &result) const { result.clear(); istream *in = open_read_file(file, do_uncompress); - if (in == (istream *)NULL) { + if (in == nullptr) { express_cat.info() << "Unable to read " << file << "\n"; return false; } - streamsize file_size = get_file_size(file, in); + std::streamsize file_size = get_file_size(file, in); if (file_size > 0) { result.reserve((size_t)file_size); } @@ -158,7 +163,7 @@ bool VirtualFileMount:: write_file(const Filename &file, bool do_compress, const unsigned char *data, size_t data_size) { ostream *out = open_write_file(file, do_compress, true); - if (out == (ostream *)NULL) { + if (out == nullptr) { express_cat.info() << "Unable to write " << file << "\n"; return false; @@ -188,7 +193,7 @@ open_read_file(const Filename &file, bool do_uncompress) const { istream *result = open_read_file(file); #ifdef HAVE_ZLIB - if (result != (istream *)NULL && do_uncompress) { + if (result != nullptr && do_uncompress) { // We have to slip in a layer to decompress the file on the fly. IDecompressStream *wrapper = new IDecompressStream(result, true); result = wrapper; @@ -216,7 +221,7 @@ close_read_file(istream *stream) const { */ ostream *VirtualFileMount:: open_write_file(const Filename &file, bool truncate) { - return NULL; + return nullptr; } /** @@ -231,7 +236,7 @@ open_write_file(const Filename &file, bool do_compress, bool truncate) { ostream *result = open_write_file(file, truncate); #ifdef HAVE_ZLIB - if (result != (ostream *)NULL && do_compress) { + if (result != nullptr && do_compress) { // We have to slip in a layer to compress the file on the fly. OCompressStream *wrapper = new OCompressStream(result, true); result = wrapper; @@ -248,7 +253,7 @@ open_write_file(const Filename &file, bool do_compress, bool truncate) { */ ostream *VirtualFileMount:: open_append_file(const Filename &file) { - return NULL; + return nullptr; } /** @@ -269,7 +274,7 @@ close_write_file(ostream *stream) { */ iostream *VirtualFileMount:: open_read_write_file(const Filename &file, bool truncate) { - return NULL; + return nullptr; } /** @@ -279,7 +284,7 @@ open_read_write_file(const Filename &file, bool truncate) { */ iostream *VirtualFileMount:: open_read_append_file(const Filename &file) { - return NULL; + return nullptr; } /** diff --git a/panda/src/express/virtualFileMount.h b/panda/src/express/virtualFileMount.h index 47b36b52f1..137400b1c0 100644 --- a/panda/src/express/virtualFileMount.h +++ b/panda/src/express/virtualFileMount.h @@ -28,7 +28,7 @@ class VirtualFileSystem; * VirtualFileSystem. Normally users don't need to monkey with this class * directly. */ -class EXPCL_PANDAEXPRESS VirtualFileMount : public TypedReferenceCount { +class EXPCL_PANDA_EXPRESS VirtualFileMount : public TypedReferenceCount { PUBLISHED: INLINE VirtualFileMount(); virtual ~VirtualFileMount(); @@ -54,37 +54,37 @@ public: virtual bool is_writable(const Filename &file) const; virtual bool read_file(const Filename &file, bool do_uncompress, - pvector &result) const; + vector_uchar &result) const; virtual bool write_file(const Filename &file, bool do_compress, const unsigned char *data, size_t data_size); - virtual istream *open_read_file(const Filename &file) const=0; - istream *open_read_file(const Filename &file, bool do_uncompress) const; - virtual void close_read_file(istream *stream) const; + virtual std::istream *open_read_file(const Filename &file) const=0; + std::istream *open_read_file(const Filename &file, bool do_uncompress) const; + virtual void close_read_file(std::istream *stream) const; - virtual ostream *open_write_file(const Filename &file, bool truncate); - ostream *open_write_file(const Filename &file, bool do_compress, bool truncate); - virtual ostream *open_append_file(const Filename &file); - virtual void close_write_file(ostream *stream); + virtual std::ostream *open_write_file(const Filename &file, bool truncate); + std::ostream *open_write_file(const Filename &file, bool do_compress, bool truncate); + virtual std::ostream *open_append_file(const Filename &file); + virtual void close_write_file(std::ostream *stream); - virtual iostream *open_read_write_file(const Filename &file, bool truncate); - virtual iostream *open_read_append_file(const Filename &file); - virtual void close_read_write_file(iostream *stream); + virtual std::iostream *open_read_write_file(const Filename &file, bool truncate); + virtual std::iostream *open_read_append_file(const Filename &file); + virtual void close_read_write_file(std::iostream *stream); - virtual streamsize get_file_size(const Filename &file, istream *stream) const=0; - virtual streamsize get_file_size(const Filename &file) const=0; + virtual std::streamsize get_file_size(const Filename &file, std::istream *stream) const=0; + virtual std::streamsize get_file_size(const Filename &file) const=0; virtual time_t get_timestamp(const Filename &file) const=0; virtual bool get_system_info(const Filename &file, SubfileInfo &info); virtual bool scan_directory(vector_string &contents, const Filename &dir) const=0; - virtual bool atomic_compare_and_exchange_contents(const Filename &file, string &orig_contents, const string &old_contents, const string &new_contents); - virtual bool atomic_read_contents(const Filename &file, string &contents) const; + virtual bool atomic_compare_and_exchange_contents(const Filename &file, std::string &orig_contents, const std::string &old_contents, const std::string &new_contents); + virtual bool atomic_read_contents(const Filename &file, std::string &contents) const; PUBLISHED: - virtual void output(ostream &out) const; - virtual void write(ostream &out) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out) const; protected: VirtualFileSystem *_file_system; @@ -112,7 +112,7 @@ private: friend class VirtualFileSystem; }; -INLINE ostream &operator << (ostream &out, const VirtualFileMount &mount); +INLINE std::ostream &operator << (std::ostream &out, const VirtualFileMount &mount); #include "virtualFileMount.I" diff --git a/panda/src/express/virtualFileMountAndroidAsset.I b/panda/src/express/virtualFileMountAndroidAsset.I index 7a96300d99..c3079e04ee 100644 --- a/panda/src/express/virtualFileMountAndroidAsset.I +++ b/panda/src/express/virtualFileMountAndroidAsset.I @@ -15,7 +15,7 @@ * */ VirtualFileMountAndroidAsset:: -VirtualFileMountAndroidAsset(AAssetManager *mgr, const string &apk_path) : +VirtualFileMountAndroidAsset(AAssetManager *mgr, const std::string &apk_path) : _asset_mgr(mgr), _apk_path(apk_path) { } @@ -25,5 +25,5 @@ VirtualFileMountAndroidAsset(AAssetManager *mgr, const string &apk_path) : */ INLINE VirtualFileMountAndroidAsset::AssetStream:: AssetStream(AAsset *asset) : - istream(new VirtualFileMountAndroidAsset::AssetStreamBuf(asset)) { + std::istream(new VirtualFileMountAndroidAsset::AssetStreamBuf(asset)) { } diff --git a/panda/src/express/virtualFileMountAndroidAsset.cxx b/panda/src/express/virtualFileMountAndroidAsset.cxx index d7ffb6254a..c9074fe97a 100644 --- a/panda/src/express/virtualFileMountAndroidAsset.cxx +++ b/panda/src/express/virtualFileMountAndroidAsset.cxx @@ -20,6 +20,10 @@ #include #endif +using std::streamoff; +using std::streampos; +using std::streamsize; + TypeHandle VirtualFileMountAndroidAsset::_type_handle; /** @@ -80,7 +84,7 @@ is_regular_file(const Filename &file) const { //express_cat.error() << "is_regular_file " << file << " - " << asset << "\n"; - if (asset == NULL) { + if (asset == nullptr) { return false; } AAsset_close(asset); @@ -93,7 +97,7 @@ is_regular_file(const Filename &file) const { */ bool VirtualFileMountAndroidAsset:: read_file(const Filename &file, bool do_uncompress, - pvector &result) const { + vector_uchar &result) const { if (do_uncompress) { // If the file is to be decompressed, we'd better just use the higher- // level implementation, which includes support for on-the-fly @@ -107,7 +111,7 @@ read_file(const Filename &file, bool do_uncompress, AAsset* asset; asset = AAssetManager_open(_asset_mgr, file.c_str(), AASSET_MODE_STREAMING); - if (asset == (AAsset *)NULL) { + if (asset == nullptr) { express_cat.info() << "Unable to read " << file << "\n"; return false; @@ -140,16 +144,16 @@ read_file(const Filename &file, bool do_uncompress, * istream on success (which you should eventually delete when you are done * reading). Returns NULL on failure. */ -istream *VirtualFileMountAndroidAsset:: +std::istream *VirtualFileMountAndroidAsset:: open_read_file(const Filename &file) const { AAsset* asset; asset = AAssetManager_open(_asset_mgr, file.c_str(), AASSET_MODE_UNKNOWN); - if (asset == (AAsset *)NULL) { - return NULL; + if (asset == nullptr) { + return nullptr; } AssetStream *stream = new AssetStream(asset); - return (istream *) stream; + return (std::istream *) stream; } /** @@ -158,7 +162,7 @@ open_read_file(const Filename &file) const { * implementations may require this stream to determine the size. */ streamsize VirtualFileMountAndroidAsset:: -get_file_size(const Filename &file, istream *in) const { +get_file_size(const Filename &file, std::istream *in) const { // If it's already open, get the AAsset pointer from the streambuf. const AssetStreamBuf *buf = (const AssetStreamBuf *) in->rdbuf(); off_t length = AAsset_getLength(buf->_asset); @@ -229,14 +233,14 @@ get_system_info(const Filename &file, SubfileInfo &info) { bool VirtualFileMountAndroidAsset:: scan_directory(vector_string &contents, const Filename &dir) const { AAssetDir *asset_dir = AAssetManager_openDir(_asset_mgr, dir.c_str()); - if (asset_dir == NULL) { + if (asset_dir == nullptr) { return false; } // Note: this returns the full path. const char *fullpath = AAssetDir_getNextFileName(asset_dir); - while (fullpath != NULL) { + while (fullpath != nullptr) { express_cat.error() << fullpath << "\n"; // DEBUG // Determine the basename and add it to the vector. Filename fname (fullpath); @@ -290,10 +294,10 @@ seekoff(streamoff off, ios_seekdir dir, ios_openmode which) { int whence; switch (dir) { - case ios_base::beg: + case std::ios_base::beg: whence = SEEK_SET; break; - case ios_base::cur: + case std::ios_base::cur: if (off == 0) { // Just requesting the current position, no need to void the buffer. return AAsset_seek(_asset, 0, SEEK_CUR) - n; @@ -305,7 +309,7 @@ seekoff(streamoff off, ios_seekdir dir, ios_openmode which) { } whence = SEEK_CUR; break; - case ios_base::end: + case std::ios_base::end: whence = SEEK_END; break; default: diff --git a/panda/src/express/virtualFileMountAndroidAsset.h b/panda/src/express/virtualFileMountAndroidAsset.h index 792db38ffc..1caccf98f5 100644 --- a/panda/src/express/virtualFileMountAndroidAsset.h +++ b/panda/src/express/virtualFileMountAndroidAsset.h @@ -27,9 +27,9 @@ /** * Maps a Multifile's contents into the VirtualFileSystem. */ -class EXPCL_PANDAEXPRESS VirtualFileMountAndroidAsset : public VirtualFileMount { +class EXPCL_PANDA_EXPRESS VirtualFileMountAndroidAsset : public VirtualFileMount { PUBLISHED: - INLINE VirtualFileMountAndroidAsset(AAssetManager *mgr, const string &apk_path); + INLINE VirtualFileMountAndroidAsset(AAssetManager *mgr, const std::string &apk_path); virtual ~VirtualFileMountAndroidAsset(); public: @@ -40,11 +40,11 @@ public: virtual bool is_regular_file(const Filename &file) const; virtual bool read_file(const Filename &file, bool do_uncompress, - pvector &result) const; + vector_uchar &result) const; - virtual istream *open_read_file(const Filename &file) const; - virtual streamsize get_file_size(const Filename &file, istream *stream) const; - virtual streamsize get_file_size(const Filename &file) const; + virtual std::istream *open_read_file(const Filename &file) const; + virtual std::streamsize get_file_size(const Filename &file, std::istream *stream) const; + virtual std::streamsize get_file_size(const Filename &file) const; virtual time_t get_timestamp(const Filename &file) const; virtual bool get_system_info(const Filename &file, SubfileInfo &info); @@ -53,21 +53,21 @@ public: private: AAssetManager *_asset_mgr; - string _apk_path; + std::string _apk_path; - class AssetStream : public istream { + class AssetStream : public std::istream { public: INLINE AssetStream(AAsset *asset); virtual ~AssetStream(); }; - class AssetStreamBuf : public streambuf { + class AssetStreamBuf : public std::streambuf { public: AssetStreamBuf(AAsset *asset); virtual ~AssetStreamBuf(); - virtual streampos seekoff(streamoff off, ios_seekdir dir, ios_openmode which); - virtual streampos seekpos(streampos pos, ios_openmode which); + virtual std::streampos seekoff(std::streamoff off, ios_seekdir dir, ios_openmode which); + virtual std::streampos seekpos(std::streampos pos, ios_openmode which); protected: virtual int underflow(); diff --git a/panda/src/express/virtualFileMountMultifile.cxx b/panda/src/express/virtualFileMountMultifile.cxx index c871ea39a1..1c9a0782ba 100644 --- a/panda/src/express/virtualFileMountMultifile.cxx +++ b/panda/src/express/virtualFileMountMultifile.cxx @@ -59,7 +59,7 @@ is_regular_file(const Filename &file) const { */ bool VirtualFileMountMultifile:: read_file(const Filename &file, bool do_uncompress, - pvector &result) const { + vector_uchar &result) const { if (do_uncompress) { // If the file is to be decompressed, we'd better just use the higher- // level implementation, which includes support for on-the-fly @@ -85,11 +85,11 @@ read_file(const Filename &file, bool do_uncompress, * istream on success (which you should eventually delete when you are done * reading). Returns NULL on failure. */ -istream *VirtualFileMountMultifile:: +std::istream *VirtualFileMountMultifile:: open_read_file(const Filename &file) const { int subfile_index = _multifile->find_subfile(file); if (subfile_index < 0) { - return NULL; + return nullptr; } // The caller will eventually pass this pointer to @@ -104,8 +104,8 @@ open_read_file(const Filename &file) const { * file. Pass in the stream that was returned by open_read_file(); some * implementations may require this stream to determine the size. */ -streamsize VirtualFileMountMultifile:: -get_file_size(const Filename &file, istream *) const { +std::streamsize VirtualFileMountMultifile:: +get_file_size(const Filename &file, std::istream *) const { int subfile_index = _multifile->find_subfile(file); if (subfile_index < 0) { return 0; @@ -117,7 +117,7 @@ get_file_size(const Filename &file, istream *) const { * Returns the current size on disk (or wherever it is) of the file before it * has been opened. */ -streamsize VirtualFileMountMultifile:: +std::streamsize VirtualFileMountMultifile:: get_file_size(const Filename &file) const { int subfile_index = _multifile->find_subfile(file); if (subfile_index < 0) { @@ -167,7 +167,7 @@ get_system_info(const Filename &file, SubfileInfo &info) { return false; } - streampos start = _multifile->get_subfile_internal_start(subfile_index); + std::streampos start = _multifile->get_subfile_internal_start(subfile_index); size_t length = _multifile->get_subfile_internal_length(subfile_index); info = SubfileInfo(multifile_name, start, length); @@ -189,6 +189,6 @@ scan_directory(vector_string &contents, const Filename &dir) const { * */ void VirtualFileMountMultifile:: -output(ostream &out) const { +output(std::ostream &out) const { out << _multifile->get_multifile_name(); } diff --git a/panda/src/express/virtualFileMountMultifile.h b/panda/src/express/virtualFileMountMultifile.h index d82b29af4d..23b60df447 100644 --- a/panda/src/express/virtualFileMountMultifile.h +++ b/panda/src/express/virtualFileMountMultifile.h @@ -23,7 +23,7 @@ /** * Maps a Multifile's contents into the VirtualFileSystem. */ -class EXPCL_PANDAEXPRESS VirtualFileMountMultifile : public VirtualFileMount { +class EXPCL_PANDA_EXPRESS VirtualFileMountMultifile : public VirtualFileMount { PUBLISHED: INLINE VirtualFileMountMultifile(Multifile *multifile); virtual ~VirtualFileMountMultifile(); @@ -36,18 +36,18 @@ public: virtual bool is_regular_file(const Filename &file) const; virtual bool read_file(const Filename &file, bool do_uncompress, - pvector &result) const; + vector_uchar &result) const; - virtual istream *open_read_file(const Filename &file) const; - virtual streamsize get_file_size(const Filename &file, istream *stream) const; - virtual streamsize get_file_size(const Filename &file) const; + virtual std::istream *open_read_file(const Filename &file) const; + virtual std::streamsize get_file_size(const Filename &file, std::istream *stream) const; + virtual std::streamsize get_file_size(const Filename &file) const; virtual time_t get_timestamp(const Filename &file) const; virtual bool get_system_info(const Filename &file, SubfileInfo &info); virtual bool scan_directory(vector_string &contents, const Filename &dir) const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: PT(Multifile) _multifile; diff --git a/panda/src/express/virtualFileMountRamdisk.I b/panda/src/express/virtualFileMountRamdisk.I index 37d89f9ce3..27c07c4dce 100644 --- a/panda/src/express/virtualFileMountRamdisk.I +++ b/panda/src/express/virtualFileMountRamdisk.I @@ -15,7 +15,7 @@ * */ INLINE VirtualFileMountRamdisk::FileBase:: -FileBase(const string &basename) : _basename(basename), _timestamp(time(NULL)) { +FileBase(const std::string &basename) : _basename(basename), _timestamp(time(nullptr)) { } /** @@ -30,7 +30,7 @@ operator < (const FileBase &other) const { * */ INLINE VirtualFileMountRamdisk::File:: -File(const string &basename) : +File(const std::string &basename) : FileBase(basename), _wrapper(&_data, false, true) { @@ -40,5 +40,5 @@ File(const string &basename) : * */ INLINE VirtualFileMountRamdisk::Directory:: -Directory(const string &basename) : FileBase(basename) { +Directory(const std::string &basename) : FileBase(basename) { } diff --git a/panda/src/express/virtualFileMountRamdisk.cxx b/panda/src/express/virtualFileMountRamdisk.cxx index 244f5c79df..feda85d1f6 100644 --- a/panda/src/express/virtualFileMountRamdisk.cxx +++ b/panda/src/express/virtualFileMountRamdisk.cxx @@ -15,6 +15,11 @@ #include "subStream.h" #include "dcast.h" +using std::iostream; +using std::istream; +using std::ostream; +using std::string; + TypeHandle VirtualFileMountRamdisk::_type_handle; TypeHandle VirtualFileMountRamdisk::FileBase::_type_handle; TypeHandle VirtualFileMountRamdisk::File::_type_handle; @@ -32,10 +37,10 @@ VirtualFileMountRamdisk() : _root("") { */ bool VirtualFileMountRamdisk:: has_file(const Filename &file) const { - _lock.acquire(); + _lock.lock(); PT(FileBase) f = _root.do_find_file(file); - _lock.release(); - return (f != NULL); + _lock.unlock(); + return (f != nullptr); } /** @@ -45,10 +50,10 @@ has_file(const Filename &file) const { */ bool VirtualFileMountRamdisk:: create_file(const Filename &file) { - _lock.acquire(); + _lock.lock(); PT(File) f = _root.do_create_file(file); - _lock.release(); - return (f != NULL); + _lock.unlock(); + return (f != nullptr); } /** @@ -58,10 +63,10 @@ create_file(const Filename &file) { */ bool VirtualFileMountRamdisk:: delete_file(const Filename &file) { - _lock.acquire(); + _lock.lock(); PT(FileBase) f = _root.do_delete_file(file); - _lock.release(); - return (f != NULL); + _lock.unlock(); + return (f != nullptr); } /** @@ -72,10 +77,10 @@ delete_file(const Filename &file) { */ bool VirtualFileMountRamdisk:: rename_file(const Filename &orig_filename, const Filename &new_filename) { - _lock.acquire(); + _lock.lock(); PT(FileBase) orig_fb = _root.do_find_file(orig_filename); - if (orig_fb == NULL) { - _lock.release(); + if (orig_fb == nullptr) { + _lock.unlock(); return false; } @@ -83,8 +88,8 @@ rename_file(const Filename &orig_filename, const Filename &new_filename) { // Rename the directory. Directory *orig_d = DCAST(Directory, orig_fb); PT(Directory) new_d = _root.do_make_directory(new_filename); - if (new_d == NULL || !new_d->_files.empty()) { - _lock.release(); + if (new_d == nullptr || !new_d->_files.empty()) { + _lock.unlock(); return false; } @@ -95,15 +100,15 @@ rename_file(const Filename &orig_filename, const Filename &new_filename) { new_d->_files.swap(orig_d->_files); _root.do_delete_file(orig_filename); - _lock.release(); + _lock.unlock(); return true; } // Rename the file. File *orig_f = DCAST(File, orig_fb); PT(File) new_f = _root.do_create_file(new_filename); - if (new_f == NULL) { - _lock.release(); + if (new_f == nullptr) { + _lock.unlock(); return false; } @@ -115,7 +120,7 @@ rename_file(const Filename &orig_filename, const Filename &new_filename) { new_f->_data.str(orig_f->_data.str()); _root.do_delete_file(orig_filename); - _lock.release(); + _lock.unlock(); return true; } @@ -127,18 +132,18 @@ rename_file(const Filename &orig_filename, const Filename &new_filename) { */ bool VirtualFileMountRamdisk:: copy_file(const Filename &orig_filename, const Filename &new_filename) { - _lock.acquire(); + _lock.lock(); PT(FileBase) orig_fb = _root.do_find_file(orig_filename); - if (orig_fb == NULL || orig_fb->is_directory()) { - _lock.release(); + if (orig_fb == nullptr || orig_fb->is_directory()) { + _lock.unlock(); return false; } // Copy the file. File *orig_f = DCAST(File, orig_fb); PT(File) new_f = _root.do_create_file(new_filename); - if (new_f == NULL) { - _lock.release(); + if (new_f == nullptr) { + _lock.unlock(); return false; } @@ -149,7 +154,7 @@ copy_file(const Filename &orig_filename, const Filename &new_filename) { new_f->_data.str(orig_f->_data.str()); - _lock.release(); + _lock.unlock(); return true; } @@ -161,10 +166,10 @@ copy_file(const Filename &orig_filename, const Filename &new_filename) { */ bool VirtualFileMountRamdisk:: make_directory(const Filename &file) { - _lock.acquire(); + _lock.lock(); PT(Directory) f = _root.do_make_directory(file); - _lock.release(); - return (f != NULL); + _lock.unlock(); + return (f != nullptr); } /** @@ -173,10 +178,10 @@ make_directory(const Filename &file) { */ bool VirtualFileMountRamdisk:: is_directory(const Filename &file) const { - _lock.acquire(); + _lock.lock(); PT(FileBase) f = _root.do_find_file(file); - _lock.release(); - return (f != NULL && f->is_directory()); + _lock.unlock(); + return (f != nullptr && f->is_directory()); } /** @@ -185,10 +190,10 @@ is_directory(const Filename &file) const { */ bool VirtualFileMountRamdisk:: is_regular_file(const Filename &file) const { - _lock.acquire(); + _lock.lock(); PT(FileBase) f = _root.do_find_file(file); - _lock.release(); - return (f != NULL && !f->is_directory()); + _lock.unlock(); + return (f != nullptr && !f->is_directory()); } /** @@ -207,11 +212,11 @@ is_writable(const Filename &file) const { */ istream *VirtualFileMountRamdisk:: open_read_file(const Filename &file) const { - _lock.acquire(); + _lock.lock(); PT(FileBase) f = _root.do_find_file(file); - _lock.release(); - if (f == (FileBase *)NULL || f->is_directory()) { - return NULL; + _lock.unlock(); + if (f == nullptr || f->is_directory()) { + return nullptr; } File *f2 = DCAST(File, f); @@ -225,11 +230,11 @@ open_read_file(const Filename &file) const { */ ostream *VirtualFileMountRamdisk:: open_write_file(const Filename &file, bool truncate) { - _lock.acquire(); + _lock.lock(); PT(File) f = _root.do_create_file(file); - _lock.release(); - if (f == (File *)NULL) { - return NULL; + _lock.unlock(); + if (f == nullptr) { + return nullptr; } if (truncate) { @@ -241,7 +246,7 @@ open_write_file(const Filename &file, bool truncate) { // second, since the timer only has a one second precision. The proper // solution to fix this would be to switch to a higher precision // timer everywhere. - f->_timestamp = max(f->_timestamp + 1, time(NULL)); + f->_timestamp = std::max(f->_timestamp + 1, time(nullptr)); } return new OSubStream(&f->_wrapper, 0, 0); @@ -254,11 +259,11 @@ open_write_file(const Filename &file, bool truncate) { */ ostream *VirtualFileMountRamdisk:: open_append_file(const Filename &file) { - _lock.acquire(); + _lock.lock(); PT(File) f = _root.do_create_file(file); - _lock.release(); - if (f == (File *)NULL) { - return NULL; + _lock.unlock(); + if (f == nullptr) { + return nullptr; } return new OSubStream(&f->_wrapper, 0, 0, true); @@ -271,11 +276,11 @@ open_append_file(const Filename &file) { */ iostream *VirtualFileMountRamdisk:: open_read_write_file(const Filename &file, bool truncate) { - _lock.acquire(); + _lock.lock(); PT(File) f = _root.do_create_file(file); - _lock.release(); - if (f == (File *)NULL) { - return NULL; + _lock.unlock(); + if (f == nullptr) { + return nullptr; } if (truncate) { @@ -283,7 +288,7 @@ open_read_write_file(const Filename &file, bool truncate) { f->_data.str(string()); // See open_write_file - f->_timestamp = max(f->_timestamp + 1, time(NULL)); + f->_timestamp = std::max(f->_timestamp + 1, time(nullptr)); } return new SubStream(&f->_wrapper, 0, 0); @@ -296,11 +301,11 @@ open_read_write_file(const Filename &file, bool truncate) { */ iostream *VirtualFileMountRamdisk:: open_read_append_file(const Filename &file) { - _lock.acquire(); + _lock.lock(); PT(FileBase) f = _root.do_find_file(file); - _lock.release(); - if (f == (FileBase *)NULL || f->is_directory()) { - return NULL; + _lock.unlock(); + if (f == nullptr || f->is_directory()) { + return nullptr; } File *f2 = DCAST(File, f); @@ -312,12 +317,12 @@ open_read_append_file(const Filename &file) { * file. Pass in the stream that was returned by open_read_file(); some * implementations may require this stream to determine the size. */ -streamsize VirtualFileMountRamdisk:: +std::streamsize VirtualFileMountRamdisk:: get_file_size(const Filename &file, istream *stream) const { - _lock.acquire(); + _lock.lock(); PT(FileBase) f = _root.do_find_file(file); - _lock.release(); - if (f == (FileBase *)NULL || f->is_directory()) { + _lock.unlock(); + if (f == nullptr || f->is_directory()) { return 0; } @@ -329,12 +334,12 @@ get_file_size(const Filename &file, istream *stream) const { * Returns the current size on disk (or wherever it is) of the file before it * has been opened. */ -streamsize VirtualFileMountRamdisk:: +std::streamsize VirtualFileMountRamdisk:: get_file_size(const Filename &file) const { - _lock.acquire(); + _lock.lock(); PT(FileBase) f = _root.do_find_file(file); - _lock.release(); - if (f == (FileBase *)NULL || f->is_directory()) { + _lock.unlock(); + if (f == nullptr || f->is_directory()) { return 0; } @@ -354,14 +359,14 @@ get_file_size(const Filename &file) const { */ time_t VirtualFileMountRamdisk:: get_timestamp(const Filename &file) const { - _lock.acquire(); + _lock.lock(); PT(FileBase) f = _root.do_find_file(file); if (f.is_null()) { - _lock.release(); + _lock.unlock(); return 0; } time_t timestamp = f->_timestamp; - _lock.release(); + _lock.unlock(); return timestamp; } @@ -372,17 +377,17 @@ get_timestamp(const Filename &file) const { */ bool VirtualFileMountRamdisk:: scan_directory(vector_string &contents, const Filename &dir) const { - _lock.acquire(); + _lock.lock(); PT(FileBase) f = _root.do_find_file(dir); - if (f == (FileBase *)NULL || !f->is_directory()) { - _lock.release(); + if (f == nullptr || !f->is_directory()) { + _lock.unlock(); return false; } Directory *f2 = DCAST(Directory, f); bool result = f2->do_scan_directory(contents); - _lock.release(); + _lock.unlock(); return result; } @@ -393,10 +398,10 @@ bool VirtualFileMountRamdisk:: atomic_compare_and_exchange_contents(const Filename &file, string &orig_contents, const string &old_contents, const string &new_contents) { - _lock.acquire(); + _lock.lock(); PT(FileBase) f = _root.do_find_file(file); - if (f == (FileBase *)NULL || f->is_directory()) { - _lock.release(); + if (f == nullptr || f->is_directory()) { + _lock.unlock(); return false; } @@ -405,11 +410,11 @@ atomic_compare_and_exchange_contents(const Filename &file, string &orig_contents orig_contents = f2->_data.str(); if (orig_contents == old_contents) { f2->_data.str(new_contents); - f2->_timestamp = time(NULL); + f2->_timestamp = time(nullptr); retval = true; } - _lock.release(); + _lock.unlock(); return retval; } @@ -418,17 +423,17 @@ atomic_compare_and_exchange_contents(const Filename &file, string &orig_contents */ bool VirtualFileMountRamdisk:: atomic_read_contents(const Filename &file, string &contents) const { - _lock.acquire(); + _lock.lock(); PT(FileBase) f = _root.do_find_file(file); - if (f == (FileBase *)NULL || f->is_directory()) { - _lock.release(); + if (f == nullptr || f->is_directory()) { + _lock.unlock(); return false; } File *f2 = DCAST(File, f); contents = f2->_data.str(); - _lock.release(); + _lock.unlock(); return true; } @@ -479,7 +484,7 @@ do_find_file(const string &filename) const { if (fi != _files.end()) { return (*fi); } - return NULL; + return nullptr; } // A nested directory. Search for the directory name, then recurse. @@ -495,7 +500,7 @@ do_find_file(const string &filename) const { } } - return NULL; + return nullptr; } /** @@ -516,7 +521,7 @@ do_create_file(const string &filename) { return DCAST(File, file.p()); } // Cannot create: a directory by the same name already exists. - return NULL; + return nullptr; } // Create a new file. @@ -526,7 +531,7 @@ do_create_file(const string &filename) { } PT(File) file = new File(filename); _files.insert(file.p()); - _timestamp = time(NULL); + _timestamp = time(nullptr); return file; } @@ -543,7 +548,7 @@ do_create_file(const string &filename) { } } - return NULL; + return nullptr; } /** @@ -564,7 +569,7 @@ do_make_directory(const string &filename) { return DCAST(Directory, file.p()); } // Cannot create: a file by the same name already exists. - return NULL; + return nullptr; } // Create a new directory. @@ -574,7 +579,7 @@ do_make_directory(const string &filename) { } PT(Directory) file = new Directory(filename); _files.insert(file.p()); - _timestamp = time(NULL); + _timestamp = time(nullptr); return file; } @@ -591,7 +596,7 @@ do_make_directory(const string &filename) { } } - return NULL; + return nullptr; } /** @@ -612,14 +617,14 @@ do_delete_file(const string &filename) { Directory *dir = DCAST(Directory, file.p()); if (!dir->_files.empty()) { // Can't delete a nonempty directory. - return NULL; + return nullptr; } } _files.erase(fi); - _timestamp = time(NULL); + _timestamp = time(nullptr); return file; } - return NULL; + return nullptr; } // A nested directory. Search for the directory name, then recurse. @@ -635,7 +640,7 @@ do_delete_file(const string &filename) { } } - return NULL; + return nullptr; } /** diff --git a/panda/src/express/virtualFileMountRamdisk.h b/panda/src/express/virtualFileMountRamdisk.h index 9812746534..ae87105473 100644 --- a/panda/src/express/virtualFileMountRamdisk.h +++ b/panda/src/express/virtualFileMountRamdisk.h @@ -27,7 +27,7 @@ * limits to the size of the files that may be written with this system; and * "files" written here are not automatically persistent between sessions. */ -class EXPCL_PANDAEXPRESS VirtualFileMountRamdisk : public VirtualFileMount { +class EXPCL_PANDA_EXPRESS VirtualFileMountRamdisk : public VirtualFileMount { PUBLISHED: VirtualFileMountRamdisk(); @@ -42,23 +42,23 @@ public: virtual bool is_regular_file(const Filename &file) const; virtual bool is_writable(const Filename &file) const; - virtual istream *open_read_file(const Filename &file) const; - virtual ostream *open_write_file(const Filename &file, bool truncate); - virtual ostream *open_append_file(const Filename &file); - virtual iostream *open_read_write_file(const Filename &file, bool truncate); - virtual iostream *open_read_append_file(const Filename &file); + virtual std::istream *open_read_file(const Filename &file) const; + virtual std::ostream *open_write_file(const Filename &file, bool truncate); + virtual std::ostream *open_append_file(const Filename &file); + virtual std::iostream *open_read_write_file(const Filename &file, bool truncate); + virtual std::iostream *open_read_append_file(const Filename &file); - virtual streamsize get_file_size(const Filename &file, istream *stream) const; - virtual streamsize get_file_size(const Filename &file) const; + virtual std::streamsize get_file_size(const Filename &file, std::istream *stream) const; + virtual std::streamsize get_file_size(const Filename &file) const; virtual time_t get_timestamp(const Filename &file) const; virtual bool scan_directory(vector_string &contents, const Filename &dir) const; - virtual bool atomic_compare_and_exchange_contents(const Filename &file, string &orig_contents, const string &old_contents, const string &new_contents); - virtual bool atomic_read_contents(const Filename &file, string &contents) const; + virtual bool atomic_compare_and_exchange_contents(const Filename &file, std::string &orig_contents, const std::string &old_contents, const std::string &new_contents); + virtual bool atomic_read_contents(const Filename &file, std::string &contents) const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: class FileBase; @@ -67,13 +67,13 @@ private: class FileBase : public TypedReferenceCount { public: - INLINE FileBase(const string &basename); + INLINE FileBase(const std::string &basename); virtual ~FileBase(); INLINE bool operator < (const FileBase &other) const; virtual bool is_directory() const; - string _basename; + std::string _basename; time_t _timestamp; public: @@ -96,9 +96,9 @@ private: class File : public FileBase { public: - INLINE File(const string &basename); + INLINE File(const std::string &basename); - stringstream _data; + std::stringstream _data; StreamWrapper _wrapper; public: @@ -123,14 +123,14 @@ private: class Directory : public FileBase { public: - INLINE Directory(const string &basename); + INLINE Directory(const std::string &basename); virtual bool is_directory() const; - PT(FileBase) do_find_file(const string &filename) const; - PT(File) do_create_file(const string &filename); - PT(Directory) do_make_directory(const string &filename); - PT(FileBase) do_delete_file(const string &filename); + PT(FileBase) do_find_file(const std::string &filename) const; + PT(File) do_create_file(const std::string &filename); + PT(Directory) do_make_directory(const std::string &filename); + PT(FileBase) do_delete_file(const std::string &filename); bool do_scan_directory(vector_string &contents) const; Files _files; diff --git a/panda/src/express/virtualFileMountSystem.cxx b/panda/src/express/virtualFileMountSystem.cxx index ce201712b2..ebf5fa6645 100644 --- a/panda/src/express/virtualFileMountSystem.cxx +++ b/panda/src/express/virtualFileMountSystem.cxx @@ -14,6 +14,13 @@ #include "virtualFileMountSystem.h" #include "virtualFileSystem.h" +using std::iostream; +using std::istream; +using std::ostream; +using std::streampos; +using std::streamsize; +using std::string; + TypeHandle VirtualFileMountSystem::_type_handle; @@ -49,7 +56,7 @@ bool VirtualFileMountSystem:: create_file(const Filename &file) { Filename pathname(_physical_filename, file); pathname.set_binary(); - ofstream stream; + std::ofstream stream; return pathname.open_write(stream, false); } @@ -167,7 +174,7 @@ open_read_file(const Filename &file) const { // First ensure that the file exists to validate its case. if (VirtualFileSystem::get_global_ptr()->vfs_case_sensitive) { if (!has_file(file)) { - return NULL; + return nullptr; } } #endif // WIN32 @@ -176,7 +183,7 @@ open_read_file(const Filename &file) const { if (!pathname.open_read(*stream)) { // Couldn't open the file for some reason. close_read_file(stream); - return NULL; + return nullptr; } return stream; @@ -193,7 +200,7 @@ open_write_file(const Filename &file, bool truncate) { // First ensure that the file exists to validate its case. if (VirtualFileSystem::get_global_ptr()->vfs_case_sensitive) { if (!has_file(file)) { - return NULL; + return nullptr; } } #endif // WIN32 @@ -202,7 +209,7 @@ open_write_file(const Filename &file, bool truncate) { if (!pathname.open_write(*stream, truncate)) { // Couldn't open the file for some reason. close_write_file(stream); - return NULL; + return nullptr; } return stream; @@ -219,7 +226,7 @@ open_append_file(const Filename &file) { // First ensure that the file exists to validate its case. if (VirtualFileSystem::get_global_ptr()->vfs_case_sensitive) { if (!has_file(file)) { - return NULL; + return nullptr; } } #endif // WIN32 @@ -228,7 +235,7 @@ open_append_file(const Filename &file) { if (!pathname.open_append(*stream)) { // Couldn't open the file for some reason. close_write_file(stream); - return NULL; + return nullptr; } return stream; @@ -245,7 +252,7 @@ open_read_write_file(const Filename &file, bool truncate) { // First ensure that the file exists to validate its case. if (VirtualFileSystem::get_global_ptr()->vfs_case_sensitive) { if (!has_file(file)) { - return NULL; + return nullptr; } } #endif // WIN32 @@ -254,7 +261,7 @@ open_read_write_file(const Filename &file, bool truncate) { if (!pathname.open_read_write(*stream, truncate)) { // Couldn't open the file for some reason. close_read_write_file(stream); - return NULL; + return nullptr; } return stream; @@ -271,7 +278,7 @@ open_read_append_file(const Filename &file) { // First ensure that the file exists to validate its case. if (VirtualFileSystem::get_global_ptr()->vfs_case_sensitive) { if (!has_file(file)) { - return NULL; + return nullptr; } } #endif // WIN32 @@ -280,7 +287,7 @@ open_read_append_file(const Filename &file) { if (!pathname.open_read_append(*stream)) { // Couldn't open the file for some reason. close_read_write_file(stream); - return NULL; + return nullptr; } return stream; @@ -297,7 +304,7 @@ get_file_size(const Filename &file, istream *stream) const { streampos orig = stream->tellg(); // Seek to the end and get the stream position there. - stream->seekg(0, ios::end); + stream->seekg(0, std::ios::end); if (stream->fail()) { // Seeking not supported. stream->clear(); @@ -306,7 +313,7 @@ get_file_size(const Filename &file, istream *stream) const { streampos size = stream->tellg(); // Then return to the original point. - stream->seekg(orig, ios::beg); + stream->seekg(orig, std::ios::beg); // Make sure there are no error flags set as a result of the seek. stream->clear(); @@ -385,7 +392,7 @@ atomic_compare_and_exchange_contents(const Filename &file, string &orig_contents // First ensure that the file exists to validate its case. if (VirtualFileSystem::get_global_ptr()->vfs_case_sensitive) { if (!has_file(file)) { - return NULL; + return false; } } #endif // WIN32 @@ -402,7 +409,7 @@ atomic_read_contents(const Filename &file, string &contents) const { // First ensure that the file exists to validate its case. if (VirtualFileSystem::get_global_ptr()->vfs_case_sensitive) { if (!has_file(file)) { - return NULL; + return false; } } #endif // WIN32 diff --git a/panda/src/express/virtualFileMountSystem.h b/panda/src/express/virtualFileMountSystem.h index 2854c32ae0..f812b53365 100644 --- a/panda/src/express/virtualFileMountSystem.h +++ b/panda/src/express/virtualFileMountSystem.h @@ -21,7 +21,7 @@ /** * Maps an actual OS directory into the VirtualFileSystem. */ -class EXPCL_PANDAEXPRESS VirtualFileMountSystem : public VirtualFileMount { +class EXPCL_PANDA_EXPRESS VirtualFileMountSystem : public VirtualFileMount { PUBLISHED: INLINE VirtualFileMountSystem(const Filename &physical_filename); @@ -38,24 +38,24 @@ public: virtual bool is_regular_file(const Filename &file) const; virtual bool is_writable(const Filename &file) const; - virtual istream *open_read_file(const Filename &file) const; - virtual ostream *open_write_file(const Filename &file, bool truncate); - virtual ostream *open_append_file(const Filename &file); - virtual iostream *open_read_write_file(const Filename &file, bool truncate); - virtual iostream *open_read_append_file(const Filename &file); + virtual std::istream *open_read_file(const Filename &file) const; + virtual std::ostream *open_write_file(const Filename &file, bool truncate); + virtual std::ostream *open_append_file(const Filename &file); + virtual std::iostream *open_read_write_file(const Filename &file, bool truncate); + virtual std::iostream *open_read_append_file(const Filename &file); - virtual streamsize get_file_size(const Filename &file, istream *stream) const; - virtual streamsize get_file_size(const Filename &file) const; + virtual std::streamsize get_file_size(const Filename &file, std::istream *stream) const; + virtual std::streamsize get_file_size(const Filename &file) const; virtual time_t get_timestamp(const Filename &file) const; virtual bool get_system_info(const Filename &file, SubfileInfo &info); virtual bool scan_directory(vector_string &contents, const Filename &dir) const; - virtual bool atomic_compare_and_exchange_contents(const Filename &file, string &orig_contents, const string &old_contents, const string &new_contents); - virtual bool atomic_read_contents(const Filename &file, string &contents) const; + virtual bool atomic_compare_and_exchange_contents(const Filename &file, std::string &orig_contents, const std::string &old_contents, const std::string &new_contents); + virtual bool atomic_read_contents(const Filename &file, std::string &contents) const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: Filename _physical_filename; diff --git a/panda/src/express/virtualFileSimple.I b/panda/src/express/virtualFileSimple.I index dcdd7cec90..1d30ef08e5 100644 --- a/panda/src/express/virtualFileSimple.I +++ b/panda/src/express/virtualFileSimple.I @@ -19,8 +19,7 @@ VirtualFileSimple(VirtualFileMount *mount, const Filename &local_filename, bool implicit_pz_file, int open_flags) : _mount(mount), _local_filename(local_filename), - _implicit_pz_file(implicit_pz_file), - _open_flags(open_flags) + _implicit_pz_file(implicit_pz_file) { } diff --git a/panda/src/express/virtualFileSimple.cxx b/panda/src/express/virtualFileSimple.cxx index 1c521b6459..11ee94cce9 100644 --- a/panda/src/express/virtualFileSimple.cxx +++ b/panda/src/express/virtualFileSimple.cxx @@ -16,6 +16,11 @@ #include "virtualFileList.h" #include "dcast.h" +using std::iostream; +using std::istream; +using std::ostream; +using std::string; + TypeHandle VirtualFileSimple::_type_handle; @@ -308,7 +313,7 @@ close_read_write_file(iostream *stream) { * file. Pass in the stream that was returned by open_read_file(); some * implementations may require this stream to determine the size. */ -streamsize VirtualFileSimple:: +std::streamsize VirtualFileSimple:: get_file_size(istream *stream) const { return _mount->get_file_size(_local_filename, stream); } @@ -317,7 +322,7 @@ get_file_size(istream *stream) const { * Returns the current size on disk (or wherever it is) of the file before it * has been opened. */ -streamsize VirtualFileSimple:: +std::streamsize VirtualFileSimple:: get_file_size() const { return _mount->get_file_size(_local_filename); } @@ -372,7 +377,7 @@ atomic_read_contents(string &contents) const { * regular file. Returns true on success, false otherwise. */ bool VirtualFileSimple:: -read_file(pvector &result, bool auto_unwrap) const { +read_file(vector_uchar &result, bool auto_unwrap) const { // Will we be automatically unwrapping a .pz file? bool do_uncompress = (_implicit_pz_file || diff --git a/panda/src/express/virtualFileSimple.h b/panda/src/express/virtualFileSimple.h index 917898791e..1f8608a2ec 100644 --- a/panda/src/express/virtualFileSimple.h +++ b/panda/src/express/virtualFileSimple.h @@ -23,7 +23,7 @@ * exactly one file on one mount point. Most directories, and all regular * files, are of this kind. */ -class EXPCL_PANDAEXPRESS VirtualFileSimple : public VirtualFile { +class EXPCL_PANDA_EXPRESS VirtualFileSimple : public VirtualFile { public: INLINE VirtualFileSimple(VirtualFileMount *mount, const Filename &local_filename, @@ -45,36 +45,35 @@ PUBLISHED: virtual bool rename_file(VirtualFile *new_file); virtual bool copy_file(VirtualFile *new_file); - virtual istream *open_read_file(bool auto_unwrap) const; - virtual void close_read_file(istream *stream) const; - virtual ostream *open_write_file(bool auto_wrap, bool truncate); - virtual ostream *open_append_file(); - virtual void close_write_file(ostream *stream); - virtual iostream *open_read_write_file(bool truncate); - virtual iostream *open_read_append_file(); - virtual void close_read_write_file(iostream *stream); + virtual std::istream *open_read_file(bool auto_unwrap) const; + virtual void close_read_file(std::istream *stream) const; + virtual std::ostream *open_write_file(bool auto_wrap, bool truncate); + virtual std::ostream *open_append_file(); + virtual void close_write_file(std::ostream *stream); + virtual std::iostream *open_read_write_file(bool truncate); + virtual std::iostream *open_read_append_file(); + virtual void close_read_write_file(std::iostream *stream); - virtual streamsize get_file_size(istream *stream) const; - virtual streamsize get_file_size() const; + virtual std::streamsize get_file_size(std::istream *stream) const; + virtual std::streamsize get_file_size() const; virtual time_t get_timestamp() const; virtual bool get_system_info(SubfileInfo &info); public: - virtual bool atomic_compare_and_exchange_contents(string &orig_contents, const string &old_contents, const string &new_contents); - virtual bool atomic_read_contents(string &contents) const; + virtual bool atomic_compare_and_exchange_contents(std::string &orig_contents, const std::string &old_contents, const std::string &new_contents); + virtual bool atomic_read_contents(std::string &contents) const; - virtual bool read_file(pvector &result, bool auto_unwrap) const; + virtual bool read_file(vector_uchar &result, bool auto_unwrap) const; virtual bool write_file(const unsigned char *data, size_t data_size, bool auto_wrap); protected: virtual bool scan_local_directory(VirtualFileList *file_list, - const ov_set &mount_points) const; + const ov_set &mount_points) const; private: VirtualFileMount *_mount; Filename _local_filename; bool _implicit_pz_file; - int _open_flags; public: virtual TypeHandle get_type() const { diff --git a/panda/src/express/virtualFileSystem.I b/panda/src/express/virtualFileSystem.I index 3a33e3df9c..b74b9edbee 100644 --- a/panda/src/express/virtualFileSystem.I +++ b/panda/src/express/virtualFileSystem.I @@ -16,7 +16,7 @@ */ INLINE bool VirtualFileSystem:: exists(const Filename &filename) const { - return get_file(filename, true) != (VirtualFile *)NULL; + return get_file(filename, true) != nullptr; } /** @@ -26,7 +26,7 @@ exists(const Filename &filename) const { INLINE bool VirtualFileSystem:: is_directory(const Filename &filename) const { PT(VirtualFile) file = get_file(filename, true); - return (file != (VirtualFile *)NULL && file->is_directory()); + return (file != nullptr && file->is_directory()); } /** @@ -36,7 +36,7 @@ is_directory(const Filename &filename) const { INLINE bool VirtualFileSystem:: is_regular_file(const Filename &filename) const { PT(VirtualFile) file = get_file(filename, true); - return (file != (VirtualFile *)NULL && file->is_regular_file()); + return (file != nullptr && file->is_regular_file()); } /** @@ -48,8 +48,8 @@ is_regular_file(const Filename &filename) const { INLINE PT(VirtualFileList) VirtualFileSystem:: scan_directory(const Filename &filename) const { PT(VirtualFile) file = get_file(filename, true); - if (file == (VirtualFile *)NULL) { - return NULL; + if (file == nullptr) { + return nullptr; } return file->scan_directory(); @@ -61,7 +61,7 @@ scan_directory(const Filename &filename) const { INLINE void VirtualFileSystem:: ls(const Filename &filename) const { PT(VirtualFile) file = get_file(filename, true); - if (file == (VirtualFile *)NULL) { + if (file == nullptr) { express_cat.info() << "Not found: " << filename << "\n"; } else { @@ -76,7 +76,7 @@ ls(const Filename &filename) const { INLINE void VirtualFileSystem:: ls_all(const Filename &filename) const { PT(VirtualFile) file = get_file(filename, true); - if (file == (VirtualFile *)NULL) { + if (file == nullptr) { express_cat.info() << "Not found: " << filename << "\n"; } else { @@ -93,11 +93,11 @@ ls_all(const Filename &filename) const { * than vfs-implicit-pz, which will automatically decompress a file if the * extension .pz is *not* given. */ -INLINE string VirtualFileSystem:: +INLINE std::string VirtualFileSystem:: read_file(const Filename &filename, bool auto_unwrap) const { - string result; + std::string result; bool okflag = read_file(filename, result, auto_unwrap); - nassertr(okflag, string()); + nassertr(okflag, std::string()); return result; } @@ -109,7 +109,7 @@ read_file(const Filename &filename, bool auto_unwrap) const { * compressed while writing. */ INLINE bool VirtualFileSystem:: -write_file(const Filename &filename, const string &data, bool auto_wrap) { +write_file(const Filename &filename, const std::string &data, bool auto_wrap) { return write_file(filename, (const unsigned char *)data.data(), data.size(), auto_wrap); } @@ -124,9 +124,9 @@ write_file(const Filename &filename, const string &data, bool auto_wrap) { * extension .pz is *not* given. */ INLINE bool VirtualFileSystem:: -read_file(const Filename &filename, string &result, bool auto_unwrap) const { +read_file(const Filename &filename, std::string &result, bool auto_unwrap) const { PT(VirtualFile) file = get_file(filename, false); - return (file != (VirtualFile *)NULL && file->read_file(result, auto_unwrap)); + return (file != nullptr && file->read_file(result, auto_unwrap)); } /** @@ -140,9 +140,9 @@ read_file(const Filename &filename, string &result, bool auto_unwrap) const { * extension .pz is *not* given. */ INLINE bool VirtualFileSystem:: -read_file(const Filename &filename, pvector &result, bool auto_unwrap) const { +read_file(const Filename &filename, vector_uchar &result, bool auto_unwrap) const { PT(VirtualFile) file = get_file(filename, false); - return (file != (VirtualFile *)NULL && file->read_file(result, auto_unwrap)); + return (file != nullptr && file->read_file(result, auto_unwrap)); } /** @@ -155,5 +155,5 @@ read_file(const Filename &filename, pvector &result, bool auto_un INLINE bool VirtualFileSystem:: write_file(const Filename &filename, const unsigned char *data, size_t data_size, bool auto_wrap) { PT(VirtualFile) file = create_file(filename); - return (file != (VirtualFile *)NULL && file->write_file(data, data_size, auto_wrap)); + return (file != nullptr && file->write_file(data, data_size, auto_wrap)); } diff --git a/panda/src/express/virtualFileSystem.cxx b/panda/src/express/virtualFileSystem.cxx index da7797ec9d..eb915b566c 100644 --- a/panda/src/express/virtualFileSystem.cxx +++ b/panda/src/express/virtualFileSystem.cxx @@ -25,7 +25,12 @@ #include "executionEnvironment.h" #include "pset.h" -VirtualFileSystem *VirtualFileSystem::_global_ptr = NULL; +using std::iostream; +using std::istream; +using std::ostream; +using std::string; + +VirtualFileSystem *VirtualFileSystem::_global_ptr = nullptr; /** @@ -151,7 +156,7 @@ bool VirtualFileSystem:: mount_loop(const Filename &virtual_filename, const Filename &mount_point, int flags, const string &password) { PT(VirtualFile) file = get_file(virtual_filename, false); - if (file == NULL) { + if (file == nullptr) { express_cat->warning() << "Attempt to mount " << virtual_filename << ", not found.\n"; return false; @@ -190,9 +195,9 @@ mount(VirtualFileMount *mount, const Filename &mount_point, int flags) { << "mount " << *mount << " under " << mount_point << "\n"; } - _lock.acquire(); + _lock.lock(); bool result = do_mount(mount, mount_point, flags); - _lock.release(); + _lock.unlock(); return result; } @@ -202,7 +207,7 @@ mount(VirtualFileMount *mount, const Filename &mount_point, int flags) { */ int VirtualFileSystem:: unmount(Multifile *multifile) { - _lock.acquire(); + _lock.lock(); Mounts::iterator ri, wi; wi = ri = _mounts.begin(); while (ri != _mounts.end()) { @@ -218,7 +223,7 @@ unmount(Multifile *multifile) { express_cat->debug() << "unmount " << *mount << " from " << mount->get_mount_point() << "\n"; } - mount->_file_system = NULL; + mount->_file_system = nullptr; } else { // Don't remove this one. @@ -234,7 +239,7 @@ unmount(Multifile *multifile) { int num_removed = _mounts.end() - wi; _mounts.erase(wi, _mounts.end()); ++_mount_seq; - _lock.release(); + _lock.unlock(); return num_removed; } @@ -244,7 +249,7 @@ unmount(Multifile *multifile) { */ int VirtualFileSystem:: unmount(const Filename &physical_filename) { - _lock.acquire(); + _lock.lock(); Mounts::iterator ri, wi; wi = ri = _mounts.begin(); while (ri != _mounts.end()) { @@ -260,7 +265,7 @@ unmount(const Filename &physical_filename) { express_cat->debug() << "unmount " << *mount << " from " << mount->get_mount_point() << "\n"; } - mount->_file_system = NULL; + mount->_file_system = nullptr; } else { // Don't remove this one. @@ -276,7 +281,7 @@ unmount(const Filename &physical_filename) { express_cat->debug() << "unmount " << *mount << " from " << mount->get_mount_point() << "\n"; } - mount->_file_system = NULL; + mount->_file_system = nullptr; } else { // Don't remove this one. @@ -293,7 +298,7 @@ unmount(const Filename &physical_filename) { int num_removed = _mounts.end() - wi; _mounts.erase(wi, _mounts.end()); ++_mount_seq; - _lock.release(); + _lock.unlock(); return num_removed; } @@ -303,7 +308,7 @@ unmount(const Filename &physical_filename) { */ int VirtualFileSystem:: unmount(VirtualFileMount *mount) { - _lock.acquire(); + _lock.lock(); Mounts::iterator ri, wi; wi = ri = _mounts.begin(); while (ri != _mounts.end()) { @@ -314,7 +319,7 @@ unmount(VirtualFileMount *mount) { express_cat->debug() << "unmount " << *mount << " from " << mount->get_mount_point() << "\n"; } - (*ri)->_file_system = NULL; + (*ri)->_file_system = nullptr; } else { // Don't remove this one. @@ -326,7 +331,7 @@ unmount(VirtualFileMount *mount) { int num_removed = _mounts.end() - wi; _mounts.erase(wi, _mounts.end()); ++_mount_seq; - _lock.release(); + _lock.unlock(); return num_removed; } @@ -336,7 +341,7 @@ unmount(VirtualFileMount *mount) { */ int VirtualFileSystem:: unmount_point(const Filename &mount_point) { - _lock.acquire(); + _lock.lock(); Filename nmp = normalize_mount_point(mount_point); Mounts::iterator ri, wi; wi = ri = _mounts.begin(); @@ -350,7 +355,7 @@ unmount_point(const Filename &mount_point) { express_cat->debug() << "unmount " << *mount << " from " << mount->get_mount_point() << "\n"; } - mount->_file_system = NULL; + mount->_file_system = nullptr; } else { // Don't remove this one. @@ -362,7 +367,7 @@ unmount_point(const Filename &mount_point) { int num_removed = _mounts.end() - wi; _mounts.erase(wi, _mounts.end()); ++_mount_seq; - _lock.release(); + _lock.unlock(); return num_removed; } @@ -372,7 +377,7 @@ unmount_point(const Filename &mount_point) { */ int VirtualFileSystem:: unmount_all() { - _lock.acquire(); + _lock.lock(); Mounts::iterator ri; for (ri = _mounts.begin(); ri != _mounts.end(); ++ri) { VirtualFileMount *mount = (*ri); @@ -380,13 +385,13 @@ unmount_all() { express_cat->debug() << "unmount " << *mount << " from " << mount->get_mount_point() << "\n"; } - mount->_file_system = NULL; + mount->_file_system = nullptr; } int num_removed = _mounts.size(); _mounts.clear(); ++_mount_seq; - _lock.release(); + _lock.unlock(); return num_removed; } @@ -395,9 +400,9 @@ unmount_all() { */ int VirtualFileSystem:: get_num_mounts() const { - ((VirtualFileSystem *)this)->_lock.acquire(); + _lock.lock(); int result = _mounts.size(); - ((VirtualFileSystem *)this)->_lock.release(); + _lock.unlock(); return result; } @@ -406,13 +411,13 @@ get_num_mounts() const { */ PT(VirtualFileMount) VirtualFileSystem:: get_mount(int n) const { - ((VirtualFileSystem *)this)->_lock.acquire(); + _lock.lock(); nassertd(n >= 0 && n < (int)_mounts.size()) { - ((VirtualFileSystem *)this)->_lock.release(); - return NULL; + _lock.unlock(); + return nullptr; } PT(VirtualFileMount) result = _mounts[n]; - ((VirtualFileSystem *)this)->_lock.release(); + _lock.unlock(); return result; } @@ -423,21 +428,21 @@ get_mount(int n) const { */ bool VirtualFileSystem:: chdir(const Filename &new_directory) { - _lock.acquire(); + _lock.lock(); if (new_directory == "/") { // We can always return to the root. _cwd = new_directory; - _lock.release(); + _lock.unlock(); return true; } PT(VirtualFile) file = do_get_file(new_directory, OF_status_only); - if (file != (VirtualFile *)NULL && file->is_directory()) { + if (file != nullptr && file->is_directory()) { _cwd = file->get_filename(); - _lock.release(); + _lock.unlock(); return true; } - _lock.release(); + _lock.unlock(); return false; } @@ -446,9 +451,9 @@ chdir(const Filename &new_directory) { */ Filename VirtualFileSystem:: get_cwd() const { - ((VirtualFileSystem *)this)->_lock.acquire(); + _lock.lock(); Filename result = _cwd; - ((VirtualFileSystem *)this)->_lock.release(); + _lock.unlock(); return result; } @@ -460,10 +465,10 @@ get_cwd() const { */ bool VirtualFileSystem:: make_directory(const Filename &filename) { - _lock.acquire(); + _lock.lock(); PT(VirtualFile) result = do_get_file(filename, OF_make_directory); - _lock.release(); - nassertr_always(result != NULL, false); + _lock.unlock(); + nassertr_always(result != nullptr, false); return result->is_directory(); } @@ -474,7 +479,7 @@ make_directory(const Filename &filename) { */ bool VirtualFileSystem:: make_directory_full(const Filename &filename) { - _lock.acquire(); + _lock.lock(); // First, make sure everything up to the last path is known. We don't care // too much if any of these fail; maybe they failed because the directory @@ -489,8 +494,8 @@ make_directory_full(const Filename &filename) { // Now make the last one, and check the return value. PT(VirtualFile) result = do_get_file(filename, OF_make_directory); - _lock.release(); - nassertr_always(result != NULL, false); + _lock.unlock(); + nassertr_always(result != nullptr, false); return result->is_directory(); } @@ -508,9 +513,9 @@ make_directory_full(const Filename &filename) { PT(VirtualFile) VirtualFileSystem:: get_file(const Filename &filename, bool status_only) const { int open_flags = status_only ? OF_status_only : 0; - ((VirtualFileSystem *)this)->_lock.acquire(); + _lock.lock(); PT(VirtualFile) result = do_get_file(filename, open_flags); - ((VirtualFileSystem *)this)->_lock.release(); + _lock.unlock(); return result; } @@ -522,9 +527,9 @@ get_file(const Filename &filename, bool status_only) const { */ PT(VirtualFile) VirtualFileSystem:: create_file(const Filename &filename) { - ((VirtualFileSystem *)this)->_lock.acquire(); + _lock.lock(); PT(VirtualFile) result = do_get_file(filename, OF_create_file); - ((VirtualFileSystem *)this)->_lock.release(); + _lock.unlock(); return result; } @@ -552,12 +557,12 @@ find_file(const Filename &filename, const DSearchPath &searchpath, match = filename; } PT(VirtualFile) found_file = get_file(match, status_only); - if (found_file != (VirtualFile *)NULL) { + if (found_file != nullptr) { return found_file; } } - return NULL; + return nullptr; } /** @@ -568,7 +573,7 @@ find_file(const Filename &filename, const DSearchPath &searchpath, bool VirtualFileSystem:: delete_file(const Filename &filename) { PT(VirtualFile) file = get_file(filename, true); - if (file == (VirtualFile *)NULL) { + if (file == nullptr) { return false; } @@ -588,20 +593,20 @@ delete_file(const Filename &filename) { */ bool VirtualFileSystem:: rename_file(const Filename &orig_filename, const Filename &new_filename) { - _lock.acquire(); + _lock.lock(); PT(VirtualFile) orig_file = do_get_file(orig_filename, OF_status_only); - if (orig_file == (VirtualFile *)NULL) { - _lock.release(); + if (orig_file == nullptr) { + _lock.unlock(); return false; } PT(VirtualFile) new_file = do_get_file(new_filename, OF_status_only | OF_allow_nonexist); - if (new_file == (VirtualFile *)NULL) { - _lock.release(); + if (new_file == nullptr) { + _lock.unlock(); return false; } - _lock.release(); + _lock.unlock(); return orig_file->rename_file(new_file); } @@ -613,12 +618,12 @@ rename_file(const Filename &orig_filename, const Filename &new_filename) { bool VirtualFileSystem:: copy_file(const Filename &orig_filename, const Filename &new_filename) { PT(VirtualFile) orig_file = get_file(orig_filename, true); - if (orig_file == (VirtualFile *)NULL) { + if (orig_file == nullptr) { return false; } PT(VirtualFile) new_file = create_file(new_filename); - if (new_file == (VirtualFile *)NULL) { + if (new_file == nullptr) { return false; } @@ -712,13 +717,13 @@ find_all_files(const Filename &filename, const DSearchPath &searchpath, */ void VirtualFileSystem:: write(ostream &out) const { - ((VirtualFileSystem *)this)->_lock.acquire(); + _lock.lock(); Mounts::const_iterator mi; for (mi = _mounts.begin(); mi != _mounts.end(); ++mi) { VirtualFileMount *mount = (*mi); mount->write(out); } - ((VirtualFileSystem *)this)->_lock.release(); + _lock.unlock(); } @@ -733,7 +738,7 @@ write(ostream &out) const { */ VirtualFileSystem *VirtualFileSystem:: get_global_ptr() { - if (_global_ptr == (VirtualFileSystem *)NULL) { + if (_global_ptr == nullptr) { // Make sure this is initialized. init_libexpress(); @@ -839,13 +844,13 @@ get_global_ptr() { istream *VirtualFileSystem:: open_read_file(const Filename &filename, bool auto_unwrap) const { PT(VirtualFile) file = get_file(filename, false); - if (file == (VirtualFile *)NULL) { - return NULL; + if (file == nullptr) { + return nullptr; } istream *str = file->open_read_file(auto_unwrap); - if (str != (istream *)NULL && str->fail()) { + if (str != nullptr && str->fail()) { close_read_file(str); - str = (istream *)NULL; + str = nullptr; } return str; } @@ -858,7 +863,7 @@ open_read_file(const Filename &filename, bool auto_unwrap) const { */ void VirtualFileSystem:: close_read_file(istream *stream) { - if (stream != (istream *)NULL) { + if (stream != nullptr) { // For some reason--compiler bug in gcc 3.2?--explicitly deleting the // stream pointer does not call the appropriate global delete function; // instead apparently calling the system delete function. So we call the @@ -883,13 +888,13 @@ close_read_file(istream *stream) { ostream *VirtualFileSystem:: open_write_file(const Filename &filename, bool auto_wrap, bool truncate) { PT(VirtualFile) file = create_file(filename); - if (file == (VirtualFile *)NULL) { - return NULL; + if (file == nullptr) { + return nullptr; } ostream *str = file->open_write_file(auto_wrap, truncate); - if (str != (ostream *)NULL && str->fail()) { + if (str != nullptr && str->fail()) { close_write_file(str); - str = (ostream *)NULL; + str = nullptr; } return str; } @@ -902,13 +907,13 @@ open_write_file(const Filename &filename, bool auto_wrap, bool truncate) { ostream *VirtualFileSystem:: open_append_file(const Filename &filename) { PT(VirtualFile) file = create_file(filename); - if (file == (VirtualFile *)NULL) { - return NULL; + if (file == nullptr) { + return nullptr; } ostream *str = file->open_append_file(); - if (str != (ostream *)NULL && str->fail()) { + if (str != nullptr && str->fail()) { close_write_file(str); - str = (ostream *)NULL; + str = nullptr; } return str; } @@ -921,7 +926,7 @@ open_append_file(const Filename &filename) { */ void VirtualFileSystem:: close_write_file(ostream *stream) { - if (stream != (ostream *)NULL) { + if (stream != nullptr) { #if (!defined(WIN32_VC) && !defined(WIN64_VC)) && !defined(USE_MEMORY_NOWRAPPERS) && defined(REDEFINE_GLOBAL_OPERATOR_NEW) stream->~ostream(); (*global_operator_delete)(stream); @@ -939,13 +944,13 @@ close_write_file(ostream *stream) { iostream *VirtualFileSystem:: open_read_write_file(const Filename &filename, bool truncate) { PT(VirtualFile) file = create_file(filename); - if (file == (VirtualFile *)NULL) { - return NULL; + if (file == nullptr) { + return nullptr; } iostream *str = file->open_read_write_file(truncate); - if (str != (iostream *)NULL && str->fail()) { + if (str != nullptr && str->fail()) { close_read_write_file(str); - str = (iostream *)NULL; + str = nullptr; } return str; } @@ -958,13 +963,13 @@ open_read_write_file(const Filename &filename, bool truncate) { iostream *VirtualFileSystem:: open_read_append_file(const Filename &filename) { PT(VirtualFile) file = create_file(filename); - if (file == (VirtualFile *)NULL) { - return NULL; + if (file == nullptr) { + return nullptr; } iostream *str = file->open_read_append_file(); - if (str != (iostream *)NULL && str->fail()) { + if (str != nullptr && str->fail()) { close_read_write_file(str); - str = (iostream *)NULL; + str = nullptr; } return str; } @@ -977,7 +982,7 @@ open_read_append_file(const Filename &filename) { */ void VirtualFileSystem:: close_read_write_file(iostream *stream) { - if (stream != (iostream *)NULL) { + if (stream != nullptr) { #if (!defined(WIN32_VC) && !defined(WIN64_VC)) && !defined(USE_MEMORY_NOWRAPPERS) && defined(REDEFINE_GLOBAL_OPERATOR_NEW) stream->~iostream(); (*global_operator_delete)(stream); @@ -995,7 +1000,7 @@ atomic_compare_and_exchange_contents(const Filename &filename, string &orig_cont const string &old_contents, const string &new_contents) { PT(VirtualFile) file = create_file(filename); - if (file == NULL) { + if (file == nullptr) { return false; } @@ -1008,7 +1013,7 @@ atomic_compare_and_exchange_contents(const Filename &filename, string &orig_cont bool VirtualFileSystem:: atomic_read_contents(const Filename &filename, string &contents) const { PT(VirtualFile) file = get_file(filename, false); - if (file == NULL) { + if (file == nullptr) { return false; } @@ -1118,7 +1123,7 @@ normalize_mount_point(const Filename &mount_point) const { */ bool VirtualFileSystem:: do_mount(VirtualFileMount *mount, const Filename &mount_point, int flags) { - nassertr(mount->_file_system == NULL, false); + nassertr(mount->_file_system == nullptr, false); mount->_file_system = this; mount->_mount_point = normalize_mount_point(mount_point); mount->_mount_flags = flags; @@ -1134,7 +1139,7 @@ do_mount(VirtualFileMount *mount, const Filename &mount_point, int flags) { PT(VirtualFile) VirtualFileSystem:: do_get_file(const Filename &filename, int open_flags) const { if (filename.empty()) { - return NULL; + return nullptr; } Filename pathname(filename); if (pathname.is_local()) { @@ -1151,8 +1156,8 @@ do_get_file(const Filename &filename, int open_flags) const { // Now scan all the mount points, from the back (since later mounts override // more recent ones), until a match is found. - PT(VirtualFile) found_file = NULL; - VirtualFileComposite *composite_file = NULL; + PT(VirtualFile) found_file = nullptr; + VirtualFileComposite *composite_file = nullptr; // We use an index instead of an iterator, since the vector might change if // implicit mounts are added during this loop. @@ -1214,7 +1219,7 @@ do_get_file(const Filename &filename, int open_flags) const { } } - if (found_file == (VirtualFile *)NULL && vfs_implicit_mf) { + if (found_file == nullptr && vfs_implicit_mf) { // The file wasn't found, as-is. Does it appear to be an implicit .mf // file reference? ((VirtualFileSystem *)this)->consider_mount_mf(filename); @@ -1268,7 +1273,7 @@ consider_match(PT(VirtualFile) &found_file, VirtualFileComposite *&composite_fil return false; } - if (found_file == (VirtualFile *)NULL) { + if (found_file == nullptr) { // This was our first match. Save it. found_file = vfile; if (!found_file->is_directory() || ((open_flags & OF_make_directory) != 0)) { @@ -1279,7 +1284,7 @@ consider_match(PT(VirtualFile) &found_file, VirtualFileComposite *&composite_fil // It is a directory, so save it for later. if (implicit_pz_file) { // Don't look for directories named file.pz. - found_file = NULL; + found_file = nullptr; } } else { @@ -1293,7 +1298,7 @@ consider_match(PT(VirtualFile) &found_file, VirtualFileComposite *&composite_fil if (!implicit_pz_file) { // At least two directories matched to the same path. We need a // composite directory. - if (composite_file == (VirtualFileComposite *)NULL) { + if (composite_file == nullptr) { composite_file = new VirtualFileComposite((VirtualFileSystem *)this, found_file->get_original_filename()); composite_file->set_original_filename(original_filename); @@ -1333,7 +1338,7 @@ consider_mount_mf(const Filename &filename) { // Hey, here's a multifile reference! dirname.set_binary(); PT(VirtualFile) file = do_get_file(dirname, false); - if (file == (VirtualFile *)NULL || !file->is_regular_file()) { + if (file == nullptr || !file->is_regular_file()) { // Oh, never mind. Not a real file. return false; } @@ -1341,7 +1346,7 @@ consider_mount_mf(const Filename &filename) { PT(Multifile) multifile = new Multifile; istream *stream = file->open_read_file(false); - if (stream == (istream *)NULL) { + if (stream == nullptr) { // Couldn't read file. return false; } diff --git a/panda/src/express/virtualFileSystem.h b/panda/src/express/virtualFileSystem.h index 2ff1fa4e95..3b1d3b3ed9 100644 --- a/panda/src/express/virtualFileSystem.h +++ b/panda/src/express/virtualFileSystem.h @@ -37,7 +37,7 @@ class VirtualFileComposite; * For instance, a VirtualFileSystem can transparently mount one or more * Multifiles as their own subdirectory hierarchies. */ -class EXPCL_PANDAEXPRESS VirtualFileSystem { +class EXPCL_PANDA_EXPRESS VirtualFileSystem { PUBLISHED: VirtualFileSystem(); ~VirtualFileSystem(); @@ -48,9 +48,9 @@ PUBLISHED: BLOCKING bool mount(Multifile *multifile, const Filename &mount_point, int flags); BLOCKING bool mount(const Filename &physical_filename, const Filename &mount_point, - int flags, const string &password = ""); + int flags, const std::string &password = ""); BLOCKING bool mount_loop(const Filename &virtual_filename, const Filename &mount_point, - int flags, const string &password = ""); + int flags, const std::string &password = ""); bool mount(VirtualFileMount *mount, const Filename &mount_point, int flags); BLOCKING int unmount(Multifile *multifile); BLOCKING int unmount(const Filename &physical_filename); @@ -78,7 +78,7 @@ PUBLISHED: BLOCKING bool copy_file(const Filename &orig_filename, const Filename &new_filename); BLOCKING bool resolve_filename(Filename &filename, const DSearchPath &searchpath, - const string &default_extension = string()) const; + const std::string &default_extension = std::string()) const; BLOCKING int find_all_files(const Filename &filename, const DSearchPath &searchpath, DSearchPath::Results &results) const; @@ -91,42 +91,42 @@ PUBLISHED: INLINE void ls(const Filename &filename) const; INLINE void ls_all(const Filename &filename) const; - void write(ostream &out) const; + void write(std::ostream &out) const; static VirtualFileSystem *get_global_ptr(); EXTENSION(PyObject *read_file(const Filename &filename, bool auto_unwrap) const); - BLOCKING istream *open_read_file(const Filename &filename, bool auto_unwrap) const; - BLOCKING static void close_read_file(istream *stream); + BLOCKING std::istream *open_read_file(const Filename &filename, bool auto_unwrap) const; + BLOCKING static void close_read_file(std::istream *stream); EXTENSION(PyObject *write_file(const Filename &filename, PyObject *data, bool auto_wrap)); - BLOCKING ostream *open_write_file(const Filename &filename, bool auto_wrap, bool truncate); - BLOCKING ostream *open_append_file(const Filename &filename); - BLOCKING static void close_write_file(ostream *stream); + BLOCKING std::ostream *open_write_file(const Filename &filename, bool auto_wrap, bool truncate); + BLOCKING std::ostream *open_append_file(const Filename &filename); + BLOCKING static void close_write_file(std::ostream *stream); - BLOCKING iostream *open_read_write_file(const Filename &filename, bool truncate); - BLOCKING iostream *open_read_append_file(const Filename &filename); - BLOCKING static void close_read_write_file(iostream *stream); + BLOCKING std::iostream *open_read_write_file(const Filename &filename, bool truncate); + BLOCKING std::iostream *open_read_append_file(const Filename &filename); + BLOCKING static void close_read_write_file(std::iostream *stream); public: // We provide Python versions of these as efficient extension methods, // above. - BLOCKING INLINE string read_file(const Filename &filename, bool auto_unwrap) const; - BLOCKING INLINE bool write_file(const Filename &filename, const string &data, bool auto_wrap); + BLOCKING INLINE std::string read_file(const Filename &filename, bool auto_unwrap) const; + BLOCKING INLINE bool write_file(const Filename &filename, const std::string &data, bool auto_wrap); - bool atomic_compare_and_exchange_contents(const Filename &filename, string &orig_contents, const string &old_contents, const string &new_contents); - bool atomic_read_contents(const Filename &filename, string &contents) const; + bool atomic_compare_and_exchange_contents(const Filename &filename, std::string &orig_contents, const std::string &old_contents, const std::string &new_contents); + bool atomic_read_contents(const Filename &filename, std::string &contents) const; - INLINE bool read_file(const Filename &filename, string &result, bool auto_unwrap) const; - INLINE bool read_file(const Filename &filename, pvector &result, bool auto_unwrap) const; + INLINE bool read_file(const Filename &filename, std::string &result, bool auto_unwrap) const; + INLINE bool read_file(const Filename &filename, vector_uchar &result, bool auto_unwrap) const; INLINE bool write_file(const Filename &filename, const unsigned char *data, size_t data_size, bool auto_wrap); void scan_mount_points(vector_string &names, const Filename &path) const; - static void parse_options(const string &options, - int &flags, string &password); - static void parse_option(const string &option, - int &flags, string &password); + static void parse_options(const std::string &options, + int &flags, std::string &password); + static void parse_option(const std::string &option, + int &flags, std::string &password); public: // These flags are passed to do_get_file() and @@ -157,7 +157,7 @@ private: int open_flags) const; bool consider_mount_mf(const Filename &filename); - MutexImpl _lock; + mutable MutexImpl _lock; typedef pvector Mounts; Mounts _mounts; unsigned int _mount_seq; diff --git a/panda/src/express/virtualFileSystem_ext.cxx b/panda/src/express/virtualFileSystem_ext.cxx index 6bc375c0d9..6018378f90 100644 --- a/panda/src/express/virtualFileSystem_ext.cxx +++ b/panda/src/express/virtualFileSystem_ext.cxx @@ -73,11 +73,11 @@ write_file(const Filename &filename, PyObject *data, bool auto_wrap) { #if PY_MAJOR_VERSION >= 3 if (PyBytes_AsStringAndSize(data, &buffer, &length) == -1) { - return NULL; + return nullptr; } #else if (PyString_AsStringAndSize(data, &buffer, &length) == -1) { - return NULL; + return nullptr; } #endif diff --git a/panda/src/express/virtualFile_ext.cxx b/panda/src/express/virtualFile_ext.cxx index db1a9a62ab..afe7473bbd 100644 --- a/panda/src/express/virtualFile_ext.cxx +++ b/panda/src/express/virtualFile_ext.cxx @@ -74,11 +74,11 @@ write_file(PyObject *data, bool auto_wrap) { #if PY_MAJOR_VERSION >= 3 if (PyBytes_AsStringAndSize(data, &buffer, &length) == -1) { - return NULL; + return nullptr; } #else if (PyString_AsStringAndSize(data, &buffer, &length) == -1) { - return NULL; + return nullptr; } #endif diff --git a/panda/src/express/weakPointerCallback.h b/panda/src/express/weakPointerCallback.h index 37b4ed2b9c..e3d300bcb3 100644 --- a/panda/src/express/weakPointerCallback.h +++ b/panda/src/express/weakPointerCallback.h @@ -21,7 +21,7 @@ * get an immediate callback from a WeakPointerTo object when its referenced * pointer is deleted. */ -class EXPCL_PANDAEXPRESS WeakPointerCallback { +class EXPCL_PANDA_EXPRESS WeakPointerCallback { public: virtual ~WeakPointerCallback(); virtual void wp_callback(void *pointer)=0; diff --git a/panda/src/express/weakPointerTo.I b/panda/src/express/weakPointerTo.I index aec710288f..c6e570979f 100644 --- a/panda/src/express/weakPointerTo.I +++ b/panda/src/express/weakPointerTo.I @@ -43,9 +43,9 @@ WeakPointerTo(const WeakPointerTo ©) : * */ template -INLINE TYPENAME WeakPointerTo::To &WeakPointerTo:: +INLINE typename WeakPointerTo::To &WeakPointerTo:: operator *() const { - nassertr(!this->was_deleted(), *((To *)NULL)); + assert(!this->was_deleted()); return *((To *)WeakPointerToBase::_void_ptr); } @@ -53,9 +53,9 @@ operator *() const { * */ template -INLINE TYPENAME WeakPointerTo::To *WeakPointerTo:: +INLINE typename WeakPointerTo::To *WeakPointerTo:: operator -> () const { - nassertr(!this->was_deleted(), (To *)NULL); + assert(!this->was_deleted()); return (To *)WeakPointerToBase::_void_ptr; } @@ -68,18 +68,47 @@ operator -> () const { template INLINE WeakPointerTo:: operator T * () const { - nassertr(!this->was_deleted(), (To *)NULL); + assert(!this->was_deleted()); return (To *)WeakPointerToBase::_void_ptr; } +/** + * A thread-safe way to access the underlying pointer; will silently return + * null if the underlying pointer was deleted or null. + * Note that this may return null even if was_deleted() still returns true, + * which can occur if the object has reached reference count 0 and is about to + * be destroyed. + */ +template +INLINE PointerTo WeakPointerTo:: +lock() const { + WeakReferenceList *weak_ref = this->_weak_ref; + if (weak_ref != nullptr) { + PointerTo ptr; + weak_ref->_lock.lock(); + if (!weak_ref->was_deleted()) { + // We also need to check that the reference count is not zero (which can + // happen if the object is currently being destructed), since that could + // cause double deletion. + To *plain_ptr = (To *)WeakPointerToBase::_void_ptr; + if (plain_ptr != nullptr && plain_ptr->ref_if_nonzero()) { + ptr.cheat() = plain_ptr; + } + } + weak_ref->_lock.unlock(); + return ptr; + } + return nullptr; +} + /** * Returns an ordinary pointer instead of a WeakPointerTo. Useful to work * around compiler problems, particularly for implicit upcasts. */ template -INLINE TYPENAME WeakPointerTo::To *WeakPointerTo:: +INLINE typename WeakPointerTo::To *WeakPointerTo:: p() const { - nassertr(!this->was_deleted(), (To *)NULL); + assert(!this->was_deleted()); return (To *)WeakPointerToBase::_void_ptr; } @@ -88,7 +117,7 @@ p() const { * deleted. */ template -INLINE TYPENAME WeakPointerTo::To *WeakPointerTo:: +INLINE typename WeakPointerTo::To *WeakPointerTo:: get_orig() const { return (To *)WeakPointerToBase::_void_ptr; } @@ -129,7 +158,7 @@ operator = (const WeakPointerTo ©) { template INLINE WeakConstPointerTo:: WeakConstPointerTo(const To *ptr) : - WeakPointerToBase((TYPENAME WeakConstPointerTo::To *)ptr) + WeakPointerToBase((typename WeakConstPointerTo::To *)ptr) { } @@ -177,9 +206,9 @@ WeakConstPointerTo(const WeakConstPointerTo ©) : * */ template -INLINE const TYPENAME WeakConstPointerTo::To &WeakConstPointerTo:: +INLINE const typename WeakConstPointerTo::To &WeakConstPointerTo:: operator *() const { - nassertr(!this->was_deleted(), *((To *)NULL)); + assert(!this->was_deleted()); return *((To *)WeakPointerToBase::_void_ptr); } @@ -187,9 +216,9 @@ operator *() const { * */ template -INLINE const TYPENAME WeakConstPointerTo::To *WeakConstPointerTo:: +INLINE const typename WeakConstPointerTo::To *WeakConstPointerTo:: operator -> () const { - nassertr(!this->was_deleted(), (To *)NULL); + assert(!this->was_deleted()); return (To *)WeakPointerToBase::_void_ptr; } @@ -203,18 +232,44 @@ operator -> () const { template INLINE WeakConstPointerTo:: operator const T * () const { - nassertr(!this->was_deleted(), (To *)NULL); + assert(!this->was_deleted()); return (To *)WeakPointerToBase::_void_ptr; } +/** + * A thread-safe way to access the underlying pointer; will silently return + * null if the underlying pointer was deleted or null. + */ +template +INLINE ConstPointerTo WeakConstPointerTo:: +lock() const { + WeakReferenceList *weak_ref = this->_weak_ref; + if (weak_ref != nullptr) { + ConstPointerTo ptr; + weak_ref->_lock.lock(); + if (!weak_ref->was_deleted()) { + // We also need to check that the reference count is not zero (which can + // happen if the object is currently being destructed), since that could + // cause double deletion. + const To *plain_ptr = (const To *)WeakPointerToBase::_void_ptr; + if (plain_ptr != nullptr && plain_ptr->ref_if_nonzero()) { + ptr.cheat() = plain_ptr; + } + } + weak_ref->_lock.unlock(); + return ptr; + } + return nullptr; +} + /** * Returns an ordinary pointer instead of a WeakConstPointerTo. Useful to * work around compiler problems, particularly for implicit upcasts. */ template -INLINE const TYPENAME WeakConstPointerTo::To *WeakConstPointerTo:: +INLINE const typename WeakConstPointerTo::To *WeakConstPointerTo:: p() const { - nassertr(!this->was_deleted(), (To *)NULL); + assert(!this->was_deleted()); return (To *)WeakPointerToBase::_void_ptr; } @@ -223,7 +278,7 @@ p() const { * deleted. */ template -INLINE const TYPENAME WeakConstPointerTo::To *WeakConstPointerTo:: +INLINE const typename WeakConstPointerTo::To *WeakConstPointerTo:: get_orig() const { return (To *)WeakPointerToBase::_void_ptr; } diff --git a/panda/src/express/weakPointerTo.h b/panda/src/express/weakPointerTo.h index 44d9561eb3..2e8c6029a5 100644 --- a/panda/src/express/weakPointerTo.h +++ b/panda/src/express/weakPointerTo.h @@ -28,9 +28,9 @@ template class WeakPointerTo : public WeakPointerToBase { public: - typedef TYPENAME WeakPointerToBase::To To; + typedef typename WeakPointerToBase::To To; PUBLISHED: - INLINE WeakPointerTo(To *ptr = (To *)NULL); + INLINE WeakPointerTo(To *ptr = nullptr); INLINE WeakPointerTo(const PointerTo ©); INLINE WeakPointerTo(const WeakPointerTo ©); @@ -38,9 +38,10 @@ public: INLINE To &operator *() const; INLINE To *operator -> () const; // MSVC.NET 2005 insists that we use T *, and not To *, here. - INLINE operator T *() const; + INLINE explicit operator T *() const; PUBLISHED: + INLINE PointerTo lock() const; INLINE To *p() const; INLINE To *get_orig() const; @@ -63,9 +64,9 @@ PUBLISHED: template class WeakConstPointerTo : public WeakPointerToBase { public: - typedef TYPENAME WeakPointerToBase::To To; + typedef typename WeakPointerToBase::To To; PUBLISHED: - INLINE WeakConstPointerTo(const To *ptr = (const To *)NULL); + INLINE WeakConstPointerTo(const To *ptr = nullptr); INLINE WeakConstPointerTo(const PointerTo ©); INLINE WeakConstPointerTo(const ConstPointerTo ©); INLINE WeakConstPointerTo(const WeakPointerTo ©); @@ -74,9 +75,10 @@ PUBLISHED: public: INLINE const To &operator *() const; INLINE const To *operator -> () const; - INLINE operator const T *() const; + INLINE explicit operator const T *() const; PUBLISHED: + INLINE ConstPointerTo lock() const; INLINE const To *p() const; INLINE const To *get_orig() const; diff --git a/panda/src/express/weakPointerToBase.I b/panda/src/express/weakPointerToBase.I index cb60c43fc2..2e537c9639 100644 --- a/panda/src/express/weakPointerToBase.I +++ b/panda/src/express/weakPointerToBase.I @@ -17,7 +17,13 @@ template INLINE WeakPointerToBase:: WeakPointerToBase(To *ptr) { - reassign(ptr); + _void_ptr = (To *)ptr; + if (ptr != nullptr) { + _weak_ref = ptr->weak_ref(); +#ifdef DO_MEMORY_USAGE + update_type(ptr); +#endif + } } /** @@ -26,7 +32,13 @@ WeakPointerToBase(To *ptr) { template INLINE WeakPointerToBase:: WeakPointerToBase(const PointerToBase ©) { - reassign(copy); + // This double-casting is a bit of a cheat to get around the inheritance + // issue--it's difficult to declare a template class to be a friend. + To *ptr = (To *)((const WeakPointerToBase *)©)->_void_ptr; + _void_ptr = ptr; + if (ptr != nullptr) { + _weak_ref = ptr->weak_ref(); + } } /** @@ -36,11 +48,35 @@ template INLINE WeakPointerToBase:: WeakPointerToBase(const WeakPointerToBase ©) { _void_ptr = copy._void_ptr; - _ptr_was_deleted = copy._ptr_was_deleted; - if (is_valid_pointer()) { - To *ptr = (To *)_void_ptr; - ptr->weak_ref(this); + // Don't bother increasing the weak reference count if the object was + // already deleted. + WeakReferenceList *weak_ref = copy._weak_ref; + if (weak_ref != nullptr && !weak_ref->was_deleted()) { + _weak_ref = copy._weak_ref; + _weak_ref->ref(); + } +} + +/** + * + */ +template +INLINE WeakPointerToBase:: +WeakPointerToBase(WeakPointerToBase &&from) noexcept { + // Protect against self-move-assignment. + if (from._void_ptr != this->_void_ptr) { + WeakReferenceList *old_ref = (To *)this->_weak_ref; + + this->_void_ptr = from._void_ptr; + this->_weak_ref = from._weak_ref; + from._void_ptr = nullptr; + from._weak_ref = nullptr; + + // Now delete the old pointer. + if (old_ref != nullptr && !old_ref->unref()) { + delete old_ref; + } } } @@ -50,7 +86,10 @@ WeakPointerToBase(const WeakPointerToBase ©) { template INLINE WeakPointerToBase:: ~WeakPointerToBase() { - reassign((To *)NULL); + WeakReferenceList *old_ref = (WeakReferenceList *)_weak_ref; + if (old_ref != nullptr && !old_ref->unref()) { + delete old_ref; + } } /** @@ -60,34 +99,23 @@ INLINE WeakPointerToBase:: template void WeakPointerToBase:: reassign(To *ptr) { - if (ptr != (To *)_void_ptr || _ptr_was_deleted) { - To *old_ptr = (To *)_void_ptr; + if (ptr != (To *)_void_ptr) { + WeakReferenceList *old_ref = (WeakReferenceList *)_weak_ref; _void_ptr = (void *)ptr; - if (ptr != (To *)NULL) { - ptr->weak_ref(this); + if (ptr != nullptr) { + _weak_ref = ptr->weak_ref(); #ifdef DO_MEMORY_USAGE - if (MemoryUsage::get_track_memory_usage()) { - // Make sure the MemoryUsage record knows what the TypeHandle is, if - // we know it ourselves. - TypeHandle type = get_type_handle(To); - if (type == TypeHandle::none()) { - do_init_type(To); - type = get_type_handle(To); - } - if (type != TypeHandle::none()) { - MemoryUsage::update_type(ptr, type); - } - } + update_type(ptr); #endif + } else { + _weak_ref = nullptr; } // Now remove the old reference. - if (old_ptr != (To *)NULL && !_ptr_was_deleted) { - old_ptr->weak_unref(this); + if (old_ref != nullptr && !old_ref->unref()) { + delete old_ref; } - - _ptr_was_deleted = false; } } @@ -108,12 +136,72 @@ reassign(const PointerToBase ©) { template INLINE void WeakPointerToBase:: reassign(const WeakPointerToBase ©) { - nassertv(!copy.was_deleted()); - reassign((To *)copy._void_ptr); + void *new_ptr = copy._void_ptr; + if (new_ptr != _void_ptr) { + WeakReferenceList *old_ref = (WeakReferenceList *)_weak_ref; + _void_ptr = new_ptr; + + // Don't bother increasing the weak reference count if the object was + // already deleted. + WeakReferenceList *weak_ref = copy._weak_ref; + if (weak_ref != nullptr && !weak_ref->was_deleted()) { + weak_ref->ref(); + _weak_ref = weak_ref; + } else { + _weak_ref = nullptr; + } + + // Now remove the old reference. + if (old_ref != nullptr && !old_ref->unref()) { + delete old_ref; + } + } +} + +/** + * + */ +template +INLINE void WeakPointerToBase:: +reassign(WeakPointerToBase &&from) noexcept { + // Protect against self-move-assignment. + if (from._void_ptr != this->_void_ptr) { + WeakReferenceList *old_ref = (WeakReferenceList *)this->_weak_ref; + + this->_void_ptr = from._void_ptr; + this->_weak_ref = from._weak_ref; + from._void_ptr = nullptr; + from._weak_ref = nullptr; + + // Now delete the old pointer. + if (old_ref != nullptr && !old_ref->unref()) { + delete old_ref; + } + } +} + +/** + * Ensures that the MemoryUsage record for the pointer has the right type of + * object, if we know the type ourselves. + */ +template +INLINE void WeakPointerToBase:: +update_type(To *ptr) { +#ifdef DO_MEMORY_USAGE + if (MemoryUsage::get_track_memory_usage()) { + TypeHandle type = get_type_handle(To); + if (type == TypeHandle::none()) { + do_init_type(To); + type = get_type_handle(To); + } + if (type != TypeHandle::none()) { + MemoryUsage::update_type(ptr, type); + } + } +#endif // DO_MEMORY_USAGE } #ifndef CPPPARSER -#ifndef WIN32_VC /** * */ @@ -203,6 +291,51 @@ operator >= (To *other) const { return (To *)_void_ptr >= other; } +/** + * + */ +template +INLINE bool WeakPointerToBase:: +operator == (std::nullptr_t) const { + return _void_ptr == nullptr; +} + +/** + * + */ +template +INLINE bool WeakPointerToBase:: +operator != (std::nullptr_t) const { + return _void_ptr != nullptr; +} + +/** + * + */ +template +INLINE bool WeakPointerToBase:: +operator > (std::nullptr_t) const { + return _void_ptr != nullptr; +} + +/** + * + */ +template +INLINE bool WeakPointerToBase:: +operator <= (std::nullptr_t) const { + return _void_ptr == nullptr; +} + +/** + * + */ +template +INLINE bool WeakPointerToBase:: +operator >= (std::nullptr_t) const { + return true; +} + /** * */ @@ -292,7 +425,6 @@ INLINE bool WeakPointerToBase:: operator >= (const PointerToBase &other) const { return (To *)_void_ptr >= (To *)((WeakPointerToBase *)&other)->_void_ptr; } -#endif // WIN32_VC /** * @@ -303,6 +435,15 @@ operator < (const To *other) const { return (To *)_void_ptr < other; } +/** + * + */ +template +INLINE bool WeakPointerToBase:: +operator < (std::nullptr_t) const { + return false; +} + /** * */ @@ -323,8 +464,6 @@ operator < (const PointerToBase &other) const { #endif // CPPPARSER - - /** * A convenient way to set the PointerTo object to NULL. (Assignment to a NULL * pointer also works, of course.) @@ -332,7 +471,14 @@ operator < (const PointerToBase &other) const { template INLINE void WeakPointerToBase:: clear() { - reassign((To *)NULL); + WeakReferenceList *old_ref = (WeakReferenceList *)_weak_ref; + _void_ptr = nullptr; + _weak_ref = nullptr; + + // Now remove the old reference. + if (old_ref != nullptr && !old_ref->unref()) { + delete old_ref; + } } /** @@ -346,7 +492,9 @@ clear() { template INLINE void WeakPointerToBase:: refresh() const { - ((WeakPointerToBase *)this)->reassign((To *)_void_ptr); + if (_void_ptr != nullptr) { + ((WeakPointerToBase *)this)->reassign((To *)_void_ptr); + } } /** @@ -355,11 +503,11 @@ refresh() const { */ template INLINE void WeakPointerToBase:: -output(ostream &out) const { +output(std::ostream &out) const { out << _void_ptr; if (was_deleted()) { out << ":deleted"; - } else if (_void_ptr != (void *)NULL) { + } else if (_void_ptr != nullptr) { out << ":" << ((To *)_void_ptr)->get_ref_count(); } } diff --git a/panda/src/express/weakPointerToBase.h b/panda/src/express/weakPointerToBase.h index 04d55b8b1d..a34b39bdb5 100644 --- a/panda/src/express/weakPointerToBase.h +++ b/panda/src/express/weakPointerToBase.h @@ -31,11 +31,15 @@ protected: INLINE WeakPointerToBase(To *ptr); INLINE WeakPointerToBase(const PointerToBase ©); INLINE WeakPointerToBase(const WeakPointerToBase ©); + INLINE WeakPointerToBase(WeakPointerToBase &&from) noexcept; INLINE ~WeakPointerToBase(); void reassign(To *ptr); INLINE void reassign(const PointerToBase ©); INLINE void reassign(const WeakPointerToBase ©); + INLINE void reassign(WeakPointerToBase &&from) noexcept; + + INLINE void update_type(To *ptr); // No assignment or retrieval functions are declared in WeakPointerToBase, // because we will have to specialize on const vs. non-const later. @@ -44,7 +48,6 @@ public: // These comparison functions are common to all things PointerTo, so they're // defined up here. #ifndef CPPPARSER -#ifndef WIN32_VC INLINE bool operator == (const To *other) const; INLINE bool operator != (const To *other) const; INLINE bool operator > (const To *other) const; @@ -56,6 +59,12 @@ public: INLINE bool operator <= (To *other) const; INLINE bool operator >= (To *other) const; + INLINE bool operator == (std::nullptr_t) const; + INLINE bool operator != (std::nullptr_t) const; + INLINE bool operator > (std::nullptr_t) const; + INLINE bool operator <= (std::nullptr_t) const; + INLINE bool operator >= (std::nullptr_t) const; + INLINE bool operator == (const WeakPointerToBase &other) const; INLINE bool operator != (const WeakPointerToBase &other) const; INLINE bool operator > (const WeakPointerToBase &other) const; @@ -67,8 +76,9 @@ public: INLINE bool operator > (const PointerToBase &other) const; INLINE bool operator <= (const PointerToBase &other) const; INLINE bool operator >= (const PointerToBase &other) const; -#endif // WIN32_VC + INLINE bool operator < (const To *other) const; + INLINE bool operator < (std::nullptr_t) const; INLINE bool operator < (const WeakPointerToBase &other) const; INLINE bool operator < (const PointerToBase &other) const; #endif // CPPPARSER @@ -77,11 +87,11 @@ PUBLISHED: INLINE void clear(); INLINE void refresh() const; - void output(ostream &out) const; + void output(std::ostream &out) const; }; template -INLINE ostream &operator <<(ostream &out, const WeakPointerToBase &pointer) { +INLINE std::ostream &operator <<(std::ostream &out, const WeakPointerToBase &pointer) { pointer.output(out); return out; } diff --git a/panda/src/express/weakPointerToVoid.I b/panda/src/express/weakPointerToVoid.I index bc778630b7..120836510d 100644 --- a/panda/src/express/weakPointerToVoid.I +++ b/panda/src/express/weakPointerToVoid.I @@ -15,46 +15,34 @@ * */ INLINE WeakPointerToVoid:: -WeakPointerToVoid() : - _ptr_was_deleted(false), - _callback(NULL) { +WeakPointerToVoid() : _weak_ref(nullptr) { } /** - * This is intended only to be called by the WeakPointerList destructor. It - * indicates that the object that we were pointing to has just been deleted. - */ -INLINE void WeakPointerToVoid:: -mark_deleted() { - nassertv(!_ptr_was_deleted); - _ptr_was_deleted = true; - if (_callback != (WeakPointerCallback *)NULL) { - _callback->wp_callback(_void_ptr); - } -} - -/** - * Sets a callback that will be made when the pointer is deleted. If a - * previous callback has already been set, it will be replaced. + * Sets a callback that will be made when the pointer is deleted. Does + * nothing if this is a null pointer. * * If the pointer has already been deleted, the callback will be made * immediately. */ INLINE void WeakPointerToVoid:: -set_callback(WeakPointerCallback *callback) { - _callback = callback; - if (_ptr_was_deleted && _callback != (WeakPointerCallback *)NULL) { - _callback->wp_callback(_void_ptr); +add_callback(WeakPointerCallback *callback) const { + if (_weak_ref != nullptr && !_weak_ref->was_deleted()) { + _weak_ref->add_callback(callback, _void_ptr); + } else if (_void_ptr != nullptr) { + callback->wp_callback(_void_ptr); + _weak_ref = nullptr; } } /** - * Returns the callback that will be made when the pointer is deleted, or NULL - * if no callback has been set. + * Removes a previously added callback. */ -INLINE WeakPointerCallback *WeakPointerToVoid:: -get_callback() const { - return _callback; +INLINE void WeakPointerToVoid:: +remove_callback(WeakPointerCallback *callback) const { + if (_weak_ref != nullptr) { + _weak_ref->remove_callback(callback); + } } /** @@ -63,7 +51,7 @@ get_callback() const { */ INLINE bool WeakPointerToVoid:: was_deleted() const { - return _ptr_was_deleted; + return _void_ptr != nullptr && (_weak_ref == nullptr || _weak_ref->was_deleted()); } /** @@ -72,5 +60,5 @@ was_deleted() const { */ INLINE bool WeakPointerToVoid:: is_valid_pointer() const { - return (_void_ptr != (void *)NULL) && !_ptr_was_deleted; + return _weak_ref != nullptr && !_weak_ref->was_deleted(); } diff --git a/panda/src/express/weakPointerToVoid.h b/panda/src/express/weakPointerToVoid.h index 98a481e49e..56ace2dcb2 100644 --- a/panda/src/express/weakPointerToVoid.h +++ b/panda/src/express/weakPointerToVoid.h @@ -17,28 +17,26 @@ #include "pandabase.h" #include "pointerToVoid.h" #include "weakPointerCallback.h" +#include "weakReferenceList.h" /** * This is the specialization of PointerToVoid for weak pointers. It needs an * additional flag to indicate that the pointer has been deleted. */ -class EXPCL_PANDAEXPRESS WeakPointerToVoid : public PointerToVoid { +class EXPCL_PANDA_EXPRESS WeakPointerToVoid : public PointerToVoid { protected: INLINE WeakPointerToVoid(); public: - INLINE void mark_deleted(); - - INLINE void set_callback(WeakPointerCallback *callback); - INLINE WeakPointerCallback *get_callback() const; + INLINE void add_callback(WeakPointerCallback *callback) const; + INLINE void remove_callback(WeakPointerCallback *callback) const; PUBLISHED: INLINE bool was_deleted() const; INLINE bool is_valid_pointer() const; protected: - bool _ptr_was_deleted; - WeakPointerCallback *_callback; + mutable WeakReferenceList *_weak_ref; }; #include "weakPointerToVoid.I" diff --git a/panda/src/express/weakReferenceList.I b/panda/src/express/weakReferenceList.I index 661c4c268f..0e4efc8c52 100644 --- a/panda/src/express/weakReferenceList.I +++ b/panda/src/express/weakReferenceList.I @@ -10,3 +10,30 @@ * @author drose * @date 2004-09-27 */ + +/** + * Increases the number of weak references. + */ +INLINE void WeakReferenceList:: +ref() const { + AtomicAdjust::inc(_count); +} + +/** + * Decreases the number of weak references. Returns true if, after this, + * there are still any weak or strong references remaining, or false if this + * structure should be deleted right away. + */ +INLINE bool WeakReferenceList:: +unref() const { + return AtomicAdjust::dec(_count); +} + +/** + * Returns true if the object represented has been deleted, ie. there are only + * weak references left pointing to the object. + */ +INLINE bool WeakReferenceList:: +was_deleted() const { + return AtomicAdjust::get(_count) < _alive_offset; +} diff --git a/panda/src/express/weakReferenceList.cxx b/panda/src/express/weakReferenceList.cxx index cd940b2ecf..0534556d7a 100644 --- a/panda/src/express/weakReferenceList.cxx +++ b/panda/src/express/weakReferenceList.cxx @@ -19,7 +19,7 @@ * */ WeakReferenceList:: -WeakReferenceList() { +WeakReferenceList() : _count(_alive_offset) { } /** @@ -27,30 +27,33 @@ WeakReferenceList() { */ WeakReferenceList:: ~WeakReferenceList() { - _lock.acquire(); - Pointers::iterator pi; - for (pi = _pointers.begin(); pi != _pointers.end(); ++pi) { - (*pi)->mark_deleted(); - } - _lock.release(); + nassertv(_count == 0); } /** - * Intended to be called only by WeakPointerTo (or by any class implementing a - * weak reference-counting pointer), this adds the indicated PointerToVoid - * structure to the list of such structures that are maintaining a weak - * pointer to this object. + * Adds the callback to the list of callbacks that will be called when the + * underlying pointer is deleted. If it has already been deleted, it will + * be called immediately. * - * When the WeakReferenceList destructs (presumably because its owning object - * destructs), the pointer within the PointerToVoid object will be set to - * NULL. + * The data pointer can be an arbitrary pointer and is passed as only argument + * to the callback. */ void WeakReferenceList:: -add_reference(WeakPointerToVoid *ptv) { - _lock.acquire(); - bool inserted = _pointers.insert(ptv).second; - _lock.release(); - nassertv(inserted); +add_callback(WeakPointerCallback *callback, void *data) { + nassertv(callback != nullptr); + _lock.lock(); + // We need to check again whether the object is deleted after grabbing the + // lock, despite having already done this in weakPointerTo.I, since it may + // have been deleted in the meantime. + bool deleted = was_deleted(); + if (!deleted) { + _callbacks.insert(std::make_pair(callback, data)); + } + _lock.unlock(); + + if (deleted) { + callback->wp_callback(data); + } } /** @@ -60,13 +63,33 @@ add_reference(WeakPointerToVoid *ptv) { * pointer to this object. */ void WeakReferenceList:: -clear_reference(WeakPointerToVoid *ptv) { - _lock.acquire(); - Pointers::iterator pi = _pointers.find(ptv); - bool valid = (pi != _pointers.end()); - if (valid) { - _pointers.erase(pi); - } - _lock.release(); - nassertv(valid); +remove_callback(WeakPointerCallback *callback) { + nassertv(callback != nullptr); + _lock.lock(); + _callbacks.erase(callback); + _lock.unlock(); +} + +/** + * Called only by the ReferenceCount pointer to indicate that it has been + * deleted. + */ +void WeakReferenceList:: +mark_deleted() { + _lock.lock(); + Callbacks::iterator ci; + for (ci = _callbacks.begin(); ci != _callbacks.end(); ++ci) { + (*ci).first->wp_callback((*ci).second); + } + _callbacks.clear(); + + // Decrement the special offset added to the weak pointer count to indicate + // that it can be deleted when all the weak references have gone. + AtomicAdjust::Integer result = AtomicAdjust::add(_count, -_alive_offset); + _lock.unlock(); + if (result == 0) { + // There are no weak references remaining either, so delete this. + delete this; + } + nassertv(result >= 0); } diff --git a/panda/src/express/weakReferenceList.h b/panda/src/express/weakReferenceList.h index 16651b7364..30ab68edae 100644 --- a/panda/src/express/weakReferenceList.h +++ b/panda/src/express/weakReferenceList.h @@ -15,30 +15,48 @@ #define WEAKREFERENCELIST_H #include "pandabase.h" -#include "pset.h" +#include "pmap.h" #include "mutexImpl.h" -class WeakPointerToVoid; +class WeakPointerCallback; /** - * This is a list of WeakPointerTo's that share a reference to a given - * ReferenceCount object. It is stored in a separate class since it is - * assumed that most ReferenceCount objects do not need to store this list at - * all; this avoids bloating every ReferenceCount object in the world with the - * size of this object. + * This is an object shared by all the weak pointers that point to the same + * ReferenceCount object. It is created whenever a weak reference to an + * object is created, and can outlive the object until all weak references + * have disappeared. */ -class EXPCL_PANDAEXPRESS WeakReferenceList { +class EXPCL_PANDA_EXPRESS WeakReferenceList { public: WeakReferenceList(); ~WeakReferenceList(); - void add_reference(WeakPointerToVoid *ptv); - void clear_reference(WeakPointerToVoid *ptv); + INLINE void ref() const; + INLINE bool unref() const; + INLINE bool was_deleted() const; + + void add_callback(WeakPointerCallback *callback, void *data); + void remove_callback(WeakPointerCallback *callback); private: - typedef pset Pointers; - Pointers _pointers; + void mark_deleted(); + +public: + // This lock protects the callbacks below, but it also protects the object + // from being deleted during a call to WeakPointerTo::lock(). MutexImpl _lock; + +private: + typedef pmap Callbacks; + Callbacks _callbacks; + + // This has a very large number added to it if the object is still alive. + // It could be 1, but having it be a large number makes it easy to check + // whether the object has been deleted or not. + static const AtomicAdjust::Integer _alive_offset = (1 << 30); + mutable AtomicAdjust::Integer _count; + + friend class ReferenceCount; }; #include "weakReferenceList.I" diff --git a/panda/src/express/windowsRegistry.cxx b/panda/src/express/windowsRegistry.cxx index 183a3a9c0d..b96091c299 100644 --- a/panda/src/express/windowsRegistry.cxx +++ b/panda/src/express/windowsRegistry.cxx @@ -21,6 +21,8 @@ #endif #include +using std::string; + /** * Sets the registry key to the indicated value as a string. The supplied * string value is automatically converted from whatever encoding is set by @@ -32,9 +34,7 @@ set_string_value(const string &key, const string &name, const string &value, WindowsRegistry::RegLevel rl) { TextEncoder encoder; - wstring wvalue = encoder.decode_text(value); - - bool okflag = true; + std::wstring wvalue = encoder.decode_text(value); // Now convert the string to Windows' idea of the correct wide-char // encoding, so we can store it in the registry. This might well be the @@ -46,8 +46,8 @@ set_string_value(const string &key, const string &name, const string &value, int mb_result_len = WideCharToMultiByte(CP_ACP, 0, wvalue.data(), wvalue.length(), - NULL, 0, - NULL, NULL); + nullptr, 0, + nullptr, nullptr); if (mb_result_len == 0) { express_cat.error() << "Unable to convert '" << value @@ -59,7 +59,7 @@ set_string_value(const string &key, const string &name, const string &value, WideCharToMultiByte(CP_ACP, 0, wvalue.data(), wvalue.length(), mb_result, mb_result_len, - NULL, NULL); + nullptr, nullptr); if (express_cat.is_debug()) { express_cat.debug() @@ -141,7 +141,7 @@ get_string_value(const string &key, const string &name, int wide_result_len = MultiByteToWideChar(CP_ACP, 0, data.data(), data.length(), - NULL, 0); + nullptr, 0); if (wide_result_len == 0) { express_cat.error() << "Unable to convert '" << data @@ -154,7 +154,7 @@ get_string_value(const string &key, const string &name, data.data(), data.length(), wide_result, wide_result_len); - wstring wdata(wide_result, wide_result_len); + std::wstring wdata(wide_result, wide_result_len); TextEncoder encoder; string result = encoder.encode_wtext(wdata); @@ -347,7 +347,7 @@ format_message(int error_code) { PVOID buffer; DWORD length = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, error_code, 0, (LPTSTR)&buffer, 0, NULL); + nullptr, error_code, 0, (LPTSTR)&buffer, 0, nullptr); if (length == 0) { return "Unknown error message"; } diff --git a/panda/src/express/windowsRegistry.h b/panda/src/express/windowsRegistry.h index d8fa951234..c402eed2ab 100644 --- a/panda/src/express/windowsRegistry.h +++ b/panda/src/express/windowsRegistry.h @@ -25,7 +25,7 @@ * encoding and stores them in Unicode (and conversely reconverts them on * retrieval). */ -class EXPCL_PANDAEXPRESS WindowsRegistry +class EXPCL_PANDA_EXPRESS WindowsRegistry { PUBLISHED: enum RegLevel { @@ -33,27 +33,27 @@ PUBLISHED: rl_user = 1 }; - static bool set_string_value(const string &key, const string &name, - const string &value, RegLevel rl = rl_machine); - static bool set_int_value(const string &key, const string &name, int value, RegLevel rl = rl_machine); + static bool set_string_value(const std::string &key, const std::string &name, + const std::string &value, RegLevel rl = rl_machine); + static bool set_int_value(const std::string &key, const std::string &name, int value, RegLevel rl = rl_machine); enum Type { T_none, T_int, T_string, }; - static Type get_key_type(const string &key, const string &name, RegLevel rl = rl_machine); - static string get_string_value(const string &key, const string &name, - const string &default_value, RegLevel rl = rl_machine); - static int get_int_value(const string &key, const string &name, + static Type get_key_type(const std::string &key, const std::string &name, RegLevel rl = rl_machine); + static std::string get_string_value(const std::string &key, const std::string &name, + const std::string &default_value, RegLevel rl = rl_machine); + static int get_int_value(const std::string &key, const std::string &name, int default_value, RegLevel rl = rl_machine); private: - static bool do_set(const string &key, const string &name, + static bool do_set(const std::string &key, const std::string &name, int data_type, const void *data, int data_length, const RegLevel rl); - static bool do_get(const string &key, const string &name, - int &data_type, string &data, const RegLevel rl); - static string format_message(int error_code); + static bool do_get(const std::string &key, const std::string &name, + int &data_type, std::string &data, const RegLevel rl); + static std::string format_message(int error_code); }; #endif // WIN32_VC diff --git a/panda/src/express/zStream.I b/panda/src/express/zStream.I index 6385b26e67..6442d03037 100644 --- a/panda/src/express/zStream.I +++ b/panda/src/express/zStream.I @@ -15,14 +15,14 @@ * */ INLINE IDecompressStream:: -IDecompressStream() : istream(&_buf) { +IDecompressStream() : std::istream(&_buf) { } /** * */ INLINE IDecompressStream:: -IDecompressStream(istream *source, bool owns_source) : istream(&_buf) { +IDecompressStream(std::istream *source, bool owns_source) : std::istream(&_buf) { open(source, owns_source); } @@ -30,7 +30,7 @@ IDecompressStream(istream *source, bool owns_source) : istream(&_buf) { * */ INLINE IDecompressStream &IDecompressStream:: -open(istream *source, bool owns_source) { +open(std::istream *source, bool owns_source) { clear((ios_iostate)0); _buf.open_read(source, owns_source); return *this; @@ -51,15 +51,15 @@ close() { * */ INLINE OCompressStream:: -OCompressStream() : ostream(&_buf) { +OCompressStream() : std::ostream(&_buf) { } /** * */ INLINE OCompressStream:: -OCompressStream(ostream *dest, bool owns_dest, int compression_level) : - ostream(&_buf) +OCompressStream(std::ostream *dest, bool owns_dest, int compression_level) : + std::ostream(&_buf) { open(dest, owns_dest, compression_level); } @@ -68,7 +68,7 @@ OCompressStream(ostream *dest, bool owns_dest, int compression_level) : * */ INLINE OCompressStream &OCompressStream:: -open(ostream *dest, bool owns_dest, int compression_level) { +open(std::ostream *dest, bool owns_dest, int compression_level) { clear((ios_iostate)0); _buf.open_write(dest, owns_dest, compression_level); return *this; diff --git a/panda/src/express/zStream.h b/panda/src/express/zStream.h index b5fcd2d7a5..b05a75158c 100644 --- a/panda/src/express/zStream.h +++ b/panda/src/express/zStream.h @@ -31,16 +31,16 @@ * * Seeking is not supported. */ -class EXPCL_PANDAEXPRESS IDecompressStream : public istream { +class EXPCL_PANDA_EXPRESS IDecompressStream : public std::istream { PUBLISHED: INLINE IDecompressStream(); - INLINE explicit IDecompressStream(istream *source, bool owns_source); + INLINE explicit IDecompressStream(std::istream *source, bool owns_source); #if _MSC_VER >= 1800 INLINE IDecompressStream(const IDecompressStream ©) = delete; #endif - INLINE IDecompressStream &open(istream *source, bool owns_source); + INLINE IDecompressStream &open(std::istream *source, bool owns_source); INLINE IDecompressStream &close(); private: @@ -57,17 +57,17 @@ private: * * Seeking is not supported. */ -class EXPCL_PANDAEXPRESS OCompressStream : public ostream { +class EXPCL_PANDA_EXPRESS OCompressStream : public std::ostream { PUBLISHED: INLINE OCompressStream(); - INLINE explicit OCompressStream(ostream *dest, bool owns_dest, + INLINE explicit OCompressStream(std::ostream *dest, bool owns_dest, int compression_level = 6); #if _MSC_VER >= 1800 INLINE OCompressStream(const OCompressStream ©) = delete; #endif - INLINE OCompressStream &open(ostream *dest, bool owns_dest, + INLINE OCompressStream &open(std::ostream *dest, bool owns_dest, int compression_level = 6); INLINE OCompressStream &close(); diff --git a/panda/src/express/zStreamBuf.cxx b/panda/src/express/zStreamBuf.cxx index c6af03499b..877254918d 100644 --- a/panda/src/express/zStreamBuf.cxx +++ b/panda/src/express/zStreamBuf.cxx @@ -18,6 +18,10 @@ #include "pnotify.h" #include "config_express.h" +using std::ios; +using std::streamoff; +using std::streampos; + #if !defined(USE_MEMORY_NOWRAPPERS) && !defined(CPPPARSER) // Define functions that hook zlib into panda's memory allocation system. static void * @@ -35,9 +39,9 @@ do_zlib_free(voidpf opaque, voidpf address) { */ ZStreamBuf:: ZStreamBuf() { - _source = (istream *)NULL; + _source = nullptr; _owns_source = false; - _dest = (ostream *)NULL; + _dest = nullptr; _owns_dest = false; #ifdef PHAVE_IOSTREAM @@ -69,7 +73,7 @@ ZStreamBuf:: * */ void ZStreamBuf:: -open_read(istream *source, bool owns_source) { +open_read(std::istream *source, bool owns_source) { _source = source; _owns_source = owns_source; @@ -100,7 +104,7 @@ open_read(istream *source, bool owns_source) { */ void ZStreamBuf:: close_read() { - if (_source != (istream *)NULL) { + if (_source != nullptr) { int result = inflateEnd(&_z_source); if (result < 0) { @@ -112,7 +116,7 @@ close_read() { delete _source; _owns_source = false; } - _source = (istream *)NULL; + _source = nullptr; } } @@ -120,7 +124,7 @@ close_read() { * */ void ZStreamBuf:: -open_write(ostream *dest, bool owns_dest, int compression_level) { +open_write(std::ostream *dest, bool owns_dest, int compression_level) { _dest = dest; _owns_dest = owns_dest; @@ -151,7 +155,7 @@ open_write(ostream *dest, bool owns_dest, int compression_level) { */ void ZStreamBuf:: close_write() { - if (_dest != (ostream *)NULL) { + if (_dest != nullptr) { size_t n = pptr() - pbase(); write_chars(pbase(), n, Z_FINISH); pbump(-(int)n); @@ -166,7 +170,7 @@ close_write() { delete _dest; _owns_dest = false; } - _dest = (ostream *)NULL; + _dest = nullptr; } } @@ -250,12 +254,12 @@ overflow(int ch) { */ int ZStreamBuf:: sync() { - if (_source != (istream *)NULL) { + if (_source != nullptr) { size_t n = egptr() - gptr(); gbump(n); } - if (_dest != (ostream *)NULL) { + if (_dest != nullptr) { size_t n = pptr() - pbase(); write_chars(pbase(), n, Z_SYNC_FLUSH); pbump(-(int)n); @@ -392,7 +396,7 @@ write_chars(const char *start, size_t length, int flush) { */ void ZStreamBuf:: show_zlib_error(const char *function, int error_code, z_stream &z) { - stringstream error_line; + std::stringstream error_line; error_line << "zlib error in " << function << ": "; @@ -427,7 +431,7 @@ show_zlib_error(const char *function, int error_code, z_stream &z) { default: error_line << error_code; } - if (z.msg != (char *)NULL) { + if (z.msg != nullptr) { error_line << " = " << z.msg; } diff --git a/panda/src/express/zStreamBuf.h b/panda/src/express/zStreamBuf.h index a034a76d6c..35446090db 100644 --- a/panda/src/express/zStreamBuf.h +++ b/panda/src/express/zStreamBuf.h @@ -24,19 +24,19 @@ /** * The streambuf object that implements IDecompressStream and OCompressStream. */ -class EXPCL_PANDAEXPRESS ZStreamBuf : public streambuf { +class EXPCL_PANDA_DOWNLOADER ZStreamBuf : public std::streambuf { public: ZStreamBuf(); virtual ~ZStreamBuf(); - void open_read(istream *source, bool owns_source); + void open_read(std::istream *source, bool owns_source); void close_read(); - void open_write(ostream *dest, bool owns_dest, int compression_level); + void open_write(std::ostream *dest, bool owns_dest, int compression_level); void close_write(); - virtual streampos seekoff(streamoff off, ios_seekdir dir, ios_openmode which); - virtual streampos seekpos(streampos pos, ios_openmode which); + virtual std::streampos seekoff(std::streamoff off, ios_seekdir dir, ios_openmode which); + virtual std::streampos seekpos(std::streampos pos, ios_openmode which); protected: virtual int overflow(int c); @@ -49,10 +49,10 @@ private: void show_zlib_error(const char *function, int error_code, z_stream &z); private: - istream *_source; + std::istream *_source; bool _owns_source; - ostream *_dest; + std::ostream *_dest; bool _owns_dest; z_stream _z_source; diff --git a/panda/src/ffmpeg/ffmpegAudio.cxx b/panda/src/ffmpeg/ffmpegAudio.cxx index ee7fee8669..6fd9a01c9e 100644 --- a/panda/src/ffmpeg/ffmpegAudio.cxx +++ b/panda/src/ffmpeg/ffmpegAudio.cxx @@ -41,9 +41,9 @@ FfmpegAudio:: PT(MovieAudioCursor) FfmpegAudio:: open() { PT(FfmpegAudioCursor) result = new FfmpegAudioCursor(this); - if (result->_format_ctx == 0) { + if (result->_format_ctx == nullptr) { ffmpeg_cat.error() << "Could not open " << _filename << "\n"; - return NULL; + return nullptr; } else { return (MovieAudioCursor*)(FfmpegAudioCursor*)result; } diff --git a/panda/src/ffmpeg/ffmpegAudioCursor.cxx b/panda/src/ffmpeg/ffmpegAudioCursor.cxx index ef6cd14d92..621de7fe8a 100644 --- a/panda/src/ffmpeg/ffmpegAudioCursor.cxx +++ b/panda/src/ffmpeg/ffmpegAudioCursor.cxx @@ -46,14 +46,14 @@ FfmpegAudioCursor:: FfmpegAudioCursor(FfmpegAudio *src) : MovieAudioCursor(src), _filename(src->_filename), - _packet(0), - _packet_data(0), - _format_ctx(0), - _audio_ctx(0), - _resample_ctx(0), - _buffer(0), - _buffer_alloc(0), - _frame(0) + _packet(nullptr), + _packet_data(nullptr), + _format_ctx(nullptr), + _audio_ctx(nullptr), + _resample_ctx(nullptr), + _buffer(nullptr), + _buffer_alloc(nullptr), + _frame(nullptr) { if (!_ffvfile.open_vfs(_filename)) { cleanup(); @@ -61,9 +61,9 @@ FfmpegAudioCursor(FfmpegAudio *src) : } _format_ctx = _ffvfile.get_format_context(); - nassertv(_format_ctx != NULL); + nassertv(_format_ctx != nullptr); - if (avformat_find_stream_info(_format_ctx, NULL) < 0) { + if (avformat_find_stream_info(_format_ctx, nullptr) < 0) { cleanup(); return; } @@ -102,7 +102,7 @@ FfmpegAudioCursor(FfmpegAudio *src) : _audio_channels = codecpar->channels; AVCodec *pAudioCodec = avcodec_find_decoder(codecpar->codec_id); - if (pAudioCodec == 0) { + if (pAudioCodec == nullptr) { cleanup(); return; } @@ -120,9 +120,9 @@ FfmpegAudioCursor(FfmpegAudio *src) : avcodec_copy_context(_audio_ctx, codecpar); #endif - AVDictionary *opts = NULL; + AVDictionary *opts = nullptr; av_dict_set(&opts, "request_sample_fmt", "s16", 0); - if (avcodec_open2(_audio_ctx, pAudioCodec, NULL) < 0) { + if (avcodec_open2(_audio_ctx, pAudioCodec, nullptr) < 0) { cleanup(); return; } @@ -148,7 +148,7 @@ FfmpegAudioCursor(FfmpegAudio *src) : if (swr_init(_resample_ctx) != 0) { ffmpeg_cat.error() << "Failed to set up resample context.\n"; - _resample_ctx = NULL; + _resample_ctx = nullptr; } #else ffmpeg_cat.error() @@ -176,7 +176,7 @@ FfmpegAudioCursor(FfmpegAudio *src) : _buffer_alloc = new int16_t[_buffer_size + 64]; // Allocate enough space for 1024 samples per channel. - if ((_packet == 0)||(_buffer_alloc == 0)) { + if ((_packet == nullptr)||(_buffer_alloc == nullptr)) { cleanup(); return; } @@ -216,7 +216,7 @@ cleanup() { #else avcodec_free_frame(&_frame); #endif - _frame = NULL; + _frame = nullptr; } if (_packet) { @@ -227,14 +227,14 @@ cleanup() { av_free_packet(_packet); } delete _packet; - _packet = NULL; + _packet = nullptr; #endif } if (_buffer_alloc) { delete[] _buffer_alloc; - _buffer_alloc = 0; - _buffer = NULL; + _buffer_alloc = nullptr; + _buffer = nullptr; } if ((_audio_ctx)&&(_audio_ctx->codec)) { @@ -245,17 +245,17 @@ cleanup() { delete _audio_ctx; #endif } - _audio_ctx = NULL; + _audio_ctx = nullptr; if (_format_ctx) { _ffvfile.close(); - _format_ctx = NULL; + _format_ctx = nullptr; } #ifdef HAVE_SWRESAMPLE if (_resample_ctx) { swr_free(&_resample_ctx); - _resample_ctx = NULL; + _resample_ctx = nullptr; } #endif @@ -287,9 +287,9 @@ fetch_packet() { av_free_packet(_packet); #endif } - _packet->data = 0; + _packet->data = nullptr; _packet_size = 0; - _packet_data = 0; + _packet_data = nullptr; } /** @@ -307,7 +307,7 @@ reload_buffer() { // First, let's fill the codec's input buffer with as many packets as it'll // take: - int ret; + int ret = 0; while (_packet->data != nullptr) { ret = avcodec_send_packet(_audio_ctx, _packet); @@ -320,7 +320,7 @@ reload_buffer() { fetch_packet(); if (_packet->data == nullptr) { // fetch_packet() says we're out of packets. Let the codec know. - ret = avcodec_send_packet(_audio_ctx, NULL); + ret = avcodec_send_packet(_audio_ctx, nullptr); } } @@ -444,7 +444,7 @@ seek(double t) { double ts = _packet->dts * _audio_timebase; if (t > ts) { int skip = (int)((t-ts) * _audio_rate); - read_samples(skip, 0); + read_samples(skip, nullptr); } _last_seek = t; _samples_read = 0; @@ -469,7 +469,7 @@ read_samples(int n, int16_t *data) { int available = _buffer_tail - _buffer_head; int ncopy = (desired > available) ? available : desired; if (ncopy) { - if (data != 0) { + if (data != nullptr) { memcpy(data, _buffer + _buffer_head, ncopy * 2); data += ncopy; } diff --git a/panda/src/ffmpeg/ffmpegVideo.cxx b/panda/src/ffmpeg/ffmpegVideo.cxx index a16336260e..3cc7105fdd 100644 --- a/panda/src/ffmpeg/ffmpegVideo.cxx +++ b/panda/src/ffmpeg/ffmpegVideo.cxx @@ -56,11 +56,11 @@ FfmpegVideo:: PT(MovieVideoCursor) FfmpegVideo:: open() { PT(FfmpegVideoCursor) result = new FfmpegVideoCursor(this); - if (result->_format_ctx == 0) { + if (result->_format_ctx == nullptr) { ffmpeg_cat.error() << "Could not open " << _filename << "\n"; - return NULL; + return nullptr; } else { - return result.p(); + return result; } } diff --git a/panda/src/ffmpeg/ffmpegVideoCursor.cxx b/panda/src/ffmpeg/ffmpegVideoCursor.cxx index 21137b30e8..f8c2163b73 100644 --- a/panda/src/ffmpeg/ffmpegVideoCursor.cxx +++ b/panda/src/ffmpeg/ffmpegVideoCursor.cxx @@ -51,14 +51,14 @@ FfmpegVideoCursor() : _action_cvar(_lock), _thread_status(TS_stopped), _seek_frame(0), - _packet(NULL), - _format_ctx(NULL), - _video_ctx(NULL), - _convert_ctx(NULL), + _packet(nullptr), + _format_ctx(nullptr), + _video_ctx(nullptr), + _convert_ctx(nullptr), _pixel_format((int)AV_PIX_FMT_NONE), _video_index(-1), - _frame(NULL), - _frame_out(NULL), + _frame(nullptr), + _frame_out(nullptr), _eof_known(false) { } @@ -69,8 +69,8 @@ FfmpegVideoCursor() : */ void FfmpegVideoCursor:: init_from(FfmpegVideo *source) { - nassertv(_thread == NULL && _thread_status == TS_stopped); - nassertv(source != NULL); + nassertv(_thread == nullptr && _thread_status == TS_stopped); + nassertv(source != nullptr); _source = source; _filename = _source->get_filename(); @@ -89,7 +89,7 @@ init_from(FfmpegVideo *source) { _frame_out = avcodec_alloc_frame(); #endif - if ((_frame == 0)||(_frame_out == 0)) { + if ((_frame == nullptr)||(_frame_out == nullptr)) { cleanup(); return; } @@ -112,20 +112,32 @@ init_from(FfmpegVideo *source) { // Check if we got an alpha format. Please note that some video codecs // (eg. libvpx) change the pix_fmt after decoding the first frame, which is // why we didn't do this earlier. - const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(_video_ctx->pix_fmt); - if (desc && (desc->flags & AV_PIX_FMT_FLAG_ALPHA) != 0) { - _num_components = 4; - _pixel_format = (int)AV_PIX_FMT_BGRA; - } else { - _num_components = 3; - _pixel_format = (int)AV_PIX_FMT_BGR24; + switch (_video_ctx->pix_fmt) { + case AV_PIX_FMT_GRAY8: + _num_components = 1; + _pixel_format = (int)AV_PIX_FMT_GRAY8; + break; + case AV_PIX_FMT_Y400A: // aka AV_PIX_FMT_YA8 + _num_components = 2; + _pixel_format = (int)AV_PIX_FMT_Y400A; + break; + default: + const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(_video_ctx->pix_fmt); + if (desc && (desc->flags & AV_PIX_FMT_FLAG_ALPHA) != 0) { + _num_components = 4; + _pixel_format = (int)AV_PIX_FMT_BGRA; + } else { + _num_components = 3; + _pixel_format = (int)AV_PIX_FMT_BGR24; + } + break; } #ifdef HAVE_SWSCALE - nassertv(_convert_ctx == NULL); + nassertv(_convert_ctx == nullptr); _convert_ctx = sws_getContext(_size_x, _size_y, _video_ctx->pix_fmt, _size_x, _size_y, (AVPixelFormat)_pixel_format, - SWS_BILINEAR | SWS_PRINT_INFO, NULL, NULL, NULL); + SWS_BILINEAR | SWS_PRINT_INFO, nullptr, nullptr, nullptr); #endif // HAVE_SWSCALE #ifdef HAVE_THREADS @@ -144,13 +156,13 @@ FfmpegVideoCursor(FfmpegVideo *src) : _action_cvar(_lock), _thread_status(TS_stopped), _seek_frame(0), - _packet(NULL), - _format_ctx(NULL), - _video_ctx(NULL), - _convert_ctx(NULL), + _packet(nullptr), + _format_ctx(nullptr), + _video_ctx(nullptr), + _convert_ctx(nullptr), _video_index(-1), - _frame(NULL), - _frame_out(NULL), + _frame(nullptr), + _frame_out(nullptr), _eof_known(false) { init_from(src); @@ -247,7 +259,7 @@ start_thread() { if (_thread_status == TS_stopped && _max_readahead_frames > 0) { // Get a unique name for the thread's sync name. - ostringstream strm; + std::ostringstream strm; strm << (void *)this; _sync_name = strm.str(); @@ -256,7 +268,7 @@ start_thread() { _thread = new GenericThread(_filename.get_basename(), _sync_name, st_thread_main, this); if (!_thread->start(_thread_priority, true)) { // Couldn't start the thread. - _thread = NULL; + _thread = nullptr; _thread_status = TS_stopped; } } @@ -279,7 +291,7 @@ stop_thread() { _thread_status = TS_shutdown; } _action_cvar.notify(); - _thread = NULL; + _thread = nullptr; } // Now that we've released the lock, we can join the thread. @@ -325,7 +337,7 @@ set_time(double timestamp, int loop_count) { } // No point in trying to position before the first frame. - frame = max(frame, _initial_dts); + frame = std::max(frame, _initial_dts); if (ffmpeg_cat.is_spam() && frame != _current_frame) { ffmpeg_cat.spam() @@ -334,7 +346,7 @@ set_time(double timestamp, int loop_count) { } _current_frame = frame; - if (_current_frame_buffer != NULL) { + if (_current_frame_buffer != nullptr) { // If we've previously returned a frame, don't bother asking for a next // one if that frame is still valid. return (_current_frame >= _current_frame_buffer->_end_frame || @@ -353,8 +365,8 @@ fetch_buffer() { MutexHolder holder(_lock); // If there was an error at any point, just return NULL. - if (_format_ctx == (AVFormatContext *)NULL) { - return NULL; + if (_format_ctx == nullptr) { + return nullptr; } PT(FfmpegBuffer) frame; @@ -400,7 +412,7 @@ fetch_buffer() { } } } - if (frame == NULL || frame->_end_frame < _current_frame) { + if (frame == nullptr || frame->_end_frame < _current_frame) { // No frame available, or the frame is too old. Seek. if (_thread_status == TS_wait || _thread_status == TS_seek || _thread_status == TS_readahead) { _thread_status = TS_seek; @@ -410,16 +422,16 @@ fetch_buffer() { } } - if (frame != NULL) { + if (frame != nullptr) { bool too_old = (frame->_end_frame < _current_frame && !ffmpeg_show_seek_frames); bool too_new = frame->_begin_frame > _current_frame; if (too_old || too_new) { // The frame is too old or too new. Just recycle it. - frame = NULL; + frame = nullptr; } } - if (frame != NULL) { + if (frame != nullptr) { _current_frame_buffer = frame; if (ffmpeg_cat.is_debug()) { ffmpeg_cat.debug() @@ -434,7 +446,7 @@ fetch_buffer() { << " at frame " << _current_frame << ", returning NULL\n"; } } - return frame.p(); + return frame; } /** @@ -443,7 +455,7 @@ fetch_buffer() { PT(MovieVideoCursor::Buffer) FfmpegVideoCursor:: make_new_buffer() { PT(FfmpegBuffer) frame = new FfmpegBuffer(size_x() * size_y() * get_num_components(), _video_timebase); - return frame.p(); + return frame; } /** @@ -475,18 +487,18 @@ open_stream() { } } - nassertr(_format_ctx == NULL, false); + nassertr(_format_ctx == nullptr, false); _format_ctx = _ffvfile.get_format_context(); - nassertr(_format_ctx != NULL, false); + nassertr(_format_ctx != nullptr, false); - if (avformat_find_stream_info(_format_ctx, NULL) < 0) { + if (avformat_find_stream_info(_format_ctx, nullptr) < 0) { ffmpeg_cat.info() << "Couldn't find stream info\n"; close_stream(); return false; } - nassertr(_video_ctx == NULL, false); + nassertr(_video_ctx == nullptr, false); // As of libavformat version 57.41.100, AVStream.codec is deprecated in favor // of AVStream.codecpar. Fortunately, the two structures have @@ -522,7 +534,7 @@ open_stream() { _video_timebase = av_q2d(stream->time_base); _min_fseek = (int)(3.0 / _video_timebase); - AVCodec *pVideoCodec = NULL; + AVCodec *pVideoCodec = nullptr; if (ffmpeg_prefer_libvpx) { #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55, 0, 0) if (codecpar->codec_id == AV_CODEC_ID_VP9) { @@ -533,10 +545,10 @@ open_stream() { pVideoCodec = avcodec_find_decoder_by_name("libvpx"); } } - if (pVideoCodec == NULL) { + if (pVideoCodec == nullptr) { pVideoCodec = avcodec_find_decoder(codecpar->codec_id); } - if (pVideoCodec == NULL) { + if (pVideoCodec == nullptr) { ffmpeg_cat.info() << "Couldn't find codec\n"; close_stream(); @@ -558,7 +570,7 @@ open_stream() { avcodec_copy_context(_video_ctx, codecpar); #endif - if (avcodec_open2(_video_ctx, pVideoCodec, NULL) < 0) { + if (avcodec_open2(_video_ctx, pVideoCodec, nullptr) < 0) { ffmpeg_cat.info() << "Couldn't open codec\n"; close_stream(); @@ -591,10 +603,10 @@ close_stream() { delete _video_ctx; #endif } - _video_ctx = NULL; + _video_ctx = nullptr; _ffvfile.close(); - _format_ctx = NULL; + _format_ctx = nullptr; _video_index = -1; } @@ -610,21 +622,21 @@ cleanup() { ReMutexHolder av_holder(_av_lock); #ifdef HAVE_SWSCALE - if (_convert_ctx != NULL) { + if (_convert_ctx != nullptr) { sws_freeContext(_convert_ctx); } - _convert_ctx = NULL; + _convert_ctx = nullptr; #endif // HAVE_SWSCALE if (_frame) { av_free(_frame); - _frame = NULL; + _frame = nullptr; } if (_frame_out) { - _frame_out->data[0] = 0; + _frame_out->data[0] = nullptr; av_free(_frame_out); - _frame_out = NULL; + _frame_out = nullptr; } if (_packet) { @@ -635,7 +647,7 @@ cleanup() { av_free_packet(_packet); } delete _packet; - _packet = NULL; + _packet = nullptr; #endif } } @@ -711,7 +723,7 @@ do_poll() { if ((int)_readahead_frames.size() < _max_readahead_frames) { // Time to read the next frame. PT(FfmpegBuffer) frame = do_alloc_frame(); - nassertr(frame != NULL, false); + nassertr(frame != nullptr, false); _lock.release(); fetch_frame(-1); if (_frame_ready) { @@ -734,7 +746,7 @@ do_poll() { int seek_frame = _seek_frame; _thread_status = TS_seeking; PT(FfmpegBuffer) frame = do_alloc_frame(); - nassertr(frame != NULL, false); + nassertr(frame != nullptr, false); _lock.release(); advance_to_frame(seek_frame); if (_frame_ready) { @@ -819,7 +831,7 @@ do_fetch_packet(int default_frame) { av_free_packet(_packet); #endif } - _packet->data = 0; + _packet->data = nullptr; if (!_eof_known && default_frame != 0) { _eof_frame = _packet_frame; @@ -1146,7 +1158,7 @@ export_frame(FfmpegBuffer *buffer) { if (ffmpeg_global_lock) { ReMutexHolder av_holder(_av_lock); #ifdef HAVE_SWSCALE - nassertv(_convert_ctx != NULL && _frame != NULL && _frame_out != NULL); + nassertv(_convert_ctx != nullptr && _frame != nullptr && _frame_out != nullptr); sws_scale(_convert_ctx, _frame->data, _frame->linesize, 0, _size_y, _frame_out->data, _frame_out->linesize); #else img_convert((AVPicture *)_frame_out, (AVPixelFormat)_pixel_format, @@ -1154,7 +1166,7 @@ export_frame(FfmpegBuffer *buffer) { #endif } else { #ifdef HAVE_SWSCALE - nassertv(_convert_ctx != NULL && _frame != NULL && _frame_out != NULL); + nassertv(_convert_ctx != nullptr && _frame != nullptr && _frame_out != nullptr); sws_scale(_convert_ctx, _frame->data, _frame->linesize, 0, _size_y, _frame_out->data, _frame_out->linesize); #else img_convert((AVPicture *)_frame_out, (AVPixelFormat)_pixel_format, @@ -1190,7 +1202,7 @@ write_datagram(BamWriter *manager, Datagram &dg) { */ void FfmpegVideoCursor:: finalize(BamReader *) { - if (_source != (MovieVideo *)NULL) { + if (_source != nullptr) { FfmpegVideo *video; DCAST_INTO_V(video, _source); init_from(video); diff --git a/panda/src/ffmpeg/ffmpegVideoCursor.h b/panda/src/ffmpeg/ffmpegVideoCursor.h index b37637a0b0..58d63eb6ba 100644 --- a/panda/src/ffmpeg/ffmpegVideoCursor.h +++ b/panda/src/ffmpeg/ffmpegVideoCursor.h @@ -100,7 +100,7 @@ private: void cleanup(); Filename _filename; - string _sync_name; + std::string _sync_name; int _max_readahead_frames; ThreadPriority _thread_priority; PT(GenericThread) _thread; diff --git a/panda/src/ffmpeg/ffmpegVirtualFile.I b/panda/src/ffmpeg/ffmpegVirtualFile.I index c7a65bef36..c7e8e5d6c2 100644 --- a/panda/src/ffmpeg/ffmpegVirtualFile.I +++ b/panda/src/ffmpeg/ffmpegVirtualFile.I @@ -16,7 +16,7 @@ */ INLINE bool FfmpegVirtualFile:: is_open() const { - return (_format_context != NULL); + return (_format_context != nullptr); } /** diff --git a/panda/src/ffmpeg/ffmpegVirtualFile.cxx b/panda/src/ffmpeg/ffmpegVirtualFile.cxx index 8819db74bc..3fd88f640f 100644 --- a/panda/src/ffmpeg/ffmpegVirtualFile.cxx +++ b/panda/src/ffmpeg/ffmpegVirtualFile.cxx @@ -17,6 +17,9 @@ #include "ffmpegVirtualFile.h" #include "virtualFileSystem.h" +using std::streampos; +using std::streamsize; + extern "C" { #include "libavcodec/avcodec.h" #include "libavformat/avformat.h" @@ -31,9 +34,9 @@ extern "C" { */ FfmpegVirtualFile:: FfmpegVirtualFile() : - _io_context(NULL), - _format_context(NULL), - _in(NULL), + _io_context(nullptr), + _format_context(nullptr), + _in(nullptr), _owns_in(false), _buffer_size(ffmpeg_read_buffer_size) { @@ -47,22 +50,6 @@ FfmpegVirtualFile:: close(); } -/** - * These objects are not meant to be copied. - */ -FfmpegVirtualFile:: -FfmpegVirtualFile(const FfmpegVirtualFile ©) { - nassertv(false); -} - -/** - * These objects are not meant to be copied. - */ -void FfmpegVirtualFile:: -operator = (const FfmpegVirtualFile ©) { - nassertv(false); -} - /** * Opens the movie file via Panda's VFS. Returns true on success, false on * failure. If successful, use get_format_context() to get the open file @@ -81,12 +68,12 @@ open_vfs(const Filename &filename) { Filename fname = filename; fname.set_binary(); PT(VirtualFile) vfile = vfs->get_file(fname); - if (vfile == NULL) { + if (vfile == nullptr) { return false; } _in = vfile->open_read_file(true); - if (_in == NULL) { + if (_in == nullptr) { return false; } @@ -100,14 +87,14 @@ open_vfs(const Filename &filename) { // pointer. unsigned char *buffer = (unsigned char*) av_malloc(_buffer_size); _io_context = avio_alloc_context(buffer, _buffer_size, 0, (void*) this, - &read_packet, 0, &seek); + &read_packet, nullptr, &seek); _format_context = avformat_alloc_context(); _format_context->pb = _io_context; // Now we can open the stream. int result = - avformat_open_input(&_format_context, "", NULL, NULL); + avformat_open_input(&_format_context, "", nullptr, nullptr); if (result < 0) { close(); return false; @@ -148,14 +135,14 @@ open_subfile(const SubfileInfo &info) { // pointer. unsigned char *buffer = (unsigned char*) av_malloc(_buffer_size); _io_context = avio_alloc_context(buffer, _buffer_size, 0, (void*) this, - &read_packet, 0, &seek); + &read_packet, nullptr, &seek); _format_context = avformat_alloc_context(); _format_context->pb = _io_context; // Now we can open the stream. int result = - avformat_open_input(&_format_context, fname.c_str(), NULL, NULL); + avformat_open_input(&_format_context, fname.c_str(), nullptr, nullptr); if (result < 0) { close(); return false; @@ -170,24 +157,24 @@ open_subfile(const SubfileInfo &info) { */ void FfmpegVirtualFile:: close() { - if (_format_context != NULL) { + if (_format_context != nullptr) { avformat_close_input(&_format_context); } - if (_io_context != NULL) { - if (_io_context->buffer != NULL) { + if (_io_context != nullptr) { + if (_io_context->buffer != nullptr) { av_free(_io_context->buffer); } av_free(_io_context); - _io_context = NULL; + _io_context = nullptr; } if (_owns_in) { - nassertv(_in != NULL); + nassertv(_in != nullptr); VirtualFileSystem::close_read_file(_in); _owns_in = false; } - _in = NULL; + _in = nullptr; } /** @@ -218,14 +205,14 @@ int FfmpegVirtualFile:: read_packet(void *opaque, uint8_t *buf, int size) { streampos ssize = (streampos)size; FfmpegVirtualFile *self = (FfmpegVirtualFile *) opaque; - istream *in = self->_in; + std::istream *in = self->_in; // Since we may be simulating a subset of the opened stream, don't allow it // to read past the "end". streampos remaining = self->_start + (streampos)self->_size - in->tellg(); if (remaining < ssize) { if (remaining <= 0) { - return 0; + return AVERROR_EOF; } ssize = remaining; @@ -244,21 +231,21 @@ read_packet(void *opaque, uint8_t *buf, int size) { int64_t FfmpegVirtualFile:: seek(void *opaque, int64_t pos, int whence) { FfmpegVirtualFile *self = (FfmpegVirtualFile *) opaque; - istream *in = self->_in; + std::istream *in = self->_in; switch (whence) { case SEEK_SET: - in->seekg(self->_start + (streampos)pos, ios::beg); + in->seekg(self->_start + (streampos)pos, std::ios::beg); break; case SEEK_CUR: - in->seekg(pos, ios::cur); + in->seekg(pos, std::ios::cur); break; case SEEK_END: // For seeks relative to the end, we actually compute the end based on // _start + _size, and then use ios::beg. - in->seekg(self->_start + (streampos)self->_size + (streampos)pos, ios::beg); + in->seekg(self->_start + (streampos)self->_size + (streampos)pos, std::ios::beg); break; case AVSEEK_SIZE: diff --git a/panda/src/ffmpeg/ffmpegVirtualFile.h b/panda/src/ffmpeg/ffmpegVirtualFile.h index 746fec67a0..3e7bd4f796 100644 --- a/panda/src/ffmpeg/ffmpegVirtualFile.h +++ b/panda/src/ffmpeg/ffmpegVirtualFile.h @@ -34,12 +34,11 @@ struct AVFormatContext; class EXPCL_FFMPEG FfmpegVirtualFile { public: FfmpegVirtualFile(); + FfmpegVirtualFile(const FfmpegVirtualFile ©) = delete; ~FfmpegVirtualFile(); -private: - FfmpegVirtualFile(const FfmpegVirtualFile ©); - void operator = (const FfmpegVirtualFile ©); -public: + FfmpegVirtualFile &operator = (const FfmpegVirtualFile ©) = delete; + bool open_vfs(const Filename &filename); bool open_subfile(const SubfileInfo &info); void close(); @@ -59,9 +58,9 @@ private: private: AVIOContext *_io_context; AVFormatContext *_format_context; - streampos _start; - streamsize _size; - istream *_in; + std::streampos _start; + std::streamsize _size; + std::istream *_in; pifstream _file_in; bool _owns_in; int _buffer_size; diff --git a/panda/src/framework/config_framework.cxx b/panda/src/framework/config_framework.cxx index 8746d5bff0..4ddc4b553a 100644 --- a/panda/src/framework/config_framework.cxx +++ b/panda/src/framework/config_framework.cxx @@ -16,12 +16,6 @@ #include "dconfig.h" #include "windowFramework.h" -// By including checkPandaVersion.h, we guarantee that runtime attempts to -// load libframework.so.dll will fail if they inadvertently link with the -// wrong version of libdtool.so.dll. - -#include "checkPandaVersion.h" - #if !defined(CPPPARSER) && !defined(BUILDING_FRAMEWORK) #error Buildsystem error: BUILDING_FRAMEWORK not defined #endif diff --git a/panda/src/framework/pandaFramework.I b/panda/src/framework/pandaFramework.I index 552d5bc2f2..24e6bc3644 100644 --- a/panda/src/framework/pandaFramework.I +++ b/panda/src/framework/pandaFramework.I @@ -17,7 +17,7 @@ */ INLINE GraphicsEngine *PandaFramework:: get_graphics_engine() { - if (_engine == (GraphicsEngine *)NULL) { + if (_engine == nullptr) { _engine = GraphicsEngine::get_global_ptr(); PT(GenericAsyncTask) task = new GenericAsyncTask("igloop", task_igloop, this); task->set_sort(50); @@ -57,7 +57,7 @@ get_task_mgr() { * Specifies the title that is set for all subsequently created windows. */ INLINE void PandaFramework:: -set_window_title(const string &title) { +set_window_title(const std::string &title) { _window_title = title; } @@ -74,7 +74,7 @@ get_num_windows() const { */ INLINE WindowFramework *PandaFramework:: get_window(int n) const { - nassertr(n >= 0 && n < (int)_windows.size(), NULL); + nassertr(n >= 0 && n < (int)_windows.size(), nullptr); return _windows[n]; } diff --git a/panda/src/framework/pandaFramework.cxx b/panda/src/framework/pandaFramework.cxx index 30968e70b3..4dfbaee572 100644 --- a/panda/src/framework/pandaFramework.cxx +++ b/panda/src/framework/pandaFramework.cxx @@ -37,6 +37,8 @@ #endif #endif +using std::string; + LoaderOptions PandaFramework::_loader_options; /** @@ -50,7 +52,7 @@ PandaFramework() : _is_open = false; _made_default_pipe = false; _window_title = string(); - _engine = (GraphicsEngine *)NULL; + _engine = nullptr; _start_time = 0.0; _frame_count = 0; _wireframe_enabled = false; @@ -91,7 +93,7 @@ open_framework(int &argc, char **&argv) { // If we're statically linking, we need to explicitly link with at least one // of the available renderers. #if defined(HAVE_GL) - extern EXPCL_PANDAGL void init_libpandagl(); + extern void init_libpandagl(); init_libpandagl(); #elif defined(HAVE_DX9) extern EXPCL_PANDADX void init_libpandadx9(); @@ -172,9 +174,9 @@ close_framework() { close_all_windows(); // Also close down any other windows that might have been opened. - if (_engine != (GraphicsEngine *)NULL) { + if (_engine != nullptr) { _engine->remove_all_windows(); - _engine = NULL; + _engine = nullptr; } _event_handler.remove_all_hooks(); @@ -191,7 +193,7 @@ close_framework() { _default_keys_enabled = false; _exit_flag = false; - _recorder = NULL; + _recorder = nullptr; Thread::prepare_for_exit(); } @@ -208,7 +210,7 @@ close_framework() { */ GraphicsPipe *PandaFramework:: get_default_pipe() { - nassertr(_is_open, NULL); + nassertr(_is_open, nullptr); if (!_made_default_pipe) { make_default_pipe(); _made_default_pipe = true; @@ -240,7 +242,7 @@ get_mouse(GraphicsOutput *window) { mouse = data_root.attach_new_node(mouse_node); RecorderController *recorder = get_recorder(); - if (recorder != (RecorderController *)NULL) { + if (recorder != nullptr) { // If we're in recording or playback mode, associate a recorder. MouseRecorder *mouse_recorder = new MouseRecorder("mouse"); mouse = mouse.attach_new_node(mouse_recorder); @@ -324,13 +326,13 @@ get_default_window_props(WindowProperties &props) { WindowFramework *PandaFramework:: open_window() { GraphicsPipe *pipe = get_default_pipe(); - if (pipe == (GraphicsPipe *)NULL) { + if (pipe == nullptr) { // Can't get a pipe. - return NULL; + return nullptr; } - WindowFramework *wf = open_window(pipe, NULL); - if (wf == (WindowFramework *)NULL) { + WindowFramework *wf = open_window(pipe, nullptr); + if (wf == nullptr) { // Ok, the default graphics pipe failed; try a little harder. GraphicsPipeSelection *selection = GraphicsPipeSelection::get_global_ptr(); selection->load_aux_modules(); @@ -340,9 +342,9 @@ open_window() { TypeHandle pipe_type = selection->get_pipe_type(i); if (pipe_type != _default_pipe->get_type()) { PT(GraphicsPipe) new_pipe = selection->make_pipe(pipe_type); - if (new_pipe != (GraphicsPipe *)NULL) { - wf = open_window(new_pipe, NULL); - if (wf != (WindowFramework *)NULL) { + if (new_pipe != nullptr) { + wf = open_window(new_pipe, nullptr); + if (wf != nullptr) { // Here's the winner! _default_pipe = new_pipe; return wf; @@ -364,7 +366,7 @@ open_window() { */ WindowFramework *PandaFramework:: open_window(GraphicsPipe *pipe, GraphicsStateGuardian *gsg) { - nassertr(_is_open, NULL); + nassertr(_is_open, nullptr); WindowProperties props; get_default_window_props(props); @@ -387,15 +389,15 @@ open_window(GraphicsPipe *pipe, GraphicsStateGuardian *gsg) { WindowFramework *PandaFramework:: open_window(const WindowProperties &props, int flags, GraphicsPipe *pipe, GraphicsStateGuardian *gsg) { - if (pipe == (GraphicsPipe *)NULL) { + if (pipe == nullptr) { pipe = get_default_pipe(); - if (pipe == (GraphicsPipe *)NULL) { + if (pipe == nullptr) { // Can't get a pipe. - return NULL; + return nullptr; } } - nassertr(_is_open, NULL); + nassertr(_is_open, nullptr); PT(WindowFramework) wf = make_window_framework(); wf->set_wireframe(get_wireframe()); wf->set_texture(get_texture()); @@ -407,18 +409,18 @@ open_window(const WindowProperties &props, int flags, GraphicsOutput *win = wf->open_window(props, flags, get_graphics_engine(), pipe, gsg); _engine->open_windows(); - if (win != (GraphicsOutput *)NULL && !win->is_valid()) { + if (win != nullptr && !win->is_valid()) { // The window won't open. _engine->remove_window(win); wf->close_window(); - win = NULL; + win = nullptr; } - if (win == (GraphicsOutput *)NULL) { + if (win == nullptr) { // Oops, couldn't make a window or buffer. framework_cat.error() << "Unable to create window.\n"; - return NULL; + return nullptr; } _windows.push_back(wf); @@ -467,7 +469,7 @@ close_window(int n) { WindowFramework *wf = _windows[n]; GraphicsOutput *win = wf->get_graphics_output(); - if (win != (GraphicsOutput *)NULL) { + if (win != nullptr) { _engine->remove_window(win); } @@ -485,7 +487,7 @@ close_all_windows() { WindowFramework *wf = (*wi); GraphicsOutput *win = wf->get_graphics_output(); - if (win != (GraphicsOutput *)NULL) { + if (win != nullptr) { _engine->remove_window(win); } @@ -535,7 +537,7 @@ get_models() { * Reports the currently measured average frame rate to the indicated ostream. */ void PandaFramework:: -report_frame_rate(ostream &out) const { +report_frame_rate(std::ostream &out) const { double now = ClockObject::get_global_clock()->get_frame_time(); double delta = now - _start_time; @@ -780,7 +782,7 @@ make_default_pipe() { _default_pipe = selection->make_default_pipe(); - if (_default_pipe == (GraphicsPipe*)NULL) { + if (_default_pipe == nullptr) { nout << "No graphics pipe is available!\n" << "Your Config.prc file must name at least one valid panda display\n" << "library via load-display or aux-display.\n"; @@ -1175,10 +1177,10 @@ event_arrow_right(const Event *, void *data) { void PandaFramework:: event_S(const Event *, void *) { #ifdef DO_PSTATS - nout << "Connecting to stats host" << endl; + nout << "Connecting to stats host" << std::endl; PStatClient::connect(); #else - nout << "Stats host not supported." << endl; + nout << "Stats host not supported." << std::endl; #endif } @@ -1219,7 +1221,7 @@ event_f9(const Event *event, void *data) { self->_screenshot_text.set_scale(0.06); self->_screenshot_text.set_pos(0.0, 0.0, -0.7); self->_screenshot_text.reparent_to(wf->get_aspect_2d()); - cout << "Screenshot saved: " + output_text + "\n"; + std::cout << "Screenshot saved: " + output_text + "\n"; // Set a do-later to remove the text in 3 seconds. self->_task_mgr.remove(self->_task_mgr.find_tasks("clear_text")); @@ -1273,7 +1275,7 @@ event_question(const Event *event, void *data) { } else { // Build up a string to display. - ostringstream help; + std::ostringstream help; KeyDefinitions::const_iterator ki; for (ki = self->_key_definitions.begin(); ki != self->_key_definitions.end(); @@ -1294,7 +1296,7 @@ event_question(const Event *event, void *data) { LVecBase4 frame = text_node->get_frame_actual(); PN_stdfloat height = frame[3] - frame[2]; - PN_stdfloat scale = min(0.06, 1.8 / height); + PN_stdfloat scale = std::min(0.06, 1.8 / height); self->_help_text.set_scale(scale); PN_stdfloat pos_scale = scale / -2.0; @@ -1412,7 +1414,7 @@ AsyncTask::DoneStatus PandaFramework:: task_record_frame(GenericAsyncTask *task, void *data) { PandaFramework *self = (PandaFramework *)data; - if (self->_recorder != (RecorderController *)NULL) { + if (self->_recorder != nullptr) { self->_recorder->record_frame(); } @@ -1427,7 +1429,7 @@ AsyncTask::DoneStatus PandaFramework:: task_play_frame(GenericAsyncTask *task, void *data) { PandaFramework *self = (PandaFramework *)data; - if (self->_recorder != (RecorderController *)NULL) { + if (self->_recorder != nullptr) { self->_recorder->play_frame(); } diff --git a/panda/src/framework/pandaFramework.h b/panda/src/framework/pandaFramework.h index 46df0f3bdd..ef570a6c96 100644 --- a/panda/src/framework/pandaFramework.h +++ b/panda/src/framework/pandaFramework.h @@ -51,20 +51,20 @@ public: NodePath get_mouse(GraphicsOutput *window); void remove_mouse(const GraphicsOutput *window); - void define_key(const string &event_name, - const string &description, + void define_key(const std::string &event_name, + const std::string &description, EventHandler::EventCallbackFunction *function, void *data); - INLINE void set_window_title(const string &title); + INLINE void set_window_title(const std::string &title); virtual void get_default_window_props(WindowProperties &props); WindowFramework *open_window(); WindowFramework *open_window(GraphicsPipe *pipe, - GraphicsStateGuardian *gsg = NULL); + GraphicsStateGuardian *gsg = nullptr); WindowFramework *open_window(const WindowProperties &props, int flags, - GraphicsPipe *pipe = NULL, - GraphicsStateGuardian *gsg = NULL); + GraphicsPipe *pipe = nullptr, + GraphicsStateGuardian *gsg = nullptr); INLINE int get_num_windows() const; INLINE WindowFramework *get_window(int n) const; @@ -77,7 +77,7 @@ public: NodePath &get_models(); - void report_frame_rate(ostream &out) const; + void report_frame_rate(std::ostream &out) const; void reset_frame_rate(); void set_wireframe(bool enable); @@ -163,7 +163,7 @@ private: bool _is_open; bool _made_default_pipe; - string _window_title; + std::string _window_title; PT(GraphicsPipe) _default_pipe; PT(GraphicsEngine) _engine; @@ -200,8 +200,8 @@ private: class KeyDefinition { public: - string _event_name; - string _description; + std::string _event_name; + std::string _description; }; typedef pvector KeyDefinitions; KeyDefinitions _key_definitions; diff --git a/panda/src/framework/windowFramework.I b/panda/src/framework/windowFramework.I index 6cd1da7d64..5fa4caafe8 100644 --- a/panda/src/framework/windowFramework.I +++ b/panda/src/framework/windowFramework.I @@ -25,11 +25,11 @@ get_panda_framework() const { */ INLINE GraphicsWindow *WindowFramework:: get_graphics_window() const { - if (_window != (GraphicsOutput *)NULL && + if (_window != nullptr && _window->is_of_type(GraphicsWindow::get_class_type())) { return DCAST(GraphicsWindow, _window); } - return NULL; + return nullptr; } /** @@ -55,7 +55,7 @@ get_num_cameras() const { */ INLINE Camera *WindowFramework:: get_camera(int n) const { - nassertr(n >= 0 && n < (int)_cameras.size(), NULL); + nassertr(n >= 0 && n < (int)_cameras.size(), nullptr); return _cameras[n]; } diff --git a/panda/src/framework/windowFramework.cxx b/panda/src/framework/windowFramework.cxx index 756a1b61f1..db49ee97e8 100644 --- a/panda/src/framework/windowFramework.cxx +++ b/panda/src/framework/windowFramework.cxx @@ -62,10 +62,14 @@ // shuttle_controls.bam_src.c. #include "shuttle_controls.bam_src.c" +using std::istringstream; +using std::ostringstream; +using std::string; + // This number is chosen arbitrarily to override any settings in model files. static const int override_priority = 100; -PT(TextFont) WindowFramework::_shuttle_controls_font = NULL; +PT(TextFont) WindowFramework::_shuttle_controls_font = nullptr; TypeHandle WindowFramework::_type_handle; /** @@ -134,7 +138,7 @@ GraphicsOutput *WindowFramework:: open_window(const WindowProperties &props, int flags, GraphicsEngine *engine, GraphicsPipe *pipe, GraphicsStateGuardian *gsg, const FrameBufferProperties &fbprops) { - nassertr(_window == (GraphicsOutput *)NULL, _window); + nassertr(_window == nullptr, _window); static int next_window_index = 1; ostringstream stream; @@ -142,11 +146,11 @@ open_window(const WindowProperties &props, int flags, GraphicsEngine *engine, next_window_index++; string name = stream.str(); - _window = 0; + _window = nullptr; GraphicsOutput *winout = engine->make_output(pipe, name, 0, fbprops, - props, flags, gsg, NULL); - if (winout != (GraphicsOutput *)NULL) { + props, flags, gsg, nullptr); + if (winout != nullptr) { _window = winout; // _window->request_properties(props); @@ -203,13 +207,13 @@ close_window() { _lighting_enabled = false; _perpixel_enabled = false; - if (_frame_rate_meter != (FrameRateMeter *)NULL) { + if (_frame_rate_meter != nullptr) { _frame_rate_meter->clear_window(); - _frame_rate_meter = (FrameRateMeter *)NULL; + _frame_rate_meter = nullptr; } - if (_scene_graph_analyzer_meter != (SceneGraphAnalyzerMeter *)NULL) { + if (_scene_graph_analyzer_meter != nullptr) { _scene_graph_analyzer_meter->clear_window(); - _scene_graph_analyzer_meter = (SceneGraphAnalyzerMeter *)NULL; + _scene_graph_analyzer_meter = nullptr; } } @@ -455,13 +459,13 @@ setup_trackball() { */ void WindowFramework:: center_trackball(const NodePath &object) { - if (_trackball == (Trackball *)NULL) { + if (_trackball == nullptr) { return; } PT(BoundingVolume) volume = object.get_bounds(); // We expect at least a geometric bounding volume around the world. - nassertv(volume != (BoundingVolume *)NULL); + nassertv(volume != nullptr); nassertv(volume->is_of_type(GeometricBoundingVolume::get_class_type())); CPT(GeometricBoundingVolume) gbv = DCAST(GeometricBoundingVolume, volume); @@ -502,27 +506,27 @@ center_trackball(const NodePath &object) { // Choose a suitable distance to view the whole volume in our frame. This // is based on the camera lens in use. Determine the lens based on the // first camera; this will be the default camera. - Lens *lens = (Lens *)NULL; + Lens *lens = nullptr; if (!_cameras.empty()) { Cameras::const_iterator ci; for (ci = _cameras.begin(); - ci != _cameras.end() && lens == (Lens *)NULL; + ci != _cameras.end() && lens == nullptr; ++ci) { lens = (*ci)->get_lens(); } } - if (lens != (Lens *)NULL) { + if (lens != nullptr) { LVecBase2 fov = lens->get_fov(); - distance = radius / ctan(deg_2_rad(min(fov[0], fov[1]) / 2.0f)); + distance = radius / ctan(deg_2_rad(std::min(fov[0], fov[1]) / 2.0f)); // Ensure the far plane is far enough back to see the entire object. PN_stdfloat ideal_far_plane = distance + radius * 1.5; - lens->set_far(max(lens->get_default_far(), ideal_far_plane)); + lens->set_far(std::max(lens->get_default_far(), ideal_far_plane)); // And that the near plane is far enough forward. PN_stdfloat ideal_near_plane = distance - radius; - lens->set_near(min(lens->get_default_near(), ideal_near_plane)); + lens->set_near(std::min(lens->get_default_near(), ideal_near_plane)); } _trackball->set_origin(center); @@ -544,7 +548,7 @@ bool WindowFramework:: load_models(const NodePath &parent, int argc, char *argv[], int first_arg) { pvector files; - for (int i = first_arg; i < argc && argv[i] != (char *)NULL; i++) { + for (int i = first_arg; i < argc && argv[i] != nullptr; i++) { files.push_back(Filename::from_os_specific(argv[i])); } @@ -596,17 +600,17 @@ load_model(const NodePath &parent, Filename filename) { } #endif // HAVE_ZLIB TexturePool *texture_pool = TexturePool::get_global_ptr(); - LoaderFileType *model_type = NULL; + LoaderFileType *model_type = nullptr; if (!extension.empty()) { LoaderFileTypeRegistry *reg = LoaderFileTypeRegistry::get_global_ptr(); model_type = reg->get_type_from_extension(extension); - if (model_type == (LoaderFileType *)NULL) { + if (model_type == nullptr) { // The extension isn't a known model file type; is it a known image file // extension? TexturePool *texture_pool = TexturePool::get_global_ptr(); - if (texture_pool->get_texture_type(extension) != NULL) { + if (texture_pool->get_texture_type(extension) != nullptr) { // It is a known image file extension. is_image = true; } @@ -630,12 +634,12 @@ load_model(const NodePath &parent, Filename filename) { // It failed to load. Is it because the extension isn't recognised? If // so, then we just got done printing out the known scene types, and we // should also print out the supported texture types. - if (node == (PandaNode *)NULL && !is_image && model_type == NULL) { + if (node == nullptr && !is_image && model_type == nullptr) { texture_pool->write_texture_types(nout, 2); } } - if (node == (PandaNode *)NULL) { + if (node == nullptr) { nout << "Unable to load " << filename << "\n"; return NodePath::not_found(); } @@ -822,7 +826,7 @@ adjust_dimensions() { Cameras::iterator ci; for (ci = _cameras.begin(); ci != _cameras.end(); ++ci) { Lens *lens = (*ci)->get_lens(); - if (lens != (Lens *)NULL) { + if (lens != nullptr) { if (y_size != 0) { lens->set_film_size(x_size, y_size); } else { @@ -840,7 +844,7 @@ adjust_dimensions() { */ WindowFramework *WindowFramework:: split_window(SplitType split_type) { - DisplayRegion *new_region = NULL; + DisplayRegion *new_region = nullptr; if (split_type == ST_default) { // Choose either horizontal or vertical according to the largest @@ -860,7 +864,7 @@ split_window(SplitType split_type) { if (split_type == ST_vertical) { _display_region_3d->set_dimensions(left, right, bottom, (top + bottom) / 2.0f); - if (_display_region_2d != (DisplayRegion *)NULL) { + if (_display_region_2d != nullptr) { _display_region_2d->set_dimensions(left, right, bottom, (top + bottom) / 2.0f); } @@ -868,7 +872,7 @@ split_window(SplitType split_type) { } else { _display_region_3d->set_dimensions(left, (left + right) / 2.0f, bottom, top); - if (_display_region_2d != (DisplayRegion *)NULL) { + if (_display_region_2d != nullptr) { _display_region_2d->set_dimensions(left, (left + right) / 2.0f, bottom, top); } @@ -1044,7 +1048,7 @@ void WindowFramework:: set_background_type(WindowFramework::BackgroundType type) { _background_type = type; - if (_display_region_3d == (DisplayRegion *)NULL) { + if (_display_region_3d == nullptr) { return; } @@ -1101,7 +1105,7 @@ set_background_type(WindowFramework::BackgroundType type) { */ TextFont *WindowFramework:: get_shuttle_controls_font() { - if (_shuttle_controls_font == (TextFont *)NULL) { + if (_shuttle_controls_font == nullptr) { PT(TextFont) font; string shuttle_controls_string((const char *)shuttle_controls, shuttle_controls_len); @@ -1109,7 +1113,7 @@ get_shuttle_controls_font() { BamFile bam_file; if (bam_file.open_read(in, "shuttle_controls font stream")) { PT(PandaNode) node = bam_file.read_node(); - if (node != (PandaNode *)NULL) { + if (node != nullptr) { _shuttle_controls_font = new StaticTextFont(node); } } @@ -1182,8 +1186,8 @@ setup_lights() { PT(PandaNode) WindowFramework:: load_image_as_model(const Filename &filename) { PT(Texture) tex = TexturePool::load_texture(filename); - if (tex == NULL) { - return NULL; + if (tex == nullptr) { + return nullptr; } // Yes, it is an image file; make a texture out of it. @@ -1330,7 +1334,7 @@ load_image_as_model(const Filename &filename) { card_node->add_geom(geom); - return card_node.p(); + return card_node; } /** @@ -1365,7 +1369,7 @@ create_anim_controls() { } AnimControl *control = _anim_controls.get_anim(_anim_index); - nassertv(control != (AnimControl *)NULL); + nassertv(control != nullptr); if (control->get_num_frames() <= 1) { // Don't show the controls when the animation has only 0 or 1 frames. @@ -1438,7 +1442,7 @@ destroy_anim_controls() { _anim_controls_group.remove_node(); _panda_framework->get_event_handler().remove_hooks_with((void *)this); - if (_update_anim_controls_task != NULL) { + if (_update_anim_controls_task != nullptr) { _panda_framework->get_task_mgr().remove(_update_anim_controls_task); _update_anim_controls_task.clear(); } @@ -1451,9 +1455,9 @@ destroy_anim_controls() { void WindowFramework:: update_anim_controls() { AnimControl *control = _anim_controls.get_anim(_anim_index); - nassertv(control != (AnimControl *)NULL); + nassertv(control != nullptr); - if (_anim_slider != NULL) { + if (_anim_slider != nullptr) { if (_anim_slider->is_button_down()) { control->pose((int)(_anim_slider->get_value() + 0.5)); } else { @@ -1461,7 +1465,7 @@ update_anim_controls() { } } - if (_frame_number != NULL) { + if (_frame_number != nullptr) { _frame_number->set_text(format_string(control->get_frame())); } @@ -1494,7 +1498,7 @@ setup_shuttle_button(const string &label, int index, style.set_type(PGFrameStyle::T_bevel_out); button->set_frame_style(PGButton::S_rollover, style); - if (get_shuttle_controls_font() != (TextFont *)NULL) { + if (get_shuttle_controls_font() != nullptr) { PT(TextNode) tn = new TextNode("label"); tn->set_align(TextNode::A_center); tn->set_font(get_shuttle_controls_font()); @@ -1521,7 +1525,7 @@ setup_shuttle_button(const string &label, int index, void WindowFramework:: back_button() { AnimControl *control = _anim_controls.get_anim(_anim_index); - nassertv(control != (AnimControl *)NULL); + nassertv(control != nullptr); control->pose(control->get_frame() - 1); } @@ -1531,7 +1535,7 @@ back_button() { void WindowFramework:: pause_button() { AnimControl *control = _anim_controls.get_anim(_anim_index); - nassertv(control != (AnimControl *)NULL); + nassertv(control != nullptr); control->stop(); } @@ -1541,7 +1545,7 @@ pause_button() { void WindowFramework:: play_button() { AnimControl *control = _anim_controls.get_anim(_anim_index); - nassertv(control != (AnimControl *)NULL); + nassertv(control != nullptr); control->loop(false); } @@ -1551,7 +1555,7 @@ play_button() { void WindowFramework:: forward_button() { AnimControl *control = _anim_controls.get_anim(_anim_index); - nassertv(control != (AnimControl *)NULL); + nassertv(control != nullptr); control->pose(control->get_frame() + 1); } diff --git a/panda/src/framework/windowFramework.h b/panda/src/framework/windowFramework.h index c74310e197..b6e93041eb 100644 --- a/panda/src/framework/windowFramework.h +++ b/panda/src/framework/windowFramework.h @@ -59,7 +59,7 @@ public: protected: GraphicsOutput *open_window(const WindowProperties &props, int flags, GraphicsEngine *engine, GraphicsPipe *pipe, - GraphicsStateGuardian *gsg = NULL, + GraphicsStateGuardian *gsg = nullptr, const FrameBufferProperties &fbprops = FrameBufferProperties::get_default()); void close_window(); @@ -147,7 +147,7 @@ private: void destroy_anim_controls(); void update_anim_controls(); - void setup_shuttle_button(const string &label, int index, + void setup_shuttle_button(const std::string &label, int index, EventHandler::EventCallbackFunction *func); void back_button(); void pause_button(); diff --git a/panda/src/glgsg/config_glgsg.cxx b/panda/src/glgsg/config_glgsg.cxx index 6e60169acc..1c7ddcbfd5 100644 --- a/panda/src/glgsg/config_glgsg.cxx +++ b/panda/src/glgsg/config_glgsg.cxx @@ -16,8 +16,8 @@ #include "dconfig.h" -#if !defined(CPPPARSER) && !defined(BUILDING_PANDAGL) - #error Buildsystem error: BUILDING_PANDAGL not defined +#if !defined(CPPPARSER) && !defined(BUILDING_PANDA_GLGSG) + #error Buildsystem error: BUILDING_PANDA_GLGSG not defined #endif ConfigureDef(config_glgsg); diff --git a/panda/src/glgsg/config_glgsg.h b/panda/src/glgsg/config_glgsg.h index 87220333ed..e2beef8e52 100644 --- a/panda/src/glgsg/config_glgsg.h +++ b/panda/src/glgsg/config_glgsg.h @@ -18,9 +18,9 @@ #include "notifyCategoryProxy.h" #include "dconfig.h" -ConfigureDecl(config_glgsg, EXPCL_PANDAGL, EXPTP_PANDAGL); -NotifyCategoryDecl(glgsg, EXPCL_PANDAGL, EXPTP_PANDAGL); +ConfigureDecl(config_glgsg, EXPCL_PANDA_GLGSG, EXPTP_PANDA_GLGSG); +NotifyCategoryDecl(glgsg, EXPCL_PANDA_GLGSG, EXPTP_PANDA_GLGSG); -extern EXPCL_PANDAGL void init_libglgsg(); +extern EXPCL_PANDA_GLGSG void init_libglgsg(); #endif diff --git a/panda/src/glgsg/glgsg.h b/panda/src/glgsg/glgsg.h index 713ce9e862..b225466ab0 100644 --- a/panda/src/glgsg/glgsg.h +++ b/panda/src/glgsg/glgsg.h @@ -37,8 +37,8 @@ #define GLSYSTEM_NAME "OpenGL" #define CONFIGOBJ config_glgsg #define GLCAT glgsg_cat -#define EXPCL_GL EXPCL_PANDAGL -#define EXPTP_GL EXPTP_PANDAGL +#define EXPCL_GL EXPCL_PANDA_GLGSG +#define EXPTP_GL EXPTP_PANDA_GLGSG #if MIN_GL_VERSION_MAJOR > 1 || (MIN_GL_VERSION_MAJOR == 1 && MIN_GL_VERSION_MINOR >= 2) #define EXPECT_GL_VERSION_1_2 diff --git a/panda/src/glstuff/glCgShaderContext_src.cxx b/panda/src/glstuff/glCgShaderContext_src.cxx index 9f6e242968..c7ba6ad3e7 100644 --- a/panda/src/glstuff/glCgShaderContext_src.cxx +++ b/panda/src/glstuff/glCgShaderContext_src.cxx @@ -195,7 +195,7 @@ CLP(CgShaderContext)(CLP(GraphicsStateGuardian) *glgsg, Shader *s) : ShaderConte // used, but it instead uses specially named variables. A bit of // guesswork is involved here; Cg seems to mostly use the semantics as // attribute names in GLSL, with a few exceptions. - const char *attribname = NULL; + const char *attribname = nullptr; switch (res) { case CG_POSITION0: attribname = "cg_Vertex"; @@ -436,42 +436,43 @@ set_state_and_transform(const RenderState *target_rs, altered |= Shader::SSD_projection; } - if (_state_rs.was_deleted() || _state_rs == (const RenderState *)NULL) { + CPT(RenderState) state_rs = _state_rs.lock(); + if (state_rs == nullptr) { // Reset all of the state. altered |= Shader::SSD_general; _state_rs = target_rs; - } else if (_state_rs != target_rs) { + } else if (state_rs != target_rs) { // The state has changed since last time. - if (_state_rs->get_attrib(ColorAttrib::get_class_slot()) != + if (state_rs->get_attrib(ColorAttrib::get_class_slot()) != target_rs->get_attrib(ColorAttrib::get_class_slot())) { altered |= Shader::SSD_color; } - if (_state_rs->get_attrib(ColorScaleAttrib::get_class_slot()) != + if (state_rs->get_attrib(ColorScaleAttrib::get_class_slot()) != target_rs->get_attrib(ColorScaleAttrib::get_class_slot())) { altered |= Shader::SSD_colorscale; } - if (_state_rs->get_attrib(MaterialAttrib::get_class_slot()) != + if (state_rs->get_attrib(MaterialAttrib::get_class_slot()) != target_rs->get_attrib(MaterialAttrib::get_class_slot())) { altered |= Shader::SSD_material; } - if (_state_rs->get_attrib(ShaderAttrib::get_class_slot()) != + if (state_rs->get_attrib(ShaderAttrib::get_class_slot()) != target_rs->get_attrib(ShaderAttrib::get_class_slot())) { altered |= Shader::SSD_shaderinputs; } - if (_state_rs->get_attrib(FogAttrib::get_class_slot()) != + if (state_rs->get_attrib(FogAttrib::get_class_slot()) != target_rs->get_attrib(FogAttrib::get_class_slot())) { altered |= Shader::SSD_fog; } - if (_state_rs->get_attrib(LightAttrib::get_class_slot()) != + if (state_rs->get_attrib(LightAttrib::get_class_slot()) != target_rs->get_attrib(LightAttrib::get_class_slot())) { altered |= Shader::SSD_light; } - if (_state_rs->get_attrib(ClipPlaneAttrib::get_class_slot()) != + if (state_rs->get_attrib(ClipPlaneAttrib::get_class_slot()) != target_rs->get_attrib(ClipPlaneAttrib::get_class_slot())) { altered |= Shader::SSD_clip_planes; } - if (_state_rs->get_attrib(TexMatrixAttrib::get_class_slot()) != + if (state_rs->get_attrib(TexMatrixAttrib::get_class_slot()) != target_rs->get_attrib(TexMatrixAttrib::get_class_slot())) { altered |= Shader::SSD_tex_matrix; } @@ -507,7 +508,7 @@ issue_parameters(int altered) { if (GLCAT.is_spam()) { GLCAT.spam() << "Setting uniforms for " << _shader->get_filename() - << " (altered 0x" << hex << altered << dec << ")\n"; + << " (altered 0x" << std::hex << altered << std::dec << ")\n"; } // We have no way to track modifications to PTAs, so we assume that they are @@ -518,13 +519,13 @@ issue_parameters(int altered) { Shader::ShaderPtrSpec &spec = _shader->_ptr_spec[i]; const Shader::ShaderPtrData *ptr_data =_glgsg->fetch_ptr_parameter(spec); - if (ptr_data == NULL){ //the input is not contained in ShaderPtrData + if (ptr_data == nullptr){ //the input is not contained in ShaderPtrData release_resources(); return; } // Check if the size of the shader input and ptr_data match - int input_size = spec._dim[0] * spec._dim[1] * spec._dim[2]; + size_t input_size = spec._dim[0] * spec._dim[1] * spec._dim[2]; // dimension is negative only if the parameter had the (deprecated)k_ // prefix. @@ -735,8 +736,8 @@ update_transform_table(const TransformTable *table) { LMatrix4f *matrices = (LMatrix4f *)alloca(_transform_table_size * 64); int i = 0; - if (table != NULL) { - int num_transforms = min(_transform_table_size, (long)table->get_num_transforms()); + if (table != nullptr) { + int num_transforms = std::min(_transform_table_size, (long)table->get_num_transforms()); for (; i < num_transforms; ++i) { #ifdef STDFLOAT_DOUBLE LMatrix4 matrix; @@ -763,8 +764,8 @@ update_slider_table(const SliderTable *table) { float *sliders = (float *)alloca(_slider_table_size * 4); memset(sliders, 0, _slider_table_size * 4); - if (table != NULL) { - int num_sliders = min(_slider_table_size, (long)table->get_num_sliders()); + if (table != nullptr) { + int num_sliders = std::min(_slider_table_size, (long)table->get_num_sliders()); for (int i = 0; i < num_sliders; ++i) { sliders[i] = table->get_slider(i)->get_slider(); } @@ -879,7 +880,7 @@ update_shader_vertex_arrays(ShaderContext *prev, bool force) { // limited in the options we can set. GLenum type = _glgsg->get_numeric_type(numeric_type); if (p >= 0) { - max_p = max(max_p, (GLuint)p + 1); + max_p = std::max(max_p, (GLuint)p + 1); _glgsg->enable_vertex_attrib_array(p); @@ -1078,7 +1079,6 @@ update_shader_texture_bindings(ShaderContext *prev) { for (int i = 0; i < (int)_shader->_tex_spec.size(); ++i) { Shader::ShaderTexSpec &spec = _shader->_tex_spec[i]; - const InternalName *id = spec._name; CGparameter p = _cg_parameter_map[spec._id._seqno]; if (p == 0) { @@ -1110,7 +1110,7 @@ update_shader_texture_bindings(ShaderContext *prev) { _glgsg->set_active_texture_stage(texunit); TextureContext *tc = tex->prepare_now(view, _glgsg->_prepared_objects, _glgsg); - if (tc == (TextureContext*)NULL) { + if (tc == nullptr) { continue; } diff --git a/panda/src/glstuff/glCgShaderContext_src.h b/panda/src/glstuff/glCgShaderContext_src.h index d5bc721e61..63338b3520 100644 --- a/panda/src/glstuff/glCgShaderContext_src.h +++ b/panda/src/glstuff/glCgShaderContext_src.h @@ -25,7 +25,7 @@ class CLP(GraphicsStateGuardian); /** * xyz */ -class EXPCL_GL CLP(CgShaderContext) FINAL : public ShaderContext { +class EXPCL_GL CLP(CgShaderContext) final : public ShaderContext { public: friend class CLP(GraphicsStateGuardian); diff --git a/panda/src/glstuff/glGeomContext_src.cxx b/panda/src/glstuff/glGeomContext_src.cxx index 11a9cf3f23..2640c1d855 100644 --- a/panda/src/glstuff/glGeomContext_src.cxx +++ b/panda/src/glstuff/glGeomContext_src.cxx @@ -41,7 +41,7 @@ get_display_list(GLuint &index, const CLP(GeomMunger) *munger, if (dl._index == 0) { dl._index = glGenLists(1); list_current = false; - if (munger != (CLP(GeomMunger) *)NULL) { + if (munger != (CLP(GeomMunger) *)nullptr) { ((CLP(GeomMunger) *)munger)->_geom_contexts.insert(this); } } @@ -70,7 +70,7 @@ release_display_lists() { ++dli) { CLP(GeomMunger) *munger = (*dli).first; const DisplayList &dl = (*dli).second; - if (munger != (CLP(GeomMunger) *)NULL) { + if (munger != (CLP(GeomMunger) *)nullptr) { munger->_geom_contexts.erase(this); } diff --git a/panda/src/glstuff/glGeomMunger_src.cxx b/panda/src/glstuff/glGeomMunger_src.cxx index 5a1649f832..27f226a6cc 100644 --- a/panda/src/glstuff/glGeomMunger_src.cxx +++ b/panda/src/glstuff/glGeomMunger_src.cxx @@ -39,8 +39,8 @@ CLP(GeomMunger)(GraphicsStateGuardian *gsg, const RenderState *state) : // TexGen object gets deleted. _texture = (const TextureAttrib *)state->get_attrib(TextureAttrib::get_class_slot()); _tex_gen = (const TexGenAttrib *)state->get_attrib(TexGenAttrib::get_class_slot()); - _texture.set_callback(this); - _tex_gen.set_callback(this); + _texture.add_callback(this); + _tex_gen.add_callback(this); } } @@ -56,6 +56,11 @@ CLP(GeomMunger):: (*gci)->remove_munger(this); } _geom_contexts.clear(); + + if ((_flags & F_parallel_arrays) == 0) { + _texture.remove_callback(this); + _tex_gen.remove_callback(this); + } } /** @@ -79,13 +84,13 @@ munge_format_impl(const GeomVertexFormat *orig, new_format->set_animation(animation); CLP(GraphicsStateGuardian) *glgsg; - DCAST_INTO_R(glgsg, get_gsg(), NULL); + DCAST_INTO_R(glgsg, get_gsg(), nullptr); #ifndef OPENGLES // OpenGL ES 1 does, but regular OpenGL doesn't support GL_BYTE vertices and // texture coordinates. const GeomVertexColumn *vertex_type = orig->get_vertex_column(); - if (vertex_type != (GeomVertexColumn *)NULL && + if (vertex_type != nullptr && (vertex_type->get_numeric_type() == NT_int8 || vertex_type->get_numeric_type() == NT_uint8)) { int vertex_array = orig->get_array_with(InternalName::get_vertex()); @@ -99,7 +104,7 @@ munge_format_impl(const GeomVertexFormat *orig, } // Convert packed formats that OpenGL may not understand. - for (int i = 0; i < orig->get_num_columns(); ++i) { + for (size_t i = 0; i < orig->get_num_columns(); ++i) { const GeomVertexColumn *column = orig->get_column(i); int array = orig->get_array_with(column->get_name()); @@ -122,7 +127,7 @@ munge_format_impl(const GeomVertexFormat *orig, #endif // !OPENGLES const GeomVertexColumn *color_type = orig->get_color_column(); - if (color_type != (GeomVertexColumn *)NULL && + if (color_type != nullptr && color_type->get_numeric_type() == NT_packed_dabc && !glgsg->_supports_packed_dabc) { // We need to convert the color format; OpenGL doesn't support the byte @@ -177,7 +182,7 @@ munge_format_impl(const GeomVertexFormat *orig, if ((_flags & F_parallel_arrays) != 0) { // Split out the interleaved array into n parallel arrays. new_format = new GeomVertexFormat; - for (int i = 0; i < format->get_num_columns(); ++i) { + for (size_t i = 0; i < format->get_num_columns(); ++i) { const GeomVertexColumn *column = format->get_column(i); PT(GeomVertexArrayFormat) new_array_format = new GeomVertexArrayFormat; new_array_format->add_column(column->get_name(), column->get_num_components(), @@ -193,7 +198,7 @@ munge_format_impl(const GeomVertexFormat *orig, PT(GeomVertexArrayFormat) new_array_format = new GeomVertexArrayFormat; const GeomVertexColumn *column = format->get_vertex_column(); - if (column != (const GeomVertexColumn *)NULL) { + if (column != nullptr) { new_array_format->add_column (column->get_name(), column->get_num_components(), column->get_numeric_type(), column->get_contents(), @@ -202,7 +207,7 @@ munge_format_impl(const GeomVertexFormat *orig, } column = format->get_normal_column(); - if (column != (const GeomVertexColumn *)NULL) { + if (column != nullptr) { new_array_format->add_column (column->get_name(), column->get_num_components(), column->get_numeric_type(), column->get_contents(), @@ -211,7 +216,7 @@ munge_format_impl(const GeomVertexFormat *orig, } column = format->get_color_column(); - if (column != (const GeomVertexColumn *)NULL) { + if (column != nullptr) { new_array_format->add_column (column->get_name(), column->get_num_components(), column->get_numeric_type(), column->get_contents(), @@ -220,21 +225,21 @@ munge_format_impl(const GeomVertexFormat *orig, } // Put only the used texture coordinates into the interleaved array. - if (_texture != (TextureAttrib *)NULL) { + if (auto texture = _texture.lock()) { typedef pset UsedStages; UsedStages used_stages; - int num_stages = _texture->get_num_on_stages(); + int num_stages = texture->get_num_on_stages(); for (int i = 0; i < num_stages; ++i) { - TextureStage *stage = _texture->get_on_stage(i); - if (_tex_gen == (TexGenAttrib *)NULL || - !_tex_gen->has_stage(stage)) { + TextureStage *stage = texture->get_on_stage(i); + CPT(TexGenAttrib) tex_gen = _tex_gen.lock(); + if (tex_gen == nullptr || !tex_gen->has_stage(stage)) { InternalName *name = stage->get_texcoord_name(); if (used_stages.insert(name).second) { // This is the first time we've encountered this texcoord name. const GeomVertexColumn *texcoord_type = format->get_column(name); - if (texcoord_type != (const GeomVertexColumn *)NULL) { + if (texcoord_type != nullptr) { new_array_format->add_column (name, texcoord_type->get_num_values(), NT_stdfloat, C_texcoord, -1, texcoord_type->get_column_alignment()); @@ -265,13 +270,13 @@ premunge_format_impl(const GeomVertexFormat *orig) { PT(GeomVertexFormat) new_format = new GeomVertexFormat(*orig); CLP(GraphicsStateGuardian) *glgsg; - DCAST_INTO_R(glgsg, get_gsg(), NULL); + DCAST_INTO_R(glgsg, get_gsg(), nullptr); #ifndef OPENGLES // OpenGL ES 1 does, but regular OpenGL doesn't support GL_BYTE vertices and // texture coordinates. const GeomVertexColumn *vertex_type = orig->get_vertex_column(); - if (vertex_type != (GeomVertexColumn *)NULL && + if (vertex_type != nullptr && (vertex_type->get_numeric_type() == NT_int8 || vertex_type->get_numeric_type() == NT_uint8)) { int vertex_array = orig->get_array_with(InternalName::get_vertex()); @@ -285,7 +290,7 @@ premunge_format_impl(const GeomVertexFormat *orig) { } // Convert packed formats that OpenGL may not understand. - for (int i = 0; i < orig->get_num_columns(); ++i) { + for (size_t i = 0; i < orig->get_num_columns(); ++i) { const GeomVertexColumn *column = orig->get_column(i); int array = orig->get_array_with(column->get_name()); @@ -312,7 +317,7 @@ premunge_format_impl(const GeomVertexFormat *orig) { if ((_flags & F_parallel_arrays) != 0) { // Split out the interleaved array into n parallel arrays. new_format = new GeomVertexFormat; - for (int i = 0; i < format->get_num_columns(); ++i) { + for (size_t i = 0; i < format->get_num_columns(); ++i) { const GeomVertexColumn *column = format->get_column(i); PT(GeomVertexArrayFormat) new_array_format = new GeomVertexArrayFormat; new_array_format->add_column(column->get_name(), column->get_num_components(), @@ -332,7 +337,7 @@ premunge_format_impl(const GeomVertexFormat *orig) { PT(GeomVertexArrayFormat) new_array_format = new GeomVertexArrayFormat; const GeomVertexColumn *column = format->get_vertex_column(); - if (column != (const GeomVertexColumn *)NULL) { + if (column != nullptr) { new_array_format->add_column (column->get_name(), column->get_num_components(), column->get_numeric_type(), column->get_contents(), @@ -341,7 +346,7 @@ premunge_format_impl(const GeomVertexFormat *orig) { } column = format->get_normal_column(); - if (column != (const GeomVertexColumn *)NULL) { + if (column != nullptr) { new_array_format->add_column (column->get_name(), column->get_num_components(), column->get_numeric_type(), column->get_contents(), @@ -350,7 +355,7 @@ premunge_format_impl(const GeomVertexFormat *orig) { } column = format->get_color_column(); - if (column != (const GeomVertexColumn *)NULL) { + if (column != nullptr) { new_array_format->add_column (column->get_name(), column->get_num_components(), column->get_numeric_type(), column->get_contents(), @@ -360,21 +365,21 @@ premunge_format_impl(const GeomVertexFormat *orig) { // Put only the used texture coordinates into the interleaved array. The // others will be kept around, but in a parallel array. - if (_texture != (TextureAttrib *)NULL) { + if (auto texture = _texture.lock()) { typedef pset UsedStages; UsedStages used_stages; - int num_stages = _texture->get_num_on_stages(); + int num_stages = texture->get_num_on_stages(); for (int i = 0; i < num_stages; ++i) { - TextureStage *stage = _texture->get_on_stage(i); - if (_tex_gen == (TexGenAttrib *)NULL || - !_tex_gen->has_stage(stage)) { + TextureStage *stage = texture->get_on_stage(i); + CPT(TexGenAttrib) tex_gen = _tex_gen.lock(); + if (tex_gen == nullptr || !tex_gen->has_stage(stage)) { InternalName *name = stage->get_texcoord_name(); if (used_stages.insert(name).second) { // This is the first time we've encountered this texcoord name. const GeomVertexColumn *texcoord_type = format->get_column(name); - if (texcoord_type != (const GeomVertexColumn *)NULL) { + if (texcoord_type != nullptr) { new_array_format->add_column (name, texcoord_type->get_num_values(), NT_stdfloat, C_texcoord, -1, texcoord_type->get_column_alignment()); @@ -391,7 +396,7 @@ premunge_format_impl(const GeomVertexFormat *orig) { // Now go through the remaining arrays and make sure they are tightly // packed (with the column alignment restrictions). If not, repack them. - for (int i = 0; i < new_format->get_num_arrays(); ++i) { + for (size_t i = 0; i < new_format->get_num_arrays(); ++i) { CPT(GeomVertexArrayFormat) orig_a = new_format->get_array(i); if (orig_a->count_unused_space() != 0) { PT(GeomVertexArrayFormat) new_a = new GeomVertexArrayFormat; diff --git a/panda/src/glstuff/glGraphicsBuffer_src.cxx b/panda/src/glstuff/glGraphicsBuffer_src.cxx index 35daa0b225..66a9e6d407 100644 --- a/panda/src/glstuff/glGraphicsBuffer_src.cxx +++ b/panda/src/glstuff/glGraphicsBuffer_src.cxx @@ -13,6 +13,9 @@ #include "depthWriteAttrib.h" +using std::max; +using std::min; + TypeHandle CLP(GraphicsBuffer)::_type_handle; /** @@ -20,7 +23,7 @@ TypeHandle CLP(GraphicsBuffer)::_type_handle; */ CLP(GraphicsBuffer):: CLP(GraphicsBuffer)(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -32,7 +35,7 @@ CLP(GraphicsBuffer)(GraphicsEngine *engine, GraphicsPipe *pipe, _resolve_multisample_pcollector(_draw_window_pcollector, "Resolve multisamples"), _requested_multisamples(0), _requested_coverage_samples(0), - _rb_context(NULL) + _rb_context(nullptr) { // A FBO doesn't have a back buffer. _draw_buffer_type = RenderBuffer::T_front; @@ -67,7 +70,7 @@ CLP(GraphicsBuffer):: // unshare all buffers that are sharing this object's depth buffer { CLP(GraphicsBuffer) *graphics_buffer; - list ::iterator graphics_buffer_iterator; + std::list ::iterator graphics_buffer_iterator; graphics_buffer_iterator = _shared_depth_buffer_list.begin(); while (graphics_buffer_iterator != _shared_depth_buffer_list.end()) { @@ -97,7 +100,7 @@ clear(Thread *current_thread) { CLP(GraphicsStateGuardian) *glgsg = (CLP(GraphicsStateGuardian) *)_gsg.p(); - if (glgsg->_glClearBufferfv == NULL) { + if (glgsg->_glClearBufferfv == nullptr) { // We can't efficiently clear the buffer. Fall back to the inefficient // default implementation for now. GraphicsOutput::clear(current_thread); @@ -267,7 +270,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { for (it = _texture_contexts.begin(); it != _texture_contexts.end(); ++it) { CLP(TextureContext) *gtc = *it; - if (gtc != NULL && gtc->needs_barrier(GL_FRAMEBUFFER_BARRIER_BIT)) { + if (gtc != nullptr && gtc->needs_barrier(GL_FRAMEBUFFER_BARRIER_BIT)) { glgsg->issue_memory_barrier(GL_FRAMEBUFFER_BARRIER_BIT); // If we've done it for one, we've done it for all. break; @@ -386,7 +389,7 @@ rebuild_bitplanes() { _rb_size_z = 1; _rb_data_size_bytes = 0; - int num_fbos = 1; + size_t num_fbos = 1; // These variables indicate what should be bound to each bitplane. Texture *attach[RTP_COUNT]; @@ -455,7 +458,7 @@ rebuild_bitplanes() { } if (tex->get_z_size() > 1) { - num_fbos = max(num_fbos, tex->get_z_size()); + num_fbos = max(num_fbos, (size_t)tex->get_z_size()); } // Assign the texture to this slot. @@ -492,10 +495,10 @@ rebuild_bitplanes() { // requested. _use_depth_stencil = true; } - } else if (attach[RTP_depth_stencil] != NULL && attach[RTP_depth] == NULL) { + } else if (attach[RTP_depth_stencil] != nullptr && attach[RTP_depth] == nullptr) { // The depth stencil slot was assigned a texture, but we don't support it. // Downgrade to a regular depth texture. - swap(attach[RTP_depth], attach[RTP_depth_stencil]); + std::swap(attach[RTP_depth], attach[RTP_depth_stencil]); } // Knowing this, we can already be a tiny bit more accurate about the @@ -510,7 +513,7 @@ rebuild_bitplanes() { // depth_stencil implies depth, and we can't bind them both. Detect that // case, normalize it, and complain. if (_use_depth_stencil && attach[RTP_depth] && attach[RTP_depth_stencil]) { - attach[RTP_depth] = NULL; + attach[RTP_depth] = nullptr; GLCAT.warning() << "Attempt to bind both RTP_depth and RTP_depth_stencil bitplanes.\n"; } @@ -520,13 +523,13 @@ rebuild_bitplanes() { if (num_fbos > _fbo.size()) { // Generate more FBO handles. - int start = _fbo.size(); + size_t start = _fbo.size(); GLuint zero = 0; _fbo.resize(num_fbos, zero); glgsg->_glGenFramebuffers(num_fbos - start, &_fbo[start]); } - for (int layer = 0; layer < num_fbos; ++layer) { + for (int layer = 0; layer < (int)num_fbos; ++layer) { // Bind the FBO if (_fbo[layer] == 0) { report_my_gl_errors(); @@ -537,9 +540,9 @@ rebuild_bitplanes() { if (glgsg->_use_object_labels) { // Assign a label for OpenGL to use when displaying debug messages. if (num_fbos > 1) { - ostringstream strm; + std::ostringstream strm; strm << _name << '[' << layer << ']'; - string name = strm.str(); + std::string name = strm.str(); glgsg->_glObjectLabel(GL_FRAMEBUFFER, _fbo[layer], name.size(), name.data()); } else { glgsg->_glObjectLabel(GL_FRAMEBUFFER, _fbo[layer], _name.size(), _name.data()); @@ -562,7 +565,7 @@ rebuild_bitplanes() { if (_fb_properties.is_stereo()) { // The second tex view has already been initialized, so bind it // straight away. - if (attach[RTP_color] != NULL) { + if (attach[RTP_color] != nullptr) { attach_tex(layer, 1, attach[RTP_color], next++); } else { // XXX hack: I needed a slot to use, and we don't currently use @@ -696,7 +699,7 @@ bind_slot(int layer, bool rb_resize, Texture **attach, RenderTexturePlane slot, if (tex && layer >= tex->get_z_size()) { // If the requested layer index exceeds the number of layers in the // texture, we will not bind this layer. - tex = NULL; + tex = nullptr; } if (!tex && _rb_size_z > 1) { @@ -861,14 +864,22 @@ bind_slot(int layer, bool rb_resize, Texture **attach, RenderTexturePlane slot, case RTP_depth_stencil: if (_fb_properties.get_depth_bits() > 24 || _fb_properties.get_float_depth()) { - gl_format = GL_DEPTH32F_STENCIL8; + if (!glgsg->_use_remapped_depth_range) { + gl_format = GL_DEPTH32F_STENCIL8; + } else { + gl_format = GL_DEPTH32F_STENCIL8_NV; + } } else { gl_format = GL_DEPTH24_STENCIL8; } break; case RTP_depth: if (_fb_properties.get_float_depth()) { - gl_format = GL_DEPTH_COMPONENT32F; + if (!glgsg->_use_remapped_depth_range) { + gl_format = GL_DEPTH_COMPONENT32F; + } else { + gl_format = GL_DEPTH_COMPONENT32F_NV; + } } else if (_fb_properties.get_depth_bits() > 24) { gl_format = GL_DEPTH_COMPONENT32; } else if (_fb_properties.get_depth_bits() > 16) { @@ -978,6 +989,23 @@ bind_slot(int layer, bool rb_resize, Texture **attach, RenderTexturePlane slot, GLint depth_size = 0; glgsg->_glRenderbufferStorage(GL_RENDERBUFFER_EXT, gl_format, _rb_size_x, _rb_size_y); glgsg->_glGetRenderbufferParameteriv(GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_DEPTH_SIZE_EXT, &depth_size); + +#ifndef OPENGLES + // Are we getting only 24 bits of depth when we requested 32? It may be + // because GL_DEPTH_COMPONENT32 is not a required format, while 32F is. + if (gl_format == GL_DEPTH_COMPONENT32 && depth_size < 32) { + if (!glgsg->_use_remapped_depth_range) { + gl_format = GL_DEPTH_COMPONENT32F; + } else { + gl_format = GL_DEPTH_COMPONENT32F_NV; + } + glgsg->_glRenderbufferStorage(GL_RENDERBUFFER_EXT, gl_format, _rb_size_x, _rb_size_y); + glgsg->_glGetRenderbufferParameteriv(GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_DEPTH_SIZE_EXT, &depth_size); + + _fb_properties.set_float_depth(true); + } +#endif + _fb_properties.set_depth_bits(depth_size); _rb_data_size_bytes += _rb_size_x * _rb_size_y * (depth_size / 8); @@ -1154,7 +1182,7 @@ attach_tex(int layer, int view, Texture *attach, GLenum attachpoint) { // Create the OpenGL texture object. TextureContext *tc = attach->prepare_now(view, glgsg->get_prepared_objects(), glgsg); - nassertv(tc != (TextureContext *)NULL); + nassertv(tc != nullptr); CLP(TextureContext) *gtc = DCAST(CLP(TextureContext), tc); glgsg->update_texture(gtc, true); @@ -1175,7 +1203,7 @@ attach_tex(int layer, int view, Texture *attach, GLenum attachpoint) { #ifndef OPENGLES if (_rb_size_z != 1) { // Bind all of the layers of the texture. - nassertv(glgsg->_glFramebufferTexture != NULL); + nassertv(glgsg->_glFramebufferTexture != nullptr); glgsg->_glFramebufferTexture(GL_FRAMEBUFFER_EXT, attachpoint, gtc->_index, 0); return; @@ -1240,7 +1268,7 @@ generate_mipmaps() { void CLP(GraphicsBuffer):: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); - nassertv(_gsg != (GraphicsStateGuardian *)NULL); + nassertv(_gsg != nullptr); // Resolve Multisample rendering if using it. if (_requested_multisamples && _fbo_multisample) { @@ -1294,7 +1322,7 @@ set_size(int x, int y) { */ void CLP(GraphicsBuffer):: select_target_tex_page(int page) { - nassertv(page >= 0 && page < _fbo.size()); + nassertv(page >= 0 && (size_t)page < _fbo.size()); CLP(GraphicsStateGuardian) *glgsg = (CLP(GraphicsStateGuardian) *)_gsg.p(); @@ -1347,7 +1375,7 @@ open_buffer() { return false; } - if (_rb_context == NULL) { + if (_rb_context == nullptr) { _rb_context = new BufferContext(&(glgsg->_renderbuffer_residency)); } @@ -1534,10 +1562,10 @@ get_host() { void CLP(GraphicsBuffer):: close_buffer() { _rb_data_size_bytes = 0; - if (_rb_context != NULL) { + if (_rb_context != nullptr) { _rb_context->update_data_size_bytes(0); delete _rb_context; - _rb_context = NULL; + _rb_context = nullptr; } check_host_valid(); @@ -1571,10 +1599,10 @@ close_buffer() { report_my_gl_errors(); // Delete the FBO itself. - for (int i = 0; i < _fbo.size(); ++i) { - glgsg->_glDeleteFramebuffers(1, &_fbo[i]); + if (!_fbo.empty()) { + glgsg->_glDeleteFramebuffers(_fbo.size(), _fbo.data()); + _fbo.clear(); } - _fbo.clear(); report_my_gl_errors(); @@ -1718,12 +1746,12 @@ void CLP(GraphicsBuffer):: check_host_valid() { if (_host != nullptr && !_host->is_valid()) { _rb_data_size_bytes = 0; - if (_rb_context != NULL) { + if (_rb_context != nullptr) { // We must delete this object first, because when the GSG destructs, so // will the tracker that this context is attached to. _rb_context->update_data_size_bytes(0); delete _rb_context; - _rb_context = NULL; + _rb_context = nullptr; } _is_valid = false; _gsg.clear(); @@ -1751,7 +1779,7 @@ resolve_multisamples() { for (it = _texture_contexts.begin(); it != _texture_contexts.end(); ++it) { CLP(TextureContext) *gtc = *it; - if (gtc != NULL && gtc->needs_barrier(GL_FRAMEBUFFER_BARRIER_BIT)) { + if (gtc != nullptr && gtc->needs_barrier(GL_FRAMEBUFFER_BARRIER_BIT)) { glgsg->issue_memory_barrier(GL_FRAMEBUFFER_BARRIER_BIT); // If we've done it for one, we've done it for all. break; @@ -1773,9 +1801,9 @@ resolve_multisamples() { bool do_depth_blit = false; if (_rbm[RTP_depth_stencil] != 0 || _rbm[RTP_depth] != 0) { if (_shared_depth_buffer) { - CLP(GraphicsBuffer) *graphics_buffer = NULL; + CLP(GraphicsBuffer) *graphics_buffer = nullptr; //CLP(GraphicsBuffer) *highest_sort_graphics_buffer = NULL; - list ::iterator graphics_buffer_iterator; + std::list ::iterator graphics_buffer_iterator; int max_sort_order = 0; for (graphics_buffer_iterator = _shared_depth_buffer_list.begin(); diff --git a/panda/src/glstuff/glGraphicsBuffer_src.h b/panda/src/glstuff/glGraphicsBuffer_src.h index 31f7c91912..c383a0a5d4 100644 --- a/panda/src/glstuff/glGraphicsBuffer_src.h +++ b/panda/src/glstuff/glGraphicsBuffer_src.h @@ -50,7 +50,7 @@ class EXPCL_GL CLP(GraphicsBuffer) : public GraphicsBuffer { public: CLP(GraphicsBuffer)(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -135,7 +135,7 @@ protected: UpdateSeq _last_textures_seq; CLP(GraphicsBuffer) *_shared_depth_buffer; - list _shared_depth_buffer_list; + std::list _shared_depth_buffer_list; PStatCollector _bind_texture_pcollector; PStatCollector _generate_mipmap_pcollector; diff --git a/panda/src/glstuff/glGraphicsStateGuardian_src.I b/panda/src/glstuff/glGraphicsStateGuardian_src.I index 5ce7902917..bdb9db6eb5 100644 --- a/panda/src/glstuff/glGraphicsStateGuardian_src.I +++ b/panda/src/glstuff/glGraphicsStateGuardian_src.I @@ -93,7 +93,7 @@ clear_my_errors(int line, const char *source_file) { /** * Returns the GL vendor string reported by the driver. */ -INLINE const string &CLP(GraphicsStateGuardian):: +INLINE const std::string &CLP(GraphicsStateGuardian):: get_gl_vendor() const { return _gl_vendor; } @@ -101,7 +101,7 @@ get_gl_vendor() const { /** * Returns the GL renderer string reported by the driver. */ -INLINE const string &CLP(GraphicsStateGuardian):: +INLINE const std::string &CLP(GraphicsStateGuardian):: get_gl_renderer() const { return _gl_renderer; } @@ -109,7 +109,7 @@ get_gl_renderer() const { /** * Returns the GL version string reported by the driver. */ -INLINE const string &CLP(GraphicsStateGuardian):: +INLINE const std::string &CLP(GraphicsStateGuardian):: get_gl_version() const { return _gl_version; } @@ -174,7 +174,7 @@ maybe_gl_finish() const { * otherwise. The extension name is case-sensitive. */ INLINE bool CLP(GraphicsStateGuardian):: -has_extension(const string &extension) const { +has_extension(const std::string &extension) const { bool has_ext = (_extensions.find(extension) != _extensions.end()); #ifndef NDEBUG if (GLCAT.is_debug()) { @@ -491,13 +491,13 @@ enable_stencil_test(bool val) { if (val) { #ifdef GSG_VERBOSE GLCAT.spam() - << "glEnable(GL_STENCIL_TEST)" << endl; + << "glEnable(GL_STENCIL_TEST)" << std::endl; #endif glEnable(GL_STENCIL_TEST); } else { #ifdef GSG_VERBOSE GLCAT.spam() - << "glDisable(GL_STENCIL_TEST)" << endl; + << "glDisable(GL_STENCIL_TEST)" << std::endl; #endif glDisable(GL_STENCIL_TEST); } @@ -514,13 +514,13 @@ enable_blend(bool val) { if (val) { #ifdef GSG_VERBOSE GLCAT.spam() - << "glEnable(GL_BLEND)" << endl; + << "glEnable(GL_BLEND)" << std::endl; #endif glEnable(GL_BLEND); } else { #ifdef GSG_VERBOSE GLCAT.spam() - << "glDisable(GL_BLEND)" << endl; + << "glDisable(GL_BLEND)" << std::endl; #endif glDisable(GL_BLEND); } @@ -537,13 +537,13 @@ enable_depth_test(bool val) { if (val) { #ifdef GSG_VERBOSE GLCAT.spam() - << "glEnable(GL_DEPTH_TEST)" << endl; + << "glEnable(GL_DEPTH_TEST)" << std::endl; #endif glEnable(GL_DEPTH_TEST); } else { #ifdef GSG_VERBOSE GLCAT.spam() - << "glDisable(GL_DEPTH_TEST)" << endl; + << "glDisable(GL_DEPTH_TEST)" << std::endl; #endif glDisable(GL_DEPTH_TEST); } @@ -561,13 +561,13 @@ enable_fog(bool val) { if (val) { #ifdef GSG_VERBOSE GLCAT.spam() - << "glEnable(GL_FOG)" << endl; + << "glEnable(GL_FOG)" << std::endl; #endif glEnable(GL_FOG); } else { #ifdef GSG_VERBOSE GLCAT.spam() - << "glDisable(GL_FOG)" << endl; + << "glDisable(GL_FOG)" << std::endl; #endif glDisable(GL_FOG); } @@ -586,13 +586,13 @@ enable_alpha_test(bool val) { if (val) { #ifdef GSG_VERBOSE GLCAT.spam() - << "glEnable(GL_ALPHA_TEST)" << endl; + << "glEnable(GL_ALPHA_TEST)" << std::endl; #endif glEnable(GL_ALPHA_TEST); } else { #ifdef GSG_VERBOSE GLCAT.spam() - << "glDisable(GL_ALPHA_TEST)" << endl; + << "glDisable(GL_ALPHA_TEST)" << std::endl; #endif glDisable(GL_ALPHA_TEST); } @@ -610,7 +610,7 @@ enable_polygon_offset(bool val) { if (val) { #ifdef GSG_VERBOSE GLCAT.spam() - << "glEnable(GL_POLYGON_OFFSET_*)" << endl; + << "glEnable(GL_POLYGON_OFFSET_*)" << std::endl; #endif glEnable(GL_POLYGON_OFFSET_FILL); // glEnable(GL_POLYGON_OFFSET_LINE); not widely supported anyway @@ -618,7 +618,7 @@ enable_polygon_offset(bool val) { } else { #ifdef GSG_VERBOSE GLCAT.spam() - << "glDisable(GL_POLYGON_OFFSET_*)" << endl; + << "glDisable(GL_POLYGON_OFFSET_*)" << std::endl; #endif glDisable(GL_POLYGON_OFFSET_FILL); // glDisable(GL_POLYGON_OFFSET_LINE); not widely supported anyway diff --git a/panda/src/glstuff/glGraphicsStateGuardian_src.cxx b/panda/src/glstuff/glGraphicsStateGuardian_src.cxx index c4dd42ceb3..74080f274f 100644 --- a/panda/src/glstuff/glGraphicsStateGuardian_src.cxx +++ b/panda/src/glstuff/glGraphicsStateGuardian_src.cxx @@ -73,6 +73,13 @@ #include +using std::dec; +using std::endl; +using std::hex; +using std::max; +using std::min; +using std::string; + TypeHandle CLP(GraphicsStateGuardian)::_type_handle; PStatCollector CLP(GraphicsStateGuardian)::_load_display_list_pcollector("Draw:Transfer data:Display lists"); @@ -86,7 +93,7 @@ PStatCollector CLP(GraphicsStateGuardian)::_fbo_bind_pcollector("Draw:Bind FBO") PStatCollector CLP(GraphicsStateGuardian)::_check_error_pcollector("Draw:Check errors"); #ifndef OPENGLES_1 -PT(Shader) CLP(GraphicsStateGuardian)::_default_shader = NULL; +PT(Shader) CLP(GraphicsStateGuardian)::_default_shader = nullptr; #endif // The following noop functions are assigned to the corresponding glext @@ -528,7 +535,7 @@ reset() { PFNGLGETSTRINGIPROC _glGetStringi = (PFNGLGETSTRINGIPROC)get_extension_func("glGetStringi"); - if (_glGetStringi != NULL) { + if (_glGetStringi != nullptr) { GLint n = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &n); for (GLint i = 0; i < n; ++i) { @@ -606,18 +613,20 @@ reset() { get_extension_func("glDebugMessageControlARB"); _supports_debug = true; #endif + } else { + _supports_debug = false; } if (_supports_debug) { // Set the categories we want to listen to. _glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_HIGH, - 0, NULL, GLCAT.is_error()); + 0, nullptr, GLCAT.is_error()); _glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_MEDIUM, - 0, NULL, GLCAT.is_warning()); + 0, nullptr, GLCAT.is_warning()); _glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_LOW, - 0, NULL, GLCAT.is_info()); + 0, nullptr, GLCAT.is_info()); _glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, - 0, NULL, GLCAT.is_debug()); + 0, nullptr, GLCAT.is_debug()); // Enable the callback. _glDebugMessageCallback((GLDEBUGPROC_P) &debug_callback, (void*)this); @@ -677,7 +686,7 @@ reset() { get_extension_func("glPointParameterfvARB"); } if (_supports_point_parameters) { - if (_glPointParameterfv == NULL) { + if (_glPointParameterfv == nullptr) { GLCAT.warning() << "glPointParameterfv advertised as supported by OpenGL runtime, but could not get pointers to extension functions.\n"; _supports_point_parameters = false; @@ -718,7 +727,7 @@ reset() { #else _explicit_primitive_restart = false; - _glPrimitiveRestartIndex = NULL; + _glPrimitiveRestartIndex = nullptr; if (gl_support_primitive_restart_index) { if ((is_at_least_gl_version(4, 3) || has_extension("GL_ARB_ES3_compatibility")) && @@ -772,7 +781,7 @@ reset() { get_extension_func("glDrawRangeElementsEXT"); } #endif - if (_glDrawRangeElements == NULL) { + if (_glDrawRangeElements == nullptr) { GLCAT.warning() << "glDrawRangeElements advertised as supported by OpenGL runtime, but could not get pointers to extension functions.\n"; _glDrawRangeElements = null_glDrawRangeElements; @@ -801,7 +810,7 @@ reset() { _glTexSubImage3D = (PFNGLTEXSUBIMAGE3DPROC) get_extension_func("glTexSubImage3DEXT"); - _glCopyTexSubImage3D = NULL; + _glCopyTexSubImage3D = nullptr; if (has_extension("GL_EXT_copy_texture")) { _glCopyTexSubImage3D = (PFNGLCOPYTEXSUBIMAGE3DPROC) get_extension_func("glCopyTexSubImage3DEXT"); @@ -822,7 +831,7 @@ reset() { } if (_supports_3d_texture) { - if (_glTexImage3D == NULL || _glTexSubImage3D == NULL) { + if (_glTexImage3D == nullptr || _glTexSubImage3D == nullptr) { GLCAT.warning() << "3-D textures advertised as supported by OpenGL runtime, but could not get pointers to extension functions.\n"; _supports_3d_texture = false; @@ -860,7 +869,7 @@ reset() { #endif if (_supports_tex_storage) { - if (_glTexStorage1D == NULL || _glTexStorage2D == NULL || _glTexStorage3D == NULL) { + if (_glTexStorage1D == nullptr || _glTexStorage2D == nullptr || _glTexStorage3D == nullptr) { GLCAT.warning() << "Immutable texture storage advertised as supported by OpenGL runtime, but could not get pointers to extension functions.\n"; _supports_tex_storage = false; @@ -873,7 +882,7 @@ reset() { _glClearTexImage = (PFNGLCLEARTEXIMAGEPROC) get_extension_func("glClearTexImage"); - if (_glClearTexImage == NULL) { + if (_glClearTexImage == nullptr) { GLCAT.warning() << "GL_ARB_clear_texture advertised as supported by OpenGL runtime, but could not get pointers to extension function.\n"; } else { @@ -888,7 +897,7 @@ reset() { _glClearBufferData = (PFNGLCLEARBUFFERDATAPROC) get_extension_func("glClearBufferData"); - if (_glClearBufferData == NULL) { + if (_glClearBufferData == nullptr) { GLCAT.warning() << "GL_ARB_clear_buffer_object advertised as supported by OpenGL runtime, but could not get pointers to extension function.\n"; } else { @@ -914,7 +923,7 @@ reset() { #endif } - if (_supports_2d_texture_array && _glFramebufferTextureLayer == NULL) { + if (_supports_2d_texture_array && _glFramebufferTextureLayer == nullptr) { GLCAT.warning() << "Texture arrays advertised as supported by OpenGL runtime, but could not get pointer to glFramebufferTextureLayer function.\n"; } @@ -965,14 +974,14 @@ reset() { _supports_compressed_texture = true; // Supported in the core. 1D textures are not supported by OpenGL ES. - _glCompressedTexImage1D = NULL; + _glCompressedTexImage1D = nullptr; _glCompressedTexImage2D = glCompressedTexImage2D; - _glCompressedTexSubImage1D = NULL; + _glCompressedTexSubImage1D = nullptr; _glCompressedTexSubImage2D = glCompressedTexSubImage2D; - _glGetCompressedTexImage = NULL; + _glGetCompressedTexImage = nullptr; - _glCompressedTexImage3D = NULL; - _glCompressedTexSubImage3D = NULL; + _glCompressedTexImage3D = nullptr; + _glCompressedTexSubImage3D = nullptr; #ifdef OPENGLES_2 if (_supports_3d_texture) { _glCompressedTexImage3D = (PFNGLCOMPRESSEDTEXIMAGE3DPROC) @@ -1024,13 +1033,13 @@ reset() { } if (_supports_compressed_texture) { - if (_glCompressedTexImage1D == NULL || - _glCompressedTexImage2D == NULL || - _glCompressedTexImage3D == NULL || - _glCompressedTexSubImage1D == NULL || - _glCompressedTexSubImage2D == NULL || - _glCompressedTexSubImage3D == NULL || - _glGetCompressedTexImage == NULL) { + if (_glCompressedTexImage1D == nullptr || + _glCompressedTexImage2D == nullptr || + _glCompressedTexImage3D == nullptr || + _glCompressedTexSubImage1D == nullptr || + _glCompressedTexSubImage2D == nullptr || + _glCompressedTexSubImage3D == nullptr || + _glGetCompressedTexImage == nullptr) { GLCAT.warning() << "Compressed textures advertised as supported by OpenGL runtime, but could not get pointers to extension functions.\n"; _supports_compressed_texture = false; @@ -1245,13 +1254,13 @@ reset() { } if (supports_multitexture) { - if (_glActiveTexture == NULL + if (_glActiveTexture == nullptr #ifdef SUPPORT_FIXED_FUNCTION - || (has_fixed_function_pipeline() && _glClientActiveTexture == NULL) + || (has_fixed_function_pipeline() && _glClientActiveTexture == nullptr) #endif #ifdef SUPPORT_IMMEDIATE_MODE - || GLf(_glMultiTexCoord1) == NULL || GLf(_glMultiTexCoord2) == NULL - || GLf(_glMultiTexCoord3) == NULL || GLf(_glMultiTexCoord4) == NULL + || GLf(_glMultiTexCoord1) == nullptr || GLf(_glMultiTexCoord2) == nullptr + || GLf(_glMultiTexCoord3) == nullptr || GLf(_glMultiTexCoord4) == nullptr #endif ) { GLCAT.warning() @@ -1414,9 +1423,9 @@ reset() { #endif // OPENGLES_1 if (_supports_buffers) { - if (_glGenBuffers == NULL || _glBindBuffer == NULL || - _glBufferData == NULL || _glBufferSubData == NULL || - _glDeleteBuffers == NULL) { + if (_glGenBuffers == nullptr || _glBindBuffer == nullptr || + _glBufferData == nullptr || _glBufferSubData == nullptr || + _glDeleteBuffers == nullptr) { GLCAT.warning() << "Buffers advertised as supported by OpenGL runtime, but could not get pointers to extension functions.\n"; _supports_buffers = false; @@ -1434,7 +1443,7 @@ reset() { get_extension_func("glMapBufferRangeEXT"); } else { - _glMapBufferRange = NULL; + _glMapBufferRange = nullptr; } #else // Check for various advanced buffer management features. @@ -1442,14 +1451,14 @@ reset() { _glMapBufferRange = (PFNGLMAPBUFFERRANGEPROC) get_extension_func("glMapBufferRange"); } else { - _glMapBufferRange = NULL; + _glMapBufferRange = nullptr; } if (is_at_least_gl_version(4, 4) || has_extension("GL_ARB_buffer_storage")) { _glBufferStorage = (PFNGLBUFFERSTORAGEPROC) get_extension_func("glBufferStorage"); - if (_glBufferStorage != NULL) { + if (_glBufferStorage != nullptr) { _supports_buffer_storage = true; } else { GLCAT.warning() @@ -1491,8 +1500,8 @@ reset() { } if (_supports_vao) { - if (_glBindVertexArray == NULL || _glDeleteVertexArrays == NULL || - _glGenVertexArrays == NULL) { + if (_glBindVertexArray == nullptr || _glDeleteVertexArrays == nullptr || + _glGenVertexArrays == nullptr) { GLCAT.warning() << "Vertex array objects advertised as supported by OpenGL runtime, but could not get pointers to extension functions.\n"; _supports_vao = false; @@ -1526,13 +1535,13 @@ reset() { } else if (has_extension("GL_EXT_geometry_shader4")) { _supports_geometry_shaders = true; - _glFramebufferTexture = NULL; + _glFramebufferTexture = nullptr; _glProgramParameteri = (PFNGLPROGRAMPARAMETERIPROC) get_extension_func("glProgramParameteriEXT"); } else { _supports_geometry_shaders = false; - _glFramebufferTexture = NULL; + _glFramebufferTexture = nullptr; } #endif _shader_caps._supports_glsl = _supports_glsl; @@ -1620,7 +1629,7 @@ reset() { _glDispatchCompute = (PFNGLDISPATCHCOMPUTEPROC) get_extension_func("glDispatchCompute"); - if (_glDispatchCompute != NULL) { + if (_glDispatchCompute != nullptr) { _supports_compute_shaders = true; } } @@ -1707,14 +1716,14 @@ reset() { _glVertexAttribIPointer = (PFNGLVERTEXATTRIBIPOINTERPROC) get_extension_func("glVertexAttribIPointer"); } else { - _glVertexAttribIPointer = NULL; + _glVertexAttribIPointer = nullptr; } if (is_at_least_gl_version(4, 1) || has_extension("GL_ARB_vertex_attrib_64bit")) { _glVertexAttribLPointer = (PFNGLVERTEXATTRIBLPOINTERPROC) get_extension_func("glVertexAttribLPointer"); } else { - _glVertexAttribLPointer = NULL; + _glVertexAttribLPointer = nullptr; } if (_supports_tessellation_shaders) { @@ -1735,8 +1744,8 @@ reset() { _glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC) get_extension_func("glVertexAttribPointerARB"); - _glVertexAttribIPointer = NULL; - _glVertexAttribLPointer = NULL; + _glVertexAttribIPointer = nullptr; + _glVertexAttribLPointer = nullptr; } #endif @@ -1774,13 +1783,13 @@ reset() { _glVertexAttrib4fv = glVertexAttrib4fv; _glVertexAttrib4dv = null_glVertexAttrib4dv; _glVertexAttribPointer = glVertexAttribPointer; - _glVertexAttribLPointer = NULL; + _glVertexAttribLPointer = nullptr; if (is_at_least_gles_version(3, 0)) { _glVertexAttribIPointer = (PFNGLVERTEXATTRIBIPOINTERPROC) get_extension_func("glVertexAttribIPointer"); } else { - _glVertexAttribIPointer = NULL; + _glVertexAttribIPointer = nullptr; } #endif @@ -1817,7 +1826,7 @@ reset() { // to have a shader applied, or if it failed to compile. This default // shader just outputs a red color, indicating that something went wrong. #ifndef OPENGLES_1 - if (_default_shader == NULL && !has_fixed_function_pipeline()) { + if (_default_shader == nullptr && !has_fixed_function_pipeline()) { _default_shader = Shader::make(Shader::SL_GLSL, default_vshader, default_fshader); } #endif @@ -1985,7 +1994,7 @@ reset() { #ifndef OPENGLES_1 if (_supports_geometry_instancing) { - if (_glDrawArraysInstanced == NULL || _glDrawElementsInstanced == NULL) { + if (_glDrawArraysInstanced == nullptr || _glDrawElementsInstanced == nullptr) { GLCAT.warning() << "Geometry instancing advertised as supported by OpenGL runtime, but could not get pointers to extension functions.\n"; _supports_geometry_instancing = false; @@ -1993,7 +2002,7 @@ reset() { } if (_supports_vertex_attrib_divisor) { - if (_glVertexAttribDivisor == NULL) { + if (_glVertexAttribDivisor == nullptr) { GLCAT.warning() << "Instanced vertex arrays advertised as supported by OpenGL runtime, but could not get pointers to extension functions.\n"; _supports_vertex_attrib_divisor = false; @@ -2014,7 +2023,7 @@ reset() { _glDrawElementsIndirect = (PFNGLDRAWELEMENTSINDIRECTPROC) get_extension_func("glDrawElementsIndirect"); - if (_glDrawArraysIndirect == NULL || _glDrawElementsIndirect == NULL) { + if (_glDrawArraysIndirect == nullptr || _glDrawElementsIndirect == nullptr) { GLCAT.warning() << "Indirect draw advertised as supported by OpenGL runtime, but could not get pointers to extension functions.\n"; } else { @@ -2051,7 +2060,7 @@ reset() { get_extension_func("glGenFramebuffersOES"); _glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSOESPROC) get_extension_func("glCheckFramebufferStatusOES"); - _glFramebufferTexture1D = NULL; + _glFramebufferTexture1D = nullptr; _glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DOESPROC) get_extension_func("glFramebufferTexture2DOES"); _glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFEROESPROC) @@ -2062,7 +2071,7 @@ reset() { get_extension_func("glGenerateMipmapOES"); } else { _supports_framebuffer_object = false; - _glGenerateMipmap = NULL; + _glGenerateMipmap = nullptr; } #elif defined(OPENGLES) // In OpenGL ES 2.x, FBO's are supported in the core. @@ -2078,7 +2087,7 @@ reset() { _glDeleteFramebuffers = glDeleteFramebuffers; _glGenFramebuffers = glGenFramebuffers; _glCheckFramebufferStatus = glCheckFramebufferStatus; - _glFramebufferTexture1D = NULL; + _glFramebufferTexture1D = nullptr; _glFramebufferTexture2D = glFramebufferTexture2D; _glFramebufferRenderbuffer = glFramebufferRenderbuffer; _glGetFramebufferAttachmentParameteriv = glGetFramebufferAttachmentParameteriv; @@ -2209,7 +2218,7 @@ reset() { _supports_framebuffer_object = false; _supports_framebuffer_multisample = false; _supports_framebuffer_blit = false; - _glGenerateMipmap = NULL; + _glGenerateMipmap = nullptr; } #endif @@ -2218,7 +2227,7 @@ reset() { _glGenerateTextureMipmap = (PFNGLGENERATETEXTUREMIPMAPPROC) get_extension_func("glGenerateTextureMipmap"); } else { - _glGenerateTextureMipmap = NULL; + _glGenerateTextureMipmap = nullptr; } #endif @@ -2248,7 +2257,7 @@ reset() { #endif #if defined(OPENGLES_1) - _glDrawBuffers = NULL; + _glDrawBuffers = nullptr; _max_color_targets = 1; #elif defined(OPENGLES_2) @@ -2265,7 +2274,7 @@ reset() { get_extension_func("glDrawBuffersNV"); } else { - _glDrawBuffers = NULL; + _glDrawBuffers = nullptr; } #else @@ -2278,13 +2287,13 @@ reset() { get_extension_func("glDrawBuffersARB"); } else { - _glDrawBuffers = NULL; + _glDrawBuffers = nullptr; } #endif #ifndef OPENGLES_1 _max_color_targets = 1; - if (_glDrawBuffers != NULL) { + if (_glDrawBuffers != nullptr) { GLint max_draw_buffers = 0; glGetIntegerv(GL_MAX_DRAW_BUFFERS, &max_draw_buffers); _max_color_targets = max_draw_buffers; @@ -2301,9 +2310,9 @@ reset() { get_extension_func("glClearBufferfi"); } else { - _glClearBufferfv = NULL; - _glClearBufferiv = NULL; - _glClearBufferfi = NULL; + _glClearBufferfv = nullptr; + _glClearBufferiv = nullptr; + _glClearBufferfi = nullptr; } #endif // !OPENGLES @@ -2318,7 +2327,7 @@ reset() { _glDepthRangeArrayv = (PFNGLDEPTHRANGEARRAYVPROC) get_extension_func("glDepthRangeArrayv"); - if (_glViewportArrayv == NULL || _glScissorArrayv == NULL || _glDepthRangeArrayv == NULL) { + if (_glViewportArrayv == nullptr || _glScissorArrayv == nullptr || _glDepthRangeArrayv == nullptr) { GLCAT.warning() << "Viewport arrays advertised as supported by OpenGL runtime, but could not get pointers to extension functions.\n"; } else { @@ -2371,9 +2380,9 @@ reset() { } if (_supports_occlusion_query) { - if (_glGenQueries == NULL || _glBeginQuery == NULL || - _glEndQuery == NULL || _glDeleteQueries == NULL || - _glGetQueryiv == NULL || _glGetQueryObjectuiv == NULL) { + if (_glGenQueries == nullptr || _glBeginQuery == nullptr || + _glEndQuery == nullptr || _glDeleteQueries == nullptr || + _glGetQueryiv == nullptr || _glGetQueryObjectuiv == nullptr) { GLCAT.warning() << "Occlusion queries advertised as supported by OpenGL runtime, but could not get pointers to extension functions.\n"; _supports_occlusion_query = false; @@ -2414,7 +2423,7 @@ reset() { _glBlendEquation = (PFNGLBLENDEQUATIONPROC) get_extension_func("glBlendEquationOES"); - if (_glBlendEquation == NULL) { + if (_glBlendEquation == nullptr) { _glBlendEquation = null_glBlendEquation; GLCAT.warning() << "BlendEquationOES advertised as supported by OpenGL ES runtime, but " @@ -2428,7 +2437,7 @@ reset() { _glBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEOESPROC) get_extension_func("glBlendEquationSeparateOES"); - if (_glBlendEquation == NULL) { + if (_glBlendEquation == nullptr) { _supports_blend_equation_separate = false; GLCAT.warning() << "BlendEquationSeparateOES advertised as supported by OpenGL ES " @@ -2438,14 +2447,14 @@ reset() { } } else { _supports_blend_equation_separate = false; - _glBlendEquationSeparate = NULL; + _glBlendEquationSeparate = nullptr; } if (has_extension("GL_OES_blend_func_separate")) { _glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEOESPROC) get_extension_func("glBlendFuncSeparateOES"); - if (_glBlendFuncSeparate == NULL) { + if (_glBlendFuncSeparate == nullptr) { _glBlendFuncSeparate = null_glBlendFuncSeparate; GLCAT.warning() << "BlendFuncSeparateOES advertised as supported by OpenGL ES runtime, but " @@ -2472,7 +2481,7 @@ reset() { _glBlendEquation = null_glBlendEquation; } - if (_glBlendEquation == NULL) { + if (_glBlendEquation == nullptr) { _glBlendEquation = null_glBlendEquation; GLCAT.warning() << "BlendEquation advertised as supported by OpenGL runtime, but could " @@ -2491,10 +2500,10 @@ reset() { } else { _supports_blend_equation_separate = false; - _glBlendEquationSeparate = NULL; + _glBlendEquationSeparate = nullptr; } - if (_supports_blend_equation_separate && _glBlendEquationSeparate == NULL) { + if (_supports_blend_equation_separate && _glBlendEquationSeparate == nullptr) { _supports_blend_equation_separate = false; GLCAT.warning() << "BlendEquationSeparate advertised as supported by OpenGL runtime, " @@ -2513,7 +2522,7 @@ reset() { _glBlendFuncSeparate = null_glBlendFuncSeparate; } - if (_glBlendFuncSeparate == NULL) { + if (_glBlendFuncSeparate == nullptr) { _glBlendFuncSeparate = null_glBlendFuncSeparate; GLCAT.warning() << "BlendFuncSeparate advertised as supported by OpenGL runtime, but could not get pointers to extension function.\n"; @@ -2522,7 +2531,7 @@ reset() { // In OpenGL ES 2.x, this is supported in the core. In 1.x, not at all. #ifndef OPENGLES - _glBlendColor = NULL; + _glBlendColor = nullptr; bool supports_blend_color = false; if (is_at_least_gl_version(1, 2)) { supports_blend_color = true; @@ -2533,11 +2542,11 @@ reset() { _glBlendColor = (PFNGLBLENDCOLORPROC) get_extension_func("glBlendColorEXT"); } - if (supports_blend_color && _glBlendColor == NULL) { + if (supports_blend_color && _glBlendColor == nullptr) { GLCAT.warning() << "BlendColor advertised as supported by OpenGL runtime, but could not get pointers to extension function.\n"; } - if (_glBlendColor == NULL) { + if (_glBlendColor == nullptr) { _glBlendColor = null_glBlendColor; } #endif @@ -2643,7 +2652,6 @@ reset() { GLint max_3d_texture_size = 0; GLint max_2d_texture_array_layers = 0; GLint max_cube_map_size = 0; - GLint max_buffer_texture_size = 0; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size); _max_texture_dimension = max_texture_size; @@ -2671,6 +2679,7 @@ reset() { #ifndef OPENGLES if (_supports_buffer_texture) { + GLint max_buffer_texture_size = 0; glGetIntegerv(GL_MAX_TEXTURE_BUFFER_SIZE, &max_buffer_texture_size); _max_buffer_texture_size = max_buffer_texture_size; } else { @@ -2678,8 +2687,8 @@ reset() { } #endif // !OPENGLES - GLint max_elements_vertices = 0, max_elements_indices = 0; #ifndef OPENGLES + GLint max_elements_vertices = 0, max_elements_indices = 0; if (is_at_least_gl_version(1, 2) || has_extension("GL_EXT_draw_range_elements")) { glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &max_elements_vertices); glGetIntegerv(GL_MAX_ELEMENTS_INDICES, &max_elements_indices); @@ -2742,7 +2751,7 @@ reset() { glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, formats); for (int i = 0; i < num_compressed_formats; ++i) { const char *format_str = get_compressed_format_string(formats[i]); - if (format_str != NULL) { + if (format_str != nullptr) { GLCAT.debug(false) << " " << format_str << '\n'; } else { GLCAT.debug(false) @@ -2794,8 +2803,8 @@ reset() { #endif } else { - _glBindImageTexture = NULL; - _glMemoryBarrier = NULL; + _glBindImageTexture = nullptr; + _glMemoryBarrier = nullptr; } #endif // !OPENGLES_1 @@ -2816,10 +2825,10 @@ reset() { _glSamplerParameterf = (PFNGLSAMPLERPARAMETERFPROC) get_extension_func("glSamplerParameterf"); _glSamplerParameterfv = (PFNGLSAMPLERPARAMETERFVPROC) get_extension_func("glSamplerParameterfv"); - if (_glGenSamplers == NULL || _glDeleteSamplers == NULL || - _glBindSampler == NULL || _glSamplerParameteri == NULL || - _glSamplerParameteriv == NULL || _glSamplerParameterf == NULL || - _glSamplerParameterfv == NULL) { + if (_glGenSamplers == nullptr || _glDeleteSamplers == nullptr || + _glBindSampler == nullptr || _glSamplerParameteri == nullptr || + _glSamplerParameteriv == nullptr || _glSamplerParameterf == nullptr || + _glSamplerParameterfv == nullptr) { GLCAT.warning() << "GL_ARB_sampler_objects advertised as supported by OpenGL runtime, but could not get pointers to extension function.\n"; } else { @@ -2847,7 +2856,7 @@ reset() { get_extension_func("glBindVertexBuffers"); } - if (_glBindTextures != NULL && _glBindImageTextures != NULL) { + if (_glBindTextures != nullptr && _glBindImageTextures != nullptr) { _supports_multi_bind = true; } else { GLCAT.warning() @@ -2865,7 +2874,7 @@ reset() { _glGetInternalformativ = (PFNGLGETINTERNALFORMATIVPROC) get_extension_func("glGetInternalformativ"); - if (_glGetInternalformativ == NULL) { + if (_glGetInternalformativ == nullptr) { GLCAT.warning() << "ARB_internalformat_query2 advertised as supported by OpenGL runtime, but could not get pointers to extension function.\n"; } @@ -2884,8 +2893,8 @@ reset() { _glUniformHandleui64 = (PFNGLUNIFORMHANDLEUI64PROC) get_extension_func("glUniformHandleui64ARB"); - if (_glGetTextureHandle == NULL || _glMakeTextureHandleResident == NULL || - _glUniformHandleui64 == NULL) { + if (_glGetTextureHandle == nullptr || _glMakeTextureHandleResident == nullptr || + _glUniformHandleui64 == nullptr) { GLCAT.warning() << "GL_ARB_bindless_texture advertised as supported by OpenGL runtime, but could not get pointers to extension function.\n"; } else { @@ -2911,9 +2920,9 @@ reset() { get_extension_func("glProgramParameteri"); GLint num_binary_formats = 0; - if (_glGetProgramBinary != NULL && - _glProgramBinary != NULL && - _glProgramParameteri != NULL) { + if (_glGetProgramBinary != nullptr && + _glProgramBinary != nullptr && + _glProgramParameteri != nullptr) { glGetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS, &num_binary_formats); } @@ -2988,6 +2997,50 @@ reset() { } #endif + // Set depth range from zero to one if requested. +#ifndef OPENGLES + _use_depth_zero_to_one = false; + _use_remapped_depth_range = false; + + if (gl_depth_zero_to_one) { + if (is_at_least_gl_version(4, 5) || has_extension("GL_ARB_clip_control")) { + PFNGLCLIPCONTROLPROC pglClipControl = + (PFNGLCLIPCONTROLPROC)get_extension_func("glClipControl"); + + if (pglClipControl != nullptr) { + pglClipControl(GL_LOWER_LEFT, GL_ZERO_TO_ONE); + _use_depth_zero_to_one = true; + + if (GLCAT.is_debug()) { + GLCAT.debug() + << "Set zero-to-one depth using glClipControl\n"; + } + } + }/* else if (has_extension("GL_NV_depth_buffer_float")) { + // Alternatively, all GeForce 8+ and even some AMD drivers support this + // extension, which (unlike the core glDepthRange, which clamps its + // input parameters) can compensate for the built-in depth remapping. + _glDepthRangedNV = (PFNGLDEPTHRANGEDNVPROC)get_extension_func("glDepthRangedNV"); + + if (_glDepthRangedNV != nullptr) { + _glDepthRangedNV(-1.0, 1.0); + _use_depth_zero_to_one = true; + _use_remapped_depth_range = true; + + if (GLCAT.is_debug()) { + GLCAT.debug() + << "Set zero-to-one depth using glDepthRangedNV\n"; + } + } + }*/ + + if (!_use_depth_zero_to_one) { + GLCAT.warning() + << "Zero-to-one depth was requested, but driver does not support it.\n"; + } + } +#endif + // Set up all the enableddisabled flags to GL's known initial values: // everything off. _multisample_mode = 0; @@ -3007,7 +3060,7 @@ reset() { #ifndef OPENGLES_1 _enabled_vertex_attrib_arrays.clear(); - memset(_vertex_attrib_divisors, 0, sizeof(GLint) * 32); + memset(_vertex_attrib_divisors, 0, sizeof(GLuint) * 32); #endif // Dither is on by default in GL; let's turn it off @@ -3015,12 +3068,12 @@ reset() { _dithering_enabled = false; #ifndef OPENGLES_1 - _current_shader = (Shader *)NULL; - _current_shader_context = (ShaderContext *)NULL; - _vertex_array_shader = (Shader *)NULL; - _vertex_array_shader_context = (ShaderContext *)NULL; - _texture_binding_shader = (Shader *)NULL; - _texture_binding_shader_context = (ShaderContext *)NULL; + _current_shader = nullptr; + _current_shader_context = nullptr; + _vertex_array_shader = nullptr; + _vertex_array_shader_context = nullptr; + _texture_binding_shader = nullptr; + _texture_binding_shader_context = nullptr; #endif // Count the max number of lights @@ -3302,7 +3355,7 @@ clear(DrawableRegion *clearable) { int mask = 0; #ifndef OPENGLES_1 - if (_current_fbo != 0 && _glClearBufferfv != NULL) { + if (_current_fbo != 0 && _glClearBufferfv != nullptr) { // We can use glClearBuffer to clear all the color attachments, which // protects us from the overhead of having to call set_draw_buffer for // every single attachment. @@ -3457,7 +3510,7 @@ clear(DrawableRegion *clearable) { */ void CLP(GraphicsStateGuardian):: prepare_display_region(DisplayRegionPipelineReader *dr) { - nassertv(dr != (DisplayRegionPipelineReader *)NULL); + nassertv(dr != nullptr); GraphicsStateGuardian::prepare_display_region(dr); int l, b, w, h; @@ -3580,8 +3633,8 @@ clear_before_callback() { #ifndef OPENGLES_1 if (_vertex_array_shader_context != 0) { _vertex_array_shader_context->disable_shader_vertex_arrays(); - _vertex_array_shader = (Shader *)NULL; - _vertex_array_shader_context = (ShaderContext *)NULL; + _vertex_array_shader = nullptr; + _vertex_array_shader_context = nullptr; } #endif unbind_buffers(); @@ -3617,12 +3670,12 @@ clear_before_callback() { */ CPT(TransformState) CLP(GraphicsStateGuardian):: calc_projection_mat(const Lens *lens) { - if (lens == (Lens *)NULL) { - return NULL; + if (lens == nullptr) { + return nullptr; } if (!lens->is_linear()) { - return NULL; + return nullptr; } // The projection matrix must always be right-handed Y-up, even if our @@ -3637,6 +3690,19 @@ calc_projection_mat(const Lens *lens) { lens->get_coordinate_system()) * lens->get_projection_mat(_current_stereo_channel); +#ifndef OPENGLES + if (_use_depth_zero_to_one) { + // If we requested that the OpenGL NDC Z goes from zero to one like in + // Direct3D, we need to scale the projection matrix, which assumes -1..1. + static const LMatrix4 rescale_mat + (1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 0.5, 0, + 0, 0, 0.5, 1); + result *= rescale_mat; + } +#endif + if (_scene_setup->get_inverted()) { // If the scene is supposed to be inverted, then invert the projection // matrix. @@ -3815,18 +3881,18 @@ end_frame(Thread *current_thread) { // This breaks shaders across multiple regions. if (_vertex_array_shader_context != 0) { _vertex_array_shader_context->disable_shader_vertex_arrays(); - _vertex_array_shader = (Shader *)NULL; - _vertex_array_shader_context = (ShaderContext *)NULL; + _vertex_array_shader = nullptr; + _vertex_array_shader_context = nullptr; } if (_texture_binding_shader_context != 0) { _texture_binding_shader_context->disable_shader_texture_bindings(); - _texture_binding_shader = (Shader *)NULL; - _texture_binding_shader_context = (ShaderContext *)NULL; + _texture_binding_shader = nullptr; + _texture_binding_shader_context = nullptr; } if (_current_shader_context != 0) { _current_shader_context->unbind(); - _current_shader = (Shader *)NULL; - _current_shader_context = (ShaderContext *)NULL; + _current_shader = nullptr; + _current_shader_context = nullptr; } #endif @@ -3964,7 +4030,7 @@ begin_draw_primitives(const GeomPipelineReader *geom_reader, if (!has_fixed_function_pipeline()) { // We can't draw without a shader bound in OpenGL ES 2. This shouldn't // happen anyway unless the default shader failed to compile somehow. - if (_current_shader_context == NULL) { + if (_current_shader_context == nullptr) { return false; } } @@ -3973,7 +4039,7 @@ begin_draw_primitives(const GeomPipelineReader *geom_reader, if (!GraphicsStateGuardian::begin_draw_primitives(geom_reader, data_reader, force)) { return false; } - nassertr(_data_reader != (GeomVertexDataPipelineReader *)NULL, false); + nassertr(_data_reader != nullptr, false); _geom_display_list = 0; @@ -4033,7 +4099,7 @@ begin_draw_primitives(const GeomPipelineReader *geom_reader, unbind_buffers(); GeomContext *gc = geom_reader->prepare_now(get_prepared_objects(), this); - nassertr(gc != (GeomContext *)NULL, false); + nassertr(gc != nullptr, false); CLP(GeomContext) *ggc = DCAST(CLP(GeomContext), gc); //const CLP(GeomMunger) *gmunger = DCAST(CLP(GeomMunger), _munger); @@ -4176,7 +4242,7 @@ update_standard_vertex_arrays(bool force) { _sender.clear(); _sender.add_column(_data_reader, InternalName::get_normal(), - NULL, NULL, GLPf(Normal3), NULL); + nullptr, nullptr, GLPf(Normal3), nullptr); #ifndef NDEBUG if (_show_texture_usage) { // In show_texture_usage mode, all colors are white, so as not to @@ -4185,7 +4251,7 @@ update_standard_vertex_arrays(bool force) { } else #endif // NDEBUG if (!_sender.add_column(_data_reader, InternalName::get_color(), - NULL, NULL, GLPf(Color3), GLPf(Color4))) { + nullptr, nullptr, GLPf(Color3), GLPf(Color4))) { // If we didn't have a color column, the item color is white. GLPf(Color4)(1.0f, 1.0f, 1.0f, 1.0f); } @@ -4229,7 +4295,7 @@ update_standard_vertex_arrays(bool force) { // We must add vertex last, because glVertex3f() is the key function call // that actually issues the vertex. _sender.add_column(_data_reader, InternalName::get_vertex(), - NULL, GLPf(Vertex2), GLPf(Vertex3), GLPf(Vertex4)); + nullptr, GLPf(Vertex2), GLPf(Vertex3), GLPf(Vertex4)); } else #endif // SUPPORT_IMMEDIATE_MODE @@ -4365,11 +4431,11 @@ unbind_buffers() { #ifndef OPENGLES if (_current_vertex_buffers.size() > 1 && _supports_multi_bind) { - _glBindVertexBuffers(0, _current_vertex_buffers.size(), NULL, NULL, NULL); + _glBindVertexBuffers(0, _current_vertex_buffers.size(), nullptr, nullptr, nullptr); } else { - for (int i = 0; i < _current_vertex_buffers.size(); ++i) { + for (size_t i = 0; i < _current_vertex_buffers.size(); ++i) { if (_current_vertex_buffers[i] != 0) { - _glBindVertexBuffer(i, 0, 0, 0); + _glBindVertexBuffer((GLuint)i, 0, 0, 0); } } } @@ -4443,7 +4509,7 @@ update_shader_vertex_format(const GeomVertexFormat *format) { continue; } - if (_vertex_attrib_columns[loc] != NULL && + if (_vertex_attrib_columns[loc] != nullptr && _vertex_attrib_columns[loc]->compare_to(*column) == 0) { continue; } @@ -5480,7 +5546,7 @@ end_draw_primitives() { */ void CLP(GraphicsStateGuardian):: issue_memory_barrier(GLbitfield barriers) { - if (!gl_enable_memory_barriers || _glMemoryBarrier == NULL) { + if (!gl_enable_memory_barriers || _glMemoryBarrier == nullptr) { return; } @@ -5542,7 +5608,7 @@ prepare_texture(Texture *tex, int view) { if (!_supports_3d_texture) { GLCAT.warning() << "3-D textures are not supported by this OpenGL driver.\n"; - return NULL; + return nullptr; } break; @@ -5550,7 +5616,7 @@ prepare_texture(Texture *tex, int view) { if (!_supports_2d_texture_array) { GLCAT.warning() << "2-D texture arrays are not supported by this OpenGL driver.\n"; - return NULL; + return nullptr; } break; @@ -5558,7 +5624,7 @@ prepare_texture(Texture *tex, int view) { if (!_supports_cube_map) { GLCAT.warning() << "Cube map textures are not supported by this OpenGL driver.\n"; - return NULL; + return nullptr; } break; @@ -5566,7 +5632,7 @@ prepare_texture(Texture *tex, int view) { if (!_supports_buffer_texture) { GLCAT.warning() << "Buffer textures are not supported by this OpenGL driver.\n"; - return NULL; + return nullptr; } break; @@ -5574,7 +5640,7 @@ prepare_texture(Texture *tex, int view) { if (!_supports_cube_map_array) { GLCAT.warning() << "Cube map arrays are not supported by this OpenGL driver.\n"; - return NULL; + return nullptr; } break; @@ -5693,7 +5759,7 @@ extract_texture_data(Texture *tex) { int num_views = tex->get_num_views(); for (int view = 0; view < num_views; ++view) { TextureContext *tc = tex->prepare_now(view, get_prepared_objects(), this); - nassertr(tc != (TextureContext *)NULL, false); + nassertr(tc != nullptr, false); CLP(TextureContext) *gtc = DCAST(CLP(TextureContext), tc); if (!do_extract_texture_data(gtc)) { @@ -5717,7 +5783,7 @@ extract_texture_data(Texture *tex) { */ SamplerContext *CLP(GraphicsStateGuardian):: prepare_sampler(const SamplerState &sampler) { - nassertr(_supports_sampler_objects, NULL); + nassertr(_supports_sampler_objects, nullptr); PStatGPUTimer timer(this, _prepare_sampler_pcollector); CLP(SamplerContext) *gsc = new CLP(SamplerContext)(this, sampler); @@ -5852,7 +5918,7 @@ prepare_shader(Shader *se) { PStatGPUTimer timer(this, _prepare_shader_pcollector); #ifndef OPENGLES_1 - ShaderContext *result = NULL; + ShaderContext *result = nullptr; switch (se->get_language()) { case Shader::SL_GLSL: @@ -5862,7 +5928,7 @@ prepare_shader(Shader *se) { } else { GLCAT.error() << "Tried to load GLSL shader, but GLSL shaders not supported.\n"; - return NULL; + return nullptr; } case Shader::SL_Cg: @@ -5873,22 +5939,22 @@ prepare_shader(Shader *se) { } else { GLCAT.error() << "Tried to load Cg shader, but basic shaders not supported.\n"; - return NULL; + return nullptr; } #elif defined(OPENGLES) GLCAT.error() << "Tried to load Cg shader, but Cg support is not available for OpenGL ES.\n"; - return NULL; + return nullptr; #else GLCAT.error() << "Tried to load Cg shader, but Cg support not compiled in.\n"; - return NULL; + return nullptr; #endif default: GLCAT.error() << "Tried to load shader with unsupported shader language!\n"; - return NULL; + return nullptr; } if (result->valid()) { @@ -5898,7 +5964,7 @@ prepare_shader(Shader *se) { delete result; #endif // OPENGLES_1 - return NULL; + return nullptr; } /** @@ -5961,7 +6027,7 @@ prepare_vertex_buffer(GeomVertexArrayData *data) { return gvbc; } - return NULL; + return nullptr; } /** @@ -5988,7 +6054,7 @@ update_vertex_buffer(CLP(VertexBufferContext) *gvbc, } if (num_bytes != 0) { const unsigned char *client_pointer = reader->get_read_pointer(force); - if (client_pointer == NULL) { + if (client_pointer == nullptr) { return false; } @@ -6077,7 +6143,7 @@ setup_array_data(const unsigned char *&client_pointer, if (!_supports_buffers) { // No support for buffer objects; always render from client. client_pointer = array_reader->get_read_pointer(force); - return (client_pointer != NULL); + return (client_pointer != nullptr); } if (!vertex_buffers || _geom_display_list != 0 || array_reader->get_usage_hint() < gl_min_buffer_usage_hint) { @@ -6092,14 +6158,14 @@ setup_array_data(const unsigned char *&client_pointer, _current_vbuffer_index = 0; } client_pointer = array_reader->get_read_pointer(force); - return (client_pointer != NULL); + return (client_pointer != nullptr); } // Prepare the buffer object and bind it. CLP(VertexBufferContext) *gvbc = DCAST(CLP(VertexBufferContext), array_reader->prepare_now(get_prepared_objects(), this)); - nassertr(gvbc != (CLP(VertexBufferContext) *)NULL, false); + nassertr(gvbc != (CLP(VertexBufferContext) *)nullptr, false); if (!update_vertex_buffer(gvbc, array_reader, force)) { return false; } @@ -6114,7 +6180,7 @@ setup_array_data(const unsigned char *&client_pointer, } // NULL is the OpenGL convention for the first byte of the buffer object. - client_pointer = NULL; + client_pointer = nullptr; return true; } @@ -6149,7 +6215,7 @@ prepare_index_buffer(GeomPrimitive *data) { return gibc; } - return NULL; + return nullptr; } /** @@ -6186,7 +6252,7 @@ apply_index_buffer(IndexBufferContext *ibc, } if (num_bytes != 0) { const unsigned char *client_pointer = reader->get_read_pointer(force); - if (client_pointer == NULL) { + if (client_pointer == nullptr) { return false; } @@ -6266,7 +6332,7 @@ setup_primitive(const unsigned char *&client_pointer, if (!_supports_buffers) { // No support for buffer objects; always render from client. client_pointer = reader->get_read_pointer(force); - return (client_pointer != NULL); + return (client_pointer != nullptr); } if (!vertex_buffers || _geom_display_list != 0 || reader->get_usage_hint() == Geom::UH_client) { @@ -6281,18 +6347,18 @@ setup_primitive(const unsigned char *&client_pointer, _current_ibuffer_index = 0; } client_pointer = reader->get_read_pointer(force); - return (client_pointer != NULL); + return (client_pointer != nullptr); } // Prepare the buffer object and bind it. IndexBufferContext *ibc = reader->prepare_now(get_prepared_objects(), this); - nassertr(ibc != (IndexBufferContext *)NULL, false); + nassertr(ibc != nullptr, false); if (!apply_index_buffer(ibc, reader, force)) { return false; } // NULL is the OpenGL convention for the first byte of the buffer object. - client_pointer = NULL; + client_pointer = nullptr; return true; } @@ -6339,7 +6405,7 @@ prepare_shader_buffer(ShaderBuffer *data) { return gbc; } - return NULL; + return nullptr; } /** @@ -6348,9 +6414,9 @@ prepare_shader_buffer(ShaderBuffer *data) { void CLP(GraphicsStateGuardian):: apply_shader_buffer(GLuint base, ShaderBuffer *buffer) { GLuint index = 0; - if (buffer != NULL) { + if (buffer != nullptr) { BufferContext *bc = buffer->prepare_now(get_prepared_objects(), this); - if (bc != NULL) { + if (bc != nullptr) { CLP(BufferContext) *gbc = DCAST(CLP(BufferContext), bc); index = gbc->_index; gbc->set_active(true); @@ -6427,7 +6493,7 @@ release_shader_buffer(BufferContext *bc) { void CLP(GraphicsStateGuardian):: begin_occlusion_query() { nassertv(_supports_occlusion_query); - nassertv(_current_occlusion_query == (OcclusionQueryContext *)NULL); + nassertv(_current_occlusion_query == nullptr); PT(CLP(OcclusionQueryContext)) query = new CLP(OcclusionQueryContext)(this); _glGenQueries(1, &query->_index); @@ -6453,7 +6519,7 @@ begin_occlusion_query() { */ PT(OcclusionQueryContext) CLP(GraphicsStateGuardian):: end_occlusion_query() { - nassertr(_current_occlusion_query != (OcclusionQueryContext *)NULL, NULL); + nassertr(_current_occlusion_query != nullptr, nullptr); PT(OcclusionQueryContext) result = _current_occlusion_query; GLuint index = DCAST(CLP(OcclusionQueryContext), result)->_index; @@ -6463,7 +6529,7 @@ end_occlusion_query() { << "ending occlusion query index " << (int)index << "\n"; } - _current_occlusion_query = NULL; + _current_occlusion_query = nullptr; _glEndQuery(GL_SAMPLES_PASSED); // Temporary hack to try working around an apparent driver bug on iMacs. @@ -6493,7 +6559,7 @@ end_occlusion_query() { PT(TimerQueryContext) CLP(GraphicsStateGuardian):: issue_timer_query(int pstats_index) { #if defined(DO_PSTATS) && !defined(OPENGLES) - nassertr(_supports_timer_query, NULL); + nassertr(_supports_timer_query, nullptr); PT(CLP(TimerQueryContext)) query; @@ -6531,7 +6597,7 @@ issue_timer_query(int pstats_index) { return (TimerQueryContext *)query; #else - return NULL; + return nullptr; #endif } @@ -6546,7 +6612,7 @@ dispatch_compute(int num_groups_x, int num_groups_y, int num_groups_z) { PStatGPUTimer timer(this, _compute_dispatch_pcollector); nassertv(_supports_compute_shaders); - nassertv(_current_shader_context != NULL); + nassertv(_current_shader_context != nullptr); _glDispatchCompute(num_groups_x, num_groups_y, num_groups_z); maybe_gl_finish(); @@ -6572,7 +6638,7 @@ make_geom_munger(const RenderState *state, Thread *current_thread) { bool CLP(GraphicsStateGuardian):: framebuffer_copy_to_texture(Texture *tex, int view, int z, const DisplayRegion *dr, const RenderBuffer &rb) { - nassertr(tex != NULL && dr != NULL, false); + nassertr(tex != nullptr && dr != nullptr, false); set_read_buffer(rb._buffer_type); clear_color_write_mask(); @@ -6659,7 +6725,7 @@ framebuffer_copy_to_texture(Texture *tex, int view, int z, } TextureContext *tc = tex->prepare_now(view, get_prepared_objects(), this); - nassertr(tc != (TextureContext *)NULL, false); + nassertr(tc != nullptr, false); CLP(TextureContext) *gtc = DCAST(CLP(TextureContext), tc); apply_texture(gtc); @@ -6675,7 +6741,7 @@ framebuffer_copy_to_texture(Texture *tex, int view, int z, if (uses_mipmaps) { if (_supports_generate_mipmap) { #ifndef OPENGLES_2 - if (_glGenerateMipmap == NULL) { + if (_glGenerateMipmap == nullptr) { glTexParameteri(target, GL_GENERATE_MIPMAP, true); } #endif @@ -6735,7 +6801,7 @@ framebuffer_copy_to_texture(Texture *tex, int view, int z, // to specify them. Might as well use the actual values. GLint external_format = get_external_image_format(tex); GLint component_type = get_component_type(tex->get_component_type()); - _glTexImage3D(target, 0, internal_format, width, height, depth, 0, external_format, component_type, NULL); + _glTexImage3D(target, 0, internal_format, width, height, depth, 0, external_format, component_type, nullptr); } _glCopyTexSubImage3D(target, 0, 0, 0, z, xo, yo, w, h); @@ -6752,7 +6818,7 @@ framebuffer_copy_to_texture(Texture *tex, int view, int z, } } - if (uses_mipmaps && _glGenerateMipmap != NULL) { + if (uses_mipmaps && _glGenerateMipmap != nullptr) { glEnable(target); _glGenerateMipmap(target); glDisable(target); @@ -6787,7 +6853,7 @@ framebuffer_copy_to_texture(Texture *tex, int view, int z, bool CLP(GraphicsStateGuardian):: framebuffer_copy_to_ram(Texture *tex, int view, int z, const DisplayRegion *dr, const RenderBuffer &rb) { - nassertr(tex != NULL && dr != NULL, false); + nassertr(tex != nullptr && dr != nullptr, false); set_read_buffer(rb._buffer_type); glPixelStorei(GL_PACK_ALIGNMENT, 1); clear_color_write_mask(); @@ -7059,7 +7125,7 @@ do_issue_shader() { // If we don't have a shader, apply the default shader. if (!has_fixed_function_pipeline() && !shader) { shader = _default_shader; - nassertv(shader != NULL); + nassertv(shader != nullptr); } if (shader) { @@ -7074,7 +7140,7 @@ do_issue_shader() { if (_default_shader != nullptr && shader != _default_shader && (context == 0 || !context->valid())) { shader = _default_shader; - nassertv(shader != NULL); + nassertv(shader != nullptr); if (_current_shader != shader) { context = shader->prepare_now(get_prepared_objects(), this); } else { @@ -7092,7 +7158,7 @@ do_issue_shader() { if (context != _current_shader_context) { // Use a completely different shader than before. Unbind old shader, // bind the new one. - if (_current_shader_context != NULL && + if (_current_shader_context != nullptr && _current_shader->get_language() != shader->get_language()) { // If it's a different type of shader, make sure to unbind the old. _current_shader_context->unbind(); @@ -7403,7 +7469,7 @@ do_issue_fog() { if (!target_fog->is_off()) { enable_fog(true); Fog *fog = target_fog->get_fog(); - nassertv(fog != (Fog *)NULL); + nassertv(fog != nullptr); apply_fog(fog); } else { enable_fog(false); @@ -7443,7 +7509,13 @@ do_issue_depth_offset() { glDepthRangef((GLclampf)min_value, (GLclampf)max_value); #else // Mainline OpenGL uses a double-precision call. - glDepthRange((GLclampd)min_value, (GLclampd)max_value); + if (!_use_remapped_depth_range) { + glDepthRange((GLclampd)min_value, (GLclampd)max_value); + } else { + // If we have a remapped depth range, we should adjust the values to range + // from -1 to 1. We need to use an NV extension to pass unclamped values. + _glDepthRangedNV(min_value * 2.0 - 1.0, max_value * 2.0 - 1.0); + } #endif // OPENGLES report_my_gl_errors(); @@ -7461,7 +7533,7 @@ do_issue_material() { const MaterialAttrib *target_material; _target_rs->get_attrib_def(target_material); - if (target_material == (MaterialAttrib *)NULL || + if (target_material == nullptr || target_material->is_off()) { material = ∅ } else { @@ -7604,7 +7676,6 @@ do_issue_blending() { #endif if (color_channels == ColorWriteAttrib::C_off) { - int color_write_slot = ColorWriteAttrib::get_class_slot(); enable_multisample_alpha_one(false); enable_multisample_alpha_mask(false); if (gl_color_mask) { @@ -7837,7 +7908,7 @@ bind_light(DirectionalLight *light_obj, const NodePath &light, int light_id) { // State:Light:Bind:Directional"); PStatGPUTimer timer(this, // _draw_set_state_light_bind_directional_pcollector); - pair lookup = _dlights.insert(DirectionalLights::value_type(light, DirectionalLightFrameData())); + std::pair lookup = _dlights.insert(DirectionalLights::value_type(light, DirectionalLightFrameData())); DirectionalLightFrameData &fdata = (*lookup.first).second; if (lookup.second) { // The light was not computed yet this frame. Compute it now. @@ -7891,7 +7962,7 @@ bind_light(Spotlight *light_obj, const NodePath &light, int light_id) { // _draw_set_state_light_bind_spotlight_pcollector); Lens *lens = light_obj->get_lens(); - nassertv(lens != (Lens *)NULL); + nassertv(lens != nullptr); GLenum id = get_light_id(light_id); static const LColor black(0.0f, 0.0f, 0.0f, 1.0f); @@ -8101,7 +8172,7 @@ get_error_string(GLenum error_code) { } // Other error, somehow? Just display the error code then. - ostringstream strm; + std::ostringstream strm; strm << "GL error " << (int)error_code; return strm.str(); @@ -8117,7 +8188,7 @@ show_gl_string(const string &name, GLenum id) { const GLubyte *text = glGetString(id); - if (text == (const GLubyte *)NULL) { + if (text == nullptr) { GLCAT.warning() << "Unable to query " << name << "\n"; @@ -8282,7 +8353,7 @@ query_glsl_version() { */ void CLP(GraphicsStateGuardian):: save_extensions(const char *extensions) { - if (extensions != (const char *)NULL) { + if (extensions != nullptr) { vector_string tokens; extract_words(extensions, tokens); @@ -8308,10 +8379,9 @@ get_extra_extensions() { void CLP(GraphicsStateGuardian):: report_extensions() const { if (GLCAT.is_debug()) { - ostream &out = GLCAT.debug(); + std::ostream &out = GLCAT.debug(); out << "GL Extensions:\n"; - size_t maxlen = 0; pset::const_iterator ei; for (ei = _extensions.begin(); ei != _extensions.end(); ++ei) { size_t len = (*ei).size(); @@ -8399,11 +8469,11 @@ get_extension_func(const char *name) { { "glDeleteBuffers", (void *)&glDeleteBuffers }, { "glGenBuffers", (void *)&glGenBuffers }, #endif - { NULL, NULL } + { nullptr, nullptr } }; int i = 0; - while (compiled_function_table[i].name != NULL) { + while (compiled_function_table[i].name != nullptr) { if (strcmp(compiled_function_table[i].name, name) == 0) { return compiled_function_table[i].fptr; } @@ -8423,7 +8493,7 @@ get_extension_func(const char *name) { */ void *CLP(GraphicsStateGuardian):: do_get_extension_func(const char *) { - return NULL; + return nullptr; } /** @@ -10448,7 +10518,7 @@ get_compressed_format_string(GLenum format) { case 0x93F0: return "GL_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV2_IMG"; case 0x93F1: return "GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV2_IMG"; default: - return NULL; + return nullptr; } } #endif @@ -10762,13 +10832,13 @@ set_state_and_transform(const RenderState *target, _state_shader = _target_shader; _state_mask.clear_bit(TextureAttrib::get_class_slot()); } - else if (!has_fixed_function_pipeline() && _current_shader == NULL) { // In the case of OpenGL ES 2.x, we need to glUseShader before we draw anything. + else if (!has_fixed_function_pipeline() && _current_shader == nullptr) { // In the case of OpenGL ES 2.x, we need to glUseShader before we draw anything. do_issue_shader(); _state_mask.clear_bit(TextureAttrib::get_class_slot()); } // Update all of the state that is bound to the shader program. - if (_current_shader_context != NULL) { + if (_current_shader_context != nullptr) { _current_shader_context->set_state_and_transform(target, transform, _scene_setup->get_camera_transform(), _projection_mat); } #endif @@ -10915,7 +10985,6 @@ set_state_and_transform(const RenderState *target, !_state_mask.get_bit(texture_slot)) { // PStatGPUTimer timer(this, _draw_set_state_texture_pcollector); determine_target_texture(); - int prev_active = _num_active_texture_stages; do_issue_texture(); // Since the TexGen and TexMatrix states depend partly on the particular @@ -11058,7 +11127,7 @@ do_issue_texture() { disable_standard_texture_bindings(); } #endif - _current_shader_context->update_shader_texture_bindings(NULL); + _current_shader_context->update_shader_texture_bindings(nullptr); } else { _current_shader_context-> update_shader_texture_bindings(_texture_binding_shader_context); @@ -11091,7 +11160,7 @@ update_standard_texture_bindings() { // see if our flash_texture is in the texture stack here. If so, then we // need to call the special show_texture method instead of the normal // texture stack. - if (_flash_texture != (Texture *)NULL) { + if (_flash_texture != nullptr) { double now = ClockObject::get_global_clock()->get_frame_time(); int this_second = (int)floor(now); if (this_second & 1) { @@ -11123,7 +11192,7 @@ update_standard_texture_bindings() { for (i = 0; i < num_stages; i++) { TextureStage *stage = _target_texture->get_on_ff_stage(i); Texture *texture = _target_texture->get_on_texture(stage); - nassertv(texture != (Texture *)NULL); + nassertv(texture != nullptr); // Issue the texture on stage i. set_active_texture_stage(i); @@ -11143,7 +11212,7 @@ update_standard_texture_bindings() { int view = get_current_tex_view_offset() + stage->get_tex_view_offset(); TextureContext *tc = texture->prepare_now(view, _prepared_objects, this); - if (tc == (TextureContext *)NULL) { + if (tc == nullptr) { // Something wrong with this texture; skip it. continue; } @@ -11378,11 +11447,11 @@ update_show_usage_texture_bindings(int show_stage_index) { for (i = 0; i < num_stages; i++) { TextureStage *stage = _target_texture->get_on_ff_stage(i); Texture *texture = _target_texture->get_on_texture(stage); - nassertv(texture != (Texture *)NULL); + nassertv(texture != nullptr); int view = get_current_tex_view_offset() + stage->get_tex_view_offset(); TextureContext *tc = texture->prepare_now(view, _prepared_objects, this); - if (tc == (TextureContext *)NULL) { + if (tc == nullptr) { // Something wrong with this texture; skip it. break; } @@ -11423,7 +11492,7 @@ update_show_usage_texture_bindings(int show_stage_index) { TextureStage *stage = _target_texture->get_on_ff_stage(i); Texture *texture = _target_texture->get_on_texture(stage); - nassertv(texture != (Texture *)NULL); + nassertv(texture != nullptr); // Choose the corresponding usage texture and apply it. set_active_texture_stage(i); @@ -11606,17 +11675,18 @@ do_issue_tex_gen() { // effectively define an identity matrix that maps the spatial coordinates // one-for-one to UV's. If you want a mapping other than identity, use a // TexMatrixAttrib (or a TexProjectorEffect). +#ifndef OPENGLES static const PN_stdfloat s_data[4] = { 1, 0, 0, 0 }; static const PN_stdfloat t_data[4] = { 0, 1, 0, 0 }; static const PN_stdfloat r_data[4] = { 0, 0, 1, 0 }; static const PN_stdfloat q_data[4] = { 0, 0, 0, 1 }; +#endif _tex_gen_modifies_mat = false; bool got_point_sprites = false; for (int i = 0; i < _num_active_texture_stages; i++) { - TextureStage *stage = _target_texture->get_on_ff_stage(i); set_active_texture_stage(i); if (_supports_point_sprite) { #ifdef OPENGLES @@ -11632,6 +11702,7 @@ do_issue_tex_gen() { glDisable(GL_TEXTURE_GEN_R); glDisable(GL_TEXTURE_GEN_Q); + TextureStage *stage = _target_texture->get_on_ff_stage(i); TexGenAttrib::Mode mode = _target_tex_gen->get_mode(stage); switch (mode) { case TexGenAttrib::M_off: @@ -12043,7 +12114,7 @@ apply_sampler(GLuint unit, const SamplerState &sampler, CLP(TextureContext) *gtc // We support sampler objects. Prepare the sampler object and bind it to // the indicated texture unit. SamplerContext *sc = sampler.prepare_now(get_prepared_objects(), this); - nassertr(sc != (SamplerContext *)NULL, false); + nassertr(sc != nullptr, false); CLP(SamplerContext) *gsc = DCAST(CLP(SamplerContext), sc); gsc->enqueue_lru(&_prepared_objects->_sampler_object_lru); @@ -12264,10 +12335,8 @@ upload_texture(CLP(TextureContext) *gtc, bool force, bool uses_mipmaps) { } if (image_compression != Texture::CM_off) { - Texture::QualityLevel quality_level = tex->get_effective_quality_level(); - #ifndef OPENGLES - switch (quality_level) { + switch (tex->get_effective_quality_level()) { case Texture::QL_fastest: glHint(GL_TEXTURE_COMPRESSION_HINT, GL_FASTEST); break; @@ -12402,7 +12471,7 @@ upload_texture(CLP(TextureContext) *gtc, bool force, bool uses_mipmaps) { } #ifndef OPENGLES_2 - if (gtc->_generate_mipmaps && _glGenerateMipmap == NULL) { + if (gtc->_generate_mipmaps && _glGenerateMipmap == nullptr) { // The old, deprecated way to generate mipmaps. glTexParameteri(target, GL_GENERATE_MIPMAP, GL_TRUE); } @@ -12552,7 +12621,7 @@ upload_texture(CLP(TextureContext) *gtc, bool force, bool uses_mipmaps) { component_type, false, 0, image_compression); } - if (gtc->_generate_mipmaps && _glGenerateMipmap != NULL && + if (gtc->_generate_mipmaps && _glGenerateMipmap != nullptr && !image.is_null()) { // We uploaded an image; we may need to generate mipmaps. if (GLCAT.is_debug()) { @@ -12587,7 +12656,7 @@ upload_texture(CLP(TextureContext) *gtc, bool force, bool uses_mipmaps) { if (tex->has_ram_image()) { BamCache *cache = BamCache::get_global_ptr(); PT(BamCacheRecord) record = cache->lookup(tex->get_fullpath(), "txo"); - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { record->set_data(tex, tex); cache->store(record); } @@ -12596,7 +12665,7 @@ upload_texture(CLP(TextureContext) *gtc, bool force, bool uses_mipmaps) { } GraphicsEngine *engine = get_engine(); - nassertr(engine != (GraphicsEngine *)NULL, false); + nassertr(engine != nullptr, false); engine->texture_uploaded(tex); gtc->mark_loaded(); @@ -12639,7 +12708,7 @@ upload_texture_image(CLP(TextureContext) *gtc, bool needs_reload, } Texture *tex = gtc->get_texture(); - nassertr(tex != (Texture *)NULL, false); + nassertr(tex != nullptr, false); CPTA_uchar image = tex->get_ram_mipmap_image(mipmap_bias); int width = tex->get_expected_mipmap_x_size(mipmap_bias); @@ -12702,7 +12771,7 @@ upload_texture_image(CLP(TextureContext) *gtc, bool needs_reload, // mipmap image pointer which is a PTA_uchar const unsigned char *image_ptr = (unsigned char*)tex->get_ram_mipmap_pointer(n); CPTA_uchar ptimage; - if (image_ptr == (const unsigned char *)NULL) { + if (image_ptr == nullptr) { ptimage = tex->get_ram_mipmap_image(n); if (ptimage.is_null()) { if (n < num_ram_mipmap_levels) { @@ -12755,7 +12824,7 @@ upload_texture_image(CLP(TextureContext) *gtc, bool needs_reload, PTA_uchar bgr_image; size_t view_size = tex->get_ram_mipmap_view_size(n); - if (image_ptr != (const unsigned char *)NULL) { + if (image_ptr != nullptr) { const unsigned char *orig_image_ptr = image_ptr; image_ptr += view_size * gtc->get_view(); if (one_page_only) { @@ -12774,7 +12843,9 @@ upload_texture_image(CLP(TextureContext) *gtc, bool needs_reload, int width = tex->get_expected_mipmap_x_size(n); int height = tex->get_expected_mipmap_y_size(n); +#ifndef OPENGLES_1 int depth = tex->get_expected_mipmap_z_size(n); +#endif #ifdef DO_PSTATS _data_transferred_pcollector.add_level(view_size); @@ -12899,7 +12970,7 @@ upload_texture_image(CLP(TextureContext) *gtc, bool needs_reload, for (int n = mipmap_bias; n < num_levels; ++n) { const unsigned char *image_ptr = (unsigned char*)tex->get_ram_mipmap_pointer(n); CPTA_uchar ptimage; - if (image_ptr == (const unsigned char *)NULL) { + if (image_ptr == nullptr) { ptimage = tex->get_ram_mipmap_image(n); if (ptimage.is_null()) { if (n < num_ram_mipmap_levels) { @@ -12935,7 +13006,7 @@ upload_texture_image(CLP(TextureContext) *gtc, bool needs_reload, PTA_uchar bgr_image; size_t view_size = tex->get_ram_mipmap_view_size(n); - if (image_ptr != (const unsigned char *)NULL) { + if (image_ptr != nullptr) { const unsigned char *orig_image_ptr = image_ptr; image_ptr += view_size * gtc->get_view(); if (one_page_only) { @@ -12954,7 +13025,9 @@ upload_texture_image(CLP(TextureContext) *gtc, bool needs_reload, int width = tex->get_expected_mipmap_x_size(n); int height = tex->get_expected_mipmap_y_size(n); +#ifndef OPENGLES_1 int depth = tex->get_expected_mipmap_z_size(n); +#endif #ifdef DO_PSTATS _data_transferred_pcollector.add_level(view_size); @@ -13059,14 +13132,14 @@ upload_texture_image(CLP(TextureContext) *gtc, bool needs_reload, void CLP(GraphicsStateGuardian):: generate_mipmaps(CLP(TextureContext) *gtc) { #ifndef OPENGLES - if (_glGenerateTextureMipmap != NULL) { + if (_glGenerateTextureMipmap != nullptr) { // OpenGL 4.5 offers an easy way to do this without binding. _glGenerateTextureMipmap(gtc->_index); return; } #endif - if (_glGenerateMipmap != NULL) { + if (_glGenerateMipmap != nullptr) { _state_texture = 0; update_texture(gtc, true); apply_texture(gtc); @@ -13087,13 +13160,13 @@ upload_simple_texture(CLP(TextureContext) *gtc) { PStatGPUTimer timer(this, _load_texture_pcollector); Texture *tex = gtc->get_texture(); - nassertr(tex != (Texture *)NULL, false); + nassertr(tex != nullptr, false); GLenum internal_format = GL_RGBA; GLenum external_format = GL_BGRA; const unsigned char *image_ptr = tex->get_simple_ram_image(); - if (image_ptr == (const unsigned char *)NULL) { + if (image_ptr == nullptr) { return false; } @@ -13150,7 +13223,6 @@ get_texture_memory_size(CLP(TextureContext) *gtc) { int height = tex->get_y_size(); int depth = 1; int scale = 1; - bool has_mipmaps = tex->uses_mipmaps(); size_t num_bytes = 2; // Temporary assumption? @@ -13254,7 +13326,7 @@ check_nonresident_texture(BufferContextChain &chain) { GLuint *texture_list = (GLuint *)alloca(num_textures * sizeof(GLuint)); size_t ti = 0; BufferContext *node = chain.get_first(); - while (node != (BufferContext *)NULL) { + while (node != nullptr) { CLP(TextureContext) *gtc = DCAST(CLP(TextureContext), node); gtc_list[ti] = gtc; texture_list[ti] = gtc->_index; @@ -13306,9 +13378,18 @@ do_extract_texture_data(CLP(TextureContext) *gtc) { << "glBindTexture(0x" << hex << target << dec << ", " << gtc->_index << "): " << *tex << "\n"; } +#ifndef OPENGLES + if (target == GL_TEXTURE_BUFFER) { + _glBindBuffer(GL_TEXTURE_BUFFER, gtc->_buffer); + } +#endif + GLint wrap_u, wrap_v, wrap_w; GLint minfilter, magfilter; + +#ifndef OPENGLES GLfloat border_color[4]; +#endif #ifdef OPENGLES if (true) { @@ -13802,11 +13883,13 @@ do_extract_texture_data(CLP(TextureContext) *gtc) { tex->set_wrap_u(get_panda_wrap_mode(wrap_u)); tex->set_wrap_v(get_panda_wrap_mode(wrap_v)); tex->set_wrap_w(get_panda_wrap_mode(wrap_w)); - tex->set_border_color(LColor(border_color[0], border_color[1], - border_color[2], border_color[3])); - tex->set_minfilter(get_panda_filter_type(minfilter)); //tex->set_magfilter(get_panda_filter_type(magfilter)); + +#ifndef OPENGLES + tex->set_border_color(LColor(border_color[0], border_color[1], + border_color[2], border_color[3])); +#endif } PTA_uchar image; diff --git a/panda/src/glstuff/glGraphicsStateGuardian_src.h b/panda/src/glstuff/glGraphicsStateGuardian_src.h index ab1d27a2a4..d00478a58d 100644 --- a/panda/src/glstuff/glGraphicsStateGuardian_src.h +++ b/panda/src/glstuff/glGraphicsStateGuardian_src.h @@ -261,15 +261,15 @@ public: virtual ~CLP(GraphicsStateGuardian)(); // #--- Zhao Nov2011 - virtual string get_driver_vendor(); - virtual string get_driver_renderer(); - virtual string get_driver_version(); + virtual std::string get_driver_vendor(); + virtual std::string get_driver_renderer(); + virtual std::string get_driver_version(); virtual int get_driver_version_major(); virtual int get_driver_version_minor(); virtual int get_driver_shader_version_major(); virtual int get_driver_shader_version_minor(); - static void debug_callback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, GLvoid *userParam); + static void APIENTRY debug_callback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, GLvoid *userParam); virtual void reset(); @@ -411,9 +411,9 @@ public: INLINE bool clear_errors(int line, const char *source_file); INLINE void clear_my_errors(int line, const char *source_file); - INLINE const string &get_gl_vendor() const; - INLINE const string &get_gl_renderer() const; - INLINE const string &get_gl_version() const; + INLINE const std::string &get_gl_vendor() const; + INLINE const std::string &get_gl_renderer() const; + INLINE const std::string &get_gl_version() const; INLINE int get_gl_version_major() const; INLINE int get_gl_version_minor() const; INLINE bool has_fixed_function_pipeline() const; @@ -422,7 +422,7 @@ public: const TransformState *transform); void bind_fbo(GLuint fbo); - virtual bool get_supports_cg_profile(const string &name) const; + virtual bool get_supports_cg_profile(const std::string &name) const; void finish(); protected: @@ -466,14 +466,14 @@ protected: static bool report_errors_loop(int line, const char *source_file, GLenum error_code, int &error_count); - static string get_error_string(GLenum error_code); - string show_gl_string(const string &name, GLenum id); + static std::string get_error_string(GLenum error_code); + std::string show_gl_string(const std::string &name, GLenum id); virtual void query_gl_version(); void query_glsl_version(); void save_extensions(const char *extensions); virtual void get_extra_extensions(); void report_extensions() const; - INLINE virtual bool has_extension(const string &extension) const; + INLINE virtual bool has_extension(const std::string &extension) const; INLINE bool is_at_least_gl_version(int major_version, int minor_version) const; INLINE bool is_at_least_gles_version(int major_version, int minor_version) const; void *get_extension_func(const char *name); @@ -661,7 +661,7 @@ protected: #ifndef OPENGLES_1 BitMask32 _enabled_vertex_attrib_arrays; - GLint _vertex_attrib_divisors[32]; + GLuint _vertex_attrib_divisors[32]; PT(Shader) _current_shader; ShaderContext *_current_shader_context; @@ -728,14 +728,14 @@ protected: bool _supports_depth32; #endif - string _gl_vendor; - string _gl_renderer; - string _gl_version; + std::string _gl_vendor; + std::string _gl_renderer; + std::string _gl_version; int _gl_version_major, _gl_version_minor; // #--- Zhao Nov2011 int _gl_shadlang_ver_major, _gl_shadlang_ver_minor; - pset _extensions; + pset _extensions; #ifndef OPENGLES // True for non-compatibility GL 3.2+ contexts. @@ -743,6 +743,12 @@ protected: #endif public: +#ifndef OPENGLES + bool _use_depth_zero_to_one; + bool _use_remapped_depth_range; + PFNGLDEPTHRANGEDNVPROC _glDepthRangedNV; +#endif + bool _supports_point_parameters; PFNGLPOINTPARAMETERFVPROC _glPointParameterfv; bool _supports_point_sprite; diff --git a/panda/src/glstuff/glImmediateModeSender_src.cxx b/panda/src/glstuff/glImmediateModeSender_src.cxx index b832132a33..f7fba14cc3 100644 --- a/panda/src/glstuff/glImmediateModeSender_src.cxx +++ b/panda/src/glstuff/glImmediateModeSender_src.cxx @@ -74,35 +74,35 @@ add_column(const GeomVertexDataPipelineReader *data_reader, const InternalName * Func1f *func1f, Func2f *func2, Func3f *func3, Func4f *func4) { if (data_reader->has_column(name)) { GeomVertexReader *reader = new GeomVertexReader(data_reader, name); - ComponentSender *sender = NULL; + ComponentSender *sender = nullptr; const GeomVertexColumn *column = reader->get_column(); switch (column->get_num_components()) { case 1: - if (func1f != (Func1f *)NULL) { + if (func1f != nullptr) { sender = new ComponentSender1f(reader, func1f); } break; case 2: - if (func2 != (Func2f *)NULL) { + if (func2 != nullptr) { sender = new ComponentSender2f(reader, func2); } break; case 3: - if (func3 != (Func3f *)NULL) { + if (func3 != nullptr) { sender = new ComponentSender3f(reader, func3); } break; case 4: - if (func4 != (Func4f *)NULL) { + if (func4 != nullptr) { sender = new ComponentSender4f(reader, func4); } break; } - if (sender != (ComponentSender *)NULL) { + if (sender != nullptr) { // Ok, we've got a valid sender; add it to the list. _senders.push_back(sender); return true; @@ -135,7 +135,7 @@ add_texcoord_column(const GeomVertexDataPipelineReader *data_reader, TexcoordFunc3f *func3, TexcoordFunc4f *func4) { if (data_reader->has_column(name)) { GeomVertexReader *reader = new GeomVertexReader(data_reader, name); - ComponentSender *sender = NULL; + ComponentSender *sender = nullptr; const GeomVertexColumn *column = reader->get_column(); switch (column->get_num_components()) { case 1: @@ -155,7 +155,7 @@ add_texcoord_column(const GeomVertexDataPipelineReader *data_reader, break; } - if (sender != (ComponentSender *)NULL) { + if (sender != nullptr) { // Ok, we've got a valid sender; add it to the list. _senders.push_back(sender); return true; @@ -186,7 +186,7 @@ add_vector_column(const GeomVertexDataPipelineReader *data_reader, const Interna VectorFunc *func) { if (data_reader->has_column(name)) { GeomVertexReader *reader = new GeomVertexReader(data_reader, name); - ComponentSender *sender = NULL; + ComponentSender *sender = nullptr; const GeomVertexColumn *column = reader->get_column(); switch (column->get_num_components()) { case 1: @@ -206,7 +206,7 @@ add_vector_column(const GeomVertexDataPipelineReader *data_reader, const Interna break; } - if (sender != (ComponentSender *)NULL) { + if (sender != nullptr) { // Ok, we've got a valid sender; add it to the list. _senders.push_back(sender); return true; @@ -236,7 +236,7 @@ add_vector_uint_column(const GeomVertexDataPipelineReader *data_reader, const InternalName *name, VectorUintFunc *func) { if (data_reader->has_column(name)) { GeomVertexReader *reader = new GeomVertexReader(data_reader, name); - ComponentSender *sender = NULL; + ComponentSender *sender = nullptr; const GeomVertexColumn *column = reader->get_column(); switch (column->get_num_components()) { case 1: @@ -256,7 +256,7 @@ add_vector_uint_column(const GeomVertexDataPipelineReader *data_reader, break; } - if (sender != (ComponentSender *)NULL) { + if (sender != nullptr) { // Ok, we've got a valid sender; add it to the list. _senders.push_back(sender); return true; diff --git a/panda/src/glstuff/glShaderContext_src.cxx b/panda/src/glstuff/glShaderContext_src.cxx index f2c3b30a9b..94adf2f6a8 100644 --- a/panda/src/glstuff/glShaderContext_src.cxx +++ b/panda/src/glstuff/glShaderContext_src.cxx @@ -27,6 +27,12 @@ #include "clipPlaneAttrib.h" #include "bamCache.h" +using std::dec; +using std::hex; +using std::max; +using std::min; +using std::string; + TypeHandle CLP(ShaderContext)::_type_handle; /** @@ -318,7 +324,7 @@ CLP(ShaderContext)(CLP(GraphicsStateGuardian) *glgsg, Shader *s) : ShaderContext for (int i = 0; i < block_count; ++i) { block_name_cstr[0] = 0; - _glgsg->_glGetActiveUniformBlockName(_glsl_program, i, block_maxlength, NULL, block_name_cstr); + _glgsg->_glGetActiveUniformBlockName(_glsl_program, i, block_maxlength, nullptr, block_name_cstr); reflect_uniform_block(i, block_name_cstr, name_buffer, name_buflen); } @@ -337,16 +343,16 @@ CLP(ShaderContext)(CLP(GraphicsStateGuardian) *glgsg, Shader *s) : ShaderContext for (int i = 0; i < block_count; ++i) { block_name_cstr[0] = 0; - _glgsg->_glGetProgramResourceName(_glsl_program, GL_SHADER_STORAGE_BLOCK, i, block_maxlength, NULL, block_name_cstr); + _glgsg->_glGetProgramResourceName(_glsl_program, GL_SHADER_STORAGE_BLOCK, i, block_maxlength, nullptr, block_name_cstr); const GLenum props[] = {GL_BUFFER_BINDING, GL_BUFFER_DATA_SIZE}; GLint values[2]; - _glgsg->_glGetProgramResourceiv(_glsl_program, GL_SHADER_STORAGE_BLOCK, i, 2, props, 2, NULL, values); + _glgsg->_glGetProgramResourceiv(_glsl_program, GL_SHADER_STORAGE_BLOCK, i, 2, props, 2, nullptr, values); StorageBlock block; block._name = InternalName::make(block_name_cstr); block._binding_index = values[0]; - block._min_size = values[1]; + block._min_size = (GLuint)values[1]; _storage_blocks.push_back(block); } } @@ -369,7 +375,7 @@ CLP(ShaderContext)(CLP(GraphicsStateGuardian) *glgsg, Shader *s) : ShaderContext _glgsg->report_my_gl_errors(); // Restore the active shader. - if (_glgsg->_current_shader_context == NULL) { + if (_glgsg->_current_shader_context == nullptr) { _glgsg->_glUseProgram(0); } else { _glgsg->_current_shader_context->bind(); @@ -387,7 +393,7 @@ reflect_attribute(int i, char *name_buffer, GLsizei name_buflen) { // Get the name, size, and type of this attribute. name_buffer[0] = 0; - _glgsg->_glGetActiveAttrib(_glsl_program, i, name_buflen, NULL, + _glgsg->_glGetActiveAttrib(_glsl_program, i, name_buflen, nullptr, ¶m_size, ¶m_type, name_buffer); // Get the attrib location. @@ -415,7 +421,7 @@ reflect_attribute(int i, char *name_buffer, GLsizei name_buflen) { Shader::ShaderVarSpec bind; bind._id = arg_id; - bind._name = NULL; + bind._name = nullptr; bind._append_uv = -1; bind._elements = 1; @@ -564,7 +570,7 @@ reflect_uniform_block(int i, const char *name, char *name_buffer, GLsizei name_b name_buffer[0] = 0; GLint param_size; GLenum param_type; - _glgsg->_glGetActiveUniform(_glsl_program, indices[ui], name_buflen, NULL, ¶m_size, ¶m_type, name_buffer); + _glgsg->_glGetActiveUniform(_glsl_program, indices[ui], name_buflen, nullptr, ¶m_size, ¶m_type, name_buffer); // Strip off [0] suffix that some drivers append to arrays. size_t size = strlen(name_buffer); @@ -675,6 +681,9 @@ reflect_uniform_block(int i, const char *name, char *name_buffer, GLsizei name_b break; } + (void)numeric_type; + (void)contents; + (void)num_components; // GeomVertexColumn column(InternalName::make(name_buffer), // num_components, numeric_type, contents, offsets[ui], 4, param_size, // astrides[ui]); block_format.add_column(column); @@ -701,7 +710,7 @@ reflect_uniform(int i, char *name_buffer, GLsizei name_buflen) { // Get the name, location, type and size of this uniform. name_buffer[0] = 0; - _glgsg->_glGetActiveUniform(_glsl_program, i, name_buflen, NULL, ¶m_size, ¶m_type, name_buffer); + _glgsg->_glGetActiveUniform(_glsl_program, i, name_buflen, nullptr, ¶m_size, ¶m_type, name_buffer); GLint p = _glgsg->_glGetUniformLocation(_glsl_program, name_buffer); if (GLCAT.is_debug()) { @@ -785,8 +794,8 @@ reflect_uniform(int i, char *name_buffer, GLsizei name_buflen) { << "Matrix input p3d_" << matrix_name << " should be mat3 or mat4\n"; return; } - bind._arg[0] = NULL; - bind._arg[1] = NULL; + bind._arg[0] = nullptr; + bind._arg[1] = nullptr; if (matrix_name == "ModelViewProjectionMatrix") { if (inverse) { @@ -884,14 +893,14 @@ reflect_uniform(int i, char *name_buffer, GLsizei name_buflen) { bind._part[0] = Shader::SMO_light_source_i_attrib; bind._arg[0] = InternalName::make(name_buffer); bind._part[1] = Shader::SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; } else if (strncmp(name_buffer, "shadowMatrix", 127) == 0) { // Only supported for backward compatibility: includes the model // matrix. Not very efficient to do this. bind._func = Shader::SMF_compose; bind._part[0] = Shader::SMO_model_to_apiview; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; bind._part[1] = Shader::SMO_light_source_i_attrib; bind._arg[1] = InternalName::make("shadowViewMatrix"); @@ -946,10 +955,10 @@ reflect_uniform(int i, char *name_buffer, GLsizei name_buflen) { bind._id = arg_id; bind._func = Shader::SMF_first; bind._part[0] = Shader::SMO_attr_material; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; bind._dep[0] = Shader::SSD_general | Shader::SSD_material | Shader::SSD_frame; bind._part[1] = Shader::SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; bind._dep[1] = Shader::SSD_NONE; if (noprefix == "Material.baseColor") { @@ -1053,10 +1062,10 @@ reflect_uniform(int i, char *name_buffer, GLsizei name_buflen) { bind._id = arg_id; bind._func = Shader::SMF_first; bind._part[0] = Shader::SMO_attr_colorscale; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; bind._dep[0] = Shader::SSD_general | Shader::SSD_colorscale; bind._part[1] = Shader::SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; bind._dep[1] = Shader::SSD_NONE; if (param_type == GL_FLOAT_VEC3) { @@ -1077,10 +1086,10 @@ reflect_uniform(int i, char *name_buffer, GLsizei name_buflen) { bind._id = arg_id; bind._func = Shader::SMF_first; bind._part[0] = Shader::SMO_attr_color; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; bind._dep[0] = Shader::SSD_general | Shader::SSD_color; bind._part[1] = Shader::SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; bind._dep[1] = Shader::SSD_NONE; if (param_type == GL_FLOAT_VEC3) { @@ -1110,10 +1119,10 @@ reflect_uniform(int i, char *name_buffer, GLsizei name_buflen) { bind._func = Shader::SMF_first; bind._index = i; bind._part[0] = Shader::SMO_apiview_clipplane_i; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; bind._dep[0] = Shader::SSD_general | Shader::SSD_clip_planes; bind._part[1] = Shader::SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; bind._dep[1] = Shader::SSD_NONE; _shader->_mat_spec.push_back(bind); _shader->_mat_deps |= bind._dep[0]; @@ -1125,10 +1134,10 @@ reflect_uniform(int i, char *name_buffer, GLsizei name_buflen) { bind._id = arg_id; bind._func = Shader::SMF_first; bind._part[0] = Shader::SMO_light_ambient; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; bind._dep[0] = Shader::SSD_general | Shader::SSD_light; bind._part[1] = Shader::SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; bind._dep[1] = Shader::SSD_NONE; if (param_type == GL_FLOAT_VEC3) { @@ -1183,7 +1192,7 @@ reflect_uniform(int i, char *name_buffer, GLsizei name_buflen) { bind._arg[0] = InternalName::make(member_name); bind._dep[0] = Shader::SSD_general | Shader::SSD_light | Shader::SSD_frame; bind._part[1] = Shader::SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; bind._dep[1] = Shader::SSD_NONE; if (member_name == "position" || member_name == "halfVector" || @@ -1245,10 +1254,10 @@ reflect_uniform(int i, char *name_buffer, GLsizei name_buflen) { bind._func = Shader::SMF_first; bind._index = 0; bind._part[0] = Shader::SMO_tex_is_alpha_i; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; bind._dep[0] = Shader::SSD_general | Shader::SSD_texture | Shader::SSD_frame; bind._part[1] = Shader::SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; bind._dep[1] = Shader::SSD_NONE; bind._piece = Shader::SMP_row3; _shader->_mat_spec.push_back(bind); @@ -1265,8 +1274,8 @@ reflect_uniform(int i, char *name_buffer, GLsizei name_buflen) { Shader::ShaderMatSpec bind; bind._id = arg_id; - bind._arg[0] = NULL; - bind._arg[1] = NULL; + bind._arg[0] = nullptr; + bind._arg[1] = nullptr; if (noprefix == "ViewMatrix") { bind._piece = Shader::SMP_whole; @@ -1395,7 +1404,7 @@ reflect_uniform(int i, char *name_buffer, GLsizei name_buflen) { bind._arg[0] = InternalName::make(param_name); bind._dep[0] = Shader::SSD_general | Shader::SSD_shaderinputs | Shader::SSD_frame; bind._part[1] = Shader::SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; bind._dep[1] = Shader::SSD_NONE; _shader->_mat_spec.push_back(bind); _shader->_mat_deps |= bind._dep[0]; @@ -1407,7 +1416,7 @@ reflect_uniform(int i, char *name_buffer, GLsizei name_buflen) { bind._piece = Shader::SMP_whole; bind._func = Shader::SMF_first; bind._part[1] = Shader::SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; bind._dep[1] = Shader::SSD_NONE; PT(InternalName) iname = InternalName::make(param_name); if (iname->get_parent() != InternalName::get_root()) { @@ -1428,7 +1437,7 @@ reflect_uniform(int i, char *name_buffer, GLsizei name_buflen) { } bind._func = Shader::SMF_compose; bind._part[0] = Shader::SMO_model_to_apiview; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; bind._dep[0] = Shader::SSD_general | Shader::SSD_transform; bind._part[1] = Shader::SMO_mat_constant_x_attrib; bind._arg[1] = iname->get_parent()->append("shadowViewMatrix"); @@ -1478,7 +1487,7 @@ reflect_uniform(int i, char *name_buffer, GLsizei name_buflen) { // position) have to be transformed to view space. bind._dep[0] = Shader::SSD_general | Shader::SSD_shaderinputs | Shader::SSD_frame | Shader::SSD_view_transform; bind._part[1] = Shader::SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; bind._dep[1] = Shader::SSD_NONE; _shader->_mat_spec.push_back(bind); _shader->_mat_deps |= bind._dep[0]; @@ -1568,7 +1577,7 @@ reflect_uniform(int i, char *name_buffer, GLsizei name_buflen) { ImageInput input; input._name = InternalName::make(param_name); input._writable = false; - input._gtc = NULL; + input._gtc = nullptr; _glsl_img_inputs.push_back(input); } return; @@ -1899,46 +1908,49 @@ set_state_and_transform(const RenderState *target_rs, altered |= Shader::SSD_projection; } - if (_state_rs.was_deleted() || _state_rs == (const RenderState *)NULL) { + CPT(RenderState) state_rs = _state_rs.lock(); + if (state_rs == nullptr) { // Reset all of the state. altered |= Shader::SSD_general; _state_rs = target_rs; + target_rs->get_attrib_def(_color_attrib); - } else if (_state_rs != target_rs) { + } else if (state_rs != target_rs) { // The state has changed since last time. - if (_state_rs->get_attrib(ColorAttrib::get_class_slot()) != + if (state_rs->get_attrib(ColorAttrib::get_class_slot()) != target_rs->get_attrib(ColorAttrib::get_class_slot())) { altered |= Shader::SSD_color; + target_rs->get_attrib_def(_color_attrib); } - if (_state_rs->get_attrib(ColorScaleAttrib::get_class_slot()) != + if (state_rs->get_attrib(ColorScaleAttrib::get_class_slot()) != target_rs->get_attrib(ColorScaleAttrib::get_class_slot())) { altered |= Shader::SSD_colorscale; } - if (_state_rs->get_attrib(MaterialAttrib::get_class_slot()) != + if (state_rs->get_attrib(MaterialAttrib::get_class_slot()) != target_rs->get_attrib(MaterialAttrib::get_class_slot())) { altered |= Shader::SSD_material; } - if (_state_rs->get_attrib(ShaderAttrib::get_class_slot()) != + if (state_rs->get_attrib(ShaderAttrib::get_class_slot()) != target_rs->get_attrib(ShaderAttrib::get_class_slot())) { altered |= Shader::SSD_shaderinputs; } - if (_state_rs->get_attrib(FogAttrib::get_class_slot()) != + if (state_rs->get_attrib(FogAttrib::get_class_slot()) != target_rs->get_attrib(FogAttrib::get_class_slot())) { altered |= Shader::SSD_fog; } - if (_state_rs->get_attrib(LightAttrib::get_class_slot()) != + if (state_rs->get_attrib(LightAttrib::get_class_slot()) != target_rs->get_attrib(LightAttrib::get_class_slot())) { altered |= Shader::SSD_light; } - if (_state_rs->get_attrib(ClipPlaneAttrib::get_class_slot()) != + if (state_rs->get_attrib(ClipPlaneAttrib::get_class_slot()) != target_rs->get_attrib(ClipPlaneAttrib::get_class_slot())) { altered |= Shader::SSD_clip_planes; } - if (_state_rs->get_attrib(TexMatrixAttrib::get_class_slot()) != + if (state_rs->get_attrib(TexMatrixAttrib::get_class_slot()) != target_rs->get_attrib(TexMatrixAttrib::get_class_slot())) { altered |= Shader::SSD_tex_matrix; } - if (_state_rs->get_attrib(TextureAttrib::get_class_slot()) != + if (state_rs->get_attrib(TextureAttrib::get_class_slot()) != target_rs->get_attrib(TextureAttrib::get_class_slot())) { altered |= Shader::SSD_texture; } @@ -1977,7 +1989,7 @@ issue_parameters(int altered) { if (altered & (Shader::SSD_shaderinputs | Shader::SSD_frame)) { // If we have an osg_FrameNumber input, set it now. - if ((altered | Shader::SSD_frame) != 0 && _frame_number_loc >= 0) { + if ((altered & Shader::SSD_frame) != 0 && _frame_number_loc >= 0) { _glgsg->_glUniform1i(_frame_number_loc, _frame_number); } @@ -1986,7 +1998,7 @@ issue_parameters(int altered) { Shader::ShaderPtrSpec &spec = _shader->_ptr_spec[i]; const Shader::ShaderPtrData* ptr_data = _glgsg->fetch_ptr_parameter(spec); - if (ptr_data == NULL) { //the input is not contained in ShaderPtrData + if (ptr_data == nullptr) { //the input is not contained in ShaderPtrData release_resources(); return; } @@ -1996,7 +2008,7 @@ issue_parameters(int altered) { switch (spec._type) { case Shader::SPT_float: { - float *data = NULL; + float *data = nullptr; switch (ptr_data->_type) { case Shader::SPT_int: @@ -2148,7 +2160,7 @@ update_transform_table(const TransformTable *table) { LMatrix4f *matrices = (LMatrix4f *)alloca(_transform_table_size * 64); size_t i = 0; - if (table != NULL) { + if (table != nullptr) { size_t num_transforms = min((size_t)_transform_table_size, table->get_num_transforms()); for (; i < num_transforms; ++i) { #ifdef STDFLOAT_DOUBLE @@ -2160,7 +2172,7 @@ update_transform_table(const TransformTable *table) { #endif } } - for (; i < _transform_table_size; ++i) { + for (; i < (size_t)_transform_table_size; ++i) { matrices[i] = LMatrix4f::ident_mat(); } @@ -2176,7 +2188,7 @@ update_slider_table(const SliderTable *table) { float *sliders = (float *)alloca(_slider_table_size * 4); memset(sliders, 0, _slider_table_size * 4); - if (table != NULL) { + if (table != nullptr) { size_t num_sliders = min((size_t)_slider_table_size, table->get_num_sliders()); for (size_t i = 0; i < num_sliders; ++i) { sliders[i] = table->get_slider(i)->get_slider(); @@ -2220,8 +2232,7 @@ update_shader_vertex_arrays(ShaderContext *prev, bool force) { // Get the active ColorAttrib. We'll need it to determine how to apply // vertex colors. - const ColorAttrib *color_attrib; - _state_rs->get_attrib_def(color_attrib); + const ColorAttrib *color_attrib = _color_attrib.p(); const GeomVertexArrayDataHandle *array_reader; @@ -2229,13 +2240,13 @@ update_shader_vertex_arrays(ShaderContext *prev, bool force) { // Use experimental new separated formatbinding state. const GeomVertexDataPipelineReader *data_reader = _glgsg->_data_reader; - for (int ai = 0; ai < data_reader->get_num_arrays(); ++ai) { + for (size_t ai = 0; ai < data_reader->get_num_arrays(); ++ai) { array_reader = data_reader->get_array_reader(ai); // Make sure the vertex buffer is up-to-date. CLP(VertexBufferContext) *gvbc = DCAST(CLP(VertexBufferContext), array_reader->prepare_now(_glgsg->get_prepared_objects(), _glgsg)); - nassertr(gvbc != (CLP(VertexBufferContext) *)NULL, false); + nassertr(gvbc != (CLP(VertexBufferContext) *)nullptr, false); if (!_glgsg->update_vertex_buffer(gvbc, array_reader, force)) { return false; @@ -2286,7 +2297,7 @@ update_shader_vertex_arrays(ShaderContext *prev, bool force) { int start, stride, num_values; size_t nvarying = _shader->_var_spec.size(); - GLuint max_p = 0; + GLint max_p = 0; for (size_t i = 0; i < nvarying; ++i) { const Shader::ShaderVarSpec &bind = _shader->_var_spec[i]; @@ -2304,7 +2315,7 @@ update_shader_vertex_arrays(ShaderContext *prev, bool force) { } } - GLuint p = bind._id._seqno; + GLint p = bind._id._seqno; max_p = max(max_p, p + 1); // Don't apply vertex colors if they are disabled with a ColorAttrib. @@ -2393,7 +2404,7 @@ disable_shader_texture_bindings() { DO_PSTATS_STUFF(_glgsg->_texture_state_pcollector.add_level(1)); - for (int i = 0; i < _shader->_tex_spec.size(); ++i) { + for (size_t i = 0; i < _shader->_tex_spec.size(); ++i) { #ifndef OPENGLES // Check if bindless was used, if so, there's nothing to unbind. if (_glgsg->_supports_bindless_texture) { @@ -2408,7 +2419,7 @@ disable_shader_texture_bindings() { // There are non-bindless textures to unbind, and we're lazy, so let's // go and unbind everything after this point using one multi-bind call, // and then break out of the loop. - _glgsg->_glBindTextures(i, _shader->_tex_spec.size() - i, NULL); + _glgsg->_glBindTextures(i, _shader->_tex_spec.size() - i, nullptr); break; } #endif @@ -2452,7 +2463,7 @@ disable_shader_texture_bindings() { if (num_image_units > 0) { #ifndef OPENGLES if (_glgsg->_supports_multi_bind) { - _glgsg->_glBindImageTextures(0, num_image_units, NULL); + _glgsg->_glBindImageTextures(0, num_image_units, nullptr); } else #endif { @@ -2465,9 +2476,9 @@ disable_shader_texture_bindings() { for (int i = 0; i < num_image_units; ++i) { ImageInput &input = _glsl_img_inputs[i]; - if (input._gtc != NULL) { + if (input._gtc != nullptr) { input._gtc->mark_incoherent(input._writable); - input._gtc = NULL; + input._gtc = nullptr; } } } @@ -2500,7 +2511,7 @@ update_shader_texture_bindings(ShaderContext *prev) { if (num_image_units > 0) { for (int i = 0; i < num_image_units; ++i) { ImageInput &input = _glsl_img_inputs[i]; - const ParamTextureImage *param = NULL; + const ParamTextureImage *param = nullptr; Texture *tex; const ShaderInput &sinp = _glgsg->_target_shader->get_shader_input(input._name); @@ -2530,11 +2541,11 @@ update_shader_texture_bindings(ShaderContext *prev) { GLuint gl_tex = 0; CLP(TextureContext) *gtc; - if (tex != NULL) { + if (tex != nullptr) { int view = _glgsg->get_current_tex_view_offset(); gtc = DCAST(CLP(TextureContext), tex->prepare_now(view, _glgsg->_prepared_objects, _glgsg)); - if (gtc != (TextureContext*)NULL) { + if (gtc != nullptr) { input._gtc = gtc; _glgsg->update_texture(gtc, true); @@ -2568,7 +2579,7 @@ update_shader_texture_bindings(ShaderContext *prev) { GLint bind_layer = 0; GLboolean layered = GL_TRUE; - if (param != NULL) { + if (param != nullptr) { layered = param->get_bind_layered(); bind_level = param->get_bind_level(); bind_layer = param->get_bind_layer(); @@ -2601,8 +2612,8 @@ update_shader_texture_bindings(ShaderContext *prev) { } size_t num_textures = _shader->_tex_spec.size(); - GLuint *textures; - GLuint *samplers; + GLuint *textures = nullptr; + GLuint *samplers = nullptr; #ifdef OPENGLES static const bool multi_bind = false; #else @@ -2637,7 +2648,7 @@ update_shader_texture_bindings(ShaderContext *prev) { } if (tex->get_texture_type() != spec._desired_type) { - if (id != NULL) { + if (id != nullptr) { GLCAT.error() << "Sampler type of GLSL shader input '" << *id << "' does not " "match type of texture " << *tex << ".\n"; @@ -2651,7 +2662,7 @@ update_shader_texture_bindings(ShaderContext *prev) { } CLP(TextureContext) *gtc = DCAST(CLP(TextureContext), tex->prepare_now(view, _glgsg->_prepared_objects, _glgsg)); - if (gtc == NULL) { + if (gtc == nullptr) { if (multi_bind) { textures[i] = 0; samplers[i] = 0; @@ -2659,9 +2670,9 @@ update_shader_texture_bindings(ShaderContext *prev) { continue; } +#ifndef OPENGLES GLint p = spec._id._seqno; -#ifndef OPENGLES // If it was recently written to, we will have to issue a memory barrier // soon. if (gtc->needs_barrier(GL_TEXTURE_FETCH_BARRIER_BIT)) { @@ -2714,7 +2725,7 @@ update_shader_texture_bindings(ShaderContext *prev) { } SamplerContext *sc = sampler.prepare_now(_glgsg->get_prepared_objects(), _glgsg); - if (sc == NULL) { + if (sc == nullptr) { samplers[i] = 0; } else { CLP(SamplerContext) *gsc = DCAST(CLP(SamplerContext), sc); @@ -2798,9 +2809,9 @@ glsl_report_shader_errors(GLuint shader, Shader::ShaderType type, bool fatal) { // Parse the errors so that we can substitute in actual file locations // instead of source indices. - istringstream log(info_log); + std::istringstream log(info_log); string line; - while (getline(log, line)) { + while (std::getline(log, line)) { int fileno, lineno, colno; int prefixlen = 0; @@ -2934,7 +2945,7 @@ glsl_compile_shader(Shader::ShaderType type) { string text_str = _shader->get_text(type); const char* text = text_str.c_str(); - _glgsg->_glShaderSource(handle, 1, &text, NULL); + _glgsg->_glShaderSource(handle, 1, &text, nullptr); _glgsg->_glCompileShader(handle); GLint status; _glgsg->_glGetShaderiv(handle, GL_COMPILE_STATUS, &status); @@ -3113,7 +3124,7 @@ glsl_compile_and_link() { sprintf(filename, "glsl_program%d.dump", gl_dump_count++); pofstream s; - s.open(filename, ios::out | ios::binary | ios::trunc); + s.open(filename, std::ios::out | std::ios::binary | std::ios::trunc); s.write(binary, num_bytes); s.close(); diff --git a/panda/src/glstuff/glShaderContext_src.h b/panda/src/glstuff/glShaderContext_src.h index 9ecfe9ed39..91130e9224 100644 --- a/panda/src/glstuff/glShaderContext_src.h +++ b/panda/src/glstuff/glShaderContext_src.h @@ -26,7 +26,7 @@ class CLP(GraphicsStateGuardian); /** * xyz */ -class EXPCL_GL CLP(ShaderContext) FINAL : public ShaderContext { +class EXPCL_GL CLP(ShaderContext) final : public ShaderContext { public: friend class CLP(GraphicsStateGuardian); @@ -75,6 +75,7 @@ private: CPT(TransformState) _modelview_transform; CPT(TransformState) _camera_transform; CPT(TransformState) _projection_transform; + CPT(ColorAttrib) _color_attrib; /* * struct ParamContext { CPT(InternalName) _name; GLint _location; GLsizei @@ -98,7 +99,7 @@ private: struct StorageBlock { CPT(InternalName) _name; GLuint _binding_index; - GLint _min_size; + GLuint _min_size; }; typedef pvector StorageBlocks; StorageBlocks _storage_blocks; diff --git a/panda/src/glstuff/glTextureContext_src.h b/panda/src/glstuff/glTextureContext_src.h index 9a345b397d..667e356d60 100644 --- a/panda/src/glstuff/glTextureContext_src.h +++ b/panda/src/glstuff/glTextureContext_src.h @@ -42,7 +42,7 @@ public: #endif #ifdef OPENGLES_1 - static CONSTEXPR bool needs_barrier(GLbitfield barrier) { return false; }; + static constexpr bool needs_barrier(GLbitfield barrier) { return false; }; #else bool needs_barrier(GLbitfield barrier); void mark_incoherent(bool wrote); diff --git a/panda/src/glstuff/glTimerQueryContext_src.cxx b/panda/src/glstuff/glTimerQueryContext_src.cxx index 36cfefb91e..a7b4ecb612 100644 --- a/panda/src/glstuff/glTimerQueryContext_src.cxx +++ b/panda/src/glstuff/glTimerQueryContext_src.cxx @@ -30,9 +30,9 @@ CLP(TimerQueryContext):: // has already shut down, though, too bad. This means we never get to // free this index, but presumably the app is already shutting down // anyway. - if (!_glgsg.was_deleted()) { - LightMutexHolder holder(_glgsg->_lock); - _glgsg->_deleted_queries.push_back(_index); + if (auto glgsg = _glgsg.lock()) { + LightMutexHolder holder(glgsg->_lock); + glgsg->_deleted_queries.push_back(_index); _index = 0; } } diff --git a/panda/src/glstuff/glmisc_src.cxx b/panda/src/glstuff/glmisc_src.cxx index fd2bcf7aee..08e200a4a0 100644 --- a/panda/src/glstuff/glmisc_src.cxx +++ b/panda/src/glstuff/glmisc_src.cxx @@ -313,6 +313,13 @@ ConfigVariableEnum gl_coordinate_system "creating a shader-only application, it may be easier and " "more efficient to set this to default.")); +ConfigVariableBool gl_depth_zero_to_one + ("gl-depth-zero-to-one", false, + PRC_DESC("Normally, OpenGL uses an NDC coordinate space wherein the Z " + "ranges from -1 to 1. This setting can be used to instead use a " + "range from 0 to 1, matching other graphics APIs. This setting " + "requires OpenGL 4.5, or NVIDIA GeForce 8+ hardware.")); + extern ConfigVariableBool gl_parallel_arrays; void CLP(init_classes)() { diff --git a/panda/src/glstuff/glmisc_src.h b/panda/src/glstuff/glmisc_src.h index fb8040828f..3c6dd81e7b 100644 --- a/panda/src/glstuff/glmisc_src.h +++ b/panda/src/glstuff/glmisc_src.h @@ -40,8 +40,8 @@ // #define GSG_VERBOSE 1 -extern ConfigVariableInt gl_version; -extern EXPCL_PANDAGL ConfigVariableBool gl_support_fbo; +extern EXPCL_GL ConfigVariableInt gl_version; +extern EXPCL_GL ConfigVariableBool gl_support_fbo; extern ConfigVariableBool gl_cheap_textures; extern ConfigVariableBool gl_ignore_clamp; extern ConfigVariableBool gl_support_clamp_to_border; @@ -58,7 +58,7 @@ extern ConfigVariableBool gl_interleaved_arrays; extern ConfigVariableBool gl_parallel_arrays; extern ConfigVariableInt gl_max_errors; extern ConfigVariableEnum gl_min_buffer_usage_hint; -extern ConfigVariableBool gl_debug; +extern EXPCL_GL ConfigVariableBool gl_debug; extern ConfigVariableBool gl_debug_synchronous; extern ConfigVariableEnum gl_debug_abort_level; extern ConfigVariableBool gl_debug_object_labels; @@ -87,8 +87,8 @@ extern EXPCL_GL void CLP(init_classes)(); #if !defined(WIN32) && defined(GSG_VERBOSE) -ostream &output_gl_enum(ostream &out, GLenum v); -INLINE ostream &operator << (ostream &out, GLenum v) { +std::ostream &output_gl_enum(std::ostream &out, GLenum v); +INLINE std::ostream &operator << (std::ostream &out, GLenum v) { return output_gl_enum(out, v); } #endif diff --git a/panda/src/glxdisplay/config_glxdisplay.cxx b/panda/src/glxdisplay/config_glxdisplay.cxx index fffcd2c264..23b8aef8fa 100644 --- a/panda/src/glxdisplay/config_glxdisplay.cxx +++ b/panda/src/glxdisplay/config_glxdisplay.cxx @@ -23,8 +23,8 @@ #include "dconfig.h" #include "pandaSystem.h" -#if !defined(CPPPARSER) && !defined(BUILDING_PANDAGL) - #error Buildsystem error: BUILDING_PANDAGL not defined +#if !defined(CPPPARSER) && !defined(BUILDING_PANDA_GLXDISPLAY) + #error Buildsystem error: BUILDING_PANDA_GLXDISPLAY not defined #endif Configure(config_glxdisplay); diff --git a/panda/src/glxdisplay/config_glxdisplay.h b/panda/src/glxdisplay/config_glxdisplay.h index 7c8aadc3b9..9cabb2de39 100644 --- a/panda/src/glxdisplay/config_glxdisplay.h +++ b/panda/src/glxdisplay/config_glxdisplay.h @@ -20,9 +20,9 @@ #include "configVariableBool.h" #include "configVariableInt.h" -NotifyCategoryDecl(glxdisplay, EXPCL_PANDAGL, EXPTP_PANDAGL); +NotifyCategoryDecl(glxdisplay, EXPCL_PANDA_GLXDISPLAY, EXPTP_PANDA_GLXDISPLAY); -extern EXPCL_PANDAGL void init_libglxdisplay(); +extern EXPCL_PANDA_GLXDISPLAY void init_libglxdisplay(); extern ConfigVariableBool glx_get_proc_address; extern ConfigVariableBool glx_get_os_address; diff --git a/panda/src/glxdisplay/glxGraphicsBuffer.cxx b/panda/src/glxdisplay/glxGraphicsBuffer.cxx index fb70d352dc..d777f7a239 100644 --- a/panda/src/glxdisplay/glxGraphicsBuffer.cxx +++ b/panda/src/glxdisplay/glxGraphicsBuffer.cxx @@ -27,7 +27,7 @@ TypeHandle glxGraphicsBuffer::_type_handle; */ glxGraphicsBuffer:: glxGraphicsBuffer(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -64,7 +64,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { PStatTimer timer(_make_current_pcollector, current_thread); begin_frame_spam(mode); - if (_gsg == (GraphicsStateGuardian *)NULL || + if (_gsg == nullptr || _pbuffer == None) { return false; } @@ -105,7 +105,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { void glxGraphicsBuffer:: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); - nassertv(_gsg != (GraphicsStateGuardian *)NULL); + nassertv(_gsg != nullptr); if (mode == FM_render) { copy_to_textures(); @@ -124,8 +124,8 @@ end_frame(FrameMode mode, Thread *current_thread) { */ void glxGraphicsBuffer:: close_buffer() { - if (_gsg != (GraphicsStateGuardian *)NULL) { - glXMakeCurrent(_display, None, NULL); + if (_gsg != nullptr) { + glXMakeCurrent(_display, None, nullptr); if (_pbuffer != None) { glxGraphicsStateGuardian *glxgsg; @@ -152,9 +152,9 @@ open_buffer() { // GSG CreationInitialization glxGraphicsStateGuardian *glxgsg; - if (_gsg == 0) { + if (_gsg == nullptr) { // There is no old gsg. Create a new one. - glxgsg = new glxGraphicsStateGuardian(_engine, _pipe, NULL); + glxgsg = new glxGraphicsStateGuardian(_engine, _pipe, nullptr); glxgsg->choose_pixel_format(_fb_properties, glx_pipe->get_display(), glx_pipe->get_screen(), true, false); _gsg = glxgsg; } else { diff --git a/panda/src/glxdisplay/glxGraphicsBuffer.h b/panda/src/glxdisplay/glxGraphicsBuffer.h index e14a329db0..0ccbd6007b 100644 --- a/panda/src/glxdisplay/glxGraphicsBuffer.h +++ b/panda/src/glxdisplay/glxGraphicsBuffer.h @@ -25,7 +25,7 @@ class glxGraphicsBuffer : public GraphicsBuffer { public: glxGraphicsBuffer(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/glxdisplay/glxGraphicsPipe.cxx b/panda/src/glxdisplay/glxGraphicsPipe.cxx index cd2f082c91..e4ec8380fb 100644 --- a/panda/src/glxdisplay/glxGraphicsPipe.cxx +++ b/panda/src/glxdisplay/glxGraphicsPipe.cxx @@ -20,6 +20,8 @@ #include "config_glxdisplay.h" #include "frameBufferProperties.h" +using std::string; + TypeHandle glxGraphicsPipe::_type_handle; /** @@ -78,14 +80,14 @@ make_output(const string &name, bool &precertify) { if (!_is_valid) { - return NULL; + return nullptr; } // This may not be a GLX GSG; it might be a callback GSG. - PosixGraphicsStateGuardian *posixgsg = NULL; - glxGraphicsStateGuardian *glxgsg = NULL; - if (gsg != NULL) { - DCAST_INTO_R(posixgsg, gsg, NULL); + PosixGraphicsStateGuardian *posixgsg = nullptr; + glxGraphicsStateGuardian *glxgsg = nullptr; + if (gsg != nullptr) { + DCAST_INTO_R(posixgsg, gsg, nullptr); glxgsg = DCAST(glxGraphicsStateGuardian, posixgsg); } @@ -103,9 +105,9 @@ make_output(const string &name, // First thing to try: a glxGraphicsWindow if (retry == 0) { - if (gsg != NULL && glxgsg == NULL) { + if (gsg != nullptr && glxgsg == nullptr) { // We can't use a non-GLX GSG. - return NULL; + return nullptr; } if (((flags&BF_require_parasite)!=0)|| ((flags&BF_refuse_window)!=0)|| @@ -115,7 +117,7 @@ make_output(const string &name, ((flags&BF_can_bind_color)!=0)|| ((flags&BF_can_bind_every)!=0)|| ((flags&BF_can_bind_layered)!=0)) { - return NULL; + return nullptr; } return new glxGraphicsWindow(engine, this, name, fb_prop, win_prop, flags, gsg, host); @@ -124,9 +126,9 @@ make_output(const string &name, // Second thing to try: a GLGraphicsBuffer if (retry == 1) { - if (!gl_support_fbo || host == NULL || + if (!gl_support_fbo || host == nullptr || (flags & (BF_require_parasite | BF_require_window)) != 0) { - return NULL; + return nullptr; } // Early failure - if we are sure that this buffer WONT meet specs, we can // bail out early. @@ -134,13 +136,13 @@ make_output(const string &name, if (fb_prop.get_indexed_color() || fb_prop.get_back_buffers() > 0 || fb_prop.get_accum_bits() > 0) { - return NULL; + return nullptr; } } - if (posixgsg != NULL && posixgsg->is_valid() && !posixgsg->needs_reset()) { + if (posixgsg != nullptr && posixgsg->is_valid() && !posixgsg->needs_reset()) { if (!posixgsg->_supports_framebuffer_object || - posixgsg->_glDrawBuffers == NULL) { - return NULL; + posixgsg->_glDrawBuffers == nullptr) { + return nullptr; } else { // Early success - if we are sure that this buffer WILL meet specs, we // can precertify it. @@ -152,10 +154,10 @@ make_output(const string &name, } // Third thing to try: a glxGraphicsBuffer - if (glxgsg == NULL || glxgsg->_supports_fbconfig) { + if (glxgsg == nullptr || glxgsg->_supports_fbconfig) { if (retry == 2) { if (!glx_support_pbuffer) { - return NULL; + return nullptr; } if (((flags&BF_require_parasite)!=0)|| @@ -163,7 +165,7 @@ make_output(const string &name, ((flags&BF_resizeable)!=0)|| ((flags&BF_size_track_host)!=0)|| ((flags&BF_can_bind_layered)!=0)) { - return NULL; + return nullptr; } if (!support_rtt) { @@ -171,7 +173,7 @@ make_output(const string &name, ((flags&BF_can_bind_every)!=0)) { // If we require Render-to-Texture, but can't be sure we support it, // bail. - return NULL; + return nullptr; } } @@ -183,7 +185,7 @@ make_output(const string &name, // Third thing to try: a glxGraphicsPixmap. if (retry == 3) { if (!glx_support_pixmap) { - return NULL; + return nullptr; } if (((flags&BF_require_parasite)!=0)|| @@ -191,12 +193,12 @@ make_output(const string &name, ((flags&BF_resizeable)!=0)|| ((flags&BF_size_track_host)!=0)|| ((flags&BF_can_bind_layered)!=0)) { - return NULL; + return nullptr; } if (((flags&BF_rtt_cumulative)!=0)|| ((flags&BF_can_bind_every)!=0)) { - return NULL; + return nullptr; } return new glxGraphicsPixmap(engine, this, name, fb_prop, win_prop, @@ -204,7 +206,7 @@ make_output(const string &name, } // Nothing else left to try. - return NULL; + return nullptr; } /** diff --git a/panda/src/glxdisplay/glxGraphicsPipe.h b/panda/src/glxdisplay/glxGraphicsPipe.h index 25ff9a7fd1..1d08297ab2 100644 --- a/panda/src/glxdisplay/glxGraphicsPipe.h +++ b/panda/src/glxdisplay/glxGraphicsPipe.h @@ -75,14 +75,14 @@ class FrameBufferProperties; */ class glxGraphicsPipe : public x11GraphicsPipe { public: - glxGraphicsPipe(const string &display = string()); + glxGraphicsPipe(const std::string &display = std::string()); virtual ~glxGraphicsPipe() {}; - virtual string get_interface_name() const; + virtual std::string get_interface_name() const; static PT(GraphicsPipe) pipe_constructor(); protected: - virtual PT(GraphicsOutput) make_output(const string &name, + virtual PT(GraphicsOutput) make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/glxdisplay/glxGraphicsPixmap.cxx b/panda/src/glxdisplay/glxGraphicsPixmap.cxx index 8c8c5a330d..7f551b8d4f 100644 --- a/panda/src/glxdisplay/glxGraphicsPixmap.cxx +++ b/panda/src/glxdisplay/glxGraphicsPixmap.cxx @@ -28,7 +28,7 @@ TypeHandle glxGraphicsPixmap::_type_handle; */ glxGraphicsPixmap:: glxGraphicsPixmap(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -67,7 +67,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { PStatTimer timer(_make_current_pcollector, current_thread); begin_frame_spam(mode); - if (_gsg == (GraphicsStateGuardian *)NULL || + if (_gsg == nullptr || _glx_pixmap == None) { return false; } @@ -108,7 +108,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { void glxGraphicsPixmap:: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); - nassertv(_gsg != (GraphicsStateGuardian *)NULL); + nassertv(_gsg != nullptr); if (mode == FM_render) { copy_to_textures(); @@ -127,8 +127,8 @@ end_frame(FrameMode mode, Thread *current_thread) { */ void glxGraphicsPixmap:: close_buffer() { - if (_gsg != (GraphicsStateGuardian *)NULL) { - glXMakeCurrent(_display, None, NULL); + if (_gsg != nullptr) { + glXMakeCurrent(_display, None, nullptr); _gsg.clear(); } @@ -156,9 +156,9 @@ open_buffer() { // GSG CreationInitialization glxGraphicsStateGuardian *glxgsg; - if (_gsg == 0) { + if (_gsg == nullptr) { // There is no old gsg. Create a new one. - glxgsg = new glxGraphicsStateGuardian(_engine, _pipe, NULL); + glxgsg = new glxGraphicsStateGuardian(_engine, _pipe, nullptr); glxgsg->choose_pixel_format(_fb_properties, _display, glx_pipe->get_screen(), false, true); _gsg = glxgsg; } else { @@ -179,7 +179,7 @@ open_buffer() { } XVisualInfo *visual_info = glxgsg->_visual; - if (visual_info == NULL) { + if (visual_info == nullptr) { // No X visual for this fbconfig; how can we create the pixmap? glxdisplay_cat.error() << "No X visual: cannot create pixmap.\n"; @@ -187,7 +187,7 @@ open_buffer() { } _drawable = glx_pipe->get_root(); - if (_host != NULL) { + if (_host != nullptr) { if (_host->is_of_type(glxGraphicsWindow::get_class_type())) { glxGraphicsWindow *win = DCAST(glxGraphicsWindow, _host); _drawable = win->get_xwindow(); @@ -208,7 +208,7 @@ open_buffer() { if (glxgsg->_fbconfig) { // Use the FBConfig to create the pixmap. - _glx_pixmap = glxgsg->_glXCreatePixmap(_display, glxgsg->_fbconfig, _x_pixmap, NULL); + _glx_pixmap = glxgsg->_glXCreatePixmap(_display, glxgsg->_fbconfig, _x_pixmap, nullptr); } else { // Use the XVisual to create the pixmap. _glx_pixmap = glXCreateGLXPixmap(_display, visual_info, _x_pixmap); diff --git a/panda/src/glxdisplay/glxGraphicsPixmap.h b/panda/src/glxdisplay/glxGraphicsPixmap.h index 7c724d4d71..9cc542fbcc 100644 --- a/panda/src/glxdisplay/glxGraphicsPixmap.h +++ b/panda/src/glxdisplay/glxGraphicsPixmap.h @@ -28,7 +28,7 @@ class glxGraphicsPixmap : public GraphicsBuffer { public: glxGraphicsPixmap(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/glxdisplay/glxGraphicsStateGuardian.cxx b/panda/src/glxdisplay/glxGraphicsStateGuardian.cxx index e79f80be3e..76c66d817e 100644 --- a/panda/src/glxdisplay/glxGraphicsStateGuardian.cxx +++ b/panda/src/glxdisplay/glxGraphicsStateGuardian.cxx @@ -18,6 +18,8 @@ #include +using std::string; + TypeHandle glxGraphicsStateGuardian::_type_handle; @@ -29,13 +31,13 @@ glxGraphicsStateGuardian(GraphicsEngine *engine, GraphicsPipe *pipe, glxGraphicsStateGuardian *share_with) : PosixGraphicsStateGuardian(engine, pipe) { - _share_context=0; - _context=0; - _display=0; + _share_context=nullptr; + _context=nullptr; + _display=nullptr; _screen=0; - _visual=0; - _visuals=0; - _fbconfig=0; + _visual=nullptr; + _visuals=nullptr; + _fbconfig=nullptr; _context_has_pbuffer = false; _context_has_pixmap = false; _slow = false; @@ -45,16 +47,16 @@ glxGraphicsStateGuardian(GraphicsEngine *engine, GraphicsPipe *pipe, _supports_pbuffer = false; _uses_sgix_pbuffer = false; - if (share_with != (glxGraphicsStateGuardian *)NULL) { + if (share_with != nullptr) { _prepared_objects = share_with->get_prepared_objects(); _share_context = share_with->_context; } _checked_get_proc_address = false; - _glXGetProcAddress = NULL; - _temp_context = (GLXContext)NULL; - _temp_xwindow = (X11_Window)NULL; - _temp_colormap = (Colormap)NULL; + _glXGetProcAddress = nullptr; + _temp_context = (GLXContext)nullptr; + _temp_xwindow = (X11_Window)nullptr; + _temp_colormap = (Colormap)nullptr; } /** @@ -63,12 +65,12 @@ glxGraphicsStateGuardian(GraphicsEngine *engine, GraphicsPipe *pipe, glxGraphicsStateGuardian:: ~glxGraphicsStateGuardian() { destroy_temp_xwindow(); - if (_visuals != (XVisualInfo *)NULL) { + if (_visuals != nullptr) { XFree(_visuals); } - if (_context != (GLXContext)NULL) { + if (_context != (GLXContext)nullptr) { glXDestroyContext(_display, _context); - _context = (GLXContext)NULL; + _context = (GLXContext)nullptr; } } @@ -224,12 +226,12 @@ choose_pixel_format(const FrameBufferProperties &properties, _display = display; _screen = screen; - _context = 0; - _fbconfig = 0; - _visual = 0; - if (_visuals != (XVisualInfo *)NULL) { + _context = nullptr; + _fbconfig = nullptr; + _visual = nullptr; + if (_visuals != nullptr) { XFree(_visuals); - _visuals = NULL; + _visuals = nullptr; } _fbprops.clear(); @@ -239,7 +241,7 @@ choose_pixel_format(const FrameBufferProperties &properties, // OpenGL context to get the required extension function pointers. destroy_temp_xwindow(); choose_temp_visual(properties); - if (_temp_context == NULL) { + if (_temp_context == nullptr) { // No good. return; } @@ -257,7 +259,7 @@ choose_pixel_format(const FrameBufferProperties &properties, << _fbprops << "\n"; _context = _temp_context; - _temp_context = (GLXContext)NULL; + _temp_context = (GLXContext)nullptr; // By convention, every indirect XVisual that can render to a window can // also render to a GLXPixmap. Direct visuals we're not as sure about. @@ -297,7 +299,7 @@ choose_pixel_format(const FrameBufferProperties &properties, GLXFBConfig *configs = _glXChooseFBConfig(_display, _screen, attrib_list, &num_configs); - if (configs != 0) { + if (configs != nullptr) { bool context_has_pbuffer, context_has_pixmap, slow; int quality, i; for (i = 0; i < num_configs; ++i) { @@ -332,7 +334,7 @@ choose_pixel_format(const FrameBufferProperties &properties, if (best_quality > 0) { _fbconfig = configs[best_result]; - if (_glXCreateContextAttribs != NULL) { + if (_glXCreateContextAttribs != nullptr) { // NB. This is a wholly different type of attrib list than below, the // same values are not used! n = 0; @@ -362,9 +364,9 @@ choose_pixel_format(const FrameBufferProperties &properties, if (_context) { mark_new(); - if (_visuals != (XVisualInfo *)NULL) { + if (_visuals != nullptr) { XFree(_visuals); - _visuals = NULL; + _visuals = nullptr; } _visuals = _glXGetVisualFromFBConfig(_display, _fbconfig); _visual = _visuals; @@ -391,10 +393,10 @@ choose_pixel_format(const FrameBufferProperties &properties, // This really shouldn't happen, so I'm not too careful about cleanup. glxdisplay_cat.error() << "Could not create FBConfig context!\n"; - _fbconfig = 0; - _context = 0; - _visual = 0; - _visuals = 0; + _fbconfig = nullptr; + _context = nullptr; + _visual = nullptr; + _visuals = nullptr; } glxdisplay_cat.warning() @@ -402,7 +404,7 @@ choose_pixel_format(const FrameBufferProperties &properties, << _fbprops << "\n"; _context = _temp_context; - _temp_context = (GLXContext)NULL; + _temp_context = (GLXContext)nullptr; // By convention, every indirect XVisual that can render to a window can // also render to a GLXPixmap. Direct visuals we're not as sure about. @@ -492,7 +494,7 @@ get_extra_extensions() { */ void *glxGraphicsStateGuardian:: do_get_extension_func(const char *name) { - nassertr(name != NULL, NULL); + nassertr(name != nullptr, nullptr); if (glx_get_proc_address) { // First, check if we have glXGetProcAddress available. This will be @@ -514,7 +516,7 @@ do_get_extension_func(const char *name) { // Otherwise, we have to fiddle around with the dynamic runtime. if (!_checked_get_proc_address) { - const char *funcName = NULL; + const char *funcName = nullptr; if (glx_is_at_least_version(1, 4)) { funcName = "glXGetProcAddress"; @@ -523,9 +525,9 @@ do_get_extension_func(const char *name) { funcName = "glXGetProcAddressARB"; } - if (funcName != NULL) { + if (funcName != nullptr) { _glXGetProcAddress = (PFNGLXGETPROCADDRESSPROC)get_system_func(funcName); - if (_glXGetProcAddress == NULL) { + if (_glXGetProcAddress == nullptr) { glxdisplay_cat.warning() << "Couldn't load function " << funcName << ", GL extensions may be unavailable.\n"; @@ -536,7 +538,7 @@ do_get_extension_func(const char *name) { } // Use glxGetProcAddress() if we've got it; it should be more robust. - if (_glXGetProcAddress != NULL) { + if (_glXGetProcAddress != nullptr) { return (void *)_glXGetProcAddress((const GLubyte *)name); } #endif // HAVE_GLXGETPROCADDRESS @@ -556,7 +558,7 @@ query_glx_extensions() { if (_supports_swap_control) { _glXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC)get_extension_func("glXSwapIntervalSGI"); - if (_glXSwapIntervalSGI == NULL) { + if (_glXSwapIntervalSGI == nullptr) { glxdisplay_cat.error() << "Driver claims to support GLX_SGI_swap_control extension, but does not define all functions.\n"; _supports_swap_control = false; @@ -585,11 +587,11 @@ query_glx_extensions() { _glXCreatePixmap = (PFNGLXCREATEPIXMAPPROC)get_extension_func("glXCreatePixmap"); - if (_glXChooseFBConfig == NULL || - _glXCreateNewContext == NULL || - _glXGetVisualFromFBConfig == NULL || - _glXGetFBConfigAttrib == NULL || - _glXCreatePixmap == NULL) { + if (_glXChooseFBConfig == nullptr || + _glXCreateNewContext == nullptr || + _glXGetVisualFromFBConfig == nullptr || + _glXGetFBConfigAttrib == nullptr || + _glXCreatePixmap == nullptr) { glxdisplay_cat.error() << "Driver claims to support GLX_fbconfig extension, but does not define all functions.\n"; _supports_fbconfig = false; @@ -611,11 +613,11 @@ query_glx_extensions() { _glXCreatePixmap = (PFNGLXCREATEPIXMAPPROC)get_extension_func("glXCreateGLXPixmapWithConfigSGIX"); - if (_glXChooseFBConfig == NULL || - _glXCreateNewContext == NULL || - _glXGetVisualFromFBConfig == NULL || - _glXGetFBConfigAttrib == NULL || - _glXCreatePixmap == NULL) { + if (_glXChooseFBConfig == nullptr || + _glXCreateNewContext == nullptr || + _glXGetVisualFromFBConfig == nullptr || + _glXGetFBConfigAttrib == nullptr || + _glXCreatePixmap == nullptr) { glxdisplay_cat.error() << "Driver claims to support GLX_SGIX_fbconfig extension, but does not define all functions.\n"; _supports_fbconfig = false; @@ -629,11 +631,11 @@ query_glx_extensions() { _glXCreatePbuffer = (PFNGLXCREATEPBUFFERPROC)get_extension_func("glXCreatePbuffer"); - _glXCreateGLXPbufferSGIX = NULL; + _glXCreateGLXPbufferSGIX = nullptr; _glXDestroyPbuffer = (PFNGLXDESTROYPBUFFERPROC)get_extension_func("glXDestroyPbuffer"); - if (_glXCreatePbuffer == NULL || - _glXDestroyPbuffer == NULL) { + if (_glXCreatePbuffer == nullptr || + _glXDestroyPbuffer == nullptr) { glxdisplay_cat.error() << "Driver claims to support GLX_pbuffer extension, but does not define all functions.\n"; _supports_pbuffer = false; @@ -646,13 +648,13 @@ query_glx_extensions() { // CreatePbuffer has a different form between SGIX and 1.3, however, so // we must treat it specially. But we can use the same function pointer // for DestroyPbuffer. - _glXCreatePbuffer = NULL; + _glXCreatePbuffer = nullptr; _glXCreateGLXPbufferSGIX = (PFNGLXCREATEGLXPBUFFERSGIXPROC)get_extension_func("glXCreateGLXPbufferSGIX"); _glXDestroyPbuffer = (PFNGLXDESTROYPBUFFERPROC)get_extension_func("glXDestroyGLXPbufferSGIX"); - if (_glXCreateGLXPbufferSGIX == NULL || - _glXDestroyPbuffer == NULL) { + if (_glXCreateGLXPbufferSGIX == nullptr || + _glXDestroyPbuffer == nullptr) { glxdisplay_cat.error() << "Driver claims to support GLX_SGIX_pbuffer extension, but does not define all functions.\n"; _supports_pbuffer = false; @@ -663,7 +665,7 @@ query_glx_extensions() { _glXCreateContextAttribs = (PFNGLXCREATECONTEXTATTRIBSARBPROC)get_extension_func("glXCreateContextAttribsARB"); } else { - _glXCreateContextAttribs = NULL; + _glXCreateContextAttribs = nullptr; } } @@ -697,7 +699,7 @@ void glxGraphicsStateGuardian:: show_glx_client_string(const string &name, int id) { if (glgsg_cat.is_debug()) { const char *text = glXGetClientString(_display, id); - if (text == (const char *)NULL) { + if (text == nullptr) { glgsg_cat.debug() << "Unable to query " << name << " (client)\n"; } else { @@ -714,7 +716,7 @@ void glxGraphicsStateGuardian:: show_glx_server_string(const string &name, int id) { if (glgsg_cat.is_debug()) { const char *text = glXQueryServerString(_display, _screen, id); - if (text == (const char *)NULL) { + if (text == nullptr) { glgsg_cat.debug() << "Unable to query " << name << " (server)\n"; } else { @@ -732,20 +734,20 @@ show_glx_server_string(const string &name, int id) { */ void glxGraphicsStateGuardian:: choose_temp_visual(const FrameBufferProperties &properties) { - nassertv(_temp_context == (GLXContext)NULL); + nassertv(_temp_context == (GLXContext)nullptr); int best_quality = 0; int best_result = 0; FrameBufferProperties best_props; // Scan available visuals. - if (_visuals != (XVisualInfo *)NULL) { + if (_visuals != nullptr) { XFree(_visuals); - _visuals = NULL; + _visuals = nullptr; } int nvisuals = 0; - _visuals = XGetVisualInfo(_display, 0, 0, &nvisuals); - if (_visuals != 0) { + _visuals = XGetVisualInfo(_display, 0, nullptr, &nvisuals); + if (_visuals != nullptr) { for (int i = 0; i < nvisuals; i++) { FrameBufferProperties fbprops; get_properties(fbprops, _visuals + i); @@ -794,7 +796,7 @@ init_temp_context() { (_display, root_window, 0, 0, 100, 100, 0, _visual->depth, InputOutput, visual, attrib_mask, &wa); - if (_temp_xwindow == (X11_Window)NULL) { + if (_temp_xwindow == (X11_Window)nullptr) { glxdisplay_cat.error() << "Could not create temporary window for context\n"; return; @@ -812,19 +814,19 @@ init_temp_context() { */ void glxGraphicsStateGuardian:: destroy_temp_xwindow() { - glXMakeCurrent(_display, None, NULL); + glXMakeCurrent(_display, None, nullptr); - if (_temp_colormap != (Colormap)NULL) { + if (_temp_colormap != (Colormap)nullptr) { XFreeColormap(_display, _temp_colormap); - _temp_colormap = (Colormap)NULL; + _temp_colormap = (Colormap)nullptr; } - if (_temp_xwindow != (X11_Window)NULL) { + if (_temp_xwindow != (X11_Window)nullptr) { XDestroyWindow(_display, _temp_xwindow); - _temp_xwindow = (X11_Window)NULL; + _temp_xwindow = (X11_Window)nullptr; } - if (_temp_context != (GLXContext)NULL) { + if (_temp_context != (GLXContext)nullptr) { glXDestroyContext(_display, _temp_context); - _temp_context = (GLXContext)NULL; + _temp_context = (GLXContext)nullptr; } } diff --git a/panda/src/glxdisplay/glxGraphicsStateGuardian.h b/panda/src/glxdisplay/glxGraphicsStateGuardian.h index 7d31b6d8a9..4470f00d0b 100644 --- a/panda/src/glxdisplay/glxGraphicsStateGuardian.h +++ b/panda/src/glxdisplay/glxGraphicsStateGuardian.h @@ -131,8 +131,8 @@ protected: private: void query_glx_extensions(); - void show_glx_client_string(const string &name, int id); - void show_glx_server_string(const string &name, int id); + void show_glx_client_string(const std::string &name, int id); + void show_glx_server_string(const std::string &name, int id); void choose_temp_visual(const FrameBufferProperties &properties); void init_temp_context(); void destroy_temp_xwindow(); diff --git a/panda/src/glxdisplay/glxGraphicsWindow.cxx b/panda/src/glxdisplay/glxGraphicsWindow.cxx index 7dd43c8675..a7a2472a84 100644 --- a/panda/src/glxdisplay/glxGraphicsWindow.cxx +++ b/panda/src/glxdisplay/glxGraphicsWindow.cxx @@ -36,7 +36,7 @@ TypeHandle glxGraphicsWindow::_type_handle; */ glxGraphicsWindow:: glxGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -57,7 +57,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { PStatTimer timer(_make_current_pcollector, current_thread); begin_frame_spam(mode); - if (_gsg == (GraphicsStateGuardian *)NULL) { + if (_gsg == nullptr) { return false; } if (_awaiting_configure) { @@ -106,7 +106,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { */ void glxGraphicsWindow:: end_flip() { - if (_gsg != (GraphicsStateGuardian *)NULL && _flip_ready) { + if (_gsg != nullptr && _flip_ready) { // It doesn't appear to be necessary to ensure the graphics context is // current before flipping the windows, and insisting on doing so can be a @@ -125,8 +125,8 @@ end_flip() { */ void glxGraphicsWindow:: close_window() { - if (_gsg != (GraphicsStateGuardian *)NULL) { - glXMakeCurrent(_display, None, NULL); + if (_gsg != nullptr) { + glXMakeCurrent(_display, None, nullptr); _gsg.clear(); } @@ -144,9 +144,9 @@ open_window() { // GSG CreationInitialization glxGraphicsStateGuardian *glxgsg; - if (_gsg == 0) { + if (_gsg == nullptr) { // There is no old gsg. Create a new one. - glxgsg = new glxGraphicsStateGuardian(_engine, _pipe, NULL); + glxgsg = new glxGraphicsStateGuardian(_engine, _pipe, nullptr); glxgsg->choose_pixel_format(_fb_properties, glx_pipe->get_display(), glx_pipe->get_screen(), false, false); _gsg = glxgsg; } else { @@ -160,7 +160,7 @@ open_window() { } } - if (glxgsg->_context == NULL) { + if (glxgsg->_context == nullptr) { // We're supposed to have a context at this point. glxdisplay_cat.error() << "No GLX context: cannot open window.\n"; @@ -168,7 +168,7 @@ open_window() { } _visual_info = glxgsg->_visual; - if (_visual_info == NULL) { + if (_visual_info == nullptr) { // No X visual for this fbconfig; how can we open the window? glxdisplay_cat.error() << "No X visual: cannot open window.\n"; @@ -212,7 +212,7 @@ setup_colormap(GLXFBConfig fbconfig) { nassertv(glxgsg->_supports_fbconfig); XVisualInfo *visual_info = glxgsg->_glXGetVisualFromFBConfig(_display, fbconfig); - if (visual_info == NULL) { + if (visual_info == nullptr) { // No X visual; no need to set up a colormap. return; } diff --git a/panda/src/glxdisplay/glxGraphicsWindow.h b/panda/src/glxdisplay/glxGraphicsWindow.h index d89ab1552b..4c583c186c 100644 --- a/panda/src/glxdisplay/glxGraphicsWindow.h +++ b/panda/src/glxdisplay/glxGraphicsWindow.h @@ -27,7 +27,7 @@ class glxGraphicsWindow : public x11GraphicsWindow { public: glxGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/glxdisplay/posixGraphicsStateGuardian.cxx b/panda/src/glxdisplay/posixGraphicsStateGuardian.cxx index 8bf738b3c2..ac5f10f8a1 100644 --- a/panda/src/glxdisplay/posixGraphicsStateGuardian.cxx +++ b/panda/src/glxdisplay/posixGraphicsStateGuardian.cxx @@ -24,7 +24,7 @@ PosixGraphicsStateGuardian:: PosixGraphicsStateGuardian(GraphicsEngine *engine, GraphicsPipe *pipe) : GLGraphicsStateGuardian(engine, pipe) { - _libgl_handle = NULL; + _libgl_handle = nullptr; } /** @@ -32,7 +32,7 @@ PosixGraphicsStateGuardian(GraphicsEngine *engine, GraphicsPipe *pipe) : */ PosixGraphicsStateGuardian:: ~PosixGraphicsStateGuardian() { - if (_libgl_handle != (void *)NULL) { + if (_libgl_handle != nullptr) { dlclose(_libgl_handle); } } @@ -45,13 +45,13 @@ PosixGraphicsStateGuardian:: */ void *PosixGraphicsStateGuardian:: do_get_extension_func(const char *name) { - nassertr(name != NULL, NULL); + nassertr(name != nullptr, nullptr); if (glx_get_os_address) { return get_system_func(name); } - return NULL; + return nullptr; } /** @@ -61,23 +61,23 @@ do_get_extension_func(const char *name) { */ void *PosixGraphicsStateGuardian:: get_system_func(const char *name) { - if (_libgl_handle == (void *)NULL) { + if (_libgl_handle == nullptr) { // We open the current executable, rather than naming a particular // library. Presumably libGL.so (or whatever the library should be // called) is already available in the current executable address space, // so this is more portable than insisting on a particular shared library // name. - _libgl_handle = dlopen(NULL, RTLD_LAZY); - nassertr(_libgl_handle != (void *)NULL, NULL); + _libgl_handle = dlopen(nullptr, RTLD_LAZY); + nassertr(_libgl_handle != nullptr, nullptr); // If that doesn't locate the symbol we expected, then fall back to // loading the GL library by its usual name. - if (dlsym(_libgl_handle, name) == NULL) { + if (dlsym(_libgl_handle, name) == nullptr) { dlclose(_libgl_handle); glxdisplay_cat.warning() << name << " not found in executable; looking in libGL.so instead.\n"; _libgl_handle = dlopen("libGL.so", RTLD_LAZY); - nassertr(_libgl_handle != (void *)NULL, NULL); + nassertr(_libgl_handle != nullptr, nullptr); } } diff --git a/panda/src/gobj/adaptiveLru.I b/panda/src/gobj/adaptiveLru.I index 77c3fcd5de..41acf47c38 100644 --- a/panda/src/gobj/adaptiveLru.I +++ b/panda/src/gobj/adaptiveLru.I @@ -134,7 +134,7 @@ get_lru() const { */ INLINE void AdaptiveLruPage:: dequeue_lru() { - enqueue_lru(NULL); + enqueue_lru(nullptr); } /** @@ -146,7 +146,7 @@ dequeue_lru() { */ INLINE void AdaptiveLruPage:: mark_used_lru() const { - if (_lru != (AdaptiveLru *)NULL) { + if (_lru != nullptr) { ((AdaptiveLruPage *)this)->mark_used_lru(_lru); } } @@ -174,7 +174,7 @@ get_lru_size() const { */ INLINE void AdaptiveLruPage:: set_lru_size(size_t lru_size) { - if (_lru != (AdaptiveLru *)NULL) { + if (_lru != nullptr) { LightMutexHolder holder(_lru->_lock); _lru->_total_size -= _lru_size; _lru->_total_size += lru_size; diff --git a/panda/src/gobj/adaptiveLru.cxx b/panda/src/gobj/adaptiveLru.cxx index a74fcfcb0d..54ed81a3c8 100644 --- a/panda/src/gobj/adaptiveLru.cxx +++ b/panda/src/gobj/adaptiveLru.cxx @@ -16,6 +16,9 @@ #include "clockObject.h" #include "indent.h" +using std::cerr; +using std::ostream; + static const int HIGH_PRIORITY_SCALE = 4; static const int LOW_PRIORITY_RANGE = 25; @@ -23,7 +26,7 @@ static const int LOW_PRIORITY_RANGE = 25; * */ AdaptiveLru:: -AdaptiveLru(const string &name, size_t max_size) : +AdaptiveLru(const std::string &name, size_t max_size) : Namable(name) { _total_size = 0; @@ -55,10 +58,10 @@ AdaptiveLru:: // to disk unnecessarily). while (_static_list._next != &_static_list) { - nassertv(_static_list._next != (LinkedListNode *)NULL); + nassertv(_static_list._next != nullptr); AdaptiveLruPage *page = (AdaptiveLruPage *)(AdaptiveLruPageStaticList *)_static_list._next; - page->_lru = NULL; + page->_lru = nullptr; ((AdaptiveLruPageDynamicList *)page)->remove_from_list(); ((AdaptiveLruPageStaticList *)page)->remove_from_list(); } @@ -156,7 +159,7 @@ update_page(AdaptiveLruPage *page) { } if (target_priority != page->_priority) { - page->_priority = min(max(target_priority, 0), LPP_TotalPriorities - 1); + page->_priority = std::min(std::max(target_priority, 0), LPP_TotalPriorities - 1); ((AdaptiveLruPageDynamicList *)page)->remove_from_list(); ((AdaptiveLruPageDynamicList *)page)->insert_before(&_page_array[page->_priority]); } @@ -170,19 +173,19 @@ update_page(AdaptiveLruPage *page) { */ void AdaptiveLruPage:: enqueue_lru(AdaptiveLru *lru) { - if (lru != _lru && _lru != (AdaptiveLru *)NULL) { + if (lru != _lru && _lru != nullptr) { // It was previously on a different LRU. Remove it first. _lru->do_remove_page(this); - _lru = NULL; + _lru = nullptr; } if (lru == _lru) { - if (_lru != (AdaptiveLru *)NULL) { + if (_lru != nullptr) { // It's already on this LRU. Access it. _lru->do_access_page(this); } } else { - nassertv(lru != (AdaptiveLru *)NULL); + nassertv(lru != nullptr); // Add it to a new LRU. _lru = lru; @@ -281,7 +284,7 @@ write(ostream &out, int indent_level) const { */ void AdaptiveLru:: do_add_page(AdaptiveLruPage *page) { - nassertv(page != (AdaptiveLruPage *)NULL && page->_lru == this); + nassertv(page != nullptr && page->_lru == this); LightMutexHolder holder(_lock); _total_size += page->_lru_size; @@ -294,7 +297,7 @@ do_add_page(AdaptiveLruPage *page) { */ void AdaptiveLru:: do_remove_page(AdaptiveLruPage *page) { - nassertv(page != (AdaptiveLruPage *)NULL && page->_lru == this); + nassertv(page != nullptr && page->_lru == this); LightMutexHolder holder(_lock); _total_size -= page->_lru_size; @@ -307,7 +310,7 @@ do_remove_page(AdaptiveLruPage *page) { */ void AdaptiveLru:: do_access_page(AdaptiveLruPage *page) { - nassertv(page != (AdaptiveLruPage *)NULL && page->_lru == this); + nassertv(page != nullptr && page->_lru == this); LightMutexHolder holder(_lock); if (page->_current_frame_identifier == _current_frame_identifier) { @@ -360,9 +363,9 @@ do_evict_to(size_t target_size, bool hard_evict) { } else { // We must release the lock while we call evict_lru(). - _lock.release(); + _lock.unlock(); page->evict_lru(); - _lock.acquire(); + _lock.lock(); if (_total_size <= target_size) { // We've evicted enough to satisfy our target. @@ -447,7 +450,7 @@ do_validate() { */ AdaptiveLruPage:: AdaptiveLruPage(size_t lru_size) : - _lru(NULL), + _lru(nullptr), _lru_size(lru_size), _priority(0), _first_frame_identifier(0), @@ -455,7 +458,6 @@ AdaptiveLruPage(size_t lru_size) : _update_frame_identifier(0), _current_frame_usage(0), _last_frame_usage(0), - _total_usage(0), _update_total_usage(0), _average_frame_utilization(1.0f) { @@ -466,7 +468,7 @@ AdaptiveLruPage(size_t lru_size) : */ AdaptiveLruPage:: AdaptiveLruPage(const AdaptiveLruPage ©) : - _lru(NULL), + _lru(nullptr), _lru_size(copy._lru_size), _priority(0), _first_frame_identifier(0), @@ -474,7 +476,6 @@ AdaptiveLruPage(const AdaptiveLruPage ©) : _update_frame_identifier(0), _current_frame_usage(0), _last_frame_usage(0), - _total_usage(0), _update_total_usage(0), _average_frame_utilization(1.0f) { @@ -493,7 +494,7 @@ operator = (const AdaptiveLruPage ©) { */ AdaptiveLruPage:: ~AdaptiveLruPage() { - if (_lru != NULL) { + if (_lru != nullptr) { dequeue_lru(); } } @@ -535,7 +536,7 @@ write(ostream &out, int indent_level) const { */ unsigned int AdaptiveLruPage:: get_num_frames() const { - if (_lru == (AdaptiveLru *)NULL) { + if (_lru == nullptr) { return 0; } return _lru->_current_frame_identifier - _first_frame_identifier; @@ -547,7 +548,7 @@ get_num_frames() const { */ unsigned int AdaptiveLruPage:: get_num_inactive_frames() const { - if (_lru == (AdaptiveLru *)NULL) { + if (_lru == nullptr) { return 0; } return _lru->_current_frame_identifier - _current_frame_identifier; diff --git a/panda/src/gobj/adaptiveLru.h b/panda/src/gobj/adaptiveLru.h index 99b78b482d..e01fa02bfb 100644 --- a/panda/src/gobj/adaptiveLru.h +++ b/panda/src/gobj/adaptiveLru.h @@ -44,7 +44,7 @@ public: */ class EXPCL_PANDA_GOBJ AdaptiveLru : public Namable { PUBLISHED: - explicit AdaptiveLru(const string &name, size_t max_size); + explicit AdaptiveLru(const std::string &name, size_t max_size); ~AdaptiveLru(); INLINE size_t get_total_size() const; @@ -58,8 +58,8 @@ PUBLISHED: INLINE bool validate(); - void output(ostream &out) const; - void write(ostream &out, int indent_level) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level) const; // The following methods are specific to AdaptiveLru, and do not exist in // the SimpleLru implementation. In most cases, the defaults will be @@ -153,8 +153,8 @@ PUBLISHED: virtual void evict_lru(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; // Not defined in SimpleLruPage. unsigned int get_num_frames() const; @@ -172,7 +172,6 @@ private: int _current_frame_usage; int _last_frame_usage; - int _total_usage; int _update_total_usage; PN_stdfloat _average_frame_utilization; @@ -180,12 +179,12 @@ private: friend class AdaptiveLru; }; -inline ostream &operator << (ostream &out, const AdaptiveLru &lru) { +inline std::ostream &operator << (std::ostream &out, const AdaptiveLru &lru) { lru.output(out); return out; } -inline ostream &operator << (ostream &out, const AdaptiveLruPage &page) { +inline std::ostream &operator << (std::ostream &out, const AdaptiveLruPage &page) { page.output(out); return out; } diff --git a/panda/src/gobj/animateVerticesRequest.h b/panda/src/gobj/animateVerticesRequest.h index be20651a13..0d804a927d 100644 --- a/panda/src/gobj/animateVerticesRequest.h +++ b/panda/src/gobj/animateVerticesRequest.h @@ -30,7 +30,7 @@ * requests are being run (presumably on multiple CPUs/cores), to ensure that * the data has been computed by the time it's needed. */ -class EXPCL_PANDA_PGRAPH AnimateVerticesRequest : public AsyncTask { +class EXPCL_PANDA_GOBJ AnimateVerticesRequest : public AsyncTask { public: ALLOC_DELETED_CHAIN(AnimateVerticesRequest); diff --git a/panda/src/gobj/bufferContext.I b/panda/src/gobj/bufferContext.I index 978e3b73da..3c34d93a8a 100644 --- a/panda/src/gobj/bufferContext.I +++ b/panda/src/gobj/bufferContext.I @@ -85,9 +85,9 @@ set_resident(bool flag) { */ INLINE BufferContext *BufferContext:: get_next() const { - nassertr(_owning_chain != (BufferContextChain *)NULL, NULL); + nassertr(_owning_chain != nullptr, nullptr); if ((BufferContextChain *)_next == _owning_chain) { - return NULL; + return nullptr; } return (BufferContext *)_next; } @@ -98,7 +98,7 @@ get_next() const { */ INLINE void BufferContext:: update_data_size_bytes(size_t new_data_size_bytes) { - if (_owning_chain != (BufferContextChain *)NULL) { + if (_owning_chain != nullptr) { _owning_chain->adjust_bytes((int)new_data_size_bytes - (int)_data_size_bytes); } _data_size_bytes = new_data_size_bytes; diff --git a/panda/src/gobj/bufferContext.cxx b/panda/src/gobj/bufferContext.cxx index b8d7ed4ba8..52cac06ce4 100644 --- a/panda/src/gobj/bufferContext.cxx +++ b/panda/src/gobj/bufferContext.cxx @@ -23,7 +23,7 @@ BufferContext(BufferResidencyTracker *residency) : _residency(residency), _residency_state(0), _data_size_bytes(0), - _owning_chain(NULL) + _owning_chain(nullptr) { set_owning_chain(&residency->_chains[0]); } @@ -33,7 +33,7 @@ BufferContext(BufferResidencyTracker *residency) : */ BufferContext:: ~BufferContext() { - set_owning_chain(NULL); + set_owning_chain(nullptr); } /** @@ -42,7 +42,7 @@ BufferContext:: void BufferContext:: set_owning_chain(BufferContextChain *chain) { if (chain != _owning_chain) { - if (_owning_chain != (BufferContextChain *)NULL){ + if (_owning_chain != nullptr){ --(_owning_chain->_count); _owning_chain->adjust_bytes(-(int)_data_size_bytes); remove_from_list(); @@ -50,7 +50,7 @@ set_owning_chain(BufferContextChain *chain) { _owning_chain = chain; - if (_owning_chain != (BufferContextChain *)NULL) { + if (_owning_chain != nullptr) { ++(_owning_chain->_count); _owning_chain->adjust_bytes((int)_data_size_bytes); insert_before(_owning_chain); diff --git a/panda/src/gobj/bufferContextChain.cxx b/panda/src/gobj/bufferContextChain.cxx index a5f9d782b5..4f27c90c88 100644 --- a/panda/src/gobj/bufferContextChain.cxx +++ b/panda/src/gobj/bufferContextChain.cxx @@ -25,7 +25,7 @@ get_first() { // This method is declared non-inline so we can include bufferContext.h, // which is necessary for proper downcasting of the _next pointer. if (_next == this) { - return NULL; + return nullptr; } return (BufferContext *)_next; } @@ -54,7 +54,7 @@ take_from(BufferContextChain &other) { * */ void BufferContextChain:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << _count << " objects, consuming " << _total_size << " bytes:\n"; diff --git a/panda/src/gobj/bufferContextChain.h b/panda/src/gobj/bufferContextChain.h index a9943fddbf..b995c2e583 100644 --- a/panda/src/gobj/bufferContextChain.h +++ b/panda/src/gobj/bufferContextChain.h @@ -40,7 +40,7 @@ public: void take_from(BufferContextChain &other); - void write(ostream &out, int indent_level) const; + void write(std::ostream &out, int indent_level) const; private: INLINE void adjust_bytes(int delta); diff --git a/panda/src/gobj/bufferResidencyTracker.cxx b/panda/src/gobj/bufferResidencyTracker.cxx index 00f0a4e5be..9ac4fef735 100644 --- a/panda/src/gobj/bufferResidencyTracker.cxx +++ b/panda/src/gobj/bufferResidencyTracker.cxx @@ -22,7 +22,7 @@ PStatCollector BufferResidencyTracker::_gmem_collector("Graphics memory"); * */ BufferResidencyTracker:: -BufferResidencyTracker(const string &pgo_name, const string &type_name) : +BufferResidencyTracker(const std::string &pgo_name, const std::string &type_name) : _pgo_collector(_gmem_collector, pgo_name), _active_resident_collector(PStatCollector(_pgo_collector, "Active"), type_name), _active_nonresident_collector(PStatCollector(_pgo_collector, "Thrashing"), type_name), @@ -90,7 +90,7 @@ set_levels() { * */ void BufferResidencyTracker:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { if (_chains[S_inactive_nonresident].get_count() != 0) { indent(out, indent_level) << "Inactive nonresident:\n"; _chains[S_inactive_nonresident].write(out, indent_level + 2); @@ -118,7 +118,7 @@ write(ostream &out, int indent_level) const { void BufferResidencyTracker:: move_inactive(BufferContextChain &inactive, BufferContextChain &active) { BufferContext *node = active.get_first(); - while (node != (BufferContext *)NULL) { + while (node != nullptr) { nassertv((node->_residency_state & S_active) != 0); node->_residency_state &= ~S_active; node = node->get_next(); diff --git a/panda/src/gobj/bufferResidencyTracker.h b/panda/src/gobj/bufferResidencyTracker.h index 973d249d41..d3714cd232 100644 --- a/panda/src/gobj/bufferResidencyTracker.h +++ b/panda/src/gobj/bufferResidencyTracker.h @@ -31,7 +31,7 @@ class BufferContext; */ class EXPCL_PANDA_GOBJ BufferResidencyTracker { public: - BufferResidencyTracker(const string &pgo_name, const string &type_name); + BufferResidencyTracker(const std::string &pgo_name, const std::string &type_name); ~BufferResidencyTracker(); void begin_frame(Thread *current_thread); @@ -43,7 +43,7 @@ public: INLINE BufferContextChain &get_inactive_resident(); INLINE BufferContextChain &get_active_resident(); - void write(ostream &out, int indent_level) const; + void write(std::ostream &out, int indent_level) const; private: void move_inactive(BufferContextChain &inactive, BufferContextChain &active); diff --git a/panda/src/gobj/geom.I b/panda/src/gobj/geom.I index 413e2de055..94469ec77c 100644 --- a/panda/src/gobj/geom.I +++ b/panda/src/gobj/geom.I @@ -98,7 +98,7 @@ INLINE PT(GeomPrimitive) Geom:: modify_primitive(size_t i) { Thread *current_thread = Thread::get_current_thread(); CDWriter cdata(_cycler, true, current_thread); - nassertr(i < cdata->_primitives.size(), NULL); + nassertr(i < cdata->_primitives.size(), nullptr); cdata->_modified = Geom::get_next_modified(); clear_cache_stage(current_thread); return cdata->_primitives[i].get_write_pointer(); @@ -285,8 +285,8 @@ get_bounds_type() const { INLINE void Geom:: set_bounds(const BoundingVolume *volume) { CDWriter cdata(_cycler, true); - if (volume == NULL) { - cdata->_user_bounds = NULL; + if (volume == nullptr) { + cdata->_user_bounds = nullptr; } else { cdata->_user_bounds = volume->make_copy(); } @@ -303,7 +303,7 @@ set_bounds(const BoundingVolume *volume) { INLINE void Geom:: clear_bounds() { CDWriter cdata(_cycler, true); - cdata->_user_bounds = NULL; + cdata->_user_bounds = nullptr; mark_internal_bounds_stale(cdata); } @@ -385,9 +385,9 @@ mark_internal_bounds_stale(CData *cdata) { */ INLINE Geom::CDataCache:: CDataCache() : - _source(NULL), - _geom_result(NULL), - _data_result(NULL) + _source(nullptr), + _geom_result(nullptr), + _data_result(nullptr) { } @@ -400,7 +400,7 @@ CDataCache(const Geom::CDataCache ©) : _geom_result(copy._geom_result), _data_result(copy._data_result) { - if (_geom_result != _source && _geom_result != (Geom *)NULL) { + if (_geom_result != _source && _geom_result != nullptr) { _geom_result->ref(); } } @@ -412,11 +412,11 @@ CDataCache(const Geom::CDataCache ©) : INLINE void Geom::CDataCache:: set_result(const Geom *geom_result, const GeomVertexData *data_result) { if (geom_result != _geom_result) { - if (_geom_result != _source && _geom_result != (Geom *)NULL) { + if (_geom_result != _source && _geom_result != nullptr) { unref_delete(_geom_result); } _geom_result = geom_result; - if (_geom_result != _source && _geom_result != (Geom *)NULL) { + if (_geom_result != _source && _geom_result != nullptr) { _geom_result->ref(); } } @@ -443,17 +443,15 @@ CacheKey(const CacheKey ©) : { } -#ifdef USE_MOVE_SEMANTICS /** * */ INLINE Geom::CacheKey:: -CacheKey(CacheKey &&from) NOEXCEPT : - _source_data(move(from._source_data)), - _modifier(move(from._modifier)) +CacheKey(CacheKey &&from) noexcept : + _source_data(std::move(from._source_data)), + _modifier(std::move(from._modifier)) { } -#endif // USE_MOVE_SEMANTICS /** * Provides a unique ordering within the map. @@ -493,17 +491,15 @@ CacheEntry(Geom *source, const Geom::CacheKey &key) : { } -#ifdef USE_MOVE_SEMANTICS /** * */ INLINE Geom::CacheEntry:: -CacheEntry(Geom *source, Geom::CacheKey &&key) NOEXCEPT : +CacheEntry(Geom *source, Geom::CacheKey &&key) noexcept : _source(source), - _key(move(key)) + _key(std::move(key)) { } -#endif // USE_MOVE_SEMANTICS /** * @@ -581,8 +577,8 @@ INLINE GeomPipelineReader:: #endif // DO_PIPELINING #ifdef _DEBUG - _object = NULL; - _cdata = NULL; + _object = nullptr; + _cdata = nullptr; #endif // _DEBUG } @@ -595,7 +591,7 @@ set_object(const Geom *object) { // _object->_cycler.release_read(_cdata); #ifdef DO_PIPELINING - if (_cdata != NULL) { + if (_cdata != nullptr) { unref_delete((CycleData *)_cdata); } #endif // DO_PIPELINING @@ -671,7 +667,7 @@ get_num_primitives() const { */ INLINE CPT(GeomPrimitive) GeomPipelineReader:: get_primitive(int i) const { - nassertr(i >= 0 && i < (int)_cdata->_primitives.size(), NULL); + nassertr(i >= 0 && i < (int)_cdata->_primitives.size(), nullptr); return _cdata->_primitives[i].get_read_pointer(); } @@ -700,8 +696,8 @@ prepare_now(PreparedGraphicsObjects *prepared_objects, return ((Geom *)_object)->prepare_now(prepared_objects, gsg); } -INLINE ostream & -operator << (ostream &out, const Geom &obj) { +INLINE std::ostream & +operator << (std::ostream &out, const Geom &obj) { obj.output(out); return out; } diff --git a/panda/src/gobj/geom.cxx b/panda/src/gobj/geom.cxx index 26dd3c942c..5cf18838d8 100644 --- a/panda/src/gobj/geom.cxx +++ b/panda/src/gobj/geom.cxx @@ -25,6 +25,9 @@ #include "lightMutexHolder.h" #include "config_mathutil.h" +using std::max; +using std::min; + UpdateSeq Geom::_next_modified; PStatCollector Geom::_draw_primitive_setup_pcollector("Draw:Primitive:Setup"); @@ -301,7 +304,7 @@ set_primitive(size_t i, const GeomPrimitive *primitive) { // They also should have a compatible shade model. CPT(GeomPrimitive) compat = primitive->match_shade_model(cdata->_shade_model); - nassertv_always(compat != (GeomPrimitive *)NULL); + nassertv_always(compat != nullptr); cdata->_primitives[i] = (GeomPrimitive *)compat.p(); PrimitiveType new_primitive_type = compat->get_primitive_type(); @@ -625,7 +628,7 @@ unify_in_place(int max_indices, bool preserve_order) { } else { // We have already encountered another primitive of this type. Combine // them. - combine_primitives((*npi).second, move(primitive), current_thread); + combine_primitives((*npi).second, std::move(primitive), current_thread); } } @@ -1030,7 +1033,7 @@ check_valid(const GeomVertexData *vertex_data) const { CPT(BoundingVolume) Geom:: get_bounds(Thread *current_thread) const { CDLockedReader cdata(_cycler, current_thread); - if (cdata->_user_bounds != (BoundingVolume *)NULL) { + if (cdata->_user_bounds != nullptr) { return cdata->_user_bounds; } @@ -1060,7 +1063,7 @@ get_nested_vertices(Thread *current_thread) const { * */ void Geom:: -output(ostream &out) const { +output(std::ostream &out) const { CDReader cdata(_cycler); // Get a list of the primitive types contained within this object. @@ -1087,7 +1090,7 @@ output(ostream &out) const { * */ void Geom:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { CDReader cdata(_cycler); // Get a list of the primitive types contained within this object. @@ -1133,7 +1136,7 @@ clear_cache_stage(Thread *current_thread) { ++ci) { CacheEntry *entry = (*ci).second; CDCacheWriter cdata(entry->_cycler, current_thread); - cdata->set_result(NULL, NULL); + cdata->set_result(nullptr, nullptr); } } @@ -1231,7 +1234,7 @@ prepare_now(PreparedGraphicsObjects *prepared_objects, } GeomContext *gc = prepared_objects->prepare_geom_now(this, gsg); - if (gc != (GeomContext *)NULL) { + if (gc != nullptr) { _contexts[prepared_objects] = gc; } return gc; @@ -1552,9 +1555,9 @@ combine_primitives(GeomPrimitive *a_prim, CPT(GeomPrimitive) b_prim, } PT(GeomVertexArrayDataHandle) a_handle = - new GeomVertexArrayDataHandle(move(a_vertices), current_thread); + new GeomVertexArrayDataHandle(std::move(a_vertices), current_thread); CPT(GeomVertexArrayDataHandle) b_handle = - new GeomVertexArrayDataHandle(move(b_vertices), current_thread); + new GeomVertexArrayDataHandle(std::move(b_vertices), current_thread); size_t orig_a_vertices = a_handle->get_num_rows(); @@ -1597,7 +1600,7 @@ write_datagram(BamWriter *manager, Datagram &dg) { */ TypedWritable *Geom:: make_from_bam(const FactoryParams ¶ms) { - Geom *object = new Geom(NULL); + Geom *object = new Geom(nullptr); DatagramIterator scan; BamReader *manager; @@ -1644,7 +1647,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { */ Geom::CDataCache:: ~CDataCache() { - set_result(NULL, NULL); + set_result(nullptr, nullptr); } /** @@ -1672,7 +1675,7 @@ evict_callback() { * */ void Geom::CacheEntry:: -output(ostream &out) const { +output(std::ostream &out) const { out << "geom " << (void *)_source << ", " << (const void *)_key._modifier; } @@ -1740,7 +1743,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { _primitives.reserve(num_primitives); for (int i = 0; i < num_primitives; ++i) { manager->read_pointer(scan); - _primitives.push_back(NULL); + _primitives.push_back(nullptr); } _primitive_type = (PrimitiveType)scan.get_uint8(); diff --git a/panda/src/gobj/geom.h b/panda/src/gobj/geom.h index 50b050e578..833ac3cd83 100644 --- a/panda/src/gobj/geom.h +++ b/panda/src/gobj/geom.h @@ -140,8 +140,8 @@ PUBLISHED: INLINE void clear_bounds(); MAKE_PROPERTY(bounds_type, get_bounds_type, set_bounds_type); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; void clear_cache(); void clear_cache_stage(Thread *current_thread); @@ -256,9 +256,8 @@ public: INLINE CacheKey(const GeomVertexData *source_data, const GeomMunger *modifier); INLINE CacheKey(const CacheKey ©); -#ifdef USE_MOVE_SEMANTICS - INLINE CacheKey(CacheKey &&from) NOEXCEPT; -#endif + INLINE CacheKey(CacheKey &&from) noexcept; + INLINE bool operator < (const CacheKey &other) const; CPT(GeomVertexData) _source_data; @@ -271,13 +270,12 @@ public: const GeomVertexData *source_data, const GeomMunger *modifier); INLINE CacheEntry(Geom *source, const CacheKey &key); -#ifdef USE_MOVE_SEMANTICS - INLINE CacheEntry(Geom *source, CacheKey &&key) NOEXCEPT; -#endif + INLINE CacheEntry(Geom *source, CacheKey &&key) noexcept; + ALLOC_DELETED_CHAIN(CacheEntry); virtual void evict_callback(); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; Geom *_source; // A back pointer to the containing Geom CacheKey _key; @@ -406,14 +404,13 @@ class EXPCL_PANDA_GOBJ GeomPipelineReader : public GeomEnums { public: INLINE GeomPipelineReader(Thread *current_thread); INLINE GeomPipelineReader(const Geom *object, Thread *current_thread); -private: - GeomPipelineReader(const GeomPipelineReader ©) DELETED; - GeomPipelineReader &operator = (const GeomPipelineReader ©) DELETED_ASSIGN; - -public: + GeomPipelineReader(const GeomPipelineReader ©) = delete; INLINE ~GeomPipelineReader(); + ALLOC_DELETED_CHAIN(GeomPipelineReader); + GeomPipelineReader &operator = (const GeomPipelineReader ©) = delete; + INLINE void set_object(const Geom *object); INLINE const Geom *get_object() const; INLINE Thread *get_current_thread() const; @@ -453,7 +450,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const Geom &obj); +INLINE std::ostream &operator << (std::ostream &out, const Geom &obj); #include "geom.I" diff --git a/panda/src/gobj/geomCacheEntry.I b/panda/src/gobj/geomCacheEntry.I index 9c7987d855..0529d0f5cb 100644 --- a/panda/src/gobj/geomCacheEntry.I +++ b/panda/src/gobj/geomCacheEntry.I @@ -17,8 +17,8 @@ INLINE GeomCacheEntry:: GeomCacheEntry() { #ifndef NDEBUG - _next = NULL; - _prev = NULL; + _next = nullptr; + _prev = nullptr; #endif } @@ -31,8 +31,8 @@ remove_from_list() { _prev->_next = _next; _next->_prev = _prev; #ifndef NDEBUG - _next = NULL; - _prev = NULL; + _next = nullptr; + _prev = nullptr; #endif } @@ -43,16 +43,16 @@ remove_from_list() { INLINE void GeomCacheEntry:: insert_before(GeomCacheEntry *node) { nassertv(node->_prev->_next == node && node->_next->_prev == node); - nassertv(_prev == (GeomCacheEntry *)NULL && - _next == (GeomCacheEntry *)NULL); + nassertv(_prev == nullptr && + _next == nullptr); _prev = node->_prev; _next = node; _prev->_next = this; node->_prev = this; } -INLINE ostream & -operator << (ostream &out, const GeomCacheEntry &entry) { +INLINE std::ostream & +operator << (std::ostream &out, const GeomCacheEntry &entry) { entry.output(out); return out; } diff --git a/panda/src/gobj/geomCacheEntry.cxx b/panda/src/gobj/geomCacheEntry.cxx index d16a7f6a08..8ddb12b042 100644 --- a/panda/src/gobj/geomCacheEntry.cxx +++ b/panda/src/gobj/geomCacheEntry.cxx @@ -31,7 +31,7 @@ GeomCacheEntry:: */ PT(GeomCacheEntry) GeomCacheEntry:: record(Thread *current_thread) { - nassertr(_next == (GeomCacheEntry *)NULL && _prev == (GeomCacheEntry *)NULL, NULL); + nassertr(_next == nullptr && _prev == nullptr, nullptr); PT(GeomCacheEntry) keepme = this; GeomCacheManager *cache_mgr = GeomCacheManager::get_global_ptr(); @@ -72,7 +72,7 @@ void GeomCacheEntry:: refresh(Thread *current_thread) { GeomCacheManager *cache_mgr = GeomCacheManager::get_global_ptr(); LightMutexHolder holder(cache_mgr->_lock); - nassertv(_next != (GeomCacheEntry *)NULL && _prev != (GeomCacheEntry *)NULL); + nassertv(_next != nullptr && _prev != nullptr); remove_from_list(); insert_before(cache_mgr->_list); @@ -93,7 +93,7 @@ refresh(Thread *current_thread) { */ PT(GeomCacheEntry) GeomCacheEntry:: erase() { - nassertr(_next != (GeomCacheEntry *)NULL && _prev != (GeomCacheEntry *)NULL, NULL); + nassertr(_next != nullptr && _prev != nullptr, nullptr); PT(GeomCacheEntry) keepme; keepme.cheat() = this; @@ -133,6 +133,6 @@ evict_callback() { * */ void GeomCacheEntry:: -output(ostream &out) const { +output(std::ostream &out) const { out << "[ unknown ]"; } diff --git a/panda/src/gobj/geomCacheEntry.h b/panda/src/gobj/geomCacheEntry.h index 85f1dfb106..ff79d096c2 100644 --- a/panda/src/gobj/geomCacheEntry.h +++ b/panda/src/gobj/geomCacheEntry.h @@ -38,7 +38,7 @@ public: PT(GeomCacheEntry) erase(); virtual void evict_callback(); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: int _last_frame_used; @@ -65,7 +65,7 @@ private: friend class GeomCacheManager; }; -INLINE ostream &operator << (ostream &out, const GeomCacheEntry &entry); +INLINE std::ostream &operator << (std::ostream &out, const GeomCacheEntry &entry); #include "geomCacheEntry.I" diff --git a/panda/src/gobj/geomCacheManager.cxx b/panda/src/gobj/geomCacheManager.cxx index b0d2624a2d..4eb06a25b4 100644 --- a/panda/src/gobj/geomCacheManager.cxx +++ b/panda/src/gobj/geomCacheManager.cxx @@ -13,10 +13,12 @@ #include "geomCacheManager.h" #include "geomCacheEntry.h" +#include "geomMunger.h" #include "lightMutexHolder.h" +#include "lightReMutexHolder.h" #include "clockObject.h" -GeomCacheManager *GeomCacheManager::_global_ptr = NULL; +GeomCacheManager *GeomCacheManager::_global_ptr = nullptr; PStatCollector GeomCacheManager::_geom_cache_size_pcollector("Geom cache size"); PStatCollector GeomCacheManager::_geom_cache_active_pcollector("Geom cache size:Active"); @@ -53,6 +55,9 @@ GeomCacheManager:: */ void GeomCacheManager:: flush() { + // Prevent deadlock + LightReMutexHolder registry_holder(GeomMunger::get_registry()->_registry_lock); + LightMutexHolder holder(_lock); evict_old_entries(0, false); } @@ -62,7 +67,7 @@ flush() { */ GeomCacheManager *GeomCacheManager:: get_global_ptr() { - if (_global_ptr == (GeomCacheManager *)NULL) { + if (_global_ptr == nullptr) { _global_ptr = new GeomCacheManager; } return _global_ptr; diff --git a/panda/src/gobj/geomEnums.cxx b/panda/src/gobj/geomEnums.cxx index e63260a144..0899fd3679 100644 --- a/panda/src/gobj/geomEnums.cxx +++ b/panda/src/gobj/geomEnums.cxx @@ -15,6 +15,10 @@ #include "string_utils.h" #include "config_gobj.h" +using std::istream; +using std::ostream; +using std::string; + /** * diff --git a/panda/src/gobj/geomEnums.h b/panda/src/gobj/geomEnums.h index 80af6d0ea2..b9a19138eb 100644 --- a/panda/src/gobj/geomEnums.h +++ b/panda/src/gobj/geomEnums.h @@ -220,9 +220,9 @@ PUBLISHED: }; }; -EXPCL_PANDA_GOBJ ostream &operator << (ostream &out, GeomEnums::UsageHint usage_hint); -EXPCL_PANDA_GOBJ istream &operator >> (istream &in, GeomEnums::UsageHint &usage_hint); -EXPCL_PANDA_GOBJ ostream &operator << (ostream &out, GeomEnums::NumericType numeric_type); -EXPCL_PANDA_GOBJ ostream &operator << (ostream &out, GeomEnums::Contents contents); +EXPCL_PANDA_GOBJ std::ostream &operator << (std::ostream &out, GeomEnums::UsageHint usage_hint); +EXPCL_PANDA_GOBJ std::istream &operator >> (std::istream &in, GeomEnums::UsageHint &usage_hint); +EXPCL_PANDA_GOBJ std::ostream &operator << (std::ostream &out, GeomEnums::NumericType numeric_type); +EXPCL_PANDA_GOBJ std::ostream &operator << (std::ostream &out, GeomEnums::Contents contents); #endif diff --git a/panda/src/gobj/geomLines.cxx b/panda/src/gobj/geomLines.cxx index 20c9aa198b..d9b460b14a 100644 --- a/panda/src/gobj/geomLines.cxx +++ b/panda/src/gobj/geomLines.cxx @@ -20,6 +20,8 @@ #include "geomVertexWriter.h" #include "geomLinesAdjacency.h" +using std::map; + TypeHandle GeomLines::_type_handle; /** @@ -125,8 +127,8 @@ make_adjacency() const { nassertr(to.is_at_end(), nullptr); } - adj->set_vertices(move(new_vertices)); - return adj.p(); + adj->set_vertices(std::move(new_vertices)); + return adj; } /** @@ -182,7 +184,7 @@ rotate_impl() const { to.set_data1i(from.get_data1i()); } - nassertr(to.is_at_end(), NULL); + nassertr(to.is_at_end(), nullptr); } else { // Nonindexed case. @@ -194,7 +196,7 @@ rotate_impl() const { to.set_data1i(begin + first_vertex); } - nassertr(to.is_at_end(), NULL); + nassertr(to.is_at_end(), nullptr); } return new_vertices; diff --git a/panda/src/gobj/geomLinestrips.cxx b/panda/src/gobj/geomLinestrips.cxx index 8a3365a201..8e85ac870a 100644 --- a/panda/src/gobj/geomLinestrips.cxx +++ b/panda/src/gobj/geomLinestrips.cxx @@ -20,6 +20,8 @@ #include "graphicsStateGuardianBase.h" #include "geomLinestripsAdjacency.h" +using std::map; + TypeHandle GeomLinestrips::_type_handle; /** @@ -143,7 +145,7 @@ make_adjacency() const { // Add the actual vertices in the strip. adj->add_vertex(v0); - int v1; + int v1 = v0; while (vi < end) { v1 = from.get_vertex(vi++); adj->add_vertex(v1); @@ -162,7 +164,7 @@ make_adjacency() const { } nassertr(vi == num_vertices, nullptr); - return adj.p(); + return adj; } /** @@ -218,7 +220,7 @@ decompose_impl() const { // Skip unused vertices between tristrips. vi += num_unused; int end = ends[li]; - nassertr(vi + 1 <= end, lines.p()); + nassertr(vi + 1 <= end, lines); int v0 = get_vertex(vi); ++vi; while (vi < end) { @@ -231,9 +233,9 @@ decompose_impl() const { } ++li; } - nassertr(vi == get_num_vertices(), NULL); + nassertr(vi == get_num_vertices(), nullptr); - return lines.p(); + return lines; } /** @@ -262,7 +264,7 @@ rotate_impl() const { begin = end; } - nassertr(to.is_at_end(), NULL); + nassertr(to.is_at_end(), nullptr); } else { // Nonindexed case. @@ -279,7 +281,7 @@ rotate_impl() const { begin = end; } - nassertr(to.is_at_end(), NULL); + nassertr(to.is_at_end(), nullptr); } return new_vertices; } diff --git a/panda/src/gobj/geomLinestripsAdjacency.cxx b/panda/src/gobj/geomLinestripsAdjacency.cxx index 11d14ab319..c9d4ba6891 100644 --- a/panda/src/gobj/geomLinestripsAdjacency.cxx +++ b/panda/src/gobj/geomLinestripsAdjacency.cxx @@ -142,7 +142,7 @@ decompose_impl() const { // Skip unused vertices between tristrips. vi += num_unused; int end = ends[li]; - nassertr(vi + 3 <= end, lines.p()); + nassertr(vi + 3 <= end, lines); int v0 = from.get_vertex(vi++); int v1 = from.get_vertex(vi++); int v2 = from.get_vertex(vi++); @@ -160,7 +160,7 @@ decompose_impl() const { } nassertr(vi == num_vertices, nullptr); - return lines.p(); + return lines; } /** diff --git a/panda/src/gobj/geomMunger.I b/panda/src/gobj/geomMunger.I index 8cbd51aa91..f1c28bb451 100644 --- a/panda/src/gobj/geomMunger.I +++ b/panda/src/gobj/geomMunger.I @@ -177,7 +177,7 @@ unregister_myself() { */ INLINE GeomMunger::Registry *GeomMunger:: get_registry() { - if (_registry == (Registry *)NULL) { + if (_registry == nullptr) { make_registry(); } return _registry; diff --git a/panda/src/gobj/geomMunger.cxx b/panda/src/gobj/geomMunger.cxx index fccbdab0b6..40a183edfa 100644 --- a/panda/src/gobj/geomMunger.cxx +++ b/panda/src/gobj/geomMunger.cxx @@ -18,7 +18,7 @@ #include "lightReMutexHolder.h" #include "pStatTimer.h" -GeomMunger::Registry *GeomMunger::_registry = NULL; +GeomMunger::Registry *GeomMunger::_registry = nullptr; TypeHandle GeomMunger::_type_handle; PStatCollector GeomMunger::_munge_pcollector("*:Munge"); @@ -116,7 +116,7 @@ munge_geom(CPT(Geom) &geom, CPT(GeomVertexData) &data, // Now check that it's fresh. Geom::CDCacheReader cdata(entry->_cycler, current_thread); if (cdata->_source == geom && - cdata->_geom_result != (Geom *)NULL && + cdata->_geom_result != nullptr && geom->get_modified(current_thread) <= cdata->_geom_result->get_modified(current_thread) && data->get_modified(current_thread) <= cdata->_data_result->get_modified(current_thread)) { // The cache entry is still good; use it. @@ -145,14 +145,11 @@ munge_geom(CPT(Geom) &geom, CPT(GeomVertexData) &data, munge_geom_impl(geom, data, current_thread); // Record the new result in the cache. - if (entry == (Geom::CacheEntry *)NULL) { + if (entry == nullptr) { // Create a new entry for the result. -#ifdef USE_MOVE_SEMANTICS // We don't need the key anymore, move the pointers into the CacheEntry. - entry = new Geom::CacheEntry(orig_geom, move(key)); -#else - entry = new Geom::CacheEntry(orig_geom, key); -#endif + entry = new Geom::CacheEntry(orig_geom, std::move(key)); + { LightMutexHolder holder(orig_geom->_cache_lock); bool inserted = orig_geom->_cache.insert(Geom::Cache::value_type(&entry->_key, entry)).second; @@ -182,8 +179,8 @@ munge_geom(CPT(Geom) &geom, CPT(GeomVertexData) &data, CPT(GeomVertexFormat) GeomMunger:: do_munge_format(const GeomVertexFormat *format, const GeomVertexAnimationSpec &animation) { - nassertr(_is_registered, NULL); - nassertr(format->is_registered(), NULL); + nassertr(_is_registered, nullptr); + nassertr(format->is_registered(), nullptr); LightMutexHolder holder(_formats_lock); @@ -198,11 +195,11 @@ do_munge_format(const GeomVertexFormat *format, // We have to munge this format for the first time. CPT(GeomVertexFormat) derived_format = munge_format_impl(format, animation); - nassertr(derived_format->is_registered(), NULL); + nassertr(derived_format->is_registered(), nullptr); // Store the answer in the map, so we can quickly get it next time. bool inserted = formats.insert(Formats::value_type(format, derived_format)).second; - nassertr(inserted, NULL); + nassertr(inserted, nullptr); return derived_format; } @@ -221,7 +218,7 @@ munge_format_impl(const GeomVertexFormat *orig, const GeomVertexAnimationSpec &) */ CPT(GeomVertexData) GeomMunger:: munge_data_impl(const GeomVertexData *data) { - nassertr(_is_registered, NULL); + nassertr(_is_registered, nullptr); CPT(GeomVertexFormat) orig_format = data->get_format(); CPT(GeomVertexFormat) new_format = @@ -250,8 +247,8 @@ munge_geom_impl(CPT(Geom) &, CPT(GeomVertexData) &, Thread *) { */ CPT(GeomVertexFormat) GeomMunger:: do_premunge_format(const GeomVertexFormat *format) { - nassertr(_is_registered, NULL); - nassertr(format->is_registered(), NULL); + nassertr(_is_registered, nullptr); + nassertr(format->is_registered(), nullptr); LightMutexHolder holder(_formats_lock); @@ -264,11 +261,11 @@ do_premunge_format(const GeomVertexFormat *format) { // We have to munge this format for the first time. CPT(GeomVertexFormat) derived_format = premunge_format_impl(format); - nassertr(derived_format->is_registered(), NULL); + nassertr(derived_format->is_registered(), nullptr); // Store the answer in the map, so we can quickly get it next time. bool inserted = _premunge_formats.insert(Formats::value_type(format, derived_format)).second; - nassertr(inserted, NULL); + nassertr(inserted, nullptr); return derived_format; } @@ -287,7 +284,7 @@ premunge_format_impl(const GeomVertexFormat *orig) { */ CPT(GeomVertexData) GeomMunger:: premunge_data_impl(const GeomVertexData *data) { - nassertr(_is_registered, NULL); + nassertr(_is_registered, nullptr); CPT(GeomVertexFormat) orig_format = data->get_format(); CPT(GeomVertexFormat) new_format = premunge_format(orig_format); @@ -335,7 +332,7 @@ geom_compare_to_impl(const GeomMunger *other) const { */ void GeomMunger:: make_registry() { - if (_registry == (Registry *)NULL) { + if (_registry == nullptr) { _registry = new Registry; } } @@ -381,7 +378,7 @@ do_unregister() { * */ void GeomMunger::CacheEntry:: -output(ostream &out) const { +output(std::ostream &out) const { out << "munger " << _munger; } diff --git a/panda/src/gobj/geomMunger.h b/panda/src/gobj/geomMunger.h index 840057539d..e8aa67bd61 100644 --- a/panda/src/gobj/geomMunger.h +++ b/panda/src/gobj/geomMunger.h @@ -109,7 +109,7 @@ private: private: class CacheEntry : public GeomCacheEntry { public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; PT(GeomMunger) _munger; }; @@ -149,6 +149,8 @@ private: static PStatCollector _munge_pcollector; + friend class GeomCacheManager; + public: static TypeHandle get_class_type() { return _type_handle; diff --git a/panda/src/gobj/geomPrimitive.I b/panda/src/gobj/geomPrimitive.I index 9863701e21..0984dbecb3 100644 --- a/panda/src/gobj/geomPrimitive.I +++ b/panda/src/gobj/geomPrimitive.I @@ -445,12 +445,12 @@ CData(const GeomPrimitive::CData ©) : INLINE GeomPrimitivePipelineReader:: GeomPrimitivePipelineReader(CPT(GeomPrimitive) object, Thread *current_thread) : - _object(move(object)), + _object(std::move(object)), _current_thread(current_thread), #ifndef CPPPARSER _cdata(_object->_cycler.read_unlocked(current_thread)), #endif - _vertices_cdata(NULL) + _vertices_cdata(nullptr) { nassertv(_object->test_ref_count_nonzero()); #ifdef DO_PIPELINING @@ -494,8 +494,8 @@ INLINE GeomPrimitivePipelineReader:: } #ifdef _DEBUG - _object = NULL; - _cdata = NULL; + _object = nullptr; + _cdata = nullptr; #endif // _DEBUG } @@ -635,8 +635,8 @@ get_ends() const { */ INLINE CPT(GeomVertexArrayData) GeomPrimitivePipelineReader:: get_mins() const { - nassertr(is_indexed(), NULL); - nassertr(_cdata->_got_minmax, NULL); + nassertr(is_indexed(), nullptr); + nassertr(_cdata->_got_minmax, nullptr); return _cdata->_mins.get_read_pointer(); } @@ -645,8 +645,8 @@ get_mins() const { */ INLINE CPT(GeomVertexArrayData) GeomPrimitivePipelineReader:: get_maxs() const { - nassertr(is_indexed(), NULL); - nassertr(_cdata->_got_minmax, NULL); + nassertr(is_indexed(), nullptr); + nassertr(_cdata->_got_minmax, nullptr); return _cdata->_maxs.get_read_pointer(); } @@ -667,8 +667,8 @@ draw(GraphicsStateGuardianBase *gsg, bool force) const { return _object->draw(gsg, this, force); } -INLINE ostream & -operator << (ostream &out, const GeomPrimitive &obj) { +INLINE std::ostream & +operator << (std::ostream &out, const GeomPrimitive &obj) { obj.output(out); return out; } diff --git a/panda/src/gobj/geomPrimitive.cxx b/panda/src/gobj/geomPrimitive.cxx index b85747a945..da3c10dffd 100644 --- a/panda/src/gobj/geomPrimitive.cxx +++ b/panda/src/gobj/geomPrimitive.cxx @@ -31,6 +31,9 @@ #include "indent.h" #include "pStatTimer.h" +using std::max; +using std::min; + TypeHandle GeomPrimitive::_type_handle; TypeHandle GeomPrimitive::CData::_type_handle; TypeHandle GeomPrimitivePipelineReader::_type_handle; @@ -52,7 +55,7 @@ GeomPrimitive() { */ PT(CopyOnWriteObject) GeomPrimitive:: make_cow_copy() { - return make_copy().p(); + return make_copy(); } /** @@ -581,7 +584,7 @@ pack_vertices(GeomVertexData *dest, const GeomVertexData *source) { // Try to add the relation { v : size() }. If that succeeds, great; if // it doesn't, look up whatever we previously added for v. - pair result = + std::pair result = copied_indices.insert(CopiedIndices::value_type(v, (int)copied_indices.size())); int v2 = (*result.first).second + dest_start; index.add_data1i(v2); @@ -789,7 +792,7 @@ rotate() const { PStatTimer timer(_rotate_pcollector); CPT(GeomVertexArrayData) rotated_vertices = rotate_impl(); - if (rotated_vertices == (GeomVertexArrayData *)NULL) { + if (rotated_vertices == nullptr) { // This primitive type can't be rotated. return this; } @@ -882,13 +885,13 @@ match_shade_model(GeomPrimitive::ShadeModel shade_model) const { CPT(GeomPrimitive) rotated = rotate(); if (rotated.p() == this) { // Oops, can't be rotated, sorry. - return NULL; + return nullptr; } return rotated; } // Not compatible, sorry. - return NULL; + return nullptr; } /** @@ -1079,7 +1082,7 @@ request_resident(Thread *current_thread) const { * */ void GeomPrimitive:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ", " << get_num_primitives() << ", " << get_num_vertices(); } @@ -1088,7 +1091,7 @@ output(ostream &out) const { * */ void GeomPrimitive:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type(); if (is_indexed()) { @@ -1195,7 +1198,7 @@ void GeomPrimitive:: set_nonindexed_vertices(int first_vertex, int num_vertices) { nassertv(num_vertices != -1); CDWriter cdata(_cycler, true); - cdata->_vertices = (GeomVertexArrayData *)NULL; + cdata->_vertices = nullptr; cdata->_first_vertex = first_vertex; cdata->_num_vertices = num_vertices; @@ -1391,7 +1394,7 @@ is_prepared(PreparedGraphicsObjects *prepared_objects) const { IndexBufferContext *GeomPrimitive:: prepare_now(PreparedGraphicsObjects *prepared_objects, GraphicsStateGuardianBase *gsg) { - nassertr(is_indexed(), NULL); + nassertr(is_indexed(), nullptr); Contexts::const_iterator ci; ci = _contexts.find(prepared_objects); @@ -1400,7 +1403,7 @@ prepare_now(PreparedGraphicsObjects *prepared_objects, } IndexBufferContext *ibc = prepared_objects->prepare_index_buffer_now(this, gsg); - if (ibc != (IndexBufferContext *)NULL) { + if (ibc != nullptr) { _contexts[prepared_objects] = ibc; } return ibc; @@ -1460,24 +1463,24 @@ get_index_format(NumericType index_type) { switch (index_type) { case NT_uint8: { - static CPT(GeomVertexArrayFormat) cformat = NULL; - if (cformat == NULL) { + static CPT(GeomVertexArrayFormat) cformat = nullptr; + if (cformat == nullptr) { cformat = make_index_format(NT_uint8); } return cformat; } case NT_uint16: { - static CPT(GeomVertexArrayFormat) cformat = NULL; - if (cformat == NULL) { + static CPT(GeomVertexArrayFormat) cformat = nullptr; + if (cformat == nullptr) { cformat = make_index_format(NT_uint16); } return cformat; } case NT_uint32: { - static CPT(GeomVertexArrayFormat) cformat = NULL; - if (cformat == NULL) { + static CPT(GeomVertexArrayFormat) cformat = nullptr; + if (cformat == nullptr) { cformat = make_index_format(NT_uint32); } return cformat; @@ -1486,10 +1489,10 @@ get_index_format(NumericType index_type) { default: gobj_cat.error() << "Not a valid index type: " << index_type << "\n"; - return NULL; + return nullptr; } - return NULL; + return nullptr; } /** @@ -1791,8 +1794,8 @@ decompose_impl() const { CPT(GeomVertexArrayData) GeomPrimitive:: rotate_impl() const { // The default implementation doesn't even try to do anything. - nassertr(false, NULL); - return NULL; + nassertr(false, nullptr); + return nullptr; } /** @@ -2074,7 +2077,7 @@ write_datagram(BamWriter *manager, Datagram &dg) { void GeomPrimitive:: finalize(BamReader *manager) { const GeomVertexArrayData *vertices = get_vertices(); - if (vertices != (GeomVertexArrayData *)NULL) { + if (vertices != nullptr) { set_usage_hint(vertices->get_usage_hint()); } } diff --git a/panda/src/gobj/geomPrimitive.h b/panda/src/gobj/geomPrimitive.h index 8748c86799..b8012507b8 100644 --- a/panda/src/gobj/geomPrimitive.h +++ b/panda/src/gobj/geomPrimitive.h @@ -147,8 +147,8 @@ PUBLISHED: INLINE bool check_valid(const GeomVertexData *vertex_data) const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; PUBLISHED: /* @@ -351,14 +351,13 @@ private: class EXPCL_PANDA_GOBJ GeomPrimitivePipelineReader : public GeomEnums { public: INLINE GeomPrimitivePipelineReader(CPT(GeomPrimitive) object, Thread *current_thread); -private: - GeomPrimitivePipelineReader(const GeomPrimitivePipelineReader ©) DELETED; - GeomPrimitivePipelineReader &operator = (const GeomPrimitivePipelineReader ©) DELETED_ASSIGN; - -public: + GeomPrimitivePipelineReader(const GeomPrimitivePipelineReader ©) = delete; INLINE ~GeomPrimitivePipelineReader(); + ALLOC_DELETED_CHAIN(GeomPrimitivePipelineReader); + GeomPrimitivePipelineReader &operator = (const GeomPrimitivePipelineReader ©) = delete; + INLINE const GeomPrimitive *get_object() const; INLINE Thread *get_current_thread() const; @@ -409,7 +408,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const GeomPrimitive &obj); +INLINE std::ostream &operator << (std::ostream &out, const GeomPrimitive &obj); #include "geomPrimitive.I" diff --git a/panda/src/gobj/geomTriangles.cxx b/panda/src/gobj/geomTriangles.cxx index a6e3b9480f..5171ec6b5f 100644 --- a/panda/src/gobj/geomTriangles.cxx +++ b/panda/src/gobj/geomTriangles.cxx @@ -19,6 +19,8 @@ #include "graphicsStateGuardianBase.h" #include "geomTrianglesAdjacency.h" +using std::map; + TypeHandle GeomTriangles::_type_handle; /** @@ -73,6 +75,8 @@ get_primitive_type() const { */ CPT(GeomPrimitive) GeomTriangles:: make_adjacency() const { + using std::make_pair; + Thread *current_thread = Thread::get_current_thread(); PT(GeomTrianglesAdjacency) adj = new GeomTrianglesAdjacency(get_usage_hint()); @@ -83,7 +87,7 @@ make_adjacency() const { new_vertices->set_num_rows(num_vertices * 2); // First, build a map of each triangle's halfedges to its opposing vertices. - map, int> edge_map; + map, int> edge_map; for (int i = 0; i < num_vertices; i += 3) { int v0 = from.get_vertex(i); int v1 = from.get_vertex(i + 1); @@ -133,8 +137,8 @@ make_adjacency() const { nassertr(to.is_at_end(), nullptr); } - adj->set_vertices(move(new_vertices)); - return adj.p(); + adj->set_vertices(std::move(new_vertices)); + return adj; } /** @@ -195,7 +199,7 @@ doubleside_impl() const { reversed = (GeomTriangles *)DCAST(GeomTriangles, reversed->rotate()); } - return reversed.p(); + return reversed; } /** @@ -228,7 +232,7 @@ reverse_impl() const { break; } - return reversed.p(); + return reversed; } /** @@ -281,7 +285,7 @@ rotate_impl() const { nassertr(false, vertices); } - nassertr(to.is_at_end(), NULL); + nassertr(to.is_at_end(), nullptr); } else { // Nonindexed case. @@ -313,10 +317,10 @@ rotate_impl() const { default: // This shouldn't get called with any other shade model. - nassertr(false, NULL); + nassertr(false, nullptr); } - nassertr(to.is_at_end(), NULL); + nassertr(to.is_at_end(), nullptr); } return new_vertices; diff --git a/panda/src/gobj/geomTrianglesAdjacency.cxx b/panda/src/gobj/geomTrianglesAdjacency.cxx index 0dffa74329..5278d69bbb 100644 --- a/panda/src/gobj/geomTrianglesAdjacency.cxx +++ b/panda/src/gobj/geomTrianglesAdjacency.cxx @@ -133,7 +133,7 @@ doubleside_impl() const { reversed = (GeomTrianglesAdjacency *)DCAST(GeomTrianglesAdjacency, reversed->rotate()); } - return reversed.p(); + return reversed; } /** @@ -166,7 +166,7 @@ reverse_impl() const { break; } - return reversed.p(); + return reversed; } /** diff --git a/panda/src/gobj/geomTrifans.cxx b/panda/src/gobj/geomTrifans.cxx index 3808da40bb..a99481e92e 100644 --- a/panda/src/gobj/geomTrifans.cxx +++ b/panda/src/gobj/geomTrifans.cxx @@ -110,7 +110,7 @@ decompose_impl() const { int li = 0; while (li < (int)ends.size()) { int end = ends[li]; - nassertr(vi + 2 <= end, triangles.p()); + nassertr(vi + 2 <= end, triangles); int v0 = get_vertex(vi); ++vi; int v1 = get_vertex(vi); @@ -127,9 +127,9 @@ decompose_impl() const { ++li; } - nassertr(vi == num_vertices, NULL); + nassertr(vi == num_vertices, nullptr); - return triangles.p(); + return triangles; } /** @@ -139,8 +139,8 @@ CPT(GeomVertexArrayData) GeomTrifans:: rotate_impl() const { // Actually, we can't rotate fans without chaging the winding order. It's // an error to define a flat shade model for a GeomTrifan. - nassertr(false, NULL); - return NULL; + nassertr(false, nullptr); + return nullptr; } /** diff --git a/panda/src/gobj/geomTristrips.cxx b/panda/src/gobj/geomTristrips.cxx index ae7bf0bc25..15b46c409a 100644 --- a/panda/src/gobj/geomTristrips.cxx +++ b/panda/src/gobj/geomTristrips.cxx @@ -20,6 +20,8 @@ #include "graphicsStateGuardianBase.h" #include "geomTristripsAdjacency.h" +using std::map; + TypeHandle GeomTristrips::_type_handle; /** @@ -87,6 +89,8 @@ get_geom_rendering() const { */ CPT(GeomPrimitive) GeomTristrips:: make_adjacency() const { + using std::make_pair; + Thread *current_thread = Thread::get_current_thread(); PT(GeomTristripsAdjacency) adj = new GeomTristripsAdjacency(get_usage_hint()); CPTA_int ends = get_ends(); @@ -96,7 +100,7 @@ make_adjacency() const { const int num_unused = 2; // First, build a map of each triangle's halfedges to its opposing vertices. - map, int> edge_map; + map, int> edge_map; int vi = -num_unused; int li = 0; @@ -215,7 +219,7 @@ make_adjacency() const { } nassertr(vi == num_vertices, nullptr); - return adj.p(); + return adj; } /** @@ -278,7 +282,7 @@ decompose_impl() const { // Skip unused vertices between tristrips. vi += num_unused; int end = ends[li]; - nassertr(vi + 2 <= end, NULL); + nassertr(vi + 2 <= end, nullptr); int v0 = get_vertex(vi); ++vi; int v1 = get_vertex(vi); @@ -309,7 +313,7 @@ decompose_impl() const { } ++li; } - nassertr(vi == num_vertices, NULL); + nassertr(vi == num_vertices, nullptr); } else { // Preserve the last vertex of each component triangle as the last vertex @@ -320,7 +324,7 @@ decompose_impl() const { // Skip unused vertices between tristrips. vi += num_unused; int end = ends[li]; - nassertr(vi + 2 <= end, NULL); + nassertr(vi + 2 <= end, nullptr); int v0 = get_vertex(vi); ++vi; int v1 = get_vertex(vi); @@ -351,10 +355,10 @@ decompose_impl() const { } ++li; } - nassertr(vi == num_vertices, NULL); + nassertr(vi == num_vertices, nullptr); } - return triangles.p(); + return triangles; } /** @@ -414,7 +418,7 @@ rotate_impl() const { // If this assertion is triggered, there was a triangle strip with an // odd number of vertices, which is not allowed. - nassertr((num_vertices & 1) == 0, NULL); + nassertr((num_vertices & 1) == 0, nullptr); for (int vi = end - 1; vi >= begin; --vi) { from.set_row_unsafe(vi); last_added = from.get_data1i(); @@ -424,7 +428,7 @@ rotate_impl() const { begin = end; } - nassertr(to.is_at_end(), NULL); + nassertr(to.is_at_end(), nullptr); } else { // Nonindexed case. @@ -447,7 +451,7 @@ rotate_impl() const { // If this assertion is triggered, there was a triangle strip with an // odd number of vertices, which is not allowed. - nassertr((num_vertices & 1) == 0, NULL); + nassertr((num_vertices & 1) == 0, nullptr); for (int vi = end - 1; vi >= begin; --vi) { last_added = vi + first_vertex; to.set_data1i(last_added); @@ -456,7 +460,7 @@ rotate_impl() const { begin = end; } - nassertr(to.is_at_end(), NULL); + nassertr(to.is_at_end(), nullptr); } return new_vertices; } diff --git a/panda/src/gobj/geomVertexAnimationSpec.I b/panda/src/gobj/geomVertexAnimationSpec.I index eb32efb5eb..0942ce5d78 100644 --- a/panda/src/gobj/geomVertexAnimationSpec.I +++ b/panda/src/gobj/geomVertexAnimationSpec.I @@ -150,8 +150,8 @@ compare_to(const GeomVertexAnimationSpec &other) const { return 0; } -INLINE ostream & -operator << (ostream &out, const GeomVertexAnimationSpec &animation) { +INLINE std::ostream & +operator << (std::ostream &out, const GeomVertexAnimationSpec &animation) { animation.output(out); return out; } diff --git a/panda/src/gobj/geomVertexAnimationSpec.cxx b/panda/src/gobj/geomVertexAnimationSpec.cxx index be4dc6903a..f4560b7980 100644 --- a/panda/src/gobj/geomVertexAnimationSpec.cxx +++ b/panda/src/gobj/geomVertexAnimationSpec.cxx @@ -19,7 +19,7 @@ * */ void GeomVertexAnimationSpec:: -output(ostream &out) const { +output(std::ostream &out) const { switch (_animation_type) { case AT_none: out << "none"; diff --git a/panda/src/gobj/geomVertexAnimationSpec.h b/panda/src/gobj/geomVertexAnimationSpec.h index ddd94866a5..c377dd9f94 100644 --- a/panda/src/gobj/geomVertexAnimationSpec.h +++ b/panda/src/gobj/geomVertexAnimationSpec.h @@ -53,7 +53,7 @@ PUBLISHED: INLINE void set_panda(); INLINE void set_hardware(int num_transforms, bool indexed_transforms); - void output(ostream &out) const; + void output(std::ostream &out) const; public: INLINE bool operator < (const GeomVertexAnimationSpec &other) const; @@ -72,8 +72,8 @@ private: bool _indexed_transforms; }; -INLINE ostream & -operator << (ostream &out, const GeomVertexAnimationSpec &animation); +INLINE std::ostream & +operator << (std::ostream &out, const GeomVertexAnimationSpec &animation); #include "geomVertexAnimationSpec.I" diff --git a/panda/src/gobj/geomVertexArrayData.I b/panda/src/gobj/geomVertexArrayData.I index 624525360d..cfe12f9013 100644 --- a/panda/src/gobj/geomVertexArrayData.I +++ b/panda/src/gobj/geomVertexArrayData.I @@ -239,10 +239,10 @@ CData(UsageHint usage_hint) : * */ INLINE GeomVertexArrayData::CData:: -CData(GeomVertexArrayData::CData &&from) NOEXCEPT : - _usage_hint(move(from._usage_hint)), - _buffer(move(from._buffer)), - _modified(move(from._modified)), +CData(GeomVertexArrayData::CData &&from) noexcept : + _usage_hint(std::move(from._usage_hint)), + _buffer(std::move(from._buffer)), + _modified(std::move(from._modified)), _rw_lock("GeomVertexArrayData::CData::_rw_lock") { } @@ -371,23 +371,6 @@ GeomVertexArrayDataHandle(GeomVertexArrayData *object, #endif } -/** - * Don't attempt to copy these objects. - */ -INLINE GeomVertexArrayDataHandle:: -GeomVertexArrayDataHandle(const GeomVertexArrayDataHandle ©) - : _current_thread(copy._current_thread) { - nassertv(false); -} - -/** - * Don't attempt to copy these objects. - */ -INLINE void GeomVertexArrayDataHandle:: -operator = (const GeomVertexArrayDataHandle &) { - nassertv(false); -} - /** * */ @@ -410,8 +393,8 @@ INLINE GeomVertexArrayDataHandle:: #endif // DO_PIPELINING #ifdef _DEBUG - _object = NULL; - _cdata = NULL; + _object = nullptr; + _cdata = nullptr; #endif // _DEBUG } @@ -510,7 +493,7 @@ get_modified() const { */ INLINE bool GeomVertexArrayDataHandle:: request_resident() const { - return (get_read_pointer(false) != (const unsigned char *)NULL); + return (get_read_pointer(false) != nullptr); } /** @@ -535,10 +518,11 @@ prepare_now(PreparedGraphicsObjects *prepared_objects, * a string. This is primarily for the benefit of high-level languages such * as Python. */ -INLINE string GeomVertexArrayDataHandle:: +INLINE vector_uchar GeomVertexArrayDataHandle:: get_data() const { mark_used(); - return string((const char *)_cdata->_buffer.get_read_pointer(true), _cdata->_buffer.get_size()); + const unsigned char *ptr = _cdata->_buffer.get_read_pointer(true); + return vector_uchar(ptr, ptr + _cdata->_buffer.get_size()); } /** @@ -546,12 +530,13 @@ get_data() const { * formatted as a string. This is primarily for the benefit of high-level * languages such as Python. */ -INLINE string GeomVertexArrayDataHandle:: +INLINE vector_uchar GeomVertexArrayDataHandle:: get_subdata(size_t start, size_t size) const { mark_used(); - start = min(start, _cdata->_buffer.get_size()); - size = min(size, _cdata->_buffer.get_size() - start); - return string((const char *)_cdata->_buffer.get_read_pointer(true) + start, size); + start = std::min(start, _cdata->_buffer.get_size()); + size = std::min(size, _cdata->_buffer.get_size() - start); + const unsigned char *ptr = _cdata->_buffer.get_read_pointer(true) + start; + return vector_uchar(ptr, ptr + size); } /** @@ -562,8 +547,8 @@ mark_used() const { _object->mark_used(); } -INLINE ostream & -operator << (ostream &out, const GeomVertexArrayData &obj) { +INLINE std::ostream & +operator << (std::ostream &out, const GeomVertexArrayData &obj) { obj.output(out); return out; } diff --git a/panda/src/gobj/geomVertexArrayData.cxx b/panda/src/gobj/geomVertexArrayData.cxx index 50a4529159..998ca1ad14 100644 --- a/panda/src/gobj/geomVertexArrayData.cxx +++ b/panda/src/gobj/geomVertexArrayData.cxx @@ -25,6 +25,9 @@ #include "vertexDataBuffer.h" #include "texture.h" +using std::max; +using std::min; + ConfigVariableInt max_independent_vertex_data ("max-independent-vertex-data", -1, PRC_DESC("Specifies the maximum number of bytes of all vertex data " @@ -57,7 +60,7 @@ ALLOC_DELETED_CHAIN_DEF(GeomVertexArrayDataHandle); */ GeomVertexArrayData:: GeomVertexArrayData() : SimpleLruPage(0) { - _contexts = NULL; + _contexts = nullptr; // Can't put it in the LRU until it has been read in and made valid. } @@ -176,7 +179,7 @@ set_usage_hint(GeomVertexArrayData::UsageHint usage_hint) { * */ void GeomVertexArrayData:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_num_rows() << " rows: " << *get_array_format(); } @@ -184,7 +187,7 @@ output(ostream &out) const { * */ void GeomVertexArrayData:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { _array_format->write_with_data(out, indent_level, this); } @@ -207,7 +210,7 @@ prepare(PreparedGraphicsObjects *prepared_objects) { */ bool GeomVertexArrayData:: is_prepared(PreparedGraphicsObjects *prepared_objects) const { - if (_contexts == (Contexts *)NULL) { + if (_contexts == nullptr) { return false; } Contexts::const_iterator ci; @@ -232,7 +235,7 @@ is_prepared(PreparedGraphicsObjects *prepared_objects) const { VertexBufferContext *GeomVertexArrayData:: prepare_now(PreparedGraphicsObjects *prepared_objects, GraphicsStateGuardianBase *gsg) { - if (_contexts == (Contexts *)NULL) { + if (_contexts == nullptr) { _contexts = new Contexts; } Contexts::const_iterator ci; @@ -242,7 +245,7 @@ prepare_now(PreparedGraphicsObjects *prepared_objects, } VertexBufferContext *vbc = prepared_objects->prepare_vertex_buffer_now(this, gsg); - if (vbc != (VertexBufferContext *)NULL) { + if (vbc != nullptr) { (*_contexts)[prepared_objects] = vbc; } return vbc; @@ -254,7 +257,7 @@ prepare_now(PreparedGraphicsObjects *prepared_objects, */ bool GeomVertexArrayData:: release(PreparedGraphicsObjects *prepared_objects) { - if (_contexts != (Contexts *)NULL) { + if (_contexts != nullptr) { Contexts::iterator ci; ci = _contexts->find(prepared_objects); if (ci != _contexts->end()) { @@ -276,7 +279,7 @@ int GeomVertexArrayData:: release_all() { int num_freed = 0; - if (_contexts != (Contexts *)NULL) { + if (_contexts != nullptr) { // We have to traverse a copy of the _contexts list, because the // PreparedGraphicsObjects object will call clear_prepared() in response // to each release_vertex_buffer(), and we don't want to be modifying the @@ -293,7 +296,7 @@ release_all() { // Now that we've called release_vertex_buffer() on every known context, // the _contexts list should have completely emptied itself. - nassertr(_contexts == NULL, num_freed); + nassertr(_contexts == nullptr, num_freed); } return num_freed; @@ -335,7 +338,7 @@ evict_lru() { */ void GeomVertexArrayData:: clear_prepared(PreparedGraphicsObjects *prepared_objects) { - nassertv(_contexts != (Contexts *)NULL); + nassertv(_contexts != nullptr); Contexts::iterator ci; ci = _contexts->find(prepared_objects); @@ -343,7 +346,7 @@ clear_prepared(PreparedGraphicsObjects *prepared_objects) { _contexts->erase(ci); if (_contexts->empty()) { delete _contexts; - _contexts = NULL; + _contexts = nullptr; } } else { // If this assertion fails, clear_prepared() was given a prepared_objects @@ -457,7 +460,7 @@ finalize(BamReader *manager) { _array_format = new_array_format; PT(BamAuxData) aux_data = (BamAuxData *)manager->get_aux_data(this, ""); - if (aux_data != (BamAuxData *)NULL) { + if (aux_data != nullptr) { if (aux_data->_endian_reversed) { // Now is the time to endian-reverse the data. VertexDataBuffer new_buffer(cdata->_buffer.get_size()); @@ -571,7 +574,7 @@ fillin(DatagramIterator &scan, BamReader *manager, void *extra_data) { if (manager->get_file_endian() != BamReader::BE_native) { // For non-native endian files, we have to convert the data. - if (array_data->_array_format == (GeomVertexArrayFormat *)NULL) { + if (array_data->_array_format == nullptr) { // But we can't do that until we've completed the _array_format pointer, // which tells us how to convert it. endian_reversed = true; @@ -600,7 +603,7 @@ fillin(DatagramIterator &scan, BamReader *manager, void *extra_data) { */ unsigned char *GeomVertexArrayDataHandle:: get_write_pointer() { - nassertr(_writable, NULL); + nassertr(_writable, nullptr); mark_used(); _cdata->_modified = Geom::get_next_modified(); return _cdata->_buffer.get_write_pointer(); @@ -842,7 +845,7 @@ copy_subdata_from(size_t to_start, size_t to_size, * Python. */ void GeomVertexArrayDataHandle:: -set_data(const string &data) { +set_data(const vector_uchar &data) { nassertv(_writable); mark_used(); @@ -864,7 +867,7 @@ set_data(const string &data) { * This is primarily for the benefit of high-level languages like Python. */ void GeomVertexArrayDataHandle:: -set_subdata(size_t start, size_t size, const string &data) { +set_subdata(size_t start, size_t size, const vector_uchar &data) { nassertv(_writable); mark_used(); diff --git a/panda/src/gobj/geomVertexArrayData.h b/panda/src/gobj/geomVertexArrayData.h index 4a49d26881..917b27c71a 100644 --- a/panda/src/gobj/geomVertexArrayData.h +++ b/panda/src/gobj/geomVertexArrayData.h @@ -92,8 +92,8 @@ PUBLISHED: MAKE_PROPERTY(data_size_bytes, get_data_size_bytes); MAKE_PROPERTY(modified, get_modified); - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; INLINE bool request_resident(Thread *current_thread = Thread::get_current_thread()) const; @@ -151,7 +151,7 @@ private: class EXPCL_PANDA_GOBJ CData : public CycleData { public: INLINE CData(UsageHint usage_hint = UH_unspecified); - INLINE CData(CData &&from) NOEXCEPT; + INLINE CData(CData &&from) noexcept; INLINE CData(const CData ©); INLINE void operator = (const CData ©); @@ -257,15 +257,17 @@ private: Thread *current_thread); INLINE GeomVertexArrayDataHandle(GeomVertexArrayData *object, Thread *current_thread); - INLINE GeomVertexArrayDataHandle(const GeomVertexArrayDataHandle &); - INLINE void operator = (const GeomVertexArrayDataHandle &); PUBLISHED: INLINE ~GeomVertexArrayDataHandle(); public: + GeomVertexArrayDataHandle(const GeomVertexArrayDataHandle &) = delete; + ALLOC_DELETED_CHAIN_DECL(GeomVertexArrayDataHandle); + GeomVertexArrayDataHandle &operator = (const GeomVertexArrayDataHandle &) = delete; + INLINE Thread *get_current_thread() const; INLINE const unsigned char *get_read_pointer(bool force) const RETURNS_ALIGNED(MEMORY_HOOK_ALIGNMENT); @@ -314,10 +316,10 @@ PUBLISHED: PyObject *buffer, size_t from_start, size_t from_size)); - INLINE string get_data() const; - void set_data(const string &data); - INLINE string get_subdata(size_t start, size_t size) const; - void set_subdata(size_t start, size_t size, const string &data); + INLINE vector_uchar get_data() const; + void set_data(const vector_uchar &data); + INLINE vector_uchar get_subdata(size_t start, size_t size) const; + void set_subdata(size_t start, size_t size, const vector_uchar &data); INLINE void mark_used() const; @@ -348,7 +350,7 @@ private: friend class GeomVertexArrayData; }; -INLINE ostream &operator << (ostream &out, const GeomVertexArrayData &obj); +INLINE std::ostream &operator << (std::ostream &out, const GeomVertexArrayData &obj); #include "geomVertexArrayData.I" diff --git a/panda/src/gobj/geomVertexArrayData_ext.cxx b/panda/src/gobj/geomVertexArrayData_ext.cxx index 72b206c469..73c795f0b5 100644 --- a/panda/src/gobj/geomVertexArrayData_ext.cxx +++ b/panda/src/gobj/geomVertexArrayData_ext.cxx @@ -19,7 +19,7 @@ struct InternalBufferData { CPT(GeomVertexArrayDataHandle) _handle; Py_ssize_t _num_rows; Py_ssize_t _stride; - string _format; + std::string _format; }; /** @@ -54,7 +54,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) { view->internal = (void*) data; - if (self != NULL) { + if (self != nullptr) { Py_INCREF(self); } view->obj = self; @@ -62,20 +62,20 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) { view->len = row_size * handle->get_num_rows(); view->readonly = 0; view->itemsize = row_size; - view->format = NULL; + view->format = nullptr; if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) { view->format = (char*) data->_format.c_str(); } view->ndim = 1; - view->shape = NULL; + view->shape = nullptr; if ((flags & PyBUF_ND) == PyBUF_ND) { view->shape = &data->_num_rows; } - view->strides = NULL; + view->strides = nullptr; if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) { view->strides = &data->_stride; } - view->suboffsets = NULL; + view->suboffsets = nullptr; return 0; #else @@ -120,7 +120,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const { view->internal = (void*) data; - if (self != NULL) { + if (self != nullptr) { Py_INCREF(self); } view->obj = self; @@ -128,20 +128,20 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const { view->len = row_size * handle->get_num_rows(); view->readonly = 1; view->itemsize = row_size; - view->format = NULL; + view->format = nullptr; if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) { view->format = (char*) data->_format.c_str(); } view->ndim = 1; - view->shape = NULL; + view->shape = nullptr; if ((flags & PyBUF_ND) == PyBUF_ND) { view->shape = &data->_num_rows; } - view->strides = NULL; + view->strides = nullptr; if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) { view->strides = &data->_stride; } - view->suboffsets = NULL; + view->suboffsets = nullptr; return 0; #else @@ -158,11 +158,11 @@ __releasebuffer__(PyObject *self, Py_buffer *view) const { // Note: PyBuffer_Release automatically decrements view->obj. InternalBufferData *data; data = (InternalBufferData *) view->internal; - if (data == NULL) { + if (data == nullptr) { return; } delete data; - view->internal = NULL; + view->internal = nullptr; #endif } @@ -251,8 +251,8 @@ copy_subdata_from(size_t to_start, size_t to_size, } size_t from_buffer_orig_size = (size_t) view.len; - from_start = min(from_start, from_buffer_orig_size); - from_size = min(from_size, from_buffer_orig_size - from_start); + from_start = std::min(from_start, from_buffer_orig_size); + from_size = std::min(from_size, from_buffer_orig_size - from_start); _this->copy_subdata_from(to_start, to_size, (const unsigned char *) view.buf, diff --git a/panda/src/gobj/geomVertexArrayFormat.I b/panda/src/gobj/geomVertexArrayFormat.I index 1765b0fcc4..10fb6b8329 100644 --- a/panda/src/gobj/geomVertexArrayFormat.I +++ b/panda/src/gobj/geomVertexArrayFormat.I @@ -126,7 +126,7 @@ get_num_columns() const { */ INLINE const GeomVertexColumn *GeomVertexArrayFormat:: get_column(int i) const { - nassertr(i >= 0 && i < (int)_columns.size(), NULL); + nassertr(i >= 0 && i < (int)_columns.size(), nullptr); consider_sort_columns(); return _columns[(size_t)i]; } @@ -136,7 +136,7 @@ get_column(int i) const { */ INLINE bool GeomVertexArrayFormat:: has_column(const InternalName *name) const { - return (get_column(name) != (GeomVertexColumn *)NULL); + return (get_column(name) != nullptr); } /** @@ -144,7 +144,7 @@ has_column(const InternalName *name) const { */ INLINE GeomVertexArrayFormat::Registry *GeomVertexArrayFormat:: get_registry() { - if (_registry == (Registry *)NULL) { + if (_registry == nullptr) { make_registry(); } return _registry; @@ -160,8 +160,8 @@ consider_sort_columns() const { } } -INLINE ostream & -operator << (ostream &out, const GeomVertexArrayFormat &obj) { +INLINE std::ostream & +operator << (std::ostream &out, const GeomVertexArrayFormat &obj) { obj.output(out); return out; } diff --git a/panda/src/gobj/geomVertexArrayFormat.cxx b/panda/src/gobj/geomVertexArrayFormat.cxx index 20568fa1a3..578e99d805 100644 --- a/panda/src/gobj/geomVertexArrayFormat.cxx +++ b/panda/src/gobj/geomVertexArrayFormat.cxx @@ -21,7 +21,11 @@ #include "indirectLess.h" #include "lightMutexHolder.h" -GeomVertexArrayFormat::Registry *GeomVertexArrayFormat::_registry = NULL; +using std::max; +using std::min; +using std::move; + +GeomVertexArrayFormat::Registry *GeomVertexArrayFormat::_registry = nullptr; TypeHandle GeomVertexArrayFormat::_type_handle; /** @@ -52,7 +56,7 @@ GeomVertexArrayFormat(CPT_InternalName name0, int num_components0, _divisor(0), _columns_unsorted(false) { - add_column(MOVE(name0), num_components0, numeric_type0, contents0); + add_column(move(name0), num_components0, numeric_type0, contents0); } /** @@ -72,8 +76,8 @@ GeomVertexArrayFormat(CPT_InternalName name0, int num_components0, _divisor(0), _columns_unsorted(false) { - add_column(MOVE(name0), num_components0, numeric_type0, contents0); - add_column(MOVE(name1), num_components1, numeric_type1, contents1); + add_column(move(name0), num_components0, numeric_type0, contents0); + add_column(move(name1), num_components1, numeric_type1, contents1); } /** @@ -96,9 +100,9 @@ GeomVertexArrayFormat(CPT_InternalName name0, int num_components0, _divisor(0), _columns_unsorted(false) { - add_column(MOVE(name0), num_components0, numeric_type0, contents0); - add_column(MOVE(name1), num_components1, numeric_type1, contents1); - add_column(MOVE(name2), num_components2, numeric_type2, contents2); + add_column(move(name0), num_components0, numeric_type0, contents0); + add_column(move(name1), num_components1, numeric_type1, contents1); + add_column(move(name2), num_components2, numeric_type2, contents2); } /** @@ -124,10 +128,10 @@ GeomVertexArrayFormat(CPT_InternalName name0, int num_components0, _divisor(0), _columns_unsorted(false) { - add_column(MOVE(name0), num_components0, numeric_type0, contents0); - add_column(MOVE(name1), num_components1, numeric_type1, contents1); - add_column(MOVE(name2), num_components2, numeric_type2, contents2); - add_column(MOVE(name3), num_components3, numeric_type3, contents3); + add_column(move(name0), num_components0, numeric_type0, contents0); + add_column(move(name1), num_components1, numeric_type1, contents1); + add_column(move(name2), num_components2, numeric_type2, contents2); + add_column(move(name3), num_components3, numeric_type3, contents3); } /** @@ -219,7 +223,7 @@ add_column(CPT_InternalName name, int num_components, start = _total_bytes; } - return add_column(GeomVertexColumn(MOVE(name), num_components, numeric_type, contents, + return add_column(GeomVertexColumn(move(name), num_components, numeric_type, contents, start, column_alignment)); } @@ -243,7 +247,7 @@ add_column(const GeomVertexColumn &column) { // Also make sure there aren't any columns that overlap with this one. const GeomVertexColumn *orig_column = get_column(column.get_start(), column.get_total_bytes()); - while (orig_column != (const GeomVertexColumn *)NULL) { + while (orig_column != nullptr) { remove_column(orig_column->get_name()); orig_column = get_column(column.get_start(), column.get_total_bytes()); } @@ -381,7 +385,7 @@ get_column(const InternalName *name) const { if (ni != _columns_by_name.end()) { return (*ni).second; } - return NULL; + return nullptr; } /** @@ -399,7 +403,7 @@ get_column(int start_byte, int num_bytes) const { } } - return NULL; + return nullptr; } /** @@ -460,7 +464,7 @@ count_unused_space() const { * */ void GeomVertexArrayFormat:: -output(ostream &out) const { +output(std::ostream &out) const { Columns::const_iterator ci; int last_pos = 0; out << "["; @@ -484,7 +488,7 @@ output(ostream &out) const { * */ void GeomVertexArrayFormat:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "Array format (stride = " << get_stride() << "):\n"; consider_sort_columns(); @@ -503,7 +507,7 @@ write(ostream &out, int indent_level) const { * */ void GeomVertexArrayFormat:: -write_with_data(ostream &out, int indent_level, +write_with_data(std::ostream &out, int indent_level, const GeomVertexArrayData *array_data) const { consider_sort_columns(); int num_rows = array_data->get_num_rows(); @@ -536,7 +540,7 @@ write_with_data(ostream &out, int indent_level, * the columns in memory, as understood by Python's struct module. If pad is * true, extra padding bytes are added to the end as 'x' characters as needed. */ -string GeomVertexArrayFormat:: +std::string GeomVertexArrayFormat:: get_format_string(bool pad) const { consider_sort_columns(); @@ -553,9 +557,7 @@ get_format_string(bool pad) const { int fi = 0; int offset = 0; - for (int ci = 0; ci < get_num_columns(); ++ci) { - const GeomVertexColumn *column = get_column(ci); - + for (const GeomVertexColumn *column : _columns) { if (offset < column->get_start()) { // Add padding bytes to fill the gap. int pad = column->get_start() - offset; @@ -603,7 +605,7 @@ get_format_string(bool pad) const { default: gobj_cat.error() << "Unknown numeric type " << column->get_numeric_type() << "!\n"; - return NULL; + return nullptr; } memset((void*) (fmt + fi), fmt_code, column->get_num_components()); offset += column->get_total_bytes(); @@ -616,7 +618,7 @@ get_format_string(bool pad) const { memset((void*) (fmt + fi), 'x', pad); } - string fmt_string (fmt); + std::string fmt_string (fmt); free(fmt); return fmt_string; } @@ -667,7 +669,7 @@ sort_columns() { */ void GeomVertexArrayFormat:: make_registry() { - if (_registry == (Registry *)NULL) { + if (_registry == nullptr) { _registry = new Registry; } } diff --git a/panda/src/gobj/geomVertexArrayFormat.h b/panda/src/gobj/geomVertexArrayFormat.h index 3b8ca3a221..2cb8aa5f14 100644 --- a/panda/src/gobj/geomVertexArrayFormat.h +++ b/panda/src/gobj/geomVertexArrayFormat.h @@ -44,7 +44,7 @@ class BamReader; * "normal", "texcoord", and "color"; other kinds of data may be piggybacked * into the data record simply by choosing a unique name. */ -class EXPCL_PANDA_GOBJ GeomVertexArrayFormat FINAL : public TypedWritableReferenceCount, public GeomEnums { +class EXPCL_PANDA_GOBJ GeomVertexArrayFormat final : public TypedWritableReferenceCount, public GeomEnums { PUBLISHED: GeomVertexArrayFormat(); GeomVertexArrayFormat(const GeomVertexArrayFormat ©); @@ -113,12 +113,12 @@ PUBLISHED: bool is_data_subset_of(const GeomVertexArrayFormat &other) const; int count_unused_space() const; - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; - void write_with_data(ostream &out, int indent_level, + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; + void write_with_data(std::ostream &out, int indent_level, const GeomVertexArrayData *array_data) const; - string get_format_string(bool pad = true) const; + std::string get_format_string(bool pad = true) const; public: int compare_to(const GeomVertexArrayFormat &other) const; @@ -192,7 +192,7 @@ private: friend class GeomVertexFormat; }; -INLINE ostream &operator << (ostream &out, const GeomVertexArrayFormat &obj); +INLINE std::ostream &operator << (std::ostream &out, const GeomVertexArrayFormat &obj); #include "geomVertexArrayFormat.I" diff --git a/panda/src/gobj/geomVertexColumn.I b/panda/src/gobj/geomVertexColumn.I index 4d6c5c3b68..b382071eac 100644 --- a/panda/src/gobj/geomVertexColumn.I +++ b/panda/src/gobj/geomVertexColumn.I @@ -16,7 +16,7 @@ */ INLINE GeomVertexColumn:: GeomVertexColumn() : - _packer(NULL) + _packer(nullptr) { } @@ -28,7 +28,7 @@ GeomVertexColumn(CPT_InternalName name, int num_components, NumericType numeric_type, Contents contents, int start, int column_alignment, int num_elements, int element_stride) : - _name(MOVE(name)), + _name(std::move(name)), _num_components(num_components), _numeric_type(numeric_type), _contents(contents), @@ -36,7 +36,7 @@ GeomVertexColumn(CPT_InternalName name, int num_components, _column_alignment(column_alignment), _num_elements(num_elements), _element_stride(element_stride), - _packer(NULL) + _packer(nullptr) { setup(); } @@ -54,7 +54,7 @@ GeomVertexColumn(const GeomVertexColumn ©) : _column_alignment(copy._column_alignment), _num_elements(copy._num_elements), _element_stride(copy._element_stride), - _packer(NULL) + _packer(nullptr) { setup(); } @@ -300,8 +300,8 @@ operator < (const GeomVertexColumn &other) const { return 0; } -INLINE ostream & -operator << (ostream &out, const GeomVertexColumn &obj) { +INLINE std::ostream & +operator << (std::ostream &out, const GeomVertexColumn &obj) { obj.output(out); return out; } diff --git a/panda/src/gobj/geomVertexColumn.cxx b/panda/src/gobj/geomVertexColumn.cxx index 3227eb7b42..d04b69a307 100644 --- a/panda/src/gobj/geomVertexColumn.cxx +++ b/panda/src/gobj/geomVertexColumn.cxx @@ -16,6 +16,9 @@ #include "bamReader.h" #include "bamWriter.h" +using std::max; +using std::min; + /** * */ @@ -97,7 +100,7 @@ set_column_alignment(int column_alignment) { * */ void GeomVertexColumn:: -output(ostream &out) const { +output(std::ostream &out) const { out << *get_name() << "(" << get_num_components(); switch (get_numeric_type()) { case NT_uint8: @@ -225,7 +228,7 @@ setup() { } _total_bytes = _element_stride * _num_elements; - if (_packer != NULL) { + if (_packer != nullptr) { delete _packer; } @@ -3869,9 +3872,9 @@ set_data3f(unsigned char *pointer, const LVecBase3f &data) { { LVecBase3f scaled = data * 4294967295.0f; uint32_t *pi = (uint32_t *)pointer; - pi[0] = (unsigned int)data[0]; - pi[1] = (unsigned int)data[1]; - pi[2] = (unsigned int)data[2]; + pi[0] = (unsigned int)scaled[0]; + pi[1] = (unsigned int)scaled[1]; + pi[2] = (unsigned int)scaled[2]; } break; @@ -3960,10 +3963,10 @@ set_data4f(unsigned char *pointer, const LVecBase4f &data) { { LVecBase4f scaled = data * 4294967295.0f; uint32_t *pi = (uint32_t *)pointer; - pi[0] = (unsigned int)data[0]; - pi[1] = (unsigned int)data[1]; - pi[2] = (unsigned int)data[2]; - pi[3] = (unsigned int)data[3]; + pi[0] = (unsigned int)scaled[0]; + pi[1] = (unsigned int)scaled[1]; + pi[2] = (unsigned int)scaled[2]; + pi[3] = (unsigned int)scaled[3]; } break; @@ -4072,9 +4075,9 @@ set_data3d(unsigned char *pointer, const LVecBase3d &data) { { LVecBase3d scaled = data * 4294967295.0; uint32_t *pi = (uint32_t *)pointer; - pi[0] = (unsigned int)data[0]; - pi[1] = (unsigned int)data[1]; - pi[2] = (unsigned int)data[2]; + pi[0] = (unsigned int)scaled[0]; + pi[1] = (unsigned int)scaled[1]; + pi[2] = (unsigned int)scaled[2]; } break; @@ -4163,10 +4166,10 @@ set_data4d(unsigned char *pointer, const LVecBase4d &data) { { LVecBase4d scaled = data * 4294967295.0; uint32_t *pi = (uint32_t *)pointer; - pi[0] = (unsigned int)data[0]; - pi[1] = (unsigned int)data[1]; - pi[2] = (unsigned int)data[2]; - pi[3] = (unsigned int)data[3]; + pi[0] = (unsigned int)scaled[0]; + pi[1] = (unsigned int)scaled[1]; + pi[2] = (unsigned int)scaled[2]; + pi[3] = (unsigned int)scaled[3]; } break; diff --git a/panda/src/gobj/geomVertexColumn.h b/panda/src/gobj/geomVertexColumn.h index 5e8df9821e..1ff36b3eda 100644 --- a/panda/src/gobj/geomVertexColumn.h +++ b/panda/src/gobj/geomVertexColumn.h @@ -69,7 +69,7 @@ PUBLISHED: void set_start(int start); void set_column_alignment(int column_alignment); - void output(ostream &out) const; + void output(std::ostream &out) const; public: INLINE bool is_packed_argb() const; @@ -342,7 +342,7 @@ private: } }; - class Packer_nativedouble_3 FINAL : public Packer_float64_3 { + class Packer_nativedouble_3 final : public Packer_float64_3 { public: virtual const LVecBase3d &get_data3d(const unsigned char *pointer); @@ -351,7 +351,7 @@ private: } }; - class Packer_point_nativedouble_2 FINAL : public Packer_point_float64_2 { + class Packer_point_nativedouble_2 final : public Packer_point_float64_2 { public: virtual const LVecBase2d &get_data2d(const unsigned char *pointer); @@ -360,7 +360,7 @@ private: } }; - class Packer_point_nativedouble_3 FINAL : public Packer_point_float64_3 { + class Packer_point_nativedouble_3 final : public Packer_point_float64_3 { public: virtual const LVecBase3d &get_data3d(const unsigned char *pointer); @@ -378,7 +378,7 @@ private: } }; - class Packer_argb_packed FINAL : public Packer_color { + class Packer_argb_packed final : public Packer_color { public: virtual const LVecBase4f &get_data4f(const unsigned char *pointer); virtual void set_data4f(unsigned char *pointer, const LVecBase4f &value); @@ -388,7 +388,7 @@ private: } }; - class Packer_rgba_uint8_4 FINAL : public Packer_color { + class Packer_rgba_uint8_4 final : public Packer_color { public: virtual const LVecBase4f &get_data4f(const unsigned char *pointer); virtual void set_data4f(unsigned char *pointer, const LVecBase4f &value); @@ -408,7 +408,7 @@ private: } }; - class Packer_rgba_nativefloat_4 FINAL : public Packer_rgba_float32_4 { + class Packer_rgba_nativefloat_4 final : public Packer_rgba_float32_4 { public: virtual const LVecBase4f &get_data4f(const unsigned char *pointer); @@ -417,7 +417,7 @@ private: } }; - class Packer_uint16_1 FINAL : public Packer { + class Packer_uint16_1 final : public Packer { public: virtual int get_data1i(const unsigned char *pointer); virtual void set_data1i(unsigned char *pointer, int value); @@ -433,7 +433,7 @@ private: friend class GeomVertexWriter; }; -INLINE ostream &operator << (ostream &out, const GeomVertexColumn &obj); +INLINE std::ostream &operator << (std::ostream &out, const GeomVertexColumn &obj); #include "geomVertexColumn.I" diff --git a/panda/src/gobj/geomVertexData.I b/panda/src/gobj/geomVertexData.I index 5a24b166a5..bfea5a10ef 100644 --- a/panda/src/gobj/geomVertexData.I +++ b/panda/src/gobj/geomVertexData.I @@ -15,7 +15,7 @@ * Returns the name passed to the constructor, if any. This name is reported * on the PStats graph for vertex computations. */ -INLINE const string &GeomVertexData:: +INLINE const std::string &GeomVertexData:: get_name() const { return _name; } @@ -220,7 +220,7 @@ get_transform_table() const { */ INLINE void GeomVertexData:: clear_transform_table() { - set_transform_table(NULL); + set_transform_table(nullptr); } /** @@ -245,7 +245,7 @@ get_transform_blend_table() const { */ INLINE void GeomVertexData:: clear_transform_blend_table() { - set_transform_blend_table(NULL); + set_transform_blend_table(nullptr); } /** @@ -268,7 +268,7 @@ get_slider_table() const { */ INLINE void GeomVertexData:: clear_slider_table() { - set_slider_table(NULL); + set_slider_table(nullptr); } /** @@ -476,7 +476,7 @@ unpack_ufloat_c(uint32_t data) { INLINE int GeomVertexData:: add_transform(TransformTable *table, const VertexTransform *transform, TransformMap &already_added) { - pair result = already_added.insert(TransformMap::value_type(transform, table->get_num_transforms())); + std::pair result = already_added.insert(TransformMap::value_type(transform, table->get_num_transforms())); if (result.second) { table->add_transform(transform); @@ -519,16 +519,14 @@ CacheKey(const CacheKey ©) : { } -#ifdef USE_MOVE_SEMANTICS /** * */ INLINE GeomVertexData::CacheKey:: -CacheKey(CacheKey &&from) NOEXCEPT : - _modifier(move(from._modifier)) +CacheKey(CacheKey &&from) noexcept : + _modifier(std::move(from._modifier)) { } -#endif // USE_MOVE_SEMANTICS /** * Provides a unique ordering within the set. @@ -558,17 +556,15 @@ CacheEntry(GeomVertexData *source, const CacheKey &key) : { } -#ifdef USE_MOVE_SEMANTICS /** * */ INLINE GeomVertexData::CacheEntry:: -CacheEntry(GeomVertexData *source, CacheKey &&key) NOEXCEPT : +CacheEntry(GeomVertexData *source, CacheKey &&key) noexcept : _source(source), - _key(move(key)) + _key(std::move(key)) { } -#endif // USE_MOVE_SEMANTICS /** * @@ -641,8 +637,8 @@ INLINE GeomVertexDataPipelineBase:: #endif // DO_PIPELINING #ifdef _DEBUG - _object = NULL; - _cdata = NULL; + _object = nullptr; + _cdata = nullptr; #endif // _DEBUG } @@ -681,7 +677,7 @@ has_column(const InternalName *name) const { /** * */ -INLINE int GeomVertexDataPipelineBase:: +INLINE size_t GeomVertexDataPipelineBase:: get_num_arrays() const { return _cdata->_arrays.size(); } @@ -690,8 +686,8 @@ get_num_arrays() const { * */ INLINE CPT(GeomVertexArrayData) GeomVertexDataPipelineBase:: -get_array(int i) const { - nassertr(i >= 0 && i < (int)_cdata->_arrays.size(), NULL); +get_array(size_t i) const { + nassertr(i < _cdata->_arrays.size(), nullptr); return _cdata->_arrays[i].get_read_pointer(); } @@ -755,7 +751,7 @@ GeomVertexDataPipelineReader(const GeomVertexData *object, INLINE void GeomVertexDataPipelineReader:: set_object(const GeomVertexData *object) { #ifdef DO_PIPELINING - if (_cdata != NULL) { + if (_cdata != nullptr) { unref_delete((CycleData *)_cdata); } #endif // DO_PIPELINING @@ -791,8 +787,8 @@ check_array_readers() const { */ INLINE const GeomVertexArrayDataHandle *GeomVertexDataPipelineReader:: get_array_reader(int i) const { - nassertr(_got_array_readers, NULL); - nassertr(i >= 0 && i < (int)_array_readers.size(), NULL); + nassertr(_got_array_readers, nullptr); + nassertr(i >= 0 && i < (int)_array_readers.size(), nullptr); return _array_readers[i]; } @@ -801,7 +797,7 @@ get_array_reader(int i) const { */ INLINE bool GeomVertexDataPipelineReader:: has_vertex() const { - return (_cdata->_format->get_vertex_column() != (GeomVertexColumn *)NULL); + return (_cdata->_format->get_vertex_column() != nullptr); } /** @@ -810,7 +806,7 @@ has_vertex() const { INLINE bool GeomVertexDataPipelineReader:: is_vertex_transformed() const { const GeomVertexColumn *column = _cdata->_format->get_vertex_column(); - if (column != (GeomVertexColumn *)NULL) { + if (column != nullptr) { return column->get_contents() == C_clip_point; } @@ -822,7 +818,7 @@ is_vertex_transformed() const { */ INLINE bool GeomVertexDataPipelineReader:: has_normal() const { - return (_cdata->_format->get_normal_column() != (GeomVertexColumn *)NULL); + return (_cdata->_format->get_normal_column() != nullptr); } /** @@ -830,7 +826,7 @@ has_normal() const { */ INLINE bool GeomVertexDataPipelineReader:: has_color() const { - return (_cdata->_format->get_color_column() != (GeomVertexColumn *)NULL); + return (_cdata->_format->get_color_column() != nullptr); } /** @@ -841,7 +837,6 @@ GeomVertexDataPipelineWriter(GeomVertexData *object, bool force_to_0, Thread *current_thread) : GeomVertexDataPipelineBase(object, current_thread, object->_cycler.write_upstream(force_to_0, current_thread)), - _force_to_0(force_to_0), _got_array_writers(false) { #ifdef _DEBUG @@ -886,13 +881,13 @@ check_array_writers() const { */ INLINE GeomVertexArrayDataHandle *GeomVertexDataPipelineWriter:: get_array_writer(size_t i) const { - nassertr(_got_array_writers, NULL); + nassertr(_got_array_writers, nullptr); nassertr(i < _array_writers.size(), nullptr); return _array_writers[i]; } -INLINE ostream & -operator << (ostream &out, const GeomVertexData &obj) { +INLINE std::ostream & +operator << (std::ostream &out, const GeomVertexData &obj) { obj.output(out); return out; } diff --git a/panda/src/gobj/geomVertexData.cxx b/panda/src/gobj/geomVertexData.cxx index 7d8e0e63f3..5e5fa7a1d4 100644 --- a/panda/src/gobj/geomVertexData.cxx +++ b/panda/src/gobj/geomVertexData.cxx @@ -22,6 +22,8 @@ #include "pset.h" #include "indent.h" +using std::ostream; + TypeHandle GeomVertexData::_type_handle; TypeHandle GeomVertexData::CDataCache::_type_handle; TypeHandle GeomVertexData::CacheEntry::_type_handle; @@ -60,7 +62,7 @@ make_cow_copy() { * */ GeomVertexData:: -GeomVertexData(const string &name, +GeomVertexData(const std::string &name, const GeomVertexFormat *format, GeomVertexData::UsageHint usage_hint) : _name(name), @@ -89,7 +91,7 @@ GeomVertexData(const GeomVertexData ©) : OPEN_ITERATE_ALL_STAGES(_cycler) { CDStageWriter cdata(_cycler, pipeline_stage); // It's important that we *not* copy the animated_vertices pointer. - cdata->_animated_vertices = NULL; + cdata->_animated_vertices = nullptr; cdata->_animated_vertices_modified = UpdateSeq(); } CLOSE_ITERATE_ALL_STAGES(_cycler); @@ -128,7 +130,7 @@ GeomVertexData(const GeomVertexData ©, } // It's important that we *not* copy the animated_vertices pointer. - cdata->_animated_vertices = NULL; + cdata->_animated_vertices = nullptr; cdata->_animated_vertices_modified = UpdateSeq(); } CLOSE_ITERATE_ALL_STAGES(_cycler); @@ -155,7 +157,7 @@ operator = (const GeomVertexData ©) { OPEN_ITERATE_ALL_STAGES(_cycler) { CDStageWriter cdata(_cycler, pipeline_stage); cdata->_modified = Geom::get_next_modified(); - cdata->_animated_vertices = NULL; + cdata->_animated_vertices = nullptr; cdata->_animated_vertices_modified = UpdateSeq(); } CLOSE_ITERATE_ALL_STAGES(_cycler); @@ -210,7 +212,7 @@ compare_to(const GeomVertexData &other) const { * graph for vertex computations. */ void GeomVertexData:: -set_name(const string &name) { +set_name(const std::string &name) { _name = name; _char_pcollector = PStatCollector(_animation_pcollector, name); _skinning_pcollector = PStatCollector(_char_pcollector, "Skinning"); @@ -342,7 +344,7 @@ void GeomVertexData:: clear_rows() { Thread *current_thread = Thread::get_current_thread(); CDWriter cdata(_cycler, true, current_thread); - nassertv(cdata->_format->get_num_arrays() == (int)cdata->_arrays.size()); + nassertv(cdata->_format->get_num_arrays() == cdata->_arrays.size()); Arrays::iterator ai; for (ai = cdata->_arrays.begin(); @@ -367,7 +369,7 @@ clear_rows() { void GeomVertexData:: set_transform_table(const TransformTable *table) { Thread *current_thread = Thread::get_current_thread(); - nassertv(table == (TransformTable *)NULL || table->is_registered()); + nassertv(table == nullptr || table->is_registered()); CDWriter cdata(_cycler, true, current_thread); cdata->_transform_table = (TransformTable *)table; @@ -425,7 +427,7 @@ set_transform_blend_table(const TransformBlendTable *table) { */ void GeomVertexData:: set_slider_table(const SliderTable *table) { - nassertv(table == (SliderTable *)NULL || table->is_registered()); + nassertv(table == nullptr || table->is_registered()); CDWriter cdata(_cycler, true); cdata->_slider_table = (SliderTable *)table; @@ -540,7 +542,7 @@ copy_from(const GeomVertexData *source, bool keep_data_objects, dest_format->get_array(dest_i); const GeomVertexColumn *dest_column = dest_array_format->get_column(source_column->get_name()); - nassertv(dest_column != (const GeomVertexColumn *)NULL); + nassertv(dest_column != nullptr); if (dest_column->is_bytewise_equivalent(*source_column)) { // We can do a quick bytewise copy. @@ -604,7 +606,7 @@ copy_from(const GeomVertexData *source, bool keep_data_objects, // Convert Panda-style animation tables to hardware-style animation // tables. CPT(TransformBlendTable) blend_table = source->get_transform_blend_table(); - if (blend_table != (TransformBlendTable *)NULL) { + if (blend_table != nullptr) { PT(TransformTable) transform_table = new TransformTable; TransformMap already_added; @@ -725,14 +727,14 @@ convert_to(const GeomVertexFormat *new_format) const { } else { entry = (*ci).second; _cache_lock.release(); - nassertr(entry->_source == this, NULL); + nassertr(entry->_source == this, nullptr); // Here's an element in the cache for this computation. Record a cache // hit, so this element will stay in the cache a while longer. entry->refresh(current_thread); CDCacheReader cdata(entry->_cycler); - if (cdata->_result != (GeomVertexData *)NULL) { + if (cdata->_result != nullptr) { return cdata->_result; } @@ -758,14 +760,11 @@ convert_to(const GeomVertexFormat *new_format) const { new_data->copy_from(this, false); // Record the new result in the cache. - if (entry == (CacheEntry *)NULL) { + if (entry == nullptr) { // Create a new entry for the result. -#ifdef USE_MOVE_SEMANTICS // We don't need the key anymore, move the pointers into the CacheEntry. - entry = new CacheEntry((GeomVertexData *)this, move(key)); -#else - entry = new CacheEntry((GeomVertexData *)this, key); -#endif + entry = new CacheEntry((GeomVertexData *)this, std::move(key)); + { LightMutexHolder holder(_cache_lock); bool inserted = ((GeomVertexData *)this)->_cache.insert(Cache::value_type(&entry->_key, entry)).second; @@ -798,7 +797,7 @@ CPT(GeomVertexData) GeomVertexData:: scale_color(const LVecBase4 &color_scale) const { const GeomVertexColumn *old_column = get_format()->get_column(InternalName::get_color()); - if (old_column == (GeomVertexColumn *)NULL) { + if (old_column == nullptr) { return this; } @@ -869,7 +868,7 @@ CPT(GeomVertexData) GeomVertexData:: set_color(const LColor &color) const { const GeomVertexColumn *old_column = get_format()->get_column(InternalName::get_color()); - if (old_column == (GeomVertexColumn *)NULL) { + if (old_column == nullptr) { return this; } @@ -913,7 +912,7 @@ CPT(GeomVertexData) GeomVertexData:: reverse_normals() const { const GeomVertexColumn *old_column = get_format()->get_column(InternalName::get_normal()); - if (old_column == (GeomVertexColumn *)NULL) { + if (old_column == nullptr) { return this; } @@ -970,15 +969,15 @@ animate_vertices(bool force, Thread *current_thread) const { { PStatTimer timer2(((GeomVertexData *)this)->_blends_pcollector, current_thread); if (!cdata->_transform_blend_table.is_null()) { - if (cdata->_slider_table != (SliderTable *)NULL) { + if (cdata->_slider_table != nullptr) { modified = - max(cdata->_transform_blend_table.get_read_pointer()->get_modified(current_thread), + std::max(cdata->_transform_blend_table.get_read_pointer()->get_modified(current_thread), cdata->_slider_table->get_modified(current_thread)); } else { modified = cdata->_transform_blend_table.get_read_pointer()->get_modified(current_thread); } - } else if (cdata->_slider_table != (SliderTable *)NULL) { + } else if (cdata->_slider_table != nullptr) { modified = cdata->_slider_table->get_modified(current_thread); } else { @@ -988,14 +987,14 @@ animate_vertices(bool force, Thread *current_thread) const { } if (cdata->_animated_vertices_modified == modified && - cdata->_animated_vertices != (GeomVertexData *)NULL) { + cdata->_animated_vertices != nullptr) { // No changes. return cdata->_animated_vertices; } if (!force && !request_resident()) { // The vertex data isn't resident. Return the best information we've got. - if (cdata->_animated_vertices != (GeomVertexData *)NULL) { + if (cdata->_animated_vertices != nullptr) { return cdata->_animated_vertices; } return this; @@ -1115,7 +1114,7 @@ do_set_color(GeomVertexData *vdata, const LColor &color) { size_t stride = format->get_array(array_index)->get_stride(); GeomVertexColumn::Packer *packer = column->_packer; - nassertv(packer != NULL); + nassertv(packer != nullptr); // Pack into a buffer, which we will then copy. unsigned char buffer[32]; @@ -1287,7 +1286,7 @@ write(ostream &out, int indent_level) const { } get_format()->write_with_data(out, indent_level + 2, this); CPT(TransformBlendTable) table = get_transform_blend_table(); - if (table != (TransformBlendTable *)NULL) { + if (table != nullptr) { indent(out, indent_level) << "Transform blend table:\n"; table->write(out, indent_level + 2); @@ -1308,7 +1307,7 @@ describe_vertex(ostream &out, int row) const { reader.set_row_unsafe(row); const GeomVertexFormat *format = get_format(); - const TransformBlendTable *tb_table = NULL; + const TransformBlendTable *tb_table = nullptr; if (format->get_animation().get_animation_type() == AT_panda) { tb_table = get_transform_blend_table(); } @@ -1319,7 +1318,7 @@ describe_vertex(ostream &out, int row) const { const GeomVertexColumn *column = format->get_column(ci); reader.set_column(ai, column); - int num_values = min(column->get_num_values(), 4); + int num_values = std::min(column->get_num_values(), 4); const LVecBase4 &d = reader.get_data4(); out << " " << *column->get_name(); @@ -1329,7 +1328,7 @@ describe_vertex(ostream &out, int row) const { out << "\n"; if (column->get_name() == InternalName::get_transform_blend() && - tb_table != NULL) { + tb_table != nullptr) { // This is an index into the transform blend table. Look up the index // and report the vertex weighting. reader.set_column(ai, column); @@ -1347,15 +1346,15 @@ describe_vertex(ostream &out, int row) const { for (int ai = 0; ai < num_arrays; ++ai) { const GeomVertexArrayData *array = get_array(ai); const GeomVertexArrayFormat *aformat = format->get_array(ai); - nassertv(array != NULL && aformat != NULL); + nassertv(array != nullptr && aformat != nullptr); out << " " << *aformat << "\n"; CPT(GeomVertexArrayDataHandle) handle = array->get_handle(); - nassertv(handle != (const GeomVertexArrayDataHandle *)NULL); + nassertv(handle != nullptr); const unsigned char *data = handle->get_read_pointer(true); - nassertv(data != NULL); + nassertv(data != nullptr); int stride = aformat->get_stride(); int start = stride * row; - if (data != NULL) { + if (data != nullptr) { Datagram dg(data + start, stride); dg.dump_hex(out, 4); } @@ -1396,7 +1395,7 @@ clear_cache_stage() { ++ci) { CacheEntry *entry = (*ci).second; CDCacheWriter cdata(entry->_cycler); - cdata->_result = NULL; + cdata->_result = nullptr; } } @@ -1469,11 +1468,11 @@ update_animated_vertices(GeomVertexData::CData *cdata, Thread *current_thread) { const GeomVertexFormat *orig_format = cdata->_format; CPT(GeomVertexFormat) new_format = orig_format; - if (cdata->_animated_vertices == (GeomVertexData *)NULL) { + if (cdata->_animated_vertices == nullptr) { new_format = orig_format->get_post_animated_format(); cdata->_animated_vertices = new GeomVertexData(get_name(), new_format, - min(get_usage_hint(), UH_dynamic)); + std::min(get_usage_hint(), UH_dynamic)); } PT(GeomVertexData) new_data = cdata->_animated_vertices; @@ -1485,7 +1484,7 @@ update_animated_vertices(GeomVertexData::CData *cdata, Thread *current_thread) { // First, apply all of the morphs. CPT(SliderTable) slider_table = cdata->_slider_table; - if (slider_table != (SliderTable *)NULL) { + if (slider_table != nullptr) { PStatTimer timer2(_morphs_pcollector); int num_morphs = orig_format->get_num_morphs(); for (int mi = 0; mi < num_morphs; mi++) { @@ -1568,7 +1567,7 @@ update_animated_vertices(GeomVertexData::CData *cdata, Thread *current_thread) { // Then apply the transforms. CPT(TransformBlendTable) tb_table = cdata->_transform_blend_table.get_read_pointer(current_thread); - if (tb_table != (TransformBlendTable *)NULL) { + if (tb_table != nullptr) { // Recompute all the blends up front, so we don't have to test each one // for staleness at each vertex. { @@ -2075,14 +2074,14 @@ finalize(BamReader *manager) { array_obj->_array_format = new_array_format; } - if (cdata->_transform_table != (TransformTable *)NULL) { + if (cdata->_transform_table != nullptr) { CPT(TransformTable) new_transform_table = TransformTable::register_table(cdata->_transform_table); manager->change_pointer(cdata->_transform_table, new_transform_table); cdata->_transform_table = new_transform_table; } - if (cdata->_slider_table != (SliderTable *)NULL) { + if (cdata->_slider_table != nullptr) { CPT(SliderTable) new_slider_table = SliderTable::register_table(cdata->_slider_table); manager->change_pointer(cdata->_slider_table, new_slider_table); @@ -2189,7 +2188,7 @@ complete_pointers(TypedWritable **p_list, BamReader *manager) { CPT(GeomVertexArrayData) adata = _arrays[0].get_read_pointer(); all_rows.set_range(0, adata->get_num_rows()); - if (_slider_table != (SliderTable *)NULL) { + if (_slider_table != nullptr) { int num_sliders = _slider_table->get_num_sliders(); for (int i = 0; i < num_sliders; ++i) { ((SliderTable *)_slider_table.p())->set_slider_rows(i, all_rows); @@ -2216,7 +2215,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { _arrays.reserve(num_arrays); for (size_t i = 0; i < num_arrays; ++i) { manager->read_pointer(scan); - _arrays.push_back(NULL); + _arrays.push_back(nullptr); } manager->read_pointer(scan); @@ -2244,7 +2243,7 @@ get_num_bytes() const { */ int GeomVertexDataPipelineReader:: get_num_rows() const { - nassertr(_cdata->_format->get_num_arrays() == (int)_cdata->_arrays.size(), 0); + nassertr(_cdata->_format->get_num_arrays() == _cdata->_arrays.size(), 0); nassertr(_got_array_readers, 0); if (_cdata->_format->get_num_arrays() == 0) { @@ -2396,7 +2395,7 @@ make_array_readers() { */ int GeomVertexDataPipelineWriter:: get_num_rows() const { - nassertr(_cdata->_format->get_num_arrays() == (int)_cdata->_arrays.size(), 0); + nassertr(_cdata->_format->get_num_arrays() == _cdata->_arrays.size(), 0); nassertr(_got_array_writers, 0); if (_cdata->_format->get_num_arrays() == 0) { @@ -2415,7 +2414,7 @@ get_num_rows() const { bool GeomVertexDataPipelineWriter:: set_num_rows(int n) { nassertr(_got_array_writers, false); - nassertr(_cdata->_format->get_num_arrays() == (int)_cdata->_arrays.size(), false); + nassertr(_cdata->_format->get_num_arrays() == _cdata->_arrays.size(), false); bool any_changed = false; @@ -2511,7 +2510,7 @@ set_num_rows(int n) { bool GeomVertexDataPipelineWriter:: unclean_set_num_rows(int n) { nassertr(_got_array_writers, false); - nassertr(_cdata->_format->get_num_arrays() == (int)_cdata->_arrays.size(), false); + nassertr(_cdata->_format->get_num_arrays() == _cdata->_arrays.size(), false); bool any_changed = false; @@ -2538,7 +2537,7 @@ unclean_set_num_rows(int n) { bool GeomVertexDataPipelineWriter:: reserve_num_rows(int n) { nassertr(_got_array_writers, false); - nassertr(_cdata->_format->get_num_arrays() == (int)_cdata->_arrays.size(), false); + nassertr(_cdata->_format->get_num_arrays() == _cdata->_arrays.size(), false); bool any_changed = false; diff --git a/panda/src/gobj/geomVertexData.h b/panda/src/gobj/geomVertexData.h index d86dd36fc4..9b861c1cbc 100644 --- a/panda/src/gobj/geomVertexData.h +++ b/panda/src/gobj/geomVertexData.h @@ -72,7 +72,7 @@ protected: virtual PT(CopyOnWriteObject) make_cow_copy(); PUBLISHED: - explicit GeomVertexData(const string &name, + explicit GeomVertexData(const std::string &name, const GeomVertexFormat *format, UsageHint usage_hint); GeomVertexData(const GeomVertexData ©); @@ -84,8 +84,8 @@ PUBLISHED: int compare_to(const GeomVertexData &other) const; - INLINE const string &get_name() const; - void set_name(const string &name); + INLINE const std::string &get_name() const; + void set_name(const std::string &name); MAKE_PROPERTY(name, get_name, set_name); INLINE UsageHint get_usage_hint() const; @@ -164,9 +164,9 @@ PUBLISHED: replace_column(InternalName *name, int num_components, NumericType numeric_type, Contents contents) const; - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; - void describe_vertex(ostream &out, int row) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; + void describe_vertex(std::ostream &out, int row) const; void clear_cache(); void clear_cache_stage(); @@ -206,7 +206,7 @@ private: TransformMap &already_added); private: - string _name; + std::string _name; typedef pvector< COWPT(GeomVertexArrayData) > Arrays; @@ -246,9 +246,7 @@ public: public: INLINE CacheKey(const GeomVertexFormat *modifier); INLINE CacheKey(const CacheKey ©); -#ifdef USE_MOVE_SEMANTICS - INLINE CacheKey(CacheKey &&from) NOEXCEPT; -#endif + INLINE CacheKey(CacheKey &&from) noexcept; INLINE bool operator < (const CacheKey &other) const; @@ -260,13 +258,12 @@ public: INLINE CacheEntry(GeomVertexData *source, const GeomVertexFormat *modifier); INLINE CacheEntry(GeomVertexData *source, const CacheKey &key); -#ifdef USE_MOVE_SEMANTICS - INLINE CacheEntry(GeomVertexData *source, CacheKey &&key) NOEXCEPT; -#endif + INLINE CacheEntry(GeomVertexData *source, CacheKey &&key) noexcept; + ALLOC_DELETED_CHAIN(CacheEntry); virtual void evict_callback(); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; GeomVertexData *_source; // A back pointer to the containing data. CacheKey _key; @@ -410,22 +407,20 @@ protected: Thread *current_thread, GeomVertexData::CData *cdata); -private: - GeomVertexDataPipelineBase(const GeomVertexDataPipelineBase ©) DELETED; - GeomVertexDataPipelineBase &operator = (const GeomVertexDataPipelineBase ©) DELETED_ASSIGN; - public: + GeomVertexDataPipelineBase(const GeomVertexDataPipelineBase ©) = delete; INLINE ~GeomVertexDataPipelineBase(); -public: + GeomVertexDataPipelineBase &operator = (const GeomVertexDataPipelineBase ©) = delete; + INLINE Thread *get_current_thread() const; INLINE const GeomVertexFormat *get_format() const; INLINE bool has_column(const InternalName *name) const; INLINE UsageHint get_usage_hint() const; - INLINE int get_num_arrays() const; - INLINE CPT(GeomVertexArrayData) get_array(int i) const; + INLINE size_t get_num_arrays() const; + INLINE CPT(GeomVertexArrayData) get_array(size_t i) const; INLINE const TransformTable *get_transform_table() const; INLINE CPT(TransformBlendTable) get_transform_blend_table() const; INLINE const SliderTable *get_slider_table() const; @@ -535,7 +530,6 @@ private: void make_array_writers(); void delete_array_writers(); - bool _force_to_0; bool _got_array_writers; typedef pvector ArrayWriters; ArrayWriters _array_writers; @@ -552,7 +546,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const GeomVertexData &obj); +INLINE std::ostream &operator << (std::ostream &out, const GeomVertexData &obj); #include "geomVertexData.I" diff --git a/panda/src/gobj/geomVertexFormat.I b/panda/src/gobj/geomVertexFormat.I index 2879599cc5..a6f85e57ff 100644 --- a/panda/src/gobj/geomVertexFormat.I +++ b/panda/src/gobj/geomVertexFormat.I @@ -11,8 +11,8 @@ * @date 2005-03-07 */ -INLINE ostream & -operator << (ostream &out, const GeomVertexFormat &obj) { +INLINE std::ostream & +operator << (std::ostream &out, const GeomVertexFormat &obj) { obj.output(out); return out; } @@ -88,7 +88,7 @@ get_num_arrays() const { */ INLINE const GeomVertexArrayFormat *GeomVertexFormat:: get_array(size_t array) const { - nassertr(array < _arrays.size(), NULL); + nassertr(array < _arrays.size(), nullptr); return _arrays[array]; } @@ -97,7 +97,7 @@ get_array(size_t array) const { */ INLINE bool GeomVertexFormat:: has_column(const InternalName *name) const { - return (get_column(name) != (GeomVertexColumn *)NULL); + return (get_column(name) != nullptr); } /** @@ -120,8 +120,8 @@ get_num_points() const { */ INLINE const InternalName *GeomVertexFormat:: get_point(size_t n) const { - nassertr(_is_registered, NULL); - nassertr(n < _points.size(), NULL); + nassertr(_is_registered, nullptr); + nassertr(n < _points.size(), nullptr); return _points[n]; } @@ -146,8 +146,8 @@ get_num_vectors() const { */ INLINE const InternalName *GeomVertexFormat:: get_vector(size_t n) const { - nassertr(_is_registered, NULL); - nassertr(n < _vectors.size(), NULL); + nassertr(_is_registered, nullptr); + nassertr(n < _vectors.size(), nullptr); return _vectors[n]; } @@ -171,8 +171,8 @@ get_num_texcoords() const { */ INLINE const InternalName *GeomVertexFormat:: get_texcoord(size_t n) const { - nassertr(_is_registered, NULL); - nassertr(n < _texcoords.size(), NULL); + nassertr(_is_registered, nullptr); + nassertr(n < _texcoords.size(), nullptr); return _texcoords[n]; } @@ -198,8 +198,8 @@ get_num_morphs() const { */ INLINE const InternalName *GeomVertexFormat:: get_morph_slider(size_t n) const { - nassertr(_is_registered, NULL); - nassertr(n < _morphs.size(), NULL); + nassertr(_is_registered, nullptr); + nassertr(n < _morphs.size(), nullptr); return _morphs[n]._slider; } @@ -213,8 +213,8 @@ get_morph_slider(size_t n) const { */ INLINE const InternalName *GeomVertexFormat:: get_morph_base(size_t n) const { - nassertr(_is_registered, NULL); - nassertr(n < _morphs.size(), NULL); + nassertr(_is_registered, nullptr); + nassertr(n < _morphs.size(), nullptr); return _morphs[n]._base; } @@ -229,8 +229,8 @@ get_morph_base(size_t n) const { */ INLINE const InternalName *GeomVertexFormat:: get_morph_delta(size_t n) const { - nassertr(_is_registered, NULL); - nassertr(n < _morphs.size(), NULL); + nassertr(_is_registered, nullptr); + nassertr(n < _morphs.size(), nullptr); return _morphs[n]._delta; } @@ -373,7 +373,7 @@ get_vertex_array_index() const { */ INLINE const GeomVertexColumn *GeomVertexFormat:: get_vertex_column() const { - nassertr(_is_registered, NULL); + nassertr(_is_registered, nullptr); return _vertex_column; } @@ -397,7 +397,7 @@ get_normal_array_index() const { */ INLINE const GeomVertexColumn *GeomVertexFormat:: get_normal_column() const { - nassertr(_is_registered, NULL); + nassertr(_is_registered, nullptr); return _normal_column; } @@ -421,7 +421,7 @@ get_color_array_index() const { */ INLINE const GeomVertexColumn *GeomVertexFormat:: get_color_column() const { - nassertr(_is_registered, NULL); + nassertr(_is_registered, nullptr); return _color_column; } @@ -430,7 +430,7 @@ get_color_column() const { */ INLINE GeomVertexFormat::Registry *GeomVertexFormat:: get_registry() { - if (_registry == (Registry *)NULL) { + if (_registry == nullptr) { make_registry(); } return _registry; diff --git a/panda/src/gobj/geomVertexFormat.cxx b/panda/src/gobj/geomVertexFormat.cxx index f3652e8321..2b3479cc4f 100644 --- a/panda/src/gobj/geomVertexFormat.cxx +++ b/panda/src/gobj/geomVertexFormat.cxx @@ -19,7 +19,7 @@ #include "bamReader.h" #include "bamWriter.h" -GeomVertexFormat::Registry *GeomVertexFormat::_registry = NULL; +GeomVertexFormat::Registry *GeomVertexFormat::_registry = nullptr; TypeHandle GeomVertexFormat::_type_handle; /** @@ -28,7 +28,7 @@ TypeHandle GeomVertexFormat::_type_handle; GeomVertexFormat:: GeomVertexFormat() : _is_registered(false), - _post_animated_format(NULL) + _post_animated_format(nullptr) { } @@ -38,7 +38,7 @@ GeomVertexFormat() : GeomVertexFormat:: GeomVertexFormat(const GeomVertexArrayFormat *array_format) : _is_registered(false), - _post_animated_format(NULL) + _post_animated_format(nullptr) { add_array(array_format); } @@ -51,7 +51,7 @@ GeomVertexFormat(const GeomVertexFormat ©) : _is_registered(false), _animation(copy._animation), _arrays(copy._arrays), - _post_animated_format(NULL) + _post_animated_format(nullptr) { } @@ -105,9 +105,9 @@ unref() const { */ CPT(GeomVertexFormat) GeomVertexFormat:: get_post_animated_format() const { - nassertr(is_registered(), NULL); + nassertr(is_registered(), nullptr); - if (_post_animated_format == (GeomVertexFormat *)NULL) { + if (_post_animated_format == nullptr) { PT(GeomVertexFormat) new_format = new GeomVertexFormat(*this); new_format->remove_column(InternalName::get_transform_blend()); @@ -145,7 +145,7 @@ get_post_animated_format() const { */ CPT(GeomVertexFormat) GeomVertexFormat:: get_union_format(const GeomVertexFormat *other) const { - nassertr(is_registered() && other->is_registered(), NULL); + nassertr(is_registered() && other->is_registered(), nullptr); PT(GeomVertexFormat) new_format = new GeomVertexFormat; @@ -173,7 +173,7 @@ get_union_format(const GeomVertexFormat *other) const { // D, E) in array 1. In general, a column will appear in the result in the // first array it appears in either of the inputs. - size_t num_arrays = max(_arrays.size(), other->_arrays.size()); + size_t num_arrays = std::max(_arrays.size(), other->_arrays.size()); for (size_t ai = 0; ai < num_arrays; ++ai) { PT(GeomVertexArrayFormat) new_array = new GeomVertexArrayFormat; @@ -186,7 +186,7 @@ get_union_format(const GeomVertexFormat *other) const { bool inserted = column_names.insert(column_a->get_name()).second; if (inserted) { const GeomVertexColumn *column_b = other->get_column(column_a->get_name()); - if (column_b != (GeomVertexColumn *)NULL && + if (column_b != nullptr && column_b->get_total_bytes() > column_a->get_total_bytes()) { // Column b is larger. Keep it. new_array->add_column(column_b->get_name(), @@ -213,7 +213,7 @@ get_union_format(const GeomVertexFormat *other) const { bool inserted = column_names.insert(column_a->get_name()).second; if (inserted) { const GeomVertexColumn *column_b = get_column(column_a->get_name()); - if (column_b != (GeomVertexColumn *)NULL && + if (column_b != nullptr && column_b->get_total_bytes() > column_a->get_total_bytes()) { // Column b is larger. Keep it. new_array->add_column(column_b->get_name(), @@ -248,8 +248,8 @@ get_union_format(const GeomVertexFormat *other) const { */ GeomVertexArrayFormat *GeomVertexFormat:: modify_array(size_t array) { - nassertr(!is_registered(), NULL); - nassertr(array < _arrays.size(), NULL); + nassertr(!is_registered(), nullptr); + nassertr(array < _arrays.size(), nullptr); if (_arrays[array]->is_registered() || _arrays[array]->get_ref_count() > 1) { @@ -376,7 +376,7 @@ get_column(size_t i) const { i -= (*ai)->get_num_columns(); } - return NULL; + return nullptr; } /** @@ -450,11 +450,11 @@ get_column(const InternalName *name) const { Arrays::const_iterator ai; for (ai = _arrays.begin(); ai != _arrays.end(); ++ai) { const GeomVertexColumn *column = (*ai)->get_column(name); - if (column != (GeomVertexColumn *)NULL) { + if (column != nullptr) { return column; } } - return NULL; + return nullptr; } else { // If the format has been registered, we can just check the toplevel @@ -466,10 +466,10 @@ get_column(const InternalName *name) const { int array_index = (*ai).second._array_index; int column_index = (*ai).second._column_index; - nassertr(array_index >= 0 && array_index < (int)_arrays.size(), NULL); + nassertr(array_index >= 0 && array_index < (int)_arrays.size(), nullptr); return _arrays[array_index]->get_column(column_index); } - return NULL; + return nullptr; } } @@ -491,7 +491,7 @@ remove_column(const InternalName *name, bool keep_empty_array) { for (int array = 0; array < (int)_arrays.size(); ++array) { GeomVertexArrayFormat *array_format = _arrays[array]; - if (array_format->get_column(name) != (GeomVertexColumn *)NULL) { + if (array_format->get_column(name) != nullptr) { // Here's the array with the named column! if (array_format->is_registered() || array_format->get_ref_count() > 1) { @@ -565,7 +565,7 @@ maybe_align_columns_for_animation() { * */ void GeomVertexFormat:: -output(ostream &out) const { +output(std::ostream &out) const { if (_arrays.empty()) { out << "(empty)"; @@ -589,7 +589,7 @@ output(ostream &out) const { * */ void GeomVertexFormat:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { for (size_t i = 0; i < _arrays.size(); i++) { indent(out, indent_level) << "Array " << i << ":\n"; @@ -606,7 +606,7 @@ write(ostream &out, int indent_level) const { * */ void GeomVertexFormat:: -write_with_data(ostream &out, int indent_level, +write_with_data(std::ostream &out, int indent_level, const GeomVertexData *data) const { indent(out, indent_level) << data->get_num_rows() << " rows.\n"; @@ -642,7 +642,7 @@ get_array_info(const InternalName *name, int &array_index, } array_index = -1; - column = NULL; + column = nullptr; return false; } @@ -676,7 +676,7 @@ compare_to(const GeomVertexFormat &other) const { */ void GeomVertexFormat:: make_registry() { - if (_registry == (Registry *)NULL) { + if (_registry == nullptr) { _registry = new Registry; _registry->make_standard_formats(); } @@ -716,7 +716,7 @@ do_register() { int num_columns = array_format->get_num_columns(); for (int i = 0; i < num_columns; i++) { const GeomVertexColumn *column = array_format->get_column(i); - pair result; + std::pair result; result = _columns_by_name.insert(DataTypesByName::value_type(column->get_name(), DataTypeRecord())); if (!result.second) { gobj_cat.warning() @@ -813,11 +813,11 @@ do_unregister() { _texcoords.clear(); _morphs.clear(); - if (_post_animated_format != (GeomVertexFormat *)NULL && + if (_post_animated_format != nullptr && _post_animated_format != this) { unref_delete(_post_animated_format); } - _post_animated_format = NULL; + _post_animated_format = nullptr; } /** @@ -892,7 +892,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { _arrays.reserve(num_arrays); for (int i = 0; i < num_arrays; i++) { manager->read_pointer(scan); - _arrays.push_back(NULL); + _arrays.push_back(nullptr); } } diff --git a/panda/src/gobj/geomVertexFormat.h b/panda/src/gobj/geomVertexFormat.h index aa2ef4606a..82eec7f8a9 100644 --- a/panda/src/gobj/geomVertexFormat.h +++ b/panda/src/gobj/geomVertexFormat.h @@ -52,7 +52,7 @@ class GeomMunger; * standard and/or user-defined columns in your custom GeomVertexFormat * constructions. */ -class EXPCL_PANDA_GOBJ GeomVertexFormat FINAL : public TypedWritableReferenceCount, public GeomEnums { +class EXPCL_PANDA_GOBJ GeomVertexFormat final : public TypedWritableReferenceCount, public GeomEnums { PUBLISHED: GeomVertexFormat(); GeomVertexFormat(const GeomVertexArrayFormat *array_format); @@ -129,9 +129,9 @@ PUBLISHED: MAKE_MAP_PROPERTY(columns, has_column, get_column); MAKE_MAP_KEYS_SEQ(columns, get_num_columns, get_column_name); - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; - void write_with_data(ostream &out, int indent_level, + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; + void write_with_data(std::ostream &out, int indent_level, const GeomVertexData *data) const; INLINE static const GeomVertexFormat *get_empty(); @@ -289,7 +289,7 @@ private: friend class GeomMunger; }; -INLINE ostream &operator << (ostream &out, const GeomVertexFormat &obj); +INLINE std::ostream &operator << (std::ostream &out, const GeomVertexFormat &obj); #include "geomVertexFormat.I" diff --git a/panda/src/gobj/geomVertexReader.I b/panda/src/gobj/geomVertexReader.I index 810f7e8f33..893d6458cf 100644 --- a/panda/src/gobj/geomVertexReader.I +++ b/panda/src/gobj/geomVertexReader.I @@ -18,7 +18,7 @@ */ INLINE GeomVertexReader:: GeomVertexReader(Thread *current_thread) : - _vertex_data(NULL), + _vertex_data(nullptr), _current_thread(current_thread) { initialize(); @@ -50,7 +50,7 @@ GeomVertexReader(const GeomVertexData *vertex_data, _current_thread(current_thread) { initialize(); - set_column(MOVE(name)); + set_column(std::move(name)); } /** @@ -227,7 +227,7 @@ get_force() const { */ INLINE bool GeomVertexReader:: set_column(int column) { - if (_vertex_data != (const GeomVertexData *)NULL) { + if (_vertex_data != nullptr) { GeomVertexDataPipelineReader reader(_vertex_data, _current_thread); reader.check_array_readers(); const GeomVertexFormat *format = reader.get_format(); @@ -235,7 +235,7 @@ set_column(int column) { format->get_column(column), &reader); } - if (_array_data != (const GeomVertexArrayData *)NULL) { + if (_array_data != nullptr) { return set_array_column(_array_data->get_array_format()->get_column(column)); } return false; @@ -252,7 +252,7 @@ set_column(int column) { */ INLINE bool GeomVertexReader:: set_column(CPT_InternalName name) { - if (_vertex_data != (const GeomVertexData *)NULL) { + if (_vertex_data != nullptr) { GeomVertexDataPipelineReader reader(_vertex_data, _current_thread); reader.check_array_readers(); const GeomVertexFormat *format = reader.get_format(); @@ -260,7 +260,7 @@ set_column(CPT_InternalName name) { format->get_column(name), &reader); } - if (_array_data != (const GeomVertexArrayData *)NULL) { + if (_array_data != nullptr) { return set_array_column(_array_data->get_array_format()->get_column(name)); } @@ -282,7 +282,7 @@ clear() { */ INLINE bool GeomVertexReader:: has_column() const { - return (_packer != (GeomVertexColumn::Packer *)NULL); + return (_packer != nullptr); } /** @@ -299,10 +299,10 @@ get_array() const { */ INLINE const GeomVertexColumn *GeomVertexReader:: get_column() const { - if (_packer != (GeomVertexColumn::Packer *)NULL) { + if (_packer != nullptr) { return _packer->_column; } - return NULL; + return nullptr; } /** @@ -683,9 +683,9 @@ get_packer() const { INLINE bool GeomVertexReader:: set_pointer(int row) { _pointer_begin = _handle->get_read_pointer(_force); - if (_pointer_begin == NULL && _handle->get_data_size_bytes() != 0) { + if (_pointer_begin == nullptr && _handle->get_data_size_bytes() != 0) { // Vertex data is not resident. - set_column(0, NULL); + set_column(0, nullptr); return false; } @@ -701,7 +701,7 @@ set_pointer(int row) { */ INLINE void GeomVertexReader:: quick_set_pointer(int row) { - nassertv(has_column() && (_pointer_begin != NULL || row == 0)); + nassertv(has_column() && (_pointer_begin != nullptr || row == 0)); #if defined(_DEBUG) // Make sure we still have the same pointer as stored in the array. diff --git a/panda/src/gobj/geomVertexReader.cxx b/panda/src/gobj/geomVertexReader.cxx index 054e7df942..c1a4f96051 100644 --- a/panda/src/gobj/geomVertexReader.cxx +++ b/panda/src/gobj/geomVertexReader.cxx @@ -13,7 +13,6 @@ #include "geomVertexReader.h" - #ifndef NDEBUG // This is defined just for the benefit of having something non-NULL to // return from a nassertr() call. @@ -32,23 +31,23 @@ const unsigned char GeomVertexReader::empty_buffer[100] = { 0 }; */ bool GeomVertexReader:: set_column(int array, const GeomVertexColumn *column) { - if (column == (const GeomVertexColumn *)NULL) { + if (column == nullptr) { // Clear the data type. _array = -1; - _packer = NULL; + _packer = nullptr; _stride = 0; - _pointer = NULL; - _pointer_end = NULL; + _pointer = nullptr; + _pointer_end = nullptr; return false; } - if (_vertex_data != (const GeomVertexData *)NULL) { + if (_vertex_data != nullptr) { GeomVertexDataPipelineReader reader(_vertex_data, _current_thread); reader.check_array_readers(); return set_vertex_column(array, column, &reader); } - if (_array_data != (const GeomVertexArrayData *)NULL) { + if (_array_data != nullptr) { return set_array_column(column); } @@ -60,9 +59,9 @@ set_column(int array, const GeomVertexColumn *column) { * */ void GeomVertexReader:: -output(ostream &out) const { +output(std::ostream &out) const { const GeomVertexColumn *column = get_column(); - if (column == (GeomVertexColumn *)NULL) { + if (column == nullptr) { out << "GeomVertexReader()"; } else { @@ -79,10 +78,10 @@ output(ostream &out) const { void GeomVertexReader:: initialize() { _array = 0; - _packer = NULL; - _pointer_begin = NULL; - _pointer_end = NULL; - _pointer = NULL; + _packer = nullptr; + _pointer_begin = nullptr; + _pointer_end = nullptr; + _pointer = nullptr; _start_row = 0; _force = true; } @@ -94,16 +93,16 @@ initialize() { bool GeomVertexReader:: set_vertex_column(int array, const GeomVertexColumn *column, const GeomVertexDataPipelineReader *data_reader) { - if (column == (const GeomVertexColumn *)NULL) { - return set_column(0, NULL); + if (column == nullptr) { + return set_column(0, nullptr); } - nassertr(_vertex_data != (const GeomVertexData *)NULL, false); + nassertr(_vertex_data != nullptr, false); #ifndef NDEBUG _array = -1; - _packer = NULL; - nassertr(array >= 0 && array < _vertex_data->get_num_arrays(), false); + _packer = nullptr; + nassertr(array >= 0 && (size_t)array < _vertex_data->get_num_arrays(), false); #endif _array = array; @@ -120,11 +119,11 @@ set_vertex_column(int array, const GeomVertexColumn *column, */ bool GeomVertexReader:: set_array_column(const GeomVertexColumn *column) { - if (column == (const GeomVertexColumn *)NULL) { - return set_column(0, NULL); + if (column == nullptr) { + return set_column(0, nullptr); } - nassertr(_array_data != (const GeomVertexArrayData *)NULL, false); + nassertr(_array_data != nullptr, false); _handle = _array_data->get_handle(); _stride = _handle->get_array_format()->get_stride(); diff --git a/panda/src/gobj/geomVertexReader.h b/panda/src/gobj/geomVertexReader.h index f657975a63..beb92b017e 100644 --- a/panda/src/gobj/geomVertexReader.h +++ b/panda/src/gobj/geomVertexReader.h @@ -119,7 +119,7 @@ PUBLISHED: INLINE const LVecBase3i &get_data3i(); INLINE const LVecBase4i &get_data4i(); - void output(ostream &out) const; + void output(std::ostream &out) const; protected: INLINE GeomVertexColumn::Packer *get_packer() const; @@ -162,8 +162,8 @@ private: #endif }; -INLINE ostream & -operator << (ostream &out, const GeomVertexReader &reader) { +INLINE std::ostream & +operator << (std::ostream &out, const GeomVertexReader &reader) { reader.output(out); return out; } diff --git a/panda/src/gobj/geomVertexRewriter.I b/panda/src/gobj/geomVertexRewriter.I index 933c545885..077dc3963c 100644 --- a/panda/src/gobj/geomVertexRewriter.I +++ b/panda/src/gobj/geomVertexRewriter.I @@ -45,7 +45,7 @@ GeomVertexRewriter(GeomVertexData *vertex_data, CPT_InternalName name, GeomVertexWriter(vertex_data, current_thread), GeomVertexReader(vertex_data, current_thread) { - set_column(MOVE(name)); + set_column(std::move(name)); } /** @@ -104,7 +104,7 @@ INLINE GeomVertexRewriter:: INLINE GeomVertexData *GeomVertexRewriter:: get_vertex_data() const { nassertr(GeomVertexWriter::get_vertex_data() == - GeomVertexReader::get_vertex_data(), NULL); + GeomVertexReader::get_vertex_data(), nullptr); return GeomVertexWriter::get_vertex_data(); } @@ -115,7 +115,7 @@ get_vertex_data() const { INLINE GeomVertexArrayData *GeomVertexRewriter:: get_array_data() const { nassertr(GeomVertexWriter::get_array_data() == - GeomVertexReader::get_array_data(), NULL); + GeomVertexReader::get_array_data(), nullptr); return GeomVertexWriter::get_array_data(); } @@ -148,7 +148,7 @@ get_stride() const { INLINE Thread *GeomVertexRewriter:: get_current_thread() const { nassertr(GeomVertexWriter::get_current_thread() == - GeomVertexReader::get_current_thread(), NULL); + GeomVertexReader::get_current_thread(), nullptr); return GeomVertexWriter::get_current_thread(); } @@ -184,7 +184,7 @@ set_column(CPT_InternalName name) { // It's important to invoke the writer first, then the reader. See // set_row(). GeomVertexWriter::set_column(name); - return GeomVertexReader::set_column(MOVE(name)); + return GeomVertexReader::set_column(std::move(name)); } /** @@ -242,7 +242,7 @@ get_array() const { INLINE const GeomVertexColumn *GeomVertexRewriter:: get_column() const { nassertr(GeomVertexWriter::get_column() == - GeomVertexReader::get_column(), NULL); + GeomVertexReader::get_column(), nullptr); return GeomVertexWriter::get_column(); } diff --git a/panda/src/gobj/geomVertexRewriter.cxx b/panda/src/gobj/geomVertexRewriter.cxx index 304606a9c3..1bad4afd9d 100644 --- a/panda/src/gobj/geomVertexRewriter.cxx +++ b/panda/src/gobj/geomVertexRewriter.cxx @@ -17,9 +17,9 @@ * */ void GeomVertexRewriter:: -output(ostream &out) const { +output(std::ostream &out) const { const GeomVertexColumn *column = get_column(); - if (column == (GeomVertexColumn *)NULL) { + if (column == nullptr) { out << "GeomVertexRewriter()"; } else { diff --git a/panda/src/gobj/geomVertexRewriter.h b/panda/src/gobj/geomVertexRewriter.h index d9291ea06a..2ed1699522 100644 --- a/panda/src/gobj/geomVertexRewriter.h +++ b/panda/src/gobj/geomVertexRewriter.h @@ -65,11 +65,11 @@ PUBLISHED: INLINE int get_start_row() const; INLINE bool is_at_end() const; - void output(ostream &out) const; + void output(std::ostream &out) const; }; -INLINE ostream & -operator << (ostream &out, const GeomVertexRewriter &rewriter) { +INLINE std::ostream & +operator << (std::ostream &out, const GeomVertexRewriter &rewriter) { rewriter.output(out); return out; } diff --git a/panda/src/gobj/geomVertexWriter.I b/panda/src/gobj/geomVertexWriter.I index d3e1da87a3..b55fdd5f4a 100644 --- a/panda/src/gobj/geomVertexWriter.I +++ b/panda/src/gobj/geomVertexWriter.I @@ -18,7 +18,7 @@ */ INLINE GeomVertexWriter:: GeomVertexWriter(Thread *current_thread) : - _vertex_data(NULL), + _vertex_data(nullptr), _current_thread(current_thread) { initialize(); @@ -48,7 +48,7 @@ GeomVertexWriter(GeomVertexData *vertex_data, CPT_InternalName name, _current_thread(current_thread) { initialize(); - set_column(MOVE(name)); + set_column(std::move(name)); } /** @@ -199,7 +199,7 @@ get_current_thread() const { */ INLINE bool GeomVertexWriter:: set_column(int column) { - if (_vertex_data != (GeomVertexData *)NULL) { + if (_vertex_data != nullptr) { GeomVertexDataPipelineWriter writer(_vertex_data, true, _current_thread); writer.check_array_writers(); const GeomVertexFormat *format = writer.get_format(); @@ -207,7 +207,7 @@ set_column(int column) { format->get_column(column), &writer); } - if (_array_data != (GeomVertexArrayData *)NULL) { + if (_array_data != nullptr) { return set_array_column(_array_data->get_array_format()->get_column(column)); } return false; @@ -223,7 +223,7 @@ set_column(int column) { */ INLINE bool GeomVertexWriter:: set_column(CPT_InternalName name) { - if (_vertex_data != (GeomVertexData *)NULL) { + if (_vertex_data != nullptr) { GeomVertexDataPipelineWriter writer(_vertex_data, true, _current_thread); writer.check_array_writers(); const GeomVertexFormat *format = writer.get_format(); @@ -231,7 +231,7 @@ set_column(CPT_InternalName name) { format->get_column(name), &writer); } - if (_array_data != (GeomVertexArrayData *)NULL) { + if (_array_data != nullptr) { return set_array_column(_array_data->get_array_format()->get_column(name)); } return false; @@ -251,7 +251,7 @@ clear() { */ INLINE bool GeomVertexWriter:: has_column() const { - return (_packer != (GeomVertexColumn::Packer *)NULL); + return (_packer != nullptr); } /** @@ -268,10 +268,10 @@ get_array() const { */ INLINE const GeomVertexColumn *GeomVertexWriter:: get_column() const { - if (_packer != (GeomVertexColumn::Packer *)NULL) { + if (_packer != nullptr) { return _packer->_column; } - return NULL; + return nullptr; } /** @@ -1376,19 +1376,19 @@ inc_add_pointer() { // Reset the data pointer. int write_row = get_write_row(); - if (_vertex_data != (GeomVertexData *)NULL) { + if (_vertex_data != nullptr) { // If we have a whole GeomVertexData, we must set the length of all its // arrays at once. - _handle = NULL; + _handle = nullptr; GeomVertexDataPipelineWriter writer(_vertex_data, true, _current_thread); writer.check_array_writers(); - writer.set_num_rows(max(write_row + 1, writer.get_num_rows())); + writer.set_num_rows(std::max(write_row + 1, writer.get_num_rows())); _handle = writer.get_array_writer(_array); } else { // Otherwise, we can get away with modifying only the one array we're // using. - _handle->set_num_rows(max(write_row + 1, _handle->get_num_rows())); + _handle->set_num_rows(std::max(write_row + 1, _handle->get_num_rows())); } set_pointer(write_row); diff --git a/panda/src/gobj/geomVertexWriter.cxx b/panda/src/gobj/geomVertexWriter.cxx index ef05c3bc44..eaae2603ac 100644 --- a/panda/src/gobj/geomVertexWriter.cxx +++ b/panda/src/gobj/geomVertexWriter.cxx @@ -13,7 +13,6 @@ #include "geomVertexWriter.h" - #ifdef _DEBUG // This is defined just for the benefit of having something non-NULL to // return from a nassertr() call. @@ -32,28 +31,28 @@ unsigned char GeomVertexWriter::empty_buffer[100] = { 0 }; */ bool GeomVertexWriter:: set_column(int array, const GeomVertexColumn *column) { - if (_vertex_data == (GeomVertexData *)NULL && - _array_data == (GeomVertexArrayData *)NULL) { + if (_vertex_data == nullptr && + _array_data == nullptr) { return false; } - if (column == (const GeomVertexColumn *)NULL) { + if (column == nullptr) { // Clear the data type. _array = -1; - _packer = NULL; + _packer = nullptr; _stride = 0; - _pointer = NULL; - _pointer_end = NULL; + _pointer = nullptr; + _pointer_end = nullptr; return false; } - if (_vertex_data != (GeomVertexData *)NULL) { + if (_vertex_data != nullptr) { GeomVertexDataPipelineWriter writer(_vertex_data, true, _current_thread); writer.check_array_writers(); return set_vertex_column(array, column, &writer); } - if (_array_data != (GeomVertexArrayData *)NULL) { + if (_array_data != nullptr) { return set_array_column(column); } @@ -71,7 +70,7 @@ bool GeomVertexWriter:: reserve_num_rows(int num_rows) { bool result; - if (_vertex_data != (GeomVertexData *)NULL) { + if (_vertex_data != nullptr) { // If we have a whole GeomVertexData, we must set the length of all its // arrays at once. GeomVertexDataPipelineWriter writer(_vertex_data, true, _current_thread); @@ -92,9 +91,9 @@ reserve_num_rows(int num_rows) { * */ void GeomVertexWriter:: -output(ostream &out) const { +output(std::ostream &out) const { const GeomVertexColumn *column = get_column(); - if (column == (GeomVertexColumn *)NULL) { + if (column == nullptr) { out << "GeomVertexWriter()"; } else { @@ -111,10 +110,10 @@ output(ostream &out) const { void GeomVertexWriter:: initialize() { _array = 0; - _packer = NULL; - _pointer_begin = NULL; - _pointer_end = NULL; - _pointer = NULL; + _packer = nullptr; + _pointer_begin = nullptr; + _pointer_end = nullptr; + _pointer = nullptr; _start_row = 0; } @@ -125,16 +124,16 @@ initialize() { bool GeomVertexWriter:: set_vertex_column(int array, const GeomVertexColumn *column, GeomVertexDataPipelineWriter *data_writer) { - if (column == (const GeomVertexColumn *)NULL) { - return set_column(0, NULL); + if (column == nullptr) { + return set_column(0, nullptr); } - nassertr(_vertex_data != (GeomVertexData *)NULL, false); + nassertr(_vertex_data != nullptr, false); #ifndef NDEBUG _array = -1; - _packer = NULL; - nassertr(array >= 0 && array < _vertex_data->get_num_arrays(), false); + _packer = nullptr; + nassertr(array >= 0 && (size_t)array < _vertex_data->get_num_arrays(), false); #endif _array = array; @@ -153,11 +152,11 @@ set_vertex_column(int array, const GeomVertexColumn *column, */ bool GeomVertexWriter:: set_array_column(const GeomVertexColumn *column) { - if (column == (const GeomVertexColumn *)NULL) { - return set_column(0, NULL); + if (column == nullptr) { + return set_column(0, nullptr); } - nassertr(_array_data != (GeomVertexArrayData *)NULL, false); + nassertr(_array_data != nullptr, false); _handle = _array_data->modify_handle(); _stride = _handle->get_array_format()->get_stride(); diff --git a/panda/src/gobj/geomVertexWriter.h b/panda/src/gobj/geomVertexWriter.h index aaedaf565b..f50b0e1596 100644 --- a/panda/src/gobj/geomVertexWriter.h +++ b/panda/src/gobj/geomVertexWriter.h @@ -174,7 +174,7 @@ PUBLISHED: INLINE void add_data4i(int a, int b, int c, int d); INLINE void add_data4i(const LVecBase4i &data); - void output(ostream &out) const; + void output(std::ostream &out) const; protected: INLINE GeomVertexColumn::Packer *get_packer() const; @@ -219,8 +219,8 @@ private: #endif }; -INLINE ostream & -operator << (ostream &out, const GeomVertexWriter &writer) { +INLINE std::ostream & +operator << (std::ostream &out, const GeomVertexWriter &writer) { writer.output(out); return out; } diff --git a/panda/src/gobj/indexBufferContext.cxx b/panda/src/gobj/indexBufferContext.cxx index ebb65ea89f..2c3e68ba0b 100644 --- a/panda/src/gobj/indexBufferContext.cxx +++ b/panda/src/gobj/indexBufferContext.cxx @@ -19,7 +19,7 @@ TypeHandle IndexBufferContext::_type_handle; * */ void IndexBufferContext:: -output(ostream &out) const { +output(std::ostream &out) const { out << *get_data() << ", " << get_data_size_bytes(); } @@ -27,6 +27,6 @@ output(ostream &out) const { * */ void IndexBufferContext:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { SavedContext::write(out, indent_level); } diff --git a/panda/src/gobj/indexBufferContext.h b/panda/src/gobj/indexBufferContext.h index 4e3019c507..6b2004fac2 100644 --- a/panda/src/gobj/indexBufferContext.h +++ b/panda/src/gobj/indexBufferContext.h @@ -46,8 +46,8 @@ public: INLINE void mark_loaded(const GeomPrimitivePipelineReader *reader); INLINE void mark_unloaded(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; private: // This cannot be a PT(GeomPrimitive), because the data and the GSG both own @@ -75,7 +75,7 @@ private: friend class PreparedGraphicsObjects; }; -inline ostream &operator << (ostream &out, const IndexBufferContext &context) { +inline std::ostream &operator << (std::ostream &out, const IndexBufferContext &context) { context.output(out); return out; } diff --git a/panda/src/gobj/internalName.I b/panda/src/gobj/internalName.I index 69e88c4563..4773faeb14 100644 --- a/panda/src/gobj/internalName.I +++ b/panda/src/gobj/internalName.I @@ -22,7 +22,7 @@ * handled transparently. */ INLINE PT(InternalName) InternalName:: -make(const string &name) { +make(const std::string &name) { return get_root()->append(name); } @@ -63,7 +63,7 @@ get_parent() const { * Return the name represented by just this particular InternalName object, * ignoring its parents names. This is everything after the rightmost dot. */ -INLINE const string &InternalName:: +INLINE const std::string &InternalName:: get_basename() const { return _basename; } @@ -75,8 +75,8 @@ get_basename() const { */ INLINE PT(InternalName) InternalName:: get_root() { - if (_root == (InternalName *)NULL) { - _root = new InternalName(NULL, ""); + if (_root == nullptr) { + _root = new InternalName(nullptr, ""); } return _root; } @@ -86,7 +86,7 @@ get_root() { */ INLINE PT(InternalName) InternalName:: get_error() { - if (_error == (InternalName *)NULL) { + if (_error == nullptr) { _error = InternalName::make("error"); } return _error; @@ -98,7 +98,7 @@ get_error() { */ INLINE PT(InternalName) InternalName:: get_vertex() { - if (_vertex == (InternalName *)NULL) { + if (_vertex == nullptr) { _vertex = InternalName::make("vertex"); } return _vertex; @@ -110,7 +110,7 @@ get_vertex() { */ INLINE PT(InternalName) InternalName:: get_normal() { - if (_normal == (InternalName *)NULL) { + if (_normal == nullptr) { _normal = InternalName::make("normal"); } return _normal; @@ -124,7 +124,7 @@ get_normal() { */ INLINE PT(InternalName) InternalName:: get_tangent() { - if (_tangent == (InternalName *)NULL) { + if (_tangent == nullptr) { _tangent = InternalName::make("tangent"); } return _tangent; @@ -136,7 +136,7 @@ get_tangent() { * coordinate set. */ INLINE PT(InternalName) InternalName:: -get_tangent_name(const string &name) { +get_tangent_name(const std::string &name) { return get_tangent()->append(name); } @@ -149,7 +149,7 @@ get_tangent_name(const string &name) { */ INLINE PT(InternalName) InternalName:: get_binormal() { - if (_binormal == (InternalName *)NULL) { + if (_binormal == nullptr) { _binormal = InternalName::make("binormal"); } return _binormal; @@ -161,7 +161,7 @@ get_binormal() { * named texture coordinate set. */ INLINE PT(InternalName) InternalName:: -get_binormal_name(const string &name) { +get_binormal_name(const std::string &name) { return get_binormal()->append(name); } @@ -172,7 +172,7 @@ get_binormal_name(const string &name) { */ INLINE PT(InternalName) InternalName:: get_texcoord() { - if (_texcoord == (InternalName *)NULL) { + if (_texcoord == nullptr) { _texcoord = InternalName::make("texcoord"); } return _texcoord; @@ -185,7 +185,7 @@ get_texcoord() { * set in a TextureStage. */ INLINE PT(InternalName) InternalName:: -get_texcoord_name(const string &name) { +get_texcoord_name(const std::string &name) { return get_texcoord()->append(name); } @@ -195,7 +195,7 @@ get_texcoord_name(const string &name) { */ INLINE PT(InternalName) InternalName:: get_color() { - if (_color == (InternalName *)NULL) { + if (_color == nullptr) { _color = InternalName::make("color"); } return _color; @@ -208,7 +208,7 @@ get_color() { */ INLINE PT(InternalName) InternalName:: get_rotate() { - if (_rotate == (InternalName *)NULL) { + if (_rotate == nullptr) { _rotate = InternalName::make("rotate"); } return _rotate; @@ -221,7 +221,7 @@ get_rotate() { */ INLINE PT(InternalName) InternalName:: get_size() { - if (_size == (InternalName *)NULL) { + if (_size == nullptr) { _size = InternalName::make("size"); } return _size; @@ -235,7 +235,7 @@ get_size() { */ INLINE PT(InternalName) InternalName:: get_aspect_ratio() { - if (_aspect_ratio == (InternalName *)NULL) { + if (_aspect_ratio == nullptr) { _aspect_ratio = InternalName::make("aspect_ratio"); } return _aspect_ratio; @@ -249,7 +249,7 @@ get_aspect_ratio() { */ INLINE PT(InternalName) InternalName:: get_transform_blend() { - if (_transform_blend == (InternalName *)NULL) { + if (_transform_blend == nullptr) { _transform_blend = InternalName::make("transform_blend"); } return _transform_blend; @@ -266,7 +266,7 @@ get_transform_blend() { */ INLINE PT(InternalName) InternalName:: get_transform_weight() { - if (_transform_weight == (InternalName *)NULL) { + if (_transform_weight == nullptr) { _transform_weight = InternalName::make("transform_weight"); } return _transform_weight; @@ -282,7 +282,7 @@ get_transform_weight() { */ INLINE PT(InternalName) InternalName:: get_transform_index() { - if (_transform_index == (InternalName *)NULL) { + if (_transform_index == nullptr) { _transform_index = InternalName::make("transform_index"); } return _transform_index; @@ -298,7 +298,7 @@ get_transform_index() { * column it applies to. */ INLINE PT(InternalName) InternalName:: -get_morph(InternalName *column, const string &slider) { +get_morph(InternalName *column, const std::string &slider) { // This actually returns "column.morph.slider", although that's just an // implementation detail--as long as it returns a consistent, unique name // for each combination of column and slider, everything is good. @@ -312,7 +312,7 @@ get_morph(InternalName *column, const string &slider) { */ INLINE PT(InternalName) InternalName:: get_index() { - if (_index == (InternalName *)NULL) { + if (_index == nullptr) { _index = InternalName::make("index"); } return _index; @@ -324,7 +324,7 @@ get_index() { */ INLINE PT(InternalName) InternalName:: get_world() { - if (_world == (InternalName *)NULL) { + if (_world == nullptr) { _world = InternalName::make("world"); } return _world; @@ -336,7 +336,7 @@ get_world() { */ INLINE PT(InternalName) InternalName:: get_camera() { - if (_camera == (InternalName *)NULL) { + if (_camera == nullptr) { _camera = InternalName::make("camera"); } return _camera; @@ -348,7 +348,7 @@ get_camera() { */ INLINE PT(InternalName) InternalName:: get_model() { - if (_model == (InternalName *)NULL) { + if (_model == nullptr) { _model = InternalName::make("model"); } return _model; @@ -360,7 +360,7 @@ get_model() { */ INLINE PT(InternalName) InternalName:: get_view() { - if (_view == (InternalName *)NULL) { + if (_view == nullptr) { _view = InternalName::make("view"); } return _view; @@ -369,8 +369,8 @@ get_view() { /** * */ -INLINE ostream & -operator << (ostream &out, const InternalName &tcn) { +INLINE std::ostream & +operator << (std::ostream &out, const InternalName &tcn) { tcn.output(out); return out; } @@ -407,7 +407,7 @@ CPT_InternalName(const ConstPointerTo ©) : * */ INLINE CPT_InternalName:: -CPT_InternalName(const string &name) : +CPT_InternalName(const std::string &name) : ConstPointerTo(InternalName::make(name)) { } @@ -422,13 +422,12 @@ CPT_InternalName(const char (&literal)[N]) : { } -#ifdef USE_MOVE_SEMANTICS /** * */ INLINE CPT_InternalName:: -CPT_InternalName(PointerTo &&from) NOEXCEPT : - ConstPointerTo(move(from)) +CPT_InternalName(PointerTo &&from) noexcept : + ConstPointerTo(std::move(from)) { } @@ -436,8 +435,8 @@ CPT_InternalName(PointerTo &&from) NOEXCEPT : * */ INLINE CPT_InternalName:: -CPT_InternalName(ConstPointerTo &&from) NOEXCEPT : - ConstPointerTo(move(from)) +CPT_InternalName(ConstPointerTo &&from) noexcept : + ConstPointerTo(std::move(from)) { } @@ -445,8 +444,8 @@ CPT_InternalName(ConstPointerTo &&from) NOEXCEPT : * */ INLINE CPT_InternalName &CPT_InternalName:: -operator = (PointerTo &&from) NOEXCEPT { - this->reassign(move(from)); +operator = (PointerTo &&from) noexcept { + this->reassign(std::move(from)); return *this; } @@ -454,11 +453,10 @@ operator = (PointerTo &&from) NOEXCEPT { * */ INLINE CPT_InternalName &CPT_InternalName:: -operator = (ConstPointerTo &&from) NOEXCEPT { - this->reassign(move(from)); +operator = (ConstPointerTo &&from) noexcept { + this->reassign(std::move(from)); return *this; } -#endif // USE_MOVE_SEMANTICS /** * diff --git a/panda/src/gobj/internalName.cxx b/panda/src/gobj/internalName.cxx index dcebada06e..6803f9bab8 100644 --- a/panda/src/gobj/internalName.cxx +++ b/panda/src/gobj/internalName.cxx @@ -18,6 +18,8 @@ #include "bamReader.h" #include "preparedGraphicsObjects.h" +using std::string; + PT(InternalName) InternalName::_root; PT(InternalName) InternalName::_error; PT(InternalName) InternalName::_default; @@ -65,7 +67,7 @@ InternalName(InternalName *parent, const string &basename) : InternalName:: ~InternalName() { #ifndef NDEBUG - if (_parent != (const InternalName *)NULL) { + if (_parent != nullptr) { // unref() should have removed us from our parent's table already. LightMutexHolder holder(_parent->_name_table_lock); NameTable::iterator ni = _parent->_name_table.find(_basename); @@ -80,7 +82,7 @@ InternalName:: */ bool InternalName:: unref() const { - if (_parent == (const InternalName *)NULL) { + if (_parent == nullptr) { // No parent; no problem. This is the root InternalName. Actually, this // probably shouldn't be destructing, but I guess it might at application // shutdown. @@ -140,7 +142,7 @@ get_name() const { if (_parent == get_root()) { return _basename; - } else if (_parent == (InternalName *)NULL) { + } else if (_parent == nullptr) { return string(); } else { @@ -156,7 +158,7 @@ join(const string &sep) const { if (_parent == get_root()) { return _basename; - } else if (_parent == (InternalName *)NULL) { + } else if (_parent == nullptr) { return string(); } else { @@ -178,7 +180,7 @@ find_ancestor(const string &basename) const { if (_basename == basename) { return 0; - } else if (_parent != (InternalName *)NULL) { + } else if (_parent != nullptr) { int index = _parent->find_ancestor(basename); if (index >= 0) { return index + 1; @@ -200,7 +202,7 @@ get_ancestor(int n) const { if (n == 0) { return this; - } else if (_parent != (InternalName *)NULL) { + } else if (_parent != nullptr) { return _parent->get_ancestor(n - 1); } else { @@ -217,7 +219,7 @@ const InternalName *InternalName:: get_top() const { test_ref_count_integrity(); - if (_parent != (InternalName *)NULL && _parent != get_root()) { + if (_parent != nullptr && _parent != get_root()) { return _parent->get_top(); } return this; @@ -236,7 +238,7 @@ get_net_basename(int n) const { } else if (n == 0) { return _basename; - } else if (_parent != (InternalName *)NULL && _parent != get_root()) { + } else if (_parent != nullptr && _parent != get_root()) { return _parent->get_net_basename(n - 1) + "." + _basename; } else { @@ -248,11 +250,11 @@ get_net_basename(int n) const { * */ void InternalName:: -output(ostream &out) const { +output(std::ostream &out) const { if (_parent == get_root()) { out << _basename; - } else if (_parent == (InternalName *)NULL) { + } else if (_parent == nullptr) { out << "(root)"; } else { diff --git a/panda/src/gobj/internalName.h b/panda/src/gobj/internalName.h index eff928b668..729ec15ab8 100644 --- a/panda/src/gobj/internalName.h +++ b/panda/src/gobj/internalName.h @@ -35,12 +35,12 @@ class FactoryParams; * composition of one or more other names, or by giving it a source string * directly. */ -class EXPCL_PANDA_GOBJ InternalName FINAL : public TypedWritableReferenceCount { +class EXPCL_PANDA_GOBJ InternalName final : public TypedWritableReferenceCount { private: - InternalName(InternalName *parent, const string &basename); + InternalName(InternalName *parent, const std::string &basename); public: - INLINE static PT(InternalName) make(const string &name); + INLINE static PT(InternalName) make(const std::string &name); template INLINE static PT(InternalName) make(const char (&literal)[N]); @@ -49,24 +49,24 @@ PUBLISHED: virtual ~InternalName(); virtual bool unref() const; - static PT(InternalName) make(const string &name, int index); - PT(InternalName) append(const string &basename); + static PT(InternalName) make(const std::string &name, int index); + PT(InternalName) append(const std::string &basename); INLINE InternalName *get_parent() const; - string get_name() const; - string join(const string &sep) const; - INLINE const string &get_basename() const; + std::string get_name() const; + std::string join(const std::string &sep) const; + INLINE const std::string &get_basename() const; MAKE_PROPERTY(parent, get_parent); MAKE_PROPERTY(name, get_name); MAKE_PROPERTY(basename, get_basename); - int find_ancestor(const string &basename) const; + int find_ancestor(const std::string &basename) const; const InternalName *get_ancestor(int n) const; const InternalName *get_top() const; - string get_net_basename(int n) const; + std::string get_net_basename(int n) const; - void output(ostream &out) const; + void output(std::ostream &out) const; // Some predefined built-in names. INLINE static PT(InternalName) get_root(); @@ -74,11 +74,11 @@ PUBLISHED: INLINE static PT(InternalName) get_vertex(); INLINE static PT(InternalName) get_normal(); INLINE static PT(InternalName) get_tangent(); - INLINE static PT(InternalName) get_tangent_name(const string &name); + INLINE static PT(InternalName) get_tangent_name(const std::string &name); INLINE static PT(InternalName) get_binormal(); - INLINE static PT(InternalName) get_binormal_name(const string &name); + INLINE static PT(InternalName) get_binormal_name(const std::string &name); INLINE static PT(InternalName) get_texcoord(); - INLINE static PT(InternalName) get_texcoord_name(const string &name); + INLINE static PT(InternalName) get_texcoord_name(const std::string &name); INLINE static PT(InternalName) get_color(); INLINE static PT(InternalName) get_rotate(); INLINE static PT(InternalName) get_size(); @@ -86,7 +86,7 @@ PUBLISHED: INLINE static PT(InternalName) get_transform_blend(); INLINE static PT(InternalName) get_transform_weight(); INLINE static PT(InternalName) get_transform_index(); - INLINE static PT(InternalName) get_morph(InternalName *column, const string &slider); + INLINE static PT(InternalName) get_morph(InternalName *column, const std::string &slider); INLINE static PT(InternalName) get_index(); INLINE static PT(InternalName) get_world(); INLINE static PT(InternalName) get_camera(); @@ -113,9 +113,9 @@ public: private: PT(InternalName) _parent; - string _basename; + std::string _basename; - typedef phash_map NameTable; + typedef phash_map NameTable; NameTable _name_table; LightMutex _name_table_lock; @@ -182,7 +182,7 @@ private: template<> INLINE void PointerToBase::update_type(To *ptr) {} -INLINE ostream &operator << (ostream &out, const InternalName &tcn); +INLINE std::ostream &operator << (std::ostream &out, const InternalName &tcn); /** * This is a const pointer to an InternalName, and should be used in lieu of a @@ -196,27 +196,24 @@ typedef ConstPointerTo CPT_InternalName; #else class CPT_InternalName : public ConstPointerTo { public: - INLINE CPT_InternalName(const To *ptr = (const To *)NULL); + INLINE CPT_InternalName(const To *ptr = nullptr); INLINE CPT_InternalName(const PointerTo ©); + INLINE CPT_InternalName(PointerTo &&from) noexcept; INLINE CPT_InternalName(const ConstPointerTo ©); - INLINE CPT_InternalName(const string &name); + INLINE CPT_InternalName(ConstPointerTo &&from) noexcept; + INLINE CPT_InternalName(const std::string &name); template INLINE CPT_InternalName(const char (&literal)[N]); -#ifdef USE_MOVE_SEMANTICS - INLINE CPT_InternalName(PointerTo &&from) NOEXCEPT; - INLINE CPT_InternalName(ConstPointerTo &&from) NOEXCEPT; - INLINE CPT_InternalName &operator = (PointerTo &&from) NOEXCEPT; - INLINE CPT_InternalName &operator = (ConstPointerTo &&from) NOEXCEPT; -#endif // USE_MOVE_SEMANTICS - INLINE CPT_InternalName &operator = (const To *ptr); INLINE CPT_InternalName &operator = (const PointerTo ©); INLINE CPT_InternalName &operator = (const ConstPointerTo ©); + INLINE CPT_InternalName &operator = (PointerTo &&from) noexcept; + INLINE CPT_InternalName &operator = (ConstPointerTo &&from) noexcept; }; -INLINE void swap(CPT_InternalName &one, CPT_InternalName &two) NOEXCEPT { +INLINE void swap(CPT_InternalName &one, CPT_InternalName &two) noexcept { one.swap(two); } #endif // CPPPARSER diff --git a/panda/src/gobj/internalName_ext.cxx b/panda/src/gobj/internalName_ext.cxx index b98bcd9c12..f1cdf0a725 100644 --- a/panda/src/gobj/internalName_ext.cxx +++ b/panda/src/gobj/internalName_ext.cxx @@ -13,6 +13,8 @@ #include "internalName_ext.h" +using std::string; + #ifdef HAVE_PYTHON /** @@ -27,8 +29,8 @@ make(PyUnicodeObject *str) { // Not an interned string; don't bother. Py_ssize_t len = 0; const char *c_str = PyUnicode_AsUTF8AndSize((PyObject *)str, &len); - if (c_str == NULL) { - return NULL; + if (c_str == nullptr) { + return nullptr; } string name(c_str, len); @@ -73,8 +75,8 @@ make(PyStringObject *str) { Py_INCREF(str); iname->ref(); - InternalName::_py_intern_table.insert(make_pair((PyObject *)str, iname.p())); - return iname.p(); + InternalName::_py_intern_table.insert(std::make_pair((PyObject *)str, iname.p())); + return iname; } } diff --git a/panda/src/gobj/lens.I b/panda/src/gobj/lens.I index 337b60ab0c..91fb6e7170 100644 --- a/panda/src/gobj/lens.I +++ b/panda/src/gobj/lens.I @@ -142,7 +142,7 @@ project(const LPoint3 &point3d, LPoint3 &point2d) const { * to automatically track changes to camera fov, etc. in the application. */ INLINE void Lens:: -set_change_event(const string &event) { +set_change_event(const std::string &event) { CDWriter cdata(_cycler, true); cdata->_change_event = event; } @@ -151,7 +151,7 @@ set_change_event(const string &event) { * Returns the name of the event that will be generated whenever any * properties of this particular Lens have changed. */ -INLINE const string &Lens:: +INLINE const std::string &Lens:: get_change_event() const { CDReader cdata(_cycler); return cdata->_change_event; @@ -709,8 +709,8 @@ do_set_near_far(CData *cdata, PN_stdfloat near_distance, PN_stdfloat far_distanc do_throw_change_event(cdata); } -INLINE ostream & -operator << (ostream &out, const Lens &lens) { +INLINE std::ostream & +operator << (std::ostream &out, const Lens &lens) { lens.output(out); return out; } diff --git a/panda/src/gobj/lens.cxx b/panda/src/gobj/lens.cxx index 8b7df0b5ac..f66f2ba6b9 100644 --- a/panda/src/gobj/lens.cxx +++ b/panda/src/gobj/lens.cxx @@ -23,6 +23,9 @@ #include "config_gobj.h" #include "plane.h" +using std::max; +using std::min; + TypeHandle Lens::_type_handle; TypeHandle Lens::CData::_type_handle; @@ -41,7 +44,7 @@ Lens:: Lens(const Lens ©) : _cycler(copy._cycler) { // We don't copy the _geom_data. That's unique to each Lens. CDWriter cdata(_cycler, true); - cdata->_geom_data = NULL; + cdata->_geom_data = nullptr; } /** @@ -53,7 +56,7 @@ operator = (const Lens ©) { // We don't copy the _geom_data. That's unique to each Lens. CDWriter cdata(_cycler, true); - cdata->_geom_data = NULL; + cdata->_geom_data = nullptr; } /** @@ -577,7 +580,7 @@ make_geometry() { if (num_segments == 0) { // Can't do a frustum. cdata->_geom_data.clear(); - return (Geom *)NULL; + return nullptr; } // Now string together the line segments. @@ -627,7 +630,7 @@ make_geometry() { PT(Geom) geom = new Geom(cdata->_geom_data); geom->add_primitive(line); - return geom.p(); + return geom; } /** @@ -648,25 +651,25 @@ make_bounds() const { // Upper left. corner.set(-1.0f, 1.0f, 0.0f); if (!do_extrude(cdata, corner, nul, ful)) { - return (BoundingVolume *)NULL; + return nullptr; } // Upper right. corner.set(1.0f, 1.0f, 0.0f); if (!do_extrude(cdata, corner, nur, fur)) { - return (BoundingVolume *)NULL; + return nullptr; } // Lower right. corner.set(1.0f, -1.0f, 0.0f); if (!do_extrude(cdata, corner, nlr, flr)) { - return (BoundingVolume *)NULL; + return nullptr; } // Lower left. corner.set(-1.0f, -1.0f, 0.0f); if (!do_extrude(cdata, corner, nll, fll)) { - return (BoundingVolume *)NULL; + return nullptr; } return new BoundingHexahedron(fll, flr, fur, ful, nll, nlr, nur, nul); @@ -676,7 +679,7 @@ make_bounds() const { * */ void Lens:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type(); } @@ -684,7 +687,7 @@ output(ostream &out) const { * */ void Lens:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type() << " fov = " << get_fov() << "\n"; } @@ -1613,7 +1616,7 @@ do_define_geom_data(CData *cdata) { num_segments = lens_geom_segments; } - if (cdata->_geom_data == (GeomVertexData *)NULL) { + if (cdata->_geom_data == nullptr) { cdata->_geom_data = new GeomVertexData ("lens", GeomVertexFormat::get_v3(), Geom::UH_dynamic); diff --git a/panda/src/gobj/lens.h b/panda/src/gobj/lens.h index f695d36558..b0ac72d907 100644 --- a/panda/src/gobj/lens.h +++ b/panda/src/gobj/lens.h @@ -64,8 +64,8 @@ PUBLISHED: INLINE bool project(const LPoint3 &point3d, LPoint3 &point2d) const; INLINE bool project(const LPoint3 &point3d, LPoint2 &point2d) const; - INLINE void set_change_event(const string &event); - INLINE const string &get_change_event() const; + INLINE void set_change_event(const std::string &event); + INLINE const std::string &get_change_event() const; MAKE_PROPERTY(change_event, get_change_event, set_change_event); void set_coordinate_system(CoordinateSystem cs); @@ -182,8 +182,8 @@ PUBLISHED: INLINE const LMatrix4 &get_lens_mat() const; INLINE const LMatrix4 &get_lens_mat_inv() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; INLINE UpdateSeq get_last_change() const; @@ -322,7 +322,7 @@ protected: void clear(); - string _change_event; + std::string _change_event; UpdateSeq _last_change; CoordinateSystem _cs; @@ -399,7 +399,7 @@ private: static TypeHandle _type_handle; }; -EXPCL_PANDA_GOBJ INLINE ostream &operator << (ostream &out, const Lens &lens); +EXPCL_PANDA_GOBJ INLINE std::ostream &operator << (std::ostream &out, const Lens &lens); #include "lens.I" diff --git a/panda/src/gobj/material.I b/panda/src/gobj/material.I index 777a555200..b9e30ba262 100644 --- a/panda/src/gobj/material.I +++ b/panda/src/gobj/material.I @@ -15,7 +15,7 @@ * */ INLINE Material:: -Material(const string &name) : Namable(name) { +Material(const std::string &name) : Namable(name) { _base_color.set(1.0f, 1.0f, 1.0f, 1.0f); _ambient.set(1.0f, 1.0f, 1.0f, 1.0f); _diffuse.set(1.0f, 1.0f, 1.0f, 1.0f); diff --git a/panda/src/gobj/material.cxx b/panda/src/gobj/material.cxx index 12d4f15365..1952066649 100644 --- a/panda/src/gobj/material.cxx +++ b/panda/src/gobj/material.cxx @@ -395,7 +395,7 @@ compare_to(const Material &other) const { * */ void Material:: -output(ostream &out) const { +output(std::ostream &out) const { out << "Material " << get_name(); if (has_base_color()) { out << " c(" << get_base_color() << ")"; @@ -432,7 +432,7 @@ output(ostream &out) const { * */ void Material:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "Material " << get_name() << "\n"; if (has_base_color()) { indent(out, indent_level + 2) << "base_color = " << get_ambient() << "\n"; diff --git a/panda/src/gobj/material.h b/panda/src/gobj/material.h index 17344df46a..5835a81ae3 100644 --- a/panda/src/gobj/material.h +++ b/panda/src/gobj/material.h @@ -41,7 +41,7 @@ class FactoryParams; */ class EXPCL_PANDA_GOBJ Material : public TypedWritableReferenceCount, public Namable { PUBLISHED: - INLINE explicit Material(const string &name = ""); + INLINE explicit Material(const std::string &name = ""); INLINE Material(const Material ©); void operator = (const Material ©); INLINE ~Material(); @@ -100,8 +100,8 @@ PUBLISHED: int compare_to(const Material &other) const; - void output(ostream &out) const; - void write(ostream &out, int indent) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent) const; INLINE bool is_attrib_locked() const; INLINE void set_attrib_lock(); @@ -186,7 +186,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const Material &m) { +INLINE std::ostream &operator << (std::ostream &out, const Material &m) { m.output(out); return out; } diff --git a/panda/src/gobj/materialPool.I b/panda/src/gobj/materialPool.I index 6d6726bde6..271bda6fa8 100644 --- a/panda/src/gobj/materialPool.I +++ b/panda/src/gobj/materialPool.I @@ -63,7 +63,7 @@ garbage_collect() { * Lists the contents of the material pool to the indicated output stream. */ INLINE void MaterialPool:: -list_contents(ostream &out) { +list_contents(std::ostream &out) { get_global_ptr()->ns_list_contents(out); } diff --git a/panda/src/gobj/materialPool.cxx b/panda/src/gobj/materialPool.cxx index 22b8f9c5ee..a2dd6c9064 100644 --- a/panda/src/gobj/materialPool.cxx +++ b/panda/src/gobj/materialPool.cxx @@ -15,14 +15,14 @@ #include "config_gobj.h" #include "lightMutexHolder.h" -MaterialPool *MaterialPool::_global_ptr = (MaterialPool *)NULL; +MaterialPool *MaterialPool::_global_ptr = nullptr; /** * Lists the contents of the material pool to the indicated output stream. */ void MaterialPool:: -write(ostream &out) { +write(std::ostream &out) { get_global_ptr()->ns_list_contents(out); } @@ -100,7 +100,7 @@ ns_garbage_collect() { * The nonstatic implementation of list_contents(). */ void MaterialPool:: -ns_list_contents(ostream &out) const { +ns_list_contents(std::ostream &out) const { LightMutexHolder holder(_lock); out << _materials.size() << " materials:\n"; @@ -119,7 +119,7 @@ ns_list_contents(ostream &out) const { */ MaterialPool *MaterialPool:: get_global_ptr() { - if (_global_ptr == (MaterialPool *)NULL) { + if (_global_ptr == nullptr) { _global_ptr = new MaterialPool; } return _global_ptr; diff --git a/panda/src/gobj/materialPool.h b/panda/src/gobj/materialPool.h index e5a0775b0b..d4cc1cc67b 100644 --- a/panda/src/gobj/materialPool.h +++ b/panda/src/gobj/materialPool.h @@ -40,9 +40,9 @@ PUBLISHED: INLINE static void release_all_materials(); INLINE static int garbage_collect(); - INLINE static void list_contents(ostream &out); + INLINE static void list_contents(std::ostream &out); - static void write(ostream &out); + static void write(std::ostream &out); private: INLINE MaterialPool(); @@ -52,7 +52,7 @@ private: void ns_release_all_materials(); int ns_garbage_collect(); - void ns_list_contents(ostream &out) const; + void ns_list_contents(std::ostream &out) const; static MaterialPool *get_global_ptr(); diff --git a/panda/src/gobj/matrixLens.cxx b/panda/src/gobj/matrixLens.cxx index 147870a954..db647516c7 100644 --- a/panda/src/gobj/matrixLens.cxx +++ b/panda/src/gobj/matrixLens.cxx @@ -41,7 +41,7 @@ is_linear() const { * */ void MatrixLens:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type() << ":\n"; get_projection_mat().write(out, indent_level + 2); } diff --git a/panda/src/gobj/matrixLens.h b/panda/src/gobj/matrixLens.h index 0b4f068b88..e5d1d1a688 100644 --- a/panda/src/gobj/matrixLens.h +++ b/panda/src/gobj/matrixLens.h @@ -52,7 +52,7 @@ public: virtual PT(Lens) make_copy() const; virtual bool is_linear() const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; protected: virtual void do_compute_projection_mat(Lens::CData *lens_cdata); diff --git a/panda/src/gobj/orthographicLens.cxx b/panda/src/gobj/orthographicLens.cxx index 86c8fe0ef5..131903935a 100644 --- a/panda/src/gobj/orthographicLens.cxx +++ b/panda/src/gobj/orthographicLens.cxx @@ -49,7 +49,7 @@ is_orthographic() const { * */ void OrthographicLens:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type() << " film size = " << get_film_size() << "\n"; } diff --git a/panda/src/gobj/orthographicLens.h b/panda/src/gobj/orthographicLens.h index 8798d4d8e7..da150fa681 100644 --- a/panda/src/gobj/orthographicLens.h +++ b/panda/src/gobj/orthographicLens.h @@ -40,7 +40,7 @@ public: virtual bool is_linear() const; virtual bool is_orthographic() const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; protected: virtual bool do_extrude_depth(const CData *cdata, const LPoint3 &point2d, diff --git a/panda/src/gobj/paramTexture.I b/panda/src/gobj/paramTexture.I index c25c71ca28..c8235778e8 100644 --- a/panda/src/gobj/paramTexture.I +++ b/panda/src/gobj/paramTexture.I @@ -55,7 +55,7 @@ INLINE ParamTextureImage:: ParamTextureImage(Texture *tex, bool read, bool write, int z, int n) : _texture(tex), _access(0), - _bind_level(min(n, 127)), + _bind_level(std::min(n, 127)), _bind_layer(z) { if (read) { diff --git a/panda/src/gobj/paramTexture.cxx b/panda/src/gobj/paramTexture.cxx index 0710f506f2..892fe157c9 100644 --- a/panda/src/gobj/paramTexture.cxx +++ b/panda/src/gobj/paramTexture.cxx @@ -21,10 +21,10 @@ TypeHandle ParamTextureImage::_type_handle; * */ void ParamTextureSampler:: -output(ostream &out) const { +output(std::ostream &out) const { out << "texture "; - if (_texture != (Texture *)NULL) { + if (_texture != nullptr) { out << _texture->get_name(); } else { out << "(empty)"; @@ -96,10 +96,10 @@ fillin(DatagramIterator &scan, BamReader *manager) { * */ void ParamTextureImage:: -output(ostream &out) const { +output(std::ostream &out) const { out << "texture "; - if (_texture != (Texture *)NULL) { + if (_texture != nullptr) { out << _texture->get_name(); } else { out << "(empty)"; diff --git a/panda/src/gobj/paramTexture.h b/panda/src/gobj/paramTexture.h index d78ceb06b9..fb9b2a5a81 100644 --- a/panda/src/gobj/paramTexture.h +++ b/panda/src/gobj/paramTexture.h @@ -37,7 +37,7 @@ PUBLISHED: MAKE_PROPERTY(texture, get_texture); MAKE_PROPERTY(sampler, get_sampler); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: PT(Texture) _texture; @@ -106,7 +106,7 @@ PUBLISHED: MAKE_PROPERTY(bind_level, get_bind_level); MAKE_PROPERTY2(bind_layer, get_bind_layered, get_bind_layer); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: PT(Texture) _texture; diff --git a/panda/src/gobj/preparedGraphicsObjects.I b/panda/src/gobj/preparedGraphicsObjects.I index 6cc6daf914..a37a447489 100644 --- a/panda/src/gobj/preparedGraphicsObjects.I +++ b/panda/src/gobj/preparedGraphicsObjects.I @@ -16,7 +16,7 @@ * arbitrary name that serves mainly to uniquify the context for PStats * reporting. */ -INLINE const string &PreparedGraphicsObjects:: +INLINE const std::string &PreparedGraphicsObjects:: get_name() const { return _name; } diff --git a/panda/src/gobj/preparedGraphicsObjects.cxx b/panda/src/gobj/preparedGraphicsObjects.cxx index 233edb46b3..4f6ecea1ed 100644 --- a/panda/src/gobj/preparedGraphicsObjects.cxx +++ b/panda/src/gobj/preparedGraphicsObjects.cxx @@ -162,7 +162,7 @@ set_graphics_memory_limit(size_t limit) { * vertex buffers are allocated in the LRU. */ void PreparedGraphicsObjects:: -show_graphics_memory_lru(ostream &out) const { +show_graphics_memory_lru(std::ostream &out) const { _graphics_memory_lru.write(out, 0); } @@ -171,7 +171,7 @@ show_graphics_memory_lru(ostream &out) const { * vertex buffers are allocated in the LRU. */ void PreparedGraphicsObjects:: -show_residency_trackers(ostream &out) const { +show_residency_trackers(std::ostream &out) const { out << "Textures:\n"; _texture_residency.write(out, 2); @@ -204,7 +204,7 @@ PT(PreparedGraphicsObjects::EnqueuedObject) PreparedGraphicsObjects:: enqueue_texture_future(Texture *tex) { ReMutexHolder holder(_lock); - pair result = + std::pair result = _enqueued_textures.insert(EnqueuedTextures::value_type(tex, nullptr)); if (result.first->second == nullptr) { result.first->second = new EnqueuedObject(this, tex); @@ -274,7 +274,7 @@ release_texture(TextureContext *tc) { // We have to set the Texture pointer to NULL at this point, since the // Texture itself might destruct at any time after it has been released. - tc->_texture = (Texture *)NULL; + tc->_texture = nullptr; bool removed = (_prepared_textures.erase(tc) != 0); nassertv(removed); @@ -308,7 +308,7 @@ release_all_textures() { ++tci) { TextureContext *tc = (*tci); tc->_texture->clear_prepared(tc->get_view(), this); - tc->_texture = (Texture *)NULL; + tc->_texture = nullptr; _released_textures.insert(tc); } @@ -372,7 +372,7 @@ prepare_texture_now(Texture *tex, int view, GraphicsStateGuardianBase *gsg) { // them creates the context (since they're all shared anyway). TextureContext *tc = gsg->prepare_texture(tex, view); - if (tc != (TextureContext *)NULL) { + if (tc != nullptr) { bool prepared = _prepared_textures.insert(tc).second; nassertr(prepared, tc); } @@ -532,7 +532,7 @@ prepare_sampler_now(const SamplerState &sampler, GraphicsStateGuardianBase *gsg) // Ask the GSG to create a brand new SamplerContext. SamplerContext *sc = gsg->prepare_sampler(sampler); - if (sc != (SamplerContext *)NULL) { + if (sc != nullptr) { _prepared_samplers[sampler] = sc; } @@ -608,7 +608,7 @@ release_geom(GeomContext *gc) { // We have to set the Geom pointer to NULL at this point, since the Geom // itself might destruct at any time after it has been released. - gc->_geom = (Geom *)NULL; + gc->_geom = nullptr; bool removed = (_prepared_geoms.erase(gc) != 0); nassertv(removed); @@ -633,7 +633,7 @@ release_all_geoms() { ++gci) { GeomContext *gc = (*gci); gc->_geom->clear_prepared(this); - gc->_geom = (Geom *)NULL; + gc->_geom = nullptr; _released_geoms.insert(gc); } @@ -686,7 +686,7 @@ prepare_geom_now(Geom *geom, GraphicsStateGuardianBase *gsg) { // them creates the context (since they're all shared anyway). GeomContext *gc = gsg->prepare_geom(geom); - if (gc != (GeomContext *)NULL) { + if (gc != nullptr) { bool prepared = _prepared_geoms.insert(gc).second; nassertr(prepared, gc); } @@ -713,7 +713,7 @@ PT(PreparedGraphicsObjects::EnqueuedObject) PreparedGraphicsObjects:: enqueue_shader_future(Shader *shader) { ReMutexHolder holder(_lock); - pair result = + std::pair result = _enqueued_shaders.insert(EnqueuedShaders::value_type(shader, nullptr)); if (result.first->second == nullptr) { result.first->second = new EnqueuedObject(this, shader); @@ -783,7 +783,7 @@ release_shader(ShaderContext *sc) { // We have to set the Shader pointer to NULL at this point, since the Shader // itself might destruct at any time after it has been released. - sc->_shader = (Shader *)NULL; + sc->_shader = nullptr; bool removed = (_prepared_shaders.erase(sc) != 0); nassertv(removed); @@ -808,7 +808,7 @@ release_all_shaders() { ++sci) { ShaderContext *sc = (*sci); sc->_shader->clear_prepared(this); - sc->_shader = (Shader *)NULL; + sc->_shader = nullptr; _released_shaders.insert(sc); } @@ -872,7 +872,7 @@ prepare_shader_now(Shader *se, GraphicsStateGuardianBase *gsg) { // them creates the context (since they're all shared anyway). ShaderContext *sc = gsg->prepare_shader(se); - if (sc != (ShaderContext *)NULL) { + if (sc != nullptr) { bool prepared = _prepared_shaders.insert(sc).second; nassertr(prepared, sc); } @@ -953,7 +953,7 @@ release_vertex_buffer(VertexBufferContext *vbc) { // We have to set the Data pointer to NULL at this point, since the Data // itself might destruct at any time after it has been released. - vbc->_data = (GeomVertexArrayData *)NULL; + vbc->_data = nullptr; bool removed = (_prepared_vertex_buffers.erase(vbc) != 0); nassertv(removed); @@ -986,7 +986,7 @@ release_all_vertex_buffers() { ++vbci) { VertexBufferContext *vbc = (VertexBufferContext *)(*vbci); vbc->_data->clear_prepared(this); - vbc->_data = (GeomVertexArrayData *)NULL; + vbc->_data = nullptr; _released_vertex_buffers.insert(vbc); } @@ -1060,7 +1060,7 @@ prepare_vertex_buffer_now(GeomVertexArrayData *data, GraphicsStateGuardianBase * get_cached_buffer(data_size_bytes, usage_hint, _vertex_buffer_cache, _vertex_buffer_cache_lru, _vertex_buffer_cache_size); - if (vbc != (VertexBufferContext *)NULL) { + if (vbc != nullptr) { vbc->_data = data; } else { @@ -1070,7 +1070,7 @@ prepare_vertex_buffer_now(GeomVertexArrayData *data, GraphicsStateGuardianBase * vbc = gsg->prepare_vertex_buffer(data); } - if (vbc != (VertexBufferContext *)NULL) { + if (vbc != nullptr) { bool prepared = _prepared_vertex_buffers.insert(vbc).second; nassertr(prepared, vbc); } @@ -1151,7 +1151,7 @@ release_index_buffer(IndexBufferContext *ibc) { // We have to set the Data pointer to NULL at this point, since the Data // itself might destruct at any time after it has been released. - ibc->_data = (GeomPrimitive *)NULL; + ibc->_data = nullptr; bool removed = (_prepared_index_buffers.erase(ibc) != 0); nassertv(removed); @@ -1184,7 +1184,7 @@ release_all_index_buffers() { ++ibci) { IndexBufferContext *ibc = (IndexBufferContext *)(*ibci); ibc->_data->clear_prepared(this); - ibc->_data = (GeomPrimitive *)NULL; + ibc->_data = nullptr; _released_index_buffers.insert(ibc); } @@ -1257,7 +1257,7 @@ prepare_index_buffer_now(GeomPrimitive *data, GraphicsStateGuardianBase *gsg) { get_cached_buffer(data_size_bytes, usage_hint, _index_buffer_cache, _index_buffer_cache_lru, _index_buffer_cache_size); - if (ibc != (IndexBufferContext *)NULL) { + if (ibc != nullptr) { ibc->_data = data; } else { @@ -1267,7 +1267,7 @@ prepare_index_buffer_now(GeomPrimitive *data, GraphicsStateGuardianBase *gsg) { ibc = gsg->prepare_index_buffer(data); } - if (ibc != (IndexBufferContext *)NULL) { + if (ibc != nullptr) { bool prepared = _prepared_index_buffers.insert(ibc).second; nassertr(prepared, ibc); } @@ -1416,7 +1416,7 @@ prepare_shader_buffer_now(ShaderBuffer *data, GraphicsStateGuardianBase *gsg) { // which of them creates the context (since they're all shared anyway). BufferContext *bc = gsg->prepare_shader_buffer(data); - if (bc != (BufferContext *)NULL) { + if (bc != nullptr) { bool prepared = _prepared_shader_buffers.insert(bc).second; nassertr(prepared, bc); } @@ -1580,7 +1580,6 @@ begin_frame(GraphicsStateGuardianBase *gsg, Thread *current_thread) { qti != _enqueued_textures.end(); ++qti) { Texture *tex = qti->first; - TextureContext *first_tc = nullptr; for (int view = 0; view < tex->get_num_views(); ++view) { TextureContext *tc = tex->prepare_now(view, this, gsg); if (tc != nullptr) { @@ -1669,10 +1668,10 @@ end_frame(Thread *current_thread) { /** * Returns a new, unique name for a newly-constructed object. */ -string PreparedGraphicsObjects:: +std::string PreparedGraphicsObjects:: init_name() { ++_name_index; - ostringstream strm; + std::ostringstream strm; strm << "context" << _name_index; return strm.str(); } @@ -1743,11 +1742,11 @@ get_cached_buffer(size_t data_size_bytes, GeomEnums::UsageHint usage_hint, BufferCache::iterator bci = buffer_cache.find(key); if (bci == buffer_cache.end()) { - return NULL; + return nullptr; } BufferList &buffer_list = (*bci).second; - nassertr(!buffer_list.empty(), NULL); + nassertr(!buffer_list.empty(), nullptr); BufferContext *buffer = buffer_list.back(); buffer_list.pop_back(); diff --git a/panda/src/gobj/preparedGraphicsObjects.h b/panda/src/gobj/preparedGraphicsObjects.h index 3eaed37167..77ee91eca3 100644 --- a/panda/src/gobj/preparedGraphicsObjects.h +++ b/panda/src/gobj/preparedGraphicsObjects.h @@ -61,12 +61,12 @@ public: ~PreparedGraphicsObjects(); PUBLISHED: - INLINE const string &get_name() const; + INLINE const std::string &get_name() const; void set_graphics_memory_limit(size_t limit); INLINE size_t get_graphics_memory_limit() const; - void show_graphics_memory_lru(ostream &out) const; - void show_residency_trackers(ostream &out) const; + void show_graphics_memory_lru(std::ostream &out) const; + void show_residency_trackers(std::ostream &out) const; INLINE void release_all(); INLINE int get_num_queued() const; @@ -164,7 +164,7 @@ public: * This is a handle to an enqueued object, from which the result can be * obtained upon completion. */ - class EXPCL_PANDA_GOBJ EnqueuedObject FINAL : public AsyncFuture { + class EXPCL_PANDA_GOBJ EnqueuedObject final : public AsyncFuture { public: EnqueuedObject(PreparedGraphicsObjects *pgo, TypedWritableReferenceCount *object); @@ -173,7 +173,7 @@ public: void set_result(SavedContext *result); void notify_removed(); - virtual bool cancel() FINAL; + virtual bool cancel() final; PUBLISHED: MAKE_PROPERTY(object, get_object); @@ -215,7 +215,7 @@ public: void end_frame(Thread *current_thread); private: - static string init_name(); + static std::string init_name(); private: typedef phash_set Textures; @@ -261,7 +261,7 @@ private: size_t &buffer_cache_size); ReMutex _lock; - string _name; + std::string _name; Textures _prepared_textures, _released_textures; EnqueuedTextures _enqueued_textures; PreparedSamplers _prepared_samplers; diff --git a/panda/src/gobj/samplerContext.cxx b/panda/src/gobj/samplerContext.cxx index aad143c2fc..5b8d9b3322 100644 --- a/panda/src/gobj/samplerContext.cxx +++ b/panda/src/gobj/samplerContext.cxx @@ -19,7 +19,7 @@ TypeHandle SamplerContext::_type_handle; * */ void SamplerContext:: -output(ostream &out) const { +output(std::ostream &out) const { SavedContext::output(out); } @@ -27,6 +27,6 @@ output(ostream &out) const { * */ void SamplerContext:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { SavedContext::write(out, indent_level); } diff --git a/panda/src/gobj/samplerContext.h b/panda/src/gobj/samplerContext.h index edb684c4b4..bf47b98b84 100644 --- a/panda/src/gobj/samplerContext.h +++ b/panda/src/gobj/samplerContext.h @@ -35,8 +35,8 @@ class EXPCL_PANDA_GOBJ SamplerContext : public SavedContext, public SimpleLruPag public: INLINE SamplerContext(const SamplerState &sampler); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; public: static TypeHandle get_class_type() { @@ -58,7 +58,7 @@ private: friend class PreparedGraphicsObjects; }; -inline ostream &operator << (ostream &out, const SamplerContext &context) { +inline std::ostream &operator << (std::ostream &out, const SamplerContext &context) { context.output(out); return out; } diff --git a/panda/src/gobj/samplerState.cxx b/panda/src/gobj/samplerState.cxx index be8bd7b23d..9f1a5766bc 100644 --- a/panda/src/gobj/samplerState.cxx +++ b/panda/src/gobj/samplerState.cxx @@ -20,6 +20,8 @@ #include "samplerContext.h" #include "preparedGraphicsObjects.h" +using std::string; + TypeHandle SamplerState::_type_handle; SamplerState SamplerState::_default; @@ -283,7 +285,7 @@ compare_to(const SamplerState &other) const { * */ void SamplerState:: -output(ostream &out) const { +output(std::ostream &out) const { out << "sampler" << " wrap(u=" << _wrap_u << ", v=" << _wrap_v << ", w=" << _wrap_w @@ -298,7 +300,7 @@ output(ostream &out) const { * */ void SamplerState:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "SamplerState\n"; indent(out, indent_level) << " wrap_u = " << _wrap_u << "\n"; indent(out, indent_level) << " wrap_v = " << _wrap_v << "\n"; diff --git a/panda/src/gobj/samplerState.h b/panda/src/gobj/samplerState.h index 2236092b81..bef695cd83 100644 --- a/panda/src/gobj/samplerState.h +++ b/panda/src/gobj/samplerState.h @@ -126,11 +126,11 @@ PUBLISHED: INLINE bool uses_mipmaps() const; INLINE static bool is_mipmap(FilterType type); - static string format_filter_type(FilterType ft); - static FilterType string_filter_type(const string &str); + static std::string format_filter_type(FilterType ft); + static FilterType string_filter_type(const std::string &str); - static string format_wrap_mode(WrapMode wm); - static WrapMode string_wrap_mode(const string &str); + static std::string format_wrap_mode(WrapMode wm); + static WrapMode string_wrap_mode(const std::string &str); INLINE bool operator == (const SamplerState &other) const; INLINE bool operator != (const SamplerState &other) const; @@ -146,8 +146,8 @@ PUBLISHED: public: int compare_to(const SamplerState &other) const; - void output(ostream &out) const; - void write(ostream &out, int indent) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent) const; private: LColor _border_color; @@ -194,28 +194,28 @@ extern EXPCL_PANDA_GOBJ ConfigVariableEnum texture_min extern EXPCL_PANDA_GOBJ ConfigVariableEnum texture_magfilter; extern EXPCL_PANDA_GOBJ ConfigVariableInt texture_anisotropic_degree; -INLINE ostream &operator << (ostream &out, const SamplerState &m) { +INLINE std::ostream &operator << (std::ostream &out, const SamplerState &m) { m.output(out); return out; } -INLINE ostream &operator << (ostream &out, SamplerState::FilterType ft) { +INLINE std::ostream &operator << (std::ostream &out, SamplerState::FilterType ft) { return out << SamplerState::format_filter_type(ft); } -INLINE istream &operator >> (istream &in, SamplerState::FilterType &ft) { - string word; +INLINE std::istream &operator >> (std::istream &in, SamplerState::FilterType &ft) { + std::string word; in >> word; ft = SamplerState::string_filter_type(word); return in; } -INLINE ostream &operator << (ostream &out, SamplerState::WrapMode wm) { +INLINE std::ostream &operator << (std::ostream &out, SamplerState::WrapMode wm) { return out << SamplerState::format_wrap_mode(wm); } -INLINE istream &operator >> (istream &in, SamplerState::WrapMode &wm) { - string word; +INLINE std::istream &operator >> (std::istream &in, SamplerState::WrapMode &wm) { + std::string word; in >> word; wm = SamplerState::string_wrap_mode(word); return in; diff --git a/panda/src/gobj/savedContext.cxx b/panda/src/gobj/savedContext.cxx index 2b93299121..92a1af46ca 100644 --- a/panda/src/gobj/savedContext.cxx +++ b/panda/src/gobj/savedContext.cxx @@ -20,7 +20,7 @@ TypeHandle SavedContext::_type_handle; * */ void SavedContext:: -output(ostream &out) const { +output(std::ostream &out) const { out << "SavedContext " << this; } @@ -28,6 +28,6 @@ output(ostream &out) const { * */ void SavedContext:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << *this << "\n"; } diff --git a/panda/src/gobj/savedContext.h b/panda/src/gobj/savedContext.h index 1e5a28594e..6c2db6aec8 100644 --- a/panda/src/gobj/savedContext.h +++ b/panda/src/gobj/savedContext.h @@ -27,8 +27,8 @@ class EXPCL_PANDA_GOBJ SavedContext : public TypedObject { public: INLINE SavedContext(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; PUBLISHED: static TypeHandle get_class_type() { @@ -49,7 +49,7 @@ private: static TypeHandle _type_handle; }; -inline ostream &operator << (ostream &out, const SavedContext &context) { +inline std::ostream &operator << (std::ostream &out, const SavedContext &context) { context.output(out); return out; } diff --git a/panda/src/gobj/shader.I b/panda/src/gobj/shader.I index fcefc1e235..3a671a5f9f 100644 --- a/panda/src/gobj/shader.I +++ b/panda/src/gobj/shader.I @@ -85,7 +85,7 @@ set_filename(ShaderType type, const Filename &filename) { /** * Return the Shader's text for the given shader type. */ -INLINE const string &Shader:: +INLINE const std::string &Shader:: get_text(ShaderType type) const { if (_text._separate) { nassertr(type != ST_none || !_text._shared.empty(), _text._shared); @@ -205,7 +205,7 @@ operator == (const ShaderCaps &other) const { */ INLINE Shader::ShaderPtrData:: ShaderPtrData() : - _ptr(NULL), + _ptr(nullptr), _type(SPT_unknown), _updated(true), _size(0) @@ -694,9 +694,9 @@ read_datagram(DatagramIterator &scan) { * */ INLINE Shader::ShaderFile:: -ShaderFile(string shared) : +ShaderFile(std::string shared) : _separate(false), - _shared(move(shared)) + _shared(std::move(shared)) { } @@ -704,14 +704,14 @@ ShaderFile(string shared) : * */ INLINE Shader::ShaderFile:: -ShaderFile(string vertex, string fragment, string geometry, - string tess_control, string tess_evaluation) : +ShaderFile(std::string vertex, std::string fragment, std::string geometry, + std::string tess_control, std::string tess_evaluation) : _separate(true), - _vertex(move(vertex)), - _fragment(move(fragment)), - _geometry(move(geometry)), - _tess_control(move(tess_control)), - _tess_evaluation(move(tess_evaluation)) + _vertex(std::move(vertex)), + _fragment(std::move(fragment)), + _geometry(std::move(geometry)), + _tess_control(std::move(tess_control)), + _tess_evaluation(std::move(tess_evaluation)) { } diff --git a/panda/src/gobj/shader.cxx b/panda/src/gobj/shader.cxx index 35fd3ce560..22a5389b8b 100644 --- a/panda/src/gobj/shader.cxx +++ b/panda/src/gobj/shader.cxx @@ -27,6 +27,12 @@ #include #endif +using std::istream; +using std::move; +using std::ostream; +using std::ostringstream; +using std::string; + TypeHandle Shader::_type_handle; Shader::ShaderTable Shader::_load_table; Shader::ShaderTable Shader::_make_table; @@ -338,7 +344,7 @@ cp_parse_coord_sys(ShaderArgInfo &p, if (fromflag) { if (word2 == "") { bind._part[0] = from_single; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; } else { if (from_double == SMO_INVALID) { cp_report_error(p, "Could not parse coordinate system name"); @@ -350,7 +356,7 @@ cp_parse_coord_sys(ShaderArgInfo &p, } else { if (word2 == "") { bind._part[1] = to_single; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; } else { if (to_double == SMO_INVALID) { cp_report_error(p, "Could not parse coordinate system name"); @@ -505,7 +511,7 @@ cp_optimize_mat_spec(ShaderMatSpec &spec) { if (spec._func == SMF_first) { spec._part[1] = SMO_INVALID; - spec._arg[1] = 0; + spec._arg[1] = nullptr; } if (spec._func == SMF_compose) { if (spec._part[1] == SMO_identity) { @@ -750,7 +756,7 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { bind._part[1] = SMO_light_source_i_attrib; bind._arg[1] = InternalName::make("shadowViewMatrix"); bind._part[0] = SMO_view_to_apiview; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; bind._index = atoi(pieces[2].c_str()); cp_optimize_mat_spec(bind); @@ -863,7 +869,7 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { bind._part[1] = SMO_light_source_i_attrib; bind._arg[1] = InternalName::make("shadowViewMatrix"); bind._part[0] = SMO_view_to_apiview; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; bind._index = atoi(pieces[2].c_str()); int next = 1; @@ -931,9 +937,9 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { bind._piece = SMP_transpose; bind._func = SMF_first; bind._part[0] = SMO_attr_material; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; bind._part[1] = SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; } else if (pieces[1] == "color") { if (!cp_errchk_parameter_float(p,3,4)) { return false; @@ -942,9 +948,9 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { bind._piece = SMP_row3; bind._func = SMF_first; bind._part[0] = SMO_attr_color; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; bind._part[1] = SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; } else if (pieces[1] == "colorscale") { if (!cp_errchk_parameter_float(p,3,4)) { return false; @@ -953,9 +959,9 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { bind._piece = SMP_row3; bind._func = SMF_first; bind._part[0] = SMO_attr_colorscale; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; bind._part[1] = SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; } else if (pieces[1] == "fog") { if (!cp_errchk_parameter_float(p,3,4)) { return false; @@ -964,9 +970,9 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { bind._piece = SMP_row3; bind._func = SMF_first; bind._part[0] = SMO_attr_fog; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; bind._part[1] = SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; } else if (pieces[1] == "fogcolor") { if (!cp_errchk_parameter_float(p,3,4)) { return false; @@ -975,9 +981,9 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { bind._piece = SMP_row3; bind._func = SMF_first; bind._part[0] = SMO_attr_fogcolor; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; bind._part[1] = SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; } else if (pieces[1] == "ambient") { if (!cp_errchk_parameter_float(p,3,4)) { return false; @@ -986,9 +992,9 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { bind._piece = SMP_row3; bind._func = SMF_first; bind._part[0] = SMO_light_ambient; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; bind._part[1] = SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; } else if (pieces[1].compare(0, 5, "light") == 0) { if (!cp_errchk_parameter_float(p,16,16)) { return false; @@ -997,9 +1003,9 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { bind._piece = SMP_transpose; bind._func = SMF_first; bind._part[0] = SMO_light_source_i_packed; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; bind._part[1] = SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; bind._index = atoi(pieces[1].c_str() + 5); } else if (pieces[1].compare(0, 5, "lspec") == 0) { if (!cp_errchk_parameter_float(p,3,4)) { @@ -1011,7 +1017,7 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { bind._part[0] = SMO_light_source_i_attrib; bind._arg[0] = InternalName::make("specular"); bind._part[1] = SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; bind._index = atoi(pieces[1].c_str() + 5); } else { cp_report_error(p,"Unknown attr parameter."); @@ -1054,7 +1060,7 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { bind._part[0] = SMO_alight_x; bind._arg[0] = InternalName::make(pieces[1]); bind._part[1] = SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; cp_optimize_mat_spec(bind); _mat_spec.push_back(bind); @@ -1076,7 +1082,7 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { bind._part[0] = SMO_satten_x; bind._arg[0] = InternalName::make(pieces[1]); bind._part[1] = SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; cp_optimize_mat_spec(bind); _mat_spec.push_back(bind); @@ -1138,9 +1144,9 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { bind._piece = SMP_whole; bind._func = SMF_first; bind._part[0] = SMO_texmat_i; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; bind._part[1] = SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; bind._index = atoi(pieces[1].c_str()); cp_optimize_mat_spec(bind); @@ -1161,9 +1167,9 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { bind._piece = SMP_row3; bind._func = SMF_first; bind._part[0] = SMO_texscale_i; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; bind._part[1] = SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; bind._index = atoi(pieces[1].c_str()); cp_optimize_mat_spec(bind); @@ -1184,9 +1190,9 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { bind._piece = SMP_row3; bind._func = SMF_first; bind._part[0] = SMO_texcolor_i; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; bind._part[1] = SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; bind._index = atoi(pieces[1].c_str()); cp_optimize_mat_spec(bind); @@ -1209,7 +1215,7 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { bind._part[0] = SMO_plane_x; bind._arg[0] = InternalName::make(pieces[1]); bind._part[1] = SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; cp_optimize_mat_spec(bind); _mat_spec.push_back(bind); @@ -1231,7 +1237,7 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { bind._part[0] = SMO_clipplane_x; bind._arg[0] = InternalName::make(pieces[1]); bind._part[1] = SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; cp_optimize_mat_spec(bind); _mat_spec.push_back(bind); @@ -1252,20 +1258,20 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { bind._piece = SMP_row3; bind._func = SMF_first; bind._part[1] = SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; if (pieces[1] == "pixelsize") { if (!cp_errchk_parameter_float(p, 2, 2)) { return false; } bind._part[0] = SMO_pixel_size; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; } else if (pieces[1] == "windowsize") { if (!cp_errchk_parameter_float(p, 2, 2)) { return false; } bind._part[0] = SMO_window_size; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; } else if (pieces[1] == "time") { if (!cp_errchk_parameter_float(p, 1, 1)) { @@ -1273,7 +1279,7 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { } bind._piece = SMP_row3x1; bind._part[0] = SMO_frame_time; - bind._arg[0] = NULL; + bind._arg[0] = nullptr; } else { cp_report_error(p, "unknown system parameter"); @@ -1299,7 +1305,7 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { } ShaderTexSpec bind; bind._id = p._id; - bind._name = 0; + bind._name = nullptr; bind._stage = atoi(pieces[1].c_str()); bind._part = STO_stage_i; switch (p._type) { @@ -1364,7 +1370,7 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { bind._part[0] = SMO_texpad_x; bind._arg[0] = InternalName::make(pieces[1]); bind._part[1] = SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; cp_optimize_mat_spec(bind); _mat_spec.push_back(bind); _mat_deps |= bind._dep[0] | bind._dep[1]; @@ -1385,7 +1391,7 @@ compile_parameter(ShaderArgInfo &p, int *arg_dim) { bind._part[0] = SMO_texpix_x; bind._arg[0] = InternalName::make(pieces[1]); bind._part[1] = SMO_identity; - bind._arg[1] = NULL; + bind._arg[1] = nullptr; cp_optimize_mat_spec(bind); _mat_spec.push_back(bind); _mat_deps |= bind._dep[0] | bind._dep[1]; @@ -1777,7 +1783,7 @@ cg_compile_entry_point(const char *entry, const ShaderCaps &caps, << "Compilation with active profile failed: " << cgGetErrorString(err) << "\n"; if (err == CG_COMPILER_ERROR) { const char *listing = cgGetLastListing(context); - if (listing != NULL) { + if (listing != nullptr) { shader_cat.debug(false) << listing; } } @@ -1792,13 +1798,13 @@ cg_compile_entry_point(const char *entry, const ShaderCaps &caps, // The active profile failed, so recompile it with the ultimate profile. prog = cgCreateProgram(context, CG_SOURCE, text.c_str(), - (CGprofile)ultimate, entry, (const char **)NULL); + (CGprofile)ultimate, entry, nullptr); // Extract the output listing. err = cgGetError(); const char *listing = cgGetLastListing(context); - if (err == CG_NO_ERROR && listing != NULL && strlen(listing) > 1) { + if (err == CG_NO_ERROR && listing != nullptr && strlen(listing) > 1) { shader_cat.warning() << "Encountered warnings during compilation of " << get_filename(type) << ":\n" << listing; @@ -1806,7 +1812,7 @@ cg_compile_entry_point(const char *entry, const ShaderCaps &caps, } else if (err == CG_COMPILER_ERROR) { shader_cat.error() << "Failed to compile Cg shader " << get_filename(type); - if (listing != NULL) { + if (listing != nullptr) { shader_cat.error(false) << ":\n" << listing; } else { shader_cat.error(false) << "!\n"; @@ -1915,7 +1921,7 @@ cg_compile_shader(const ShaderCaps &caps, CGcontext context) { CGprogram new_program; new_program = cgCreateProgram(context, CG_OBJECT, result.c_str(), (CGprofile)_cg_fprofile, "fshader", - (const char**)NULL); + nullptr); if (new_program) { cgDestroyProgram(_cg_fprogram); _cg_fprogram = new_program; @@ -2245,7 +2251,7 @@ cg_compile_for(const ShaderCaps &caps, CGcontext context, if (shader_cat.is_debug()) { const char *resource = cgGetParameterResourceName(map[id._seqno]); - if (resource != NULL) { + if (resource != nullptr) { shader_cat.debug() << "Uniform parameter " << id._name << " is bound to resource " << resource << "\n"; } @@ -2258,7 +2264,7 @@ cg_compile_for(const ShaderCaps &caps, CGcontext context, if (shader_cat.is_debug()) { const char *resource = cgGetParameterResourceName(p); - if (resource != NULL) { + if (resource != nullptr) { shader_cat.debug() << "Texture parameter " << id._name << " is bound to resource " << resource << "\n"; } @@ -2271,7 +2277,7 @@ cg_compile_for(const ShaderCaps &caps, CGcontext context, CGparameter p = cgGetNamedParameter(programs_by_type[id._type], id._name.c_str()); const char *resource = cgGetParameterResourceName(p); - if (shader_cat.is_debug() && resource != NULL) { + if (shader_cat.is_debug() && resource != nullptr) { if (cgGetParameterResource(p) == CG_GLSL_ATTRIB) { shader_cat.debug() << "Varying parameter " << id._name << " is bound to GLSL attribute " @@ -2293,7 +2299,7 @@ cg_compile_for(const ShaderCaps &caps, CGcontext context, if (shader_cat.is_debug()) { const char *resource = cgGetParameterResourceName(map[id._seqno]); - if (resource != NULL) { + if (resource != nullptr) { shader_cat.debug() << "Uniform ptr parameter " << id._name << " is bound to resource " << resource << "\n"; } @@ -2455,7 +2461,7 @@ bool Shader:: do_read_source(string &into, const Filename &fn, BamCacheRecord *record) { if (_language == SL_GLSL && glsl_preprocess) { // Preprocess the GLSL file as we read it. - set open_files; + std::set open_files; ostringstream sstr; if (!r_preprocess_source(sstr, fn, Filename(), open_files, record)) { return false; @@ -2467,7 +2473,7 @@ do_read_source(string &into, const Filename &fn, BamCacheRecord *record) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); PT(VirtualFile) vf = vfs->find_file(fn, get_model_path()); - if (vf == NULL) { + if (vf == nullptr) { shader_cat.error() << "Could not find shader file: " << fn << "\n"; return false; @@ -2479,10 +2485,10 @@ do_read_source(string &into, const Filename &fn, BamCacheRecord *record) { return false; } - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { record->add_dependent_file(vf); } - _last_modified = max(_last_modified, vf->get_timestamp()); + _last_modified = std::max(_last_modified, vf->get_timestamp()); _source_files.push_back(vf->get_filename()); } @@ -2491,6 +2497,9 @@ do_read_source(string &into, const Filename &fn, BamCacheRecord *record) { into.resize(into.size() - 1); } + // Except add back a newline at the end, which is needed by Intel drivers. + into += "\n"; + return true; } @@ -2504,7 +2513,7 @@ do_read_source(string &into, const Filename &fn, BamCacheRecord *record) { bool Shader:: r_preprocess_source(ostream &out, const Filename &fn, const Filename &source_dir, - set &once_files, + std::set &once_files, BamCacheRecord *record, int depth) { if (depth > glsl_include_recursion_limit) { @@ -2521,7 +2530,7 @@ r_preprocess_source(ostream &out, const Filename &fn, VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); PT(VirtualFile) vf = vfs->find_file(fn, path); - if (vf == NULL) { + if (vf == nullptr) { shader_cat.error() << "Could not find shader file: " << fn << "\n"; return false; @@ -2534,16 +2543,16 @@ r_preprocess_source(ostream &out, const Filename &fn, } istream *source = vf->open_read_file(true); - if (source == NULL) { + if (source == nullptr) { shader_cat.error() << "Could not open shader file: " << fn << "\n"; return false; } - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { record->add_dependent_file(vf); } - _last_modified = max(_last_modified, vf->get_timestamp()); + _last_modified = std::max(_last_modified, vf->get_timestamp()); _source_files.push_back(full_fn); // We give each file an unique index. This is so that we can identify a @@ -2575,7 +2584,7 @@ r_preprocess_source(ostream &out, const Filename &fn, int ext_google_line = 0; bool had_include = false; int lineno = 0; - while (getline(*source, line)) { + while (std::getline(*source, line)) { ++lineno; if (line.empty()) { @@ -2589,7 +2598,7 @@ r_preprocess_source(ostream &out, const Filename &fn, line.resize(line.size() - 1); string line2; - if (getline(*source, line2)) { + if (std::getline(*source, line2)) { line += line2; out.put('\n'); ++lineno; @@ -2618,7 +2627,7 @@ r_preprocess_source(ostream &out, const Filename &fn, size_t block_end = line2.find("*/"); while (block_end == string::npos) { // Didn't find it - look in the next line. - if (getline(*source, line2)) { + if (std::getline(*source, line2)) { out.put('\n'); ++lineno; block_end = line2.find("*/"); @@ -2646,7 +2655,7 @@ r_preprocess_source(ostream &out, const Filename &fn, } char pragma[64]; - int nread = 0; + size_t nread = 0; // What kind of directive is it? if (strcmp(directive, "pragma") == 0 && sscanf(line.c_str(), " # pragma %63s", pragma) == 1) { @@ -2655,13 +2664,13 @@ r_preprocess_source(ostream &out, const Filename &fn, Filename incfn, source_dir; { char incfile[2048]; - if (sscanf(line.c_str(), " # pragma%*[ \t]include \"%2047[^\"]\" %n", incfile, &nread) == 1 + if (sscanf(line.c_str(), " # pragma%*[ \t]include \"%2047[^\"]\" %zn", incfile, &nread) == 1 && nread == line.size()) { // A regular include, with double quotes. Probably a local file. source_dir = full_fn.get_dirname(); incfn = incfile; - } else if (sscanf(line.c_str(), " # pragma%*[ \t]include <%2047[^\"]> %n", incfile, &nread) == 1 + } else if (sscanf(line.c_str(), " # pragma%*[ \t]include <%2047[^\"]> %zn", incfile, &nread) == 1 && nread == line.size()) { // Angled includes are also OK, but we don't search in the directory // of the source file. @@ -2690,7 +2699,7 @@ r_preprocess_source(ostream &out, const Filename &fn, } else if (strcmp(pragma, "once") == 0) { // Do a stricter syntax check, just to be extra safe. - if (sscanf(line.c_str(), " # pragma%*[ \t]once %n", &nread) != 0 || + if (sscanf(line.c_str(), " # pragma%*[ \t]once %zn", &nread) != 0 || nread != line.size()) { shader_cat.error() << "Malformed #pragma once at line " << lineno @@ -2709,7 +2718,6 @@ r_preprocess_source(ostream &out, const Filename &fn, // Check for an #endif after an include. We have to restore the line // number in case the include happened under an #if block. out << line << "\n"; - int nread = 0; if (had_include) { out << "#line " << (lineno + 1) << " " << fileno << "\n"; } @@ -2783,7 +2791,7 @@ r_preprocess_source(ostream &out, const Filename &fn, Filename incfn; { char incfile[2048]; - if (sscanf(line.c_str(), " # include%*[ \t]\"%2047[^\"]\" %n", incfile, &nread) != 1 + if (sscanf(line.c_str(), " # include%*[ \t]\"%2047[^\"]\" %zn", incfile, &nread) != 1 || nread != line.size()) { // Couldn't parse it. shader_cat.error() @@ -2810,7 +2818,7 @@ r_preprocess_source(ostream &out, const Filename &fn, } else if (ext_google_line > 0 && strcmp(directive, "line") == 0) { // It's a #line directive. See if it uses a string instead of number. char filestr[2048]; - if (sscanf(line.c_str(), " # line%*[ \t]%d%*[ \t]\"%2047[^\"]\" %n", &lineno, filestr, &nread) == 2 + if (sscanf(line.c_str(), " # line%*[ \t]%d%*[ \t]\"%2047[^\"]\" %zn", &lineno, filestr, &nread) == 2 && nread == line.size()) { // Warn about extension use if requested. if (ext_google_line == 1) { @@ -2857,7 +2865,7 @@ check_modified() const { const Filename &fn = (*it); PT(VirtualFile) vfile = vfs->get_file(fn, true); - if (vfile == (VirtualFile *)NULL || vfile->get_timestamp() > _last_modified) { + if (vfile == nullptr || vfile->get_timestamp() > _last_modified) { return true; } } @@ -3052,7 +3060,7 @@ load(const Filename &file, ShaderLanguage lang) { PT(Shader) shader = new Shader(lang); if (!shader->read(sfile)) { - return NULL; + return nullptr; } _load_table[sfile] = shader; @@ -3090,7 +3098,7 @@ load(ShaderLanguage lang, const Filename &vertex, PT(Shader) shader = new Shader(lang); if (!shader->read(sfile)) { - return NULL; + return nullptr; } _load_table[sfile] = shader; @@ -3113,7 +3121,7 @@ load_compute(ShaderLanguage lang, const Filename &fn) { if (lang != SL_GLSL) { shader_cat.error() << "Only GLSL compute shaders are currently supported.\n"; - return NULL; + return nullptr; } Filename fullpath(fn); @@ -3121,7 +3129,7 @@ load_compute(ShaderLanguage lang, const Filename &fn) { if (!vfs->resolve_filename(fullpath, get_model_path())) { shader_cat.error() << "Could not find compute shader file: " << fn << "\n"; - return NULL; + return nullptr; } ShaderFile sfile; @@ -3143,7 +3151,7 @@ load_compute(ShaderLanguage lang, const Filename &fn) { BamCache *cache = BamCache::get_global_ptr(); PT(BamCacheRecord) record = cache->lookup(fullpath, "sho"); - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { if (record->has_data()) { shader_cat.info() << "Compute shader " << fn << " was found in disk cache.\n"; @@ -3155,7 +3163,7 @@ load_compute(ShaderLanguage lang, const Filename &fn) { PT(Shader) shader = new Shader(lang); if (!shader->read(sfile, record)) { - return NULL; + return nullptr; } _load_table[sfile] = shader; @@ -3169,7 +3177,7 @@ load_compute(ShaderLanguage lang, const Filename &fn) { // It makes little sense to cache the shader before compilation, so we keep // the record for when we have the compiled the shader. - swap(shader->_record, record); + std::swap(shader->_record, record); shader->_cache_compiled_shader = BamCache::get_global_ptr()->get_cache_compiled_shaders(); shader->_fullpath = shader->_source_files[0]; return shader; @@ -3183,7 +3191,7 @@ make(string body, ShaderLanguage lang) { if (lang == SL_GLSL) { shader_cat.error() << "GLSL shaders must have separate shader bodies!\n"; - return NULL; + return nullptr; } else if (lang == SL_none) { shader_cat.warning() @@ -3193,7 +3201,7 @@ make(string body, ShaderLanguage lang) { #ifndef HAVE_CG if (lang == SL_Cg) { shader_cat.error() << "Support for Cg shaders is not enabled.\n"; - return NULL; + return nullptr; } #endif @@ -3217,7 +3225,7 @@ make(string body, ShaderLanguage lang) { if (!shader->cg_analyze_shader(_default_caps)) { shader_cat.error() << "Shader encountered an error.\n"; - return NULL; + return nullptr; } } #endif @@ -3234,7 +3242,7 @@ make(string body, ShaderLanguage lang) { shader_cat.warning() << "Dumping shader: " << fn << "\n"; pofstream s; - s.open(fn.c_str(), ios::out | ios::trunc); + s.open(fn.c_str(), std::ios::out | std::ios::trunc); s << shader->get_text(); s.close(); } @@ -3250,13 +3258,13 @@ make(ShaderLanguage lang, string vertex, string fragment, string geometry, #ifndef HAVE_CG if (lang == SL_Cg) { shader_cat.error() << "Support for Cg shaders is not enabled.\n"; - return NULL; + return nullptr; } #endif if (lang == SL_none) { shader_cat.error() << "Shader::make() requires an explicit shader language.\n"; - return NULL; + return nullptr; } ShaderFile sbody(move(vertex), move(fragment), move(geometry), @@ -3278,7 +3286,7 @@ make(ShaderLanguage lang, string vertex, string fragment, string geometry, if (!shader->cg_analyze_shader(_default_caps)) { shader_cat.error() << "Shader encountered an error.\n"; - return NULL; + return nullptr; } } #endif @@ -3298,7 +3306,7 @@ make_compute(ShaderLanguage lang, string body) { if (lang != SL_GLSL) { shader_cat.error() << "Only GLSL compute shaders are currently supported.\n"; - return NULL; + return nullptr; } ShaderFile sbody; @@ -3409,8 +3417,7 @@ parse_eof() { */ PT(AsyncFuture) Shader:: prepare(PreparedGraphicsObjects *prepared_objects) { - PT(PreparedGraphicsObjects::EnqueuedObject) obj = prepared_objects->enqueue_shader_future(this); - return obj.p(); + return prepared_objects->enqueue_shader_future(this); } /** @@ -3437,7 +3444,7 @@ release(PreparedGraphicsObjects *prepared_objects) { ci = _contexts.find(prepared_objects); if (ci != _contexts.end()) { ShaderContext *sc = (*ci).second; - if (sc != (ShaderContext *)NULL) { + if (sc != nullptr) { prepared_objects->release_shader(sc); } else { _contexts.erase(ci); @@ -3511,7 +3518,7 @@ release_all() { for (ci = temp.begin(); ci != temp.end(); ++ci) { PreparedGraphicsObjects *prepared_objects = (*ci).first; ShaderContext *sc = (*ci).second; - if (sc != (ShaderContext *)NULL) { + if (sc != nullptr) { prepared_objects->release_shader(sc); } } diff --git a/panda/src/gobj/shader.h b/panda/src/gobj/shader.h index 996ee1b7aa..8e65c005e9 100644 --- a/panda/src/gobj/shader.h +++ b/panda/src/gobj/shader.h @@ -33,6 +33,7 @@ #include "pta_LVecBase2.h" #include "epvector.h" #include "asyncFuture.h" +#include "bamCacheRecord.h" #ifdef HAVE_CG // I don't want to include the Cg header file into panda as a whole. Instead, @@ -42,8 +43,6 @@ typedef struct _CGprogram *CGprogram; typedef struct _CGparameter *CGparameter; #endif -class BamCacheRecord; - /** */ @@ -84,7 +83,7 @@ PUBLISHED: }; static PT(Shader) load(const Filename &file, ShaderLanguage lang = SL_none); - static PT(Shader) make(string body, ShaderLanguage lang = SL_none); + static PT(Shader) make(std::string body, ShaderLanguage lang = SL_none); static PT(Shader) load(ShaderLanguage lang, const Filename &vertex, const Filename &fragment, const Filename &geometry = "", @@ -92,15 +91,15 @@ PUBLISHED: const Filename &tess_evaluation = ""); static PT(Shader) load_compute(ShaderLanguage lang, const Filename &fn); static PT(Shader) make(ShaderLanguage lang, - string vertex, string fragment, - string geometry = "", - string tess_control = "", - string tess_evaluation = ""); - static PT(Shader) make_compute(ShaderLanguage lang, string body); + std::string vertex, std::string fragment, + std::string geometry = "", + std::string tess_control = "", + std::string tess_evaluation = ""); + static PT(Shader) make_compute(ShaderLanguage lang, std::string body); INLINE Filename get_filename(ShaderType type = ST_none) const; INLINE void set_filename(ShaderType type, const Filename &filename); - INLINE const string &get_text(ShaderType type = ST_none) const; + INLINE const std::string &get_text(ShaderType type = ST_none) const; INLINE bool get_error_flag() const; INLINE ShaderLanguage get_language() const; @@ -327,7 +326,7 @@ public: }; struct ShaderArgId { - string _name; + std::string _name; ShaderType _type; int _seqno; }; @@ -437,7 +436,7 @@ public: ShaderPtrType _type; }; - class ShaderCaps { + class EXPCL_PANDA_GOBJ ShaderCaps { public: void clear(); INLINE bool operator == (const ShaderCaps &other) const; @@ -464,9 +463,9 @@ public: class ShaderFile : public ReferenceCount { public: INLINE ShaderFile() {}; - INLINE ShaderFile(string shared); - INLINE ShaderFile(string vertex, string fragment, string geometry, - string tess_control, string tess_evaluation); + INLINE ShaderFile(std::string shared); + INLINE ShaderFile(std::string vertex, std::string fragment, std::string geometry, + std::string tess_control, std::string tess_evaluation); INLINE void write_datagram(Datagram &dg) const; INLINE void read_datagram(DatagramIterator &source); @@ -475,13 +474,13 @@ public: public: bool _separate; - string _shared; - string _vertex; - string _fragment; - string _geometry; - string _tess_control; - string _tess_evaluation; - string _compute; + std::string _shared; + std::string _vertex; + std::string _fragment; + std::string _geometry; + std::string _tess_control; + std::string _tess_evaluation; + std::string _compute; }; public: @@ -489,12 +488,12 @@ public: // implementations that need to do so. Don't use them when you use separate // shader programs. void parse_init(); - void parse_line(string &result, bool rt, bool lt); - void parse_upto(string &result, string pattern, bool include); - void parse_rest(string &result); + void parse_line(std::string &result, bool rt, bool lt); + void parse_upto(std::string &result, std::string pattern, bool include); + void parse_rest(std::string &result); bool parse_eof(); - void cp_report_error(ShaderArgInfo &arg, const string &msg); + void cp_report_error(ShaderArgInfo &arg, const std::string &msg); bool cp_errchk_parameter_words(ShaderArgInfo &arg, int len); bool cp_errchk_parameter_in(ShaderArgInfo &arg); bool cp_errchk_parameter_ptr(ShaderArgInfo &p); @@ -506,7 +505,7 @@ public: vector_string &pieces, int &next); bool cp_parse_delimiter(ShaderArgInfo &arg, vector_string &pieces, int &next); - string cp_parse_non_delimiter(vector_string &pieces, int &next); + std::string cp_parse_non_delimiter(vector_string &pieces, int &next); bool cp_parse_coord_sys(ShaderArgInfo &arg, vector_string &pieces, int &next, ShaderMatSpec &spec, bool fromflag); @@ -524,7 +523,7 @@ public: void clear_parameters(); void set_compiled(unsigned int format, const char *data, size_t length); - bool get_compiled(unsigned int &format, string &binary) const; + bool get_compiled(unsigned int &format, std::string &binary) const; private: #ifdef HAVE_CG @@ -593,7 +592,7 @@ protected: PT(BamCacheRecord) _record; bool _cache_compiled_shader; unsigned int _compiled_format; - string _compiled_binary; + std::string _compiled_binary; static ShaderCaps _default_caps; static int _shaders_generated; @@ -614,11 +613,11 @@ private: Shader(ShaderLanguage lang); - bool read(const ShaderFile &sfile, BamCacheRecord *record = NULL); - bool do_read_source(string &into, const Filename &fn, BamCacheRecord *record); - bool r_preprocess_source(ostream &out, const Filename &fn, + bool read(const ShaderFile &sfile, BamCacheRecord *record = nullptr); + bool do_read_source(std::string &into, const Filename &fn, BamCacheRecord *record); + bool r_preprocess_source(std::ostream &out, const Filename &fn, const Filename &source_dir, - set &open_files, + std::set &open_files, BamCacheRecord *record, int depth = 0); bool check_modified() const; diff --git a/panda/src/gobj/shaderBuffer.I b/panda/src/gobj/shaderBuffer.I index fbd0b42e46..59d62d0171 100644 --- a/panda/src/gobj/shaderBuffer.I +++ b/panda/src/gobj/shaderBuffer.I @@ -16,7 +16,7 @@ * parameters cannot be modified, but this may change in the future. */ INLINE ShaderBuffer:: -ShaderBuffer(const string &name, uint64_t size, UsageHint usage_hint) : +ShaderBuffer(const std::string &name, uint64_t size, UsageHint usage_hint) : Namable(name), _data_size_bytes(size), _usage_hint(usage_hint), @@ -28,7 +28,7 @@ ShaderBuffer(const string &name, uint64_t size, UsageHint usage_hint) : * parameters cannot be modified, but this may change in the future. */ INLINE ShaderBuffer:: -ShaderBuffer(const string &name, pvector initial_data, UsageHint usage_hint) : +ShaderBuffer(const std::string &name, vector_uchar initial_data, UsageHint usage_hint) : Namable(name), _data_size_bytes(initial_data.size()), _usage_hint(usage_hint), @@ -58,7 +58,7 @@ get_usage_hint() const { INLINE const unsigned char *ShaderBuffer:: get_initial_data() const { if (_initial_data.empty()) { - return NULL; + return nullptr; } else { return &_initial_data[0]; } diff --git a/panda/src/gobj/shaderBuffer.cxx b/panda/src/gobj/shaderBuffer.cxx index f0b45df540..971787f0e6 100644 --- a/panda/src/gobj/shaderBuffer.cxx +++ b/panda/src/gobj/shaderBuffer.cxx @@ -28,7 +28,7 @@ ShaderBuffer:: * */ void ShaderBuffer:: -output(ostream &out) const { +output(std::ostream &out) const { out << "buffer " << get_name() << ", " << _data_size_bytes << "B, " << _usage_hint; } @@ -51,7 +51,7 @@ prepare(PreparedGraphicsObjects *prepared_objects) { */ bool ShaderBuffer:: is_prepared(PreparedGraphicsObjects *prepared_objects) const { - if (_contexts == (Contexts *)NULL) { + if (_contexts == nullptr) { return false; } Contexts::const_iterator ci; @@ -76,7 +76,7 @@ is_prepared(PreparedGraphicsObjects *prepared_objects) const { BufferContext *ShaderBuffer:: prepare_now(PreparedGraphicsObjects *prepared_objects, GraphicsStateGuardianBase *gsg) { - if (_contexts == (Contexts *)NULL) { + if (_contexts == nullptr) { _contexts = new Contexts; } Contexts::const_iterator ci; @@ -86,7 +86,7 @@ prepare_now(PreparedGraphicsObjects *prepared_objects, } BufferContext *vbc = prepared_objects->prepare_shader_buffer_now(this, gsg); - if (vbc != (BufferContext *)NULL) { + if (vbc != nullptr) { (*_contexts)[prepared_objects] = vbc; } return vbc; @@ -98,7 +98,7 @@ prepare_now(PreparedGraphicsObjects *prepared_objects, */ bool ShaderBuffer:: release(PreparedGraphicsObjects *prepared_objects) { - if (_contexts != (Contexts *)NULL) { + if (_contexts != nullptr) { Contexts::iterator ci; ci = _contexts->find(prepared_objects); if (ci != _contexts->end()) { @@ -120,7 +120,7 @@ int ShaderBuffer:: release_all() { int num_freed = 0; - if (_contexts != (Contexts *)NULL) { + if (_contexts != nullptr) { // We have to traverse a copy of the _contexts list, because the // PreparedGraphicsObjects object will call clear_prepared() in response // to each release_shader_buffer(), and we don't want to be modifying the @@ -137,7 +137,7 @@ release_all() { // Now that we've called release_shader_buffer() on every known context, // the _contexts list should have completely emptied itself. - nassertr(_contexts == NULL, num_freed); + nassertr(_contexts == nullptr, num_freed); } return num_freed; diff --git a/panda/src/gobj/shaderBuffer.h b/panda/src/gobj/shaderBuffer.h index 8d48fed425..69bdf985d9 100644 --- a/panda/src/gobj/shaderBuffer.h +++ b/panda/src/gobj/shaderBuffer.h @@ -20,6 +20,7 @@ #include "geomEnums.h" #include "graphicsStateGuardianBase.h" #include "factoryParams.h" +#include "vector_uchar.h" class BufferContext; class PreparedGraphicsObjects; @@ -29,20 +30,20 @@ class PreparedGraphicsObjects; */ class EXPCL_PANDA_GOBJ ShaderBuffer : public TypedWritableReferenceCount, public Namable, public GeomEnums { private: - INLINE ShaderBuffer() DEFAULT_CTOR; + INLINE ShaderBuffer() = default; PUBLISHED: ~ShaderBuffer(); - INLINE explicit ShaderBuffer(const string &name, uint64_t size, UsageHint usage_hint); - INLINE explicit ShaderBuffer(const string &name, pvector initial_data, UsageHint usage_hint); + INLINE explicit ShaderBuffer(const std::string &name, uint64_t size, UsageHint usage_hint); + INLINE explicit ShaderBuffer(const std::string &name, vector_uchar initial_data, UsageHint usage_hint); public: INLINE uint64_t get_data_size_bytes() const; INLINE UsageHint get_usage_hint() const; INLINE const unsigned char *get_initial_data() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; PUBLISHED: MAKE_PROPERTY(data_size_bytes, get_data_size_bytes); @@ -59,7 +60,7 @@ PUBLISHED: private: uint64_t _data_size_bytes; UsageHint _usage_hint; - pvector _initial_data; + vector_uchar _initial_data; typedef pmap Contexts; Contexts *_contexts; @@ -92,7 +93,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const ShaderBuffer &m) { +INLINE std::ostream &operator << (std::ostream &out, const ShaderBuffer &m) { m.output(out); return out; } diff --git a/panda/src/gobj/simpleAllocator.I b/panda/src/gobj/simpleAllocator.I index e537526d8a..1f8bf4e01c 100644 --- a/panda/src/gobj/simpleAllocator.I +++ b/panda/src/gobj/simpleAllocator.I @@ -32,9 +32,9 @@ SimpleAllocator(size_t max_size, Mutex &lock) : * pointer. */ SimpleAllocatorBlock *SimpleAllocator:: -alloc(size_t size) { +alloc(size_t size, size_t alignment) { MutexHolder holder(_lock); - return do_alloc(size); + return do_alloc(size, alignment); } /** @@ -95,7 +95,7 @@ get_contiguous() const { INLINE SimpleAllocatorBlock *SimpleAllocator:: get_first_block() const { MutexHolder holder(_lock); - return (_next == this) ? (SimpleAllocatorBlock *)NULL : (SimpleAllocatorBlock *)_next; + return (_next == this) ? nullptr : (SimpleAllocatorBlock *)_next; } /** @@ -148,6 +148,24 @@ SimpleAllocatorBlock(SimpleAllocator *alloc, { } +/** + * Transfers ownership from the given SimpleAllocatorBlock to this one. + */ +INLINE SimpleAllocatorBlock:: +SimpleAllocatorBlock(SimpleAllocatorBlock &&from) : + _allocator(from._allocator) +{ + if (_allocator == nullptr) { + return; + } + + MutexHolder holder(_allocator->_lock); + _start = from._start; + _size = from._size; + LinkedListNode::operator = (std::move(from)); + from._allocator = nullptr; +} + /** * The block automatically frees itself when it destructs. */ @@ -156,12 +174,34 @@ INLINE SimpleAllocatorBlock:: free(); } +/** + * Frees this block and instead takes ownership of the given other block. + */ +INLINE SimpleAllocatorBlock &SimpleAllocatorBlock:: +operator = (SimpleAllocatorBlock &&from) { + free(); + + _allocator = from._allocator; + if (_allocator == nullptr) { + _start = 0; + _size = 0; + return *this; + } + + MutexHolder holder(_allocator->_lock); + _start = from._start; + _size = from._size; + LinkedListNode::operator = (std::move(from)); + from._allocator = nullptr; + return *this; +} + /** * Releases the allocated space. */ INLINE void SimpleAllocatorBlock:: free() { - if (_allocator != (SimpleAllocator *)NULL) { + if (_allocator != nullptr) { MutexHolder holder(_allocator->_lock); do_free(); } @@ -182,7 +222,7 @@ get_allocator() const { */ INLINE size_t SimpleAllocatorBlock:: get_start() const { - nassertr(_allocator != (SimpleAllocator *)NULL, 0); + nassertr(_allocator != nullptr, 0); return _start; } @@ -192,7 +232,7 @@ get_start() const { */ INLINE size_t SimpleAllocatorBlock:: get_size() const { - nassertr(_allocator != (SimpleAllocator *)NULL, 0); + nassertr(_allocator != nullptr, 0); return _size; } @@ -201,7 +241,7 @@ get_size() const { */ INLINE bool SimpleAllocatorBlock:: is_free() const { - return (_allocator != (SimpleAllocator *)NULL); + return (_allocator != nullptr); } /** @@ -210,7 +250,7 @@ is_free() const { */ INLINE size_t SimpleAllocatorBlock:: get_max_size() const { - nassertr(_allocator != (SimpleAllocator *)NULL, 0); + nassertr(_allocator != nullptr, 0); MutexHolder holder(_allocator->_lock); return do_get_max_size(); } @@ -221,7 +261,7 @@ get_max_size() const { */ INLINE bool SimpleAllocatorBlock:: realloc(size_t size) { - nassertr(_allocator != (SimpleAllocator *)NULL, false); + nassertr(_allocator != nullptr, false); MutexHolder holder(_allocator->_lock); return do_realloc(size); } @@ -232,9 +272,9 @@ realloc(size_t size) { */ INLINE SimpleAllocatorBlock *SimpleAllocatorBlock:: get_next_block() const { - nassertr(_allocator != (SimpleAllocator *)NULL, NULL); + nassertr(_allocator != nullptr, nullptr); MutexHolder holder(_allocator->_lock); - return (_next == _allocator) ? (SimpleAllocatorBlock *)NULL : (SimpleAllocatorBlock *)_next; + return (_next == _allocator) ? nullptr : (SimpleAllocatorBlock *)_next; } /** @@ -244,13 +284,13 @@ get_next_block() const { */ INLINE void SimpleAllocatorBlock:: do_free() { - nassertv(_allocator != (SimpleAllocator *)NULL); + nassertv(_allocator != nullptr); _allocator->_total_size -= _size; LinkedListNode *prev = _prev; remove_from_list(); _allocator->mark_contiguous(prev); - _allocator = NULL; + _allocator = nullptr; } /** diff --git a/panda/src/gobj/simpleAllocator.cxx b/panda/src/gobj/simpleAllocator.cxx index ddae004ee8..fa6b20d1a3 100644 --- a/panda/src/gobj/simpleAllocator.cxx +++ b/panda/src/gobj/simpleAllocator.cxx @@ -13,6 +13,37 @@ #include "simpleAllocator.h" +/** + * Move constructor. + */ +SimpleAllocator:: +SimpleAllocator(SimpleAllocator &&from) noexcept : + LinkedListNode(std::move(from)), + _total_size(from._total_size), + _max_size(from._max_size), + _contiguous(from._contiguous), + _lock(from._lock) +{ + MutexHolder holder(_lock); + from._total_size = 0; + from._max_size = 0; + from._contiguous = 0; + + // We still need to leave the list in a valid state. + from._prev = &from; + from._next = &from; + + // Change all the blocks to point to the new allocator. + LinkedListNode *next = _next; + while (next != this) { + SimpleAllocatorBlock *block = (SimpleAllocatorBlock *)next; + nassertv(block->_allocator == &from); + block->_allocator = this; + + next = block->_next; + } +} + /** * */ @@ -22,7 +53,7 @@ SimpleAllocator:: if (_next != (LinkedListNode *)this) { MutexHolder holder(_lock); while (_next != (LinkedListNode *)this) { - nassertv(_next != (LinkedListNode *)NULL); + nassertv(_next != nullptr); ((SimpleAllocatorBlock *)_next)->do_free(); } } @@ -32,7 +63,7 @@ SimpleAllocator:: * */ void SimpleAllocator:: -output(ostream &out) const { +output(std::ostream &out) const { MutexHolder holder(_lock); out << "SimpleAllocator, " << _total_size << " of " << _max_size << " allocated"; @@ -42,7 +73,7 @@ output(ostream &out) const { * */ void SimpleAllocator:: -write(ostream &out) const { +write(std::ostream &out) const { MutexHolder holder(_lock); out << "SimpleAllocator, " << _total_size << " of " << _max_size << " allocated"; @@ -66,16 +97,16 @@ write(ostream &out) const { * Assumes the lock is already held. */ SimpleAllocatorBlock *SimpleAllocator:: -do_alloc(size_t size) { +do_alloc(size_t size, size_t alignment) { if (size > _contiguous) { // Don't even bother. - return NULL; + return nullptr; } // First fit algorithm: walk through all the empty blocks until we find one // that has enough room. - SimpleAllocatorBlock *block = NULL; + SimpleAllocatorBlock *block = nullptr; size_t end = 0; size_t best = 0; if (_next != this) { @@ -86,10 +117,10 @@ do_alloc(size_t size) { // Scan until we have reached the last allocated block. while (block->_next != this) { SimpleAllocatorBlock *next = (SimpleAllocatorBlock *)block->_next; - size_t free_size = next->_start - end; - if (size <= free_size) { - SimpleAllocatorBlock *new_block = make_block(end, size); - nassertr(new_block->get_allocator() == this, NULL); + size_t start = end + ((alignment - end) % alignment); + if (start + size <= next->_start) { + SimpleAllocatorBlock *new_block = make_block(start, size); + nassertr(new_block->get_allocator() == this, nullptr); new_block->insert_before(next); _total_size += size; @@ -103,6 +134,7 @@ do_alloc(size_t size) { } return new_block; } + size_t free_size = next->_start - end; if (free_size > best) { best = free_size; } @@ -113,10 +145,10 @@ do_alloc(size_t size) { } // No free blocks; check for room at the end. - size_t free_size = _max_size - end; - if (size <= free_size) { - SimpleAllocatorBlock *new_block = make_block(end, size); - nassertr(new_block->get_allocator() == this, NULL); + size_t start = end + ((alignment - end) % alignment); + if (start + size <= _max_size) { + SimpleAllocatorBlock *new_block = make_block(start, size); + nassertr(new_block->get_allocator() == this, nullptr); new_block->insert_before(this); _total_size += size; @@ -131,6 +163,7 @@ do_alloc(size_t size) { return new_block; } + size_t free_size = _max_size - end; if (free_size > best) { best = free_size; } @@ -143,7 +176,7 @@ do_alloc(size_t size) { } // No room for this block. - return NULL; + return nullptr; } /** @@ -168,8 +201,8 @@ changed_contiguous() { * */ void SimpleAllocatorBlock:: -output(ostream &out) const { - if (_allocator == (SimpleAllocator *)NULL) { +output(std::ostream &out) const { + if (_allocator == nullptr) { out << "free block\n"; } else { MutexHolder holder(_allocator->_lock); diff --git a/panda/src/gobj/simpleAllocator.h b/panda/src/gobj/simpleAllocator.h index 7793fdc3fe..5a9ca7b616 100644 --- a/panda/src/gobj/simpleAllocator.h +++ b/panda/src/gobj/simpleAllocator.h @@ -29,9 +29,10 @@ class SimpleAllocatorBlock; class EXPCL_PANDA_GOBJ SimpleAllocator : public LinkedListNode { PUBLISHED: INLINE explicit SimpleAllocator(size_t max_size, Mutex &lock); + SimpleAllocator(SimpleAllocator &&from) noexcept; virtual ~SimpleAllocator(); - INLINE SimpleAllocatorBlock *alloc(size_t size); + INLINE SimpleAllocatorBlock *alloc(size_t size, size_t alignment=1); INLINE bool is_empty() const; INLINE size_t get_total_size() const; @@ -41,11 +42,11 @@ PUBLISHED: INLINE SimpleAllocatorBlock *get_first_block() const; - void output(ostream &out) const; - void write(ostream &out) const; + void output(std::ostream &out) const; + void write(std::ostream &out) const; protected: - SimpleAllocatorBlock *do_alloc(size_t size); + SimpleAllocatorBlock *do_alloc(size_t size, size_t alignment=1); INLINE bool do_is_empty() const; virtual SimpleAllocatorBlock *make_block(size_t start, size_t size); @@ -91,6 +92,14 @@ protected: INLINE SimpleAllocatorBlock(SimpleAllocator *alloc, size_t start, size_t size); +public: + SimpleAllocatorBlock() = default; + SimpleAllocatorBlock(const SimpleAllocatorBlock ©) = delete; + INLINE SimpleAllocatorBlock(SimpleAllocatorBlock &&from); + + SimpleAllocatorBlock &operator = (const SimpleAllocatorBlock ©) = delete; + INLINE SimpleAllocatorBlock &operator = (SimpleAllocatorBlock &&from); + PUBLISHED: INLINE ~SimpleAllocatorBlock(); INLINE void free(); @@ -106,7 +115,7 @@ PUBLISHED: INLINE SimpleAllocatorBlock *get_next_block() const; - void output(ostream &out) const; + void output(std::ostream &out) const; protected: INLINE void do_free(); @@ -114,19 +123,19 @@ protected: INLINE bool do_realloc(size_t size); private: - SimpleAllocator *_allocator; - size_t _start; - size_t _size; + SimpleAllocator *_allocator = nullptr; + size_t _start = 0; + size_t _size = 0; friend class SimpleAllocator; }; -INLINE ostream &operator << (ostream &out, const SimpleAllocator &obj) { +INLINE std::ostream &operator << (std::ostream &out, const SimpleAllocator &obj) { obj.output(out); return out; } -INLINE ostream &operator << (ostream &out, const SimpleAllocatorBlock &obj) { +INLINE std::ostream &operator << (std::ostream &out, const SimpleAllocatorBlock &obj) { obj.output(out); return out; } diff --git a/panda/src/gobj/simpleLru.I b/panda/src/gobj/simpleLru.I index fa872c7829..5ba8f342f6 100644 --- a/panda/src/gobj/simpleLru.I +++ b/panda/src/gobj/simpleLru.I @@ -94,7 +94,7 @@ validate() { */ INLINE SimpleLruPage:: SimpleLruPage(size_t lru_size) : - _lru(NULL), + _lru(nullptr), _lru_size(lru_size) { } @@ -104,7 +104,7 @@ SimpleLruPage(size_t lru_size) : */ INLINE SimpleLruPage:: SimpleLruPage(const SimpleLruPage ©) : - _lru(NULL), + _lru(nullptr), _lru_size(copy._lru_size) { } @@ -134,10 +134,10 @@ INLINE void SimpleLruPage:: dequeue_lru() { LightMutexHolder holder(SimpleLru::_global_lock); - if (_lru != (SimpleLru *)NULL) { + if (_lru != nullptr) { remove_from_list(); _lru->_total_size -= _lru_size; - _lru = NULL; + _lru = nullptr; } } @@ -150,7 +150,7 @@ dequeue_lru() { */ INLINE void SimpleLruPage:: mark_used_lru() const { - if (_lru != (SimpleLru *)NULL) { + if (_lru != nullptr) { ((SimpleLruPage *)this)->mark_used_lru(_lru); } } @@ -179,7 +179,7 @@ get_lru_size() const { INLINE void SimpleLruPage:: set_lru_size(size_t lru_size) { LightMutexHolder holder(SimpleLru::_global_lock); - if (_lru != (SimpleLru *)NULL) { + if (_lru != nullptr) { _lru->_total_size -= _lru_size; _lru->_total_size += lru_size; _lru_size = lru_size; diff --git a/panda/src/gobj/simpleLru.cxx b/panda/src/gobj/simpleLru.cxx index 97e979df63..dfdb9113da 100644 --- a/panda/src/gobj/simpleLru.cxx +++ b/panda/src/gobj/simpleLru.cxx @@ -14,6 +14,8 @@ #include "simpleLru.h" #include "indent.h" +using std::ostream; + // We define this as a reference to an allocated object, instead of as a // concrete object, so that it won't get destructed when the program exits. // (If it did, there would be an ordering issue between it and the various @@ -24,7 +26,7 @@ LightMutex &SimpleLru::_global_lock = *new LightMutex; * */ SimpleLru:: -SimpleLru(const string &name, size_t max_size) : +SimpleLru(const std::string &name, size_t max_size) : LinkedListNode(true), Namable(name) { @@ -45,8 +47,8 @@ SimpleLru:: // explicitly evict it (that would force vertex buffers to write themselves // to disk unnecessarily). while (_next != (LinkedListNode *)this) { - nassertv(_next != (LinkedListNode *)NULL); - ((SimpleLruPage *)_next)->_lru = NULL; + nassertv(_next != nullptr); + ((SimpleLruPage *)_next)->_lru = nullptr; ((SimpleLruPage *)_next)->remove_from_list(); } #endif @@ -63,22 +65,22 @@ enqueue_lru(SimpleLru *lru) { LightMutexHolder holder(SimpleLru::_global_lock); if (_lru == lru) { - if (_lru != (SimpleLru *)NULL) { + if (_lru != nullptr) { remove_from_list(); insert_before(_lru); } return; } - if (_lru != (SimpleLru *)NULL) { + if (_lru != nullptr) { remove_from_list(); _lru->_total_size -= _lru_size; - _lru = NULL; + _lru = nullptr; } _lru = lru; - if (_lru != (SimpleLru *)NULL) { + if (_lru != nullptr) { _lru->_total_size += _lru_size; insert_before(_lru); } @@ -169,9 +171,9 @@ do_evict_to(size_t target_size, bool hard_evict) { SimpleLruPage *next = (SimpleLruPage *)node->_next; // We must release the lock while we call evict_lru(). - _global_lock.release(); + _global_lock.unlock(); node->evict_lru(); - _global_lock.acquire(); + _global_lock.lock(); if (node == end || node == _prev) { // If we reach the original tail of the list, stop. @@ -208,7 +210,7 @@ do_validate() { */ SimpleLruPage:: ~SimpleLruPage() { - if (_lru != NULL) { + if (_lru != nullptr) { dequeue_lru(); } } diff --git a/panda/src/gobj/simpleLru.h b/panda/src/gobj/simpleLru.h index 0eaaced1c8..5a712d8ffc 100644 --- a/panda/src/gobj/simpleLru.h +++ b/panda/src/gobj/simpleLru.h @@ -27,7 +27,7 @@ class SimpleLruPage; */ class EXPCL_PANDA_GOBJ SimpleLru : public LinkedListNode, public Namable { PUBLISHED: - explicit SimpleLru(const string &name, size_t max_size); + explicit SimpleLru(const std::string &name, size_t max_size); ~SimpleLru(); INLINE size_t get_total_size() const; @@ -41,8 +41,8 @@ PUBLISHED: INLINE bool validate(); - void output(ostream &out) const; - void write(ostream &out, int indent_level) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level) const; public: static LightMutex &_global_lock; @@ -83,8 +83,8 @@ PUBLISHED: virtual void evict_lru(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; private: SimpleLru *_lru; @@ -94,12 +94,12 @@ private: friend class SimpleLru; }; -inline ostream &operator << (ostream &out, const SimpleLru &lru) { +inline std::ostream &operator << (std::ostream &out, const SimpleLru &lru) { lru.output(out); return out; } -inline ostream &operator << (ostream &out, const SimpleLruPage &page) { +inline std::ostream &operator << (std::ostream &out, const SimpleLruPage &page) { page.output(out); return out; } diff --git a/panda/src/gobj/sliderTable.I b/panda/src/gobj/sliderTable.I index 959c2e8651..be2d86f12f 100644 --- a/panda/src/gobj/sliderTable.I +++ b/panda/src/gobj/sliderTable.I @@ -59,7 +59,7 @@ get_num_sliders() const { */ INLINE const VertexSlider *SliderTable:: get_slider(size_t n) const { - nassertr(n < _sliders.size(), NULL); + nassertr(n < _sliders.size(), nullptr); return _sliders[n]._slider; } diff --git a/panda/src/gobj/sliderTable.cxx b/panda/src/gobj/sliderTable.cxx index 169f023e3f..52ccdacc1c 100644 --- a/panda/src/gobj/sliderTable.cxx +++ b/panda/src/gobj/sliderTable.cxx @@ -124,7 +124,7 @@ add_slider(const VertexSlider *slider, const SparseArray &rows) { * */ void SliderTable:: -write(ostream &out) const { +write(std::ostream &out) const { for (size_t i = 0; i < _sliders.size(); ++i) { out << i << ". " << *_sliders[i]._slider << " " << _sliders[i]._rows << "\n"; diff --git a/panda/src/gobj/sliderTable.h b/panda/src/gobj/sliderTable.h index 9cc939c678..69d982112d 100644 --- a/panda/src/gobj/sliderTable.h +++ b/panda/src/gobj/sliderTable.h @@ -60,7 +60,7 @@ PUBLISHED: void remove_slider(size_t n); size_t add_slider(const VertexSlider *slider, const SparseArray &rows); - void write(ostream &out) const; + void write(std::ostream &out) const; private: void do_register(); @@ -132,7 +132,7 @@ private: friend class VertexSlider; }; -INLINE ostream &operator << (ostream &out, const SliderTable &obj); +INLINE std::ostream &operator << (std::ostream &out, const SliderTable &obj); #include "sliderTable.I" diff --git a/panda/src/gobj/test_gobj.cxx b/panda/src/gobj/test_gobj.cxx index 74b408ec97..0bbe93e907 100644 --- a/panda/src/gobj/test_gobj.cxx +++ b/panda/src/gobj/test_gobj.cxx @@ -15,7 +15,7 @@ #include "perspectiveProjection.h" int main() { - nout << "running test_gobj" << endl; + nout << "running test_gobj" << std::endl; PT(GeomTri) triangle = new GeomTri; Frustumf frust; PT(PerspectiveProjection) proj = new PerspectiveProjection(frust); diff --git a/panda/src/gobj/texture.I b/panda/src/gobj/texture.I index 8f3a91a54c..c766c5b82d 100644 --- a/panda/src/gobj/texture.I +++ b/panda/src/gobj/texture.I @@ -2147,7 +2147,7 @@ rescale_texture() { * power-2. */ INLINE bool Texture:: -adjust_this_size(int &x_size, int &y_size, const string &name, +adjust_this_size(int &x_size, int &y_size, const std::string &name, bool for_padding) const { CDReader cdata(_cycler); return do_adjust_this_size(cdata, x_size, y_size, name, for_padding); @@ -2385,7 +2385,7 @@ get_half_float(const unsigned char *&p) { */ INLINE bool Texture:: is_txo_filename(const Filename &fullpath) { - string extension = fullpath.get_extension(); + std::string extension = fullpath.get_extension(); #ifdef HAVE_ZLIB if (extension == "pz" || extension == "gz") { extension = Filename(fullpath.get_basename_wo_extension()).get_extension(); @@ -2400,7 +2400,7 @@ is_txo_filename(const Filename &fullpath) { */ INLINE bool Texture:: is_dds_filename(const Filename &fullpath) { - string extension = fullpath.get_extension(); + std::string extension = fullpath.get_extension(); #ifdef HAVE_ZLIB if (extension == "pz" || extension == "gz") { extension = Filename(fullpath.get_basename_wo_extension()).get_extension(); @@ -2415,7 +2415,7 @@ is_dds_filename(const Filename &fullpath) { */ INLINE bool Texture:: is_ktx_filename(const Filename &fullpath) { - string extension = fullpath.get_extension(); + std::string extension = fullpath.get_extension(); #ifdef HAVE_ZLIB if (extension == "pz" || extension == "gz") { extension = Filename(fullpath.get_basename_wo_extension()).get_extension(); @@ -2454,6 +2454,6 @@ inc_simple_image_modified() { INLINE Texture::RamImage:: RamImage() : _page_size(0), - _pointer_image(NULL) + _pointer_image(nullptr) { } diff --git a/panda/src/gobj/texture.cxx b/panda/src/gobj/texture.cxx index fa85fd44f0..c538391018 100644 --- a/panda/src/gobj/texture.cxx +++ b/panda/src/gobj/texture.cxx @@ -49,6 +49,14 @@ #include +using std::endl; +using std::istream; +using std::max; +using std::min; +using std::ostream; +using std::string; +using std::swap; + ConfigVariableEnum texture_quality_level ("texture-quality-level", Texture::QL_normal, PRC_DESC("This specifies a global quality level for all textures. You " @@ -546,7 +554,7 @@ read(const Filename &fullpath, const LoaderOptions &options) { cdata->inc_properties_modified(); cdata->inc_image_modified(); return do_read(cdata, fullpath, Filename(), 0, 0, 0, 0, false, false, - options, NULL); + options, nullptr); } /** @@ -566,7 +574,7 @@ read(const Filename &fullpath, const Filename &alpha_fullpath, cdata->inc_image_modified(); return do_read(cdata, fullpath, alpha_fullpath, primary_file_num_channels, alpha_file_channel, 0, 0, false, false, - options, NULL); + options, nullptr); } /** @@ -584,7 +592,7 @@ read(const Filename &fullpath, int z, int n, cdata->inc_properties_modified(); cdata->inc_image_modified(); return do_read(cdata, fullpath, Filename(), 0, 0, z, n, read_pages, read_mipmaps, - options, NULL); + options, nullptr); } /** @@ -817,7 +825,7 @@ get_aux_data(const string &key) const { if (di != _aux_data.end()) { return (*di).second; } - return NULL; + return nullptr; } /** @@ -850,30 +858,30 @@ make_from_txo(istream &in, const string &filename) { if (!din.open(in, filename)) { gobj_cat.error() << "Could not read texture object: " << filename << "\n"; - return NULL; + return nullptr; } string head; if (!din.read_header(head, _bam_header.size())) { gobj_cat.error() << filename << " is not a texture object file.\n"; - return NULL; + return nullptr; } if (head != _bam_header) { gobj_cat.error() << filename << " is not a texture object file.\n"; - return NULL; + return nullptr; } BamReader reader(&din); if (!reader.init()) { - return NULL; + return nullptr; } TypedWritable *object = reader.read_object(); - if (object != (TypedWritable *)NULL && + if (object != nullptr && object->is_exact_type(BamCacheRecord::get_class_type())) { // Here's a special case: if the first object in the file is a // BamCacheRecord, it's really a cache data file and not a true txo file; @@ -882,23 +890,23 @@ make_from_txo(istream &in, const string &filename) { object = reader.read_object(); } - if (object == (TypedWritable *)NULL) { + if (object == nullptr) { gobj_cat.error() << "Texture object " << filename << " is empty.\n"; - return NULL; + return nullptr; } else if (!object->is_of_type(Texture::get_class_type())) { gobj_cat.error() << "Texture object " << filename << " contains a " << object->get_type() << ", not a Texture.\n"; - return NULL; + return nullptr; } PT(Texture) other = DCAST(Texture, object); if (!reader.resolve()) { gobj_cat.error() << "Unable to fully resolve texture object file.\n"; - return NULL; + return nullptr; } return other; @@ -967,7 +975,7 @@ load_related(const InternalName *suffix) const { return (*ti).second; } if (cdata->_fullpath.empty()) { - return (Texture*)NULL; + return nullptr; } Filename main = cdata->_fullpath; main.set_basename_wo_extension(main.get_basename_wo_extension() + @@ -1216,7 +1224,7 @@ get_ram_mipmap_pointer(int n) const { if (n < (int)cdata->_ram_images.size()) { return cdata->_ram_images[n]._pointer_image; } - return NULL; + return nullptr; } /** @@ -1267,7 +1275,7 @@ clear_ram_mipmap_image(int n) { } cdata->_ram_images[n]._page_size = 0; cdata->_ram_images[n]._image.clear(); - cdata->_ram_images[n]._pointer_image = NULL; + cdata->_ram_images[n]._pointer_image = nullptr; } /** @@ -1277,7 +1285,7 @@ clear_ram_mipmap_image(int n) { PTA_uchar Texture:: modify_simple_ram_image() { CDWriter cdata(_cycler, true); - cdata->_simple_image_date_generated = (int32_t)time(NULL); + cdata->_simple_image_date_generated = (int32_t)time(nullptr); return cdata->_simple_ram_image._image; } @@ -1295,7 +1303,7 @@ new_simple_ram_image(int x_size, int y_size) { cdata->_simple_y_size = y_size; cdata->_simple_ram_image._image = PTA_uchar::empty_array(expected_page_size); cdata->_simple_ram_image._page_size = expected_page_size; - cdata->_simple_image_date_generated = (int32_t)time(NULL); + cdata->_simple_image_date_generated = (int32_t)time(nullptr); cdata->inc_simple_image_modified(); return cdata->_simple_ram_image._image; @@ -1381,7 +1389,7 @@ generate_simple_ram_image() { convert_from_pnmimage(image, expected_page_size, x_size, 0, 0, 0, scaled, 4, 1); do_set_simple_ram_image(cdata, image, x_size, y_size); - cdata->_simple_image_date_generated = (int32_t)time(NULL); + cdata->_simple_image_date_generated = (int32_t)time(nullptr); } /** @@ -1405,7 +1413,7 @@ peek() { return peeker; } - return NULL; + return nullptr; } /** @@ -1419,8 +1427,7 @@ peek() { */ PT(AsyncFuture) Texture:: prepare(PreparedGraphicsObjects *prepared_objects) { - PT(PreparedGraphicsObjects::EnqueuedObject) obj = prepared_objects->enqueue_texture_future(this); - return obj.p(); + return prepared_objects->enqueue_texture_future(this); } /** @@ -1567,7 +1574,7 @@ release(PreparedGraphicsObjects *prepared_objects) { Contexts::iterator ci; for (ci = temp.begin(); ci != temp.end(); ++ci) { TextureContext *tc = (*ci).second; - if (tc != (TextureContext *)NULL) { + if (tc != nullptr) { prepared_objects->release_texture(tc); } } @@ -1602,7 +1609,7 @@ release_all() { Contexts::iterator ci; for (ci = temp.begin(); ci != temp.end(); ++ci) { TextureContext *tc = (*ci).second; - if (tc != (TextureContext *)NULL) { + if (tc != nullptr) { prepared_objects->release_texture(tc); } } @@ -2706,7 +2713,7 @@ adjust_size(int &x_size, int &y_size, const string &name, if (max_dimension < 0) { GraphicsStateGuardianBase *gsg = GraphicsStateGuardianBase::get_default_gsg(); - if (gsg != (GraphicsStateGuardianBase *)NULL) { + if (gsg != nullptr) { max_dimension = gsg->get_max_texture_dimension(); } } @@ -2778,7 +2785,7 @@ do_read(CData *cdata, const Filename &fullpath, const Filename &alpha_fullpath, } bool header_only = ((options.get_texture_flags() & (LoaderOptions::TF_preload | LoaderOptions::TF_preload_simple)) == 0); - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { header_only = false; } @@ -2789,21 +2796,21 @@ do_read(CData *cdata, const Filename &fullpath, const Filename &alpha_fullpath, } if (is_txo_filename(fullpath)) { - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { record->add_dependent_file(fullpath); } return do_read_txo_file(cdata, fullpath); } if (is_dds_filename(fullpath)) { - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { record->add_dependent_file(fullpath); } return do_read_dds_file(cdata, fullpath, header_only); } if (is_ktx_filename(fullpath)) { - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { record->add_dependent_file(fullpath); } return do_read_ktx_file(cdata, fullpath, header_only); @@ -3013,15 +3020,15 @@ bool Texture:: do_read_one(CData *cdata, const Filename &fullpath, const Filename &alpha_fullpath, int z, int n, int primary_file_num_channels, int alpha_file_channel, const LoaderOptions &options, bool header_only, BamCacheRecord *record) { - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { nassertr(!header_only, false); record->add_dependent_file(fullpath); } PNMImage image; PfmFile pfm; - PNMReader *image_reader = image.make_reader(fullpath, NULL, false); - if (image_reader == NULL) { + PNMReader *image_reader = image.make_reader(fullpath, nullptr, false); + if (image_reader == nullptr) { gobj_cat.error() << "Texture::read() - couldn't read: " << fullpath << endl; return false; @@ -3125,15 +3132,15 @@ do_read_one(CData *cdata, const Filename &fullpath, const Filename &alpha_fullpa PNMImage alpha_image; if (!alpha_fullpath.empty()) { - PNMReader *alpha_image_reader = alpha_image.make_reader(alpha_fullpath, NULL, false); - if (alpha_image_reader == NULL) { + PNMReader *alpha_image_reader = alpha_image.make_reader(alpha_fullpath, nullptr, false); + if (alpha_image_reader == nullptr) { gobj_cat.error() << "Texture::read() - couldn't read: " << alpha_fullpath << endl; return false; } alpha_image.copy_header_from(*alpha_image_reader); - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { record->add_dependent_file(alpha_fullpath); } @@ -3468,7 +3475,7 @@ do_read_txo_file(CData *cdata, const Filename &fullpath) { Filename filename = Filename::binary_filename(fullpath); PT(VirtualFile) file = vfs->get_file(filename); - if (file == (VirtualFile *)NULL) { + if (file == nullptr) { // No such file. gobj_cat.error() << "Could not find " << fullpath << "\n"; @@ -3497,7 +3504,7 @@ do_read_txo_file(CData *cdata, const Filename &fullpath) { bool Texture:: do_read_txo(CData *cdata, istream &in, const string &filename) { PT(Texture) other = make_from_txo(in, filename); - if (other == (Texture *)NULL) { + if (other == nullptr) { return false; } @@ -3523,7 +3530,7 @@ do_read_dds_file(CData *cdata, const Filename &fullpath, bool header_only) { Filename filename = Filename::binary_filename(fullpath); PT(VirtualFile) file = vfs->get_file(filename); - if (file == (VirtualFile *)NULL) { + if (file == nullptr) { // No such file. gobj_cat.error() << "Could not find " << fullpath << "\n"; @@ -3632,7 +3639,7 @@ do_read_dds(CData *cdata, istream &in, const string &filename, bool header_only) // Determine the function to use to read the DDS image. typedef PTA_uchar (*ReadDDSLevelFunc)(Texture *tex, Texture::CData *cdata, const DDSHeader &header, int n, istream &in); - ReadDDSLevelFunc func = NULL; + ReadDDSLevelFunc func = nullptr; Format format = F_rgb; ComponentType component_type = T_unsigned_byte; @@ -3960,7 +3967,7 @@ do_read_dds(CData *cdata, istream &in, const string &filename, bool header_only) default: gobj_cat.error() << filename << ": unsupported texture compression (FourCC: 0x" - << hex << header.pf.four_cc << dec << ").\n"; + << std::hex << header.pf.four_cc << std::dec << ").\n"; return false; } @@ -4173,7 +4180,7 @@ do_read_ktx_file(CData *cdata, const Filename &fullpath, bool header_only) { Filename filename = Filename::binary_filename(fullpath); PT(VirtualFile) file = vfs->get_file(filename); - if (file == (VirtualFile *)NULL) { + if (file == nullptr) { // No such file. gobj_cat.error() << "Could not find " << fullpath << "\n"; @@ -4216,7 +4223,7 @@ do_read_ktx(CData *cdata, istream &in, const string &filename, bool header_only) } // See: https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/ - uint32_t gl_type, type_size, gl_format, internal_format, gl_base_format, + uint32_t gl_type, /*type_size,*/ gl_format, internal_format, gl_base_format, width, height, depth, num_array_elements, num_faces, num_mipmap_levels, kvdata_size; @@ -4224,7 +4231,7 @@ do_read_ktx(CData *cdata, istream &in, const string &filename, bool header_only) if (ktx.get_uint32() == 0x04030201) { big_endian = false; gl_type = ktx.get_uint32(); - type_size = ktx.get_uint32(); + /*type_size = */ktx.get_uint32(); gl_format = ktx.get_uint32(); internal_format = ktx.get_uint32(); gl_base_format = ktx.get_uint32(); @@ -4238,7 +4245,7 @@ do_read_ktx(CData *cdata, istream &in, const string &filename, bool header_only) } else { big_endian = true; gl_type = ktx.get_be_uint32(); - type_size = ktx.get_be_uint32(); + /*type_size = */ktx.get_be_uint32(); gl_format = ktx.get_be_uint32(); internal_format = ktx.get_be_uint32(); gl_base_format = ktx.get_be_uint32(); @@ -4432,8 +4439,8 @@ do_read_ktx(CData *cdata, istream &in, const string &filename, bool header_only) if (base_format != gl_base_format) { gobj_cat.error() << filename << " has internal format that is incompatible with base " - "format (0x" << hex << gl_base_format << ", expected 0x" - << base_format << dec << ")\n"; + "format (0x" << std::hex << gl_base_format << ", expected 0x" + << base_format << std::dec << ")\n"; return false; } @@ -4895,14 +4902,14 @@ do_read_ktx(CData *cdata, istream &in, const string &filename, bool header_only) } } - do_set_ram_mipmap_image(cdata, (int)n, MOVE(image), + do_set_ram_mipmap_image(cdata, (int)n, std::move(image), row_size * do_get_expected_mipmap_y_size(cdata, (int)n)); } else { // Compressed image. We'll trust that the file has the right size. image = PTA_uchar::empty_array(image_size); ktx.extract_bytes(image.p(), image_size); - do_set_ram_mipmap_image(cdata, (int)n, MOVE(image), image_size / depth); + do_set_ram_mipmap_image(cdata, (int)n, std::move(image), image_size / depth); } ktx.skip_bytes(3 - ((image_size + 3) & 3)); @@ -5144,7 +5151,7 @@ do_write_txo_file(const CData *cdata, const Filename &fullpath) const { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); Filename filename = Filename::binary_filename(fullpath); ostream *out = vfs->open_write_file(filename, true, true); - if (out == NULL) { + if (out == nullptr) { gobj_cat.error() << "Unable to open " << filename << "\n"; return false; @@ -5234,19 +5241,19 @@ unlocked_ensure_ram_image(bool allow_compression) { } // We need to reload. - nassertr(!_reloading, NULL); + nassertr(!_reloading, nullptr); _reloading = true; PT(Texture) tex = do_make_copy(cdata); _cycler.release_read(cdata); - _lock.release(); + _lock.unlock(); // Perform the actual reload in a copy of the texture, while our own mutex // is left unlocked. CDWriter cdata_tex(tex->_cycler, true); tex->do_reload_ram_image(cdata_tex, allow_compression); - _lock.acquire(); + _lock.lock(); CData *cdataw = _cycler.write_upstream(false, current_thread); @@ -5288,7 +5295,7 @@ unlocked_ensure_ram_image(bool allow_compression) { cdataw->_ram_image_compression = cdata_tex->_ram_image_compression; cdataw->_ram_images = cdata_tex->_ram_images; - nassertr(_reloading, NULL); + nassertr(_reloading, nullptr); _reloading = false; // We don't generally increment the cdata->_image_modified semaphore, @@ -5322,7 +5329,7 @@ do_reload_ram_image(CData *cdata, bool allow_compression) { // See if the texture can be found in the on-disk cache, if it is active. record = cache->lookup(cdata->_fullpath, "txo"); - if (record != (BamCacheRecord *)NULL && + if (record != nullptr && record->has_data()) { PT(Texture) tex = DCAST(Texture, record->get_data()); @@ -5413,7 +5420,7 @@ do_reload_ram_image(CData *cdata, bool allow_compression) { } do_read(cdata, cdata->_fullpath, cdata->_alpha_fullpath, cdata->_primary_file_num_channels, cdata->_alpha_file_channel, - z, n, cdata->_has_read_pages, cdata->_has_read_mipmaps, options, NULL); + z, n, cdata->_has_read_pages, cdata->_has_read_mipmaps, options, nullptr); if (orig_num_components == cdata->_num_components) { // Restore the original format, in case it was needlessly changed during @@ -5421,10 +5428,10 @@ do_reload_ram_image(CData *cdata, bool allow_compression) { cdata->_format = orig_format; } - if (do_has_ram_image(cdata) && record != (BamCacheRecord *)NULL) { + if (do_has_ram_image(cdata) && record != nullptr) { if (cache->get_cache_textures() || (cdata->_ram_image_compression != CM_off && cache->get_cache_compressed_textures())) { // Update the cache. - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { record->add_dependent_file(cdata->_fullpath); } record->set_data(this, this); @@ -5459,7 +5466,7 @@ do_make_ram_image(CData *cdata) { cdata->_ram_images.push_back(RamImage()); cdata->_ram_images[0]._page_size = do_get_expected_ram_page_size(cdata); cdata->_ram_images[0]._image = PTA_uchar::empty_array(image_size, get_class_type()); - cdata->_ram_images[0]._pointer_image = NULL; + cdata->_ram_images[0]._pointer_image = nullptr; cdata->_ram_image_compression = CM_off; if (cdata->_has_clear_color) { @@ -5502,7 +5509,7 @@ do_set_ram_image(CData *cdata, CPTA_uchar image, Texture::CompressionMode compre cdata->_ram_image_compression != compression) { cdata->_ram_images[0]._image = image.cast_non_const(); cdata->_ram_images[0]._page_size = page_size; - cdata->_ram_images[0]._pointer_image = NULL; + cdata->_ram_images[0]._pointer_image = nullptr; cdata->_ram_image_compression = compression; cdata->inc_image_modified(); } @@ -5536,7 +5543,7 @@ do_make_ram_mipmap_image(CData *cdata, int n) { size_t image_size = do_get_expected_ram_mipmap_image_size(cdata, n); cdata->_ram_images[n]._image = PTA_uchar::empty_array(image_size, get_class_type()); - cdata->_ram_images[n]._pointer_image = NULL; + cdata->_ram_images[n]._pointer_image = nullptr; cdata->_ram_images[n]._page_size = do_get_expected_ram_mipmap_page_size(cdata, n); if (cdata->_has_clear_color) { @@ -5571,7 +5578,7 @@ do_set_ram_mipmap_image(CData *cdata, int n, CPTA_uchar image, size_t page_size) if (cdata->_ram_images[n]._image != image || cdata->_ram_images[n]._page_size != page_size) { cdata->_ram_images[n]._image = image.cast_non_const(); - cdata->_ram_images[n]._pointer_image = NULL; + cdata->_ram_images[n]._pointer_image = nullptr; cdata->_ram_images[n]._page_size = page_size; cdata->inc_image_modified(); } @@ -5841,7 +5848,7 @@ do_compress_ram_image(CData *cdata, Texture::CompressionMode compression, case Texture::F_rgb16: case Texture::F_rgb32: case Texture::F_rgb10_a2: - if (gsg == NULL || gsg->get_supports_compressed_texture_format(CM_dxt1)) { + if (gsg == nullptr || gsg->get_supports_compressed_texture_format(CM_dxt1)) { compression = CM_dxt1; } else if (gsg->get_supports_compressed_texture_format(CM_dxt3)) { compression = CM_dxt3; @@ -5855,7 +5862,7 @@ do_compress_ram_image(CData *cdata, Texture::CompressionMode compression, break; case Texture::F_rgba4: - if (gsg == NULL || gsg->get_supports_compressed_texture_format(CM_dxt3)) { + if (gsg == nullptr || gsg->get_supports_compressed_texture_format(CM_dxt3)) { compression = CM_dxt3; } else if (gsg->get_supports_compressed_texture_format(CM_dxt5)) { compression = CM_dxt5; @@ -5869,7 +5876,7 @@ do_compress_ram_image(CData *cdata, Texture::CompressionMode compression, case Texture::F_rgba12: case Texture::F_rgba16: case Texture::F_rgba32: - if (gsg == NULL || gsg->get_supports_compressed_texture_format(CM_dxt5)) { + if (gsg == nullptr || gsg->get_supports_compressed_texture_format(CM_dxt5)) { compression = CM_dxt5; } else if (gsg->get_supports_compressed_texture_format(CM_etc2)) { compression = CM_etc2; @@ -5878,7 +5885,7 @@ do_compress_ram_image(CData *cdata, Texture::CompressionMode compression, case Texture::F_red: case Texture::F_rg: - if (gsg == NULL || gsg->get_supports_compressed_texture_format(CM_rgtc)) { + if (gsg == nullptr || gsg->get_supports_compressed_texture_format(CM_rgtc)) { compression = CM_rgtc; } else if (gsg->get_supports_compressed_texture_format(CM_eac)) { compression = CM_eac; @@ -7289,7 +7296,7 @@ get_ram_image_as(const string &requested_format) { // Make sure we can grab something that's uncompressed. CPTA_uchar data = do_get_uncompressed_ram_image(cdata); - if (data == NULL) { + if (data == nullptr) { gobj_cat.error() << "Couldn't find an uncompressed RAM image!\n"; return CPTA_uchar(get_class_type()); } @@ -7495,7 +7502,7 @@ do_set_simple_ram_image(CData *cdata, CPTA_uchar image, int x_size, int y_size) cdata->_simple_y_size = y_size; cdata->_simple_ram_image._image = image.cast_non_const(); cdata->_simple_ram_image._page_size = image.size(); - cdata->_simple_image_date_generated = (int32_t)time(NULL); + cdata->_simple_image_date_generated = (int32_t)time(nullptr); cdata->inc_simple_image_modified(); } @@ -7697,7 +7704,7 @@ do_generate_ram_mipmap_images(CData *cdata, bool allow_recompress) { RamImage uncompressed_image = cdata->_ram_images[0]; cdata->_ram_images.erase(cdata->_ram_images.begin()); - bool success = do_compress_ram_image(cdata, orig_compression_mode, QL_default, NULL); + bool success = do_compress_ram_image(cdata, orig_compression_mode, QL_default, nullptr); // Now restore the toplevel image. if (success) { if (gobj_cat.is_debug()) { @@ -10159,7 +10166,7 @@ make_this_from_bam(const FactoryParams ¶ms) { has_read_mipmaps = scan.get_bool(); } - Texture *me = NULL; + Texture *me = nullptr; if (has_rawdata) { // If the raw image data is included, then just load the texture directly // from the stream, and return it. In this case we return the "this" @@ -10252,7 +10259,7 @@ make_this_from_bam(const FactoryParams ¶ms) { } } - if (me != (Texture *)NULL) { + if (me != nullptr) { me->set_name(name); CDWriter cdata_me(me->_cycler, true); me->do_fillin_from(cdata_me, dummy); diff --git a/panda/src/gobj/texture.h b/panda/src/gobj/texture.h index 890710a216..852f618c81 100644 --- a/panda/src/gobj/texture.h +++ b/panda/src/gobj/texture.h @@ -222,7 +222,7 @@ PUBLISHED: }; PUBLISHED: - explicit Texture(const string &name = string()); + explicit Texture(const std::string &name = std::string()); protected: Texture(const Texture ©); @@ -279,18 +279,18 @@ PUBLISHED: BLOCKING bool read(const Filename &fullpath, const Filename &alpha_fullpath, int primary_file_num_channels, int alpha_file_channel, int z, int n, bool read_pages, bool read_mipmaps, - BamCacheRecord *record = NULL, + BamCacheRecord *record = nullptr, const LoaderOptions &options = LoaderOptions()); BLOCKING INLINE bool write(const Filename &fullpath); BLOCKING INLINE bool write(const Filename &fullpath, int z, int n, bool write_pages, bool write_mipmaps); - BLOCKING bool read_txo(istream &in, const string &filename = ""); - BLOCKING static PT(Texture) make_from_txo(istream &in, const string &filename = ""); - BLOCKING bool write_txo(ostream &out, const string &filename = "") const; - BLOCKING bool read_dds(istream &in, const string &filename = "", bool header_only = false); - BLOCKING bool read_ktx(istream &in, const string &filename = "", bool header_only = false); + BLOCKING bool read_txo(std::istream &in, const std::string &filename = ""); + BLOCKING static PT(Texture) make_from_txo(std::istream &in, const std::string &filename = ""); + BLOCKING bool write_txo(std::ostream &out, const std::string &filename = "") const; + BLOCKING bool read_dds(std::istream &in, const std::string &filename = "", bool header_only = false); + BLOCKING bool read_ktx(std::istream &in, const std::string &filename = "", bool header_only = false); BLOCKING INLINE bool load(const PNMImage &pnmimage, const LoaderOptions &options = LoaderOptions()); BLOCKING INLINE bool load(const PNMImage &pnmimage, int z, int n, const LoaderOptions &options = LoaderOptions()); @@ -443,17 +443,17 @@ PUBLISHED: INLINE CPTA_uchar get_ram_image(); INLINE CompressionMode get_ram_image_compression() const; INLINE CPTA_uchar get_uncompressed_ram_image(); - CPTA_uchar get_ram_image_as(const string &requested_format); + CPTA_uchar get_ram_image_as(const std::string &requested_format); INLINE PTA_uchar modify_ram_image(); INLINE PTA_uchar make_ram_image(); #ifndef CPPPARSER INLINE void set_ram_image(CPTA_uchar image, CompressionMode compression = CM_off, size_t page_size = 0); - void set_ram_image_as(CPTA_uchar image, const string &provided_format); + void set_ram_image_as(CPTA_uchar image, const std::string &provided_format); #else EXTEND void set_ram_image(PyObject *image, CompressionMode compression = CM_off, size_t page_size = 0); - EXTEND void set_ram_image_as(PyObject *image, const string &provided_format); + EXTEND void set_ram_image_as(PyObject *image, const std::string &provided_format); #endif INLINE void clear_ram_image(); INLINE void set_keep_ram_image(bool keep_ram_image); @@ -466,7 +466,7 @@ PUBLISHED: BLOCKING INLINE bool compress_ram_image(CompressionMode compression = CM_on, QualityLevel quality_level = QL_default, - GraphicsStateGuardianBase *gsg = NULL); + GraphicsStateGuardianBase *gsg = nullptr); BLOCKING INLINE bool uncompress_ram_image(); INLINE int get_num_ram_mipmap_images() const; @@ -533,13 +533,13 @@ PUBLISHED: bool release(PreparedGraphicsObjects *prepared_objects); int release_all(); - void write(ostream &out, int indent_level) const; + void write(std::ostream &out, int indent_level) const; size_t estimate_texture_memory() const; - void set_aux_data(const string &key, TypedReferenceCount *aux_data); - void clear_aux_data(const string &key); - TypedReferenceCount *get_aux_data(const string &key) const; + void set_aux_data(const std::string &key, TypedReferenceCount *aux_data); + void clear_aux_data(const std::string &key); + TypedReferenceCount *get_aux_data(const std::string &key) const; MAKE_MAP_PROPERTY(aux_data, get_aux_data, get_aux_data, set_aux_data, clear_aux_data); @@ -593,23 +593,23 @@ PUBLISHED: static int down_to_power_2(int value); void consider_rescale(PNMImage &pnmimage); - static void consider_rescale(PNMImage &pnmimage, const string &name, AutoTextureScale auto_texture_scale = ATS_unspecified); + static void consider_rescale(PNMImage &pnmimage, const std::string &name, AutoTextureScale auto_texture_scale = ATS_unspecified); INLINE bool rescale_texture(); - static string format_texture_type(TextureType tt); - static TextureType string_texture_type(const string &str); + static std::string format_texture_type(TextureType tt); + static TextureType string_texture_type(const std::string &str); - static string format_component_type(ComponentType ct); - static ComponentType string_component_type(const string &str); + static std::string format_component_type(ComponentType ct); + static ComponentType string_component_type(const std::string &str); - static string format_format(Format f); - static Format string_format(const string &str); + static std::string format_format(Format f); + static Format string_format(const std::string &str); - static string format_compression_mode(CompressionMode cm); - static CompressionMode string_compression_mode(const string &str); + static std::string format_compression_mode(CompressionMode cm); + static CompressionMode string_compression_mode(const std::string &str); - static string format_quality_level(QualityLevel tql); - static QualityLevel string_quality_level(const string &str); + static std::string format_quality_level(QualityLevel tql); + static QualityLevel string_quality_level(const std::string &str); public: void texture_uploaded(); @@ -626,9 +626,9 @@ public: static bool has_binary_alpha(Format format); static bool is_srgb(Format format); - static bool adjust_size(int &x_size, int &y_size, const string &name, + static bool adjust_size(int &x_size, int &y_size, const std::string &name, bool for_padding, AutoTextureScale auto_texture_scale = ATS_unspecified); - INLINE bool adjust_this_size(int &x_size, int &y_size, const string &name, + INLINE bool adjust_this_size(int &x_size, int &y_size, const std::string &name, bool for_padding) const; virtual void ensure_loader_type(const Filename &filename); @@ -647,7 +647,7 @@ protected: // pointer representing that lock); generally, they also avoid adjusting the // _properties_modified and _image_modified semaphores. virtual bool do_adjust_this_size(const CData *cdata, - int &x_size, int &y_size, const string &name, + int &x_size, int &y_size, const std::string &name, bool for_padding) const; virtual bool do_read(CData *cdata, @@ -661,19 +661,19 @@ protected: const LoaderOptions &options, bool header_only, BamCacheRecord *record); virtual bool do_load_one(CData *cdata, - const PNMImage &pnmimage, const string &name, + const PNMImage &pnmimage, const std::string &name, int z, int n, const LoaderOptions &options); virtual bool do_load_one(CData *cdata, - const PfmFile &pfm, const string &name, + const PfmFile &pfm, const std::string &name, int z, int n, const LoaderOptions &options); virtual bool do_load_sub_image(CData *cdata, const PNMImage &image, int x, int y, int z, int n); bool do_read_txo_file(CData *cdata, const Filename &fullpath); - bool do_read_txo(CData *cdata, istream &in, const string &filename); + bool do_read_txo(CData *cdata, std::istream &in, const std::string &filename); bool do_read_dds_file(CData *cdata, const Filename &fullpath, bool header_only); - bool do_read_dds(CData *cdata, istream &in, const string &filename, bool header_only); + bool do_read_dds(CData *cdata, std::istream &in, const std::string &filename, bool header_only); bool do_read_ktx_file(CData *cdata, const Filename &fullpath, bool header_only); - bool do_read_ktx(CData *cdata, istream &in, const string &filename, bool header_only); + bool do_read_ktx(CData *cdata, std::istream &in, const std::string &filename, bool header_only); bool do_write(CData *cdata, const Filename &fullpath, int z, int n, bool write_pages, bool write_mipmaps); @@ -681,7 +681,7 @@ protected: bool do_store_one(CData *cdata, PNMImage &pnmimage, int z, int n); bool do_store_one(CData *cdata, PfmFile &pfm, int z, int n); bool do_write_txo_file(const CData *cdata, const Filename &fullpath) const; - bool do_write_txo(const CData *cdata, ostream &out, const string &filename) const; + bool do_write_txo(const CData *cdata, std::ostream &out, const std::string &filename) const; virtual CData *unlocked_ensure_ram_image(bool allow_compression); virtual void do_reload_ram_image(CData *cdata, bool allow_compression); @@ -810,44 +810,44 @@ private: CPTA_uchar image, size_t page_size, int z); static PTA_uchar read_dds_level_bgr8(Texture *tex, CData *cdata, const DDSHeader &header, - int n, istream &in); + int n, std::istream &in); static PTA_uchar read_dds_level_rgb8(Texture *tex, CData *cdata, const DDSHeader &header, - int n, istream &in); + int n, std::istream &in); static PTA_uchar read_dds_level_abgr8(Texture *tex, CData *cdata, const DDSHeader &header, - int n, istream &in); + int n, std::istream &in); static PTA_uchar read_dds_level_rgba8(Texture *tex, CData *cdata, const DDSHeader &header, - int n, istream &in); + int n, std::istream &in); static PTA_uchar read_dds_level_abgr16(Texture *tex, CData *cdata, const DDSHeader &header, - int n, istream &in); + int n, std::istream &in); static PTA_uchar read_dds_level_abgr32(Texture *tex, CData *cdata, const DDSHeader &header, - int n, istream &in); + int n, std::istream &in); static PTA_uchar read_dds_level_raw(Texture *tex, CData *cdata, const DDSHeader &header, - int n, istream &in); + int n, std::istream &in); static PTA_uchar read_dds_level_generic_uncompressed(Texture *tex, CData *cdata, const DDSHeader &header, - int n, istream &in); + int n, std::istream &in); static PTA_uchar read_dds_level_luminance_uncompressed(Texture *tex, CData *cdata, const DDSHeader &header, - int n, istream &in); + int n, std::istream &in); static PTA_uchar read_dds_level_bc1(Texture *tex, CData *cdata, const DDSHeader &header, - int n, istream &in); + int n, std::istream &in); static PTA_uchar read_dds_level_bc2(Texture *tex, CData *cdata, const DDSHeader &header, - int n, istream &in); + int n, std::istream &in); static PTA_uchar read_dds_level_bc3(Texture *tex, CData *cdata, const DDSHeader &header, - int n, istream &in); + int n, std::istream &in); static PTA_uchar read_dds_level_bc4(Texture *tex, CData *cdata, const DDSHeader &header, - int n, istream &in); + int n, std::istream &in); static PTA_uchar read_dds_level_bc5(Texture *tex, CData *cdata, const DDSHeader &header, - int n, istream &in); + int n, std::istream &in); void clear_prepared(int view, PreparedGraphicsObjects *prepared_objects); - static void consider_downgrade(PNMImage &pnmimage, int num_channels, const string &name); + static void consider_downgrade(PNMImage &pnmimage, int num_channels, const std::string &name); static bool compare_images(const PNMImage &a, const PNMImage &b); @@ -1058,7 +1058,7 @@ protected: private: // The auxiliary data is not recorded to a bam file. - typedef pmap AuxData; + typedef pmap AuxData; AuxData _aux_data; static AutoTextureScale _textures_power_2; @@ -1108,13 +1108,13 @@ private: extern EXPCL_PANDA_GOBJ ConfigVariableEnum texture_quality_level; -EXPCL_PANDA_GOBJ ostream &operator << (ostream &out, Texture::TextureType tt); -EXPCL_PANDA_GOBJ ostream &operator << (ostream &out, Texture::ComponentType ct); -EXPCL_PANDA_GOBJ ostream &operator << (ostream &out, Texture::Format f); +EXPCL_PANDA_GOBJ std::ostream &operator << (std::ostream &out, Texture::TextureType tt); +EXPCL_PANDA_GOBJ std::ostream &operator << (std::ostream &out, Texture::ComponentType ct); +EXPCL_PANDA_GOBJ std::ostream &operator << (std::ostream &out, Texture::Format f); -EXPCL_PANDA_GOBJ ostream &operator << (ostream &out, Texture::CompressionMode cm); -EXPCL_PANDA_GOBJ ostream &operator << (ostream &out, Texture::QualityLevel tql); -EXPCL_PANDA_GOBJ istream &operator >> (istream &in, Texture::QualityLevel &tql); +EXPCL_PANDA_GOBJ std::ostream &operator << (std::ostream &out, Texture::CompressionMode cm); +EXPCL_PANDA_GOBJ std::ostream &operator << (std::ostream &out, Texture::QualityLevel tql); +EXPCL_PANDA_GOBJ std::istream &operator >> (std::istream &in, Texture::QualityLevel &tql); #include "texture.I" diff --git a/panda/src/gobj/textureCollection.cxx b/panda/src/gobj/textureCollection.cxx index ce2eee4519..57f91a8ef8 100644 --- a/panda/src/gobj/textureCollection.cxx +++ b/panda/src/gobj/textureCollection.cxx @@ -181,7 +181,7 @@ reserve(size_t num) { * NULL if no texture has that name. */ Texture *TextureCollection:: -find_texture(const string &name) const { +find_texture(const std::string &name) const { int num_textures = get_num_textures(); for (int i = 0; i < num_textures; i++) { Texture *texture = get_texture(i); @@ -189,7 +189,7 @@ find_texture(const string &name) const { return texture; } } - return NULL; + return nullptr; } /** @@ -205,7 +205,7 @@ get_num_textures() const { */ Texture *TextureCollection:: get_texture(int index) const { - nassertr(index >= 0 && index < (int)_textures.size(), NULL); + nassertr(index >= 0 && index < (int)_textures.size(), nullptr); return _textures[index]; } @@ -216,7 +216,7 @@ get_texture(int index) const { */ Texture *TextureCollection:: operator [] (int index) const { - nassertr(index >= 0 && index < (int)_textures.size(), NULL); + nassertr(index >= 0 && index < (int)_textures.size(), nullptr); return _textures[index]; } @@ -235,7 +235,7 @@ size() const { * indicated output stream. */ void TextureCollection:: -output(ostream &out) const { +output(std::ostream &out) const { if (get_num_textures() == 1) { out << "1 Texture"; } else { @@ -248,7 +248,7 @@ output(ostream &out) const { * indicated output stream. */ void TextureCollection:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { for (int i = 0; i < get_num_textures(); i++) { indent(out, indent_level) << *get_texture(i) << "\n"; } diff --git a/panda/src/gobj/textureCollection.h b/panda/src/gobj/textureCollection.h index 4cf0872708..5250d94a17 100644 --- a/panda/src/gobj/textureCollection.h +++ b/panda/src/gobj/textureCollection.h @@ -43,7 +43,7 @@ PUBLISHED: void clear(); void reserve(size_t num); - Texture *find_texture(const string &name) const; + Texture *find_texture(const std::string &name) const; int get_num_textures() const; Texture *get_texture(int index) const; @@ -57,15 +57,15 @@ PUBLISHED: INLINE void append(Texture *texture); INLINE void extend(const TextureCollection &other); - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; private: typedef PTA(PT(Texture)) Textures; Textures _textures; }; -INLINE ostream &operator << (ostream &out, const TextureCollection &col) { +INLINE std::ostream &operator << (std::ostream &out, const TextureCollection &col) { col.output(out); return out; } diff --git a/panda/src/gobj/textureCollection_ext.cxx b/panda/src/gobj/textureCollection_ext.cxx index de104e775c..127bba9ac5 100644 --- a/panda/src/gobj/textureCollection_ext.cxx +++ b/panda/src/gobj/textureCollection_ext.cxx @@ -27,7 +27,7 @@ extern struct Dtool_PyTypedObject Dtool_Texture; void Extension:: __init__(PyObject *self, PyObject *sequence) { PyObject *fast = PySequence_Fast(sequence, "TextureCollection constructor requires a sequence"); - if (fast == NULL) { + if (fast == nullptr) { return; } @@ -36,17 +36,17 @@ __init__(PyObject *self, PyObject *sequence) { for (int i = 0; i < size; ++i) { PyObject *item = PySequence_Fast_GET_ITEM(fast, i); - if (item == NULL) { + if (item == nullptr) { return; } Texture *tex; DTOOL_Call_ExtractThisPointerForType(item, &Dtool_Texture, (void **)&tex); - if (tex == (Texture *)NULL) { + if (tex == nullptr) { // Unable to add item--probably it wasn't of the appropriate type. - ostringstream stream; + std::ostringstream stream; stream << "Element " << i << " in sequence passed to TextureCollection constructor is not a Texture"; - string str = stream.str(); + std::string str = stream.str(); PyErr_SetString(PyExc_TypeError, str.c_str()); Py_DECREF(fast); return; @@ -72,8 +72,8 @@ __reduce__(PyObject *self) const { // necessary to reconstruct this object. PyObject *this_class = PyObject_Type(self); - if (this_class == NULL) { - return NULL; + if (this_class == nullptr) { + return nullptr; } // Since a TextureCollection is itself an iterator, we can simply pass it as diff --git a/panda/src/gobj/textureContext.I b/panda/src/gobj/textureContext.I index b5d3712ad8..fa947755d0 100644 --- a/panda/src/gobj/textureContext.I +++ b/panda/src/gobj/textureContext.I @@ -123,7 +123,7 @@ mark_loaded() { // _data_size_bytes = _data->get_texture_size_bytes(); _properties_modified = _texture->get_properties_modified(); _image_modified = _texture->get_image_modified(); - update_modified(max(_properties_modified, _image_modified)); + update_modified(std::max(_properties_modified, _image_modified)); // Assume the texture is now resident. set_resident(true); @@ -137,7 +137,7 @@ INLINE void TextureContext:: mark_simple_loaded() { _properties_modified = _texture->get_properties_modified(); _simple_image_modified = _texture->get_simple_image_modified(); - update_modified(max(_properties_modified, _simple_image_modified)); + update_modified(std::max(_properties_modified, _simple_image_modified)); // The texture's not exactly resident now, but some part of it is. set_resident(true); diff --git a/panda/src/gobj/textureContext.cxx b/panda/src/gobj/textureContext.cxx index 32224a7bde..7a83a17a01 100644 --- a/panda/src/gobj/textureContext.cxx +++ b/panda/src/gobj/textureContext.cxx @@ -40,7 +40,7 @@ get_native_buffer_id() const { * */ void TextureContext:: -output(ostream &out) const { +output(std::ostream &out) const { out << *get_texture() << ", " << get_data_size_bytes(); } @@ -48,6 +48,6 @@ output(ostream &out) const { * */ void TextureContext:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { SavedContext::write(out, indent_level); } diff --git a/panda/src/gobj/textureContext.h b/panda/src/gobj/textureContext.h index 813cd37dd9..c7ae367ccc 100644 --- a/panda/src/gobj/textureContext.h +++ b/panda/src/gobj/textureContext.h @@ -56,8 +56,8 @@ public: INLINE void mark_unloaded(); INLINE void mark_needs_reload(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; private: // This cannot be a PT(Texture), because the texture and the GSG both own @@ -88,7 +88,7 @@ private: friend class PreparedGraphicsObjects; }; -inline ostream &operator << (ostream &out, const TextureContext &context) { +inline std::ostream &operator << (std::ostream &out, const TextureContext &context) { context.output(out); return out; } diff --git a/panda/src/gobj/texturePeeker.cxx b/panda/src/gobj/texturePeeker.cxx index b4e1be9224..ef007d91dd 100644 --- a/panda/src/gobj/texturePeeker.cxx +++ b/panda/src/gobj/texturePeeker.cxx @@ -108,6 +108,8 @@ TexturePeeker(Texture *tex, Texture::CData *cdata) { case Texture::F_depth_component32: case Texture::F_red: case Texture::F_r16: + case Texture::F_r32: + case Texture::F_r32i: _get_texel = get_texel_r; break; @@ -178,7 +180,7 @@ TexturePeeker(Texture *tex, Texture::CData *cdata) { default: // Not supported. gobj_cat.error() << "Unsupported texture peeker format: " - << Texture::format_format(_format) << endl; + << Texture::format_format(_format) << std::endl; _image.clear(); return; } diff --git a/panda/src/gobj/texturePool.I b/panda/src/gobj/texturePool.I index 499ab04a83..6ff48f14d3 100644 --- a/panda/src/gobj/texturePool.I +++ b/panda/src/gobj/texturePool.I @@ -30,7 +30,7 @@ has_texture(const Filename &filename) { */ INLINE bool TexturePool:: verify_texture(const Filename &filename) { - return load_texture(filename) != (Texture *)NULL; + return load_texture(filename) != nullptr; } /** @@ -200,7 +200,7 @@ garbage_collect() { * Lists the contents of the texture pool to the indicated output stream. */ INLINE void TexturePool:: -list_contents(ostream &out) { +list_contents(std::ostream &out) { get_global_ptr()->ns_list_contents(out); } @@ -209,7 +209,7 @@ list_contents(ostream &out) { */ INLINE void TexturePool:: list_contents() { - get_global_ptr()->ns_list_contents(cout); + get_global_ptr()->ns_list_contents(std::cout); } /** @@ -218,7 +218,7 @@ list_contents() { * if it is not. */ INLINE Texture *TexturePool:: -find_texture(const string &name) { +find_texture(const std::string &name) { return get_global_ptr()->ns_find_texture(name); } @@ -227,7 +227,7 @@ find_texture(const string &name) { * name (which may contain wildcards). */ INLINE TextureCollection TexturePool:: -find_all_textures(const string &name) { +find_all_textures(const std::string &name) { return get_global_ptr()->ns_find_all_textures(name); } @@ -245,7 +245,7 @@ set_fake_texture_image(const Filename &filename) { */ INLINE void TexturePool:: clear_fake_texture_image() { - set_fake_texture_image(string()); + set_fake_texture_image(std::string()); } /** @@ -272,6 +272,6 @@ get_fake_texture_image() { * register_texture_type(). */ PT(Texture) TexturePool:: -make_texture(const string &extension) { +make_texture(const std::string &extension) { return get_global_ptr()->ns_make_texture(extension); } diff --git a/panda/src/gobj/texturePool.cxx b/panda/src/gobj/texturePool.cxx index 6b4c0a5168..d62b68b377 100644 --- a/panda/src/gobj/texturePool.cxx +++ b/panda/src/gobj/texturePool.cxx @@ -28,6 +28,10 @@ #include "mutexHolder.h" #include "dcast.h" +using std::istream; +using std::ostream; +using std::string; + TexturePool *TexturePool::_global_ptr; /** @@ -90,14 +94,14 @@ get_texture_type(const string &extension) const { // Check the PNM type registry. PNMFileTypeRegistry *pnm_reg = PNMFileTypeRegistry::get_global_ptr(); PNMFileType *type = pnm_reg->get_type_from_extension(c); - if (type != (PNMFileType *)NULL || c == "txo" || c == "dds" || c == "ktx") { + if (type != nullptr || c == "txo" || c == "dds" || c == "ktx") { // This is a known image type; create an ordinary Texture. ((TexturePool *)this)->_type_registry[c] = Texture::make_texture; return Texture::make_texture; } // This is an unknown texture type. - return NULL; + return nullptr; } /** @@ -124,11 +128,11 @@ write_texture_types(ostream &out, int indent_level) const { string extension = (*ti).first; MakeTextureFunc *func = (*ti).second; - if (pnm_reg->get_type_from_extension(extension) == NULL) { + if (pnm_reg->get_type_from_extension(extension) == nullptr) { PT(Texture) tex = func(); string name = tex->get_type().get_name(); indent(out, indent_level) << name; - indent(out, max(30 - (int)name.length(), 0)) + indent(out, std::max(30 - (int)name.length(), 0)) << " ." << extension << "\n"; } } @@ -140,7 +144,7 @@ write_texture_types(ostream &out, int indent_level) const { */ TexturePool *TexturePool:: get_global_ptr() { - if (_global_ptr == (TexturePool *)NULL) { + if (_global_ptr == nullptr) { _global_ptr = new TexturePool; // We have to call this here, not in the constructor, so that the @@ -221,7 +225,7 @@ ns_load_texture(const Filename &orig_filename, int primary_file_num_channels, try_load_cache(tex, cache, filename, record, compressed_cache_record, options); - if (tex == (Texture *)NULL) { + if (tex == nullptr) { // The texture was neither in the pool, nor found in the on-disk cache; it // needs to be loaded from its source image(s). gobj_cat.info() @@ -236,11 +240,11 @@ ns_load_texture(const Filename &orig_filename, int primary_file_num_channels, filename.set_binary(); PT(VirtualFile) file = vfs->get_file(filename); - if (file == (VirtualFile *)NULL) { + if (file == nullptr) { // No such file. gobj_cat.error() << "Could not find " << filename << "\n"; - return NULL; + return nullptr; } if (gobj_cat.is_debug()) { @@ -252,8 +256,8 @@ ns_load_texture(const Filename &orig_filename, int primary_file_num_channels, tex = Texture::make_from_txo(*in, filename); vfs->close_read_file(in); - if (tex == (Texture *)NULL) { - return NULL; + if (tex == nullptr) { + return nullptr; } tex->set_fullpath(filename); tex->clear_alpha_fullpath(); @@ -266,7 +270,7 @@ ns_load_texture(const Filename &orig_filename, int primary_file_num_channels, 0, 0, false, read_mipmaps, record, options)) { // This texture was not found or could not be read. report_texture_unreadable(filename); - return NULL; + return nullptr; } } @@ -274,7 +278,7 @@ ns_load_texture(const Filename &orig_filename, int primary_file_num_channels, tex->generate_simple_ram_image(); } - store_record = (record != (BamCacheRecord *)NULL); + store_record = (record != nullptr); } if (cache->get_cache_compressed_textures() && tex->has_compression()) { @@ -298,7 +302,7 @@ ns_load_texture(const Filename &orig_filename, int primary_file_num_channels, } // Set the original filename, before we searched along the path. - nassertr(tex != (Texture *)NULL, NULL); + nassertr(tex != nullptr, nullptr); tex->set_filename(orig_filename); tex->set_fullpath(filename); tex->_texture_pool_key = filename; @@ -384,26 +388,26 @@ ns_load_texture(const Filename &orig_filename, try_load_cache(tex, cache, filename, record, compressed_cache_record, options); - if (tex == (Texture *)NULL) { + if (tex == nullptr) { // The texture was neither in the pool, nor found in the on-disk cache; it // needs to be loaded from its source image(s). gobj_cat.info() << "Loading texture " << filename << " and alpha component " - << alpha_filename << endl; + << alpha_filename << std::endl; tex = ns_make_texture(filename.get_extension()); if (!tex->read(filename, alpha_filename, primary_file_num_channels, - alpha_file_channel, 0, 0, false, read_mipmaps, NULL, + alpha_file_channel, 0, 0, false, read_mipmaps, nullptr, options)) { // This texture was not found or could not be read. report_texture_unreadable(filename); - return NULL; + return nullptr; } if (options.get_texture_flags() & LoaderOptions::TF_preload_simple) { tex->generate_simple_ram_image(); } - store_record = (record != (BamCacheRecord *)NULL); + store_record = (record != nullptr); } if (cache->get_cache_compressed_textures() && tex->has_compression()) { @@ -427,7 +431,7 @@ ns_load_texture(const Filename &orig_filename, } // Set the original filenames, before we searched along the path. - nassertr(tex != (Texture *)NULL, NULL); + nassertr(tex != nullptr, nullptr); tex->set_filename(orig_filename); tex->set_fullpath(filename); tex->set_alpha_filename(orig_alpha_filename); @@ -502,7 +506,7 @@ ns_load_3d_texture(const Filename &filename_pattern, try_load_cache(tex, cache, filename, record, compressed_cache_record, options); - if (tex == (Texture *)NULL || + if (tex == nullptr || tex->get_texture_type() != Texture::TT_3d_texture) { // The texture was neither in the pool, nor found in the on-disk cache; it // needs to be loaded from its source image(s). @@ -513,9 +517,9 @@ ns_load_3d_texture(const Filename &filename_pattern, if (!tex->read(filename, 0, 0, true, read_mipmaps, options)) { // This texture was not found or could not be read. report_texture_unreadable(filename); - return NULL; + return nullptr; } - store_record = (record != (BamCacheRecord *)NULL); + store_record = (record != nullptr); } if (cache->get_cache_compressed_textures() && tex->has_compression()) { @@ -539,7 +543,7 @@ ns_load_3d_texture(const Filename &filename_pattern, } // Set the original filename, before we searched along the path. - nassertr(tex != (Texture *)NULL, NULL); + nassertr(tex != nullptr, nullptr); tex->set_filename(filename_pattern); tex->set_fullpath(filename); tex->_texture_pool_key = filename; @@ -606,7 +610,7 @@ ns_load_2d_texture_array(const Filename &filename_pattern, try_load_cache(tex, cache, filename, record, compressed_cache_record, options); - if (tex == (Texture *)NULL || + if (tex == nullptr || tex->get_texture_type() != Texture::TT_2d_texture_array) { // The texture was neither in the pool, nor found in the on-disk cache; it // needs to be loaded from its source image(s). @@ -617,9 +621,9 @@ ns_load_2d_texture_array(const Filename &filename_pattern, if (!tex->read(filename, 0, 0, true, read_mipmaps, options)) { // This texture was not found or could not be read. report_texture_unreadable(filename); - return NULL; + return nullptr; } - store_record = (record != (BamCacheRecord *)NULL); + store_record = (record != nullptr); } if (cache->get_cache_compressed_textures() && tex->has_compression()) { @@ -643,7 +647,7 @@ ns_load_2d_texture_array(const Filename &filename_pattern, } // Set the original filename, before we searched along the path. - nassertr(tex != (Texture *)NULL, NULL); + nassertr(tex != nullptr, nullptr); tex->set_filename(filename_pattern); tex->set_fullpath(filename); tex->_texture_pool_key = unique_filename; @@ -705,7 +709,7 @@ ns_load_cube_map(const Filename &filename_pattern, bool read_mipmaps, try_load_cache(tex, cache, filename, record, compressed_cache_record, options); - if (tex == (Texture *)NULL || + if (tex == nullptr || tex->get_texture_type() != Texture::TT_cube_map) { // The texture was neither in the pool, nor found in the on-disk cache; it // needs to be loaded from its source image(s). @@ -716,9 +720,9 @@ ns_load_cube_map(const Filename &filename_pattern, bool read_mipmaps, if (!tex->read(filename, 0, 0, true, read_mipmaps, options)) { // This texture was not found or could not be read. report_texture_unreadable(filename); - return NULL; + return nullptr; } - store_record = (record != (BamCacheRecord *)NULL); + store_record = (record != nullptr); } if (cache->get_cache_compressed_textures() && tex->has_compression()) { @@ -742,7 +746,7 @@ ns_load_cube_map(const Filename &filename_pattern, bool read_mipmaps, } // Set the original filename, before we searched along the path. - nassertr(tex != (Texture *)NULL, NULL); + nassertr(tex != nullptr, nullptr); tex->set_filename(filename_pattern); tex->set_fullpath(filename); tex->_texture_pool_key = filename; @@ -778,7 +782,7 @@ Texture *TexturePool:: ns_get_normalization_cube_map(int size) { MutexHolder holder(_lock); - if (_normalization_cube_map == (Texture *)NULL) { + if (_normalization_cube_map == nullptr) { _normalization_cube_map = new Texture("normalization_cube_map"); } if (_normalization_cube_map->get_x_size() < size || @@ -796,7 +800,7 @@ Texture *TexturePool:: ns_get_alpha_scale_map() { MutexHolder holder(_lock); - if (_alpha_scale_map == (Texture *)NULL) { + if (_alpha_scale_map == nullptr) { _alpha_scale_map = new Texture("alpha_scale_map"); _alpha_scale_map->generate_alpha_scale_map(); } @@ -860,7 +864,7 @@ ns_release_all_textures() { } _textures.clear(); - _normalization_cube_map = NULL; + _normalization_cube_map = nullptr; // Blow away the cache of resolved relative filenames. _relpath_lookup.clear(); @@ -893,14 +897,14 @@ ns_garbage_collect() { _textures.swap(new_set); - if (_normalization_cube_map != (Texture *)NULL && + if (_normalization_cube_map != nullptr && _normalization_cube_map->get_ref_count() == 1) { if (gobj_cat.is_debug()) { gobj_cat.debug() << "Releasing normalization cube map\n"; } ++num_released; - _normalization_cube_map = NULL; + _normalization_cube_map = nullptr; } return num_released; @@ -957,7 +961,7 @@ ns_find_texture(const string &name) const { } } - return NULL; + return nullptr; } /** @@ -988,7 +992,7 @@ ns_find_all_textures(const string &name) const { PT(Texture) TexturePool:: ns_make_texture(const string &extension) const { MakeTextureFunc *func = get_texture_type(extension); - if (func != NULL) { + if (func != nullptr) { return func(); } @@ -1034,7 +1038,7 @@ void TexturePool:: try_load_cache(PT(Texture) &tex, BamCache *cache, const Filename &filename, PT(BamCacheRecord) &record, bool &compressed_cache_record, const LoaderOptions &options) { - if (tex == (Texture *)NULL) { + if (tex == nullptr) { // The texture was not supplied by a texture filter. See if it can be // found in the on-disk cache, if it is active. if ((cache->get_cache_textures() || cache->get_cache_compressed_textures()) && !textures_header_only) { @@ -1049,7 +1053,7 @@ try_load_cache(PT(Texture) &tex, BamCache *cache, const Filename &filename, dummy.clear(); record = cache->lookup(filename, "txo"); - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { if (record->has_data()) { tex = DCAST(Texture, record->get_data()); compressed_cache_record = (tex->get_ram_image_compression() != Texture::CM_off); @@ -1063,8 +1067,8 @@ try_load_cache(PT(Texture) &tex, BamCache *cache, const Filename &filename, gobj_cat.debug() << "Not caching uncompressed texture " << *tex << "\n"; } - tex = NULL; - record = NULL; + tex = nullptr; + record = nullptr; } else if (x_size != tex->get_x_size() || y_size != tex->get_y_size()) { @@ -1079,7 +1083,7 @@ try_load_cache(PT(Texture) &tex, BamCache *cache, const Filename &filename, << " instead of " << x_size << " x " << y_size << "; dropping cache.\n"; } - tex = NULL; + tex = nullptr; } else if (!tex->has_compression() && tex->get_ram_image_compression() != Texture::CM_off) { // This texture shouldn't be compressed, but it is. Go reload it. @@ -1088,7 +1092,7 @@ try_load_cache(PT(Texture) &tex, BamCache *cache, const Filename &filename, << "Cached texture " << *tex << " is compressed in cache; dropping cache.\n"; } - tex = NULL; + tex = nullptr; } else { gobj_cat.info() @@ -1127,7 +1131,7 @@ try_load_cache(PT(Texture) &tex, BamCache *cache, const Filename &filename, gobj_cat.debug() << "Not caching uncompressed texture\n"; } - record = NULL; + record = nullptr; } } } @@ -1170,7 +1174,7 @@ report_texture_unreadable(const Filename &filename) const { // Maybe the filename extension is unknown. MakeTextureFunc *func = get_texture_type(filename.get_extension()); - if (func == (MakeTextureFunc *)NULL) { + if (func == nullptr) { gobj_cat.error() << "Texture extension \"" << filename.get_extension() << "\" is unknown. Supported texture types:\n"; @@ -1199,7 +1203,7 @@ pre_load(const Filename &orig_filename, const Filename &orig_alpha_filename, tex = (*fi)->pre_load(orig_filename, orig_alpha_filename, primary_file_num_channels, alpha_file_channel, read_mipmaps, options); - if (tex != (Texture *)NULL) { + if (tex != nullptr) { return tex; } } @@ -1245,11 +1249,11 @@ load_filters() { Filename dlname = Filename::dso_filename("lib" + name + ".so"); gobj_cat->info() - << "loading texture filter: " << dlname.to_os_specific() << endl; + << "loading texture filter: " << dlname.to_os_specific() << std::endl; void *tmp = load_dso(get_plugin_path().get_value(), dlname); - if (tmp == (void *)NULL) { + if (tmp == nullptr) { gobj_cat.info() - << "Unable to load: " << load_dso_error() << endl; + << "Unable to load: " << load_dso_error() << std::endl; } } } diff --git a/panda/src/gobj/texturePool.h b/panda/src/gobj/texturePool.h index 2f0866cf3f..866374ec96 100644 --- a/panda/src/gobj/texturePool.h +++ b/panda/src/gobj/texturePool.h @@ -68,27 +68,27 @@ PUBLISHED: INLINE static int garbage_collect(); - INLINE static void list_contents(ostream &out); + INLINE static void list_contents(std::ostream &out); INLINE static void list_contents(); - INLINE static Texture *find_texture(const string &name); - INLINE static TextureCollection find_all_textures(const string &name = "*"); + INLINE static Texture *find_texture(const std::string &name); + INLINE static TextureCollection find_all_textures(const std::string &name = "*"); INLINE static void set_fake_texture_image(const Filename &filename); INLINE static void clear_fake_texture_image(); INLINE static bool has_fake_texture_image(); INLINE static const Filename &get_fake_texture_image(); - INLINE static PT(Texture) make_texture(const string &extension); + INLINE static PT(Texture) make_texture(const std::string &extension); - static void write(ostream &out); + static void write(std::ostream &out); public: typedef Texture::MakeTextureFunc MakeTextureFunc; - void register_texture_type(MakeTextureFunc *func, const string &extensions); + void register_texture_type(MakeTextureFunc *func, const std::string &extensions); void register_filter(TexturePoolFilter *filter); - MakeTextureFunc *get_texture_type(const string &extension) const; - void write_texture_types(ostream &out, int indent_level) const; + MakeTextureFunc *get_texture_type(const std::string &extension) const; + void write_texture_types(std::ostream &out, int indent_level) const; static TexturePool *get_global_ptr(); @@ -122,10 +122,10 @@ private: void ns_release_texture(Texture *texture); void ns_release_all_textures(); int ns_garbage_collect(); - void ns_list_contents(ostream &out) const; - Texture *ns_find_texture(const string &name) const; - TextureCollection ns_find_all_textures(const string &name) const; - PT(Texture) ns_make_texture(const string &extension) const; + void ns_list_contents(std::ostream &out) const; + Texture *ns_find_texture(const std::string &name) const; + TextureCollection ns_find_all_textures(const std::string &name) const; + PT(Texture) ns_make_texture(const std::string &extension) const; void resolve_filename(Filename &new_filename, const Filename &orig_filename, bool read_mipmaps, const LoaderOptions &options); @@ -159,7 +159,7 @@ private: PT(Texture) _normalization_cube_map; PT(Texture) _alpha_scale_map; - typedef pmap TypeRegistry; + typedef pmap TypeRegistry; TypeRegistry _type_registry; typedef pvector FilterRegistry; diff --git a/panda/src/gobj/texturePoolFilter.cxx b/panda/src/gobj/texturePoolFilter.cxx index 6d752dd7c7..c63803860c 100644 --- a/panda/src/gobj/texturePoolFilter.cxx +++ b/panda/src/gobj/texturePoolFilter.cxx @@ -32,7 +32,7 @@ TexturePoolFilter:: PT(Texture) TexturePoolFilter:: pre_load(const Filename &, const Filename &, int, int, bool, const LoaderOptions &) { - return NULL; + return nullptr; } /** @@ -51,6 +51,6 @@ post_load(Texture *tex) { * */ void TexturePoolFilter:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type(); } diff --git a/panda/src/gobj/texturePoolFilter.h b/panda/src/gobj/texturePoolFilter.h index 019b66fa9f..69a5278ff7 100644 --- a/panda/src/gobj/texturePoolFilter.h +++ b/panda/src/gobj/texturePoolFilter.h @@ -51,7 +51,7 @@ public: const LoaderOptions &options); virtual PT(Texture) post_load(Texture *tex); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; public: static TypeHandle get_class_type() { @@ -71,7 +71,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const TexturePoolFilter &filter) { +INLINE std::ostream &operator << (std::ostream &out, const TexturePoolFilter &filter) { filter.output(out); return out; } diff --git a/panda/src/gobj/textureReloadRequest.I b/panda/src/gobj/textureReloadRequest.I index d17bdc72b4..1b958ac6ef 100644 --- a/panda/src/gobj/textureReloadRequest.I +++ b/panda/src/gobj/textureReloadRequest.I @@ -16,7 +16,7 @@ * load_async(), to begin an asynchronous load. */ INLINE TextureReloadRequest:: -TextureReloadRequest(const string &name, +TextureReloadRequest(const std::string &name, PreparedGraphicsObjects *pgo, Texture *texture, bool allow_compressed) : AsyncTask(name), @@ -24,8 +24,8 @@ TextureReloadRequest(const string &name, _texture(texture), _allow_compressed(allow_compressed) { - nassertv(_pgo != (PreparedGraphicsObjects *)NULL); - nassertv(_texture != (Texture *)NULL); + nassertv(_pgo != nullptr); + nassertv(_texture != nullptr); } /** diff --git a/panda/src/gobj/textureReloadRequest.h b/panda/src/gobj/textureReloadRequest.h index 1e97c99ea2..625ac3ce3e 100644 --- a/panda/src/gobj/textureReloadRequest.h +++ b/panda/src/gobj/textureReloadRequest.h @@ -33,7 +33,7 @@ public: ALLOC_DELETED_CHAIN(TextureReloadRequest); PUBLISHED: - INLINE explicit TextureReloadRequest(const string &name, + INLINE explicit TextureReloadRequest(const std::string &name, PreparedGraphicsObjects *pgo, Texture *texture, bool allow_compressed); diff --git a/panda/src/gobj/textureStage.I b/panda/src/gobj/textureStage.I index 17034231a3..a6d26d8600 100644 --- a/panda/src/gobj/textureStage.I +++ b/panda/src/gobj/textureStage.I @@ -22,7 +22,7 @@ TextureStage(const TextureStage ©) { /** * Returns the name of this texture stage */ -INLINE const string &TextureStage:: +INLINE const std::string &TextureStage:: get_name() const { return _name; } @@ -31,7 +31,7 @@ get_name() const { * Changes the name of this texture stage */ INLINE void TextureStage:: -set_name(const string &name) { +set_name(const std::string &name) { _name = name; } @@ -121,7 +121,7 @@ set_texcoord_name(InternalName *name) { * any number of associated UV sets, each of which must have a unique name. */ INLINE void TextureStage:: -set_texcoord_name(const string &name) { +set_texcoord_name(const std::string &name) { set_texcoord_name(InternalName::get_texcoord_name(name)); } @@ -139,7 +139,7 @@ get_texcoord_name() const { */ INLINE InternalName *TextureStage:: get_tangent_name() const { - if (_texcoord_name->get_parent() == NULL) { + if (_texcoord_name->get_parent() == nullptr) { return InternalName::get_tangent(); } else { return InternalName::get_tangent_name(_texcoord_name->get_basename()); @@ -152,7 +152,7 @@ get_tangent_name() const { */ INLINE InternalName *TextureStage:: get_binormal_name() const { - if (_texcoord_name->get_parent() == NULL) { + if (_texcoord_name->get_parent() == nullptr) { return InternalName::get_binormal(); } else { return InternalName::get_binormal_name(_texcoord_name->get_basename()); @@ -659,7 +659,7 @@ operator < (const TextureStage &other) const { */ INLINE TextureStage *TextureStage:: get_default() { - if (_default_stage == (TextureStage *)NULL) { + if (_default_stage == nullptr) { _default_stage = new TextureStage("default"); } return _default_stage; @@ -733,8 +733,8 @@ update_color_flags() { } } -INLINE ostream & -operator << (ostream &out, const TextureStage &ts) { +INLINE std::ostream & +operator << (std::ostream &out, const TextureStage &ts) { ts.output(out); return out; } diff --git a/panda/src/gobj/textureStage.cxx b/panda/src/gobj/textureStage.cxx index 120bb4feb3..4fecd20999 100644 --- a/panda/src/gobj/textureStage.cxx +++ b/panda/src/gobj/textureStage.cxx @@ -16,6 +16,8 @@ #include "bamReader.h" #include "bamWriter.h" +using std::ostream; + PT(TextureStage) TextureStage::_default_stage; UpdateSeq TextureStage::_sort_seq; @@ -25,7 +27,7 @@ TypeHandle TextureStage::_type_handle; * Initialize the texture stage at construction */ TextureStage:: -TextureStage(const string &name) : _used_by_auto_shader(false) { +TextureStage(const std::string &name) : _used_by_auto_shader(false) { _name = name; _sort = 0; _priority = 0; diff --git a/panda/src/gobj/textureStage.h b/panda/src/gobj/textureStage.h index 2414e72991..5635f1e65a 100644 --- a/panda/src/gobj/textureStage.h +++ b/panda/src/gobj/textureStage.h @@ -34,7 +34,7 @@ class FactoryParams; */ class EXPCL_PANDA_GOBJ TextureStage : public TypedWritableReferenceCount { PUBLISHED: - explicit TextureStage(const string &name); + explicit TextureStage(const std::string &name); INLINE TextureStage(const TextureStage ©); void operator = (const TextureStage ©); @@ -97,8 +97,8 @@ PUBLISHED: CO_one_minus_src_alpha, }; - INLINE void set_name(const string &name); - INLINE const string &get_name() const; + INLINE void set_name(const std::string &name); + INLINE const std::string &get_name() const; INLINE void set_sort(int sort); INLINE int get_sort() const; @@ -107,7 +107,7 @@ PUBLISHED: INLINE int get_priority() const; INLINE void set_texcoord_name(InternalName *name); - INLINE void set_texcoord_name(const string &texcoord_name); + INLINE void set_texcoord_name(const std::string &texcoord_name); INLINE InternalName *get_texcoord_name() const; INLINE InternalName *get_tangent_name() const; INLINE InternalName *get_binormal_name() const; @@ -179,8 +179,8 @@ PUBLISHED: int compare_to(const TextureStage &other) const; - void write(ostream &out) const; - void output(ostream &out) const; + void write(std::ostream &out) const; + void output(std::ostream &out) const; INLINE static TextureStage *get_default(); @@ -216,7 +216,7 @@ private: static bool operand_valid_for_rgb(CombineOperand co); static bool operand_valid_for_alpha(CombineOperand co); - string _name; + std::string _name; int _sort; int _priority; PT(InternalName) _texcoord_name; @@ -283,12 +283,12 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const TextureStage &ts); +INLINE std::ostream &operator << (std::ostream &out, const TextureStage &ts); -EXPCL_PANDA_GOBJ ostream &operator << (ostream &out, TextureStage::Mode mode); -EXPCL_PANDA_GOBJ ostream &operator << (ostream &out, TextureStage::CombineMode cm); -EXPCL_PANDA_GOBJ ostream &operator << (ostream &out, TextureStage::CombineSource cs); -EXPCL_PANDA_GOBJ ostream &operator << (ostream &out, TextureStage::CombineOperand co); +EXPCL_PANDA_GOBJ std::ostream &operator << (std::ostream &out, TextureStage::Mode mode); +EXPCL_PANDA_GOBJ std::ostream &operator << (std::ostream &out, TextureStage::CombineMode cm); +EXPCL_PANDA_GOBJ std::ostream &operator << (std::ostream &out, TextureStage::CombineSource cs); +EXPCL_PANDA_GOBJ std::ostream &operator << (std::ostream &out, TextureStage::CombineOperand co); #include "textureStage.I" diff --git a/panda/src/gobj/textureStagePool.I b/panda/src/gobj/textureStagePool.I index a88d5e1561..3023116285 100644 --- a/panda/src/gobj/textureStagePool.I +++ b/panda/src/gobj/textureStagePool.I @@ -87,6 +87,6 @@ garbage_collect() { * Lists the contents of the TextureStage pool to the indicated output stream. */ INLINE void TextureStagePool:: -list_contents(ostream &out) { +list_contents(std::ostream &out) { get_global_ptr()->ns_list_contents(out); } diff --git a/panda/src/gobj/textureStagePool.cxx b/panda/src/gobj/textureStagePool.cxx index 2d9b33a036..01e009ef7c 100644 --- a/panda/src/gobj/textureStagePool.cxx +++ b/panda/src/gobj/textureStagePool.cxx @@ -17,7 +17,11 @@ #include "configVariableEnum.h" #include "string_utils.h" -TextureStagePool *TextureStagePool::_global_ptr = (TextureStagePool *)NULL; +using std::istream; +using std::ostream; +using std::string; + +TextureStagePool *TextureStagePool::_global_ptr = nullptr; /** @@ -86,7 +90,7 @@ ns_get_stage(TextureStage *temp) { } } - return NULL; + return nullptr; } /** @@ -258,7 +262,7 @@ ns_list_contents(ostream &out) const { */ TextureStagePool *TextureStagePool:: get_global_ptr() { - if (_global_ptr == (TextureStagePool *)NULL) { + if (_global_ptr == nullptr) { _global_ptr = new TextureStagePool; } return _global_ptr; diff --git a/panda/src/gobj/textureStagePool.h b/panda/src/gobj/textureStagePool.h index 4db775251d..3e654d50cb 100644 --- a/panda/src/gobj/textureStagePool.h +++ b/panda/src/gobj/textureStagePool.h @@ -46,8 +46,8 @@ PUBLISHED: MAKE_PROPERTY(mode, get_mode, set_mode); INLINE static int garbage_collect(); - INLINE static void list_contents(ostream &out); - static void write(ostream &out); + INLINE static void list_contents(std::ostream &out); + static void write(std::ostream &out); private: TextureStagePool(); @@ -60,7 +60,7 @@ private: Mode ns_get_mode(); int ns_garbage_collect(); - void ns_list_contents(ostream &out) const; + void ns_list_contents(std::ostream &out) const; static TextureStagePool *get_global_ptr(); @@ -75,14 +75,14 @@ private: typedef pmap > StagesByProperties; StagesByProperties _stages_by_properties; - typedef pmap StagesByName; + typedef pmap StagesByName; StagesByName _stages_by_name; Mode _mode; }; -EXPCL_PANDA_GOBJ ostream &operator << (ostream &out, TextureStagePool::Mode mode); -EXPCL_PANDA_GOBJ istream &operator >> (istream &in, TextureStagePool::Mode &mode); +EXPCL_PANDA_GOBJ std::ostream &operator << (std::ostream &out, TextureStagePool::Mode mode); +EXPCL_PANDA_GOBJ std::istream &operator >> (std::istream &in, TextureStagePool::Mode &mode); #include "textureStagePool.I" diff --git a/panda/src/gobj/texture_ext.cxx b/panda/src/gobj/texture_ext.cxx index e81d40c15f..9af792be08 100644 --- a/panda/src/gobj/texture_ext.cxx +++ b/panda/src/gobj/texture_ext.cxx @@ -77,7 +77,7 @@ set_ram_image(PyObject *image, Texture::CompressionMode compression, PTA_uchar data = PTA_uchar::empty_array(view.len, Texture::get_class_type()); memcpy(data.p(), view.buf, view.len); - _this->set_ram_image(MOVE(data), compression, page_size); + _this->set_ram_image(std::move(data), compression, page_size); PyBuffer_Release(&view); return; @@ -102,7 +102,7 @@ set_ram_image(PyObject *image, Texture::CompressionMode compression, PTA_uchar data = PTA_uchar::empty_array(buffer_len, Texture::get_class_type()); memcpy(data.p(), buffer, buffer_len); - _this->set_ram_image(MOVE(data), compression, page_size); + _this->set_ram_image(std::move(data), compression, page_size); return; } #endif @@ -117,7 +117,7 @@ set_ram_image(PyObject *image, Texture::CompressionMode compression, * support compressed image data or sub-pages; use set_ram_image() for that. */ void Extension:: -set_ram_image_as(PyObject *image, const string &provided_format) { +set_ram_image_as(PyObject *image, const std::string &provided_format) { // Check if perhaps a PointerToArray object was passed in. if (DtoolInstance_Check(image)) { if (DtoolInstance_TYPE(image) == &Dtool_ConstPointerToArray_unsigned_char) { @@ -155,7 +155,7 @@ set_ram_image_as(PyObject *image, const string &provided_format) { PTA_uchar data = PTA_uchar::empty_array(view.len, Texture::get_class_type()); memcpy(data.p(), view.buf, view.len); - _this->set_ram_image_as(MOVE(data), provided_format); + _this->set_ram_image_as(std::move(data), provided_format); PyBuffer_Release(&view); return; diff --git a/panda/src/gobj/texture_ext.h b/panda/src/gobj/texture_ext.h index d33fce24ef..b4f0559b08 100644 --- a/panda/src/gobj/texture_ext.h +++ b/panda/src/gobj/texture_ext.h @@ -31,7 +31,7 @@ class Extension : public ExtensionBase { public: void set_ram_image(PyObject *image, Texture::CompressionMode compression = Texture::CM_off, size_t page_size = 0); - void set_ram_image_as(PyObject *image, const string &provided_format); + void set_ram_image_as(PyObject *image, const std::string &provided_format); }; #endif // HAVE_PYTHON diff --git a/panda/src/gobj/transformBlend.I b/panda/src/gobj/transformBlend.I index 936ca57cc4..092e9bbeec 100644 --- a/panda/src/gobj/transformBlend.I +++ b/panda/src/gobj/transformBlend.I @@ -128,7 +128,7 @@ get_num_transforms() const { */ INLINE const VertexTransform *TransformBlend:: get_transform(size_t n) const { - nassertr(n < _entries.size(), NULL); + nassertr(n < _entries.size(), nullptr); return _entries[n]._transform; } @@ -376,8 +376,8 @@ CData(const TransformBlend::CData ©) : { } -INLINE ostream & -operator << (ostream &out, const TransformBlend &obj) { +INLINE std::ostream & +operator << (std::ostream &out, const TransformBlend &obj) { obj.output(out); return out; } diff --git a/panda/src/gobj/transformBlend.cxx b/panda/src/gobj/transformBlend.cxx index 656a691a95..9ca70390e2 100644 --- a/panda/src/gobj/transformBlend.cxx +++ b/panda/src/gobj/transformBlend.cxx @@ -54,7 +54,7 @@ add_transform(const VertexTransform *transform, PN_stdfloat weight) { TransformEntry entry; entry._transform = transform; entry._weight = weight; - pair result = _entries.insert(entry); + std::pair result = _entries.insert(entry); if (!result.second) { // If the new value was not inserted, it was already there; increment // the existing weight factor. @@ -168,7 +168,7 @@ get_weight(const VertexTransform *transform) const { * */ void TransformBlend:: -output(ostream &out) const { +output(std::ostream &out) const { if (_entries.empty()) { out << "empty"; } else { @@ -186,7 +186,7 @@ output(ostream &out) const { * */ void TransformBlend:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { Thread *current_thread = Thread::get_current_thread(); Entries::const_iterator ei; for (ei = _entries.begin(); ei != _entries.end(); ++ei) { @@ -218,7 +218,7 @@ recompute_result(CData *cdata, Thread *current_thread) { UpdateSeq seq; Entries::const_iterator ei; for (ei = _entries.begin(); ei != _entries.end(); ++ei) { - seq = max(seq, (*ei)._transform->get_modified(current_thread)); + seq = std::max(seq, (*ei)._transform->get_modified(current_thread)); } if (cdata->_modified != seq) { diff --git a/panda/src/gobj/transformBlend.h b/panda/src/gobj/transformBlend.h index 45b5793294..3adcb73128 100644 --- a/panda/src/gobj/transformBlend.h +++ b/panda/src/gobj/transformBlend.h @@ -86,8 +86,8 @@ PUBLISHED: INLINE UpdateSeq get_modified(Thread *current_thread = Thread::get_current_thread()) const; MAKE_PROPERTY(modified, get_modified); - void output(ostream &out) const; - void write(ostream &out, int indent_level) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level) const; private: class CData; @@ -145,7 +145,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const TransformBlend &obj); +INLINE std::ostream &operator << (std::ostream &out, const TransformBlend &obj); #include "transformBlend.I" diff --git a/panda/src/gobj/transformBlendTable.cxx b/panda/src/gobj/transformBlendTable.cxx index da76d38626..266da16c3b 100644 --- a/panda/src/gobj/transformBlendTable.cxx +++ b/panda/src/gobj/transformBlendTable.cxx @@ -107,7 +107,7 @@ add_blend(const TransformBlend &blend) { // latest. const TransformBlend &added_blend = _blends[new_position]; _blend_index[&added_blend] = new_position; - _max_simultaneous_transforms = max(_max_simultaneous_transforms, + _max_simultaneous_transforms = std::max(_max_simultaneous_transforms, (int)blend.get_num_transforms()); // We can't compute this one as we go, so set it to a special value to @@ -122,7 +122,7 @@ add_blend(const TransformBlend &blend) { * */ void TransformBlendTable:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { for (size_t i = 0; i < _blends.size(); ++i) { indent(out, indent_level) << i << ". " << _blends[i] << "\n"; @@ -158,7 +158,7 @@ rebuild_index() { for (size_t ti = 0; ti < blend.get_num_transforms(); ++ti) { transforms.insert(blend.get_transform(ti)); } - _max_simultaneous_transforms = max((size_t)_max_simultaneous_transforms, + _max_simultaneous_transforms = std::max((size_t)_max_simultaneous_transforms, blend.get_num_transforms()); } @@ -179,7 +179,7 @@ recompute_modified(TransformBlendTable::CData *cdata, Thread *current_thread) { UpdateSeq seq; Blends::const_iterator bi; for (bi = _blends.begin(); bi != _blends.end(); ++bi) { - seq = max(seq, (*bi).get_modified(current_thread)); + seq = std::max(seq, (*bi).get_modified(current_thread)); } cdata->_modified = seq; diff --git a/panda/src/gobj/transformBlendTable.h b/panda/src/gobj/transformBlendTable.h index 55d628d349..644fbbb9b9 100644 --- a/panda/src/gobj/transformBlendTable.h +++ b/panda/src/gobj/transformBlendTable.h @@ -68,7 +68,7 @@ PUBLISHED: INLINE const SparseArray &get_rows() const; INLINE SparseArray &modify_rows(); - void write(ostream &out, int indent_level) const; + void write(std::ostream &out, int indent_level) const; MAKE_SEQ_PROPERTY(blends, get_num_blends, get_blend, set_blend, remove_blend); MAKE_PROPERTY(modified, get_modified); @@ -156,7 +156,7 @@ private: friend class VertexTransform; }; -INLINE ostream &operator << (ostream &out, const TransformBlendTable &obj); +INLINE std::ostream &operator << (std::ostream &out, const TransformBlendTable &obj); #include "transformBlendTable.I" diff --git a/panda/src/gobj/transformTable.I b/panda/src/gobj/transformTable.I index ce8fe2d196..acf7aa95fb 100644 --- a/panda/src/gobj/transformTable.I +++ b/panda/src/gobj/transformTable.I @@ -59,7 +59,7 @@ get_num_transforms() const { */ INLINE const VertexTransform *TransformTable:: get_transform(size_t n) const { - nassertr(n < _transforms.size(), NULL); + nassertr(n < _transforms.size(), nullptr); return _transforms[n]; } diff --git a/panda/src/gobj/transformTable.cxx b/panda/src/gobj/transformTable.cxx index 73d0665079..3ddadca33a 100644 --- a/panda/src/gobj/transformTable.cxx +++ b/panda/src/gobj/transformTable.cxx @@ -111,7 +111,7 @@ add_transform(const VertexTransform *transform) { * */ void TransformTable:: -write(ostream &out) const { +write(std::ostream &out) const { for (size_t i = 0; i < _transforms.size(); ++i) { out << i << ". " << *_transforms[i] << "\n"; } @@ -221,7 +221,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { _transforms.reserve(num_transforms); for (size_t i = 0; i < num_transforms; ++i) { manager->read_pointer(scan); - _transforms.push_back(NULL); + _transforms.push_back(nullptr); } manager->read_cdata(scan, _cycler); diff --git a/panda/src/gobj/transformTable.h b/panda/src/gobj/transformTable.h index b55e4106df..8d77777dbb 100644 --- a/panda/src/gobj/transformTable.h +++ b/panda/src/gobj/transformTable.h @@ -55,7 +55,7 @@ PUBLISHED: void remove_transform(size_t n); size_t add_transform(const VertexTransform *transform); - void write(ostream &out) const; + void write(std::ostream &out) const; MAKE_PROPERTY(registered, is_registered); MAKE_PROPERTY(modified, get_modified); @@ -121,7 +121,7 @@ private: friend class VertexTransform; }; -INLINE ostream &operator << (ostream &out, const TransformTable &obj); +INLINE std::ostream &operator << (std::ostream &out, const TransformTable &obj); #include "transformTable.I" diff --git a/panda/src/gobj/userVertexSlider.cxx b/panda/src/gobj/userVertexSlider.cxx index d6363082a8..a868be2058 100644 --- a/panda/src/gobj/userVertexSlider.cxx +++ b/panda/src/gobj/userVertexSlider.cxx @@ -21,7 +21,7 @@ TypeHandle UserVertexSlider::_type_handle; * */ UserVertexSlider:: -UserVertexSlider(const string &name) : +UserVertexSlider(const std::string &name) : VertexSlider(InternalName::make(name)) { } diff --git a/panda/src/gobj/userVertexSlider.h b/panda/src/gobj/userVertexSlider.h index aadeafd893..574e6bc6b7 100644 --- a/panda/src/gobj/userVertexSlider.h +++ b/panda/src/gobj/userVertexSlider.h @@ -30,7 +30,7 @@ class FactoryParams; */ class EXPCL_PANDA_GOBJ UserVertexSlider : public VertexSlider { PUBLISHED: - explicit UserVertexSlider(const string &name); + explicit UserVertexSlider(const std::string &name); explicit UserVertexSlider(const InternalName *name); INLINE void set_slider(PN_stdfloat slider); diff --git a/panda/src/gobj/userVertexTransform.I b/panda/src/gobj/userVertexTransform.I index 3b6d7b046a..3ac9204cca 100644 --- a/panda/src/gobj/userVertexTransform.I +++ b/panda/src/gobj/userVertexTransform.I @@ -14,7 +14,7 @@ /** * Returns the name passed to the constructor. Completely arbitrary. */ -INLINE const string &UserVertexTransform:: +INLINE const std::string &UserVertexTransform:: get_name() const { return _name; } diff --git a/panda/src/gobj/userVertexTransform.cxx b/panda/src/gobj/userVertexTransform.cxx index d83aeb4c8a..c27cb38d61 100644 --- a/panda/src/gobj/userVertexTransform.cxx +++ b/panda/src/gobj/userVertexTransform.cxx @@ -21,7 +21,7 @@ TypeHandle UserVertexTransform::_type_handle; * */ UserVertexTransform:: -UserVertexTransform(const string &name) : +UserVertexTransform(const std::string &name) : _name(name) { } @@ -39,7 +39,7 @@ get_matrix(LMatrix4 &matrix) const { * */ void UserVertexTransform:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << " " << get_name(); } diff --git a/panda/src/gobj/userVertexTransform.h b/panda/src/gobj/userVertexTransform.h index 377dff2a17..356d4f823a 100644 --- a/panda/src/gobj/userVertexTransform.h +++ b/panda/src/gobj/userVertexTransform.h @@ -30,17 +30,17 @@ class FactoryParams; */ class EXPCL_PANDA_GOBJ UserVertexTransform : public VertexTransform { PUBLISHED: - explicit UserVertexTransform(const string &name); + explicit UserVertexTransform(const std::string &name); - INLINE const string &get_name() const; + INLINE const std::string &get_name() const; INLINE void set_matrix(const LMatrix4 &matrix); virtual void get_matrix(LMatrix4 &matrix) const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: - string _name; + std::string _name; // This is the data that must be cycled between pipeline stages. class EXPCL_PANDA_GOBJ CData : public CycleData { diff --git a/panda/src/gobj/vertexBufferContext.cxx b/panda/src/gobj/vertexBufferContext.cxx index cde6ec023a..b0eab66a74 100644 --- a/panda/src/gobj/vertexBufferContext.cxx +++ b/panda/src/gobj/vertexBufferContext.cxx @@ -20,7 +20,7 @@ TypeHandle VertexBufferContext::_type_handle; * */ void VertexBufferContext:: -output(ostream &out) const { +output(std::ostream &out) const { out << *get_data() << ", " << get_data_size_bytes(); } @@ -28,6 +28,6 @@ output(ostream &out) const { * */ void VertexBufferContext:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { SavedContext::write(out, indent_level); } diff --git a/panda/src/gobj/vertexBufferContext.h b/panda/src/gobj/vertexBufferContext.h index 76956aa8d2..69f02e0ed7 100644 --- a/panda/src/gobj/vertexBufferContext.h +++ b/panda/src/gobj/vertexBufferContext.h @@ -47,8 +47,8 @@ public: INLINE void mark_loaded(const GeomVertexArrayDataHandle *reader); INLINE void mark_unloaded(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; private: // This cannot be a PT(GeomVertexArrayData), because the data and the GSG @@ -77,7 +77,7 @@ private: friend class PreparedGraphicsObjects; }; -inline ostream &operator << (ostream &out, const VertexBufferContext &context) { +inline std::ostream &operator << (std::ostream &out, const VertexBufferContext &context) { context.output(out); return out; } diff --git a/panda/src/gobj/vertexDataBlock.I b/panda/src/gobj/vertexDataBlock.I index 61aa8e3a14..7660bd315f 100644 --- a/panda/src/gobj/vertexDataBlock.I +++ b/panda/src/gobj/vertexDataBlock.I @@ -38,10 +38,10 @@ get_page() const { */ INLINE unsigned char *VertexDataBlock:: get_pointer(bool force) const { - nassertr(get_page() != (VertexDataPage *)NULL, NULL); + nassertr(get_page() != nullptr, nullptr); unsigned char *page_data = get_page()->get_page_data(force); - if (page_data == (unsigned char *)NULL) { - return NULL; + if (page_data == nullptr) { + return nullptr; } else { return page_data + get_start(); } diff --git a/panda/src/gobj/vertexDataBook.cxx b/panda/src/gobj/vertexDataBook.cxx index 5be3a0718a..555033da3c 100644 --- a/panda/src/gobj/vertexDataBook.cxx +++ b/panda/src/gobj/vertexDataBook.cxx @@ -141,7 +141,7 @@ do_alloc(size_t size) { // This is why we've already computed pnext. VertexDataBlock *block = page->do_alloc(size); - if (block != (VertexDataBlock *)NULL) { + if (block != nullptr) { // This page worked. return block; } diff --git a/panda/src/gobj/vertexDataBuffer.I b/panda/src/gobj/vertexDataBuffer.I index 3bc1f85b80..f3770d3b21 100644 --- a/panda/src/gobj/vertexDataBuffer.I +++ b/panda/src/gobj/vertexDataBuffer.I @@ -16,7 +16,7 @@ */ INLINE VertexDataBuffer:: VertexDataBuffer() : - _resident_data(NULL), + _resident_data(nullptr), _size(0), _reserved_size(0) { @@ -27,7 +27,7 @@ VertexDataBuffer() : */ INLINE VertexDataBuffer:: VertexDataBuffer(size_t size) : - _resident_data(NULL), + _resident_data(nullptr), _size(0), _reserved_size(0) { @@ -40,7 +40,7 @@ VertexDataBuffer(size_t size) : */ INLINE VertexDataBuffer:: VertexDataBuffer(const VertexDataBuffer ©) : - _resident_data(NULL), + _resident_data(nullptr), _size(0), _reserved_size(0) { @@ -68,11 +68,11 @@ get_read_pointer(bool force) const { LightMutexHolder holder(_lock); const unsigned char *ptr; - if (_resident_data != (unsigned char *)NULL || _size == 0) { + if (_resident_data != nullptr || _size == 0) { ptr = _resident_data; } else { - nassertr(_block != (VertexDataBlock *)NULL, NULL); - nassertr(_reserved_size >= _size, NULL); + nassertr(_block != nullptr, nullptr); + nassertr(_reserved_size >= _size, nullptr); // We don't necessarily need to page the buffer all the way into independent // status; it's sufficient just to return the block's pointer, which will @@ -92,10 +92,10 @@ INLINE unsigned char *VertexDataBuffer:: get_write_pointer() { LightMutexHolder holder(_lock); - if (_resident_data == (unsigned char *)NULL && _reserved_size != 0) { + if (_resident_data == nullptr && _reserved_size != 0) { do_page_in(); } - nassertr(_reserved_size >= _size, NULL); + nassertr(_reserved_size >= _size, nullptr); #ifdef _DEBUG assert(((uintptr_t)_resident_data % MEMORY_HOOK_ALIGNMENT) == 0); #endif @@ -133,7 +133,7 @@ set_size(size_t size) { nassertv(size <= _reserved_size); if (size != _size) { - if (_resident_data == (unsigned char *)NULL && _reserved_size != 0) { + if (_resident_data == nullptr && _reserved_size != 0) { do_page_in(); } diff --git a/panda/src/gobj/vertexDataBuffer.cxx b/panda/src/gobj/vertexDataBuffer.cxx index 19f50b3013..e1d3ad5c56 100644 --- a/panda/src/gobj/vertexDataBuffer.cxx +++ b/panda/src/gobj/vertexDataBuffer.cxx @@ -25,12 +25,12 @@ operator = (const VertexDataBuffer ©) { LightMutexHolder holder(_lock); LightMutexHolder holder2(copy._lock); - if (_resident_data != (unsigned char *)NULL) { + if (_resident_data != nullptr) { nassertv(_reserved_size != 0); get_class_type().deallocate_array(_resident_data); - _resident_data = NULL; + _resident_data = nullptr; } - if (copy._resident_data != (unsigned char *)NULL && copy._size != 0) { + if (copy._resident_data != nullptr && copy._size != 0) { // We only allocate _size bytes, not the full _reserved_size allocated by // the original copy. _resident_data = (unsigned char *)get_class_type().allocate_array(copy._size); @@ -87,22 +87,22 @@ do_clean_realloc(size_t reserved_size) { } // Page in if we're currently paged out. - if (_reserved_size != 0 && _resident_data == (unsigned char *)NULL) { + if (_reserved_size != 0 && _resident_data == nullptr) { do_page_in(); } if (_reserved_size == 0) { - nassertv(_resident_data == (unsigned char *)NULL); + nassertv(_resident_data == nullptr); _resident_data = (unsigned char *)get_class_type().allocate_array(reserved_size); } else { - nassertv(_resident_data != (unsigned char *)NULL); + nassertv(_resident_data != nullptr); _resident_data = (unsigned char *)get_class_type().reallocate_array(_resident_data, reserved_size); } - nassertv(_resident_data != (unsigned char *)NULL); + nassertv(_resident_data != nullptr); _reserved_size = reserved_size; } - _size = min(_size, _reserved_size); + _size = std::min(_size, _reserved_size); } /** @@ -113,25 +113,25 @@ do_clean_realloc(size_t reserved_size) { */ void VertexDataBuffer:: do_unclean_realloc(size_t reserved_size) { - if (reserved_size != _reserved_size || _resident_data == (unsigned char *)NULL) { + if (reserved_size != _reserved_size || _resident_data == nullptr) { if (gobj_cat.is_debug()) { gobj_cat.debug() << this << ".unclean_realloc(" << reserved_size << ")\n"; } // If we're paged out, discard the page. - _block = NULL; + _block = nullptr; - if (_resident_data != (unsigned char *)NULL) { + if (_resident_data != nullptr) { nassertv(_reserved_size != 0); get_class_type().deallocate_array(_resident_data); - _resident_data = NULL; + _resident_data = nullptr; _reserved_size = 0; } if (reserved_size != 0) { - nassertv(_resident_data == (unsigned char *)NULL); + nassertv(_resident_data == nullptr); _resident_data = (unsigned char *)get_class_type().allocate_array(reserved_size); } @@ -151,30 +151,30 @@ do_unclean_realloc(size_t reserved_size) { */ void VertexDataBuffer:: do_page_out(VertexDataBook &book) { - if (_block != (VertexDataBlock *)NULL || _reserved_size == 0) { + if (_block != nullptr || _reserved_size == 0) { // We're already paged out. return; } - nassertv(_resident_data != (unsigned char *)NULL); + nassertv(_resident_data != nullptr); if (_size == 0) { // It's an empty buffer. Just deallocate it; don't bother to create a // block. get_class_type().deallocate_array(_resident_data); - _resident_data = NULL; + _resident_data = nullptr; _reserved_size = 0; } else { // It's a nonempty buffer, so write _size bytes (but not the full // _reserved_size bytes) to a block. _block = book.alloc(_size); - nassertv(_block != (VertexDataBlock *)NULL); + nassertv(_block != nullptr); unsigned char *pointer = _block->get_pointer(true); - nassertv(pointer != (unsigned char *)NULL); + nassertv(pointer != nullptr); memcpy(pointer, _resident_data, _size); get_class_type().deallocate_array(_resident_data); - _resident_data = NULL; + _resident_data = nullptr; _reserved_size = _size; } @@ -189,16 +189,16 @@ do_page_out(VertexDataBook &book) { */ void VertexDataBuffer:: do_page_in() { - if (_resident_data != (unsigned char *)NULL || _reserved_size == 0) { + if (_resident_data != nullptr || _reserved_size == 0) { // We're already paged in. return; } - nassertv(_block != (VertexDataBlock *)NULL); + nassertv(_block != nullptr); nassertv(_reserved_size == _size); _resident_data = (unsigned char *)get_class_type().allocate_array(_size); - nassertv(_resident_data != (unsigned char *)NULL); + nassertv(_resident_data != nullptr); memcpy(_resident_data, _block->get_pointer(true), _size); } diff --git a/panda/src/gobj/vertexDataPage.I b/panda/src/gobj/vertexDataPage.I index 0dd8109adb..d5dc44be9e 100644 --- a/panda/src/gobj/vertexDataPage.I +++ b/panda/src/gobj/vertexDataPage.I @@ -81,7 +81,7 @@ get_book() const { */ INLINE SimpleLru *VertexDataPage:: get_global_lru(RamClass rclass) { - nassertr(rclass >= 0 && rclass < RC_end_of_list, NULL); + nassertr(rclass >= 0 && rclass < RC_end_of_list, nullptr); return _global_lru[rclass]; } @@ -100,7 +100,7 @@ get_pending_lru() { */ INLINE VertexDataSaveFile *VertexDataPage:: get_save_file() { - if (_save_file == (VertexDataSaveFile *)NULL) { + if (_save_file == nullptr) { make_save_file(); } return _save_file; @@ -126,7 +126,7 @@ save_to_disk() { INLINE int VertexDataPage:: get_num_threads() { MutexHolder holder(_tlock); - if (_thread_mgr == (PageThreadManager *)NULL) { + if (_thread_mgr == nullptr) { return 0; } return _thread_mgr->get_num_threads(); @@ -139,7 +139,7 @@ get_num_threads() { INLINE int VertexDataPage:: get_num_pending_reads() { MutexHolder holder(_tlock); - if (_thread_mgr == (PageThreadManager *)NULL) { + if (_thread_mgr == nullptr) { return 0; } return _thread_mgr->get_num_pending_reads(); @@ -152,7 +152,7 @@ get_num_pending_reads() { INLINE int VertexDataPage:: get_num_pending_writes() { MutexHolder holder(_tlock); - if (_thread_mgr == (PageThreadManager *)NULL) { + if (_thread_mgr == nullptr) { return 0; } return _thread_mgr->get_num_pending_writes(); @@ -175,7 +175,7 @@ get_page_data(bool force) { } else { request_ram_class(RC_resident); if (_ram_class != RC_resident) { - return NULL; + return nullptr; } } } diff --git a/panda/src/gobj/vertexDataPage.cxx b/panda/src/gobj/vertexDataPage.cxx index ada598b9df..74e58edb58 100644 --- a/panda/src/gobj/vertexDataPage.cxx +++ b/panda/src/gobj/vertexDataPage.cxx @@ -109,9 +109,9 @@ VertexDataPage(size_t book_size) : SimpleLruPage(book_size), _book_size(book_size), _block_size(0), - _book(NULL) + _book(nullptr) { - _page_data = NULL; + _page_data = nullptr; _size = 0; _uncompressed_size = 0; _ram_class = RC_resident; @@ -150,17 +150,17 @@ VertexDataPage:: { MutexHolder holder2(_tlock); if (_pending_ram_class != _ram_class) { - nassertv(_thread_mgr != (PageThreadManager *)NULL); + nassertv(_thread_mgr != nullptr); _thread_mgr->remove_page(this); } } - if (_page_data != NULL) { + if (_page_data != nullptr) { free_page_data(_page_data, _allocated_size); _size = 0; } - nassertv(_book == NULL); + nassertv(_book == nullptr); } /** @@ -176,7 +176,7 @@ stop_threads() { _thread_mgr.clear(); } - if (thread_mgr != (PageThreadManager *)NULL) { + if (thread_mgr != nullptr) { gobj_cat.info() << "Stopping vertex paging threads.\n"; thread_mgr->stop_threads(); @@ -200,7 +200,7 @@ flush_threads() { thread_mgr = _thread_mgr; } - if (thread_mgr != (PageThreadManager *)NULL) { + if (thread_mgr != nullptr) { thread_mgr->stop_threads(); MutexHolder holder(_tlock); thread_mgr->start_threads(num_threads); @@ -211,7 +211,7 @@ flush_threads() { * */ void VertexDataPage:: -output(ostream &out) const { +output(std::ostream &out) const { SimpleAllocator::output(out); } @@ -219,7 +219,7 @@ output(ostream &out) const { * */ void VertexDataPage:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { SimpleAllocator::write(out); } @@ -244,7 +244,7 @@ changed_contiguous() { VertexDataBook::Pages::iterator pi = _book->_pages.find(this); nassertv(pi != _book->_pages.end()); _book->_pages.erase(pi); - _book = NULL; + _book = nullptr; delete this; return; } @@ -301,7 +301,7 @@ VertexDataBlock *VertexDataPage:: do_alloc(size_t size) { VertexDataBlock *block = (VertexDataBlock *)SimpleAllocator::do_alloc(size); - if (block != (VertexDataBlock *)NULL && _ram_class != RC_disk) { + if (block != nullptr && _ram_class != RC_disk) { // When we allocate a new block within a resident page, we have to clear // the disk cache (since we have just invalidated it). _saved_block.clear(); @@ -321,7 +321,7 @@ void VertexDataPage:: make_resident_now() { MutexHolder holder(_tlock); if (_pending_ram_class != _ram_class) { - nassertv(_thread_mgr != (PageThreadManager *)NULL); + nassertv(_thread_mgr != nullptr); _thread_mgr->remove_page(this); } @@ -391,7 +391,7 @@ make_resident() { while (result != Z_STREAM_END) { unsigned char *start_out = (unsigned char *)z_source.next_out; nassertv(start_out < end_data); - z_source.avail_out = min((size_t)(end_data - start_out), (size_t)inflate_page_size); + z_source.avail_out = std::min((size_t)(end_data - start_out), (size_t)inflate_page_size); nassertv(z_source.avail_out != 0); result = inflate(&z_source, flush); if (result < 0 && result != Z_BUF_ERROR) { @@ -522,7 +522,7 @@ make_compressed() { size_t copied_size = 0; unsigned char *p = new_data; page = head; - while (page != NULL) { + while (page != nullptr) { memcpy(p, page->_buffer, page->_used_size); copied_size += page->_used_size; p += page->_used_size; @@ -573,7 +573,7 @@ make_disk() { } free_page_data(_page_data, _allocated_size); - _page_data = NULL; + _page_data = nullptr; _size = 0; set_ram_class(RC_disk); @@ -593,7 +593,7 @@ do_save_to_disk() { if (_ram_class == RC_resident || _ram_class == RC_compressed) { PStatTimer timer(_vdata_save_pcollector); - if (_saved_block == (VertexDataSaveBlock *)NULL) { + if (_saved_block == nullptr) { if (gobj_cat.is_debug()) { gobj_cat.debug() << "Storing page, " << _size << " bytes, to disk\n"; @@ -602,7 +602,7 @@ do_save_to_disk() { bool compressed = (_ram_class == RC_compressed); _saved_block = get_save_file()->write_data(_page_data, _allocated_size, compressed); - if (_saved_block == (VertexDataSaveBlock *)NULL) { + if (_saved_block == nullptr) { // Can't write it to disk. Too bad. return false; } @@ -626,8 +626,8 @@ do_save_to_disk() { void VertexDataPage:: do_restore_from_disk() { if (_ram_class == RC_disk) { - nassertv(_saved_block != (VertexDataSaveBlock *)NULL); - nassertv(_page_data == (unsigned char *)NULL && _size == 0); + nassertv(_saved_block != nullptr); + nassertv(_page_data == nullptr && _size == 0); PStatTimer timer(_vdata_restore_pcollector); @@ -643,7 +643,7 @@ do_restore_from_disk() { nassert_raise("read error"); } - nassertv(_page_data == (unsigned char *)NULL); + nassertv(_page_data == nullptr); _page_data = new_data; _size = buffer_size; _allocated_size = new_allocated_size; @@ -669,7 +669,7 @@ adjust_book_size() { new_size = 0; } - if (_book != (VertexDataBook *)NULL && new_size != _book_size) { + if (_book != nullptr && new_size != _book_size) { VertexDataBook::Pages::iterator pi = _book->_pages.find(this); nassertv(pi != _book->_pages.end()); _book->_pages.erase(pi); @@ -713,7 +713,7 @@ request_ram_class(RamClass ram_class) { } MutexHolder holder(_tlock); - if (_thread_mgr == (PageThreadManager *)NULL) { + if (_thread_mgr == nullptr) { // Create the thread manager. gobj_cat.info() << "Spawning " << num_threads << " vertex paging threads.\n"; @@ -812,7 +812,7 @@ add_page(VertexDataPage *page, RamClass ram_class) { */ void VertexDataPage::PageThreadManager:: remove_page(VertexDataPage *page) { - nassertv(page != (VertexDataPage *)NULL); + nassertv(page != nullptr); PageThreads::iterator ti; for (ti = _threads.begin(); ti != _threads.end(); ++ti) { @@ -884,7 +884,7 @@ start_threads(int num_threads) { _threads.reserve(num_threads); for (int i = 0; i < num_threads; ++i) { - ostringstream name_strm; + std::ostringstream name_strm; name_strm << "VertexDataPage" << _threads.size(); PT(PageThread) thread = new PageThread(this, name_strm.str()); thread->start(TP_low, true); @@ -919,7 +919,7 @@ stop_threads() { * */ VertexDataPage::PageThread:: -PageThread(PageThreadManager *manager, const string &name) : +PageThread(PageThreadManager *manager, const std::string &name) : Thread(name, name), _manager(manager), _working_cvar(_tlock) @@ -980,7 +980,7 @@ thread_main() { _tlock.acquire(); - _working_page = NULL; + _working_page = nullptr; _working_cvar.notify(); Thread::consider_yield(); diff --git a/panda/src/gobj/vertexDataPage.h b/panda/src/gobj/vertexDataPage.h index 4c7fd02bf2..bceca6adea 100644 --- a/panda/src/gobj/vertexDataPage.h +++ b/panda/src/gobj/vertexDataPage.h @@ -74,8 +74,8 @@ PUBLISHED: static void stop_threads(); static void flush_threads(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; public: INLINE unsigned char *get_page_data(bool force); @@ -114,7 +114,7 @@ private: class PageThreadManager; class EXPCL_PANDA_GOBJ PageThread : public Thread { public: - PageThread(PageThreadManager *manager, const string &name); + PageThread(PageThreadManager *manager, const std::string &name); protected: virtual void thread_main(); @@ -176,7 +176,7 @@ private: public: DeflatePage() { _used_size = 0; - _next = NULL; + _next = nullptr; } ALLOC_DELETED_CHAIN(DeflatePage); @@ -228,7 +228,7 @@ private: friend class VertexDataBook; }; -inline ostream &operator << (ostream &out, const VertexDataPage &page) { +inline std::ostream &operator << (std::ostream &out, const VertexDataPage &page) { page.output(out); return out; } diff --git a/panda/src/gobj/vertexDataSaveFile.cxx b/panda/src/gobj/vertexDataSaveFile.cxx index fd7087ba5d..37839099dc 100644 --- a/panda/src/gobj/vertexDataSaveFile.cxx +++ b/panda/src/gobj/vertexDataSaveFile.cxx @@ -23,16 +23,19 @@ #include #endif // _WIN32 -#if defined(__ANDROID__) && !defined(HAVE_LOCKF) +#if defined(__ANDROID__) && !defined(PHAVE_LOCKF) // Needed for flock. #include #endif +using std::dec; +using std::hex; + /** * */ VertexDataSaveFile:: -VertexDataSaveFile(const Filename &directory, const string &prefix, +VertexDataSaveFile(const Filename &directory, const std::string &prefix, size_t max_size) : SimpleAllocator(max_size, _lock) { @@ -50,12 +53,12 @@ VertexDataSaveFile(const Filename &directory, const string &prefix, int index = 0; while (true) { ++index; - ostringstream strm; + std::ostringstream strm; strm << prefix << "_" << index << ".dat"; - string basename = strm.str(); + std::string basename = strm.str(); _filename = Filename(dir, basename); - string os_specific = _filename.to_os_specific(); + std::string os_specific = _filename.to_os_specific(); if (gobj_cat.is_debug()) { gobj_cat.debug() @@ -70,7 +73,7 @@ VertexDataSaveFile(const Filename &directory, const string &prefix, flags |= FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING; #endif _handle = CreateFile(os_specific.c_str(), GENERIC_READ | GENERIC_WRITE, - 0, NULL, CREATE_ALWAYS, flags, NULL); + 0, nullptr, CREATE_ALWAYS, flags, nullptr); if (_handle != INVALID_HANDLE_VALUE) { // The file was successfully opened and locked. break; @@ -130,7 +133,7 @@ VertexDataSaveFile(const Filename &directory, const string &prefix, // Now try to lock the file, so we can be sure that no other process is // simultaneously writing to the same save file. -#ifdef HAVE_LOCKF +#ifdef PHAVE_LOCKF int result = lockf(_fd, F_TLOCK, 0); #else int result = flock(_fd, LOCK_EX | LOCK_NB); @@ -167,7 +170,7 @@ VertexDataSaveFile(const Filename &directory, const string &prefix, VertexDataSaveFile:: ~VertexDataSaveFile() { #ifdef _WIN32 - if (_handle != NULL) { + if (_handle != nullptr) { CloseHandle(_handle); } #else @@ -196,12 +199,12 @@ write_data(const unsigned char *data, size_t size, bool compressed) { MutexHolder holder(_lock); if (!_is_valid) { - return NULL; + return nullptr; } PT(VertexDataSaveBlock) block = (VertexDataSaveBlock *)SimpleAllocator::do_alloc(size); - if (block != (VertexDataSaveBlock *)NULL) { - _total_file_size = max(_total_file_size, block->get_start() + size); + if (block != nullptr) { + _total_file_size = std::max(_total_file_size, block->get_start() + size); block->set_compressed(compressed); #ifdef _WIN32 @@ -224,11 +227,11 @@ write_data(const unsigned char *data, size_t size, bool compressed) { << "Error writing " << size << " bytes to save file, windows error code 0x" << hex << error << dec << ". Disk full?\n"; - return NULL; + return nullptr; } success = GetOverlappedResult(_handle, &overlapped, &bytes_written, false); } - nassertr(bytes_written == size, NULL); + nassertr(bytes_written == size, nullptr); double finish_time = ClockObject::get_global_clock()->get_real_time(); if (gobj_cat.is_debug()) { gobj_cat.debug() @@ -239,7 +242,7 @@ write_data(const unsigned char *data, size_t size, bool compressed) { if (lseek(_fd, block->get_start(), SEEK_SET) == -1) { gobj_cat.error() << "Error seeking to position " << block->get_start() << " in save file.\n"; - return NULL; + return nullptr; } while (size > 0) { @@ -250,7 +253,7 @@ write_data(const unsigned char *data, size_t size, bool compressed) { } else { gobj_cat.error() << "Error writing " << size << " bytes to save file. Disk full?\n"; - return NULL; + return nullptr; } continue; } @@ -306,11 +309,11 @@ read_data(unsigned char *data, size_t size, VertexDataSaveBlock *block) { << "Error reading " << size << " bytes from save file, windows error code 0x" << hex << error << dec << ".\n"; - return NULL; + return false; } success = GetOverlappedResult(_handle, &overlapped, &bytes_read, false); } - nassertr(bytes_read == size, NULL); + nassertr(bytes_read == size, nullptr); double finish_time = ClockObject::get_global_clock()->get_real_time(); if (gobj_cat.is_debug()) { gobj_cat.debug() diff --git a/panda/src/gobj/vertexDataSaveFile.h b/panda/src/gobj/vertexDataSaveFile.h index d71708227a..56eac67ee3 100644 --- a/panda/src/gobj/vertexDataSaveFile.h +++ b/panda/src/gobj/vertexDataSaveFile.h @@ -35,7 +35,7 @@ class VertexDataSaveBlock; */ class EXPCL_PANDA_GOBJ VertexDataSaveFile : public SimpleAllocator { public: - VertexDataSaveFile(const Filename &directory, const string &prefix, + VertexDataSaveFile(const Filename &directory, const std::string &prefix, size_t max_size); ~VertexDataSaveFile(); diff --git a/panda/src/gobj/vertexSlider.I b/panda/src/gobj/vertexSlider.I index 2d48a56e29..faad108d69 100644 --- a/panda/src/gobj/vertexSlider.I +++ b/panda/src/gobj/vertexSlider.I @@ -47,8 +47,8 @@ CData(const VertexSlider::CData ©) : { } -INLINE ostream & -operator << (ostream &out, const VertexSlider &obj) { +INLINE std::ostream & +operator << (std::ostream &out, const VertexSlider &obj) { obj.output(out); return out; } diff --git a/panda/src/gobj/vertexSlider.cxx b/panda/src/gobj/vertexSlider.cxx index 86d841ad53..bc05232eb2 100644 --- a/panda/src/gobj/vertexSlider.cxx +++ b/panda/src/gobj/vertexSlider.cxx @@ -40,7 +40,7 @@ VertexSlider:: * */ void VertexSlider:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << " " << *get_name(); } @@ -48,7 +48,7 @@ output(ostream &out) const { * */ void VertexSlider:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << *this << " = " << get_slider() << "\n"; } diff --git a/panda/src/gobj/vertexSlider.h b/panda/src/gobj/vertexSlider.h index 7c3c135292..649fab72fb 100644 --- a/panda/src/gobj/vertexSlider.h +++ b/panda/src/gobj/vertexSlider.h @@ -47,8 +47,8 @@ PUBLISHED: MAKE_PROPERTY(slider, get_slider); MAKE_PROPERTY(modified, get_modified); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; protected: void mark_modified(Thread *current_thread); @@ -106,7 +106,7 @@ private: friend class SliderTable; }; -INLINE ostream &operator << (ostream &out, const VertexSlider &obj); +INLINE std::ostream &operator << (std::ostream &out, const VertexSlider &obj); #include "vertexSlider.I" diff --git a/panda/src/gobj/vertexTransform.I b/panda/src/gobj/vertexTransform.I index cf7830c296..57fd7dd939 100644 --- a/panda/src/gobj/vertexTransform.I +++ b/panda/src/gobj/vertexTransform.I @@ -48,8 +48,8 @@ CData(const VertexTransform::CData ©) : { } -INLINE ostream & -operator << (ostream &out, const VertexTransform &obj) { +INLINE std::ostream & +operator << (std::ostream &out, const VertexTransform &obj) { obj.output(out); return out; } diff --git a/panda/src/gobj/vertexTransform.cxx b/panda/src/gobj/vertexTransform.cxx index 35a60bd25a..972584b527 100644 --- a/panda/src/gobj/vertexTransform.cxx +++ b/panda/src/gobj/vertexTransform.cxx @@ -68,7 +68,7 @@ accumulate_matrix(LMatrix4 &accum, PN_stdfloat weight) const { * */ void VertexTransform:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type(); } @@ -76,7 +76,7 @@ output(ostream &out) const { * */ void VertexTransform:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << *this << ":\n"; LMatrix4 mat; diff --git a/panda/src/gobj/vertexTransform.h b/panda/src/gobj/vertexTransform.h index 51e84c9edb..86a663c9b3 100644 --- a/panda/src/gobj/vertexTransform.h +++ b/panda/src/gobj/vertexTransform.h @@ -44,8 +44,8 @@ PUBLISHED: INLINE UpdateSeq get_modified(Thread *current_thread = Thread::get_current_thread()) const; MAKE_PROPERTY(modified, get_modified); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; static UpdateSeq get_next_modified(Thread *current_thread); INLINE static UpdateSeq get_global_modified(Thread *current_thread); @@ -67,6 +67,7 @@ private: virtual int complete_pointers(TypedWritable **plist, BamReader *manager); virtual void fillin(DatagramIterator &scan, BamReader *manager); virtual TypeHandle get_parent_type() const { + VertexTransform::init_type(); return VertexTransform::get_class_type(); } @@ -106,7 +107,7 @@ private: friend class TransformTable; }; -INLINE ostream &operator << (ostream &out, const VertexTransform &obj); +INLINE std::ostream &operator << (std::ostream &out, const VertexTransform &obj); #include "vertexTransform.I" diff --git a/panda/src/gobj/videoTexture.cxx b/panda/src/gobj/videoTexture.cxx index 0cde2d98f6..a3b5e2c72b 100644 --- a/panda/src/gobj/videoTexture.cxx +++ b/panda/src/gobj/videoTexture.cxx @@ -23,7 +23,7 @@ TypeHandle VideoTexture::_type_handle; * */ VideoTexture:: -VideoTexture(const string &name) : +VideoTexture(const std::string &name) : Texture(name) { // We don't want to try to compress each frame as it's loaded. @@ -104,8 +104,8 @@ set_video_size(int video_width, int video_height) { Texture::CDWriter cdata(Texture::_cycler, true); do_set_pad_size(cdata, - max(cdata->_x_size - _video_width, 0), - max(cdata->_y_size - _video_height, 0), + std::max(cdata->_x_size - _video_width, 0), + std::max(cdata->_y_size - _video_height, 0), 0); } @@ -181,7 +181,7 @@ do_can_reload(const Texture::CData *cdata) const { */ bool VideoTexture:: do_adjust_this_size(const Texture::CData *cdata_tex, - int &x_size, int &y_size, const string &name, + int &x_size, int &y_size, const std::string &name, bool for_padding) const { AutoTextureScale ats = do_get_auto_texture_scale(cdata_tex); if (ats != ATS_none) { diff --git a/panda/src/gobj/videoTexture.h b/panda/src/gobj/videoTexture.h index 755bc763c1..b9a0b4540e 100644 --- a/panda/src/gobj/videoTexture.h +++ b/panda/src/gobj/videoTexture.h @@ -27,7 +27,7 @@ */ class EXPCL_PANDA_GOBJ VideoTexture : public Texture, public AnimInterface { protected: - VideoTexture(const string &name); + VideoTexture(const std::string &name); VideoTexture(const VideoTexture ©); PUBLISHED: @@ -53,7 +53,7 @@ protected: virtual bool do_can_reload(const Texture::CData *cdata) const; virtual bool do_adjust_this_size(const Texture::CData *cdata, - int &x_size, int &y_size, const string &name, + int &x_size, int &y_size, const std::string &name, bool for_padding) const; virtual void consider_update(); diff --git a/panda/src/grutil/cardMaker.I b/panda/src/grutil/cardMaker.I index 8d051a72bc..b960808ca0 100644 --- a/panda/src/grutil/cardMaker.I +++ b/panda/src/grutil/cardMaker.I @@ -15,7 +15,7 @@ * */ INLINE CardMaker:: -CardMaker(const string &name) : Namable(name) { +CardMaker(const std::string &name) : Namable(name) { reset(); } @@ -134,5 +134,5 @@ set_source_geometry(PandaNode *node, const LVecBase4 &frame) { */ INLINE void CardMaker:: clear_source_geometry() { - _source_geometry = (PandaNode *)NULL; + _source_geometry = nullptr; } diff --git a/panda/src/grutil/cardMaker.cxx b/panda/src/grutil/cardMaker.cxx index ddfeae6947..33f6fc88ad 100644 --- a/panda/src/grutil/cardMaker.cxx +++ b/panda/src/grutil/cardMaker.cxx @@ -33,7 +33,7 @@ reset() { _color.set(1.0f, 1.0f, 1.0f, 1.0f); _has_normals = true; - _source_geometry = (PandaNode *)NULL; + _source_geometry = nullptr; _source_frame.set(0.0f, 0.0f, 0.0f, 0.0f); } @@ -43,7 +43,7 @@ reset() { */ PT(PandaNode) CardMaker:: generate() { - if (_source_geometry != (PandaNode *)NULL) { + if (_source_geometry != nullptr) { return rescale_source_geometry(); } @@ -133,7 +133,7 @@ generate() { gnode->add_geom(geom, state); - return gnode.p(); + return gnode; } /** diff --git a/panda/src/grutil/cardMaker.h b/panda/src/grutil/cardMaker.h index ff8e6e2eb6..426fc2d5c5 100644 --- a/panda/src/grutil/cardMaker.h +++ b/panda/src/grutil/cardMaker.h @@ -28,7 +28,7 @@ */ class EXPCL_PANDA_GRUTIL CardMaker : public Namable { PUBLISHED: - INLINE explicit CardMaker(const string &name); + INLINE explicit CardMaker(const std::string &name); INLINE ~CardMaker(); void reset(); diff --git a/panda/src/grutil/fisheyeMaker.I b/panda/src/grutil/fisheyeMaker.I index c567e9e43e..54085a23e0 100644 --- a/panda/src/grutil/fisheyeMaker.I +++ b/panda/src/grutil/fisheyeMaker.I @@ -15,7 +15,7 @@ * */ INLINE FisheyeMaker:: -FisheyeMaker(const string &name) : Namable(name) { +FisheyeMaker(const std::string &name) : Namable(name) { reset(); } diff --git a/panda/src/grutil/fisheyeMaker.cxx b/panda/src/grutil/fisheyeMaker.cxx index f245242aec..5e7d7395ec 100644 --- a/panda/src/grutil/fisheyeMaker.cxx +++ b/panda/src/grutil/fisheyeMaker.cxx @@ -177,7 +177,7 @@ generate() { int piece_size = max_vertices_per_primitive / 2 - 1; int vi = 0; while (vi < ring_size) { - int piece_end = min(ring_size + 1, piece_size + 1 + vi); + int piece_end = std::min(ring_size + 1, piece_size + 1 + vi); for (int pi = vi; pi < piece_end; ++pi) { tristrips->add_vertex(last_ring_vertex + pi % last_ring_size); tristrips->add_vertex(ring_vertex + pi % ring_size); @@ -284,7 +284,7 @@ generate() { int piece_size = max_vertices_per_primitive / 2 - 1; int vi = 0; while (vi < ring_size) { - int piece_end = min(ring_size + 1, piece_size + 1 + vi); + int piece_end = std::min(ring_size + 1, piece_size + 1 + vi); for (int pi = vi; pi < piece_end; ++pi) { tristrips->add_vertex(last_ring_vertex + pi % last_ring_size); tristrips->add_vertex(ring_vertex + pi % ring_size); @@ -322,7 +322,7 @@ generate() { } } - return geom_node.p(); + return geom_node; } /** diff --git a/panda/src/grutil/fisheyeMaker.h b/panda/src/grutil/fisheyeMaker.h index d6bb5b7a73..83aa118ac3 100644 --- a/panda/src/grutil/fisheyeMaker.h +++ b/panda/src/grutil/fisheyeMaker.h @@ -33,7 +33,7 @@ class GeomVertexWriter; */ class EXPCL_PANDA_GRUTIL FisheyeMaker : public Namable { PUBLISHED: - INLINE explicit FisheyeMaker(const string &name); + INLINE explicit FisheyeMaker(const std::string &name); INLINE ~FisheyeMaker(); void reset(); diff --git a/panda/src/grutil/frameRateMeter.I b/panda/src/grutil/frameRateMeter.I index 744ed17d49..02877fa226 100644 --- a/panda/src/grutil/frameRateMeter.I +++ b/panda/src/grutil/frameRateMeter.I @@ -56,7 +56,7 @@ get_update_interval() const { * per second. */ INLINE void FrameRateMeter:: -set_text_pattern(const string &text_pattern) { +set_text_pattern(const std::string &text_pattern) { _text_pattern = text_pattern; Thread *current_thread = Thread::get_current_thread(); do_update(current_thread); @@ -65,7 +65,7 @@ set_text_pattern(const string &text_pattern) { /** * Returns the sprintf() pattern that is used to format the text. */ -INLINE const string &FrameRateMeter:: +INLINE const std::string &FrameRateMeter:: get_text_pattern() const { return _text_pattern; } diff --git a/panda/src/grutil/frameRateMeter.cxx b/panda/src/grutil/frameRateMeter.cxx index 044a87a9a9..f015e0ab55 100644 --- a/panda/src/grutil/frameRateMeter.cxx +++ b/panda/src/grutil/frameRateMeter.cxx @@ -31,7 +31,7 @@ TypeHandle FrameRateMeter::_type_handle; * */ FrameRateMeter:: -FrameRateMeter(const string &name) : +FrameRateMeter(const std::string &name) : TextNode(name), _last_aspect_ratio(-1) { @@ -58,7 +58,7 @@ FrameRateMeter(const string &name) : // calculation within TextAssembler. PN_stdfloat height = 1.0f; TextFont *font = get_font(); - if (font != NULL){ + if (font != nullptr){ height = font->get_line_height() * 0.8; } @@ -134,10 +134,10 @@ setup_window(GraphicsOutput *window) { */ void FrameRateMeter:: clear_window() { - if (_window != (GraphicsOutput *)NULL) { + if (_window != nullptr) { _window->remove_display_region(_display_region); - _window = (GraphicsOutput *)NULL; - _display_region = (DisplayRegion *)NULL; + _window = nullptr; + _display_region = nullptr; } _root = NodePath(); } @@ -164,7 +164,7 @@ bool FrameRateMeter:: cull_callback(CullTraverser *trav, CullTraverserData &data) { // This triggers when you try to parent a frame rate meter into the scene // graph yourself. Instead, use setup_window(). - nassertr(_display_region != NULL, false); + nassertr(_display_region != nullptr, false); Thread *current_thread = trav->get_current_thread(); diff --git a/panda/src/grutil/frameRateMeter.h b/panda/src/grutil/frameRateMeter.h index 2e3f657819..5faa692a43 100644 --- a/panda/src/grutil/frameRateMeter.h +++ b/panda/src/grutil/frameRateMeter.h @@ -36,7 +36,7 @@ class ClockObject; */ class EXPCL_PANDA_GRUTIL FrameRateMeter : public TextNode { PUBLISHED: - explicit FrameRateMeter(const string &name); + explicit FrameRateMeter(const std::string &name); virtual ~FrameRateMeter(); void setup_window(GraphicsOutput *window); @@ -48,8 +48,8 @@ PUBLISHED: INLINE void set_update_interval(double update_interval); INLINE double get_update_interval() const; - INLINE void set_text_pattern(const string &text_pattern); - INLINE const string &get_text_pattern() const; + INLINE void set_text_pattern(const std::string &text_pattern); + INLINE const std::string &get_text_pattern() const; INLINE void set_clock_object(ClockObject *clock_object); INLINE ClockObject *get_clock_object() const; @@ -70,7 +70,7 @@ private: bool _show_milliseconds; double _update_interval; double _last_update; - string _text_pattern; + std::string _text_pattern; ClockObject *_clock_object; PN_stdfloat _last_aspect_ratio; diff --git a/panda/src/grutil/geoMipTerrain.I b/panda/src/grutil/geoMipTerrain.I index eb41d492fc..7eeeddab7a 100644 --- a/panda/src/grutil/geoMipTerrain.I +++ b/panda/src/grutil/geoMipTerrain.I @@ -17,7 +17,7 @@ * */ INLINE GeoMipTerrain:: -GeoMipTerrain(const string &name) { +GeoMipTerrain(const std::string &name) { _root = NodePath(name); _root_flattened = false; _xsize = 0; @@ -425,7 +425,7 @@ set_color_map(const Texture *tex) { } INLINE bool GeoMipTerrain:: -set_color_map(const string &path) { +set_color_map(const std::string &path) { return set_color_map(Filename(path)); } @@ -479,8 +479,8 @@ get_border_stitching() { */ INLINE double GeoMipTerrain:: get_pixel_value(int x, int y) { - x = max(min(x,int(_xsize-1)),0); - y = max(min(y,int(_ysize-1)),0); + x = std::max(std::min(x,int(_xsize-1)),0); + y = std::max(std::min(y,int(_ysize-1)),0); if (_heightfield.is_grayscale()) { return double(_heightfield.get_bright(x, y)); } else { diff --git a/panda/src/grutil/geoMipTerrain.cxx b/panda/src/grutil/geoMipTerrain.cxx index 0df3787086..457e55d901 100644 --- a/panda/src/grutil/geoMipTerrain.cxx +++ b/panda/src/grutil/geoMipTerrain.cxx @@ -29,6 +29,9 @@ #include "collideMask.h" +using std::max; +using std::min; + static ConfigVariableBool geomipterrain_incorrect_normals ("geomipterrain-incorrect-normals", false, PRC_DESC("If true, uses the incorrect normal vector calculation that " @@ -50,8 +53,8 @@ generate_block(unsigned short mx, unsigned short my, unsigned short level) { - nassertr(mx < (_xsize - 1) / _block_size, NULL); - nassertr(my < (_ysize - 1) / _block_size, NULL); + nassertr(mx < (_xsize - 1) / _block_size, nullptr); + nassertr(my < (_ysize - 1) / _block_size, nullptr); unsigned short center = _block_size / 2; unsigned int vcounter = 0; @@ -256,7 +259,7 @@ generate_block(unsigned short mx, geom->add_primitive(prim); geom->set_bounds_type(BoundingVolume::BT_box); - ostringstream sname; + std::ostringstream sname; sname << "gmm" << mx << "x" << my; PT(GeomNode) node = new GeomNode(sname.str()); node->add_geom(geom); diff --git a/panda/src/grutil/geoMipTerrain.h b/panda/src/grutil/geoMipTerrain.h index 88727e9077..0d0ce94da0 100644 --- a/panda/src/grutil/geoMipTerrain.h +++ b/panda/src/grutil/geoMipTerrain.h @@ -35,18 +35,18 @@ */ class EXPCL_PANDA_GRUTIL GeoMipTerrain : public TypedObject { PUBLISHED: - INLINE explicit GeoMipTerrain(const string &name); + INLINE explicit GeoMipTerrain(const std::string &name); INLINE ~GeoMipTerrain(); INLINE PNMImage &heightfield(); - bool set_heightfield(const Filename &filename, PNMFileType *type = NULL); + bool set_heightfield(const Filename &filename, PNMFileType *type = nullptr); INLINE bool set_heightfield(const PNMImage &image); INLINE PNMImage &color_map(); INLINE bool set_color_map(const Filename &filename, - PNMFileType *type = NULL); + PNMFileType *type = nullptr); INLINE bool set_color_map(const PNMImage &image); INLINE bool set_color_map(const Texture *image); - INLINE bool set_color_map(const string &path); + INLINE bool set_color_map(const std::string &path); INLINE bool has_color_map() const; INLINE void clear_color_map(); void calc_ambient_occlusion(PN_stdfloat radius = 32, PN_stdfloat contrast = 2.0f, PN_stdfloat brightness = 0.75f); diff --git a/panda/src/grutil/heightfieldTesselator.I b/panda/src/grutil/heightfieldTesselator.I index dee41354a1..7bab2b0a45 100644 --- a/panda/src/grutil/heightfieldTesselator.I +++ b/panda/src/grutil/heightfieldTesselator.I @@ -15,7 +15,7 @@ * */ INLINE HeightfieldTesselator:: -HeightfieldTesselator(const string &name) : Namable(name) { +HeightfieldTesselator(const std::string &name) : Namable(name) { _poly_count = 10000; _visibility_radius = 32768; _focal_x = 0; diff --git a/panda/src/grutil/heightfieldTesselator.cxx b/panda/src/grutil/heightfieldTesselator.cxx index 8106071ed7..58d8324521 100644 --- a/panda/src/grutil/heightfieldTesselator.cxx +++ b/panda/src/grutil/heightfieldTesselator.cxx @@ -175,9 +175,9 @@ generate() { delete[] _vertex_index; delete[] _dirty_vertices; delete[] _triangle_totals; - _vertex_index =0; - _dirty_vertices =0; - _triangle_totals =0; + _vertex_index =nullptr; + _dirty_vertices =nullptr; + _triangle_totals =nullptr; return root; } @@ -257,7 +257,7 @@ generate_square(NodePath root, int scale, int x, int y, bool forceclose) { #define POINTH get_vertex(x+hsize,y+size) #define POINTI get_vertex(x+size ,y+size) - if (_triangles == 0) { + if (_triangles == nullptr) { open_geom(); } if (subdivide(scale, x, y)) { @@ -376,7 +376,7 @@ open_geom() { */ void HeightfieldTesselator:: close_geom(NodePath root) { - if (_triangles == 0) { + if (_triangles == nullptr) { return; } _triangles->close_primitive(); @@ -395,7 +395,7 @@ close_geom(NodePath root) { _next_index = 0; _last_vertex_a = -1; _last_vertex_b = -1; - _vertex_writer = 0; - _normal_writer = 0; - _triangles = 0; + _vertex_writer = nullptr; + _normal_writer = nullptr; + _triangles = nullptr; } diff --git a/panda/src/grutil/heightfieldTesselator.h b/panda/src/grutil/heightfieldTesselator.h index 247d1de218..f2d358a82f 100644 --- a/panda/src/grutil/heightfieldTesselator.h +++ b/panda/src/grutil/heightfieldTesselator.h @@ -57,11 +57,11 @@ class EXPCL_PANDA_GRUTIL HeightfieldTesselator : public Namable { PUBLISHED: - INLINE explicit HeightfieldTesselator(const string &name); + INLINE explicit HeightfieldTesselator(const std::string &name); INLINE ~HeightfieldTesselator(); INLINE PNMImage &heightfield(); - INLINE bool set_heightfield(const Filename &filename, PNMFileType *type = NULL); + INLINE bool set_heightfield(const Filename &filename, PNMFileType *type = nullptr); INLINE void set_poly_count(int n); INLINE void set_visibility_radius(int r); INLINE void set_focal_point(int x, int y); diff --git a/panda/src/grutil/lineSegs.I b/panda/src/grutil/lineSegs.I index d9e8101c1c..5236f13b74 100644 --- a/panda/src/grutil/lineSegs.I +++ b/panda/src/grutil/lineSegs.I @@ -117,7 +117,7 @@ create(bool dynamic) { */ INLINE int LineSegs:: get_num_vertices() const { - if (_created_data == (GeomVertexData *)NULL) { + if (_created_data == nullptr) { return 0; } return _created_data->get_num_rows(); diff --git a/panda/src/grutil/lineSegs.cxx b/panda/src/grutil/lineSegs.cxx index 9bb54f40ab..534c1f5700 100644 --- a/panda/src/grutil/lineSegs.cxx +++ b/panda/src/grutil/lineSegs.cxx @@ -29,7 +29,7 @@ * which will render the described path. */ LineSegs:: -LineSegs(const string &name) : Namable(name) { +LineSegs(const std::string &name) : Namable(name) { _color.set(1.0f, 1.0f, 1.0f, 1.0f); _thick = 1.0f; } @@ -105,7 +105,7 @@ is_empty() { */ LVertex LineSegs:: get_vertex(int n) const { - nassertr(_created_data != (GeomVertexData *)NULL, LVertex::zero()); + nassertr(_created_data != nullptr, LVertex::zero()); GeomVertexReader vertex(_created_data, InternalName::get_vertex()); vertex.set_row_unsafe(n); return vertex.get_data3(); @@ -118,7 +118,7 @@ get_vertex(int n) const { */ void LineSegs:: set_vertex(int n, const LVertex &vert) { - nassertv(_created_data != (GeomVertexData *)NULL); + nassertv(_created_data != nullptr); GeomVertexWriter vertex(_created_data, InternalName::get_vertex()); vertex.set_row_unsafe(n); vertex.set_data3(vert); @@ -129,7 +129,7 @@ set_vertex(int n, const LVertex &vert) { */ LColor LineSegs:: get_vertex_color(int n) const { - nassertr(_created_data != (GeomVertexData *)NULL, LColor::zero()); + nassertr(_created_data != nullptr, LColor::zero()); GeomVertexReader color(_created_data, InternalName::get_color()); color.set_row_unsafe(n); return color.get_data4(); @@ -140,7 +140,7 @@ get_vertex_color(int n) const { */ void LineSegs:: set_vertex_color(int n, const LColor &c) { - nassertv(_created_data != (GeomVertexData *)NULL); + nassertv(_created_data != nullptr); GeomVertexWriter color(_created_data, InternalName::get_color()); color.set_row_unsafe(n); color.set_data4(c); diff --git a/panda/src/grutil/lineSegs.h b/panda/src/grutil/lineSegs.h index 174467da31..08bc56ab0e 100644 --- a/panda/src/grutil/lineSegs.h +++ b/panda/src/grutil/lineSegs.h @@ -32,7 +32,7 @@ */ class EXPCL_PANDA_GRUTIL LineSegs : public Namable { PUBLISHED: - explicit LineSegs(const string &name = "lines"); + explicit LineSegs(const std::string &name = "lines"); ~LineSegs(); void reset(); diff --git a/panda/src/grutil/meshDrawer.I b/panda/src/grutil/meshDrawer.I index 72a21bd504..030f646cb9 100644 --- a/panda/src/grutil/meshDrawer.I +++ b/panda/src/grutil/meshDrawer.I @@ -20,13 +20,13 @@ INLINE MeshDrawer:: MeshDrawer() { _root = NodePath("MeshDrawer"); _at_start = 0; - _bv = NULL; - _vertex = NULL; - _normal = NULL; - _uv = NULL; - _color = NULL; + _bv = nullptr; + _vertex = nullptr; + _normal = nullptr; + _uv = nullptr; + _color = nullptr; _budget = 5000; - _vdata = NULL; + _vdata = nullptr; } /** @@ -35,10 +35,10 @@ MeshDrawer() { INLINE MeshDrawer:: ~MeshDrawer() { _root.remove_node(); - if (_vertex != NULL) delete _vertex; - if (_normal != NULL) delete _normal; - if (_uv != NULL) delete _uv; - if (_color != NULL) delete _color; + if (_vertex != nullptr) delete _vertex; + if (_normal != nullptr) delete _normal; + if (_uv != nullptr) delete _uv; + if (_color != nullptr) delete _color; } /** diff --git a/panda/src/grutil/meshDrawer.cxx b/panda/src/grutil/meshDrawer.cxx index 57ac0d9590..b87380d3b8 100644 --- a/panda/src/grutil/meshDrawer.cxx +++ b/panda/src/grutil/meshDrawer.cxx @@ -71,7 +71,7 @@ void MeshDrawer::generator(int budget) { _prim->close_primitive(); _geom = new Geom(_vdata); _geom->add_primitive(_prim); - if (_geomnode == NULL) { + if (_geomnode == nullptr) { _geomnode = new GeomNode("__MeshDrawer_GeomNode"); _root.attach_new_node(_geomnode); } else { @@ -104,12 +104,12 @@ void MeshDrawer::begin(NodePath camera, NodePath render) { _b4 = - _right + _up; // recreate our rewriters - if (_vertex != NULL) delete _vertex; - if (_normal != NULL) delete _normal; - if (_uv != NULL) delete _uv; - if (_color != NULL) delete _color; + if (_vertex != nullptr) delete _vertex; + if (_normal != nullptr) delete _normal; + if (_uv != nullptr) delete _uv; + if (_color != nullptr) delete _color; - if (_vdata == NULL) { + if (_vdata == nullptr) { generator(_budget); } @@ -141,10 +141,10 @@ void MeshDrawer::end() { _last_clear_index = _clear_index; // delete the re writers - delete _vertex; _vertex = NULL; - delete _uv; _uv = NULL; - delete _normal; _normal = NULL; - delete _color; _color = NULL; + delete _vertex; _vertex = nullptr; + delete _uv; _uv = nullptr; + delete _normal; _normal = nullptr; + delete _color; _color = nullptr; } @@ -374,7 +374,7 @@ void MeshDrawer::geometry(NodePath draw_node) { CPT(GeomVertexData) v_data = geom->get_vertex_data(); GeomVertexReader *prim_vertex_reader = new GeomVertexReader(v_data, "vertex"); GeomVertexReader *prim_uv_reader = new GeomVertexReader(v_data, "texcoord"); - for(int k=0; k get_num_primitives(); k++) { + for (size_t k = 0; k < geom->get_num_primitives(); ++k) { CPT(GeomPrimitive) prim1 = geom->get_primitive(k); CPT(GeomPrimitive) _prim = prim1->decompose(); diff --git a/panda/src/grutil/meshDrawer.h b/panda/src/grutil/meshDrawer.h index 1b391210f6..e959b37c24 100644 --- a/panda/src/grutil/meshDrawer.h +++ b/panda/src/grutil/meshDrawer.h @@ -107,8 +107,6 @@ private: GeomVertexRewriter *_color; // billboard vectors - LVector4 _colorv; - LVector3 _normalv; LVector3 _eyePos; LVector3 _b1, _b2, _b3, _b4; LVector3 _up, _right; diff --git a/panda/src/grutil/meshDrawer2D.I b/panda/src/grutil/meshDrawer2D.I index 9846eda7ee..4ff460c567 100644 --- a/panda/src/grutil/meshDrawer2D.I +++ b/panda/src/grutil/meshDrawer2D.I @@ -19,10 +19,10 @@ INLINE MeshDrawer2D:: MeshDrawer2D() { _root = NodePath("MeshDrawer"); - _bv = NULL; - _vertex = NULL; - _uv = NULL; - _color = NULL; + _bv = nullptr; + _vertex = nullptr; + _uv = nullptr; + _color = nullptr; _budget = 5000; _clip_x = -1000000; @@ -37,9 +37,9 @@ MeshDrawer2D() { INLINE MeshDrawer2D:: ~MeshDrawer2D() { _root.remove_node(); - if (_vertex != NULL) delete _vertex; - if (_uv != NULL) delete _uv; - if (_color != NULL) delete _color; + if (_vertex != nullptr) delete _vertex; + if (_uv != nullptr) delete _uv; + if (_color != nullptr) delete _color; } /** diff --git a/panda/src/grutil/meshDrawer2D.cxx b/panda/src/grutil/meshDrawer2D.cxx index fbf99a2778..a34f4b7d34 100644 --- a/panda/src/grutil/meshDrawer2D.cxx +++ b/panda/src/grutil/meshDrawer2D.cxx @@ -88,9 +88,9 @@ void MeshDrawer2D::generator(int budget) { void MeshDrawer2D::begin() { // recreate our rewriters - if (_vertex != NULL) delete _vertex; - if (_uv != NULL) delete _uv; - if (_color != NULL) delete _color; + if (_vertex != nullptr) delete _vertex; + if (_uv != nullptr) delete _uv; + if (_color != nullptr) delete _color; _vertex = new GeomVertexRewriter(_vdata, "vertex"); _uv = new GeomVertexRewriter(_vdata, "texcoord"); @@ -120,9 +120,9 @@ void MeshDrawer2D::end() { _last_clear_index = _clear_index; // delete the re writers - delete _vertex; _vertex = NULL; - delete _uv; _uv = NULL; - delete _color; _color = NULL; + delete _vertex; _vertex = nullptr; + delete _uv; _uv = nullptr; + delete _color; _color = nullptr; } diff --git a/panda/src/grutil/movieTexture.I b/panda/src/grutil/movieTexture.I index d52220695e..9b3f6eceb8 100644 --- a/panda/src/grutil/movieTexture.I +++ b/panda/src/grutil/movieTexture.I @@ -49,7 +49,7 @@ get_video_height() const { INLINE MovieVideoCursor *MovieTexture:: get_color_cursor(int page) { CDReader cdata(_cycler); - nassertr(page >= 0 && page < (int)cdata->_pages.size(), NULL); + nassertr(page >= 0 && page < (int)cdata->_pages.size(), nullptr); return cdata->_pages[page]._color; } @@ -60,6 +60,6 @@ get_color_cursor(int page) { INLINE MovieVideoCursor *MovieTexture:: get_alpha_cursor(int page) { CDReader cdata(_cycler); - nassertr(page >= 0 && page < (int)cdata->_pages.size(), NULL); + nassertr(page >= 0 && page < (int)cdata->_pages.size(), nullptr); return cdata->_pages[page]._alpha; } diff --git a/panda/src/grutil/movieTexture.cxx b/panda/src/grutil/movieTexture.cxx index a2d8d3bc3a..36f4913085 100644 --- a/panda/src/grutil/movieTexture.cxx +++ b/panda/src/grutil/movieTexture.cxx @@ -35,7 +35,7 @@ TypeHandle MovieTexture::_type_handle; * do_load_one. */ MovieTexture:: -MovieTexture(const string &name) : +MovieTexture(const std::string &name) : Texture(name) { } @@ -48,7 +48,7 @@ MovieTexture(MovieVideo *video) : Texture(video->get_name()) { Texture::CDWriter cdata_tex(Texture::_cycler, true); - do_load_one(cdata_tex, video->open(), NULL, 0, LoaderOptions()); + do_load_one(cdata_tex, video->open(), nullptr, 0, LoaderOptions()); } /** @@ -92,17 +92,6 @@ make_copy() const { return new CData(*this); } -/** - * Use MovieTexture::make_copy() to make a duplicate copy of an existing - * MovieTexture. - */ -MovieTexture:: -MovieTexture(const MovieTexture ©) : - Texture(copy) -{ - nassertv(false); -} - /** * xxx */ @@ -152,6 +141,7 @@ void MovieTexture:: do_recalculate_image_properties(CData *cdata, Texture::CData *cdata_tex, const LoaderOptions &options) { int x_max = 1; int y_max = 1; + bool rgb = false; bool alpha = false; double len = 0.0; @@ -161,7 +151,8 @@ do_recalculate_image_properties(CData *cdata, Texture::CData *cdata_tex, const L if (t->size_x() > x_max) x_max = t->size_x(); if (t->size_y() > y_max) y_max = t->size_y(); if (t->length() > len) len = t->length(); - if (t->get_num_components() == 4) alpha=true; + if (t->get_num_components() >= 3) rgb=true; + if (t->get_num_components() == 4 || t->get_num_components() == 2) alpha=true; } t = cdata->_pages[i]._alpha; if (t) { @@ -178,15 +169,16 @@ do_recalculate_image_properties(CData *cdata, Texture::CData *cdata_tex, const L do_adjust_this_size(cdata_tex, x_max, y_max, get_name(), true); - do_reconsider_image_properties(cdata_tex, x_max, y_max, alpha?4:3, + int num_components = (rgb ? 3 : 1) + alpha; + do_reconsider_image_properties(cdata_tex, x_max, y_max, num_components, T_unsigned_byte, cdata->_pages.size(), options); cdata_tex->_orig_file_x_size = cdata->_video_width; cdata_tex->_orig_file_y_size = cdata->_video_height; do_set_pad_size(cdata_tex, - max(cdata_tex->_x_size - cdata_tex->_orig_file_x_size, 0), - max(cdata_tex->_y_size - cdata_tex->_orig_file_y_size, 0), + std::max(cdata_tex->_x_size - cdata_tex->_orig_file_x_size, 0), + std::max(cdata_tex->_y_size - cdata_tex->_orig_file_y_size, 0), 0); } @@ -196,7 +188,7 @@ do_recalculate_image_properties(CData *cdata, Texture::CData *cdata_tex, const L */ bool MovieTexture:: do_adjust_this_size(const Texture::CData *cdata_tex, - int &x_size, int &y_size, const string &name, + int &x_size, int &y_size, const std::string &name, bool for_padding) const { AutoTextureScale ats = do_get_auto_texture_scale(cdata_tex); if (ats != ATS_none) { @@ -222,7 +214,7 @@ do_read_one(Texture::CData *cdata_tex, } nassertr(z >= 0 && z < cdata_tex->_z_size * cdata_tex->_num_views, false); - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { record->add_dependent_file(fullpath); } @@ -230,12 +222,12 @@ do_read_one(Texture::CData *cdata_tex, PT(MovieVideoCursor) alpha; color = MovieVideo::get(fullpath)->open(); - if (color == 0) { + if (color == nullptr) { return false; } if (!alpha_fullpath.empty()) { alpha = MovieVideo::get(alpha_fullpath)->open(); - if (alpha == 0) { + if (alpha == nullptr) { return false; } } @@ -293,7 +285,18 @@ do_load_one(Texture::CData *cdata_tex, */ bool MovieTexture:: do_load_one(Texture::CData *cdata_tex, - const PNMImage &pnmimage, const string &name, int z, int n, + const PNMImage &pnmimage, const std::string &name, int z, int n, + const LoaderOptions &options) { + grutil_cat.error() << "You cannot load a static image into a MovieTexture\n"; + return false; +} + +/** + * Loading a static image into a MovieTexture is an error. + */ +bool MovieTexture:: +do_load_one(Texture::CData *cdata_tex, + const PfmFile &pfm, const std::string &name, int z, int n, const LoaderOptions &options) { grutil_cat.error() << "You cannot load a static image into a MovieTexture\n"; return false; @@ -337,7 +340,7 @@ cull_callback(CullTraverser *, const CullTraverserData &) const { // compute a new one. double offset; int true_loop_count = 1; - if (cdata->_synchronize != 0) { + if (cdata->_synchronize != nullptr) { offset = cdata->_synchronize->get_time(); } else { // Calculate the cursor position modulo the length of the movie. @@ -369,11 +372,11 @@ cull_callback(CullTraverser *, const CullTraverserData &) const { MovieVideoCursor *alpha = page._alpha; size_t i = pi - cdata->_pages.begin(); - if (color != NULL && alpha != NULL) { + if (color != nullptr && alpha != nullptr) { color->apply_to_texture_rgb(page._cbuffer, (MovieTexture*)this, i); alpha->apply_to_texture_alpha(page._abuffer, (MovieTexture*)this, i, cdata_tex->_alpha_file_channel); - } else if (color != NULL) { + } else if (color != nullptr) { color->apply_to_texture(page._cbuffer, (MovieTexture*)this, i); } @@ -398,7 +401,7 @@ cull_callback(CullTraverser *, const CullTraverserData &) const { * independently of the original. */ PT(Texture) MovieTexture:: -make_copy_impl() { +make_copy_impl() const { Texture::CDReader cdata_tex(Texture::_cycler); CDReader cdata(_cycler); PT(MovieTexture) copy = new MovieTexture(get_name()); @@ -406,7 +409,7 @@ make_copy_impl() { CDWriter cdata_copy(copy->_cycler, true); copy->do_assign(cdata_copy, cdata_copy_tex, this, cdata, cdata_tex); - return copy.p(); + return copy; } /** @@ -531,7 +534,7 @@ play() { void MovieTexture:: set_time(double t) { CDWriter cdata(_cycler); - t = min(cdata->_video_length, max(0.0, t)); + t = std::min(cdata->_video_length, std::max(0.0, t)); if (cdata->_playing) { double now = ClockObject::get_global_clock()->get_frame_time(); cdata->_clock = t - (now * cdata->_play_rate); @@ -645,7 +648,7 @@ synchronize_to(AudioSound *s) { void MovieTexture:: unsynchronize() { CDWriter cdata(_cycler); - cdata->_synchronize = 0; + cdata->_synchronize = nullptr; } @@ -668,12 +671,12 @@ do_update_frames(const CData *cdata) const { MovieVideoCursor *color = page._color; MovieVideoCursor *alpha = page._alpha; - if (color != NULL && page._cbuffer == NULL) { + if (color != nullptr && page._cbuffer == nullptr) { if (color->set_time(cdata->_offset, cdata->_true_loop_count)) { ((VideoPage &)page)._cbuffer = color->fetch_buffer(); } } - if (alpha != NULL && page._abuffer == NULL) { + if (alpha != nullptr && page._abuffer == nullptr) { if (alpha->set_time(cdata->_offset, cdata->_true_loop_count)) { ((VideoPage &)page)._abuffer = alpha->fetch_buffer(); } @@ -693,15 +696,15 @@ do_update_frames(const CData *cdata) const { PT(MovieVideoCursor::Buffer) newest; for (pi = cdata->_pages.begin(); pi != cdata->_pages.end(); ++pi) { const VideoPage &page = (*pi); - if (page._cbuffer == NULL) { - if (page._color != NULL) { + if (page._cbuffer == nullptr) { + if (page._color != nullptr) { // This page isn't ready at all. in_sync = false; } } else { - nassertr(page._color != NULL, true); + nassertr(page._color != nullptr, true); any_frames = true; - if (newest == NULL) { + if (newest == nullptr) { newest = page._cbuffer; } else { int ref = newest->compare_timestamp(page._cbuffer); @@ -715,14 +718,14 @@ do_update_frames(const CData *cdata) const { } } } - if (page._abuffer == NULL) { - if (page._alpha != NULL) { + if (page._abuffer == nullptr) { + if (page._alpha != nullptr) { in_sync = false; } } else { - nassertr(page._alpha != NULL, true); + nassertr(page._alpha != nullptr, true); any_frames = true; - if (newest == NULL) { + if (newest == nullptr) { newest = page._abuffer; } else { int ref = newest->compare_timestamp(page._abuffer); @@ -745,15 +748,15 @@ do_update_frames(const CData *cdata) const { if (!in_sync) { // If we're not in sync, throw away pages that are older than the newest // available frame. - if (newest != NULL) { + if (newest != nullptr) { Pages::const_iterator pi; for (pi = cdata->_pages.begin(); pi != cdata->_pages.end(); ++pi) { const VideoPage &page = (*pi); - if (page._cbuffer != NULL && newest->compare_timestamp(page._cbuffer) > 0) { + if (page._cbuffer != nullptr && newest->compare_timestamp(page._cbuffer) > 0) { ((VideoPage &)page)._cbuffer.clear(); any_dropped = true; } - if (page._abuffer != NULL && newest->compare_timestamp(page._abuffer) > 0) { + if (page._abuffer != nullptr && newest->compare_timestamp(page._abuffer) > 0) { ((VideoPage &)page)._abuffer.clear(); any_dropped = true; } diff --git a/panda/src/grutil/movieTexture.h b/panda/src/grutil/movieTexture.h index d719f21d87..1a49c885b1 100644 --- a/panda/src/grutil/movieTexture.h +++ b/panda/src/grutil/movieTexture.h @@ -32,11 +32,9 @@ */ class EXPCL_PANDA_GRUTIL MovieTexture : public Texture { PUBLISHED: - explicit MovieTexture(const string &name); + explicit MovieTexture(const std::string &name); explicit MovieTexture(MovieVideo *video); -private: - MovieTexture(const MovieTexture ©); -PUBLISHED: + MovieTexture(const MovieTexture ©) = delete; virtual ~MovieTexture(); INLINE double get_video_length() const; @@ -82,7 +80,7 @@ public: protected: class CData; - virtual PT(Texture) make_copy_impl(); + virtual PT(Texture) make_copy_impl() const; void do_assign(CData *cdata, Texture::CData *cdata_tex, const MovieTexture *copy, const CData *cdata_copy, const Texture::CData *cdata_copy_tex); @@ -93,7 +91,7 @@ protected: virtual bool do_can_reload(const Texture::CData *cdata) const; virtual bool do_adjust_this_size(const Texture::CData *cdata, - int &x_size, int &y_size, const string &name, + int &x_size, int &y_size, const std::string &name, bool for_padding) const; virtual bool do_read_one(Texture::CData *cdata, @@ -102,7 +100,10 @@ protected: const LoaderOptions &options, bool header_only, BamCacheRecord *record); virtual bool do_load_one(Texture::CData *cdata, - const PNMImage &pnmimage, const string &name, + const PNMImage &pnmimage, const std::string &name, + int z, int n, const LoaderOptions &options); + virtual bool do_load_one(Texture::CData *cdata, + const PfmFile &pfm, const std::string &name, int z, int n, const LoaderOptions &options); bool do_load_one(Texture::CData *cdata, PT(MovieVideoCursor) color, PT(MovieVideoCursor) alpha, diff --git a/panda/src/grutil/multitexReducer.cxx b/panda/src/grutil/multitexReducer.cxx index 8481444a2d..fdad25bb48 100644 --- a/panda/src/grutil/multitexReducer.cxx +++ b/panda/src/grutil/multitexReducer.cxx @@ -37,6 +37,9 @@ #include "geomVertexWriter.h" #include "geomVertexReader.h" +using std::max; +using std::min; + /** * */ @@ -236,12 +239,12 @@ flatten(GraphicsOutput *window) { window); static int multitex_id = 1; - ostringstream multitex_name_strm; + std::ostringstream multitex_name_strm; multitex_name_strm << "multitex" << multitex_id; multitex_id++; GraphicsOutput *buffer = window->make_texture_buffer - (multitex_name_strm.str(), x_size, y_size, NULL, false); + (multitex_name_strm.str(), x_size, y_size, nullptr, false); // TODO: this no longer automatically deletes the buffer. We need to take // care of this explicitly now. @@ -323,7 +326,7 @@ flatten(GraphicsOutput *window) { // first texture layer to apply only. nassertv(bake_in_color); PT(GeomNode) geom_node = new GeomNode("background"); - transfer_geom(geom_node, NULL, geom_list, true); + transfer_geom(geom_node, nullptr, geom_list, true); render.attach_new_node(geom_node); } @@ -362,7 +365,7 @@ flatten(GraphicsOutput *window) { const RenderAttrib *attrib = geom_info._geom_net_state->get_attrib(ColorScaleAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { geom_state = geom_state->add_attrib (attrib->invert_compose(ColorScaleAttrib::make_identity())); } @@ -372,7 +375,7 @@ flatten(GraphicsOutput *window) { CPT(TransformState) tex_mat = TransformState::make_identity(); const RenderAttrib *ra = geom_info._state->get_attrib(TexMatrixAttrib::get_class_slot()); - if (ra != (const RenderAttrib *)NULL) { + if (ra != nullptr) { // There is a texture matrix inherited from above; put an inverse // matrix on the Geom to compensate. const TexMatrixAttrib *tma = DCAST(TexMatrixAttrib, ra); @@ -437,19 +440,19 @@ scan_geom_node(GeomNode *node, const RenderState *state, if (grutil_cat.is_debug()) { grutil_cat.debug() << "geom " << gi << " net_state =\n"; - geom_net_state->write(cerr, 2); + geom_net_state->write(std::cerr, 2); } // Get out the net TextureAttrib and TexMatrixAttrib from the state. const RenderAttrib *attrib; - const TextureAttrib *ta = NULL; + const TextureAttrib *ta = nullptr; attrib = geom_net_state->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { ta = DCAST(TextureAttrib, attrib); } - if (ta == (TextureAttrib *)NULL) { + if (ta == nullptr) { // No texture should be on the Geom. CPT(RenderState) geom_state = node->get_geom_state(gi); geom_state = geom_state->remove_attrib(TextureAttrib::get_class_slot()); @@ -468,7 +471,7 @@ scan_geom_node(GeomNode *node, const RenderState *state, // Ok, we have multitexture. Record the Geom. CPT(TexMatrixAttrib) tma = DCAST(TexMatrixAttrib, TexMatrixAttrib::make()); attrib = geom_net_state->get_attrib(TexMatrixAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { tma = DCAST(TexMatrixAttrib, attrib); } @@ -880,13 +883,13 @@ transfer_geom(GeomNode *geom_node, const InternalName *texcoord_name, } } - if (texcoord_name != (const InternalName *)NULL && + if (texcoord_name != nullptr && texcoord_name != InternalName::get_texcoord()) { // Copy the texture coordinates from the indicated name over to the // default name. const GeomVertexColumn *column = vdata->get_format()->get_column(texcoord_name); - if (column != (const GeomVertexColumn *)NULL) { + if (column != nullptr) { vdata = vdata->replace_column (InternalName::get_texcoord(), column->get_num_components(), column->get_numeric_type(), column->get_contents()); @@ -904,11 +907,11 @@ transfer_geom(GeomNode *geom_node, const InternalName *texcoord_name, if (preserve_color) { // Be sure to preserve whatever colors are on the geom. const RenderAttrib *ca = geom_info._geom_net_state->get_attrib(ColorAttrib::get_class_slot()); - if (ca != (const RenderAttrib *)NULL) { + if (ca != nullptr) { geom_state = geom_state->add_attrib(ca); } const RenderAttrib *csa = geom_info._geom_net_state->get_attrib(ColorScaleAttrib::get_class_slot()); - if (csa != (const RenderAttrib *)NULL) { + if (csa != nullptr) { geom_state = geom_state->add_attrib(csa); } } @@ -938,7 +941,7 @@ scan_color(const MultitexReducer::GeomList &geom_list, LColor &geom_color, LColor color_scale(1.0f, 1.0f, 1.0f, 1.0f); const RenderAttrib *csa = geom_info._geom_net_state->get_attrib(ColorScaleAttrib::get_class_slot()); - if (csa != (const RenderAttrib *)NULL) { + if (csa != nullptr) { const ColorScaleAttrib *a = DCAST(ColorScaleAttrib, csa); if (a->has_scale()) { color_scale = a->get_scale(); @@ -947,7 +950,7 @@ scan_color(const MultitexReducer::GeomList &geom_list, LColor &geom_color, ColorAttrib::Type color_type = ColorAttrib::T_vertex; const RenderAttrib *ca = geom_info._geom_net_state->get_attrib(ColorAttrib::get_class_slot()); - if (ca != (const RenderAttrib *)NULL) { + if (ca != nullptr) { color_type = DCAST(ColorAttrib, ca)->get_color_type(); } diff --git a/panda/src/grutil/nodeVertexTransform.cxx b/panda/src/grutil/nodeVertexTransform.cxx index de5b14d0f0..7d4cb2deac 100644 --- a/panda/src/grutil/nodeVertexTransform.cxx +++ b/panda/src/grutil/nodeVertexTransform.cxx @@ -32,7 +32,7 @@ NodeVertexTransform(const PandaNode *node, */ void NodeVertexTransform:: get_matrix(LMatrix4 &matrix) const { - if (_prev != (const VertexTransform *)NULL) { + if (_prev != nullptr) { LMatrix4 prev_matrix; _prev->get_matrix(prev_matrix); matrix.multiply(_node->get_transform()->get_mat(), prev_matrix); @@ -46,8 +46,8 @@ get_matrix(LMatrix4 &matrix) const { * */ void NodeVertexTransform:: -output(ostream &out) const { - if (_prev != (const VertexTransform *)NULL) { +output(std::ostream &out) const { + if (_prev != nullptr) { _prev->output(out); out << " * "; } diff --git a/panda/src/grutil/nodeVertexTransform.h b/panda/src/grutil/nodeVertexTransform.h index 9f1d891615..12b8b11667 100644 --- a/panda/src/grutil/nodeVertexTransform.h +++ b/panda/src/grutil/nodeVertexTransform.h @@ -29,7 +29,7 @@ class FactoryParams; class EXPCL_PANDA_GRUTIL NodeVertexTransform : public VertexTransform { PUBLISHED: NodeVertexTransform(const PandaNode *node, - const VertexTransform *prev = NULL); + const VertexTransform *prev = nullptr); INLINE const PandaNode *get_node() const; INLINE const VertexTransform *get_prev() const; @@ -38,7 +38,7 @@ PUBLISHED: virtual void get_matrix(LMatrix4 &matrix) const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: CPT(PandaNode) _node; diff --git a/panda/src/grutil/pfmVizzer.I b/panda/src/grutil/pfmVizzer.I index 2185248829..7af594088a 100644 --- a/panda/src/grutil/pfmVizzer.I +++ b/panda/src/grutil/pfmVizzer.I @@ -79,7 +79,7 @@ set_flat_texcoord_name(InternalName *flat_texcoord_name) { */ INLINE void PfmVizzer:: clear_flat_texcoord_name() { - _flat_texcoord_name = NULL; + _flat_texcoord_name = nullptr; } /** @@ -149,7 +149,7 @@ set_vis_blend(const PNMImage *vis_blend) { */ INLINE void PfmVizzer:: clear_vis_blend() { - _vis_blend = NULL; + _vis_blend = nullptr; } /** @@ -171,7 +171,7 @@ get_vis_blend() const { */ INLINE void PfmVizzer:: set_aux_pfm(const PfmFile *pfm) { - assert(pfm == NULL || (pfm->get_x_size() == _pfm.get_x_size() && + assert(pfm == nullptr || (pfm->get_x_size() == _pfm.get_x_size() && pfm->get_y_size() == _pfm.get_y_size())); _aux_pfm = pfm; } @@ -181,7 +181,7 @@ set_aux_pfm(const PfmFile *pfm) { */ INLINE void PfmVizzer:: clear_aux_pfm() { - _aux_pfm = NULL; + _aux_pfm = nullptr; } /** @@ -199,5 +199,5 @@ get_aux_pfm() const { */ INLINE PfmVizzer::VisColumn:: VisColumn() { - _undist_lut = NULL; + _undist_lut = nullptr; } diff --git a/panda/src/grutil/pfmVizzer.cxx b/panda/src/grutil/pfmVizzer.cxx index 9bd440a0c3..f3d60787a8 100644 --- a/panda/src/grutil/pfmVizzer.cxx +++ b/panda/src/grutil/pfmVizzer.cxx @@ -23,6 +23,9 @@ #include "pnmImage.h" #include "config_grutil.h" +using std::max; +using std::min; + /** * The PfmVizzer constructor receives a reference to a PfmFile which it will * operate on. It does not keep ownership of this reference; it is your @@ -34,8 +37,8 @@ PfmVizzer(PfmFile &pfm) : _pfm(pfm) { _vis_inverse = false; _vis_2d = false; _keep_beyond_lens = false; - _vis_blend = NULL; - _aux_pfm = NULL; + _vis_blend = nullptr; + _aux_pfm = nullptr; } /** @@ -73,7 +76,7 @@ project(const Lens *lens, const PfmFile *undist_lut) { // these to [0, 1]. LPoint3f uvw = LCAST(float, film * to_uv); - if (undist_lut != NULL) { + if (undist_lut != nullptr) { // Apply the undistortion map, if given. LPoint3f p2; undist_lut->calc_bilinear_point(p2, uvw[0], 1.0 - uvw[1]); @@ -244,7 +247,7 @@ generate_vis_points() const { nassertr(_pfm.is_valid(), NodePath()); bool check_aux_pfm = uses_aux_pfm(); - nassertr(!check_aux_pfm || (_aux_pfm != NULL && _aux_pfm->is_valid()), NodePath()); + nassertr(!check_aux_pfm || (_aux_pfm != nullptr && _aux_pfm->is_valid()), NodePath()); CPT(GeomVertexFormat) format; if (_vis_inverse) { @@ -323,8 +326,7 @@ generate_vis_points() const { NodePath PfmVizzer:: generate_vis_mesh(MeshFace face) const { nassertr(_pfm.is_valid(), NodePath()); - bool check_aux_pfm = uses_aux_pfm(); - nassertr(!check_aux_pfm || (_aux_pfm != NULL && _aux_pfm->is_valid()), NodePath()); + nassertr(!uses_aux_pfm() || (_aux_pfm != nullptr && _aux_pfm->is_valid()), NodePath()); nassertr(face != 0, NodePath()); if (_pfm.get_num_channels() == 1 && _vis_columns.empty()) { @@ -778,7 +780,7 @@ make_vis_mesh_geom(GeomNode *gnode, bool inverted) const { num_vertices = x_size * y_size; max_indices = (x_size - 1) * (y_size - 1) * 6; - ostringstream mesh_name; + std::ostringstream mesh_name; mesh_name << "mesh_" << xci << "_" << yci; PT(GeomVertexData) vdata = new GeomVertexData (mesh_name.str(), format, Geom::UH_static); @@ -878,11 +880,11 @@ add_vis_column(VisColumns &vis_columns, ColumnType source, ColumnType target, column._target = target; column._name = name; column._transform = transform; - if (transform == NULL) { + if (transform == nullptr) { column._transform = TransformState::make_identity(); } column._lens = lens; - if (undist_lut != NULL && undist_lut->is_valid()) { + if (undist_lut != nullptr && undist_lut->is_valid()) { column._undist_lut = undist_lut; } vis_columns.push_back(column); @@ -923,12 +925,12 @@ build_auto_vis_columns(VisColumns &vis_columns, bool for_points) const { } } - if (_flat_texcoord_name != (InternalName *)NULL) { + if (_flat_texcoord_name != nullptr) { // We need an additional texcoord column for the flat texcoords. add_vis_column(vis_columns, CT_texcoord2, CT_texcoord2, _flat_texcoord_name); } - if (_vis_blend != (PNMImage *)NULL) { + if (_vis_blend != nullptr) { // The blend map, if specified, also gets applied to the vertices. add_vis_column(vis_columns, CT_blend1, CT_blend1, InternalName::get_color()); } @@ -996,7 +998,7 @@ make_array_format(const VisColumns &vis_columns) const { contents = GeomEnums::C_color; break; } - nassertr(num_components != 0, NULL); + nassertr(num_components != 0, nullptr); array_format->add_column(name, num_components, numeric_type, contents); } @@ -1050,7 +1052,7 @@ add_data(const PfmVizzer &vizzer, GeomVertexWriter &vwriter, int xi, int yi, boo case CT_aux_vertex1: { - nassertr(vizzer.get_aux_pfm() != NULL, false); + nassertr(vizzer.get_aux_pfm() != nullptr, false); PN_float32 p = vizzer.get_aux_pfm()->get_point1(xi, yi); LPoint2f point(p, 0.0); if (!transform_point(point)) { @@ -1072,7 +1074,7 @@ add_data(const PfmVizzer &vizzer, GeomVertexWriter &vwriter, int xi, int yi, boo case CT_aux_vertex2: { - nassertr(vizzer.get_aux_pfm() != NULL, false); + nassertr(vizzer.get_aux_pfm() != nullptr, false); LPoint2f point = vizzer.get_aux_pfm()->get_point2(xi, yi); if (!transform_point(point)) { success = false; @@ -1156,7 +1158,7 @@ add_data(const PfmVizzer &vizzer, GeomVertexWriter &vwriter, int xi, int yi, boo case CT_blend1: { const PNMImage *vis_blend = vizzer.get_vis_blend(); - if (vis_blend != NULL) { + if (vis_blend != nullptr) { double gray = vis_blend->get_gray(xi, yi); vwriter.set_data3d(gray, gray, gray); } @@ -1189,7 +1191,7 @@ transform_point(LPoint3f &point) const { if (!_transform->is_identity()) { LCAST(PN_float32, _transform->get_mat()).xform_point_in_place(point); } - if (_lens != (Lens *)NULL) { + if (_lens != nullptr) { static LMatrix4f to_uv(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, @@ -1201,7 +1203,7 @@ transform_point(LPoint3f &point) const { point = to_uv.xform_point(LCAST(PN_float32, film)); } - if (_undist_lut != NULL) { + if (_undist_lut != nullptr) { LPoint3f p; if (!_undist_lut->calc_bilinear_point(p, point[0], 1.0 - point[1])) { // Point is missing. diff --git a/panda/src/grutil/pfmVizzer.h b/panda/src/grutil/pfmVizzer.h index e04e8a06bc..3f3fbeb62c 100644 --- a/panda/src/grutil/pfmVizzer.h +++ b/panda/src/grutil/pfmVizzer.h @@ -34,7 +34,7 @@ PUBLISHED: INLINE PfmFile &get_pfm(); INLINE const PfmFile &get_pfm() const; - BLOCKING void project(const Lens *lens, const PfmFile *undist_lut = NULL); + BLOCKING void project(const Lens *lens, const PfmFile *undist_lut = nullptr); BLOCKING void extrude(const Lens *lens); INLINE void set_vis_inverse(bool vis_inverse); @@ -70,8 +70,8 @@ PUBLISHED: void clear_vis_columns(); void add_vis_column(ColumnType source, ColumnType target, InternalName *name, - const TransformState *transform = NULL, const Lens *lens = NULL, - const PfmFile *undist_lut = NULL); + const TransformState *transform = nullptr, const Lens *lens = nullptr, + const PfmFile *undist_lut = nullptr); BLOCKING NodePath generate_vis_points() const; @@ -120,8 +120,8 @@ private: static void add_vis_column(VisColumns &vis_columns, ColumnType source, ColumnType target, InternalName *name, - const TransformState *transform = NULL, - const Lens *lens = NULL, const PfmFile *undist_lut = NULL); + const TransformState *transform = nullptr, + const Lens *lens = nullptr, const PfmFile *undist_lut = nullptr); void build_auto_vis_columns(VisColumns &vis_columns, bool for_points) const; CPT(GeomVertexFormat) make_array_format(const VisColumns &vis_columns) const; diff --git a/panda/src/grutil/pipeOcclusionCullTraverser.cxx b/panda/src/grutil/pipeOcclusionCullTraverser.cxx index 1052d5ace5..2a7f27a878 100644 --- a/panda/src/grutil/pipeOcclusionCullTraverser.cxx +++ b/panda/src/grutil/pipeOcclusionCullTraverser.cxx @@ -103,14 +103,14 @@ PipeOcclusionCullTraverser(GraphicsOutput *host) { _buffer = engine->make_output(pipe, "occlusion", 0, fb_prop, win_prop, GraphicsPipe::BF_refuse_window, gsg, host->get_host()); - nassertv(_buffer != (GraphicsOutput *)NULL); + nassertv(_buffer != nullptr); // This buffer isn't really active--we render it by hand; we don't want the // GraphicsEngine to render it. _buffer->set_active(0); _display_region = _buffer->make_display_region(); - _internal_cull_handler = NULL; + _internal_cull_handler = nullptr; make_sphere(); make_box(); @@ -119,16 +119,6 @@ PipeOcclusionCullTraverser(GraphicsOutput *host) { _live = true; } -/** - * - */ -PipeOcclusionCullTraverser:: -PipeOcclusionCullTraverser(const PipeOcclusionCullTraverser ©) : - CullTraverser(copy) -{ - nassertv(false); -} - /** * */ @@ -202,8 +192,8 @@ set_scene(SceneSetup *scene_setup, GraphicsStateGuardianBase *gsgbase, _internal_trav->set_view_frustum(get_view_frustum()); _internal_trav->set_camera_mask(_occlusion_mask); - _current_query = NULL; - _next_query = NULL; + _current_query = nullptr; + _next_query = nullptr; // Begin by rendering all the occluders into our internal scene. PStatTimer timer2(_draw_occlusion_pcollector); @@ -224,13 +214,13 @@ end_traverse() { GraphicsStateGuardian *gsg = _buffer->get_gsg(); Thread *current_thread = get_current_thread(); - _current_query = NULL; - _next_query = NULL; + _current_query = nullptr; + _next_query = nullptr; PendingObjects::iterator oi; for (oi = _pending_objects.begin(); oi != _pending_objects.end(); ++oi) { PendingObject &pobj = (*oi); - if (pobj._query == (OcclusionQueryContext *)NULL) { + if (pobj._query == nullptr) { _occlusion_untested_pcollector.add_level(1); _true_cull_handler->record_object(pobj._object, this); } else { @@ -247,7 +237,7 @@ end_traverse() { // The CullableObject has by now either been recorded (which will // eventually delete it) or deleted directly. #ifndef NDEBUG - pobj._object = NULL; + pobj._object = nullptr; #endif // NDEBUG } _pending_objects.clear(); @@ -260,7 +250,7 @@ end_traverse() { _buffer->end_flip(); delete _internal_cull_handler; - _internal_cull_handler = NULL; + _internal_cull_handler = nullptr; _occlusion_untested_pcollector.flush_level(); _occlusion_passed_pcollector.flush_level(); @@ -274,7 +264,7 @@ end_traverse() { */ Texture *PipeOcclusionCullTraverser:: get_texture() { - if (_texture != (Texture *)NULL) { + if (_texture != nullptr) { return _texture; } @@ -298,7 +288,7 @@ get_texture() { */ bool PipeOcclusionCullTraverser:: is_in_view(CullTraverserData &data) { - _next_query = NULL; + _next_query = nullptr; if (!CullTraverser::is_in_view(data)) { return false; @@ -307,7 +297,7 @@ is_in_view(CullTraverserData &data) { return true; } - if (_current_query != (OcclusionQueryContext *)NULL) { + if (_current_query != nullptr) { // We've already performed an occlusion test for some ancestor of this // node; no need to perform another. return true; @@ -351,15 +341,15 @@ traverse_below(CullTraverserData &data) { // Save and restore _current_query, and clear _next_query, for traversing // the children of this node. PT(OcclusionQueryContext) prev_query = _current_query; - if (_next_query != (OcclusionQueryContext *)NULL) { + if (_next_query != nullptr) { _current_query = _next_query; } - _next_query = NULL; + _next_query = nullptr; CullTraverser::traverse_below(data); _current_query = prev_query; - _next_query = NULL; + _next_query = nullptr; } /** @@ -379,12 +369,12 @@ record_object(CullableObject *object, const CullTraverser *traverser) { Thread *current_thread = get_current_thread(); - if (_next_query != (OcclusionQueryContext *)NULL) { + if (_next_query != nullptr) { // We have just performed an occlusion query for this node. Don't perform // another one. pobj._query = _next_query; - } else if (_current_query != (OcclusionQueryContext *)NULL) { + } else if (_current_query != nullptr) { // We have previously performed an occlusion query for this node or some // ancestor. Don't perform another one. pobj._query = _current_query; diff --git a/panda/src/grutil/pipeOcclusionCullTraverser.h b/panda/src/grutil/pipeOcclusionCullTraverser.h index 55d2a795ce..d41c5acff4 100644 --- a/panda/src/grutil/pipeOcclusionCullTraverser.h +++ b/panda/src/grutil/pipeOcclusionCullTraverser.h @@ -42,7 +42,7 @@ class EXPCL_PANDA_GRUTIL PipeOcclusionCullTraverser : public CullTraverser, public CullHandler { PUBLISHED: explicit PipeOcclusionCullTraverser(GraphicsOutput *host); - PipeOcclusionCullTraverser(const PipeOcclusionCullTraverser ©); + PipeOcclusionCullTraverser(const PipeOcclusionCullTraverser ©) = delete; virtual void set_scene(SceneSetup *scene_setup, GraphicsStateGuardianBase *gsg, diff --git a/panda/src/grutil/rigidBodyCombiner.cxx b/panda/src/grutil/rigidBodyCombiner.cxx index 7e3ccefd65..fb2c3959ab 100644 --- a/panda/src/grutil/rigidBodyCombiner.cxx +++ b/panda/src/grutil/rigidBodyCombiner.cxx @@ -30,7 +30,7 @@ TypeHandle RigidBodyCombiner::_type_handle; * */ RigidBodyCombiner:: -RigidBodyCombiner(const string &name) : PandaNode(name) { +RigidBodyCombiner(const std::string &name) : PandaNode(name) { set_cull_callback(); _internal_root = new PandaNode(name); @@ -90,7 +90,7 @@ collect() { Children cr = get_children(); int num_children = cr.get_num_children(); for (int i = 0; i < num_children; i++) { - r_collect(cr.get_child(i), RenderState::make_empty(), NULL); + r_collect(cr.get_child(i), RenderState::make_empty(), nullptr); } _vd_table.clear(); @@ -179,7 +179,7 @@ r_collect(PandaNode *node, const RenderState *state, int num_geoms = gnode->get_num_geoms(); for (int i = 0; i < num_geoms; ++i) { PT(Geom) geom = gnode->get_geom(i)->make_copy(); - if (next_transform != (const VertexTransform *)NULL) { + if (next_transform != nullptr) { geom->set_vertex_data(convert_vd(next_transform, geom->get_vertex_data())); } CPT(RenderState) gstate = next_state->compose(gnode->get_geom_state(i)); @@ -225,7 +225,7 @@ convert_vd(const VertexTransform *transform, const GeomVertexData *orig) { CPT(GeomVertexData) converted = orig->convert_to(new_format); PT(GeomVertexData) new_data = new GeomVertexData(*converted); - if (new_data->get_transform_blend_table() == (TransformBlendTable *)NULL) { + if (new_data->get_transform_blend_table() == nullptr) { // Create a new table that has just the one blend: all vertices hard- // assigned to the indicated transform. PT(TransformBlendTable) new_table = new TransformBlendTable; diff --git a/panda/src/grutil/rigidBodyCombiner.h b/panda/src/grutil/rigidBodyCombiner.h index fca66e0031..f1694f49b0 100644 --- a/panda/src/grutil/rigidBodyCombiner.h +++ b/panda/src/grutil/rigidBodyCombiner.h @@ -43,7 +43,7 @@ class NodePath; */ class EXPCL_PANDA_GRUTIL RigidBodyCombiner : public PandaNode { PUBLISHED: - explicit RigidBodyCombiner(const string &name); + explicit RigidBodyCombiner(const std::string &name); protected: RigidBodyCombiner(const RigidBodyCombiner ©); virtual PandaNode *make_copy() const; diff --git a/panda/src/grutil/sceneGraphAnalyzerMeter.cxx b/panda/src/grutil/sceneGraphAnalyzerMeter.cxx index f5a14caed3..02d6ed3709 100644 --- a/panda/src/grutil/sceneGraphAnalyzerMeter.cxx +++ b/panda/src/grutil/sceneGraphAnalyzerMeter.cxx @@ -29,7 +29,7 @@ TypeHandle SceneGraphAnalyzerMeter::_type_handle; * */ SceneGraphAnalyzerMeter:: -SceneGraphAnalyzerMeter(const string &name, PandaNode *node) : TextNode(name) { +SceneGraphAnalyzerMeter(const std::string &name, PandaNode *node) : TextNode(name) { set_cull_callback(); Thread *current_thread = Thread::get_current_thread(); @@ -105,10 +105,10 @@ setup_window(GraphicsOutput *window) { */ void SceneGraphAnalyzerMeter:: clear_window() { - if (_window != (GraphicsOutput *)NULL) { + if (_window != nullptr) { _window->remove_display_region(_display_region); - _window = (GraphicsOutput *)NULL; - _display_region = (DisplayRegion *)NULL; + _window = nullptr; + _display_region = nullptr; } _root = NodePath(); } diff --git a/panda/src/grutil/sceneGraphAnalyzerMeter.h b/panda/src/grutil/sceneGraphAnalyzerMeter.h index a20066d9d7..148aa37022 100644 --- a/panda/src/grutil/sceneGraphAnalyzerMeter.h +++ b/panda/src/grutil/sceneGraphAnalyzerMeter.h @@ -38,7 +38,7 @@ class ClockObject; */ class EXPCL_PANDA_GRUTIL SceneGraphAnalyzerMeter : public TextNode { PUBLISHED: - explicit SceneGraphAnalyzerMeter(const string &name, PandaNode *node); + explicit SceneGraphAnalyzerMeter(const std::string &name, PandaNode *node); virtual ~SceneGraphAnalyzerMeter(); void setup_window(GraphicsOutput *window); diff --git a/panda/src/grutil/shaderTerrainMesh.I b/panda/src/grutil/shaderTerrainMesh.I index 91ac1035d3..f6a66bc7f5 100644 --- a/panda/src/grutil/shaderTerrainMesh.I +++ b/panda/src/grutil/shaderTerrainMesh.I @@ -153,7 +153,7 @@ INLINE bool ShaderTerrainMesh::get_update_enabled() const { INLINE void ShaderTerrainMesh::Chunk::clear_children() { for (size_t i = 0; i < 4; ++i) { delete children[i]; - children[i] = NULL; + children[i] = nullptr; } } @@ -163,7 +163,7 @@ INLINE void ShaderTerrainMesh::Chunk::clear_children() { */ INLINE ShaderTerrainMesh::Chunk::Chunk() { for (size_t i = 0; i < 4; ++i) - children[i] = NULL; + children[i] = nullptr; } /** diff --git a/panda/src/grutil/shaderTerrainMesh.cxx b/panda/src/grutil/shaderTerrainMesh.cxx index 8c9c7bd9b6..44c8397279 100644 --- a/panda/src/grutil/shaderTerrainMesh.cxx +++ b/panda/src/grutil/shaderTerrainMesh.cxx @@ -34,6 +34,10 @@ #include "config_grutil.h" #include "typeHandle.h" +using std::endl; +using std::max; +using std::min; + ConfigVariableBool stm_use_hexagonal_layout ("stm-use-hexagonal-layout", false, PRC_DESC("Set this to true to use a hexagonal vertex layout. This approximates " @@ -94,13 +98,13 @@ ShaderTerrainMesh::ShaderTerrainMesh() : _size(0), _chunk_size(32), _generate_patches(false), - _data_texture(NULL), - _chunk_geom(NULL), + _data_texture(nullptr), + _chunk_geom(nullptr), _current_view_index(0), _last_frame_count(-1), _target_triangle_width(10.0f), _update_enabled(true), - _heightfield_tex(NULL) + _heightfield_tex(nullptr) { set_final(true); set_bounds(new OmniBoundingVolume()); @@ -261,7 +265,7 @@ void ShaderTerrainMesh::do_init_chunk(Chunk* chunk) { } else { // Final chunk, initialize all children to zero for (size_t i = 0; i < 4; ++i) { - chunk->children[i] = NULL; + chunk->children[i] = nullptr; } } } @@ -375,7 +379,7 @@ void ShaderTerrainMesh::do_create_chunk_geom() { GeomVertexWriter vertex_writer(gvd, "vertex"); // Create primitive - PT(GeomPrimitive) triangles = NULL; + PT(GeomPrimitive) triangles = nullptr; if (_generate_patches) { triangles = new GeomPatches(3, Geom::UH_static); } else { @@ -460,8 +464,8 @@ void ShaderTerrainMesh::add_for_draw(CullTraverser *trav, CullTraverserData &dat // Make sure the terrain was properly initialized, and the geom was created // successfully - nassertv(_data_texture != NULL); - nassertv(_chunk_geom != NULL); + nassertv(_data_texture != nullptr); + nassertv(_chunk_geom != nullptr); _basic_collector.start(); @@ -524,7 +528,7 @@ void ShaderTerrainMesh::add_for_draw(CullTraverser *trav, CullTraverserData &dat } // Should never happen - nassertv(current_shader_attrib != NULL); + nassertv(current_shader_attrib != nullptr); current_shader_attrib = DCAST(ShaderAttrib, current_shader_attrib)->set_shader_input( ShaderInput("ShaderTerrainMesh.terrain_size", LVecBase2i(_size))); @@ -542,7 +546,7 @@ void ShaderTerrainMesh::add_for_draw(CullTraverser *trav, CullTraverserData &dat state = state->set_attrib(current_shader_attrib, 10000); // Emit chunk - CullableObject *object = new CullableObject(_chunk_geom, move(state), move(modelview_transform)); + CullableObject *object = new CullableObject(_chunk_geom, std::move(state), std::move(modelview_transform)); trav->get_cull_handler()->record_object(object, trav); // After rendering, increment the view index @@ -707,11 +711,11 @@ void ShaderTerrainMesh::do_emit_chunk(Chunk* chunk, TraversalData* data) { * @return World-Space point */ LPoint3 ShaderTerrainMesh::uv_to_world(const LTexCoord& coord) const { - nassertr(_heightfield_tex != NULL, LPoint3(0)); // Heightfield not set yet + nassertr(_heightfield_tex != nullptr, LPoint3(0)); // Heightfield not set yet nassertr(_heightfield_tex->has_ram_image(), LPoint3(0)); // Heightfield not in memory PT(TexturePeeker) peeker = _heightfield_tex->peek(); - nassertr(peeker != NULL, LPoint3(0)); + nassertr(peeker != nullptr, LPoint3(0)); LColor result; if (!peeker->lookup_bilinear(result, coord.get_x(), coord.get_y())) { diff --git a/panda/src/gsgbase/graphicsStateGuardianBase.cxx b/panda/src/gsgbase/graphicsStateGuardianBase.cxx index fefd8037f2..5ac46dd4af 100644 --- a/panda/src/gsgbase/graphicsStateGuardianBase.cxx +++ b/panda/src/gsgbase/graphicsStateGuardianBase.cxx @@ -30,9 +30,9 @@ TypeHandle GraphicsStateGuardianBase::_type_handle; GraphicsStateGuardianBase *GraphicsStateGuardianBase:: get_default_gsg() { GSGList *gsg_list = (GSGList *)AtomicAdjust::get_ptr(_gsg_list); - if (gsg_list == NULL) { + if (gsg_list == nullptr) { // Nobody created a GSG list, so we won't have any GSGs either. - return NULL; + return nullptr; } LightMutexHolder holder(gsg_list->_lock); return gsg_list->_default_gsg; @@ -45,7 +45,7 @@ get_default_gsg() { void GraphicsStateGuardianBase:: set_default_gsg(GraphicsStateGuardianBase *default_gsg) { GSGList *gsg_list = (GSGList *)AtomicAdjust::get_ptr(_gsg_list); - if (gsg_list == NULL) { + if (gsg_list == nullptr) { // Nobody ever created a GSG list. How could we have a GSG? nassertv(false); return; @@ -67,7 +67,7 @@ set_default_gsg(GraphicsStateGuardianBase *default_gsg) { size_t GraphicsStateGuardianBase:: get_num_gsgs() { GSGList *gsg_list = (GSGList *)AtomicAdjust::get_ptr(_gsg_list); - if (gsg_list == NULL) { + if (gsg_list == nullptr) { // Nobody created a GSG list, so we won't have any GSGs either. return 0; } @@ -82,10 +82,10 @@ get_num_gsgs() { GraphicsStateGuardianBase *GraphicsStateGuardianBase:: get_gsg(size_t n) { GSGList *gsg_list = (GSGList *)AtomicAdjust::get_ptr(_gsg_list); - nassertr(gsg_list != NULL, NULL); + nassertr(gsg_list != nullptr, nullptr); LightMutexHolder holder(gsg_list->_lock); - nassertr(n < gsg_list->_gsgs.size(), NULL); + nassertr(n < gsg_list->_gsgs.size(), nullptr); return gsg_list->_gsgs[n]; } @@ -96,14 +96,14 @@ get_gsg(size_t n) { void GraphicsStateGuardianBase:: add_gsg(GraphicsStateGuardianBase *gsg) { GSGList *gsg_list = (GSGList *)AtomicAdjust::get_ptr(_gsg_list); - if (gsg_list == NULL) { + if (gsg_list == nullptr) { gsg_list = new GSGList; - gsg_list->_default_gsg = NULL; + gsg_list->_default_gsg = nullptr; GSGList *orig_gsg_list = (GSGList *) - AtomicAdjust::compare_and_exchange_ptr(_gsg_list, NULL, gsg_list); + AtomicAdjust::compare_and_exchange_ptr(_gsg_list, nullptr, gsg_list); - if (orig_gsg_list != NULL) { + if (orig_gsg_list != nullptr) { // Another thread beat us to it. No problem, we'll use that. delete gsg_list; gsg_list = orig_gsg_list; @@ -119,7 +119,7 @@ add_gsg(GraphicsStateGuardianBase *gsg) { gsg_list->_gsgs.push_back(gsg); - if (gsg_list->_default_gsg == (GraphicsStateGuardianBase *)NULL) { + if (gsg_list->_default_gsg == nullptr) { gsg_list->_default_gsg = gsg; } } @@ -130,7 +130,7 @@ add_gsg(GraphicsStateGuardianBase *gsg) { void GraphicsStateGuardianBase:: remove_gsg(GraphicsStateGuardianBase *gsg) { GSGList *gsg_list = (GSGList *)AtomicAdjust::get_ptr(_gsg_list); - if (gsg_list == NULL) { + if (gsg_list == nullptr) { // No GSGs were added yet, or the program is destructing anyway. return; } @@ -150,7 +150,7 @@ remove_gsg(GraphicsStateGuardianBase *gsg) { if (!gsg_list->_gsgs.empty()) { gsg_list->_default_gsg = *gsg_list->_gsgs.begin(); } else { - gsg_list->_default_gsg = NULL; + gsg_list->_default_gsg = nullptr; } } } diff --git a/panda/src/iphone/iphone_runappmf_src.mm b/panda/src/iphone/iphone_runappmf_src.mm index 40479f894f..56d97e8364 100644 --- a/panda/src/iphone/iphone_runappmf_src.mm +++ b/panda/src/iphone/iphone_runappmf_src.mm @@ -15,7 +15,6 @@ #include #include #include -using namespace std; #include "pnotify.h" diff --git a/panda/src/iphonedisplay/iPhoneGraphicsPipe.h b/panda/src/iphonedisplay/iPhoneGraphicsPipe.h index 24418bda12..12405bcbbc 100644 --- a/panda/src/iphonedisplay/iPhoneGraphicsPipe.h +++ b/panda/src/iphonedisplay/iPhoneGraphicsPipe.h @@ -33,14 +33,14 @@ public: IPhoneGraphicsPipe(); virtual ~IPhoneGraphicsPipe(); - virtual string get_interface_name() const; + virtual std::string get_interface_name() const; static PT(GraphicsPipe) pipe_constructor(); virtual PreferredWindowThread get_preferred_window_thread() const; void rotate_windows(); protected: - virtual PT(GraphicsOutput) make_output(const string &name, + virtual PT(GraphicsOutput) make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/iphonedisplay/iPhoneGraphicsPipe.mm b/panda/src/iphonedisplay/iPhoneGraphicsPipe.mm index dba09cbcc9..82e92f4b70 100644 --- a/panda/src/iphonedisplay/iPhoneGraphicsPipe.mm +++ b/panda/src/iphonedisplay/iPhoneGraphicsPipe.mm @@ -51,7 +51,7 @@ IPhoneGraphicsPipe:: * choose between several possible GraphicsPipes available on a particular * platform, so the name should be meaningful and unique for a given platform. */ -string IPhoneGraphicsPipe:: +std::string IPhoneGraphicsPipe:: get_interface_name() const { return "OpenGL ES"; } diff --git a/panda/src/iphonedisplay/iPhoneGraphicsWindow.h b/panda/src/iphonedisplay/iPhoneGraphicsWindow.h index 7a73a70302..6da377b18d 100644 --- a/panda/src/iphonedisplay/iPhoneGraphicsWindow.h +++ b/panda/src/iphonedisplay/iPhoneGraphicsWindow.h @@ -28,7 +28,7 @@ class IPhoneGraphicsWindow : public GraphicsWindow { public: IPhoneGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/linmath/configVariableColor.I b/panda/src/linmath/configVariableColor.I index 21a0af8660..751d7f415a 100644 --- a/panda/src/linmath/configVariableColor.I +++ b/panda/src/linmath/configVariableColor.I @@ -15,7 +15,7 @@ * */ INLINE ConfigVariableColor:: -ConfigVariableColor(const string &name) : +ConfigVariableColor(const std::string &name) : ConfigVariable(name, VT_color), _local_modified(initial_invalid_cache()), _cache(0, 0, 0, 1) @@ -27,12 +27,12 @@ ConfigVariableColor(const string &name) : * */ INLINE ConfigVariableColor:: -ConfigVariableColor(const string &name, const LColor &default_value, - const string &description, int flags) : +ConfigVariableColor(const std::string &name, const LColor &default_value, + const std::string &description, int flags) : #ifdef PRC_SAVE_DESCRIPTIONS ConfigVariable(name, ConfigVariableCore::VT_color, description, flags), #else - ConfigVariable(name, ConfigVariableCore::VT_color, string(), flags), + ConfigVariable(name, ConfigVariableCore::VT_color, std::string(), flags), #endif _local_modified(initial_invalid_cache()), _cache(0, 0, 0, 1) @@ -45,12 +45,12 @@ ConfigVariableColor(const string &name, const LColor &default_value, * */ INLINE ConfigVariableColor:: -ConfigVariableColor(const string &name, const string &default_value, - const string &description, int flags) : +ConfigVariableColor(const std::string &name, const std::string &default_value, + const std::string &description, int flags) : #ifdef PRC_SAVE_DESCRIPTIONS ConfigVariable(name, ConfigVariableCore::VT_color, description, flags), #else - ConfigVariable(name, ConfigVariableCore::VT_color, string(), flags), + ConfigVariable(name, ConfigVariableCore::VT_color, std::string(), flags), #endif _local_modified(initial_invalid_cache()), _cache(0, 0, 0, 1) @@ -141,7 +141,7 @@ get_value() const { INLINE LColor ConfigVariableColor:: get_default_value() const { const ConfigDeclaration *decl = ConfigVariable::get_default_value(); - if (decl != (ConfigDeclaration *)NULL) { + if (decl != nullptr) { switch (decl->get_num_words()) { case 1: return LColor((PN_stdfloat)decl->get_double_word(0), (PN_stdfloat)decl->get_double_word(0), diff --git a/panda/src/linmath/configVariableColor.h b/panda/src/linmath/configVariableColor.h index 380644a57a..fba5330e26 100644 --- a/panda/src/linmath/configVariableColor.h +++ b/panda/src/linmath/configVariableColor.h @@ -34,12 +34,12 @@ */ class EXPCL_PANDA_LINMATH ConfigVariableColor : public ConfigVariable { PUBLISHED: - INLINE ConfigVariableColor(const string &name); - INLINE ConfigVariableColor(const string &name, const LColor &default_value, - const string &description = string(), + INLINE ConfigVariableColor(const std::string &name); + INLINE ConfigVariableColor(const std::string &name, const LColor &default_value, + const std::string &description = std::string(), int flags = 0); - INLINE ConfigVariableColor(const string &name, const string &default_value, - const string &description = string(), + INLINE ConfigVariableColor(const std::string &name, const std::string &default_value, + const std::string &description = std::string(), int flags = 0); INLINE void operator = (const LColor &value); diff --git a/panda/src/linmath/coordinateSystem.cxx b/panda/src/linmath/coordinateSystem.cxx index 6eb81077ca..b94b0ec4ff 100644 --- a/panda/src/linmath/coordinateSystem.cxx +++ b/panda/src/linmath/coordinateSystem.cxx @@ -21,6 +21,11 @@ #include +using std::istream; +using std::ostream; +using std::ostringstream; +using std::string; + static ConfigVariableEnum default_cs ("coordinate-system", CS_zup_right, PRC_DESC("The default coordinate system to use throughout Panda for " diff --git a/panda/src/linmath/coordinateSystem.h b/panda/src/linmath/coordinateSystem.h index ba40f3d2b0..313645a35e 100644 --- a/panda/src/linmath/coordinateSystem.h +++ b/panda/src/linmath/coordinateSystem.h @@ -38,16 +38,16 @@ enum CoordinateSystem { }; EXPCL_PANDA_LINMATH CoordinateSystem get_default_coordinate_system(); -EXPCL_PANDA_LINMATH CoordinateSystem parse_coordinate_system_string(const string &str); -EXPCL_PANDA_LINMATH string format_coordinate_system(CoordinateSystem cs); +EXPCL_PANDA_LINMATH CoordinateSystem parse_coordinate_system_string(const std::string &str); +EXPCL_PANDA_LINMATH std::string format_coordinate_system(CoordinateSystem cs); EXPCL_PANDA_LINMATH bool is_right_handed(CoordinateSystem cs = CS_default); END_PUBLISH #define IS_LEFT_HANDED_COORDSYSTEM(cs) ((cs==CS_zup_left) || (cs==CS_yup_left)) -EXPCL_PANDA_LINMATH ostream &operator << (ostream &out, CoordinateSystem cs); -EXPCL_PANDA_LINMATH istream &operator >> (istream &in, CoordinateSystem &cs); +EXPCL_PANDA_LINMATH std::ostream &operator << (std::ostream &out, CoordinateSystem cs); +EXPCL_PANDA_LINMATH std::istream &operator >> (std::istream &in, CoordinateSystem &cs); #endif diff --git a/panda/src/linmath/lmatrix3_ext_src.I b/panda/src/linmath/lmatrix3_ext_src.I index b1997ec746..0d92b37aa4 100644 --- a/panda/src/linmath/lmatrix3_ext_src.I +++ b/panda/src/linmath/lmatrix3_ext_src.I @@ -21,8 +21,8 @@ __reduce__(PyObject *self) const { // object whose constructor we should call (e.g. this), and the arguments // necessary to reconstruct this object. PyObject *this_class = PyObject_Type(self); - if (this_class == NULL) { - return NULL; + if (this_class == nullptr) { + return nullptr; } PyObject *result = Py_BuildValue("(O(fffffffff))", this_class, @@ -37,9 +37,9 @@ __reduce__(PyObject *self) const { /** * */ -INLINE_LINMATH string Extension:: +INLINE_LINMATH std::string Extension:: __repr__() const { - ostringstream out; + std::ostringstream out; out << "LMatrix3" << FLOATTOKEN << "(" << MAYBE_ZERO(_this->_m(0, 0)) << ", " << MAYBE_ZERO(_this->_m(0, 1)) << ", " diff --git a/panda/src/linmath/lmatrix3_ext_src.h b/panda/src/linmath/lmatrix3_ext_src.h index 34828c9133..6c4894c69f 100644 --- a/panda/src/linmath/lmatrix3_ext_src.h +++ b/panda/src/linmath/lmatrix3_ext_src.h @@ -19,7 +19,7 @@ template<> class Extension : public ExtensionBase { public: INLINE_LINMATH PyObject *__reduce__(PyObject *self) const; - INLINE_LINMATH string __repr__() const; + INLINE_LINMATH std::string __repr__() const; }; #include "lmatrix3_ext_src.I" diff --git a/panda/src/linmath/lmatrix3_src.cxx b/panda/src/linmath/lmatrix3_src.cxx index e21160b2fd..e654b3accd 100644 --- a/panda/src/linmath/lmatrix3_src.cxx +++ b/panda/src/linmath/lmatrix3_src.cxx @@ -326,7 +326,7 @@ almost_equal(const FLOATNAME(LMatrix3) &other, FLOATTYPE threshold) const { * */ void FLOATNAME(LMatrix3):: -output(ostream &out) const { +output(std::ostream &out) const { out << "[ " << MAYBE_ZERO(_m(0, 0)) << " " << MAYBE_ZERO(_m(0, 1)) << " " @@ -346,7 +346,7 @@ output(ostream &out) const { * */ void FLOATNAME(LMatrix3):: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << MAYBE_ZERO(_m(0, 0)) << " " << MAYBE_ZERO(_m(0, 1)) << " " diff --git a/panda/src/linmath/lmatrix3_src.h b/panda/src/linmath/lmatrix3_src.h index fa01ef2c27..399508ed5f 100644 --- a/panda/src/linmath/lmatrix3_src.h +++ b/panda/src/linmath/lmatrix3_src.h @@ -285,9 +285,9 @@ PUBLISHED: INLINE_LINMATH bool almost_equal(const FLOATNAME(LMatrix3) &other) const; - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; - EXTENSION(INLINE_LINMATH string __repr__() const); + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; + EXTENSION(INLINE_LINMATH std::string __repr__() const); INLINE_LINMATH void generate_hash(ChecksumHashGenerator &hashgen) const; void generate_hash( @@ -327,7 +327,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const FLOATNAME(LMatrix3) &mat) { +INLINE std::ostream &operator << (std::ostream &out, const FLOATNAME(LMatrix3) &mat) { mat.output(out); return out; } diff --git a/panda/src/linmath/lmatrix4_ext_src.I b/panda/src/linmath/lmatrix4_ext_src.I index 23a4a26518..68a2741bbb 100644 --- a/panda/src/linmath/lmatrix4_ext_src.I +++ b/panda/src/linmath/lmatrix4_ext_src.I @@ -21,8 +21,8 @@ __reduce__(PyObject *self) const { // object whose constructor we should call (e.g. this), and the arguments // necessary to reconstruct this object. PyObject *this_class = PyObject_Type(self); - if (this_class == NULL) { - return NULL; + if (this_class == nullptr) { + return nullptr; } PyObject *result = Py_BuildValue("(O(ffffffffffffffff))", this_class, @@ -38,9 +38,9 @@ __reduce__(PyObject *self) const { /** * */ -INLINE_LINMATH string Extension:: +INLINE_LINMATH std::string Extension:: __repr__() const { - ostringstream out; + std::ostringstream out; out << "LMatrix4" << FLOATTOKEN << "(" << MAYBE_ZERO(_this->_m(0, 0)) << ", " << MAYBE_ZERO(_this->_m(0, 1)) << ", " diff --git a/panda/src/linmath/lmatrix4_ext_src.h b/panda/src/linmath/lmatrix4_ext_src.h index 65dfe8bb20..768be01526 100644 --- a/panda/src/linmath/lmatrix4_ext_src.h +++ b/panda/src/linmath/lmatrix4_ext_src.h @@ -19,7 +19,7 @@ template<> class Extension : public ExtensionBase { public: INLINE_LINMATH PyObject *__reduce__(PyObject *self) const; - INLINE_LINMATH string __repr__() const; + INLINE_LINMATH std::string __repr__() const; }; #include "lmatrix4_ext_src.I" diff --git a/panda/src/linmath/lmatrix4_src.cxx b/panda/src/linmath/lmatrix4_src.cxx index 427841965f..0a1d5a6a0e 100644 --- a/panda/src/linmath/lmatrix4_src.cxx +++ b/panda/src/linmath/lmatrix4_src.cxx @@ -306,7 +306,7 @@ almost_equal(const FLOATNAME(LMatrix4) &other, FLOATTYPE threshold) const { * */ void FLOATNAME(LMatrix4):: -output(ostream &out) const { +output(std::ostream &out) const { out << "[ " << MAYBE_ZERO(_m(0, 0)) << " " << MAYBE_ZERO(_m(0, 1)) << " " @@ -334,7 +334,7 @@ output(ostream &out) const { * */ void FLOATNAME(LMatrix4):: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << MAYBE_ZERO(_m(0, 0)) << " " << MAYBE_ZERO(_m(0, 1)) << " " diff --git a/panda/src/linmath/lmatrix4_src.h b/panda/src/linmath/lmatrix4_src.h index de2d2fbf78..4d749cddd5 100644 --- a/panda/src/linmath/lmatrix4_src.h +++ b/panda/src/linmath/lmatrix4_src.h @@ -263,9 +263,9 @@ PUBLISHED: FLOATTYPE threshold) const; INLINE_LINMATH bool almost_equal(const FLOATNAME(LMatrix4) &other) const; - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; - EXTENSION(INLINE_LINMATH string __repr__() const); + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; + EXTENSION(INLINE_LINMATH std::string __repr__() const); INLINE_LINMATH void generate_hash(ChecksumHashGenerator &hashgen) const; void generate_hash(ChecksumHashGenerator &hashgen, FLOATTYPE scale) const; @@ -363,7 +363,7 @@ private: }; -INLINE ostream &operator << (ostream &out, const FLOATNAME(LMatrix4) &mat) { +INLINE std::ostream &operator << (std::ostream &out, const FLOATNAME(LMatrix4) &mat) { mat.output(out); return out; } diff --git a/panda/src/linmath/lpoint2_ext_src.I b/panda/src/linmath/lpoint2_ext_src.I index 371017955d..acfa098501 100644 --- a/panda/src/linmath/lpoint2_ext_src.I +++ b/panda/src/linmath/lpoint2_ext_src.I @@ -14,9 +14,9 @@ /** * */ -INLINE_LINMATH string Extension:: +INLINE_LINMATH std::string Extension:: __repr__() const { - ostringstream out; + std::ostringstream out; out << "LPoint2" << FLOATTOKEN << "(" << MAYBE_ZERO(_this->_v(0)) << ", " << MAYBE_ZERO(_this->_v(1)) << ")"; @@ -27,7 +27,7 @@ __repr__() const { * This is used to implement swizzle masks. */ INLINE_LINMATH PyObject *Extension:: -__getattr__(PyObject *self, const string &attr_name) const { +__getattr__(PyObject *self, const std::string &attr_name) const { #ifndef CPPPARSER extern struct Dtool_PyTypedObject FLOATNAME(Dtool_LPoint2); extern struct Dtool_PyTypedObject FLOATNAME(Dtool_LPoint3); @@ -35,7 +35,7 @@ __getattr__(PyObject *self, const string &attr_name) const { #endif // Validate the attribute name. - for (string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { + for (std::string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { if (*it != 'x' && *it != 'y') { return Dtool_Raise_AttributeError(self, attr_name.c_str()); } @@ -75,7 +75,7 @@ __getattr__(PyObject *self, const string &attr_name) const { * This is used to implement write masks. */ INLINE_LINMATH int Extension:: -__setattr__(PyObject *self, const string &attr_name, PyObject *assign) { +__setattr__(PyObject *self, const std::string &attr_name, PyObject *assign) { // Upcall to LVecBase2. return invoke_extension(_this).__setattr__(self, attr_name, assign); } diff --git a/panda/src/linmath/lpoint2_ext_src.h b/panda/src/linmath/lpoint2_ext_src.h index 78fa18cfa9..27eadd1bdf 100644 --- a/panda/src/linmath/lpoint2_ext_src.h +++ b/panda/src/linmath/lpoint2_ext_src.h @@ -18,9 +18,9 @@ template<> class Extension : public ExtensionBase { public: - INLINE_LINMATH PyObject *__getattr__(PyObject *self, const string &attr_name) const; - INLINE_LINMATH int __setattr__(PyObject *self, const string &attr_name, PyObject *assign); - INLINE_LINMATH string __repr__() const; + INLINE_LINMATH PyObject *__getattr__(PyObject *self, const std::string &attr_name) const; + INLINE_LINMATH int __setattr__(PyObject *self, const std::string &attr_name, PyObject *assign); + INLINE_LINMATH std::string __repr__() const; }; #include "lpoint2_ext_src.I" diff --git a/panda/src/linmath/lpoint2_src.h b/panda/src/linmath/lpoint2_src.h index 090b49d4b9..070fc13086 100644 --- a/panda/src/linmath/lpoint2_src.h +++ b/panda/src/linmath/lpoint2_src.h @@ -17,13 +17,13 @@ class EXPCL_PANDA_LINMATH FLOATNAME(LPoint2) : public FLOATNAME(LVecBase2) { PUBLISHED: - INLINE_LINMATH FLOATNAME(LPoint2)() DEFAULT_CTOR; + INLINE_LINMATH FLOATNAME(LPoint2)() = default; INLINE_LINMATH FLOATNAME(LPoint2)(const FLOATNAME(LVecBase2)& copy); INLINE_LINMATH FLOATNAME(LPoint2)(FLOATTYPE fill_value); INLINE_LINMATH FLOATNAME(LPoint2)(FLOATTYPE x, FLOATTYPE y); - EXTENSION(INLINE_LINMATH PyObject *__getattr__(PyObject *self, const string &attr_name) const); - EXTENSION(INLINE_LINMATH int __setattr__(PyObject *self, const string &attr_name, PyObject *assign)); + EXTENSION(INLINE_LINMATH PyObject *__getattr__(PyObject *self, const std::string &attr_name) const); + EXTENSION(INLINE_LINMATH int __setattr__(PyObject *self, const std::string &attr_name, PyObject *assign)); INLINE_LINMATH static const FLOATNAME(LPoint2) &zero(); INLINE_LINMATH static const FLOATNAME(LPoint2) &unit_x(); @@ -51,7 +51,7 @@ PUBLISHED: INLINE_LINMATH FLOATNAME(LPoint2) project(const FLOATNAME(LVecBase2) &onto) const; #endif - EXTENSION(INLINE_LINMATH string __repr__() const); + EXTENSION(INLINE_LINMATH std::string __repr__() const); public: static TypeHandle get_class_type() { diff --git a/panda/src/linmath/lpoint3_ext_src.I b/panda/src/linmath/lpoint3_ext_src.I index e695988177..95cb1dbdd3 100644 --- a/panda/src/linmath/lpoint3_ext_src.I +++ b/panda/src/linmath/lpoint3_ext_src.I @@ -14,9 +14,9 @@ /** * */ -INLINE_LINMATH string Extension:: +INLINE_LINMATH std::string Extension:: __repr__() const { - ostringstream out; + std::ostringstream out; out << "LPoint3" << FLOATTOKEN << "(" << MAYBE_ZERO(_this->_v(0)) << ", " << MAYBE_ZERO(_this->_v(1)) << ", " @@ -28,7 +28,7 @@ __repr__() const { * This is used to implement swizzle masks. */ INLINE_LINMATH PyObject *Extension:: -__getattr__(PyObject *self, const string &attr_name) const { +__getattr__(PyObject *self, const std::string &attr_name) const { #ifndef CPPPARSER extern struct Dtool_PyTypedObject FLOATNAME(Dtool_LPoint2); extern struct Dtool_PyTypedObject FLOATNAME(Dtool_LPoint3); @@ -36,7 +36,7 @@ __getattr__(PyObject *self, const string &attr_name) const { #endif // Validate the attribute name. - for (string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { + for (std::string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { if (*it < 'x' || *it > 'z') { return Dtool_Raise_AttributeError(self, attr_name.c_str()); } @@ -76,7 +76,7 @@ __getattr__(PyObject *self, const string &attr_name) const { * This is used to implement write masks. */ INLINE_LINMATH int Extension:: -__setattr__(PyObject *self, const string &attr_name, PyObject *assign) { +__setattr__(PyObject *self, const std::string &attr_name, PyObject *assign) { // Upcall to LVecBase2. return invoke_extension(_this).__setattr__(self, attr_name, assign); } diff --git a/panda/src/linmath/lpoint3_ext_src.h b/panda/src/linmath/lpoint3_ext_src.h index f5aa413ec8..3c820d3a45 100644 --- a/panda/src/linmath/lpoint3_ext_src.h +++ b/panda/src/linmath/lpoint3_ext_src.h @@ -18,9 +18,9 @@ template<> class Extension : public ExtensionBase { public: - INLINE_LINMATH PyObject *__getattr__(PyObject *self, const string &attr_name) const; - INLINE_LINMATH int __setattr__(PyObject *self, const string &attr_name, PyObject *assign); - INLINE_LINMATH string __repr__() const; + INLINE_LINMATH PyObject *__getattr__(PyObject *self, const std::string &attr_name) const; + INLINE_LINMATH int __setattr__(PyObject *self, const std::string &attr_name, PyObject *assign); + INLINE_LINMATH std::string __repr__() const; }; #include "lpoint3_ext_src.I" diff --git a/panda/src/linmath/lpoint3_src.h b/panda/src/linmath/lpoint3_src.h index 3465fc37d1..3510aa329e 100644 --- a/panda/src/linmath/lpoint3_src.h +++ b/panda/src/linmath/lpoint3_src.h @@ -20,14 +20,14 @@ */ class EXPCL_PANDA_LINMATH FLOATNAME(LPoint3) : public FLOATNAME(LVecBase3) { PUBLISHED: - INLINE_LINMATH FLOATNAME(LPoint3)() DEFAULT_CTOR; + INLINE_LINMATH FLOATNAME(LPoint3)() = default; INLINE_LINMATH FLOATNAME(LPoint3)(const FLOATNAME(LVecBase3) ©); INLINE_LINMATH FLOATNAME(LPoint3)(FLOATTYPE fill_value); INLINE_LINMATH FLOATNAME(LPoint3)(FLOATTYPE x, FLOATTYPE y, FLOATTYPE z); INLINE_LINMATH FLOATNAME(LPoint3)(const FLOATNAME(LVecBase2) ©, FLOATTYPE z); - EXTENSION(INLINE_LINMATH PyObject *__getattr__(PyObject *self, const string &attr_name) const); - EXTENSION(INLINE_LINMATH int __setattr__(PyObject *self, const string &attr_name, PyObject *assign)); + EXTENSION(INLINE_LINMATH PyObject *__getattr__(PyObject *self, const std::string &attr_name) const); + EXTENSION(INLINE_LINMATH int __setattr__(PyObject *self, const std::string &attr_name, PyObject *assign)); INLINE_LINMATH static const FLOATNAME(LPoint3) &zero(); INLINE_LINMATH static const FLOATNAME(LPoint3) &unit_x(); @@ -74,7 +74,7 @@ PUBLISHED: FLOATTYPE up, CoordinateSystem cs = CS_default); - EXTENSION(INLINE_LINMATH string __repr__() const); + EXTENSION(INLINE_LINMATH std::string __repr__() const); public: static TypeHandle get_class_type() { diff --git a/panda/src/linmath/lpoint4_ext_src.I b/panda/src/linmath/lpoint4_ext_src.I index bef1b1d012..e4101b5ed9 100644 --- a/panda/src/linmath/lpoint4_ext_src.I +++ b/panda/src/linmath/lpoint4_ext_src.I @@ -14,9 +14,9 @@ /** * */ -INLINE_LINMATH string Extension:: +INLINE_LINMATH std::string Extension:: __repr__() const { - ostringstream out; + std::ostringstream out; out << "LPoint4" << FLOATTOKEN << "(" << MAYBE_ZERO(_this->_v(0)) << ", " << MAYBE_ZERO(_this->_v(1)) << ", " @@ -29,7 +29,7 @@ __repr__() const { * This is used to implement swizzle masks. */ INLINE_LINMATH PyObject *Extension:: -__getattr__(PyObject *self, const string &attr_name) const { +__getattr__(PyObject *self, const std::string &attr_name) const { #ifndef CPPPARSER extern struct Dtool_PyTypedObject FLOATNAME(Dtool_LPoint2); extern struct Dtool_PyTypedObject FLOATNAME(Dtool_LPoint3); @@ -37,7 +37,7 @@ __getattr__(PyObject *self, const string &attr_name) const { #endif // Validate the attribute name. - for (string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { + for (std::string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { if (*it < 'w' || *it > 'z') { return Dtool_Raise_AttributeError(self, attr_name.c_str()); } @@ -81,7 +81,7 @@ __getattr__(PyObject *self, const string &attr_name) const { * This is used to implement write masks. */ INLINE_LINMATH int Extension:: -__setattr__(PyObject *self, const string &attr_name, PyObject *assign) { +__setattr__(PyObject *self, const std::string &attr_name, PyObject *assign) { // Upcall to LVecBase4. return invoke_extension(_this).__setattr__(self, attr_name, assign); } diff --git a/panda/src/linmath/lpoint4_ext_src.h b/panda/src/linmath/lpoint4_ext_src.h index 88ae845ed4..82c9ea62f1 100644 --- a/panda/src/linmath/lpoint4_ext_src.h +++ b/panda/src/linmath/lpoint4_ext_src.h @@ -18,9 +18,9 @@ template<> class Extension : public ExtensionBase { public: - INLINE_LINMATH PyObject *__getattr__(PyObject *self, const string &attr_name) const; - INLINE_LINMATH int __setattr__(PyObject *self, const string &attr_name, PyObject *assign); - INLINE_LINMATH string __repr__() const; + INLINE_LINMATH PyObject *__getattr__(PyObject *self, const std::string &attr_name) const; + INLINE_LINMATH int __setattr__(PyObject *self, const std::string &attr_name, PyObject *assign); + INLINE_LINMATH std::string __repr__() const; }; #include "lpoint4_ext_src.I" diff --git a/panda/src/linmath/lpoint4_src.h b/panda/src/linmath/lpoint4_src.h index 103c018738..7a9902f55d 100644 --- a/panda/src/linmath/lpoint4_src.h +++ b/panda/src/linmath/lpoint4_src.h @@ -16,14 +16,14 @@ */ class EXPCL_PANDA_LINMATH FLOATNAME(LPoint4) : public FLOATNAME(LVecBase4) { PUBLISHED: - INLINE_LINMATH FLOATNAME(LPoint4)() DEFAULT_CTOR; + INLINE_LINMATH FLOATNAME(LPoint4)() = default; INLINE_LINMATH FLOATNAME(LPoint4)(const FLOATNAME(LVecBase4) ©); INLINE_LINMATH FLOATNAME(LPoint4)(FLOATTYPE fill_value); INLINE_LINMATH FLOATNAME(LPoint4)(FLOATTYPE x, FLOATTYPE y, FLOATTYPE z, FLOATTYPE w); INLINE_LINMATH FLOATNAME(LPoint4)(const FLOATNAME(LVecBase3) ©, FLOATTYPE w); - EXTENSION(INLINE_LINMATH PyObject *__getattr__(PyObject *self, const string &attr_name) const); - EXTENSION(INLINE_LINMATH int __setattr__(PyObject *self, const string &attr_name, PyObject *assign)); + EXTENSION(INLINE_LINMATH PyObject *__getattr__(PyObject *self, const std::string &attr_name) const); + EXTENSION(INLINE_LINMATH int __setattr__(PyObject *self, const std::string &attr_name, PyObject *assign)); INLINE_LINMATH static const FLOATNAME(LPoint4) &zero(); INLINE_LINMATH static const FLOATNAME(LPoint4) &unit_x(); @@ -59,7 +59,7 @@ PUBLISHED: INLINE_LINMATH FLOATNAME(LPoint4) project(const FLOATNAME(LVecBase4) &onto) const; #endif - EXTENSION(INLINE_LINMATH string __repr__() const); + EXTENSION(INLINE_LINMATH std::string __repr__() const); public: static TypeHandle get_class_type() { diff --git a/panda/src/linmath/lquaternion_src.I b/panda/src/linmath/lquaternion_src.I index 05f1d46bec..eb464d07f1 100644 --- a/panda/src/linmath/lquaternion_src.I +++ b/panda/src/linmath/lquaternion_src.I @@ -231,7 +231,7 @@ almost_same_direction(const FLOATNAME(LQuaternion) &other, * */ INLINE_LINMATH void FLOATNAME(LQuaternion):: -output(ostream& os) const { +output(std::ostream& os) const { os << MAYBE_ZERO(_v(0)) << " + " << MAYBE_ZERO(_v(1)) << "i + " << MAYBE_ZERO(_v(2)) << "j + " diff --git a/panda/src/linmath/lquaternion_src.h b/panda/src/linmath/lquaternion_src.h index 00ba2a934f..52bbc6fff7 100644 --- a/panda/src/linmath/lquaternion_src.h +++ b/panda/src/linmath/lquaternion_src.h @@ -68,7 +68,7 @@ PUBLISHED: INLINE_LINMATH bool almost_same_direction( const FLOATNAME(LQuaternion) &other, FLOATTYPE threshold) const; - INLINE_LINMATH void output(ostream&) const; + INLINE_LINMATH void output(std::ostream&) const; void extract_to_matrix(FLOATNAME(LMatrix3) &m) const; void extract_to_matrix(FLOATNAME(LMatrix4) &m) const; @@ -127,7 +127,7 @@ private: }; -INLINE ostream& operator<<(ostream& os, const FLOATNAME(LQuaternion)& q) { +INLINE std::ostream& operator<<(std::ostream& os, const FLOATNAME(LQuaternion)& q) { q.output(os); return os; } diff --git a/panda/src/linmath/lsimpleMatrix.I b/panda/src/linmath/lsimpleMatrix.I index 7ce8b4ed69..6d322bfb75 100644 --- a/panda/src/linmath/lsimpleMatrix.I +++ b/panda/src/linmath/lsimpleMatrix.I @@ -11,33 +11,6 @@ * @date 2011-12-15 */ -/** - * - */ -template -INLINE LSimpleMatrix:: -LSimpleMatrix() { - // No default initialization. -} - -/** - * - */ -template -INLINE LSimpleMatrix:: -LSimpleMatrix(const LSimpleMatrix ©) { - memcpy(_array, copy._array, sizeof(_array)); -} - -/** - * - */ -template -INLINE void LSimpleMatrix:: -operator = (const LSimpleMatrix ©) { - memcpy(_array, copy._array, sizeof(_array)); -} - /** * */ diff --git a/panda/src/linmath/lsimpleMatrix.h b/panda/src/linmath/lsimpleMatrix.h index 3228caf5bb..faeecd9516 100644 --- a/panda/src/linmath/lsimpleMatrix.h +++ b/panda/src/linmath/lsimpleMatrix.h @@ -28,9 +28,6 @@ template class LSimpleMatrix { public: - INLINE LSimpleMatrix(); - INLINE LSimpleMatrix(const LSimpleMatrix ©); - INLINE void operator = (const LSimpleMatrix ©); INLINE const FloatType &operator () (int row, int col) const; INLINE FloatType &operator () (int row, int col); INLINE const FloatType &operator () (int col) const; diff --git a/panda/src/linmath/lvecBase2_ext_src.I b/panda/src/linmath/lvecBase2_ext_src.I index 40399dc327..c76cb6649f 100644 --- a/panda/src/linmath/lvecBase2_ext_src.I +++ b/panda/src/linmath/lvecBase2_ext_src.I @@ -27,9 +27,9 @@ /** * */ -INLINE_LINMATH string Extension:: +INLINE_LINMATH std::string Extension:: __repr__() const { - ostringstream out; + std::ostringstream out; out << "LVecBase2" << FLOATTOKEN << "(" << MAYBE_ZERO(_this->_v(0)) << ", " << MAYBE_ZERO(_this->_v(1)) << ")"; @@ -46,8 +46,8 @@ __reduce__(PyObject *self) const { // object whose constructor we should call (e.g. this), and the arguments // necessary to reconstruct this object. PyObject *this_class = PyObject_Type(self); - if (this_class == NULL) { - return NULL; + if (this_class == nullptr) { + return nullptr; } #if FLOATTOKEN == 'i' @@ -69,7 +69,7 @@ __reduce__(PyObject *self) const { * This is used to implement swizzle masks. */ INLINE_LINMATH PyObject *Extension:: -__getattr__(PyObject *self, const string &attr_name) const { +__getattr__(PyObject *self, const std::string &attr_name) const { #ifndef CPPPARSER extern struct Dtool_PyTypedObject FLOATNAME(Dtool_LVecBase2); extern struct Dtool_PyTypedObject FLOATNAME(Dtool_LVecBase3); @@ -77,7 +77,7 @@ __getattr__(PyObject *self, const string &attr_name) const { #endif // Validate the attribute name. - for (string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { + for (std::string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { if (*it != 'x' && *it != 'y') { return Dtool_Raise_AttributeError(self, attr_name.c_str()); } @@ -117,10 +117,10 @@ __getattr__(PyObject *self, const string &attr_name) const { * This is used to implement write masks. */ INLINE_LINMATH int Extension:: -__setattr__(PyObject *self, const string &attr_name, PyObject *assign) { +__setattr__(PyObject *self, const std::string &attr_name, PyObject *assign) { #ifndef NDEBUG // Validate the attribute name. - for (string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { + for (std::string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { if (*it != 'x' && *it != 'y') { Dtool_Raise_AttributeError(self, attr_name.c_str()); return -1; @@ -133,7 +133,7 @@ __setattr__(PyObject *self, const string &attr_name, PyObject *assign) { // Whoosh. PyObject* fast = PySequence_Fast(assign, ""); - nassertr(fast != NULL, -1); + nassertr(fast != nullptr, -1); // Let's be strict about size mismatches, to prevent user error. if (PySequence_Fast_GET_SIZE(fast) != (int)attr_name.size()) { @@ -148,7 +148,7 @@ __setattr__(PyObject *self, const string &attr_name, PyObject *assign) { for (size_t i = 0; i < attr_name.size(); ++i) { PyObject* fl = PYNUMBER_FLOATTYPE(items[i]); - if (fl == NULL) { + if (fl == nullptr) { // Oh darn. Not when we've come this far. #ifdef FLOATTYPE_IS_INT PyErr_SetString(PyExc_ValueError, "a sequence of integers is required"); @@ -169,7 +169,7 @@ __setattr__(PyObject *self, const string &attr_name, PyObject *assign) { } else { // Maybe it's a single floating-point value. PyObject* fl = PYNUMBER_FLOATTYPE(assign); - if (fl == NULL) { + if (fl == nullptr) { // It's not a floating-point value either? Sheesh, I don't know what to // do with it then. if (attr_name.size() == 1) { @@ -189,7 +189,7 @@ __setattr__(PyObject *self, const string &attr_name, PyObject *assign) { // Loop through the components in the attribute name, and assign the // floating-point value to every one of them. - for (string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { + for (std::string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { _this->_v((*it) - 'x') = value; } } diff --git a/panda/src/linmath/lvecBase2_ext_src.h b/panda/src/linmath/lvecBase2_ext_src.h index 3d6efe4831..9abffe5859 100644 --- a/panda/src/linmath/lvecBase2_ext_src.h +++ b/panda/src/linmath/lvecBase2_ext_src.h @@ -19,9 +19,9 @@ template<> class Extension : public ExtensionBase { public: INLINE_LINMATH PyObject *__reduce__(PyObject *self) const; - INLINE_LINMATH PyObject *__getattr__(PyObject *self, const string &attr_name) const; - INLINE_LINMATH int __setattr__(PyObject *self, const string &attr_name, PyObject *assign); - INLINE_LINMATH string __repr__() const; + INLINE_LINMATH PyObject *__getattr__(PyObject *self, const std::string &attr_name) const; + INLINE_LINMATH int __setattr__(PyObject *self, const std::string &attr_name, PyObject *assign); + INLINE_LINMATH std::string __repr__() const; INLINE_LINMATH FLOATNAME(LVecBase2) __pow__(FLOATTYPE exponent) const; INLINE_LINMATH PyObject *__ipow__(PyObject *self, FLOATTYPE exponent); diff --git a/panda/src/linmath/lvecBase2_src.I b/panda/src/linmath/lvecBase2_src.I index 401e2e346a..1ef2c133a7 100644 --- a/panda/src/linmath/lvecBase2_src.I +++ b/panda/src/linmath/lvecBase2_src.I @@ -631,7 +631,7 @@ almost_equal(const FLOATNAME(LVecBase2) &other) const { * */ INLINE_LINMATH void FLOATNAME(LVecBase2):: -output(ostream &out) const { +output(std::ostream &out) const { out << MAYBE_ZERO(_v(0)) << " " << MAYBE_ZERO(_v(1)); } diff --git a/panda/src/linmath/lvecBase2_src.h b/panda/src/linmath/lvecBase2_src.h index d0c0693f55..c868f90d60 100644 --- a/panda/src/linmath/lvecBase2_src.h +++ b/panda/src/linmath/lvecBase2_src.h @@ -30,7 +30,7 @@ PUBLISHED: #endif }; - INLINE_LINMATH FLOATNAME(LVecBase2)() DEFAULT_CTOR; + INLINE_LINMATH FLOATNAME(LVecBase2)() = default; INLINE_LINMATH FLOATNAME(LVecBase2)(FLOATTYPE fill_value); INLINE_LINMATH FLOATNAME(LVecBase2)(FLOATTYPE x, FLOATTYPE y); ALLOC_DELETED_CHAIN(FLOATNAME(LVecBase2)); @@ -45,12 +45,12 @@ PUBLISHED: INLINE_LINMATH static const FLOATNAME(LVecBase2) &unit_y(); EXTENSION(INLINE_LINMATH PyObject *__reduce__(PyObject *self) const); - EXTENSION(INLINE_LINMATH PyObject *__getattr__(PyObject *self, const string &attr_name) const); - EXTENSION(INLINE_LINMATH int __setattr__(PyObject *self, const string &attr_name, PyObject *assign)); + EXTENSION(INLINE_LINMATH PyObject *__getattr__(PyObject *self, const std::string &attr_name) const); + EXTENSION(INLINE_LINMATH int __setattr__(PyObject *self, const std::string &attr_name, PyObject *assign)); INLINE_LINMATH FLOATTYPE operator [](int i) const; INLINE_LINMATH FLOATTYPE &operator [](int i); - CONSTEXPR static int size() { return 2; } + constexpr static int size() { return 2; } INLINE_LINMATH bool is_nan() const; @@ -74,7 +74,7 @@ PUBLISHED: INLINE_LINMATH void add_y(FLOATTYPE value); INLINE_LINMATH const FLOATTYPE *get_data() const; - CONSTEXPR static int get_num_components() { return 2; } + constexpr static int get_num_components() { return 2; } public: INLINE_LINMATH iterator begin(); @@ -143,8 +143,8 @@ PUBLISHED: FLOATTYPE threshold) const; INLINE_LINMATH bool almost_equal(const FLOATNAME(LVecBase2) &other) const; - INLINE_LINMATH void output(ostream &out) const; - EXTENSION(INLINE_LINMATH string __repr__() const); + INLINE_LINMATH void output(std::ostream &out) const; + EXTENSION(INLINE_LINMATH std::string __repr__() const); INLINE_LINMATH void write_datagram_fixed(Datagram &destination) const; INLINE_LINMATH void read_datagram_fixed(DatagramIterator &source); @@ -180,7 +180,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const FLOATNAME(LVecBase2) &vec) { +INLINE std::ostream &operator << (std::ostream &out, const FLOATNAME(LVecBase2) &vec) { vec.output(out); return out; } diff --git a/panda/src/linmath/lvecBase3_ext_src.I b/panda/src/linmath/lvecBase3_ext_src.I index a2705edbb6..ba163ec637 100644 --- a/panda/src/linmath/lvecBase3_ext_src.I +++ b/panda/src/linmath/lvecBase3_ext_src.I @@ -27,9 +27,9 @@ /** * */ -INLINE_LINMATH string Extension:: +INLINE_LINMATH std::string Extension:: __repr__() const { - ostringstream out; + std::ostringstream out; out << "LVecBase3" << FLOATTOKEN << "(" << MAYBE_ZERO(_this->_v(0)) << ", " << MAYBE_ZERO(_this->_v(1)) << ", " @@ -47,8 +47,8 @@ __reduce__(PyObject *self) const { // object whose constructor we should call (e.g. this), and the arguments // necessary to reconstruct this object. PyObject *this_class = PyObject_Type(self); - if (this_class == NULL) { - return NULL; + if (this_class == nullptr) { + return nullptr; } #if FLOATTOKEN == 'i' @@ -70,7 +70,7 @@ __reduce__(PyObject *self) const { * This is used to implement swizzle masks. */ INLINE_LINMATH PyObject *Extension:: -__getattr__(PyObject *self, const string &attr_name) const { +__getattr__(PyObject *self, const std::string &attr_name) const { #ifndef CPPPARSER extern struct Dtool_PyTypedObject FLOATNAME(Dtool_LVecBase2); extern struct Dtool_PyTypedObject FLOATNAME(Dtool_LVecBase3); @@ -78,7 +78,7 @@ __getattr__(PyObject *self, const string &attr_name) const { #endif // Validate the attribute name. - for (string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { + for (std::string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { if (*it < 'x' || *it > 'z') { return Dtool_Raise_AttributeError(self, attr_name.c_str()); } @@ -118,10 +118,10 @@ __getattr__(PyObject *self, const string &attr_name) const { * This is used to implement write masks. */ INLINE_LINMATH int Extension:: -__setattr__(PyObject *self, const string &attr_name, PyObject *assign) { +__setattr__(PyObject *self, const std::string &attr_name, PyObject *assign) { #ifndef NDEBUG // Validate the attribute name. - for (string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { + for (std::string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { if (*it < 'x' || *it > 'z') { Dtool_Raise_AttributeError(self, attr_name.c_str()); return -1; @@ -134,7 +134,7 @@ __setattr__(PyObject *self, const string &attr_name, PyObject *assign) { // Whoosh. PyObject* fast = PySequence_Fast(assign, ""); - nassertr(fast != NULL, -1); + nassertr(fast != nullptr, -1); // Let's be strict about size mismatches, to prevent user error. if (PySequence_Fast_GET_SIZE(fast) != (int)attr_name.size()) { @@ -149,7 +149,7 @@ __setattr__(PyObject *self, const string &attr_name, PyObject *assign) { for (size_t i = 0; i < attr_name.size(); ++i) { PyObject* fl = PYNUMBER_FLOATTYPE(items[i]); - if (fl == NULL) { + if (fl == nullptr) { // Oh darn. Not when we've come this far. #ifdef FLOATTYPE_IS_INT PyErr_SetString(PyExc_ValueError, "a sequence of integers is required"); @@ -170,7 +170,7 @@ __setattr__(PyObject *self, const string &attr_name, PyObject *assign) { } else { // Maybe it's a single floating-point value. PyObject* fl = PYNUMBER_FLOATTYPE(assign); - if (fl == NULL) { + if (fl == nullptr) { // It's not a floating-point value either? Sheesh, I don't know what to // do with it then. if (attr_name.size() == 1) { @@ -190,7 +190,7 @@ __setattr__(PyObject *self, const string &attr_name, PyObject *assign) { // Loop through the components in the attribute name, and assign the // floating-point value to every one of them. - for (string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { + for (std::string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { _this->_v((*it) - 'x') = value; } } diff --git a/panda/src/linmath/lvecBase3_ext_src.h b/panda/src/linmath/lvecBase3_ext_src.h index e88a28790b..4f91322f23 100644 --- a/panda/src/linmath/lvecBase3_ext_src.h +++ b/panda/src/linmath/lvecBase3_ext_src.h @@ -19,9 +19,9 @@ template<> class Extension : public ExtensionBase { public: INLINE_LINMATH PyObject *__reduce__(PyObject *self) const; - INLINE_LINMATH PyObject *__getattr__(PyObject *self, const string &attr_name) const; - INLINE_LINMATH int __setattr__(PyObject *self, const string &attr_name, PyObject *assign); - INLINE_LINMATH string __repr__() const; + INLINE_LINMATH PyObject *__getattr__(PyObject *self, const std::string &attr_name) const; + INLINE_LINMATH int __setattr__(PyObject *self, const std::string &attr_name, PyObject *assign); + INLINE_LINMATH std::string __repr__() const; INLINE_LINMATH FLOATNAME(LVecBase3) __pow__(FLOATTYPE exponent) const; INLINE_LINMATH PyObject *__ipow__(PyObject *self, FLOATTYPE exponent); diff --git a/panda/src/linmath/lvecBase3_src.I b/panda/src/linmath/lvecBase3_src.I index eeaea584d5..b34b783faf 100644 --- a/panda/src/linmath/lvecBase3_src.I +++ b/panda/src/linmath/lvecBase3_src.I @@ -795,7 +795,7 @@ almost_equal(const FLOATNAME(LVecBase3) &other) const { * */ INLINE_LINMATH void FLOATNAME(LVecBase3):: -output(ostream &out) const { +output(std::ostream &out) const { out << MAYBE_ZERO(_v(0)) << " " << MAYBE_ZERO(_v(1)) << " " << MAYBE_ZERO(_v(2)); diff --git a/panda/src/linmath/lvecBase3_src.h b/panda/src/linmath/lvecBase3_src.h index fb9b67ca27..3536615aeb 100644 --- a/panda/src/linmath/lvecBase3_src.h +++ b/panda/src/linmath/lvecBase3_src.h @@ -30,7 +30,7 @@ PUBLISHED: #endif }; - INLINE_LINMATH FLOATNAME(LVecBase3)() DEFAULT_CTOR; + INLINE_LINMATH FLOATNAME(LVecBase3)() = default; INLINE_LINMATH FLOATNAME(LVecBase3)(FLOATTYPE fill_value); INLINE_LINMATH FLOATNAME(LVecBase3)(FLOATTYPE x, FLOATTYPE y, FLOATTYPE z); INLINE_LINMATH FLOATNAME(LVecBase3)(const FLOATNAME(LVecBase2) ©, FLOATTYPE z); @@ -47,12 +47,12 @@ PUBLISHED: INLINE_LINMATH static const FLOATNAME(LVecBase3) &unit_z(); EXTENSION(INLINE_LINMATH PyObject *__reduce__(PyObject *self) const); - EXTENSION(INLINE_LINMATH PyObject *__getattr__(PyObject *self, const string &attr_name) const); - EXTENSION(INLINE_LINMATH int __setattr__(PyObject *self, const string &attr_name, PyObject *assign)); + EXTENSION(INLINE_LINMATH PyObject *__getattr__(PyObject *self, const std::string &attr_name) const); + EXTENSION(INLINE_LINMATH int __setattr__(PyObject *self, const std::string &attr_name, PyObject *assign)); INLINE_LINMATH FLOATTYPE operator [](int i) const; INLINE_LINMATH FLOATTYPE &operator [](int i); - CONSTEXPR static int size() { return 3; } + constexpr static int size() { return 3; } INLINE_LINMATH bool is_nan() const; @@ -87,7 +87,7 @@ PUBLISHED: INLINE_LINMATH void add_z(FLOATTYPE value); INLINE_LINMATH const FLOATTYPE *get_data() const; - CONSTEXPR static int get_num_components() { return 3; } + constexpr static int get_num_components() { return 3; } public: INLINE_LINMATH iterator begin(); @@ -164,8 +164,8 @@ PUBLISHED: FLOATTYPE threshold) const; INLINE_LINMATH bool almost_equal(const FLOATNAME(LVecBase3) &other) const; - INLINE_LINMATH void output(ostream &out) const; - EXTENSION(INLINE_LINMATH string __repr__() const); + INLINE_LINMATH void output(std::ostream &out) const; + EXTENSION(INLINE_LINMATH std::string __repr__() const); INLINE_LINMATH void write_datagram_fixed(Datagram &destination) const; INLINE_LINMATH void read_datagram_fixed(DatagramIterator &source); @@ -199,7 +199,7 @@ private: }; -INLINE ostream &operator << (ostream &out, const FLOATNAME(LVecBase3) &vec) { +INLINE std::ostream &operator << (std::ostream &out, const FLOATNAME(LVecBase3) &vec) { vec.output(out); return out; }; diff --git a/panda/src/linmath/lvecBase4_ext_src.I b/panda/src/linmath/lvecBase4_ext_src.I index 76eee6b7bf..78d359c315 100644 --- a/panda/src/linmath/lvecBase4_ext_src.I +++ b/panda/src/linmath/lvecBase4_ext_src.I @@ -27,9 +27,9 @@ /** * */ -INLINE_LINMATH string Extension:: +INLINE_LINMATH std::string Extension:: __repr__() const { - ostringstream out; + std::ostringstream out; out << "LVecBase4" << FLOATTOKEN << "(" << MAYBE_ZERO(_this->_v(0)) << ", " << MAYBE_ZERO(_this->_v(1)) << ", " @@ -48,8 +48,8 @@ __reduce__(PyObject *self) const { // object whose constructor we should call (e.g. this), and the arguments // necessary to reconstruct this object. PyObject *this_class = PyObject_Type(self); - if (this_class == NULL) { - return NULL; + if (this_class == nullptr) { + return nullptr; } #if FLOATTOKEN == 'i' @@ -71,7 +71,7 @@ __reduce__(PyObject *self) const { * This is used to implement swizzle masks. */ INLINE_LINMATH PyObject *Extension:: -__getattr__(PyObject *self, const string &attr_name) const { +__getattr__(PyObject *self, const std::string &attr_name) const { #ifndef CPPPARSER extern struct Dtool_PyTypedObject FLOATNAME(Dtool_LVecBase2); extern struct Dtool_PyTypedObject FLOATNAME(Dtool_LVecBase3); @@ -79,7 +79,7 @@ __getattr__(PyObject *self, const string &attr_name) const { #endif // Validate the attribute name. - for (string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { + for (std::string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { if (*it < 'w' || *it > 'z') { return Dtool_Raise_AttributeError(self, attr_name.c_str()); } @@ -123,10 +123,10 @@ __getattr__(PyObject *self, const string &attr_name) const { * This is used to implement write masks. */ INLINE_LINMATH int Extension:: -__setattr__(PyObject *self, const string &attr_name, PyObject *assign) { +__setattr__(PyObject *self, const std::string &attr_name, PyObject *assign) { #ifndef NDEBUG // Validate the attribute name. - for (string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { + for (std::string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { if (*it < 'w' || *it > 'z') { Dtool_Raise_AttributeError(self, attr_name.c_str()); return -1; @@ -139,7 +139,7 @@ __setattr__(PyObject *self, const string &attr_name, PyObject *assign) { // Whoosh. PyObject* fast = PySequence_Fast(assign, ""); - nassertr(fast != NULL, -1); + nassertr(fast != nullptr, -1); // Let's be strict about size mismatches, to prevent user error. if (PySequence_Fast_GET_SIZE(fast) != (int)attr_name.size()) { @@ -154,7 +154,7 @@ __setattr__(PyObject *self, const string &attr_name, PyObject *assign) { for (size_t i = 0; i < attr_name.size(); ++i) { PyObject* fl = PYNUMBER_FLOATTYPE(items[i]); - if (fl == NULL) { + if (fl == nullptr) { // Oh darn. Not when we've come this far. #ifdef FLOATTYPE_IS_INT PyErr_SetString(PyExc_ValueError, "a sequence of integers is required"); @@ -176,7 +176,7 @@ __setattr__(PyObject *self, const string &attr_name, PyObject *assign) { // Maybe it's a single floating-point value. PyObject* fl = PYNUMBER_FLOATTYPE(assign); - if (fl == NULL) { + if (fl == nullptr) { // It's not a floating-point value either? Sheesh, I don't know what to // do with it then. if (attr_name.size() == 1) { @@ -196,7 +196,7 @@ __setattr__(PyObject *self, const string &attr_name, PyObject *assign) { // Loop through the components in the attribute name, and assign the // floating-point value to every one of them. - for (string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { + for (std::string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { _this->_v(((*it) == 'w') ? 3 : (*it) - 'x') = value; } } diff --git a/panda/src/linmath/lvecBase4_ext_src.h b/panda/src/linmath/lvecBase4_ext_src.h index b7a916fd60..9d7d837c89 100644 --- a/panda/src/linmath/lvecBase4_ext_src.h +++ b/panda/src/linmath/lvecBase4_ext_src.h @@ -19,9 +19,9 @@ template<> class Extension : public ExtensionBase { public: INLINE_LINMATH PyObject *__reduce__(PyObject *self) const; - INLINE_LINMATH PyObject *__getattr__(PyObject *self, const string &attr_name) const; - INLINE_LINMATH int __setattr__(PyObject *self, const string &attr_name, PyObject *assign); - INLINE_LINMATH string __repr__() const; + INLINE_LINMATH PyObject *__getattr__(PyObject *self, const std::string &attr_name) const; + INLINE_LINMATH int __setattr__(PyObject *self, const std::string &attr_name, PyObject *assign); + INLINE_LINMATH std::string __repr__() const; INLINE_LINMATH FLOATNAME(LVecBase4) __pow__(FLOATTYPE exponent) const; INLINE_LINMATH PyObject *__ipow__(PyObject *self, FLOATTYPE exponent); diff --git a/panda/src/linmath/lvecBase4_src.I b/panda/src/linmath/lvecBase4_src.I index bdf7e917b6..9cf554454b 100644 --- a/panda/src/linmath/lvecBase4_src.I +++ b/panda/src/linmath/lvecBase4_src.I @@ -799,7 +799,7 @@ almost_equal(const FLOATNAME(LVecBase4) &other) const { * */ INLINE_LINMATH void FLOATNAME(LVecBase4):: -output(ostream &out) const { +output(std::ostream &out) const { out << MAYBE_ZERO(_v(0)) << " " << MAYBE_ZERO(_v(1)) << " " << MAYBE_ZERO(_v(2)) << " " diff --git a/panda/src/linmath/lvecBase4_src.h b/panda/src/linmath/lvecBase4_src.h index d04201d988..b634791d91 100644 --- a/panda/src/linmath/lvecBase4_src.h +++ b/panda/src/linmath/lvecBase4_src.h @@ -36,7 +36,7 @@ PUBLISHED: #endif }; - INLINE_LINMATH FLOATNAME(LVecBase4)() DEFAULT_CTOR; + INLINE_LINMATH FLOATNAME(LVecBase4)() = default; INLINE_LINMATH FLOATNAME(LVecBase4)(FLOATTYPE fill_value); INLINE_LINMATH FLOATNAME(LVecBase4)(FLOATTYPE x, FLOATTYPE y, FLOATTYPE z, FLOATTYPE w); INLINE_LINMATH FLOATNAME(LVecBase4)(const FLOATNAME(UnalignedLVecBase4) ©); @@ -57,12 +57,12 @@ PUBLISHED: INLINE_LINMATH static const FLOATNAME(LVecBase4) &unit_w(); EXTENSION(INLINE_LINMATH PyObject *__reduce__(PyObject *self) const); - EXTENSION(INLINE_LINMATH PyObject *__getattr__(PyObject *self, const string &attr_name) const); - EXTENSION(INLINE_LINMATH int __setattr__(PyObject *self, const string &attr_name, PyObject *assign)); + EXTENSION(INLINE_LINMATH PyObject *__getattr__(PyObject *self, const std::string &attr_name) const); + EXTENSION(INLINE_LINMATH int __setattr__(PyObject *self, const std::string &attr_name, PyObject *assign)); INLINE_LINMATH FLOATTYPE operator [](int i) const; INLINE_LINMATH FLOATTYPE &operator [](int i); - CONSTEXPR static int size() { return 4; } + constexpr static int size() { return 4; } INLINE_LINMATH bool is_nan() const; @@ -100,7 +100,7 @@ PUBLISHED: INLINE_LINMATH void add_w(FLOATTYPE value); INLINE_LINMATH const FLOATTYPE *get_data() const; - CONSTEXPR static int get_num_components() { return 4; } + constexpr static int get_num_components() { return 4; } INLINE_LINMATH void extract_data(float*){}; public: @@ -170,8 +170,8 @@ PUBLISHED: FLOATTYPE threshold) const; INLINE_LINMATH bool almost_equal(const FLOATNAME(LVecBase4) &other) const; - INLINE_LINMATH void output(ostream &out) const; - EXTENSION(INLINE_LINMATH string __repr__() const); + INLINE_LINMATH void output(std::ostream &out) const; + EXTENSION(INLINE_LINMATH std::string __repr__() const); INLINE_LINMATH void write_datagram_fixed(Datagram &destination) const; INLINE_LINMATH void read_datagram_fixed(DatagramIterator &source); @@ -228,7 +228,7 @@ PUBLISHED: #endif }; - INLINE_LINMATH FLOATNAME(UnalignedLVecBase4)() DEFAULT_CTOR; + INLINE_LINMATH FLOATNAME(UnalignedLVecBase4)() = default; INLINE_LINMATH FLOATNAME(UnalignedLVecBase4)(const FLOATNAME(LVecBase4) ©); INLINE_LINMATH FLOATNAME(UnalignedLVecBase4)(FLOATTYPE fill_value); INLINE_LINMATH FLOATNAME(UnalignedLVecBase4)(FLOATTYPE x, FLOATTYPE y, FLOATTYPE z, FLOATTYPE w); @@ -238,10 +238,10 @@ PUBLISHED: INLINE_LINMATH FLOATTYPE operator [](int i) const; INLINE_LINMATH FLOATTYPE &operator [](int i); - CONSTEXPR static int size() { return 4; } + constexpr static int size() { return 4; } INLINE_LINMATH const FLOATTYPE *get_data() const; - CONSTEXPR static int get_num_components() { return 4; } + constexpr static int get_num_components() { return 4; } INLINE_LINMATH bool operator == (const FLOATNAME(UnalignedLVecBase4) &other) const; INLINE_LINMATH bool operator != (const FLOATNAME(UnalignedLVecBase4) &other) const; @@ -261,7 +261,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const FLOATNAME(LVecBase4) &vec) { +INLINE std::ostream &operator << (std::ostream &out, const FLOATNAME(LVecBase4) &vec) { vec.output(out); return out; } diff --git a/panda/src/linmath/lvector2_ext_src.I b/panda/src/linmath/lvector2_ext_src.I index dd4dc5e95e..0d9aaa0258 100644 --- a/panda/src/linmath/lvector2_ext_src.I +++ b/panda/src/linmath/lvector2_ext_src.I @@ -14,9 +14,9 @@ /** * */ -INLINE_LINMATH string Extension:: +INLINE_LINMATH std::string Extension:: __repr__() const { - ostringstream out; + std::ostringstream out; out << "LVector2" << FLOATTOKEN << "(" << MAYBE_ZERO(_this->_v(0)) << ", " << MAYBE_ZERO(_this->_v(1)) << ")"; @@ -27,7 +27,7 @@ __repr__() const { * This is used to implement swizzle masks. */ INLINE_LINMATH PyObject *Extension:: -__getattr__(PyObject *self, const string &attr_name) const { +__getattr__(PyObject *self, const std::string &attr_name) const { #ifndef CPPPARSER extern struct Dtool_PyTypedObject FLOATNAME(Dtool_LVector2); extern struct Dtool_PyTypedObject FLOATNAME(Dtool_LVector3); @@ -35,7 +35,7 @@ __getattr__(PyObject *self, const string &attr_name) const { #endif // Validate the attribute name. - for (string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { + for (std::string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { if (*it != 'x' && *it != 'y') { return Dtool_Raise_AttributeError(self, attr_name.c_str()); } @@ -75,7 +75,7 @@ __getattr__(PyObject *self, const string &attr_name) const { * This is used to implement write masks. */ INLINE_LINMATH int Extension:: -__setattr__(PyObject *self, const string &attr_name, PyObject *assign) { +__setattr__(PyObject *self, const std::string &attr_name, PyObject *assign) { // Upcall to LVecBase2. return invoke_extension(_this).__setattr__(self, attr_name, assign); } diff --git a/panda/src/linmath/lvector2_ext_src.h b/panda/src/linmath/lvector2_ext_src.h index fb16cbda9d..0028c73431 100644 --- a/panda/src/linmath/lvector2_ext_src.h +++ b/panda/src/linmath/lvector2_ext_src.h @@ -18,9 +18,9 @@ template<> class Extension : public ExtensionBase { public: - INLINE_LINMATH PyObject *__getattr__(PyObject *self, const string &attr_name) const; - INLINE_LINMATH int __setattr__(PyObject *self, const string &attr_name, PyObject *assign); - INLINE_LINMATH string __repr__() const; + INLINE_LINMATH PyObject *__getattr__(PyObject *self, const std::string &attr_name) const; + INLINE_LINMATH int __setattr__(PyObject *self, const std::string &attr_name, PyObject *assign); + INLINE_LINMATH std::string __repr__() const; }; #include "lvector2_ext_src.I" diff --git a/panda/src/linmath/lvector2_src.h b/panda/src/linmath/lvector2_src.h index 4a78cc7519..1454205985 100644 --- a/panda/src/linmath/lvector2_src.h +++ b/panda/src/linmath/lvector2_src.h @@ -17,13 +17,13 @@ class EXPCL_PANDA_LINMATH FLOATNAME(LVector2) : public FLOATNAME(LVecBase2) { PUBLISHED: - INLINE_LINMATH FLOATNAME(LVector2)() DEFAULT_CTOR; + INLINE_LINMATH FLOATNAME(LVector2)() = default; INLINE_LINMATH FLOATNAME(LVector2)(const FLOATNAME(LVecBase2)& copy); INLINE_LINMATH FLOATNAME(LVector2)(FLOATTYPE fill_value); INLINE_LINMATH FLOATNAME(LVector2)(FLOATTYPE x, FLOATTYPE y); - EXTENSION(INLINE_LINMATH PyObject *__getattr__(PyObject *self, const string &attr_name) const); - EXTENSION(INLINE_LINMATH int __setattr__(PyObject *self, const string &attr_name, PyObject *assign)); + EXTENSION(INLINE_LINMATH PyObject *__getattr__(PyObject *self, const std::string &attr_name) const); + EXTENSION(INLINE_LINMATH int __setattr__(PyObject *self, const std::string &attr_name, PyObject *assign)); INLINE_LINMATH static const FLOATNAME(LVector2) &zero(); INLINE_LINMATH static const FLOATNAME(LVector2) &unit_x(); @@ -47,7 +47,7 @@ PUBLISHED: INLINE_LINMATH FLOATTYPE signed_angle_deg(const FLOATNAME(LVector2) &other) const; #endif - EXTENSION(INLINE_LINMATH string __repr__() const); + EXTENSION(INLINE_LINMATH std::string __repr__() const); public: static TypeHandle get_class_type() { diff --git a/panda/src/linmath/lvector3_ext_src.I b/panda/src/linmath/lvector3_ext_src.I index 155c2a013a..ee620ba30a 100644 --- a/panda/src/linmath/lvector3_ext_src.I +++ b/panda/src/linmath/lvector3_ext_src.I @@ -14,9 +14,9 @@ /** * */ -INLINE_LINMATH string Extension:: +INLINE_LINMATH std::string Extension:: __repr__() const { - ostringstream out; + std::ostringstream out; out << "LVector3" << FLOATTOKEN << "(" << MAYBE_ZERO(_this->_v(0)) << ", " << MAYBE_ZERO(_this->_v(1)) << ", " @@ -28,7 +28,7 @@ __repr__() const { * This is used to implement swizzle masks. */ INLINE_LINMATH PyObject *Extension:: -__getattr__(PyObject *self, const string &attr_name) const { +__getattr__(PyObject *self, const std::string &attr_name) const { #ifndef CPPPARSER extern struct Dtool_PyTypedObject FLOATNAME(Dtool_LVector2); extern struct Dtool_PyTypedObject FLOATNAME(Dtool_LVector3); @@ -36,7 +36,7 @@ __getattr__(PyObject *self, const string &attr_name) const { #endif // Validate the attribute name. - for (string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { + for (std::string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { if (*it < 'x' || *it > 'z') { return Dtool_Raise_AttributeError(self, attr_name.c_str()); } @@ -76,7 +76,7 @@ __getattr__(PyObject *self, const string &attr_name) const { * This is used to implement write masks. */ INLINE_LINMATH int Extension:: -__setattr__(PyObject *self, const string &attr_name, PyObject *assign) { +__setattr__(PyObject *self, const std::string &attr_name, PyObject *assign) { // Upcall to LVecBase3. return invoke_extension(_this).__setattr__(self, attr_name, assign); } diff --git a/panda/src/linmath/lvector3_ext_src.h b/panda/src/linmath/lvector3_ext_src.h index 4283e61d36..577382dcd8 100644 --- a/panda/src/linmath/lvector3_ext_src.h +++ b/panda/src/linmath/lvector3_ext_src.h @@ -18,9 +18,9 @@ template<> class Extension : public ExtensionBase { public: - INLINE_LINMATH PyObject *__getattr__(PyObject *self, const string &attr_name) const; - INLINE_LINMATH int __setattr__(PyObject *self, const string &attr_name, PyObject *assign); - INLINE_LINMATH string __repr__() const; + INLINE_LINMATH PyObject *__getattr__(PyObject *self, const std::string &attr_name) const; + INLINE_LINMATH int __setattr__(PyObject *self, const std::string &attr_name, PyObject *assign); + INLINE_LINMATH std::string __repr__() const; }; #include "lvector3_ext_src.I" diff --git a/panda/src/linmath/lvector3_src.I b/panda/src/linmath/lvector3_src.I index 3e2404f272..3313e6e45f 100644 --- a/panda/src/linmath/lvector3_src.I +++ b/panda/src/linmath/lvector3_src.I @@ -183,10 +183,10 @@ angle_rad(const FLOATNAME(LVector3) &other) const { // poorly as dot(other) approaches 1.0. if (dot(other) < 0.0f) { FLOATTYPE a = ((*this)+other).length() / 2.0f; - return MathNumbers::cpi((FLOATTYPE)0.0f) - 2.0f * casin(min(a, (FLOATTYPE)1.0)); + return MathNumbers::cpi((FLOATTYPE)0.0f) - 2.0f * casin(std::min(a, (FLOATTYPE)1.0)); } else { FLOATTYPE a = ((*this)-other).length() / 2.0f; - return 2.0f * casin(min(a, (FLOATTYPE)1.0)); + return 2.0f * casin(std::min(a, (FLOATTYPE)1.0)); } } diff --git a/panda/src/linmath/lvector3_src.h b/panda/src/linmath/lvector3_src.h index e8f010cec7..1052e5cee8 100644 --- a/panda/src/linmath/lvector3_src.h +++ b/panda/src/linmath/lvector3_src.h @@ -20,14 +20,14 @@ */ class EXPCL_PANDA_LINMATH FLOATNAME(LVector3) : public FLOATNAME(LVecBase3) { PUBLISHED: - INLINE_LINMATH FLOATNAME(LVector3)() DEFAULT_CTOR; + INLINE_LINMATH FLOATNAME(LVector3)() = default; INLINE_LINMATH FLOATNAME(LVector3)(const FLOATNAME(LVecBase3) ©); INLINE_LINMATH FLOATNAME(LVector3)(FLOATTYPE fill_value); INLINE_LINMATH FLOATNAME(LVector3)(FLOATTYPE x, FLOATTYPE y, FLOATTYPE z); INLINE_LINMATH FLOATNAME(LVector3)(const FLOATNAME(LVecBase2) ©, FLOATTYPE z); - EXTENSION(INLINE_LINMATH PyObject *__getattr__(PyObject *self, const string &attr_name) const); - EXTENSION(INLINE_LINMATH int __setattr__(PyObject *self, const string &attr_name, PyObject *assign)); + EXTENSION(INLINE_LINMATH PyObject *__getattr__(PyObject *self, const std::string &attr_name) const); + EXTENSION(INLINE_LINMATH int __setattr__(PyObject *self, const std::string &attr_name, PyObject *assign)); INLINE_LINMATH static const FLOATNAME(LVector3) &zero(); INLINE_LINMATH static const FLOATNAME(LVector3) &unit_x(); @@ -85,7 +85,7 @@ PUBLISHED: INLINE_LINMATH static FLOATNAME(LVector3) rfu(FLOATTYPE right, FLOATTYPE fwd,FLOATTYPE up, CoordinateSystem cs = CS_default); - EXTENSION(INLINE_LINMATH string __repr__() const); + EXTENSION(INLINE_LINMATH std::string __repr__() const); public: static TypeHandle get_class_type() { diff --git a/panda/src/linmath/lvector4_ext_src.I b/panda/src/linmath/lvector4_ext_src.I index a188d6c4a2..6d4f7743b6 100644 --- a/panda/src/linmath/lvector4_ext_src.I +++ b/panda/src/linmath/lvector4_ext_src.I @@ -14,9 +14,9 @@ /** * */ -INLINE_LINMATH string Extension:: +INLINE_LINMATH std::string Extension:: __repr__() const { - ostringstream out; + std::ostringstream out; out << "LVector4" << FLOATTOKEN << "(" << MAYBE_ZERO(_this->_v(0)) << ", " << MAYBE_ZERO(_this->_v(1)) << ", " @@ -29,7 +29,7 @@ __repr__() const { * This is used to implement swizzle masks. */ INLINE_LINMATH PyObject *Extension:: -__getattr__(PyObject *self, const string &attr_name) const { +__getattr__(PyObject *self, const std::string &attr_name) const { #ifndef CPPPARSER extern struct Dtool_PyTypedObject FLOATNAME(Dtool_LVector2); extern struct Dtool_PyTypedObject FLOATNAME(Dtool_LVector3); @@ -37,7 +37,7 @@ __getattr__(PyObject *self, const string &attr_name) const { #endif // Validate the attribute name. - for (string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { + for (std::string::const_iterator it = attr_name.begin(); it < attr_name.end(); it++) { if (*it < 'w' || *it > 'z') { return Dtool_Raise_AttributeError(self, attr_name.c_str()); } @@ -81,7 +81,7 @@ __getattr__(PyObject *self, const string &attr_name) const { * This is used to implement write masks. */ INLINE_LINMATH int Extension:: -__setattr__(PyObject *self, const string &attr_name, PyObject *assign) { +__setattr__(PyObject *self, const std::string &attr_name, PyObject *assign) { // Upcall to LVecBase4. return invoke_extension(_this).__setattr__(self, attr_name, assign); } diff --git a/panda/src/linmath/lvector4_ext_src.h b/panda/src/linmath/lvector4_ext_src.h index 0cc68bca17..4aebf7c1e3 100644 --- a/panda/src/linmath/lvector4_ext_src.h +++ b/panda/src/linmath/lvector4_ext_src.h @@ -18,9 +18,9 @@ template<> class Extension : public ExtensionBase { public: - INLINE_LINMATH PyObject *__getattr__(PyObject *self, const string &attr_name) const; - INLINE_LINMATH int __setattr__(PyObject *self, const string &attr_name, PyObject *assign); - INLINE_LINMATH string __repr__() const; + INLINE_LINMATH PyObject *__getattr__(PyObject *self, const std::string &attr_name) const; + INLINE_LINMATH int __setattr__(PyObject *self, const std::string &attr_name, PyObject *assign); + INLINE_LINMATH std::string __repr__() const; }; #include "lvector4_ext_src.I" diff --git a/panda/src/linmath/lvector4_src.h b/panda/src/linmath/lvector4_src.h index 4c576e8406..cc04c5bbdf 100644 --- a/panda/src/linmath/lvector4_src.h +++ b/panda/src/linmath/lvector4_src.h @@ -16,14 +16,14 @@ */ class EXPCL_PANDA_LINMATH FLOATNAME(LVector4) : public FLOATNAME(LVecBase4) { PUBLISHED: - INLINE_LINMATH FLOATNAME(LVector4)() DEFAULT_CTOR; + INLINE_LINMATH FLOATNAME(LVector4)() = default; INLINE_LINMATH FLOATNAME(LVector4)(const FLOATNAME(LVecBase4) ©); INLINE_LINMATH FLOATNAME(LVector4)(FLOATTYPE fill_value); INLINE_LINMATH FLOATNAME(LVector4)(FLOATTYPE x, FLOATTYPE y, FLOATTYPE z, FLOATTYPE w); INLINE_LINMATH FLOATNAME(LVector4)(const FLOATNAME(LVecBase3) ©, FLOATTYPE w); - EXTENSION(INLINE_LINMATH PyObject *__getattr__(PyObject *self, const string &attr_name) const); - EXTENSION(INLINE_LINMATH int __setattr__(PyObject *self, const string &attr_name, PyObject *assign)); + EXTENSION(INLINE_LINMATH PyObject *__getattr__(PyObject *self, const std::string &attr_name) const); + EXTENSION(INLINE_LINMATH int __setattr__(PyObject *self, const std::string &attr_name, PyObject *assign)); INLINE_LINMATH static const FLOATNAME(LVector4) &zero(); INLINE_LINMATH static const FLOATNAME(LVector4) &unit_x(); @@ -53,7 +53,7 @@ PUBLISHED: INLINE_LINMATH FLOATNAME(LVector4) project(const FLOATNAME(LVecBase4) &onto) const; #endif - EXTENSION(INLINE_LINMATH string __repr__() const); + EXTENSION(INLINE_LINMATH std::string __repr__() const); public: static TypeHandle get_class_type() { diff --git a/panda/src/linmath/test_math.cxx b/panda/src/linmath/test_math.cxx index 41d1d15431..5a92f433d2 100644 --- a/panda/src/linmath/test_math.cxx +++ b/panda/src/linmath/test_math.cxx @@ -19,6 +19,10 @@ #include "pnotify.h" #include +using std::cerr; +using std::cout; +using std::endl; + void test() { LMatrix4f x = LMatrix4f::ident_mat(); LMatrix4f y = LMatrix4f::ident_mat(); diff --git a/panda/src/mathutil/boundingBox.cxx b/panda/src/mathutil/boundingBox.cxx index e2ce9c6c6a..1f0a1b7758 100644 --- a/panda/src/mathutil/boundingBox.cxx +++ b/panda/src/mathutil/boundingBox.cxx @@ -22,6 +22,9 @@ #include #include +using std::max; +using std::min; + const int BoundingBox::plane_def[6][3] = { { 0, 4, 5 }, { 4, 6, 7 }, @@ -111,7 +114,7 @@ xform(const LMatrix4 &mat) { * */ void BoundingBox:: -output(ostream &out) const { +output(std::ostream &out) const { if (is_empty()) { out << "bbox, empty"; } else if (is_infinite()) { diff --git a/panda/src/mathutil/boundingBox.h b/panda/src/mathutil/boundingBox.h index 2ba4b273e1..8826008ff5 100644 --- a/panda/src/mathutil/boundingBox.h +++ b/panda/src/mathutil/boundingBox.h @@ -42,7 +42,7 @@ public: virtual LPoint3 get_approx_center() const; virtual void xform(const LMatrix4 &mat); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; PUBLISHED: diff --git a/panda/src/mathutil/boundingHexahedron.cxx b/panda/src/mathutil/boundingHexahedron.cxx index b765f043b0..1e500cb64c 100644 --- a/panda/src/mathutil/boundingHexahedron.cxx +++ b/panda/src/mathutil/boundingHexahedron.cxx @@ -19,6 +19,9 @@ #include #include +using std::max; +using std::min; + TypeHandle BoundingHexahedron::_type_handle; /** @@ -151,7 +154,7 @@ xform(const LMatrix4 &mat) { * */ void BoundingHexahedron:: -output(ostream &out) const { +output(std::ostream &out) const { if (is_empty()) { out << "bhexahedron, empty"; } else if (is_infinite()) { @@ -165,7 +168,7 @@ output(ostream &out) const { * */ void BoundingHexahedron:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { if (is_empty()) { indent(out, indent_level) << "bhexahedron, empty\n"; } else if (is_infinite()) { diff --git a/panda/src/mathutil/boundingHexahedron.h b/panda/src/mathutil/boundingHexahedron.h index 40851a219f..ac87135509 100644 --- a/panda/src/mathutil/boundingHexahedron.h +++ b/panda/src/mathutil/boundingHexahedron.h @@ -51,8 +51,8 @@ public: virtual LPoint3 get_approx_center() const; virtual void xform(const LMatrix4 &mat); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; PUBLISHED: INLINE_MATHUTIL int get_num_points() const; diff --git a/panda/src/mathutil/boundingLine.cxx b/panda/src/mathutil/boundingLine.cxx index 38dd4704a5..93de2f6d5e 100644 --- a/panda/src/mathutil/boundingLine.cxx +++ b/panda/src/mathutil/boundingLine.cxx @@ -60,7 +60,7 @@ xform(const LMatrix4 &mat) { * */ void BoundingLine:: -output(ostream &out) const { +output(std::ostream &out) const { if (is_empty()) { out << "bline, empty"; } else if (is_infinite()) { diff --git a/panda/src/mathutil/boundingLine.h b/panda/src/mathutil/boundingLine.h index 15e5f43417..e1dff97177 100644 --- a/panda/src/mathutil/boundingLine.h +++ b/panda/src/mathutil/boundingLine.h @@ -40,7 +40,7 @@ public: virtual LPoint3 get_approx_center() const; virtual void xform(const LMatrix4 &mat); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; PUBLISHED: INLINE_MATHUTIL const LPoint3 &get_point_a() const; diff --git a/panda/src/mathutil/boundingPlane.cxx b/panda/src/mathutil/boundingPlane.cxx index b0a36ab3e3..9690bb8dae 100644 --- a/panda/src/mathutil/boundingPlane.cxx +++ b/panda/src/mathutil/boundingPlane.cxx @@ -53,7 +53,7 @@ xform(const LMatrix4 &mat) { * */ void BoundingPlane:: -output(ostream &out) const { +output(std::ostream &out) const { if (is_empty()) { out << "bplane, empty"; } else if (is_infinite()) { diff --git a/panda/src/mathutil/boundingPlane.h b/panda/src/mathutil/boundingPlane.h index aff1ebe36b..82e02870a0 100644 --- a/panda/src/mathutil/boundingPlane.h +++ b/panda/src/mathutil/boundingPlane.h @@ -37,7 +37,7 @@ public: virtual LPoint3 get_approx_center() const; virtual void xform(const LMatrix4 &mat); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; PUBLISHED: INLINE_MATHUTIL const LPlane &get_plane() const; diff --git a/panda/src/mathutil/boundingSphere.cxx b/panda/src/mathutil/boundingSphere.cxx index 5ea6661aa7..32e48adad9 100644 --- a/panda/src/mathutil/boundingSphere.cxx +++ b/panda/src/mathutil/boundingSphere.cxx @@ -22,6 +22,9 @@ #include +using std::max; +using std::min; + TypeHandle BoundingSphere::_type_handle; /** @@ -116,7 +119,7 @@ xform(const LMatrix4 &mat) { * */ void BoundingSphere:: -output(ostream &out) const { +output(std::ostream &out) const { if (is_empty()) { out << "bsphere, empty"; } else if (is_infinite()) { @@ -363,17 +366,17 @@ around_finite(const BoundingVolume **first, const BoundingVolume **p = first; nassertr(!(*p)->is_empty() && !(*p)->is_infinite(), false); const FiniteBoundingVolume *vol = (*p)->as_finite_bounding_volume(); - nassertr(vol != (FiniteBoundingVolume *)NULL, false); + nassertr(vol != nullptr, false); LPoint3 min_box = vol->get_min(); LPoint3 max_box = vol->get_max(); - bool any_spheres = (vol->as_bounding_sphere() != NULL); + bool any_spheres = (vol->as_bounding_sphere() != nullptr); for (++p; p != last; ++p) { nassertr(!(*p)->is_infinite(), false); if (!(*p)->is_empty()) { vol = (*p)->as_finite_bounding_volume(); - if (vol == (FiniteBoundingVolume *)NULL) { + if (vol == nullptr) { set_infinite(); return true; } @@ -386,7 +389,7 @@ around_finite(const BoundingVolume **first, max(max_box[1], max1[1]), max(max_box[2], max1[2])); - if (vol->as_bounding_sphere() != NULL) { + if (vol->as_bounding_sphere() != nullptr) { any_spheres = true; } } @@ -407,7 +410,7 @@ around_finite(const BoundingVolume **first, for (p = first; p != last; ++p) { if (!(*p)->is_empty()) { const BoundingSphere *sphere = (*p)->as_bounding_sphere(); - if (sphere != (BoundingSphere *)NULL) { + if (sphere != nullptr) { // This is a sphere; consider its corner. PN_stdfloat dist = length(sphere->_center - _center); _radius = max(_radius, dist + sphere->_radius); @@ -415,7 +418,7 @@ around_finite(const BoundingVolume **first, } else { // This is a nonsphere. We fit around it. const FiniteBoundingVolume *vol = (*p)->as_finite_bounding_volume(); - nassertr(vol != (FiniteBoundingVolume *)NULL, false); + nassertr(vol != nullptr, false); BoundingBox box(vol->get_min(), vol->get_max()); box.local_object(); diff --git a/panda/src/mathutil/boundingSphere.h b/panda/src/mathutil/boundingSphere.h index 09027e3b8c..8c105daa01 100644 --- a/panda/src/mathutil/boundingSphere.h +++ b/panda/src/mathutil/boundingSphere.h @@ -38,7 +38,7 @@ public: virtual LPoint3 get_approx_center() const; virtual void xform(const LMatrix4 &mat); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; PUBLISHED: INLINE_MATHUTIL LPoint3 get_center() const; diff --git a/panda/src/mathutil/boundingVolume.I b/panda/src/mathutil/boundingVolume.I index 2778e886ba..1b5daf418b 100644 --- a/panda/src/mathutil/boundingVolume.I +++ b/panda/src/mathutil/boundingVolume.I @@ -94,7 +94,7 @@ contains(const BoundingVolume *vol) const { return vol->contains_other(this); } -INLINE_MATHUTIL ostream &operator << (ostream &out, const BoundingVolume &bound) { +INLINE_MATHUTIL std::ostream &operator << (std::ostream &out, const BoundingVolume &bound) { bound.output(out); return out; } diff --git a/panda/src/mathutil/boundingVolume.cxx b/panda/src/mathutil/boundingVolume.cxx index 3a2bee0577..a806dc819b 100644 --- a/panda/src/mathutil/boundingVolume.cxx +++ b/panda/src/mathutil/boundingVolume.cxx @@ -24,6 +24,10 @@ #include "indent.h" +using std::istream; +using std::ostream; +using std::string; + TypeHandle BoundingVolume::_type_handle; @@ -84,7 +88,7 @@ write(ostream &out, int indent_level) const { */ GeometricBoundingVolume *BoundingVolume:: as_geometric_bounding_volume() { - return NULL; + return nullptr; } /** @@ -93,7 +97,7 @@ as_geometric_bounding_volume() { */ const GeometricBoundingVolume *BoundingVolume:: as_geometric_bounding_volume() const { - return NULL; + return nullptr; } /** @@ -102,7 +106,7 @@ as_geometric_bounding_volume() const { */ const FiniteBoundingVolume *BoundingVolume:: as_finite_bounding_volume() const { - return NULL; + return nullptr; } /** @@ -111,7 +115,7 @@ as_finite_bounding_volume() const { */ const BoundingSphere *BoundingVolume:: as_bounding_sphere() const { - return NULL; + return nullptr; } /** @@ -120,7 +124,7 @@ as_bounding_sphere() const { */ const BoundingBox *BoundingVolume:: as_bounding_box() const { - return NULL; + return nullptr; } /** @@ -129,7 +133,7 @@ as_bounding_box() const { */ const BoundingHexahedron *BoundingVolume:: as_bounding_hexahedron() const { - return NULL; + return nullptr; } /** @@ -138,7 +142,7 @@ as_bounding_hexahedron() const { */ const BoundingLine *BoundingVolume:: as_bounding_line() const { - return NULL; + return nullptr; } /** @@ -147,7 +151,7 @@ as_bounding_line() const { */ const BoundingPlane *BoundingVolume:: as_bounding_plane() const { - return NULL; + return nullptr; } /** diff --git a/panda/src/mathutil/boundingVolume.h b/panda/src/mathutil/boundingVolume.h index df904145ad..67bde45839 100644 --- a/panda/src/mathutil/boundingVolume.h +++ b/panda/src/mathutil/boundingVolume.h @@ -92,8 +92,8 @@ PUBLISHED: INLINE_MATHUTIL int contains(const BoundingVolume *vol) const; - virtual void output(ostream &out) const=0; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const=0; + virtual void write(std::ostream &out, int indent_level = 0) const; // This enum is used to control the automatic generation of bounding // volumes. @@ -115,7 +115,7 @@ public: virtual const BoundingLine *as_bounding_line() const; virtual const BoundingPlane *as_bounding_plane() const; - static BoundsType string_bounds_type(const string &str); + static BoundsType string_bounds_type(const std::string &str); protected: enum Flags { @@ -203,11 +203,11 @@ private: friend class IntersectionBoundingVolume; }; -INLINE_MATHUTIL ostream &operator << (ostream &out, const BoundingVolume &bound); +INLINE_MATHUTIL std::ostream &operator << (std::ostream &out, const BoundingVolume &bound); #include "boundingVolume.I" -EXPCL_PANDA_MATHUTIL ostream &operator << (ostream &out, BoundingVolume::BoundsType type); -EXPCL_PANDA_MATHUTIL istream &operator >> (istream &in, BoundingVolume::BoundsType &type); +EXPCL_PANDA_MATHUTIL std::ostream &operator << (std::ostream &out, BoundingVolume::BoundsType type); +EXPCL_PANDA_MATHUTIL std::istream &operator >> (std::istream &in, BoundingVolume::BoundsType &type); #endif diff --git a/panda/src/mathutil/fftCompressor.cxx b/panda/src/mathutil/fftCompressor.cxx index 0a5b7425e1..b8a9764d8f 100644 --- a/panda/src/mathutil/fftCompressor.cxx +++ b/panda/src/mathutil/fftCompressor.cxx @@ -386,9 +386,9 @@ write_hprs(Datagram &datagram, const LVecBase3 *array, int length) { } if (length == 0) { - write_reals(datagram, NULL, length); - write_reals(datagram, NULL, length); - write_reals(datagram, NULL, length); + write_reals(datagram, nullptr, length); + write_reals(datagram, nullptr, length); + write_reals(datagram, nullptr, length); } else { write_reals(datagram, &h[0], length); write_reals(datagram, &p[0], length); @@ -419,15 +419,15 @@ write_hprs(Datagram &datagram, const LVecBase3 *array, int length) { } if (length == 0) { - write_reals(datagram, NULL, length); - write_reals(datagram, NULL, length); - write_reals(datagram, NULL, length); - write_reals(datagram, NULL, length); - write_reals(datagram, NULL, length); - write_reals(datagram, NULL, length); - write_reals(datagram, NULL, length); - write_reals(datagram, NULL, length); - write_reals(datagram, NULL, length); + write_reals(datagram, nullptr, length); + write_reals(datagram, nullptr, length); + write_reals(datagram, nullptr, length); + write_reals(datagram, nullptr, length); + write_reals(datagram, nullptr, length); + write_reals(datagram, nullptr, length); + write_reals(datagram, nullptr, length); + write_reals(datagram, nullptr, length); + write_reals(datagram, nullptr, length); } else { write_reals(datagram, &m00[0], length); write_reals(datagram, &m01[0], length); @@ -513,16 +513,16 @@ write_hprs(Datagram &datagram, const LVecBase3 *array, int length) { #ifndef NDEBUG if (_quality >= 102) { if (length == 0) { - write_reals(datagram, NULL, length); + write_reals(datagram, nullptr, length); } else { write_reals(datagram, &qr[0], length); } } #endif if (length == 0) { - write_reals(datagram, NULL, length); - write_reals(datagram, NULL, length); - write_reals(datagram, NULL, length); + write_reals(datagram, nullptr, length); + write_reals(datagram, nullptr, length); + write_reals(datagram, nullptr, length); } else { write_reals(datagram, &qi[0], length); write_reals(datagram, &qj[0], length); @@ -1060,7 +1060,7 @@ get_real_compress_plan(int length) { } fftw_plan plan; - plan = fftw_plan_dft_r2c_1d(length, NULL, NULL, FFTW_ESTIMATE); + plan = fftw_plan_dft_r2c_1d(length, nullptr, nullptr, FFTW_ESTIMATE); _real_compress_plans.insert(RealPlans::value_type(length, plan)); return plan; @@ -1079,7 +1079,7 @@ get_real_decompress_plan(int length) { } fftw_plan plan; - plan = fftw_plan_dft_c2r_1d(length, NULL, NULL, FFTW_ESTIMATE); + plan = fftw_plan_dft_c2r_1d(length, nullptr, nullptr, FFTW_ESTIMATE); _real_decompress_plans.insert(RealPlans::value_type(length, plan)); return plan; diff --git a/panda/src/mathutil/geometricBoundingVolume.h b/panda/src/mathutil/geometricBoundingVolume.h index a27c19a724..a8f75a226f 100644 --- a/panda/src/mathutil/geometricBoundingVolume.h +++ b/panda/src/mathutil/geometricBoundingVolume.h @@ -51,8 +51,8 @@ PUBLISHED: virtual void xform(const LMatrix4 &mat)=0; public: - virtual GeometricBoundingVolume *as_geometric_bounding_volume() FINAL; - virtual const GeometricBoundingVolume *as_geometric_bounding_volume() const FINAL; + virtual GeometricBoundingVolume *as_geometric_bounding_volume() final; + virtual const GeometricBoundingVolume *as_geometric_bounding_volume() const final; protected: // Some virtual functions to implement fundamental bounding operations on diff --git a/panda/src/mathutil/intersectionBoundingVolume.I b/panda/src/mathutil/intersectionBoundingVolume.I index 514c692333..4242446c1d 100644 --- a/panda/src/mathutil/intersectionBoundingVolume.I +++ b/panda/src/mathutil/intersectionBoundingVolume.I @@ -32,6 +32,6 @@ get_num_components() const { */ INLINE_MATHUTIL const GeometricBoundingVolume *IntersectionBoundingVolume:: get_component(int n) const { - nassertr(n >= 0 && n < (int)_components.size(), NULL); + nassertr(n >= 0 && n < (int)_components.size(), nullptr); return _components[n]; } diff --git a/panda/src/mathutil/intersectionBoundingVolume.cxx b/panda/src/mathutil/intersectionBoundingVolume.cxx index a8af2d2b97..334cb428fe 100644 --- a/panda/src/mathutil/intersectionBoundingVolume.cxx +++ b/panda/src/mathutil/intersectionBoundingVolume.cxx @@ -74,7 +74,7 @@ xform(const LMatrix4 &mat) { * */ void IntersectionBoundingVolume:: -output(ostream &out) const { +output(std::ostream &out) const { if (is_empty()) { out << "intersection, empty"; } else if (is_infinite()) { @@ -94,7 +94,7 @@ output(ostream &out) const { * */ void IntersectionBoundingVolume:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { if (is_empty()) { indent(out, indent_level) << "intersection, empty\n"; } else if (is_infinite()) { diff --git a/panda/src/mathutil/intersectionBoundingVolume.h b/panda/src/mathutil/intersectionBoundingVolume.h index 74e750acb9..1869c92131 100644 --- a/panda/src/mathutil/intersectionBoundingVolume.h +++ b/panda/src/mathutil/intersectionBoundingVolume.h @@ -40,8 +40,8 @@ public: virtual LPoint3 get_approx_center() const; virtual void xform(const LMatrix4 &mat); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; PUBLISHED: INLINE_MATHUTIL int get_num_components() const; diff --git a/panda/src/mathutil/omniBoundingVolume.cxx b/panda/src/mathutil/omniBoundingVolume.cxx index 65e556b767..687374c1be 100644 --- a/panda/src/mathutil/omniBoundingVolume.cxx +++ b/panda/src/mathutil/omniBoundingVolume.cxx @@ -46,7 +46,7 @@ xform(const LMatrix4 &) { * */ void OmniBoundingVolume:: -output(ostream &out) const { +output(std::ostream &out) const { out << "omni"; } diff --git a/panda/src/mathutil/omniBoundingVolume.h b/panda/src/mathutil/omniBoundingVolume.h index b124de5767..631c514bd5 100644 --- a/panda/src/mathutil/omniBoundingVolume.h +++ b/panda/src/mathutil/omniBoundingVolume.h @@ -31,7 +31,7 @@ public: virtual LPoint3 get_approx_center() const; virtual void xform(const LMatrix4 &mat); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual bool extend_other(BoundingVolume *other) const; diff --git a/panda/src/mathutil/parabola_src.cxx b/panda/src/mathutil/parabola_src.cxx index a695a89c31..437ab012e5 100644 --- a/panda/src/mathutil/parabola_src.cxx +++ b/panda/src/mathutil/parabola_src.cxx @@ -27,7 +27,7 @@ xform(const FLOATNAME(LMatrix4) &mat) { * */ void FLOATNAME(LParabola):: -output(ostream &out) const { +output(std::ostream &out) const { out << "LParabola(" << _a << ", " << _b << ", " << _c << ")"; } @@ -35,7 +35,7 @@ output(ostream &out) const { * */ void FLOATNAME(LParabola):: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << *this << "\n"; } diff --git a/panda/src/mathutil/parabola_src.h b/panda/src/mathutil/parabola_src.h index 742f0c5450..8eaec14744 100644 --- a/panda/src/mathutil/parabola_src.h +++ b/panda/src/mathutil/parabola_src.h @@ -35,8 +35,8 @@ PUBLISHED: INLINE_MATHUTIL FLOATNAME(LPoint3) calc_point(FLOATTYPE t) const; - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; void write_datagram_fixed(Datagram &destination) const; void read_datagram_fixed(DatagramIterator &source); @@ -47,8 +47,8 @@ private: FLOATNAME(LVecBase3) _a, _b, _c; }; -inline ostream & -operator << (ostream &out, const FLOATNAME(LParabola) &p) { +inline std::ostream & +operator << (std::ostream &out, const FLOATNAME(LParabola) &p) { p.output(out); return out; } diff --git a/panda/src/mathutil/plane_src.I b/panda/src/mathutil/plane_src.I index 373d256e31..f357b34e60 100644 --- a/panda/src/mathutil/plane_src.I +++ b/panda/src/mathutil/plane_src.I @@ -202,8 +202,8 @@ intersects_line(FLOATTYPE &t, return true; } -INLINE_MATHUTIL ostream & -operator << (ostream &out, const FLOATNAME(LPlane) &p) { +INLINE_MATHUTIL std::ostream & +operator << (std::ostream &out, const FLOATNAME(LPlane) &p) { p.output(out); return out; } diff --git a/panda/src/mathutil/plane_src.cxx b/panda/src/mathutil/plane_src.cxx index 3a3baff375..7ba18701c6 100644 --- a/panda/src/mathutil/plane_src.cxx +++ b/panda/src/mathutil/plane_src.cxx @@ -145,7 +145,7 @@ intersects_parabola(FLOATTYPE &t1, FLOATTYPE &t2, * */ void FLOATNAME(LPlane):: -output(ostream &out) const { +output(std::ostream &out) const { out << "LPlane("; FLOATNAME(LVecBase4)::output(out); out << ")"; @@ -155,6 +155,6 @@ output(ostream &out) const { * */ void FLOATNAME(LPlane):: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << *this << "\n"; } diff --git a/panda/src/mathutil/plane_src.h b/panda/src/mathutil/plane_src.h index 2e0d7aa0f6..c3301aa641 100644 --- a/panda/src/mathutil/plane_src.h +++ b/panda/src/mathutil/plane_src.h @@ -56,11 +56,11 @@ PUBLISHED: bool intersects_parabola(FLOATTYPE &t1, FLOATTYPE &t2, const FLOATNAME(LParabola) ¶bola) const; - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; }; -INLINE_MATHUTIL ostream & -operator << (ostream &out, const FLOATNAME(LPlane) &p); +INLINE_MATHUTIL std::ostream & +operator << (std::ostream &out, const FLOATNAME(LPlane) &p); #include "plane_src.I" diff --git a/panda/src/mathutil/randomizer.I b/panda/src/mathutil/randomizer.I index 3cb30939b9..410d1c266e 100644 --- a/panda/src/mathutil/randomizer.I +++ b/panda/src/mathutil/randomizer.I @@ -68,7 +68,7 @@ random_real_unit() { INLINE unsigned long Randomizer:: get_next_seed() { if (!_got_first_seed) { - _next_seed = Mersenne((unsigned long)time(NULL)); + _next_seed = Mersenne((unsigned long)time(nullptr)); _got_first_seed = true; } return _next_seed.get_uint31(); diff --git a/panda/src/mathutil/test_tri.cxx b/panda/src/mathutil/test_tri.cxx index 57852b3773..e09b86fc21 100644 --- a/panda/src/mathutil/test_tri.cxx +++ b/panda/src/mathutil/test_tri.cxx @@ -42,7 +42,7 @@ int main(int argc, char *argv[]) { t.triangulate(); for (int i = 0; i < t.get_num_triangles(); ++i) { - cerr << "tri: " << t.get_triangle_v0(i) << " " + std::cerr << "tri: " << t.get_triangle_v0(i) << " " << t.get_triangle_v1(i) << " " << t.get_triangle_v2(i) << "\n"; } diff --git a/panda/src/mathutil/triangulator.cxx b/panda/src/mathutil/triangulator.cxx index a0c1ad9ad5..fabfe31147 100644 --- a/panda/src/mathutil/triangulator.cxx +++ b/panda/src/mathutil/triangulator.cxx @@ -867,7 +867,7 @@ add_segment(int segnum) { int tfirstr = 0, tlastr = 0, tfirstl = 0, tlastl = 0; int i1, i2, t, tn; // t1, t2, point_t tpt; - int tritop = 0, tribot = 0, is_swapped = 0; + int tribot = 0, is_swapped = 0; int tmptriseg; s = seg[segnum]; @@ -939,7 +939,6 @@ add_segment(int segnum) { else /* v0 already present */ { /* Get the topmost intersecting trapezoid */ tfirst = locate_endpoint(&s.v0, &s.v1, s.root0); - tritop = 1; } @@ -1294,16 +1293,13 @@ add_segment(int segnum) { // int tmpseg = tr[tr[t].d0].rseg; double y0, yt; point_t tmppt; - int tnext, i_d0, i_d1; + int tnext, i_d0; - i_d1 = false; i_d0 = false; if (FP_EQUAL(tr[t].lo.y, s.v0.y)) { if (tr[t].lo.x > s.v0.x) i_d0 = true; - else - i_d1 = true; } else { @@ -1314,8 +1310,6 @@ add_segment(int segnum) { if (_less_than(&tmppt, &tr[t].lo)) i_d0 = true; - else - i_d1 = true; } /* check continuity from the top so that the lower-neighbour */ @@ -1792,7 +1786,6 @@ traverse_polygon(int mcur, int trnum, int from, int dir) { int mnew; int v0, v1; //, v0next, v1next; int retval = 0; //, tmp; - int do_switch = false; // printf("visited size = %d, visited[trnum] = %d\n", visited.size(), // visited[trnum]); @@ -1817,7 +1810,6 @@ traverse_polygon(int mcur, int trnum, int from, int dir) { v1 = t->lseg; if (from == t->d1) { - do_switch = true; mnew = make_new_monotone_poly(mcur, v1, v0); traverse_polygon(mcur, t->d1, trnum, TR_FROM_UP); traverse_polygon(mnew, t->d0, trnum, TR_FROM_UP); @@ -1847,7 +1839,6 @@ traverse_polygon(int mcur, int trnum, int from, int dir) { v1 = tr[t->u0].rseg; if (from == t->u1) { - do_switch = true; mnew = make_new_monotone_poly(mcur, v1, v0); traverse_polygon(mcur, t->u1, trnum, TR_FROM_DN); traverse_polygon(mnew, t->u0, trnum, TR_FROM_DN); @@ -1879,7 +1870,6 @@ traverse_polygon(int mcur, int trnum, int from, int dir) { if (((dir == TR_FROM_DN) && (t->d1 == from)) || ((dir == TR_FROM_UP) && (t->u1 == from))) { - do_switch = true; mnew = make_new_monotone_poly(mcur, v1, v0); traverse_polygon(mcur, t->u1, trnum, TR_FROM_DN); traverse_polygon(mcur, t->d1, trnum, TR_FROM_UP); @@ -1905,7 +1895,6 @@ traverse_polygon(int mcur, int trnum, int from, int dir) { retval = SP_2UP_LEFT; if ((dir == TR_FROM_UP) && (t->u0 == from)) { - do_switch = true; mnew = make_new_monotone_poly(mcur, v1, v0); traverse_polygon(mcur, t->u0, trnum, TR_FROM_DN); traverse_polygon(mnew, t->d0, trnum, TR_FROM_UP); @@ -1928,7 +1917,6 @@ traverse_polygon(int mcur, int trnum, int from, int dir) { retval = SP_2UP_RIGHT; if ((dir == TR_FROM_UP) && (t->u1 == from)) { - do_switch = true; mnew = make_new_monotone_poly(mcur, v1, v0); traverse_polygon(mcur, t->u1, trnum, TR_FROM_DN); traverse_polygon(mnew, t->d1, trnum, TR_FROM_UP); @@ -1957,7 +1945,6 @@ traverse_polygon(int mcur, int trnum, int from, int dir) { retval = SP_2DN_LEFT; if (!((dir == TR_FROM_DN) && (t->d0 == from))) { - do_switch = true; mnew = make_new_monotone_poly(mcur, v1, v0); traverse_polygon(mcur, t->u1, trnum, TR_FROM_DN); traverse_polygon(mcur, t->d1, trnum, TR_FROM_UP); @@ -1981,7 +1968,6 @@ traverse_polygon(int mcur, int trnum, int from, int dir) { retval = SP_2DN_RIGHT; if ((dir == TR_FROM_DN) && (t->d1 == from)) { - do_switch = true; mnew = make_new_monotone_poly(mcur, v1, v0); traverse_polygon(mcur, t->d1, trnum, TR_FROM_UP); traverse_polygon(mnew, t->u1, trnum, TR_FROM_DN); @@ -2008,7 +1994,6 @@ traverse_polygon(int mcur, int trnum, int from, int dir) { retval = SP_SIMPLE_LRDN; if (dir == TR_FROM_UP) { - do_switch = true; mnew = make_new_monotone_poly(mcur, v1, v0); traverse_polygon(mcur, t->u0, trnum, TR_FROM_DN); traverse_polygon(mcur, t->u1, trnum, TR_FROM_DN); @@ -2033,7 +2018,6 @@ traverse_polygon(int mcur, int trnum, int from, int dir) { retval = SP_SIMPLE_LRUP; if (dir == TR_FROM_UP) { - do_switch = true; mnew = make_new_monotone_poly(mcur, v1, v0); traverse_polygon(mcur, t->u0, trnum, TR_FROM_DN); traverse_polygon(mcur, t->u1, trnum, TR_FROM_DN); diff --git a/panda/src/mathutil/unionBoundingVolume.I b/panda/src/mathutil/unionBoundingVolume.I index 6212b1f2b8..9c7e782b45 100644 --- a/panda/src/mathutil/unionBoundingVolume.I +++ b/panda/src/mathutil/unionBoundingVolume.I @@ -31,6 +31,6 @@ get_num_components() const { */ INLINE_MATHUTIL const GeometricBoundingVolume *UnionBoundingVolume:: get_component(int n) const { - nassertr(n >= 0 && n < (int)_components.size(), NULL); + nassertr(n >= 0 && n < (int)_components.size(), nullptr); return _components[n]; } diff --git a/panda/src/mathutil/unionBoundingVolume.cxx b/panda/src/mathutil/unionBoundingVolume.cxx index dfc96f8e92..2c4d7c41a9 100644 --- a/panda/src/mathutil/unionBoundingVolume.cxx +++ b/panda/src/mathutil/unionBoundingVolume.cxx @@ -74,7 +74,7 @@ xform(const LMatrix4 &mat) { * */ void UnionBoundingVolume:: -output(ostream &out) const { +output(std::ostream &out) const { if (is_empty()) { out << "union, empty"; } else if (is_infinite()) { @@ -94,7 +94,7 @@ output(ostream &out) const { * */ void UnionBoundingVolume:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { if (is_empty()) { indent(out, indent_level) << "union, empty\n"; } else if (is_infinite()) { @@ -236,7 +236,7 @@ around_geometric(const BoundingVolume **first, nassertr(!(*p)->is_infinite(), false); if (!(*p)->is_empty()) { const GeometricBoundingVolume *volume = (*p)->as_geometric_bounding_volume(); - if (volume != (GeometricBoundingVolume *)NULL) { + if (volume != nullptr) { add_component(volume); } else { set_infinite(); diff --git a/panda/src/mathutil/unionBoundingVolume.h b/panda/src/mathutil/unionBoundingVolume.h index 4af835eae7..a18f6b3926 100644 --- a/panda/src/mathutil/unionBoundingVolume.h +++ b/panda/src/mathutil/unionBoundingVolume.h @@ -39,8 +39,8 @@ public: virtual LPoint3 get_approx_center() const; virtual void xform(const LMatrix4 &mat); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; PUBLISHED: INLINE_MATHUTIL int get_num_components() const; diff --git a/panda/src/movies/dr_flac.h b/panda/src/movies/dr_flac.h index fdac6a2f79..3d0b1cdd91 100644 --- a/panda/src/movies/dr_flac.h +++ b/panda/src/movies/dr_flac.h @@ -328,7 +328,9 @@ static drflac* drflac_open_memory(const void* data, size_t dataSize); #endif #ifdef __linux__ +#ifndef _BSD_SOURCE #define _BSD_SOURCE +#endif #include #endif diff --git a/panda/src/movies/flacAudio.cxx b/panda/src/movies/flacAudio.cxx index 8bfbd56ad2..07f41ca350 100644 --- a/panda/src/movies/flacAudio.cxx +++ b/panda/src/movies/flacAudio.cxx @@ -41,14 +41,14 @@ FlacAudio:: PT(MovieAudioCursor) FlacAudio:: open() { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); - istream *stream = vfs->open_read_file(_filename, true); + std::istream *stream = vfs->open_read_file(_filename, true); - if (stream == NULL) { - return NULL; + if (stream == nullptr) { + return nullptr; } else { PT(FlacAudioCursor) cursor = new FlacAudioCursor(this, stream); - if (cursor == NULL || !cursor->_is_valid) { - return NULL; + if (cursor == nullptr || !cursor->_is_valid) { + return nullptr; } else { return DCAST(MovieAudioCursor, cursor); } diff --git a/panda/src/movies/flacAudioCursor.cxx b/panda/src/movies/flacAudioCursor.cxx index a4c33822cd..19eb71cbc9 100644 --- a/panda/src/movies/flacAudioCursor.cxx +++ b/panda/src/movies/flacAudioCursor.cxx @@ -25,8 +25,8 @@ extern "C" { * Callback passed to dr_flac to implement file I/O via the VirtualFileSystem. */ static size_t cb_read_proc(void *user, void *buffer, size_t size) { - istream *stream = (istream *)user; - nassertr(stream != NULL, false); + std::istream *stream = (std::istream *)user; + nassertr(stream != nullptr, false); stream->read((char *)buffer, size); @@ -42,10 +42,10 @@ static size_t cb_read_proc(void *user, void *buffer, size_t size) { * Callback passed to dr_flac to implement file I/O via the VirtualFileSystem. */ static bool cb_seek_proc(void *user, int offset) { - istream *stream = (istream *)user; - nassertr(stream != NULL, false); + std::istream *stream = (std::istream *)user; + nassertr(stream != nullptr, false); - stream->seekg(offset, ios::cur); + stream->seekg(offset, std::ios::cur); return !stream->fail(); } @@ -56,17 +56,17 @@ TypeHandle FlacAudioCursor::_type_handle; * pointer positioned at the start of the data. */ FlacAudioCursor:: -FlacAudioCursor(FlacAudio *src, istream *stream) : +FlacAudioCursor(FlacAudio *src, std::istream *stream) : MovieAudioCursor(src), _is_valid(false), - _drflac(NULL) + _drflac(nullptr) { - nassertv(stream != NULL); + nassertv(stream != nullptr); nassertv(stream->good()); _drflac = drflac_open(&cb_read_proc, &cb_seek_proc, (void *)stream); - if (_drflac == NULL) { + if (_drflac == nullptr) { movies_cat.error() << "Failed to open FLAC file.\n"; _is_valid = false; @@ -88,7 +88,7 @@ FlacAudioCursor(FlacAudio *src, istream *stream) : */ FlacAudioCursor:: ~FlacAudioCursor() { - if (_drflac != NULL) { + if (_drflac != nullptr) { drflac_close(_drflac); } } @@ -99,7 +99,7 @@ FlacAudioCursor:: */ void FlacAudioCursor:: seek(double t) { - t = max(t, 0.0); + t = std::max(t, 0.0); uint64_t sample = t * _drflac->sampleRate; diff --git a/panda/src/movies/flacAudioCursor.h b/panda/src/movies/flacAudioCursor.h index edae05a674..55d59d5488 100644 --- a/panda/src/movies/flacAudioCursor.h +++ b/panda/src/movies/flacAudioCursor.h @@ -30,7 +30,7 @@ class FlacAudio; */ class EXPCL_PANDA_MOVIES FlacAudioCursor : public MovieAudioCursor { PUBLISHED: - explicit FlacAudioCursor(FlacAudio *src, istream *stream); + explicit FlacAudioCursor(FlacAudio *src, std::istream *stream); virtual ~FlacAudioCursor(); virtual void seek(double offset); diff --git a/panda/src/movies/microphoneAudio.cxx b/panda/src/movies/microphoneAudio.cxx index bc21c758d9..65ff4010bf 100644 --- a/panda/src/movies/microphoneAudio.cxx +++ b/panda/src/movies/microphoneAudio.cxx @@ -69,6 +69,6 @@ get_num_options() { PT(MicrophoneAudio) MicrophoneAudio:: get_option(int n) { find_all_microphones(); - nassertr((n >= 0) && (n < (int)_all_microphones.size()), NULL); + nassertr((n >= 0) && (n < (int)_all_microphones.size()), nullptr); return _all_microphones[n]; } diff --git a/panda/src/movies/microphoneAudioDS.cxx b/panda/src/movies/microphoneAudioDS.cxx index 95412fb961..1ce78b0209 100644 --- a/panda/src/movies/microphoneAudioDS.cxx +++ b/panda/src/movies/microphoneAudioDS.cxx @@ -146,10 +146,10 @@ find_all_microphones_ds() { format.nBlockAlign = 2 * chan; format.wBitsPerSample = 16; format.cbSize = 0; - stat = waveInOpen(NULL, i, &format, NULL, NULL, WAVE_FORMAT_QUERY); + stat = waveInOpen(nullptr, i, &format, 0, 0, WAVE_FORMAT_QUERY); if (stat == MMSYSERR_NOERROR) { PT(MicrophoneAudioDS) p = new MicrophoneAudioDS(); - ostringstream name; + std::ostringstream name; name << "WaveIn: " << caps.szPname << " Chan:" << chan << " HZ:" << freq; p->set_name(name.str()); p->_device_id = i; @@ -235,7 +235,7 @@ open() { if (failed) { delete_buffers(buffers); nassert_raise("Could not allocate audio input buffers."); - return NULL; + return nullptr; } WAVEFORMATEX format; @@ -248,12 +248,12 @@ open() { format.cbSize = 0; HWAVEIN hwav; - MMRESULT stat = waveInOpen(&hwav, _device_id, &format, NULL, NULL, CALLBACK_NULL); + MMRESULT stat = waveInOpen(&hwav, _device_id, &format, 0, 0, CALLBACK_NULL); if (stat != MMSYSERR_NOERROR) { delete_buffers(buffers); nassert_raise("Could not open audio input device."); - return NULL; + return nullptr; } for (int i=0; i<(int)buffers.size(); i++) { @@ -265,7 +265,7 @@ open() { waveInClose(hwav); delete_buffers(buffers); nassert_raise("Could not queue buffers for audio input device."); - return NULL; + return nullptr; } } stat = waveInStart(hwav); @@ -273,7 +273,7 @@ open() { waveInClose(hwav); delete_buffers(buffers); nassert_raise("Could not start recording on input device."); - return NULL; + return nullptr; } return new MicrophoneAudioCursorDS(this, buffers, hwav); } diff --git a/panda/src/movies/movieAudio.cxx b/panda/src/movies/movieAudio.cxx index 0dee90e805..6843984ac3 100644 --- a/panda/src/movies/movieAudio.cxx +++ b/panda/src/movies/movieAudio.cxx @@ -24,7 +24,7 @@ TypeHandle MovieAudio::_type_handle; * construct a subclass of this class. */ MovieAudio:: -MovieAudio(const string &name) : +MovieAudio(const std::string &name) : Namable(name) { } diff --git a/panda/src/movies/movieAudio.h b/panda/src/movies/movieAudio.h index 5e04f474eb..cce8eb3465 100644 --- a/panda/src/movies/movieAudio.h +++ b/panda/src/movies/movieAudio.h @@ -25,7 +25,7 @@ class MovieAudioCursor; // Non-release build: #define movies_debug(msg) \ if (movies_cat.is_debug()) { \ - movies_cat->debug() << msg << endl; \ + movies_cat->debug() << msg << std::endl; \ } else {} #else //][ // Release build: @@ -43,7 +43,7 @@ class MovieAudioCursor; */ class EXPCL_PANDA_MOVIES MovieAudio : public TypedWritableReferenceCount, public Namable { PUBLISHED: - MovieAudio(const string &name = "Blank Audio"); + MovieAudio(const std::string &name = "Blank Audio"); virtual ~MovieAudio(); virtual PT(MovieAudioCursor) open(); static PT(MovieAudio) get(const Filename &name); diff --git a/panda/src/movies/movieAudioCursor.cxx b/panda/src/movies/movieAudioCursor.cxx index f386401103..33acc0e10c 100644 --- a/panda/src/movies/movieAudioCursor.cxx +++ b/panda/src/movies/movieAudioCursor.cxx @@ -92,9 +92,9 @@ read_samples(int n, Datagram *dg) { * This is not particularly efficient, but it may be a convenient way to * manipulate samples in python. */ -string MovieAudioCursor:: +std::string MovieAudioCursor:: read_samples(int n) { - ostringstream result; + std::ostringstream result; int16_t tmp[4096]; while (n > 0) { int blocksize = (4096 / _audio_channels); diff --git a/panda/src/movies/movieAudioCursor.h b/panda/src/movies/movieAudioCursor.h index 8d49c26ccf..b2d5d9bebe 100644 --- a/panda/src/movies/movieAudioCursor.h +++ b/panda/src/movies/movieAudioCursor.h @@ -48,7 +48,7 @@ PUBLISHED: virtual int ready() const; virtual void seek(double offset); void read_samples(int n, Datagram *dg); - string read_samples(int n); + std::string read_samples(int n); public: virtual void read_samples(int n, int16_t *data); diff --git a/panda/src/movies/movieTypeRegistry.I b/panda/src/movies/movieTypeRegistry.I index a444d91d9b..901abca903 100644 --- a/panda/src/movies/movieTypeRegistry.I +++ b/panda/src/movies/movieTypeRegistry.I @@ -16,7 +16,7 @@ */ INLINE MovieTypeRegistry *MovieTypeRegistry:: get_global_ptr() { - if (_global_ptr == NULL) { + if (_global_ptr == nullptr) { _global_ptr = new MovieTypeRegistry; } diff --git a/panda/src/movies/movieTypeRegistry.cxx b/panda/src/movies/movieTypeRegistry.cxx index 9c747b6fe3..012deff1cd 100644 --- a/panda/src/movies/movieTypeRegistry.cxx +++ b/panda/src/movies/movieTypeRegistry.cxx @@ -17,7 +17,10 @@ #include "config_putil.h" #include "load_dso.h" -MovieTypeRegistry *MovieTypeRegistry::_global_ptr = NULL; +using std::endl; +using std::string; + +MovieTypeRegistry *MovieTypeRegistry::_global_ptr = nullptr; /** * Obtains a MovieVideo that references a file. @@ -104,7 +107,7 @@ load_audio_types() { movies_cat.info() << "loading audio type module: " << name << endl; void *tmp = load_dso(get_plugin_path().get_value(), dlname); - if (tmp == (void *)NULL) { + if (tmp == nullptr) { movies_cat.warning() << "Unable to load " << dlname.to_os_specific() << ": " << load_dso_error() << endl; @@ -220,7 +223,7 @@ load_video_types() { movies_cat.info() << "loading video type module: " << name << endl; void *tmp = load_dso(get_plugin_path().get_value(), dlname); - if (tmp == (void *)NULL) { + if (tmp == nullptr) { movies_cat.warning() << "Unable to load " << dlname.to_os_specific() << ": " << load_dso_error() << endl; @@ -261,7 +264,7 @@ load_movie_library(const string &name) { << "loading video type module: " << name << endl; void *tmp = load_dso(get_plugin_path().get_value(), dlname); - if (tmp == (void *)NULL) { + if (tmp == nullptr) { movies_cat.warning() << "Unable to load " << dlname.to_os_specific() << ": " << load_dso_error() << endl; diff --git a/panda/src/movies/movieTypeRegistry.h b/panda/src/movies/movieTypeRegistry.h index 0ebe467ffb..ee5fc14da2 100644 --- a/panda/src/movies/movieTypeRegistry.h +++ b/panda/src/movies/movieTypeRegistry.h @@ -28,26 +28,26 @@ class EXPCL_PANDA_MOVIES MovieTypeRegistry { public: typedef PT(MovieAudio) (*MakeAudioFunc)(const Filename&); PT(MovieAudio) make_audio(const Filename &name); - void register_audio_type(MakeAudioFunc func, const string &extensions); + void register_audio_type(MakeAudioFunc func, const std::string &extensions); void load_audio_types(); typedef PT(MovieVideo) (*MakeVideoFunc)(const Filename&); PT(MovieVideo) make_video(const Filename &name); - void register_video_type(MakeVideoFunc func, const string &extensions); + void register_video_type(MakeVideoFunc func, const std::string &extensions); void load_video_types(); - void load_movie_library(const string &name); + void load_movie_library(const std::string &name); INLINE static MovieTypeRegistry *get_global_ptr(); private: static MovieTypeRegistry *_global_ptr; - pmap _audio_type_registry; - pmap _deferred_audio_types; + pmap _audio_type_registry; + pmap _deferred_audio_types; - pmap _video_type_registry; - pmap _deferred_video_types; + pmap _video_type_registry; + pmap _deferred_video_types; }; #include "movieTypeRegistry.I" diff --git a/panda/src/movies/movieVideo.cxx b/panda/src/movies/movieVideo.cxx index 9b6c970472..57b755a453 100644 --- a/panda/src/movies/movieVideo.cxx +++ b/panda/src/movies/movieVideo.cxx @@ -26,7 +26,7 @@ TypeHandle MovieVideo::_type_handle; * need to construct a subclass of this class. */ MovieVideo:: -MovieVideo(const string &name) : +MovieVideo(const std::string &name) : Namable(name) { } @@ -44,7 +44,7 @@ MovieVideo:: */ PT(MovieVideoCursor) MovieVideo:: open() { - return NULL; + return nullptr; } /** diff --git a/panda/src/movies/movieVideo.h b/panda/src/movies/movieVideo.h index 4573495aa3..1e7da6288e 100644 --- a/panda/src/movies/movieVideo.h +++ b/panda/src/movies/movieVideo.h @@ -37,7 +37,7 @@ class BamReader; */ class EXPCL_PANDA_MOVIES MovieVideo : public TypedWritableReferenceCount, public Namable { PUBLISHED: - MovieVideo(const string &name = "Blank Video"); + MovieVideo(const std::string &name = "Blank Video"); virtual ~MovieVideo(); virtual PT(MovieVideoCursor) open(); static PT(MovieVideo) get(const Filename &name); diff --git a/panda/src/movies/movieVideoCursor.cxx b/panda/src/movies/movieVideoCursor.cxx index f1f531453a..96ead8c8f0 100644 --- a/panda/src/movies/movieVideoCursor.cxx +++ b/panda/src/movies/movieVideoCursor.cxx @@ -60,7 +60,21 @@ setup_texture(Texture *tex) const { int fullx = size_x(); int fully = size_y(); tex->adjust_this_size(fullx, fully, tex->get_name(), true); - Texture::Format fmt = (get_num_components() == 4) ? Texture::F_rgba : Texture::F_rgb; + Texture::Format fmt; + switch (get_num_components()) { + case 1: + fmt = Texture::F_luminance; + break; + case 2: + fmt = Texture::F_luminance_alpha; + break; + default: + fmt = Texture::F_rgb; + break; + case 4: + fmt = Texture::F_rgba; + break; + } tex->setup_texture(Texture::TT_2d_texture, fullx, fully, 1, Texture::T_unsigned_byte, fmt); tex->set_pad_size(fullx - size_x(), fully - size_y()); } @@ -97,7 +111,7 @@ set_time(double timestamp, int loop_count) { */ PT(MovieVideoCursor::Buffer) MovieVideoCursor:: fetch_buffer() { - return NULL; + return nullptr; } /** @@ -105,7 +119,7 @@ fetch_buffer() { */ void MovieVideoCursor:: apply_to_texture(const Buffer *buffer, Texture *t, int page) { - if (buffer == NULL) { + if (buffer == nullptr) { return; } @@ -113,7 +127,9 @@ apply_to_texture(const Buffer *buffer, Texture *t, int page) { nassertv(t->get_x_size() >= size_x()); nassertv(t->get_y_size() >= size_y()); - nassertv((t->get_num_components() == 3) || (t->get_num_components() == 4)); + nassertv((t->get_num_components() == 3) || (t->get_num_components() == 4) || + (t->get_num_components() == 1 && get_num_components() == 1) || + (t->get_num_components() == 2 && get_num_components() == 2)); nassertv(t->get_component_width() == 1); nassertv(page < t->get_num_pages()); @@ -132,17 +148,19 @@ apply_to_texture(const Buffer *buffer, Texture *t, int page) { } else { unsigned char *p = buffer->_block; - if (t->get_num_components() == get_num_components()) { - int src_stride = size_x() * get_num_components(); - int dst_stride = t->get_x_size() * t->get_num_components(); + int src_width = get_num_components(); + int dst_width = t->get_num_components(); + if (src_width == dst_width) { + int src_stride = src_width * size_x(); + int dst_stride = dst_width * t->get_x_size(); for (int y=0; yget_num_components(); + nassertv(src_width >= 3); + nassertv(dst_width >= 3); for (int y = 0; y < size_y(); ++y) { for (int x = 0; x < size_x(); ++x) { data[0] = p[0]; @@ -162,15 +180,26 @@ apply_to_texture(const Buffer *buffer, Texture *t, int page) { */ void MovieVideoCursor:: apply_to_texture_alpha(const Buffer *buffer, Texture *t, int page, int alpha_src) { - if (buffer == NULL) { + if (buffer == nullptr) { return; } PStatTimer timer(_copy_pcollector); + // Is this a grayscale texture? + if (get_num_components() < 3) { + if (get_num_components() == 1 || alpha_src < 2 || alpha_src == 3) { + // There's only one "RGB" channel to take from. + alpha_src = 1; + } else { + // Alpha is actually in the second channel for grayscale-alpha. + alpha_src = 2; + } + } + nassertv(t->get_x_size() >= size_x()); nassertv(t->get_y_size() >= size_y()); - nassertv(t->get_num_components() == 4); + nassertv(t->get_num_components() == 4 || t->get_num_components() == 2); nassertv(t->get_component_width() == 1); nassertv(page < t->get_z_size()); nassertv((alpha_src >= 0) && (alpha_src <= get_num_components())); @@ -186,14 +215,16 @@ apply_to_texture_alpha(const Buffer *buffer, Texture *t, int page, int alpha_src PStatTimer timer2(_copy_pcollector_copy); int src_width = get_num_components(); + int dst_width = t->get_num_components(); int src_stride = size_x() * src_width; - int dst_stride = t->get_x_size() * 4; + int dst_stride = t->get_x_size() * dst_width; unsigned char *p = buffer->_block; if (alpha_src == 0) { + nassertv(src_width >= 3); for (int y=0; yget_x_size() >= size_x()); nassertv(t->get_y_size() >= size_y()); - nassertv(t->get_num_components() == 4); + nassertv(t->get_num_components() == 4 || t->get_num_components() == 2); nassertv(t->get_component_width() == 1); nassertv(page < t->get_z_size()); @@ -238,18 +269,35 @@ apply_to_texture_rgb(const Buffer *buffer, Texture *t, int page) { unsigned char *data = img.p() + page * t->get_expected_ram_page_size(); PStatTimer timer2(_copy_pcollector_copy); - int src_stride = size_x() * get_num_components(); int src_width = get_num_components(); - int dst_stride = t->get_x_size() * 4; + int dst_width = t->get_num_components(); + int src_stride = size_x() * src_width; + int dst_stride = t->get_x_size() * dst_width; unsigned char *p = buffer->_block; - for (int y=0; y= 3) { + // It has RGB values. + nassertv(dst_width >= 3); + for (int y = 0; y < size_y(); ++y) { + for (int x = 0; x < size_x(); ++x) { + data[x * dst_width + 0] = p[x * src_width + 0]; + data[x * dst_width + 1] = p[x * src_width + 1]; + data[x * dst_width + 2] = p[x * src_width + 2]; + } + data += dst_stride; + p += src_stride; + } + } else if (dst_width == 4) { + // It has only grayscale. + for (int y = 0; y < size_y(); ++y) { + for (int x = 0; x < size_x(); ++x) { + unsigned char gray = p[x * src_width]; + data[x * dst_width + 0] = gray; + data[x * dst_width + 1] = gray; + data[x * dst_width + 2] = gray; + } + data += dst_stride; + p += src_stride; } - data += dst_stride; - p += src_stride; } } @@ -259,7 +307,7 @@ apply_to_texture_rgb(const Buffer *buffer, Texture *t, int page) { */ MovieVideoCursor::Buffer *MovieVideoCursor:: get_standard_buffer() { - if (_standard_buffer == NULL) { + if (_standard_buffer == nullptr) { _standard_buffer = make_new_buffer(); } return _standard_buffer; diff --git a/panda/src/movies/movieVideoCursor.h b/panda/src/movies/movieVideoCursor.h index 0fb11fe04b..8357f14693 100644 --- a/panda/src/movies/movieVideoCursor.h +++ b/panda/src/movies/movieVideoCursor.h @@ -40,7 +40,7 @@ class BamReader; */ class EXPCL_PANDA_MOVIES MovieVideoCursor : public TypedWritableReferenceCount { protected: - MovieVideoCursor(MovieVideo *src = NULL); + MovieVideoCursor(MovieVideo *src = nullptr); PUBLISHED: virtual ~MovieVideoCursor(); diff --git a/panda/src/movies/opusAudio.cxx b/panda/src/movies/opusAudio.cxx index 024560156a..54be404cd2 100644 --- a/panda/src/movies/opusAudio.cxx +++ b/panda/src/movies/opusAudio.cxx @@ -43,7 +43,7 @@ OpusAudio:: PT(MovieAudioCursor) OpusAudio:: open() { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); - istream *stream = vfs->open_read_file(_filename, true); + std::istream *stream = vfs->open_read_file(_filename, true); if (stream == nullptr) { return nullptr; diff --git a/panda/src/movies/opusAudioCursor.cxx b/panda/src/movies/opusAudioCursor.cxx index 698648c5cb..2b1591e971 100644 --- a/panda/src/movies/opusAudioCursor.cxx +++ b/panda/src/movies/opusAudioCursor.cxx @@ -18,6 +18,8 @@ #include +using std::istream; + /** * Callbacks passed to libopusfile to implement file I/O via the * VirtualFileSystem. @@ -46,15 +48,15 @@ int cb_seek(void *stream, opus_int64 offset, int whence) { switch (whence) { case SEEK_SET: - in->seekg(offset, ios::beg); + in->seekg(offset, std::ios::beg); break; case SEEK_CUR: - in->seekg(offset, ios::cur); + in->seekg(offset, std::ios::cur); break; case SEEK_END: - in->seekg(offset, ios::end); + in->seekg(offset, std::ios::end); break; default: @@ -165,7 +167,7 @@ seek(double t) { return; } - t = max(t, 0.0); + t = std::max(t, 0.0); // Use op_time_seek_lap if cross-lapping is enabled. int error = op_pcm_seek(_op, (ogg_int64_t)(t * 48000.0)); diff --git a/panda/src/movies/opusAudioCursor.h b/panda/src/movies/opusAudioCursor.h index 51916fbc29..1a3dfa035b 100644 --- a/panda/src/movies/opusAudioCursor.h +++ b/panda/src/movies/opusAudioCursor.h @@ -31,7 +31,7 @@ class OpusAudio; */ class EXPCL_PANDA_MOVIES OpusAudioCursor : public MovieAudioCursor { PUBLISHED: - explicit OpusAudioCursor(OpusAudio *src, istream *stream); + explicit OpusAudioCursor(OpusAudio *src, std::istream *stream); virtual ~OpusAudioCursor(); virtual void seek(double offset); @@ -49,8 +49,8 @@ protected: int _bytes_per_sample; bool _is_float; - streampos _data_start; - streampos _data_pos; + std::streampos _data_start; + std::streampos _data_pos; size_t _data_size; public: diff --git a/panda/src/movies/userDataAudio.cxx b/panda/src/movies/userDataAudio.cxx index 7575ad977b..f02726d10b 100644 --- a/panda/src/movies/userDataAudio.cxx +++ b/panda/src/movies/userDataAudio.cxx @@ -25,7 +25,7 @@ UserDataAudio(int rate, int channels, bool remove_after_read) : MovieAudio("User Data Audio"), _desired_rate(rate), _desired_channels(channels), - _cursor(NULL), + _cursor(nullptr), _aborted(false), _remove_after_read(remove_after_read) { @@ -46,7 +46,7 @@ PT(MovieAudioCursor) UserDataAudio:: open() { if (_cursor) { nassert_raise("A UserDataAudio can only be opened by one consumer at a time."); - return NULL; + return nullptr; } _cursor = new UserDataAudioCursor(this); return _cursor; @@ -107,7 +107,7 @@ append(DatagramIterator *src, int n) { * but it may be convenient to deal with samples in python. */ void UserDataAudio:: -append(const string &str) { +append(const std::string &str) { nassertv(!_aborted); int samples = str.size() / (2 * _desired_channels); int words = samples * _desired_channels; diff --git a/panda/src/movies/userDataAudio.h b/panda/src/movies/userDataAudio.h index 0f56ea492f..c37831b17b 100644 --- a/panda/src/movies/userDataAudio.h +++ b/panda/src/movies/userDataAudio.h @@ -37,7 +37,7 @@ class EXPCL_PANDA_MOVIES UserDataAudio : public MovieAudio { void append(int16_t *data, int n); void append(DatagramIterator *src, int len=0x40000000); - void append(const string &str); + void append(const std::string &str); void done(); // A promise not to write any more samples. private: diff --git a/panda/src/movies/userDataAudioCursor.cxx b/panda/src/movies/userDataAudioCursor.cxx index e0494cf53e..93bab206fa 100644 --- a/panda/src/movies/userDataAudioCursor.cxx +++ b/panda/src/movies/userDataAudioCursor.cxx @@ -39,7 +39,7 @@ UserDataAudioCursor(UserDataAudio *src) : UserDataAudioCursor:: ~UserDataAudioCursor() { UserDataAudio *source = (UserDataAudio*)(MovieAudio*)_source; - source->_cursor = NULL; + source->_cursor = nullptr; } /** diff --git a/panda/src/movies/vorbisAudio.cxx b/panda/src/movies/vorbisAudio.cxx index bd704e2bd1..db4c70b000 100644 --- a/panda/src/movies/vorbisAudio.cxx +++ b/panda/src/movies/vorbisAudio.cxx @@ -43,14 +43,14 @@ VorbisAudio:: PT(MovieAudioCursor) VorbisAudio:: open() { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); - istream *stream = vfs->open_read_file(_filename, true); + std::istream *stream = vfs->open_read_file(_filename, true); - if (stream == NULL) { - return NULL; + if (stream == nullptr) { + return nullptr; } else { PT(VorbisAudioCursor) cursor = new VorbisAudioCursor(this, stream); - if (cursor == NULL || !cursor->_is_valid) { - return NULL; + if (cursor == nullptr || !cursor->_is_valid) { + return nullptr; } else { return DCAST(MovieAudioCursor, cursor); } diff --git a/panda/src/movies/vorbisAudioCursor.cxx b/panda/src/movies/vorbisAudioCursor.cxx index 9d751629c2..d4478c9f07 100644 --- a/panda/src/movies/vorbisAudioCursor.cxx +++ b/panda/src/movies/vorbisAudioCursor.cxx @@ -16,6 +16,8 @@ #ifdef HAVE_VORBIS +using std::istream; + TypeHandle VorbisAudioCursor::_type_handle; /** @@ -28,7 +30,7 @@ VorbisAudioCursor(VorbisAudio *src, istream *stream) : _is_valid(false), _bitstream(0) { - nassertv(stream != NULL); + nassertv(stream != nullptr); nassertv(stream->good()); // Set up the callbacks to read via the VFS. @@ -40,10 +42,10 @@ VorbisAudioCursor(VorbisAudio *src, istream *stream) : if (vorbis_enable_seek) { callbacks.seek_func = &cb_seek_func; } else { - callbacks.seek_func = NULL; + callbacks.seek_func = nullptr; } - if (ov_open_callbacks((void*) stream, &_ov, NULL, 0, callbacks) != 0) { + if (ov_open_callbacks((void*) stream, &_ov, nullptr, 0, callbacks) != 0) { movies_cat.error() << "Failed to read Ogg Vorbis file.\n"; return; @@ -82,7 +84,7 @@ seek(double t) { return; } - t = max(t, 0.0); + t = std::max(t, 0.0); // Use ov_time_seek_lap if cross-lapping is enabled. if (vorbis_seek_lap) { @@ -162,7 +164,7 @@ read_samples(int n, int16_t *data) { size_t VorbisAudioCursor:: cb_read_func(void *ptr, size_t size, size_t nmemb, void *datasource) { istream *stream = (istream*) datasource; - nassertr(stream != NULL, -1); + nassertr(stream != nullptr, -1); stream->read((char *)ptr, size * nmemb); @@ -185,19 +187,19 @@ cb_seek_func(void *datasource, ogg_int64_t offset, int whence) { } istream *stream = (istream*) datasource; - nassertr(stream != NULL, -1); + nassertr(stream != nullptr, -1); switch (whence) { case SEEK_SET: - stream->seekg(offset, ios::beg); + stream->seekg(offset, std::ios::beg); break; case SEEK_CUR: - stream->seekg(offset, ios::cur); + stream->seekg(offset, std::ios::cur); break; case SEEK_END: - stream->seekg(offset, ios::end); + stream->seekg(offset, std::ios::end); break; default: @@ -239,7 +241,7 @@ cb_seek_func(void *datasource, ogg_int64_t offset, int whence) { int VorbisAudioCursor:: cb_close_func(void *datasource) { istream *stream = (istream*) datasource; - nassertr(stream != NULL, -1); + nassertr(stream != nullptr, -1); VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->close_read_file(stream); @@ -255,7 +257,7 @@ cb_close_func(void *datasource) { long VorbisAudioCursor:: cb_tell_func(void *datasource) { istream *stream = (istream*) datasource; - nassertr(stream != NULL, -1); + nassertr(stream != nullptr, -1); return stream->tellg(); } diff --git a/panda/src/movies/vorbisAudioCursor.h b/panda/src/movies/vorbisAudioCursor.h index 4a9bb79847..d194cb0c23 100644 --- a/panda/src/movies/vorbisAudioCursor.h +++ b/panda/src/movies/vorbisAudioCursor.h @@ -30,7 +30,7 @@ class VorbisAudio; */ class EXPCL_PANDA_MOVIES VorbisAudioCursor : public MovieAudioCursor { PUBLISHED: - explicit VorbisAudioCursor(VorbisAudio *src, istream *stream); + explicit VorbisAudioCursor(VorbisAudio *src, std::istream *stream); virtual ~VorbisAudioCursor(); virtual void seek(double offset); @@ -57,8 +57,8 @@ protected: int _bytes_per_sample; bool _is_float; - streampos _data_start; - streampos _data_pos; + std::streampos _data_start; + std::streampos _data_pos; size_t _data_size; public: diff --git a/panda/src/movies/wavAudio.cxx b/panda/src/movies/wavAudio.cxx index 0240c37a94..854d2aef5c 100644 --- a/panda/src/movies/wavAudio.cxx +++ b/panda/src/movies/wavAudio.cxx @@ -41,14 +41,14 @@ WavAudio:: PT(MovieAudioCursor) WavAudio:: open() { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); - istream *stream = vfs->open_read_file(_filename, true); + std::istream *stream = vfs->open_read_file(_filename, true); - if (stream == NULL) { - return NULL; + if (stream == nullptr) { + return nullptr; } else { PT(WavAudioCursor) cursor = new WavAudioCursor(this, stream); - if (cursor == NULL || !cursor->_is_valid) { - return NULL; + if (cursor == nullptr || !cursor->_is_valid) { + return nullptr; } else { return DCAST(MovieAudioCursor, cursor); } diff --git a/panda/src/movies/wavAudioCursor.cxx b/panda/src/movies/wavAudioCursor.cxx index ccfaa9733e..381ce2d81b 100644 --- a/panda/src/movies/wavAudioCursor.cxx +++ b/panda/src/movies/wavAudioCursor.cxx @@ -94,7 +94,7 @@ TypeHandle WavAudioCursor::_type_handle; * pointer positioned at the start of the data. */ WavAudioCursor:: -WavAudioCursor(WavAudio *src, istream *stream) : +WavAudioCursor(WavAudio *src, std::istream *stream) : MovieAudioCursor(src), _is_valid(false), _stream(stream), @@ -103,7 +103,7 @@ WavAudioCursor(WavAudio *src, istream *stream) : _data_pos(0), _data_size(0) { - nassertv(stream != NULL); + nassertv(stream != nullptr); // Beginning of "RIFF" chunk. unsigned char magic[4]; @@ -279,7 +279,7 @@ WavAudioCursor(WavAudio *src, istream *stream) : */ WavAudioCursor:: ~WavAudioCursor() { - if (_stream != NULL) { + if (_stream != nullptr) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->close_read_file(_stream); } @@ -291,8 +291,8 @@ WavAudioCursor:: */ void WavAudioCursor:: seek(double t) { - t = max(t, 0.0); - streampos pos = _data_start + (streampos) min((size_t) (t * _byte_rate), _data_size); + t = std::max(t, 0.0); + std::streampos pos = _data_start + (std::streampos) std::min((size_t) (t * _byte_rate), _data_size); if (_can_seek_fast) { _stream->seekg(pos); @@ -303,7 +303,7 @@ seek(double t) { } if (!_can_seek_fast) { - streampos current = _stream->tellg(); + std::streampos current = _stream->tellg(); if (pos > current) { // It is ahead of our current position. Skip ahead. @@ -327,7 +327,7 @@ seek(double t) { void WavAudioCursor:: read_samples(int n, int16_t *data) { int desired = n * _audio_channels; - int read_samples = min(desired, ((int) (_data_size - _data_pos)) / _bytes_per_sample); + int read_samples = std::min(desired, ((int) (_data_size - _data_pos)) / _bytes_per_sample); if (read_samples <= 0) { return; diff --git a/panda/src/movies/wavAudioCursor.h b/panda/src/movies/wavAudioCursor.h index 2f37f37f4e..21133b1c62 100644 --- a/panda/src/movies/wavAudioCursor.h +++ b/panda/src/movies/wavAudioCursor.h @@ -26,7 +26,7 @@ class WavAudio; */ class EXPCL_PANDA_MOVIES WavAudioCursor : public MovieAudioCursor { PUBLISHED: - explicit WavAudioCursor(WavAudio *src, istream *stream); + explicit WavAudioCursor(WavAudio *src, std::istream *stream); virtual ~WavAudioCursor(); virtual void seek(double offset); @@ -46,7 +46,7 @@ protected: F_extensible = 0xfffe, }; - istream *_stream; + std::istream *_stream; StreamReader _reader; Format _format; @@ -54,8 +54,8 @@ protected: int _block_align; int _bytes_per_sample; - streampos _data_start; - streampos _data_pos; + std::streampos _data_start; + std::streampos _data_pos; size_t _data_size; public: diff --git a/panda/src/nativenet/membuffer.I b/panda/src/nativenet/membuffer.I index 157df8301a..a2e7ad6d1d 100644 --- a/panda/src/nativenet/membuffer.I +++ b/panda/src/nativenet/membuffer.I @@ -6,11 +6,11 @@ inline void MemBuffer:: ClearBuffer(void) { if (_BufferLocal == true) { - if (_Buffer != NULL) { + if (_Buffer != nullptr) { delete[] _Buffer; } - _Buffer = NULL; + _Buffer = nullptr; } } @@ -29,7 +29,7 @@ AllocBuffer(size_t len) { */ inline MemBuffer:: MemBuffer(void) { - _Buffer = NULL; + _Buffer = nullptr; _BufferLocal = false; _BufferLen = 0; } @@ -87,7 +87,7 @@ GrowBuffer(size_t new_len) { char *tmp = new char[len]; - if (_Buffer != NULL) { + if (_Buffer != nullptr) { memcpy(tmp,_Buffer,_BufferLen); } diff --git a/panda/src/nativenet/socket_address.cxx b/panda/src/nativenet/socket_address.cxx index cf27b0771c..3d7882aeed 100644 --- a/panda/src/nativenet/socket_address.cxx +++ b/panda/src/nativenet/socket_address.cxx @@ -26,12 +26,12 @@ set_host(const std::string &hostname, unsigned short port) { return set_broadcast(port); } - struct addrinfo hints, *res = NULL; + struct addrinfo hints, *res = nullptr; memset(&hints, 0, sizeof(hints)); hints.ai_flags = AI_ADDRCONFIG; hints.ai_family = support_ipv6 ? AF_UNSPEC : AF_INET; - if (getaddrinfo(hostname.c_str(), NULL, &hints, &res)) { + if (getaddrinfo(hostname.c_str(), nullptr, &hints, &res)) { return false; } @@ -92,10 +92,10 @@ get_ip() const { buf[0] = 0; if (_storage.ss_family == AF_INET) { - getnameinfo(&_addr, sizeof(sockaddr_in), buf, sizeof(buf), NULL, 0, NI_NUMERICHOST); + getnameinfo(&_addr, sizeof(sockaddr_in), buf, sizeof(buf), nullptr, 0, NI_NUMERICHOST); } else if (_storage.ss_family == AF_INET6) { - getnameinfo(&_addr, sizeof(sockaddr_in6), buf, sizeof(buf), NULL, 0, NI_NUMERICHOST); + getnameinfo(&_addr, sizeof(sockaddr_in6), buf, sizeof(buf), nullptr, 0, NI_NUMERICHOST); } else { nassertr(false, std::string()); @@ -114,13 +114,13 @@ get_ip_port() const { buf[0] = 0; if (_storage.ss_family == AF_INET) { - getnameinfo(&_addr, sizeof(sockaddr_in), buf, sizeof(buf), NULL, 0, NI_NUMERICHOST); + getnameinfo(&_addr, sizeof(sockaddr_in), buf, sizeof(buf), nullptr, 0, NI_NUMERICHOST); sprintf(buf + strlen(buf), ":%hu", get_port()); } else if (_storage.ss_family == AF_INET6) { // Protect the IPv6 address within square brackets. buf[0] = '['; - getnameinfo(&_addr, sizeof(sockaddr_in6), buf + 1, sizeof(buf) - 1, NULL, 0, NI_NUMERICHOST); + getnameinfo(&_addr, sizeof(sockaddr_in6), buf + 1, sizeof(buf) - 1, nullptr, 0, NI_NUMERICHOST); sprintf(buf + strlen(buf), "]:%hu", get_port()); } else { diff --git a/panda/src/nativenet/socket_fdset.h b/panda/src/nativenet/socket_fdset.h index 45c990bf27..7da876c0f8 100644 --- a/panda/src/nativenet/socket_fdset.h +++ b/panda/src/nativenet/socket_fdset.h @@ -90,13 +90,13 @@ inline int Socket_fdset::WaitForRead(bool zeroFds, uint32_t sleep_time) { int retVal = 0; if (sleep_time == 0xffffffff) { - retVal = DO_SELECT(_maxid + 1, &_the_set, NULL, NULL, NULL); + retVal = DO_SELECT(_maxid + 1, &_the_set, nullptr, nullptr, nullptr); } else { timeval timeoutValue; timeoutValue.tv_sec = sleep_time / 1000; timeoutValue.tv_usec = (sleep_time % 1000) * 1000; - retVal = DO_SELECT(_maxid + 1, &_the_set, NULL, NULL, &timeoutValue); + retVal = DO_SELECT(_maxid + 1, &_the_set, nullptr, nullptr, &timeoutValue); } if (zeroFds) clear(); @@ -111,7 +111,7 @@ inline int Socket_fdset::WaitForRead(bool zeroFds, const Time_Span & timeout) { timeval localtv = timeout.GetTval(); - int retVal = DO_SELECT(_maxid + 1, &_the_set, NULL, NULL, &localtv); + int retVal = DO_SELECT(_maxid + 1, &_the_set, nullptr, nullptr, &localtv); if (zeroFds) clear(); @@ -144,7 +144,7 @@ inline int Socket_fdset::WaitForWrite(bool zeroFds, uint32_t sleep_time) int retVal = 0; if (sleep_time == 0xffffffff) { - retVal = DO_SELECT(_maxid + 1, NULL, &_the_set, NULL, NULL); + retVal = DO_SELECT(_maxid + 1, nullptr, &_the_set, nullptr, nullptr); } else { @@ -152,7 +152,7 @@ inline int Socket_fdset::WaitForWrite(bool zeroFds, uint32_t sleep_time) timeoutValue.tv_sec = sleep_time / 1000; timeoutValue.tv_usec = (sleep_time % 1000) * 1000; - retVal = DO_SELECT(_maxid + 1, NULL, &_the_set, NULL, &timeoutValue); + retVal = DO_SELECT(_maxid + 1, nullptr, &_the_set, nullptr, &timeoutValue); } if (zeroFds) clear(); @@ -169,7 +169,7 @@ inline int Socket_fdset::WaitForError(bool zeroFds, uint32_t sleep_time) int retVal = 0; if (sleep_time == 0xffffffff) { - retVal = DO_SELECT(_maxid + 1, NULL, NULL, &_the_set, NULL); + retVal = DO_SELECT(_maxid + 1, nullptr, nullptr, &_the_set, nullptr); } else { @@ -177,7 +177,7 @@ inline int Socket_fdset::WaitForError(bool zeroFds, uint32_t sleep_time) timeoutValue.tv_sec = sleep_time / 1000; timeoutValue.tv_usec = (sleep_time % 1000) * 1000; - retVal = DO_SELECT(_maxid + 1, NULL, NULL, &_the_set, &timeoutValue); + retVal = DO_SELECT(_maxid + 1, nullptr, nullptr, &_the_set, &timeoutValue); } if (zeroFds) clear(); diff --git a/panda/src/nativenet/socket_tcp_ssl.h b/panda/src/nativenet/socket_tcp_ssl.h index 83b45b4389..8f16f188dc 100644 --- a/panda/src/nativenet/socket_tcp_ssl.h +++ b/panda/src/nativenet/socket_tcp_ssl.h @@ -30,10 +30,10 @@ struct SSlStartup { ~SSlStartup() { SSL_CTX_free (global_ssl_ctx); - global_ssl_ctx = NULL; + global_ssl_ctx = nullptr; } - bool isactive() { return global_ssl_ctx != NULL; }; + bool isactive() { return global_ssl_ctx != nullptr; }; }; /** @@ -42,7 +42,7 @@ struct SSlStartup { class EXPCL_PANDA_NATIVENET Socket_TCP_SSL : public Socket_IP { public: inline Socket_TCP_SSL(SOCKET); - inline Socket_TCP_SSL() : _ssl(NULL) {} + inline Socket_TCP_SSL() : _ssl(nullptr) {} virtual inline ~Socket_TCP_SSL() { @@ -67,10 +67,10 @@ private: SSL *_ssl; void CleanSslUp() { - if (_ssl != NULL) { + if (_ssl != nullptr) { SSL_shutdown(_ssl); SSL_free(_ssl); - _ssl = NULL; + _ssl = nullptr; } } @@ -101,7 +101,7 @@ Socket_TCP_SSL(SOCKET sck) : ::Socket_IP(sck) { SetNonBlocking(); // maybe should be blocking? _ssl = SSL_new(global_ssl_ctx); - if (_ssl == NULL) { + if (_ssl == nullptr) { return; } @@ -188,7 +188,7 @@ ActiveOpen(const Socket_Address &theaddress) { } _ssl = SSL_new(global_ssl_ctx); - if (_ssl == NULL) { + if (_ssl == nullptr) { return false; } SSL_set_fd(_ssl, (int)GetSocket()); @@ -206,7 +206,7 @@ ActiveOpen(const Socket_Address &theaddress) { */ inline int Socket_TCP_SSL:: SendData(const char *data, int size) { - if (_ssl == NULL) { + if (_ssl == nullptr) { return -1; } @@ -221,7 +221,7 @@ SendData(const char *data, int size) { */ inline int Socket_TCP_SSL:: RecvData(char *data, int len) { - if (_ssl == NULL) { + if (_ssl == nullptr) { return -1; } @@ -235,7 +235,7 @@ RecvData(char *data, int len) { */ inline bool Socket_TCP_SSL:: ErrorIs_WouldBlocking(int err) { - if (_ssl == NULL || err >= 0) { + if (_ssl == nullptr || err >= 0) { nativenet_cat.warning() << "Socket_TCP_SSL::ErrorIs_WouldBlocking->Called With Error number " << err << " or _ssl is NULL\n"; diff --git a/panda/src/nativenet/socket_udp.h b/panda/src/nativenet/socket_udp.h index 58c410dd97..5f7b02c49e 100644 --- a/panda/src/nativenet/socket_udp.h +++ b/panda/src/nativenet/socket_udp.h @@ -31,11 +31,11 @@ PUBLISHED: public: inline bool Send(const char *data, int len); PUBLISHED: - inline bool Send(const string &data); + inline bool Send(const std::string &data); public: inline bool SendTo(const char *data, int len, const Socket_Address &address); PUBLISHED: - inline bool SendTo(const string &data, const Socket_Address &address); + inline bool SendTo(const std::string &data, const Socket_Address &address); inline bool SetToBroadCast(); public: @@ -96,7 +96,7 @@ Send(const char *data, int len) { * Send data to connected address */ inline bool Socket_UDP:: -Send(const string &data) { +Send(const std::string &data) { return Send(data.data(), data.size()); } @@ -112,7 +112,7 @@ SendTo(const char *data, int len, const Socket_Address &address) { * Send data to specified address */ inline bool Socket_UDP:: -SendTo(const string &data, const Socket_Address &address) { +SendTo(const std::string &data, const Socket_Address &address) { return SendTo(data.data(), data.size(), address); } diff --git a/panda/src/nativenet/socket_udp_outgoing.h b/panda/src/nativenet/socket_udp_outgoing.h index 3d1c9bb688..f8acaaccc2 100644 --- a/panda/src/nativenet/socket_udp_outgoing.h +++ b/panda/src/nativenet/socket_udp_outgoing.h @@ -16,13 +16,13 @@ PUBLISHED: public: inline bool Send(const char *data, int len); PUBLISHED: - inline bool Send(const string &data); + inline bool Send(const std::string &data); // use this interface for a none tagreted UDP connection inline bool InitNoAddress(); public: inline bool SendTo(const char *data, int len, const Socket_Address &address); PUBLISHED: - inline bool SendTo(const string &data, const Socket_Address &address); + inline bool SendTo(const std::string &data, const Socket_Address &address); inline bool SetToBroadCast(); public: @@ -98,7 +98,7 @@ Send(const char *data, int len) { * Send data to connected address */ inline bool Socket_UDP_Outgoing:: -Send(const string &data) { +Send(const std::string &data) { return Send(data.data(), data.size()); } @@ -114,7 +114,7 @@ SendTo(const char *data, int len, const Socket_Address &address) { * Send data to specified address */ inline bool Socket_UDP_Outgoing:: -SendTo(const string &data, const Socket_Address &address) { +SendTo(const std::string &data, const Socket_Address &address) { return SendTo(data.data(), data.size(), address); } diff --git a/panda/src/nativenet/time_accumulator.h b/panda/src/nativenet/time_accumulator.h index 32d0747310..3b7959a018 100644 --- a/panda/src/nativenet/time_accumulator.h +++ b/panda/src/nativenet/time_accumulator.h @@ -26,7 +26,7 @@ inline void Time_Accumulator::Set(const Time_Span & in) // this seems to make the most since .. if you are running the clock right // know... assume the timespane you are passing in is inclusive.. but keep // clock running.. May need to rethink this... - if(_accum_start != NULL) + if(_accum_start != nullptr) { Stop(); Start(); @@ -35,7 +35,7 @@ inline void Time_Accumulator::Set(const Time_Span & in) /** * */ -inline Time_Accumulator::Time_Accumulator() : _total_time(0,0,0,0,0), _accum_start(NULL) +inline Time_Accumulator::Time_Accumulator() : _total_time(0,0,0,0,0), _accum_start(nullptr) { } /** @@ -43,7 +43,7 @@ inline Time_Accumulator::Time_Accumulator() : _total_time(0,0,0,0,0), _accum_sta */ inline Time_Accumulator::~Time_Accumulator() { - if(_accum_start != NULL) + if(_accum_start != nullptr) delete _accum_start; } /** @@ -51,7 +51,7 @@ inline Time_Accumulator::~Time_Accumulator() */ inline void Time_Accumulator::Start() { - if(_accum_start == NULL) + if(_accum_start == nullptr) _accum_start = new Time_Clock(); } /** @@ -59,12 +59,12 @@ inline void Time_Accumulator::Start() */ inline void Time_Accumulator::Stop() { - if(_accum_start != NULL) + if(_accum_start != nullptr) { Time_Span work1(Time_Clock::GetCurrentTime() - *_accum_start); _total_time += work1; delete _accum_start; - _accum_start = NULL; + _accum_start = nullptr; } } /** @@ -72,10 +72,10 @@ inline void Time_Accumulator::Stop() */ void Time_Accumulator::Reset() { - if(_accum_start != NULL) + if(_accum_start != nullptr) { delete _accum_start; - _accum_start = NULL; + _accum_start = nullptr; } _total_time.Set(0,0,0,0,0); } @@ -85,7 +85,7 @@ void Time_Accumulator::Reset() inline Time_Span Time_Accumulator::Report() { Time_Span answer(_total_time); - if(_accum_start != NULL) + if(_accum_start != nullptr) { Time_Span ww(Time_Clock::GetCurrentTime() - *_accum_start); answer += ww; diff --git a/panda/src/nativenet/time_clock.h b/panda/src/nativenet/time_clock.h index 2c326fd7da..08f3616377 100644 --- a/panda/src/nativenet/time_clock.h +++ b/panda/src/nativenet/time_clock.h @@ -134,7 +134,7 @@ GetCurrentTime() { */ inline Time_Clock:: Time_Clock() { - gettimeofday(&_my_time, NULL); + gettimeofday(&_my_time, nullptr); } /** @@ -142,7 +142,7 @@ Time_Clock() { */ inline void Time_Clock:: ToCurrentTime() { - gettimeofday(&_my_time, NULL); + gettimeofday(&_my_time, nullptr); } /** @@ -152,9 +152,9 @@ ToCurrentTime() { */ inline struct tm *Time_Clock:: GetGmtTm(struct tm *ptm) const { - nassertr(ptm != NULL, NULL); + nassertr(ptm != nullptr, nullptr); #ifdef _WIN32 - return (gmtime_s(ptm, (const time_t *)&_my_time.tv_sec) == 0) ? ptm : NULL; + return (gmtime_s(ptm, (const time_t *)&_my_time.tv_sec) == 0) ? ptm : nullptr; #else return gmtime_r((const time_t *)&_my_time.tv_sec, ptm); #endif @@ -165,9 +165,9 @@ GetGmtTm(struct tm *ptm) const { */ inline struct tm *Time_Clock:: GetLocalTm(struct tm *ptm) const { - nassertr(ptm != NULL, NULL); + nassertr(ptm != nullptr, nullptr); #ifdef _WIN32 - return (localtime_s(ptm, (const time_t *)&_my_time.tv_sec) == 0) ? ptm : NULL; + return (localtime_s(ptm, (const time_t *)&_my_time.tv_sec) == 0) ? ptm : nullptr; #else return localtime_r((const time_t *)&_my_time.tv_sec, ptm); #endif @@ -210,7 +210,7 @@ Format(const char *pFormat) const { char szBuffer1[maxTimeBufferSize]; struct tm tmTemp; - if (GetLocalTm(&tmTemp) == NULL || + if (GetLocalTm(&tmTemp) == nullptr || !strftime(szBuffer1, sizeof(szBuffer1), szBuffer, &tmTemp)) { szBuffer1[0] = '\0'; } @@ -253,7 +253,7 @@ FormatGmt(const char *pFormat) const { char szBuffer1[maxTimeBufferSize]; struct tm tmTemp; - if (GetGmtTm(&tmTemp) == NULL || + if (GetGmtTm(&tmTemp) == nullptr || !strftime(szBuffer1, sizeof(szBuffer1), szBuffer, &tmTemp)) { szBuffer1[0] = '\0'; } diff --git a/panda/src/net/config_net.cxx b/panda/src/net/config_net.cxx index ae717bb580..80af80147a 100644 --- a/panda/src/net/config_net.cxx +++ b/panda/src/net/config_net.cxx @@ -40,9 +40,9 @@ ConfigureFn(config_net) { int get_net_max_write_queue() { - static ConfigVariableInt *net_max_write_queue = NULL; + static ConfigVariableInt *net_max_write_queue = nullptr; - if (net_max_write_queue == (ConfigVariableInt *)NULL) { + if (net_max_write_queue == nullptr) { net_max_write_queue = new ConfigVariableInt ("net-max-write-queue", 10000, PRC_DESC("This limits the number of datagrams in a ConnectionWriter's " @@ -54,9 +54,9 @@ get_net_max_write_queue() { int get_net_max_response_queue() { - static ConfigVariableInt *net_max_response_queue = NULL; + static ConfigVariableInt *net_max_response_queue = nullptr; - if (net_max_response_queue == (ConfigVariableInt *)NULL) { + if (net_max_response_queue == nullptr) { net_max_response_queue = new ConfigVariableInt ("net-max-response-queue", 50000, PRC_DESC("This limits the number of datagrams, messages, what have you, " @@ -69,9 +69,9 @@ get_net_max_response_queue() { bool get_net_error_abort() { - static ConfigVariableBool *net_error_abort = NULL; + static ConfigVariableBool *net_error_abort = nullptr; - if (net_error_abort == (ConfigVariableBool *)NULL) { + if (net_error_abort == nullptr) { net_error_abort = new ConfigVariableBool ("net-error-abort", false); } @@ -81,9 +81,9 @@ get_net_error_abort() { double get_net_max_poll_cycle() { - static ConfigVariableDouble *net_max_poll_cycle = NULL; + static ConfigVariableDouble *net_max_poll_cycle = nullptr; - if (net_max_poll_cycle == (ConfigVariableDouble *)NULL) { + if (net_max_poll_cycle == nullptr) { net_max_poll_cycle = new ConfigVariableDouble ("net-max-poll-cycle", 0.2, PRC_DESC("Specifies the maximum amount of time, in seconds, to " @@ -100,9 +100,9 @@ get_net_max_poll_cycle() { double get_net_max_block() { - static ConfigVariableDouble *net_max_block = NULL; + static ConfigVariableDouble *net_max_block = nullptr; - if (net_max_block == (ConfigVariableDouble *)NULL) { + if (net_max_block == nullptr) { net_max_block = new ConfigVariableDouble ("net-max-block", 0.01, PRC_DESC("Specifies the maximum amount of time, in seconds, to " @@ -119,9 +119,9 @@ get_net_max_block() { // This function is used in the ReaderThread and WriterThread constructors to // make a simple name for each thread. -string -make_thread_name(const string &thread_name, int thread_index) { - ostringstream stream; +std::string +make_thread_name(const std::string &thread_name, int thread_index) { + std::ostringstream stream; stream << thread_name << "_" << thread_index; return stream.str(); } diff --git a/panda/src/net/config_net.h b/panda/src/net/config_net.h index e039f6bd2a..a80faa1642 100644 --- a/panda/src/net/config_net.h +++ b/panda/src/net/config_net.h @@ -31,7 +31,7 @@ extern int get_net_max_response_queue(); extern bool get_net_error_abort(); extern double get_net_max_poll_cycle(); extern double get_net_max_block(); -extern string make_thread_name(const string &thread_name, int thread_index); +extern std::string make_thread_name(const std::string &thread_name, int thread_index); extern ConfigVariableInt net_max_read_per_epoch; extern ConfigVariableInt net_max_write_per_epoch; diff --git a/panda/src/net/connection.cxx b/panda/src/net/connection.cxx index 4c42614f7c..aecfc111ac 100644 --- a/panda/src/net/connection.cxx +++ b/panda/src/net/connection.cxx @@ -60,7 +60,7 @@ Connection:: net_cat.info() << "Deleting connection " << (void *)this << "\n"; - if (_socket != (Socket_IP *)NULL) { + if (_socket != nullptr) { flush(); _socket->Close(); @@ -294,7 +294,7 @@ set_max_segment(int size) { */ bool Connection:: send_datagram(const NetDatagram &datagram, int tcp_header_size) { - nassertr(_socket != (Socket_IP *)NULL, false); + nassertr(_socket != nullptr, false); if (_socket->is_exact_type(Socket_UDP::get_class_type())) { // We have to send UDP right away. @@ -303,7 +303,7 @@ send_datagram(const NetDatagram &datagram, int tcp_header_size) { LightReMutexHolder holder(_write_mutex); DatagramUDPHeader header(datagram); - string data; + std::string data; data += header.get_header(); data += datagram.get_message(); @@ -367,14 +367,14 @@ send_datagram(const NetDatagram &datagram, int tcp_header_size) { */ bool Connection:: send_raw_datagram(const NetDatagram &datagram) { - nassertr(_socket != (Socket_IP *)NULL, false); + nassertr(_socket != nullptr, false); if (_socket->is_exact_type(Socket_UDP::get_class_type())) { // We have to send UDP right away. Socket_UDP *udp; DCAST_INTO_R(udp, _socket, false); - string data = datagram.get_message(); + std::string data = datagram.get_message(); LightReMutexHolder holder(_write_mutex); Socket_Address addr = datagram.get_address().get_addr(); @@ -430,7 +430,7 @@ do_flush() { Socket_TCP *tcp; DCAST_INTO_R(tcp, _socket, false); - string sending_data; + std::string sending_data; _queued_data.swap(sending_data); _queued_count = 0; @@ -438,7 +438,7 @@ do_flush() { #if defined(HAVE_THREADS) && defined(SIMPLE_THREADS) int max_send = net_max_write_per_epoch; - int data_sent = tcp->SendData(sending_data.data(), min((size_t)max_send, sending_data.size())); + int data_sent = tcp->SendData(sending_data.data(), std::min((size_t)max_send, sending_data.size())); bool okflag = (data_sent == (int)sending_data.size()); if (!okflag) { int total_sent = 0; @@ -453,7 +453,7 @@ do_flush() { } else { Thread::consider_yield(); } - data_sent = tcp->SendData(sending_data.data() + total_sent, min((size_t)max_send, sending_data.size() - total_sent)); + data_sent = tcp->SendData(sending_data.data() + total_sent, std::min((size_t)max_send, sending_data.size() - total_sent)); if (data_sent > 0) { total_sent += data_sent; } @@ -483,7 +483,7 @@ check_send_error(bool okflag) { // Assume any error means the connection has been reset; tell our manager // about it and ignore it. - if (_manager != (ConnectionManager *)NULL) { + if (_manager != nullptr) { _manager->flush_read_connection(this); _manager->connection_reset(this, okflag); } diff --git a/panda/src/net/connection.h b/panda/src/net/connection.h index bac0c8def0..6a7c44a744 100644 --- a/panda/src/net/connection.h +++ b/panda/src/net/connection.h @@ -68,7 +68,7 @@ private: bool _collect_tcp; double _collect_tcp_interval; double _queued_data_start; - string _queued_data; + std::string _queued_data; int _queued_count; friend class ConnectionWriter; diff --git a/panda/src/net/connectionListener.cxx b/panda/src/net/connectionListener.cxx index c959051653..2ab8b33ef7 100644 --- a/panda/src/net/connectionListener.cxx +++ b/panda/src/net/connectionListener.cxx @@ -19,8 +19,8 @@ #include "config_net.h" #include "socket_tcp_listen.h" -static string -listener_thread_name(const string &thread_name) { +static std::string +listener_thread_name(const std::string &thread_name) { if (!thread_name.empty()) { return thread_name; } @@ -32,7 +32,7 @@ listener_thread_name(const string &thread_name) { */ ConnectionListener:: ConnectionListener(ConnectionManager *manager, int num_threads, - const string &thread_name) : + const std::string &thread_name) : ConnectionReader(manager, num_threads, listener_thread_name(thread_name)) { } @@ -82,7 +82,7 @@ process_incoming_data(SocketInfo *sinfo) { << "\n"; PT(Connection) new_connection = new Connection(_manager, session); - if (_manager != (ConnectionManager *)NULL) { + if (_manager != nullptr) { _manager->new_connection(new_connection); } connection_opened(sinfo->_connection, net_addr, new_connection); diff --git a/panda/src/net/connectionListener.h b/panda/src/net/connectionListener.h index 9ec42ab456..7251dafe27 100644 --- a/panda/src/net/connectionListener.h +++ b/panda/src/net/connectionListener.h @@ -31,7 +31,7 @@ class NetAddress; class EXPCL_PANDA_NET ConnectionListener : public ConnectionReader { PUBLISHED: ConnectionListener(ConnectionManager *manager, int num_threads, - const string &thread_name = string()); + const std::string &thread_name = std::string()); protected: virtual void receive_datagram(const NetDatagram &datagram); diff --git a/panda/src/net/connectionManager.cxx b/panda/src/net/connectionManager.cxx index 8a0bfc1e86..f125356f50 100644 --- a/panda/src/net/connectionManager.cxx +++ b/panda/src/net/connectionManager.cxx @@ -33,6 +33,9 @@ #include #endif +using std::stringstream; +using std::string; + /** * */ @@ -328,7 +331,7 @@ open_TCP_client_connection(const string &hostname, uint16_t port, */ bool ConnectionManager:: close_connection(const PT(Connection) &connection) { - if (connection != (Connection *)NULL) { + if (connection != nullptr) { connection->flush(); } @@ -412,7 +415,7 @@ wait_for_readers(double timeout) { double wait_timeout = get_net_max_block(); if (!block_forever) { - wait_timeout = min(wait_timeout, stop - now); + wait_timeout = std::min(wait_timeout, stop - now); } uint32_t wait_timeout_ms = (uint32_t)(wait_timeout * 1000.0); @@ -479,17 +482,17 @@ scan_interfaces() { int flags = GAA_FLAG_INCLUDE_PREFIX | GAA_FLAG_SKIP_UNICAST | GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER; ULONG family = support_ipv6 ? AF_UNSPEC : AF_INET; ULONG buffer_size = 0; - ULONG result = GetAdaptersAddresses(family, flags, NULL, NULL, &buffer_size); + ULONG result = GetAdaptersAddresses(family, flags, nullptr, nullptr, &buffer_size); if (result == ERROR_BUFFER_OVERFLOW) { IP_ADAPTER_ADDRESSES *addresses = (IP_ADAPTER_ADDRESSES *)PANDA_MALLOC_ARRAY(buffer_size); - result = GetAdaptersAddresses(family, flags, NULL, addresses, &buffer_size); + result = GetAdaptersAddresses(family, flags, nullptr, addresses, &buffer_size); if (result == ERROR_SUCCESS) { IP_ADAPTER_ADDRESSES *p = addresses; - while (p != NULL) { + while (p != nullptr) { // p->AdapterName appears to be a GUID. Not sure if this is actually // useful to anyone; we'll store the "friendly name" instead. TextEncoder encoder; - encoder.set_wtext(wstring(p->FriendlyName)); + encoder.set_wtext(std::wstring(p->FriendlyName)); string friendly_name = encoder.get_text(); Interface iface; @@ -505,7 +508,7 @@ scan_interfaces() { NetAddress addresses[3]; IP_ADAPTER_PREFIX *m = p->FirstPrefix; int mc = 0; - while (m != NULL && mc < 3) { + while (m != nullptr && mc < 3) { addresses[mc] = NetAddress(Socket_Address(*m->Address.lpSockaddr)); m = m->Next; ++mc; @@ -551,20 +554,20 @@ scan_interfaces() { } struct ifaddrs *p = ifa; - while (p != NULL) { + while (p != nullptr) { if (p->ifa_addr->sa_family == AF_INET || (support_ipv6 && p->ifa_addr->sa_family == AF_INET6)) { Interface iface; iface.set_name(p->ifa_name); - if (p->ifa_addr != NULL) { + if (p->ifa_addr != nullptr) { iface.set_ip(NetAddress(Socket_Address(*p->ifa_addr))); } - if (p->ifa_netmask != NULL) { + if (p->ifa_netmask != nullptr) { iface.set_netmask(NetAddress(Socket_Address(*p->ifa_netmask))); } - if ((p->ifa_flags & IFF_BROADCAST) && p->ifa_broadaddr != NULL) { + if ((p->ifa_flags & IFF_BROADCAST) && p->ifa_broadaddr != nullptr) { iface.set_broadcast(NetAddress(Socket_Address(*p->ifa_broadaddr))); - } else if ((p->ifa_flags & IFF_POINTOPOINT) && p->ifa_dstaddr != NULL) { + } else if ((p->ifa_flags & IFF_POINTOPOINT) && p->ifa_dstaddr != nullptr) { iface.set_p2p(NetAddress(Socket_Address(*p->ifa_dstaddr))); } _interfaces.push_back(iface); @@ -716,12 +719,12 @@ remove_writer(ConnectionWriter *writer) { */ string ConnectionManager:: format_mac_address(const unsigned char *data, size_t data_size) { - stringstream strm; + std::stringstream strm; for (size_t di = 0; di < data_size; ++di) { if (di != 0) { strm << "-"; } - strm << hex << setw(2) << setfill('0') << (unsigned int)data[di]; + strm << std::hex << std::setw(2) << std::setfill('0') << (unsigned int)data[di]; } return strm.str(); @@ -731,7 +734,7 @@ format_mac_address(const unsigned char *data, size_t data_size) { * */ void ConnectionManager::Interface:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_name() << " ["; if (has_ip()) { out << " " << get_ip().get_ip_string(); diff --git a/panda/src/net/connectionManager.h b/panda/src/net/connectionManager.h index 1b00268d6c..a3a6f862c1 100644 --- a/panda/src/net/connectionManager.h +++ b/panda/src/net/connectionManager.h @@ -44,27 +44,27 @@ PUBLISHED: virtual ~ConnectionManager(); PT(Connection) open_UDP_connection(uint16_t port = 0); - PT(Connection) open_UDP_connection(const string &hostname, uint16_t port, bool for_broadcast = false); + PT(Connection) open_UDP_connection(const std::string &hostname, uint16_t port, bool for_broadcast = false); BLOCKING PT(Connection) open_TCP_server_rendezvous(uint16_t port, int backlog); - BLOCKING PT(Connection) open_TCP_server_rendezvous(const string &hostname, + BLOCKING PT(Connection) open_TCP_server_rendezvous(const std::string &hostname, uint16_t port, int backlog); BLOCKING PT(Connection) open_TCP_server_rendezvous(const NetAddress &address, int backlog); BLOCKING PT(Connection) open_TCP_client_connection(const NetAddress &address, int timeout_ms); - BLOCKING PT(Connection) open_TCP_client_connection(const string &hostname, + BLOCKING PT(Connection) open_TCP_client_connection(const std::string &hostname, uint16_t port, int timeout_ms); bool close_connection(const PT(Connection) &connection); BLOCKING bool wait_for_readers(double timeout); - static string get_host_name(); + static std::string get_host_name(); class EXPCL_PANDA_NET Interface { PUBLISHED: - const string &get_name() const { return _name; } - const string &get_mac_address() const { return _mac_address; } + const std::string &get_name() const { return _name; } + const std::string &get_mac_address() const { return _mac_address; } bool has_ip() const { return (_flags & F_has_ip) != 0; } const NetAddress &get_ip() const { return _ip; } bool has_netmask() const { return (_flags & F_has_netmask) != 0; } @@ -74,20 +74,20 @@ PUBLISHED: bool has_p2p() const { return (_flags & F_has_p2p) != 0; } const NetAddress &get_p2p() const { return _p2p; } - void output(ostream &out) const; + void output(std::ostream &out) const; public: Interface() { _flags = 0; } - void set_name(const string &name) { _name = name; } - void set_mac_address(const string &mac_address) { _mac_address = mac_address; } + void set_name(const std::string &name) { _name = name; } + void set_mac_address(const std::string &mac_address) { _mac_address = mac_address; } void set_ip(const NetAddress &ip) { _ip = ip; _flags |= F_has_ip; } void set_netmask(const NetAddress &ip) { _netmask = ip; _flags |= F_has_netmask; } void set_broadcast(const NetAddress &ip) { _broadcast = ip; _flags |= F_has_broadcast; } void set_p2p(const NetAddress &ip) { _p2p = ip; _flags |= F_has_p2p; } private: - string _name; - string _mac_address; + std::string _name; + std::string _mac_address; NetAddress _ip; NetAddress _netmask; @@ -122,7 +122,7 @@ protected: void add_writer(ConnectionWriter *writer); void remove_writer(ConnectionWriter *writer); - string format_mac_address(const unsigned char *data, size_t data_size); + std::string format_mac_address(const unsigned char *data, size_t data_size); typedef phash_set< PT(Connection) > Connections; typedef phash_set Readers; @@ -143,7 +143,7 @@ private: friend class Connection; }; -INLINE ostream &operator << (ostream &out, const ConnectionManager::Interface &iface) { +INLINE std::ostream &operator << (std::ostream &out, const ConnectionManager::Interface &iface) { iface.output(out); return out; } diff --git a/panda/src/net/connectionReader.cxx b/panda/src/net/connectionReader.cxx index 0ca114e476..9fbab3e1dc 100644 --- a/panda/src/net/connectionReader.cxx +++ b/panda/src/net/connectionReader.cxx @@ -27,6 +27,8 @@ #include "atomicAdjust.h" #include "config_downloader.h" +using std::min; + static const int read_buffer_size = maximum_udp_datagram + datagram_udp_header_size; /** @@ -60,7 +62,7 @@ get_socket() const { * */ ConnectionReader::ReaderThread:: -ReaderThread(ConnectionReader *reader, const string &thread_name, +ReaderThread(ConnectionReader *reader, const std::string &thread_name, int thread_index) : Thread(make_thread_name(thread_name, thread_index), make_thread_name(thread_name, thread_index)), @@ -85,7 +87,7 @@ thread_main() { */ ConnectionReader:: ConnectionReader(ConnectionManager *manager, int num_threads, - const string &thread_name) : + const std::string &thread_name) : _manager(manager) { if (!Thread::is_threading_supported()) { @@ -111,7 +113,7 @@ ConnectionReader(ConnectionManager *manager, int num_threads, _currently_polling_thread = -1; - string reader_thread_name = thread_name; + std::string reader_thread_name = thread_name; if (thread_name.empty()) { reader_thread_name = "ReaderThread"; } @@ -132,7 +134,7 @@ ConnectionReader(ConnectionManager *manager, int num_threads, */ ConnectionReader:: ~ConnectionReader() { - if (_manager != (ConnectionManager *)NULL) { + if (_manager != nullptr) { _manager->remove_reader(this); } @@ -172,7 +174,7 @@ ConnectionReader:: */ bool ConnectionReader:: add_connection(Connection *connection) { - nassertr(connection != (Connection *)NULL, false); + nassertr(connection != nullptr, false); LightMutexHolder holder(_sockets_mutex); @@ -261,11 +263,11 @@ poll() { } SocketInfo *sinfo = get_next_available_socket(false, -2); - if (sinfo != (SocketInfo *)NULL) { + if (sinfo != nullptr) { double max_poll_cycle = get_net_max_poll_cycle(); if (max_poll_cycle < 0.0) { // Continue to read all data. - while (sinfo != (SocketInfo *)NULL) { + while (sinfo != nullptr) { process_incoming_data(sinfo); sinfo = get_next_available_socket(false, -2); } @@ -275,7 +277,7 @@ poll() { TrueClock *global_clock = TrueClock::get_global_ptr(); double stop = global_clock->get_short_time() + max_poll_cycle; - while (sinfo != (SocketInfo *)NULL) { + while (sinfo != nullptr) { process_incoming_data(sinfo); if (global_clock->get_short_time() >= stop) { return; @@ -406,7 +408,7 @@ flush_read_connection(Connection *connection) { */ void ConnectionReader:: clear_manager() { - _manager = (ConnectionManager *)NULL; + _manager = nullptr; } /** @@ -465,7 +467,7 @@ process_incoming_udp_data(SocketInfo *sinfo) { } else if (bytes_read == 0) { // The socket was closed (!). This shouldn't happen with a UDP // connection. Oh well. Report that and return. - if (_manager != (ConnectionManager *)NULL) { + if (_manager != nullptr) { _manager->connection_reset(sinfo->_connection, 0); } finish_socket(sinfo); @@ -547,7 +549,7 @@ process_incoming_tcp_data(SocketInfo *sinfo) { if (bytes_read <= 0) { // The socket was closed. Report that and return. - if (_manager != (ConnectionManager *)NULL) { + if (_manager != nullptr) { _manager->connection_reset(sinfo->_connection, 0); } finish_socket(sinfo); @@ -601,7 +603,7 @@ process_incoming_tcp_data(SocketInfo *sinfo) { if (bytes_read <= 0) { // The socket was closed. Report that and return. - if (_manager != (ConnectionManager *)NULL) { + if (_manager != nullptr) { _manager->connection_reset(sinfo->_connection, 0); } finish_socket(sinfo); @@ -674,7 +676,7 @@ process_raw_incoming_udp_data(SocketInfo *sinfo) { } else if (bytes_read == 0) { // The socket was closed (!). This shouldn't happen with a UDP // connection. Oh well. Report that and return. - if (_manager != (ConnectionManager *)NULL) { + if (_manager != nullptr) { _manager->connection_reset(sinfo->_connection, 0); } finish_socket(sinfo); @@ -728,7 +730,7 @@ process_raw_incoming_tcp_data(SocketInfo *sinfo) { if (bytes_read <= 0) { // The socket was closed. Report that and return. - if (_manager != (ConnectionManager *)NULL) { + if (_manager != nullptr) { _manager->connection_reset(sinfo->_connection, 0); } finish_socket(sinfo); @@ -772,7 +774,7 @@ thread_run(int thread_index) { while (!_shutdown) { SocketInfo *sinfo = get_next_available_socket(true, thread_index); - if (sinfo != (SocketInfo *)NULL) { + if (sinfo != nullptr) { process_incoming_data(sinfo); Thread::consider_yield(); } else { @@ -801,7 +803,7 @@ get_next_available_socket(bool allow_block, int current_thread_index) { // First, check the result from the previous select call. If there are // any sockets remaining there, process them first. while (!_shutdown && _num_results > 0) { - nassertr(_next_index < (int)_selecting_sockets.size(), NULL); + nassertr(_next_index < (int)_selecting_sockets.size(), nullptr); int i = _next_index; _next_index++; @@ -858,7 +860,7 @@ get_next_available_socket(bool allow_block, int current_thread_index) { } else if (_num_results < 0) { // If we had an error, just return. But yield the timeslice first. Thread::force_yield(); - return (SocketInfo *)NULL; + return nullptr; } } while (!_shutdown && interrupted); @@ -868,7 +870,7 @@ get_next_available_socket(bool allow_block, int current_thread_index) { // (b) return from PR_Poll() with no sockets available. } while (!_shutdown && _num_results > 0); - return (SocketInfo *)NULL; + return nullptr; } diff --git a/panda/src/net/connectionReader.h b/panda/src/net/connectionReader.h index fb9542df4a..a1a8bdf33a 100644 --- a/panda/src/net/connectionReader.h +++ b/panda/src/net/connectionReader.h @@ -61,7 +61,7 @@ PUBLISHED: // new call to PR_Poll(). explicit ConnectionReader(ConnectionManager *manager, int num_threads, - const string &thread_name = string()); + const std::string &thread_name = std::string()); virtual ~ConnectionReader(); bool add_connection(Connection *connection); @@ -135,7 +135,7 @@ private: class ReaderThread : public Thread { public: - ReaderThread(ConnectionReader *reader, const string &thread_name, + ReaderThread(ConnectionReader *reader, const std::string &thread_name, int thread_index); virtual void thread_main(); diff --git a/panda/src/net/connectionWriter.cxx b/panda/src/net/connectionWriter.cxx index a07b52fa63..47cde6c35d 100644 --- a/panda/src/net/connectionWriter.cxx +++ b/panda/src/net/connectionWriter.cxx @@ -24,7 +24,7 @@ * */ ConnectionWriter::WriterThread:: -WriterThread(ConnectionWriter *writer, const string &thread_name, +WriterThread(ConnectionWriter *writer, const std::string &thread_name, int thread_index) : Thread(make_thread_name(thread_name, thread_index), make_thread_name(thread_name, thread_index)), @@ -50,7 +50,7 @@ thread_main() { */ ConnectionWriter:: ConnectionWriter(ConnectionManager *manager, int num_threads, - const string &thread_name) : + const std::string &thread_name) : _manager(manager) { if (!Thread::is_threading_supported()) { @@ -70,7 +70,7 @@ ConnectionWriter(ConnectionManager *manager, int num_threads, _immediate = (num_threads <= 0); _shutdown = false; - string writer_thread_name = thread_name; + std::string writer_thread_name = thread_name; if (thread_name.empty()) { writer_thread_name = "WriterThread"; } @@ -91,7 +91,7 @@ ConnectionWriter(ConnectionManager *manager, int num_threads, */ ConnectionWriter:: ~ConnectionWriter() { - if (_manager != (ConnectionManager *)NULL) { + if (_manager != nullptr) { _manager->remove_writer(this); } @@ -142,7 +142,7 @@ get_current_queue_size() const { bool ConnectionWriter:: send(const Datagram &datagram, const PT(Connection) &connection, bool block) { nassertr(!_shutdown, false); - nassertr(connection != (Connection *)NULL, false); + nassertr(connection != nullptr, false); nassertr(connection->get_socket()->is_exact_type(Socket_TCP::get_class_type()), false); NetDatagram copy(datagram); @@ -177,7 +177,7 @@ bool ConnectionWriter:: send(const Datagram &datagram, const PT(Connection) &connection, const NetAddress &address, bool block) { nassertr(!_shutdown, false); - nassertr(connection != (Connection *)NULL, false); + nassertr(connection != nullptr, false); nassertr(connection->get_socket()->is_exact_type(Socket_UDP::get_class_type()), false); if ((int)datagram.get_length() > maximum_udp_datagram) { @@ -309,7 +309,7 @@ shutdown() { */ void ConnectionWriter:: clear_manager() { - _manager = (ConnectionManager *)NULL; + _manager = nullptr; shutdown(); } diff --git a/panda/src/net/connectionWriter.h b/panda/src/net/connectionWriter.h index 58a0300ef6..578cc260f8 100644 --- a/panda/src/net/connectionWriter.h +++ b/panda/src/net/connectionWriter.h @@ -35,7 +35,7 @@ class NetAddress; class EXPCL_PANDA_NET ConnectionWriter { PUBLISHED: explicit ConnectionWriter(ConnectionManager *manager, int num_threads, - const string &thread_name = string()); + const std::string &thread_name = std::string()); ~ConnectionWriter(); void set_max_queue_size(int max_size); @@ -83,7 +83,7 @@ private: class WriterThread : public Thread { public: - WriterThread(ConnectionWriter *writer, const string &thread_name, + WriterThread(ConnectionWriter *writer, const std::string &thread_name, int thread_index); virtual void thread_main(); diff --git a/panda/src/net/datagramSinkNet.cxx b/panda/src/net/datagramSinkNet.cxx index d09bc465ac..89e0d7c294 100644 --- a/panda/src/net/datagramSinkNet.cxx +++ b/panda/src/net/datagramSinkNet.cxx @@ -32,7 +32,7 @@ DatagramSinkNet(ConnectionManager *manager, int num_threads) : */ bool DatagramSinkNet:: put_datagram(const Datagram &data) { - if (_target == (Connection *)NULL) { + if (_target == nullptr) { return false; } return send(data, _target, true); @@ -44,7 +44,7 @@ put_datagram(const Datagram &data) { */ bool DatagramSinkNet:: is_error() { - return (_target == (Connection *)NULL || _target->get_socket() == (Socket_IP *)NULL); + return (_target == nullptr || _target->get_socket() == nullptr); } /** @@ -53,7 +53,7 @@ is_error() { */ void DatagramSinkNet:: flush() { - if (_target != (Connection *)NULL) { + if (_target != nullptr) { _target->flush(); } } diff --git a/panda/src/net/datagramTCPHeader.I b/panda/src/net/datagramTCPHeader.I index 1aa2cf99c8..8f7d263cff 100644 --- a/panda/src/net/datagramTCPHeader.I +++ b/panda/src/net/datagramTCPHeader.I @@ -15,7 +15,7 @@ * Returns a pointer to a block of data of length datagram_tcp_header_size, * which can be written to the network as the header information. */ -INLINE string DatagramTCPHeader:: +INLINE std::string DatagramTCPHeader:: get_header() const { return _header.get_message(); } diff --git a/panda/src/net/datagramTCPHeader.cxx b/panda/src/net/datagramTCPHeader.cxx index bd013f0c33..44db216b3d 100644 --- a/panda/src/net/datagramTCPHeader.cxx +++ b/panda/src/net/datagramTCPHeader.cxx @@ -107,7 +107,7 @@ verify_datagram(const NetDatagram &datagram, int header_size) const { // We write the hex dump into a ostringstream first, to guarantee an // atomic write to the output stream in case we're threaded. - ostringstream hex; + std::ostringstream hex; datagram.dump_hex(hex); hex << "\n"; net_cat.debug() << hex.str(); diff --git a/panda/src/net/datagramTCPHeader.h b/panda/src/net/datagramTCPHeader.h index 51f489e3ed..3e0485ac81 100644 --- a/panda/src/net/datagramTCPHeader.h +++ b/panda/src/net/datagramTCPHeader.h @@ -38,7 +38,7 @@ public: DatagramTCPHeader(const void *data, int header_size); int get_datagram_size(int header_size) const; - INLINE string get_header() const; + INLINE std::string get_header() const; bool verify_datagram(const NetDatagram &datagram, int header_size) const; diff --git a/panda/src/net/datagramUDPHeader.I b/panda/src/net/datagramUDPHeader.I index 85ada55054..ff60db084a 100644 --- a/panda/src/net/datagramUDPHeader.I +++ b/panda/src/net/datagramUDPHeader.I @@ -24,7 +24,7 @@ get_datagram_checksum() const { * Returns a pointer to a block of data of length datagram_udp_header_size, * which can be written to the network as the header information. */ -INLINE string DatagramUDPHeader:: +INLINE std::string DatagramUDPHeader:: get_header() const { return _header.get_message(); } diff --git a/panda/src/net/datagramUDPHeader.cxx b/panda/src/net/datagramUDPHeader.cxx index 2191c0241a..7c58205e8d 100644 --- a/panda/src/net/datagramUDPHeader.cxx +++ b/panda/src/net/datagramUDPHeader.cxx @@ -73,7 +73,7 @@ verify_datagram(const NetDatagram &datagram) const { // We write the hex dump into a ostringstream first, to guarantee an // atomic write to the output stream in case we're threaded. - ostringstream hex; + std::ostringstream hex; datagram.dump_hex(hex); hex << "\n"; net_cat.debug(false) << hex.str(); diff --git a/panda/src/net/datagramUDPHeader.h b/panda/src/net/datagramUDPHeader.h index e8ee0b8b1a..12d690fd53 100644 --- a/panda/src/net/datagramUDPHeader.h +++ b/panda/src/net/datagramUDPHeader.h @@ -37,7 +37,7 @@ public: DatagramUDPHeader(const void *data); INLINE int get_datagram_checksum() const; - INLINE string get_header() const; + INLINE std::string get_header() const; bool verify_datagram(const NetDatagram &datagram) const; diff --git a/panda/src/net/datagram_ui.cxx b/panda/src/net/datagram_ui.cxx index fb5fc1a958..d5f0bdea1b 100644 --- a/panda/src/net/datagram_ui.cxx +++ b/panda/src/net/datagram_ui.cxx @@ -19,6 +19,9 @@ #include #include +using std::istream; +using std::ostream; + enum DatagramElement { DE_int32, DE_float64, @@ -31,8 +34,8 @@ operator >> (istream &in, NetDatagram &datagram) { datagram.clear(); // First, read a line of text. - string line; - getline(in, line); + std::string line; + std::getline(in, line); // Now parse the text. size_t p = 0; @@ -74,7 +77,7 @@ operator >> (istream &in, NetDatagram &datagram) { while (p < line.length() && line[p] != '"') { p++; } - string str = line.substr(start, p - start); + std::string str = line.substr(start, p - start); datagram.add_int8(DE_string); datagram.add_string(str); p++; @@ -85,7 +88,7 @@ operator >> (istream &in, NetDatagram &datagram) { while (p < line.length() && !isspace(line[p])) { p++; } - string str = line.substr(start, p - start); + std::string str = line.substr(start, p - start); datagram.add_int8(DE_string); datagram.add_string(str); } diff --git a/panda/src/net/datagram_ui.h b/panda/src/net/datagram_ui.h index 6f0e6c4cba..3e705d3698 100644 --- a/panda/src/net/datagram_ui.h +++ b/panda/src/net/datagram_ui.h @@ -26,7 +26,7 @@ #include "netDatagram.h" -istream &operator >> (istream &in, NetDatagram &datagram); -ostream &operator << (ostream &out, const NetDatagram &datagram); +std::istream &operator >> (std::istream &in, NetDatagram &datagram); +std::ostream &operator << (std::ostream &out, const NetDatagram &datagram); #endif diff --git a/panda/src/net/fake_http_server.cxx b/panda/src/net/fake_http_server.cxx index 718b6db824..bc29e9806a 100644 --- a/panda/src/net/fake_http_server.cxx +++ b/panda/src/net/fake_http_server.cxx @@ -24,6 +24,8 @@ #include +using std::string; + QueuedConnectionManager cm; QueuedConnectionReader reader(&cm, 10); ConnectionWriter writer(&cm, 10); @@ -65,7 +67,7 @@ receive_data(const Datagram &data) { void ClientState:: receive_line(string line) { - cerr << "received: " << line << "\n"; + std::cerr << "received: " << line << "\n"; // trim trailing whitespace. size_t size = line.size(); while (size > 0 && isspace(line[size - 1])) { diff --git a/panda/src/net/netAddress.cxx b/panda/src/net/netAddress.cxx index 0f0404dc45..9d49623252 100644 --- a/panda/src/net/netAddress.cxx +++ b/panda/src/net/netAddress.cxx @@ -63,7 +63,7 @@ set_broadcast(int port) { * Returns true if the hostname is known, false otherwise. */ bool NetAddress:: -set_host(const string &hostname, int port) { +set_host(const std::string &hostname, int port) { return _addr.set_host(hostname, port); } @@ -102,7 +102,7 @@ is_any() const { /** * Returns the IP address to which this address refers, formatted as a string. */ -string NetAddress:: +std::string NetAddress:: get_ip_string() const { return _addr.get_ip(); } @@ -143,7 +143,7 @@ get_addr() const { * */ void NetAddress:: -output(ostream &out) const { +output(std::ostream &out) const { out << _addr.get_ip_port(); } diff --git a/panda/src/net/netAddress.h b/panda/src/net/netAddress.h index d6b15b307e..dcb5e41fb3 100644 --- a/panda/src/net/netAddress.h +++ b/panda/src/net/netAddress.h @@ -30,20 +30,20 @@ PUBLISHED: bool set_any(int port); bool set_localhost(int port); bool set_broadcast(int port); - bool set_host(const string &hostname, int port); + bool set_host(const std::string &hostname, int port); void clear(); int get_port() const; void set_port(int port); - string get_ip_string() const; + std::string get_ip_string() const; bool is_any() const; uint32_t get_ip() const; uint8_t get_ip_component(int n) const; const Socket_Address &get_addr() const; - void output(ostream &out) const; + void output(std::ostream &out) const; size_t get_hash() const; bool operator == (const NetAddress &other) const; @@ -53,7 +53,7 @@ private: Socket_Address _addr; }; -INLINE ostream &operator << (ostream &out, const NetAddress &addr) { +INLINE std::ostream &operator << (std::ostream &out, const NetAddress &addr) { addr.output(out); return out; } diff --git a/panda/src/net/queuedConnectionReader.cxx b/panda/src/net/queuedConnectionReader.cxx index bdc562bd22..807b69337c 100644 --- a/panda/src/net/queuedConnectionReader.cxx +++ b/panda/src/net/queuedConnectionReader.cxx @@ -123,7 +123,7 @@ void QueuedConnectionReader:: start_delay(double min_delay, double max_delay) { LightMutexHolder holder(_dd_mutex); _min_delay = min_delay; - _delay_variance = max(max_delay - min_delay, 0.0); + _delay_variance = std::max(max_delay - min_delay, 0.0); _delay_active = true; } diff --git a/panda/src/net/test_datagram.cxx b/panda/src/net/test_datagram.cxx index db2f3fd305..93da4b6c87 100644 --- a/panda/src/net/test_datagram.cxx +++ b/panda/src/net/test_datagram.cxx @@ -14,6 +14,9 @@ #include "netDatagram.h" #include "datagramIterator.h" +using std::cout; +using std::endl; + int main() { NetDatagram dg; diff --git a/panda/src/net/test_raw_server.cxx b/panda/src/net/test_raw_server.cxx index 7811fdd446..444d65756c 100644 --- a/panda/src/net/test_raw_server.cxx +++ b/panda/src/net/test_raw_server.cxx @@ -82,9 +82,9 @@ main(int argc, char *argv[]) { while (reader.data_available()) { NetDatagram datagram; if (reader.get_data(datagram)) { - string data = datagram.get_message(); + std::string data = datagram.get_message(); nout.write(data.data(), data.length()); - nout << flush; + nout << std::flush; Clients::iterator ci; for (ci = clients.begin(); ci != clients.end(); ++ci) { diff --git a/panda/src/net/test_spam_client.cxx b/panda/src/net/test_spam_client.cxx index e76643e5c2..5488cec357 100644 --- a/panda/src/net/test_spam_client.cxx +++ b/panda/src/net/test_spam_client.cxx @@ -28,7 +28,7 @@ main(int argc, char *argv[]) { exit(1); } - string hostname = argv[1]; + std::string hostname = argv[1]; int port = atoi(argv[2]); NetAddress host; @@ -54,8 +54,8 @@ main(int argc, char *argv[]) { bool lost_connection = false; NetDatagram datagram; - cout << "Enter a datagram.\n"; - cin >> datagram; + std::cout << "Enter a datagram.\n"; + std::cin >> datagram; nout << "Read datagram " << datagram << "\n"; datagram.dump_hex(nout); diff --git a/panda/src/net/test_tcp_client.cxx b/panda/src/net/test_tcp_client.cxx index 4c5b15fa17..c88821149c 100644 --- a/panda/src/net/test_tcp_client.cxx +++ b/panda/src/net/test_tcp_client.cxx @@ -20,6 +20,9 @@ #include "datagram_ui.h" +using std::cin; +using std::cout; + int main(int argc, char *argv[]) { if (argc != 3) { @@ -27,7 +30,7 @@ main(int argc, char *argv[]) { exit(1); } - string hostname = argv[1]; + std::string hostname = argv[1]; int port = atoi(argv[2]); NetAddress host; diff --git a/panda/src/net/test_udp.cxx b/panda/src/net/test_udp.cxx index f069523f48..4aec3ecc76 100644 --- a/panda/src/net/test_udp.cxx +++ b/panda/src/net/test_udp.cxx @@ -20,6 +20,9 @@ #include "datagram_ui.h" +using std::cin; +using std::cout; + int main(int argc, char *argv[]) { if (argc != 3) { @@ -27,7 +30,7 @@ main(int argc, char *argv[]) { exit(1); } - string hostname = argv[1]; + std::string hostname = argv[1]; int port = atoi(argv[2]); NetAddress host; diff --git a/panda/src/ode/odeAMotorJoint.cxx b/panda/src/ode/odeAMotorJoint.cxx index 8b7a16d6bc..8923453068 100644 --- a/panda/src/ode/odeAMotorJoint.cxx +++ b/panda/src/ode/odeAMotorJoint.cxx @@ -23,7 +23,7 @@ OdeAMotorJoint(dJointID id) : OdeAMotorJoint:: OdeAMotorJoint(OdeWorld &world) : - OdeJoint(dJointCreateAMotor(world.get_id(), 0)) { + OdeJoint(dJointCreateAMotor(world.get_id(), nullptr)) { } OdeAMotorJoint:: diff --git a/panda/src/ode/odeBallJoint.cxx b/panda/src/ode/odeBallJoint.cxx index b578c72c6b..f051c07c9a 100644 --- a/panda/src/ode/odeBallJoint.cxx +++ b/panda/src/ode/odeBallJoint.cxx @@ -23,7 +23,7 @@ OdeBallJoint(dJointID id) : OdeBallJoint:: OdeBallJoint(OdeWorld &world) : - OdeJoint(dJointCreateBall(world.get_id(), 0)) { + OdeJoint(dJointCreateBall(world.get_id(), nullptr)) { } OdeBallJoint:: diff --git a/panda/src/ode/odeBody.cxx b/panda/src/ode/odeBody.cxx index 4f70faff08..70ad46169d 100644 --- a/panda/src/ode/odeBody.cxx +++ b/panda/src/ode/odeBody.cxx @@ -63,13 +63,13 @@ get_data() const { OdeJoint OdeBody:: get_joint(int index) const { - nassertr(_id != 0, OdeJoint(0)); - nassertr(index < get_num_joints(), OdeJoint(0)); + nassertr(_id != nullptr, OdeJoint(nullptr)); + nassertr(index < get_num_joints(), OdeJoint(nullptr)); return OdeJoint(dBodyGetJoint(_id, index)); } void OdeBody:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, unsigned int indent) const { out.width(indent); out << "" << get_type() \ << "(id = " << _id \ << ")"; @@ -77,5 +77,5 @@ write(ostream &out, unsigned int indent) const { OdeBody:: operator bool () const { - return (_id != NULL); + return (_id != nullptr); } diff --git a/panda/src/ode/odeBody.h b/panda/src/ode/odeBody.h index dd68389abd..8e27dd8802 100644 --- a/panda/src/ode/odeBody.h +++ b/panda/src/ode/odeBody.h @@ -143,7 +143,7 @@ PUBLISHED: INLINE void set_gravity_mode(int mode); INLINE int get_gravity_mode() const; - virtual void write(ostream &out = cout, unsigned int indent=0) const; + virtual void write(std::ostream &out = std::cout, unsigned int indent=0) const; operator bool () const; INLINE int compare_to(const OdeBody &other) const; diff --git a/panda/src/ode/odeBoxGeom.cxx b/panda/src/ode/odeBoxGeom.cxx index 77a594b552..2636da81da 100644 --- a/panda/src/ode/odeBoxGeom.cxx +++ b/panda/src/ode/odeBoxGeom.cxx @@ -23,7 +23,7 @@ OdeBoxGeom(dGeomID id) : OdeBoxGeom:: OdeBoxGeom(dReal lx, dReal ly, dReal lz) : - OdeGeom(dCreateBox(0, lx, ly, lz)) { + OdeGeom(dCreateBox(nullptr, lx, ly, lz)) { } OdeBoxGeom:: diff --git a/panda/src/ode/odeCappedCylinderGeom.cxx b/panda/src/ode/odeCappedCylinderGeom.cxx index 5b1a3b5b40..7fa7120f69 100644 --- a/panda/src/ode/odeCappedCylinderGeom.cxx +++ b/panda/src/ode/odeCappedCylinderGeom.cxx @@ -23,7 +23,7 @@ OdeCappedCylinderGeom(dGeomID id) : OdeCappedCylinderGeom:: OdeCappedCylinderGeom(dReal radius, dReal length) : - OdeGeom(dCreateCapsule(0, radius, length)) { + OdeGeom(dCreateCapsule(nullptr, radius, length)) { } OdeCappedCylinderGeom:: diff --git a/panda/src/ode/odeContactJoint.cxx b/panda/src/ode/odeContactJoint.cxx index b53694b1b3..10bf0b94ec 100644 --- a/panda/src/ode/odeContactJoint.cxx +++ b/panda/src/ode/odeContactJoint.cxx @@ -23,7 +23,7 @@ OdeContactJoint(dJointID id) : OdeContactJoint:: OdeContactJoint(OdeWorld &world, const OdeContact &contact) : - OdeJoint(dJointCreateContact(world.get_id(), 0, contact.get_contact_ptr())) { + OdeJoint(dJointCreateContact(world.get_id(), nullptr, contact.get_contact_ptr())) { } OdeContactJoint:: diff --git a/panda/src/ode/odeConvexGeom.cxx b/panda/src/ode/odeConvexGeom.cxx index 3160d343de..9a3b07d29a 100644 --- a/panda/src/ode/odeConvexGeom.cxx +++ b/panda/src/ode/odeConvexGeom.cxx @@ -23,7 +23,7 @@ OdeConvexGeom(dGeomID id) : OdeConvexGeom:: OdeConvexGeom(dReal radius, dReal length) : - OdeGeom(dCreateConvex(0, radius, length)) { + OdeGeom(dCreateConvex(nullptr, radius, length)) { } OdeConvexGeom:: diff --git a/panda/src/ode/odeCylinderGeom.cxx b/panda/src/ode/odeCylinderGeom.cxx index 7b7eccc49e..4076e3aa36 100644 --- a/panda/src/ode/odeCylinderGeom.cxx +++ b/panda/src/ode/odeCylinderGeom.cxx @@ -23,7 +23,7 @@ OdeCylinderGeom(dGeomID id) : OdeCylinderGeom:: OdeCylinderGeom(dReal radius, dReal length) : - OdeGeom(dCreateCylinder(0, radius, length)) { + OdeGeom(dCreateCylinder(nullptr, radius, length)) { } OdeCylinderGeom:: diff --git a/panda/src/ode/odeFixedJoint.cxx b/panda/src/ode/odeFixedJoint.cxx index 346a1dbdaa..a339776d60 100644 --- a/panda/src/ode/odeFixedJoint.cxx +++ b/panda/src/ode/odeFixedJoint.cxx @@ -23,7 +23,7 @@ OdeFixedJoint(dJointID id) : OdeFixedJoint:: OdeFixedJoint(OdeWorld &world) : - OdeJoint(dJointCreateFixed(world.get_id(), 0)) { + OdeJoint(dJointCreateFixed(world.get_id(), nullptr)) { } OdeFixedJoint:: diff --git a/panda/src/ode/odeGeom.I b/panda/src/ode/odeGeom.I index 883e367e70..e402b470e9 100644 --- a/panda/src/ode/odeGeom.I +++ b/panda/src/ode/odeGeom.I @@ -31,7 +31,7 @@ get_id() const { INLINE bool OdeGeom:: has_body() const { - return (dGeomGetBody(_id) != NULL); + return (dGeomGetBody(_id) != nullptr); } INLINE OdeBody OdeGeom:: diff --git a/panda/src/ode/odeGeom.cxx b/panda/src/ode/odeGeom.cxx index c1d4d0866f..e25c6c45b6 100644 --- a/panda/src/ode/odeGeom.cxx +++ b/panda/src/ode/odeGeom.cxx @@ -107,100 +107,100 @@ get_space() const { void OdeGeom:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, unsigned int indent) const { out.width(indent); out << get_type() << "(id = " << _id << ")"; } OdeBoxGeom OdeGeom:: convert_to_box() const { - nassertr(_id != 0, OdeBoxGeom((dGeomID)0)); - nassertr(get_class() == GC_box, OdeBoxGeom((dGeomID)0)); + nassertr(_id != nullptr, OdeBoxGeom(nullptr)); + nassertr(get_class() == GC_box, OdeBoxGeom(nullptr)); return OdeBoxGeom(_id); } OdeCappedCylinderGeom OdeGeom:: convert_to_capped_cylinder() const { - nassertr(_id != 0, OdeCappedCylinderGeom((dGeomID)0)); - nassertr(get_class() == GC_capped_cylinder, OdeCappedCylinderGeom((dGeomID)0)); + nassertr(_id != nullptr, OdeCappedCylinderGeom(nullptr)); + nassertr(get_class() == GC_capped_cylinder, OdeCappedCylinderGeom(nullptr)); return OdeCappedCylinderGeom(_id); } /* OdeConvexGeom OdeGeom:: convert_to_convex() const { - nassertr(_id != 0, OdeConvexGeom((dGeomID)0)); - nassertr(get_class() == GC_convex, OdeConvexGeom((dGeomID)0)); + nassertr(_id != nullptr, OdeConvexGeom(nullptr)); + nassertr(get_class() == GC_convex, OdeConvexGeom(nullptr)); return OdeConvexGeom(_id); } */ OdeCylinderGeom OdeGeom:: convert_to_cylinder() const { - nassertr(_id != 0, OdeCylinderGeom((dGeomID)0)); - nassertr(get_class() == GC_cylinder, OdeCylinderGeom((dGeomID)0)); + nassertr(_id != nullptr, OdeCylinderGeom(nullptr)); + nassertr(get_class() == GC_cylinder, OdeCylinderGeom(nullptr)); return OdeCylinderGeom(_id); } /* OdeHeightfieldGeom OdeGeom:: convert_to_heightfield() const { - nassertr(_id != 0, OdeHeightfieldGeom((dGeomID)0)); - nassertr(get_class() == GC_heightfield, OdeHeightfieldGeom((dGeomID)0)); + nassertr(_id != nullptr, OdeHeightfieldGeom(nullptr)); + nassertr(get_class() == GC_heightfield, OdeHeightfieldGeom(nullptr)); return OdeHeightfieldGeom(_id); } */ OdePlaneGeom OdeGeom:: convert_to_plane() const { - nassertr(_id != 0, OdePlaneGeom((dGeomID)0)); - nassertr(get_class() == GC_plane, OdePlaneGeom((dGeomID)0)); + nassertr(_id != nullptr, OdePlaneGeom(nullptr)); + nassertr(get_class() == GC_plane, OdePlaneGeom(nullptr)); return OdePlaneGeom(_id); } OdeRayGeom OdeGeom:: convert_to_ray() const { - nassertr(_id != 0, OdeRayGeom((dGeomID)0)); - nassertr(get_class() == GC_ray, OdeRayGeom((dGeomID)0)); + nassertr(_id != nullptr, OdeRayGeom(nullptr)); + nassertr(get_class() == GC_ray, OdeRayGeom(nullptr)); return OdeRayGeom(_id); } OdeSphereGeom OdeGeom:: convert_to_sphere() const { - nassertr(_id != 0, OdeSphereGeom((dGeomID)0)); - nassertr(get_class() == GC_sphere, OdeSphereGeom((dGeomID)0)); + nassertr(_id != nullptr, OdeSphereGeom(nullptr)); + nassertr(get_class() == GC_sphere, OdeSphereGeom(nullptr)); return OdeSphereGeom(_id); } OdeTriMeshGeom OdeGeom:: convert_to_tri_mesh() const { - nassertr(_id != 0, OdeTriMeshGeom((dGeomID)0)); - nassertr(get_class() == GC_tri_mesh, OdeTriMeshGeom((dGeomID)0)); + nassertr(_id != nullptr, OdeTriMeshGeom(nullptr)); + nassertr(get_class() == GC_tri_mesh, OdeTriMeshGeom(nullptr)); return OdeTriMeshGeom(_id); } OdeSimpleSpace OdeGeom:: convert_to_simple_space() const { - nassertr(_id != 0, OdeSimpleSpace((dSpaceID)0)); - nassertr(get_class() == GC_simple_space, OdeSimpleSpace((dSpaceID)0)); + nassertr(_id != nullptr, OdeSimpleSpace(nullptr)); + nassertr(get_class() == GC_simple_space, OdeSimpleSpace(nullptr)); return OdeSimpleSpace((dSpaceID)_id); } OdeHashSpace OdeGeom:: convert_to_hash_space() const { - nassertr(_id != 0, OdeHashSpace((dSpaceID)0)); - nassertr(get_class() == GC_hash_space, OdeHashSpace((dSpaceID)0)); + nassertr(_id != nullptr, OdeHashSpace(nullptr)); + nassertr(get_class() == GC_hash_space, OdeHashSpace(nullptr)); return OdeHashSpace((dSpaceID)_id); } OdeQuadTreeSpace OdeGeom:: convert_to_quad_tree_space() const { - nassertr(_id != 0, OdeQuadTreeSpace((dSpaceID)0)); - nassertr(get_class() == GC_quad_tree_space, OdeQuadTreeSpace((dSpaceID)0)); + nassertr(_id != nullptr, OdeQuadTreeSpace(nullptr)); + nassertr(get_class() == GC_quad_tree_space, OdeQuadTreeSpace(nullptr)); return OdeQuadTreeSpace((dSpaceID)_id); } OdeGeom:: operator bool () const { - return (_id != NULL); + return (_id != nullptr); } diff --git a/panda/src/ode/odeGeom.h b/panda/src/ode/odeGeom.h index 27d62965cb..1d6c69651f 100644 --- a/panda/src/ode/odeGeom.h +++ b/panda/src/ode/odeGeom.h @@ -116,7 +116,7 @@ PUBLISHED: OdeSpace get_space() const; EXTENSION(INLINE PyObject *get_converted_space() const); - virtual void write(ostream &out = cout, unsigned int indent=0) const; + virtual void write(std::ostream &out = std::cout, unsigned int indent=0) const; operator bool () const; INLINE int compare_to(const OdeGeom &other) const; diff --git a/panda/src/ode/odeHashSpace.cxx b/panda/src/ode/odeHashSpace.cxx index af81c100a8..863bb1ae8d 100644 --- a/panda/src/ode/odeHashSpace.cxx +++ b/panda/src/ode/odeHashSpace.cxx @@ -23,7 +23,7 @@ OdeHashSpace(dSpaceID id) : OdeHashSpace:: OdeHashSpace() : - OdeSpace(dHashSpaceCreate(0)) { + OdeSpace(dHashSpaceCreate(nullptr)) { } OdeHashSpace:: diff --git a/panda/src/ode/odeHinge2Joint.cxx b/panda/src/ode/odeHinge2Joint.cxx index 157d642f2f..48b373ef21 100644 --- a/panda/src/ode/odeHinge2Joint.cxx +++ b/panda/src/ode/odeHinge2Joint.cxx @@ -23,7 +23,7 @@ OdeHinge2Joint(dJointID id) : OdeHinge2Joint:: OdeHinge2Joint(OdeWorld &world) : - OdeJoint(dJointCreateHinge2(world.get_id(), 0)) { + OdeJoint(dJointCreateHinge2(world.get_id(), nullptr)) { } OdeHinge2Joint:: diff --git a/panda/src/ode/odeHingeJoint.cxx b/panda/src/ode/odeHingeJoint.cxx index 352cf0ee32..3b2c1b509e 100644 --- a/panda/src/ode/odeHingeJoint.cxx +++ b/panda/src/ode/odeHingeJoint.cxx @@ -23,7 +23,7 @@ OdeHingeJoint(dJointID id) : OdeHingeJoint:: OdeHingeJoint(OdeWorld &world) : - OdeJoint(dJointCreateHinge(world.get_id(), 0)) { + OdeJoint(dJointCreateHinge(world.get_id(), nullptr)) { } OdeHingeJoint:: diff --git a/panda/src/ode/odeJoint.I b/panda/src/ode/odeJoint.I index a71fc8ac84..946dae9456 100644 --- a/panda/src/ode/odeJoint.I +++ b/panda/src/ode/odeJoint.I @@ -49,13 +49,13 @@ get_joint_type() const { INLINE void OdeJoint:: set_feedback(bool flag) { if (flag) { - if (dJointGetFeedback(_id) != NULL) { + if (dJointGetFeedback(_id) != nullptr) { return; } OdeJointFeedback* feedback = new OdeJointFeedback; dJointSetFeedback(_id, (dJointFeedback*) feedback); } else if (dJointFeedback* feedback = dJointGetFeedback(_id)) { - dJointSetFeedback(_id, NULL); + dJointSetFeedback(_id, nullptr); delete feedback; } } diff --git a/panda/src/ode/odeJoint.cxx b/panda/src/ode/odeJoint.cxx index cdaa12e95f..dd10c57f0a 100644 --- a/panda/src/ode/odeJoint.cxx +++ b/panda/src/ode/odeJoint.cxx @@ -30,15 +30,15 @@ TypeHandle OdeJoint::_type_handle; OdeJoint:: OdeJoint() : - _id(0) { - ostream &out = odejoint_cat.debug(); + _id(nullptr) { + std::ostream &out = odejoint_cat.debug(); out << get_type() << "(" << _id << ")\n"; } OdeJoint:: OdeJoint(dJointID id) : _id(id) { - ostream &out = odejoint_cat.debug(); + std::ostream &out = odejoint_cat.debug(); out << get_type() << "(" << _id << ")\n"; } @@ -60,7 +60,7 @@ destroy() { void OdeJoint:: attach_bodies(const OdeBody &body1, const OdeBody &body2) { nassertv(_id); - nassertv(body1.get_id() != 0 || body2.get_id() != 0); + nassertv(body1.get_id() != nullptr || body2.get_id() != nullptr); dJointAttach(_id, body1.get_id(), body2.get_id()); } @@ -72,35 +72,35 @@ attach_bodies(const OdeBody &body1, const OdeBody &body2) { void OdeJoint:: attach_body(const OdeBody &body, int index) { nassertv(_id); - nassertv(body.get_id() != 0); + nassertv(body.get_id() != nullptr); nassertv(index == 0 || index == 1); if (index == 0) { - dJointAttach(_id, body.get_id(), 0); + dJointAttach(_id, body.get_id(), nullptr); } else { - dJointAttach(_id, 0, body.get_id()); + dJointAttach(_id, nullptr, body.get_id()); } } void OdeJoint:: detach() { nassertv(_id); - dJointAttach(_id, 0, 0); + dJointAttach(_id, nullptr, nullptr); } OdeBody OdeJoint:: get_body(int index) const { - nassertr(_id, OdeBody(0)); - nassertr(index == 0 || index == 1, OdeBody(0)); + nassertr(_id, OdeBody(nullptr)); + nassertr(index == 0 || index == 1, OdeBody(nullptr)); return OdeBody(dJointGetBody(_id, index)); } void OdeJoint:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, unsigned int indent) const { out.width(indent); out << "" << get_type() \ << "(id = " << _id \ << ", body1 = "; OdeBody body = get_body(0); - if (body.get_id() != 0) { + if (body.get_id() != nullptr) { body.write(out); } else { @@ -108,7 +108,7 @@ write(ostream &out, unsigned int indent) const { } out << ", body2 = "; body = get_body(1); - if (body.get_id() != 0) { + if (body.get_id() != nullptr) { body.write(out); } else { @@ -120,82 +120,82 @@ write(ostream &out, unsigned int indent) const { OdeJoint:: operator bool () const { - return (_id != NULL); + return (_id != nullptr); } OdeBallJoint OdeJoint:: convert_to_ball() const { - nassertr(_id != 0, OdeBallJoint(0)); - nassertr(get_joint_type() == JT_ball, OdeBallJoint(0)); + nassertr(_id != nullptr, OdeBallJoint(nullptr)); + nassertr(get_joint_type() == JT_ball, OdeBallJoint(nullptr)); return OdeBallJoint(_id); } OdeHingeJoint OdeJoint:: convert_to_hinge() const { - nassertr(_id != 0, OdeHingeJoint(0)); - nassertr(get_joint_type() == JT_hinge, OdeHingeJoint(0)); + nassertr(_id != nullptr, OdeHingeJoint(nullptr)); + nassertr(get_joint_type() == JT_hinge, OdeHingeJoint(nullptr)); return OdeHingeJoint(_id); } OdeSliderJoint OdeJoint:: convert_to_slider() const { - nassertr(_id != 0, OdeSliderJoint(0)); - nassertr(get_joint_type() == JT_slider, OdeSliderJoint(0)); + nassertr(_id != nullptr, OdeSliderJoint(nullptr)); + nassertr(get_joint_type() == JT_slider, OdeSliderJoint(nullptr)); return OdeSliderJoint(_id); } OdeContactJoint OdeJoint:: convert_to_contact() const { - nassertr(_id != 0, OdeContactJoint(0)); - nassertr(get_joint_type() == JT_contact, OdeContactJoint(0)); + nassertr(_id != nullptr, OdeContactJoint(nullptr)); + nassertr(get_joint_type() == JT_contact, OdeContactJoint(nullptr)); return OdeContactJoint(_id); } OdeUniversalJoint OdeJoint:: convert_to_universal() const { - nassertr(_id != 0, OdeUniversalJoint(0)); - nassertr(get_joint_type() == JT_universal, OdeUniversalJoint(0)); + nassertr(_id != nullptr, OdeUniversalJoint(nullptr)); + nassertr(get_joint_type() == JT_universal, OdeUniversalJoint(nullptr)); return OdeUniversalJoint(_id); } OdeHinge2Joint OdeJoint:: convert_to_hinge2() const { - nassertr(_id != 0, OdeHinge2Joint(0)); - nassertr(get_joint_type() == JT_hinge2, OdeHinge2Joint(0)); + nassertr(_id != nullptr, OdeHinge2Joint(nullptr)); + nassertr(get_joint_type() == JT_hinge2, OdeHinge2Joint(nullptr)); return OdeHinge2Joint(_id); } OdeFixedJoint OdeJoint:: convert_to_fixed() const { - nassertr(_id != 0, OdeFixedJoint(0)); - nassertr(get_joint_type() == JT_fixed, OdeFixedJoint(0)); + nassertr(_id != nullptr, OdeFixedJoint(nullptr)); + nassertr(get_joint_type() == JT_fixed, OdeFixedJoint(nullptr)); return OdeFixedJoint(_id); } OdeNullJoint OdeJoint:: convert_to_null() const { - nassertr(_id != 0, OdeNullJoint(0)); - nassertr(get_joint_type() == JT_null, OdeNullJoint(0)); + nassertr(_id != nullptr, OdeNullJoint(nullptr)); + nassertr(get_joint_type() == JT_null, OdeNullJoint(nullptr)); return OdeNullJoint(_id); } OdeAMotorJoint OdeJoint:: convert_to_a_motor() const { - nassertr(_id != 0, OdeAMotorJoint(0)); - nassertr(get_joint_type() == JT_a_motor, OdeAMotorJoint(0)); + nassertr(_id != nullptr, OdeAMotorJoint(nullptr)); + nassertr(get_joint_type() == JT_a_motor, OdeAMotorJoint(nullptr)); return OdeAMotorJoint(_id); } OdeLMotorJoint OdeJoint:: convert_to_l_motor() const { - nassertr(_id != 0, OdeLMotorJoint(0)); - nassertr(get_joint_type() == JT_l_motor, OdeLMotorJoint(0)); + nassertr(_id != nullptr, OdeLMotorJoint(nullptr)); + nassertr(get_joint_type() == JT_l_motor, OdeLMotorJoint(nullptr)); return OdeLMotorJoint(_id); } OdePlane2dJoint OdeJoint:: convert_to_plane2d() const { - nassertr(_id != 0, OdePlane2dJoint(0)); - nassertr(get_joint_type() == JT_plane2d, OdePlane2dJoint(0)); + nassertr(_id != nullptr, OdePlane2dJoint(nullptr)); + nassertr(get_joint_type() == JT_plane2d, OdePlane2dJoint(nullptr)); return OdePlane2dJoint(_id); } diff --git a/panda/src/ode/odeJoint.h b/panda/src/ode/odeJoint.h index ae9c23a2be..eda2a98b96 100644 --- a/panda/src/ode/odeJoint.h +++ b/panda/src/ode/odeJoint.h @@ -88,7 +88,7 @@ PUBLISHED: void attach_body(const OdeBody &body, int index); void detach(); - virtual void write(ostream &out = cout, unsigned int indent=0) const; + virtual void write(std::ostream &out = std::cout, unsigned int indent=0) const; INLINE int compare_to(const OdeJoint &other) const; INLINE bool operator == (const OdeJoint &other) const; operator bool () const; diff --git a/panda/src/ode/odeLMotorJoint.cxx b/panda/src/ode/odeLMotorJoint.cxx index 6c8abd2ee2..e1194603ac 100644 --- a/panda/src/ode/odeLMotorJoint.cxx +++ b/panda/src/ode/odeLMotorJoint.cxx @@ -23,7 +23,7 @@ OdeLMotorJoint(dJointID id) : OdeLMotorJoint:: OdeLMotorJoint(OdeWorld &world ) : - OdeJoint(dJointCreateLMotor(world.get_id(), 0)) { + OdeJoint(dJointCreateLMotor(world.get_id(), nullptr)) { } OdeLMotorJoint:: diff --git a/panda/src/ode/odeMass.cxx b/panda/src/ode/odeMass.cxx index de9d52567a..76c3d360e8 100644 --- a/panda/src/ode/odeMass.cxx +++ b/panda/src/ode/odeMass.cxx @@ -51,7 +51,7 @@ operator = (const OdeMass ©) { void OdeMass:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, unsigned int indent) const { out.width(indent); out << get_type() \ << "(mag = " << get_magnitude() \ diff --git a/panda/src/ode/odeMass.h b/panda/src/ode/odeMass.h index bd2ee5a167..4320ac281a 100644 --- a/panda/src/ode/odeMass.h +++ b/panda/src/ode/odeMass.h @@ -66,7 +66,7 @@ PUBLISHED: INLINE LPoint3f get_center() const; INLINE LMatrix3f get_inertial_tensor() const; - virtual void write(ostream &out = cout, unsigned int indent=0) const; + virtual void write(std::ostream &out = std::cout, unsigned int indent=0) const; public: dMass* get_mass_ptr(); diff --git a/panda/src/ode/odeNullJoint.cxx b/panda/src/ode/odeNullJoint.cxx index 2cf348a6b2..214f101430 100644 --- a/panda/src/ode/odeNullJoint.cxx +++ b/panda/src/ode/odeNullJoint.cxx @@ -23,7 +23,7 @@ OdeNullJoint(dJointID id) : OdeNullJoint:: OdeNullJoint(OdeWorld &world) : - OdeJoint(dJointCreateNull(world.get_id(), 0)) { + OdeJoint(dJointCreateNull(world.get_id(), nullptr)) { } OdeNullJoint:: diff --git a/panda/src/ode/odePlane2dJoint.cxx b/panda/src/ode/odePlane2dJoint.cxx index 000f893ea6..1618452bb8 100644 --- a/panda/src/ode/odePlane2dJoint.cxx +++ b/panda/src/ode/odePlane2dJoint.cxx @@ -23,7 +23,7 @@ OdePlane2dJoint(dJointID id) : OdePlane2dJoint:: OdePlane2dJoint(OdeWorld &world) : - OdeJoint(dJointCreatePlane2D(world.get_id(), 0)) { + OdeJoint(dJointCreatePlane2D(world.get_id(), nullptr)) { } OdePlane2dJoint:: diff --git a/panda/src/ode/odePlaneGeom.cxx b/panda/src/ode/odePlaneGeom.cxx index a23d4961bb..5fe4b0bdb8 100644 --- a/panda/src/ode/odePlaneGeom.cxx +++ b/panda/src/ode/odePlaneGeom.cxx @@ -23,12 +23,12 @@ OdePlaneGeom(dGeomID id) : OdePlaneGeom:: OdePlaneGeom(dReal a, dReal b, dReal c, dReal d) : - OdeGeom(dCreatePlane(0, a, b, c, d)) { + OdeGeom(dCreatePlane(nullptr, a, b, c, d)) { } OdePlaneGeom:: OdePlaneGeom(const LVecBase4f ¶ms) : - OdeGeom(dCreatePlane(0, params[0], params[1], params[2], params[3])) { + OdeGeom(dCreatePlane(nullptr, params[0], params[1], params[2], params[3])) { } OdePlaneGeom:: diff --git a/panda/src/ode/odeQuadTreeSpace.cxx b/panda/src/ode/odeQuadTreeSpace.cxx index 2ced39a003..52b151e46e 100644 --- a/panda/src/ode/odeQuadTreeSpace.cxx +++ b/panda/src/ode/odeQuadTreeSpace.cxx @@ -38,7 +38,7 @@ OdeQuadTreeSpace:: OdeQuadTreeSpace(const LPoint3f ¢er, const LVecBase3f &extents, const int depth) : - OdeSpace(dQuadTreeSpaceCreate(0, + OdeSpace(dQuadTreeSpaceCreate(nullptr, LVec3_to_sdVector4(center).vec, LVec3_to_sdVector4(extents).vec, depth)) { diff --git a/panda/src/ode/odeRayGeom.cxx b/panda/src/ode/odeRayGeom.cxx index 10e727d76f..88a361948c 100644 --- a/panda/src/ode/odeRayGeom.cxx +++ b/panda/src/ode/odeRayGeom.cxx @@ -23,7 +23,7 @@ OdeRayGeom(dGeomID id) : OdeRayGeom:: OdeRayGeom(dReal length) : - OdeGeom(dCreateRay(0, length)) { + OdeGeom(dCreateRay(nullptr, length)) { } OdeRayGeom:: diff --git a/panda/src/ode/odeSimpleSpace.cxx b/panda/src/ode/odeSimpleSpace.cxx index a9e52d2015..1714d9af27 100644 --- a/panda/src/ode/odeSimpleSpace.cxx +++ b/panda/src/ode/odeSimpleSpace.cxx @@ -23,7 +23,7 @@ OdeSimpleSpace(dSpaceID id) : OdeSimpleSpace:: OdeSimpleSpace() : - OdeSpace(dSimpleSpaceCreate(0)) { + OdeSpace(dSimpleSpaceCreate(nullptr)) { } OdeSimpleSpace:: diff --git a/panda/src/ode/odeSliderJoint.cxx b/panda/src/ode/odeSliderJoint.cxx index 2976cbe65e..1e86396637 100644 --- a/panda/src/ode/odeSliderJoint.cxx +++ b/panda/src/ode/odeSliderJoint.cxx @@ -23,7 +23,7 @@ OdeSliderJoint(dJointID id) : OdeSliderJoint:: OdeSliderJoint(OdeWorld &world) : - OdeJoint(dJointCreateSlider(world.get_id(), 0)) { + OdeJoint(dJointCreateSlider(world.get_id(), nullptr)) { } OdeSliderJoint:: diff --git a/panda/src/ode/odeSpace.I b/panda/src/ode/odeSpace.I index d4c60779d9..93fc719e40 100644 --- a/panda/src/ode/odeSpace.I +++ b/panda/src/ode/odeSpace.I @@ -103,11 +103,11 @@ is_enabled() { } INLINE void OdeSpace:: -set_collision_event(const string &event_name) { +set_collision_event(const std::string &event_name) { _collision_event = event_name; } -INLINE string OdeSpace:: +INLINE std::string OdeSpace:: get_collision_event() { return _collision_event; } diff --git a/panda/src/ode/odeSpace.cxx b/panda/src/ode/odeSpace.cxx index 6c4749f946..f2beca8efb 100644 --- a/panda/src/ode/odeSpace.cxx +++ b/panda/src/ode/odeSpace.cxx @@ -31,8 +31,8 @@ dJointGroupID OdeSpace::_static_auto_collide_joint_group; OdeSpace:: OdeSpace(dSpaceID id) : _id(id) { - _auto_collide_world = NULL; - _auto_collide_joint_group = NULL; + _auto_collide_world = nullptr; + _auto_collide_joint_group = nullptr; } OdeSpace:: @@ -89,19 +89,19 @@ clean() { OdeGeom OdeSpace:: get_geom(int i) { - nassertr(_id, OdeGeom(0)); + nassertr(_id, OdeGeom(nullptr)); return OdeGeom(dSpaceGetGeom(_id, i)); } void OdeSpace:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, unsigned int indent) const { out.width(indent); out << "" << get_type() << "(id = " << _id << ")"; } OdeSpace:: operator bool () const { - return (_id != NULL); + return (_id != nullptr); } void OdeSpace:: @@ -116,10 +116,10 @@ set_auto_collide_joint_group(OdeJointGroup &joint_group) { void OdeSpace:: auto_collide() { - if (_auto_collide_world == NULL) { + if (_auto_collide_world == nullptr) { odespace_cat.error() << "No collide world has been set!\n"; } else { - nassertv(_id != NULL); + nassertv(_id != nullptr); _static_auto_collide_space = this; _static_auto_collide_world = _auto_collide_world; _static_auto_collide_joint_group = _auto_collide_joint_group; @@ -140,7 +140,7 @@ auto_callback(void *data, dGeomID o1, dGeomID o2) { int surface1 = _static_auto_collide_space->get_surface_type(o1); int surface2 = _static_auto_collide_space->get_surface_type(o2); - nassertv(_static_auto_collide_world != NULL); + nassertv(_static_auto_collide_world != nullptr); sSurfaceParams collide_params; collide_params = _static_auto_collide_world->get_surface(surface1, surface2); @@ -191,22 +191,22 @@ auto_callback(void *data, dGeomID o1, dGeomID o2) { OdeSimpleSpace OdeSpace:: convert_to_simple_space() const { - nassertr(_id != 0, OdeSimpleSpace((dSpaceID)0)); - nassertr(get_class() == OdeGeom::GC_simple_space, OdeSimpleSpace((dSpaceID)0)); + nassertr(_id != nullptr, OdeSimpleSpace(nullptr)); + nassertr(get_class() == OdeGeom::GC_simple_space, OdeSimpleSpace(nullptr)); return OdeSimpleSpace(_id); } OdeHashSpace OdeSpace:: convert_to_hash_space() const { - nassertr(_id != 0, OdeHashSpace((dSpaceID)0)); - nassertr(get_class() == OdeGeom::GC_hash_space, OdeHashSpace((dSpaceID)0)); + nassertr(_id != nullptr, OdeHashSpace(nullptr)); + nassertr(get_class() == OdeGeom::GC_hash_space, OdeHashSpace(nullptr)); return OdeHashSpace(_id); } OdeQuadTreeSpace OdeSpace:: convert_to_quad_tree_space() const { - nassertr(_id != 0, OdeQuadTreeSpace((dSpaceID)0)); - nassertr(get_class() == OdeGeom::GC_quad_tree_space, OdeQuadTreeSpace((dSpaceID)0)); + nassertr(_id != nullptr, OdeQuadTreeSpace(nullptr)); + nassertr(get_class() == OdeGeom::GC_quad_tree_space, OdeQuadTreeSpace(nullptr)); return OdeQuadTreeSpace(_id); } diff --git a/panda/src/ode/odeSpace.h b/panda/src/ode/odeSpace.h index 928defe8b6..c4888d70f6 100644 --- a/panda/src/ode/odeSpace.h +++ b/panda/src/ode/odeSpace.h @@ -75,7 +75,7 @@ PUBLISHED: INLINE OdeSpace get_space() const; - virtual void write(ostream &out = cout, unsigned int indent=0) const; + virtual void write(std::ostream &out = std::cout, unsigned int indent=0) const; operator bool () const; OdeSimpleSpace convert_to_simple_space() const; @@ -97,8 +97,8 @@ PUBLISHED: int get_collide_id(dGeomID o1); int get_collide_id(OdeGeom& geom); - INLINE void set_collision_event(const string &event_name); - INLINE string get_collision_event(); + INLINE void set_collision_event(const std::string &event_name); + INLINE std::string get_collision_event(); public: static void auto_callback(void*, dGeomID, dGeomID); @@ -108,7 +108,7 @@ public: static OdeSpace* _static_auto_collide_space; static dJointGroupID _static_auto_collide_joint_group; static int contactCount; - string _collision_event; + std::string _collision_event; protected: dSpaceID _id; diff --git a/panda/src/ode/odeSpace_ext.cxx b/panda/src/ode/odeSpace_ext.cxx index bed4a3e30b..97e841f30b 100644 --- a/panda/src/ode/odeSpace_ext.cxx +++ b/panda/src/ode/odeSpace_ext.cxx @@ -29,7 +29,7 @@ extern Dtool_PyTypedObject Dtool_OdeSpace; extern Dtool_PyTypedObject Dtool_OdeQuadTreeSpace; #endif -PyObject *Extension::_python_callback = NULL; +PyObject *Extension::_python_callback = nullptr; /** * Do a sort of pseudo-downcast on this space in order to expose its @@ -69,13 +69,13 @@ convert() const { int Extension:: collide(PyObject* arg, PyObject* callback) { - nassertr(callback != NULL, -1); + nassertr(callback != nullptr, -1); if (!PyCallable_Check(callback)) { PyErr_Format(PyExc_TypeError, "'%s' object is not callable", callback->ob_type->tp_name); return -1; - } else if (_this->get_id() == NULL) { + } else if (_this->get_id() == nullptr) { // Well, while we're in the mood of python exceptions, let's make this one // too. PyErr_Format(PyExc_TypeError, "OdeSpace is not valid!"); @@ -96,7 +96,7 @@ near_callback(void *data, dGeomID o1, dGeomID o2) { OdeGeom g2 (o2); PyObject* p1 = invoke_extension(&g1).convert(); PyObject* p2 = invoke_extension(&g2).convert(); - PyObject *result = PyObject_CallFunctionObjArgs(_python_callback, (PyObject*) data, p1, p2, NULL); + PyObject *result = PyObject_CallFunctionObjArgs(_python_callback, (PyObject*) data, p1, p2, nullptr); if (!result) { odespace_cat.error() << "An error occurred while calling python function!\n"; PyErr_Print(); diff --git a/panda/src/ode/odeSphereGeom.cxx b/panda/src/ode/odeSphereGeom.cxx index 96cb041495..eb49b7ea5e 100644 --- a/panda/src/ode/odeSphereGeom.cxx +++ b/panda/src/ode/odeSphereGeom.cxx @@ -23,7 +23,7 @@ OdeSphereGeom(dGeomID id) : OdeSphereGeom:: OdeSphereGeom(dReal radius) : - OdeGeom(dCreateSphere(0, radius)) { + OdeGeom(dCreateSphere(nullptr, radius)) { } OdeSphereGeom:: diff --git a/panda/src/ode/odeTriMeshData.I b/panda/src/ode/odeTriMeshData.I index e0cc754623..2aad3a2404 100644 --- a/panda/src/ode/odeTriMeshData.I +++ b/panda/src/ode/odeTriMeshData.I @@ -13,7 +13,7 @@ INLINE OdeTriMeshData::TriMeshDataMap &OdeTriMeshData:: get_tri_mesh_data_map() { - if (_tri_mesh_data_map == (TriMeshDataMap *)NULL) { + if (_tri_mesh_data_map == nullptr) { _tri_mesh_data_map = new TriMeshDataMap; } return *_tri_mesh_data_map; diff --git a/panda/src/ode/odeTriMeshData.cxx b/panda/src/ode/odeTriMeshData.cxx index a87853c4bb..c92602ac34 100644 --- a/panda/src/ode/odeTriMeshData.cxx +++ b/panda/src/ode/odeTriMeshData.cxx @@ -13,8 +13,10 @@ #include "odeTriMeshData.h" +using std::ostream; + TypeHandle OdeTriMeshData::_type_handle; -OdeTriMeshData::TriMeshDataMap *OdeTriMeshData::_tri_mesh_data_map = NULL; +OdeTriMeshData::TriMeshDataMap *OdeTriMeshData::_tri_mesh_data_map = nullptr; void OdeTriMeshData:: link_data(dGeomID id, PT(OdeTriMeshData) data) { @@ -29,13 +31,13 @@ get_data(dGeomID id) { if (iter != data_map.end()) { return iter->second; } - return NULL; + return nullptr; } void OdeTriMeshData:: unlink_data(dGeomID id) { odetrimeshdata_cat.debug() << get_class_type() << "::unlink_data(" << id << ")" << "\n"; - nassertv(_tri_mesh_data_map != (TriMeshDataMap *)NULL); + nassertv(_tri_mesh_data_map != nullptr); TriMeshDataMap::iterator iter = _tri_mesh_data_map->find(id); if (iter != _tri_mesh_data_map->end()) { _tri_mesh_data_map->erase(iter); @@ -43,7 +45,7 @@ unlink_data(dGeomID id) { } void OdeTriMeshData:: -print_data(const string &marker) { +print_data(const std::string &marker) { odetrimeshdata_cat.debug() << get_class_type() << "::print_data(" << marker << ")\n"; const TriMeshDataMap &data_map = get_tri_mesh_data_map(); TriMeshDataMap::const_iterator iter = data_map.begin(); @@ -58,7 +60,7 @@ remove_data(OdeTriMeshData *data) { odetrimeshdata_cat.debug() << get_class_type() << "::remove_data(" << data->get_id() << ")" << "\n"; } - if (_tri_mesh_data_map == (TriMeshDataMap *)NULL) { + if (_tri_mesh_data_map == nullptr) { return; } @@ -88,9 +90,9 @@ remove_data(OdeTriMeshData *data) { OdeTriMeshData:: OdeTriMeshData(const NodePath& model, bool use_normals) : _id(dGeomTriMeshDataCreate()), - _vertices(0), - _faces(0), - _normals(0), + _vertices(nullptr), + _faces(nullptr), + _normals(nullptr), _num_vertices(0), _num_faces(0) { odetrimeshdata_cat.debug() << get_type() << "(" << _id << ")" << "\n"; @@ -131,16 +133,16 @@ OdeTriMeshData:: ~OdeTriMeshData() { odetrimeshdata_cat.debug() << "~" << get_type() << "(" << _id << ")" << "\n"; destroy(); - if (_vertices != 0) { + if (_vertices != nullptr) { PANDA_FREE_ARRAY(_vertices); - _vertices = 0; + _vertices = nullptr; _num_vertices = 0; } - if (_faces != 0) { + if (_faces != nullptr) { PANDA_FREE_ARRAY(_faces); - _faces = 0; + _faces = nullptr; } - if (_normals != 0) { + if (_normals != nullptr) { // This is never allocated? Until we use _normals, assert that we don't // accidentally free it here through some mistake. nassertv(false); @@ -151,10 +153,10 @@ OdeTriMeshData:: void OdeTriMeshData:: destroy() { odetrimeshdata_cat.debug() << get_type() << "::destroy(" << _id << ")" << "\n"; - if (_id != 0) { + if (_id != nullptr) { dGeomTriMeshDataDestroy(_id); remove_data(this); - _id = 0; + _id = nullptr; } } @@ -219,7 +221,7 @@ process_geom(const Geom *geom) { CPT(GeomVertexData) vData = geom->get_vertex_data(); - for (int i = 0; i < geom->get_num_primitives(); ++i) { + for (size_t i = 0; i < geom->get_num_primitives(); ++i) { process_primitive(geom->get_primitive(i), vData); } } @@ -229,7 +231,7 @@ process_primitive(const GeomPrimitive *primitive, CPT(GeomVertexData) vData) { GeomVertexReader vReader(vData, "vertex"); GeomVertexReader nReader(vData, "normal"); - LVecBase3f vertex, normal; + LVecBase3f vertex; // CPT(GeomPrimitive) dPrimitive = primitive->decompose(); CPT(GeomPrimitive) dPrimitive = primitive; ostream &out = odetrimeshdata_cat.debug(); @@ -306,7 +308,7 @@ analyze(const Geom *geom) { return; } - for (int i = 0; i < geom->get_num_primitives(); ++i) { + for (size_t i = 0; i < geom->get_num_primitives(); ++i) { analyze(geom->get_primitive(i)); } } diff --git a/panda/src/ode/odeTriMeshData.h b/panda/src/ode/odeTriMeshData.h index e8b46fad73..efdda31c78 100644 --- a/panda/src/ode/odeTriMeshData.h +++ b/panda/src/ode/odeTriMeshData.h @@ -38,7 +38,7 @@ public: static PT(OdeTriMeshData) get_data(dGeomID id); static void unlink_data(dGeomID id); static void remove_data(OdeTriMeshData *data); - static void print_data(const string &marker); + static void print_data(const std::string &marker); private: typedef pmap TriMeshDataMap; @@ -59,8 +59,8 @@ PUBLISHED: // data_id); INLINE void get_buffer(unsigned char** buf, int* buf_len) // const; INLINE void set_buffer(unsigned char* buf); INLINE void update(); - virtual void write(ostream &out = cout, unsigned int indent=0) const; - void write_faces(ostream &out) const; + virtual void write(std::ostream &out = std::cout, unsigned int indent=0) const; + void write_faces(std::ostream &out) const; public: INLINE void build_single(const void* vertices, int vertex_stride, int vertex_count, \ diff --git a/panda/src/ode/odeTriMeshGeom.I b/panda/src/ode/odeTriMeshGeom.I index b0a2e6177c..0a7dccaf53 100644 --- a/panda/src/ode/odeTriMeshGeom.I +++ b/panda/src/ode/odeTriMeshGeom.I @@ -34,7 +34,7 @@ set_tri_mesh_data(OdeTriMeshData &data) { INLINE PT(OdeTriMeshData) OdeTriMeshGeom:: get_tri_mesh_data() const { - nassertr(_id != 0, NULL); + nassertr(_id != 0, nullptr); return OdeTriMeshData::get_data(_id); } diff --git a/panda/src/ode/odeTriMeshGeom.cxx b/panda/src/ode/odeTriMeshGeom.cxx index f3e596d72b..257dbef3bb 100644 --- a/panda/src/ode/odeTriMeshGeom.cxx +++ b/panda/src/ode/odeTriMeshGeom.cxx @@ -23,19 +23,19 @@ OdeTriMeshGeom(dGeomID id) : OdeTriMeshGeom:: OdeTriMeshGeom(OdeTriMeshData &data) : - OdeGeom(dCreateTriMesh(0, data.get_id(), 0, 0, 0)) { + OdeGeom(dCreateTriMesh(nullptr, data.get_id(), nullptr, nullptr, nullptr)) { OdeTriMeshData::link_data(_id, &data); } OdeTriMeshGeom:: OdeTriMeshGeom(OdeSpace &space, OdeTriMeshData &data) : - OdeGeom(dCreateTriMesh(space.get_id(), data.get_id(), 0, 0, 0)) { + OdeGeom(dCreateTriMesh(space.get_id(), data.get_id(), nullptr, nullptr, nullptr)) { OdeTriMeshData::link_data(_id, &data); } OdeTriMeshGeom:: OdeTriMeshGeom(const OdeTriMeshGeom ©) : - OdeGeom(dCreateTriMesh(0, copy.get_data_id(), 0, 0, 0)) { + OdeGeom(dCreateTriMesh(nullptr, copy.get_data_id(), nullptr, nullptr, nullptr)) { OdeTriMeshData::link_data(_id, copy.get_data()); } diff --git a/panda/src/ode/odeUniversalJoint.cxx b/panda/src/ode/odeUniversalJoint.cxx index 4e9780bf92..ca8264e9ee 100644 --- a/panda/src/ode/odeUniversalJoint.cxx +++ b/panda/src/ode/odeUniversalJoint.cxx @@ -23,7 +23,7 @@ OdeUniversalJoint(dJointID id) : OdeUniversalJoint:: OdeUniversalJoint(OdeWorld &world) : - OdeJoint(dJointCreateUniversal(world.get_id(), 0)) { + OdeJoint(dJointCreateUniversal(world.get_id(), nullptr)) { } OdeUniversalJoint:: diff --git a/panda/src/ode/odeUtil.cxx b/panda/src/ode/odeUtil.cxx index 0e38b45558..2ae8d281d4 100644 --- a/panda/src/ode/odeUtil.cxx +++ b/panda/src/ode/odeUtil.cxx @@ -28,7 +28,7 @@ get_connecting_joint(const OdeBody &body1, const OdeBody &body2) { */ OdeJointCollection OdeUtil:: get_connecting_joint_list(const OdeBody &body1, const OdeBody &body2) { - const int max_possible_joints = min(body1.get_num_joints(), body1.get_num_joints()); + const int max_possible_joints = std::min(body1.get_num_joints(), body1.get_num_joints()); dJointID *joint_list = (dJointID *)PANDA_MALLOC_ARRAY(max_possible_joints * sizeof(dJointID)); int num_joints = dConnectingJointList(body1.get_id(), body2.get_id(), diff --git a/panda/src/ode/odeUtil_ext.cxx b/panda/src/ode/odeUtil_ext.cxx index 862e215eae..c5aabaa812 100644 --- a/panda/src/ode/odeUtil_ext.cxx +++ b/panda/src/ode/odeUtil_ext.cxx @@ -18,7 +18,7 @@ #ifdef HAVE_PYTHON -PyObject *Extension::_python_callback = NULL; +PyObject *Extension::_python_callback = nullptr; /** * Calls the callback for all potentially intersecting pairs that contain one @@ -26,7 +26,7 @@ PyObject *Extension::_python_callback = NULL; */ int Extension:: collide2(const OdeGeom &geom1, const OdeGeom &geom2, PyObject* arg, PyObject* callback) { - nassertr(callback != NULL, -1); + nassertr(callback != nullptr, -1); if (!PyCallable_Check(callback)) { PyErr_Format(PyExc_TypeError, "'%s' object is not callable", callback->ob_type->tp_name); return -1; @@ -50,7 +50,7 @@ near_callback(void *data, dGeomID o1, dGeomID o2) { OdeGeom g2 (o2); PyObject* p1 = invoke_extension(&g1).convert(); PyObject* p2 = invoke_extension(&g2).convert(); - PyObject* result = PyObject_CallFunctionObjArgs(_python_callback, (PyObject*) data, p1, p2, NULL); + PyObject* result = PyObject_CallFunctionObjArgs(_python_callback, (PyObject*) data, p1, p2, nullptr); if (!result) { ode_cat.error() << "An error occurred while calling python function!\n"; PyErr_Print(); diff --git a/panda/src/ode/odeWorld.cxx b/panda/src/ode/odeWorld.cxx index 30b98ddd8b..f087c46374 100644 --- a/panda/src/ode/odeWorld.cxx +++ b/panda/src/ode/odeWorld.cxx @@ -178,5 +178,5 @@ apply_dampening(float dt, OdeBody& body) { OdeWorld:: operator bool () const { - return (_id != NULL); + return (_id != nullptr); } diff --git a/panda/src/osxdisplay/config_osxdisplay.cxx b/panda/src/osxdisplay/config_osxdisplay.cxx index 4ac68f5e58..43f897b862 100644 --- a/panda/src/osxdisplay/config_osxdisplay.cxx +++ b/panda/src/osxdisplay/config_osxdisplay.cxx @@ -20,8 +20,8 @@ #include "pandaSystem.h" -#if !defined(CPPPARSER) && !defined(BUILDING_PANDAGL) - #error Buildsystem error: BUILDING_PANDAGL not defined +#if !defined(CPPPARSER) && !defined(BUILDING_PANDA_OSXDISPLAY) + #error Buildsystem error: BUILDING_PANDA_OSXDISPLAY not defined #endif Configure(config_osxdisplay); diff --git a/panda/src/osxdisplay/config_osxdisplay.h b/panda/src/osxdisplay/config_osxdisplay.h index cedaff1e3e..5eadc80a7e 100644 --- a/panda/src/osxdisplay/config_osxdisplay.h +++ b/panda/src/osxdisplay/config_osxdisplay.h @@ -17,9 +17,9 @@ #include "configVariableBool.h" #include "configVariableInt.h" -NotifyCategoryDecl( osxdisplay , EXPCL_PANDAGL, EXPTP_PANDAGL); +NotifyCategoryDecl( osxdisplay , EXPCL_PANDA_OSXDISPLAY, EXPTP_PANDA_OSXDISPLAY); -extern EXPCL_PANDAGL void init_libosxdisplay(); +extern EXPCL_PANDA_OSXDISPLAY void init_libosxdisplay(); extern ConfigVariableBool show_resize_box; extern ConfigVariableBool osx_support_gl_buffer; diff --git a/panda/src/osxdisplay/osxGraphicsBuffer.cxx b/panda/src/osxdisplay/osxGraphicsBuffer.cxx index 7b1beb26f8..03bfa46d79 100644 --- a/panda/src/osxdisplay/osxGraphicsBuffer.cxx +++ b/panda/src/osxdisplay/osxGraphicsBuffer.cxx @@ -25,7 +25,7 @@ TypeHandle osxGraphicsBuffer::_type_handle; */ osxGraphicsBuffer:: osxGraphicsBuffer(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -36,7 +36,7 @@ osxGraphicsBuffer(GraphicsEngine *engine, GraphicsPipe *pipe, osxGraphicsPipe *osx_pipe; DCAST_INTO_V(osx_pipe, _pipe); - _pbuffer = NULL; + _pbuffer = nullptr; // Since the pbuffer never gets flipped, we get screenshots from the same // buffer we draw into. @@ -48,7 +48,7 @@ osxGraphicsBuffer(GraphicsEngine *engine, GraphicsPipe *pipe, */ osxGraphicsBuffer:: ~osxGraphicsBuffer() { - nassertv(_pbuffer == NULL); + nassertv(_pbuffer == nullptr); } /** @@ -62,10 +62,10 @@ begin_frame(FrameMode mode, Thread *current_thread) { PStatTimer timer(_make_current_pcollector); begin_frame_spam(mode); - if (_gsg == (GraphicsStateGuardian *)NULL) { + if (_gsg == nullptr) { return false; } - nassertr(_pbuffer != NULL, false); + nassertr(_pbuffer != nullptr, false); osxGraphicsStateGuardian *osxgsg; DCAST_INTO_R(osxgsg, _gsg, false); @@ -106,7 +106,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { void osxGraphicsBuffer:: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); - nassertv(_gsg != (GraphicsStateGuardian *)NULL); + nassertv(_gsg != nullptr); if (mode == FM_render) { copy_to_textures(); @@ -125,13 +125,13 @@ end_frame(FrameMode mode, Thread *current_thread) { */ void osxGraphicsBuffer:: close_buffer() { - if (_gsg != (GraphicsStateGuardian *)NULL) { + if (_gsg != nullptr) { // aglSetPBuffer(osxgsg->get_context(), _pbuffer, 0, 0, 0); _gsg.clear(); } - if (_pbuffer != NULL) { + if (_pbuffer != nullptr) { aglDestroyPBuffer(_pbuffer); - _pbuffer = NULL; + _pbuffer = nullptr; } _is_valid = false; } @@ -143,10 +143,10 @@ close_buffer() { bool osxGraphicsBuffer:: open_buffer() { if (_gsg == 0) { - _gsg = new osxGraphicsStateGuardian(_engine, _pipe, NULL); + _gsg = new osxGraphicsStateGuardian(_engine, _pipe, nullptr); } - if (_pbuffer == NULL) { + if (_pbuffer == nullptr) { GLenum target = GL_TEXTURE_RECTANGLE_ARB; if (_size[0] == Texture::up_to_power_2(_size[0]) && _size[1] == Texture::up_to_power_2(_size[1])) { diff --git a/panda/src/osxdisplay/osxGraphicsBuffer.h b/panda/src/osxdisplay/osxGraphicsBuffer.h index a2ff19f76a..7ea83d1c4c 100644 --- a/panda/src/osxdisplay/osxGraphicsBuffer.h +++ b/panda/src/osxdisplay/osxGraphicsBuffer.h @@ -27,7 +27,7 @@ class osxGraphicsBuffer : public GraphicsBuffer { public: osxGraphicsBuffer(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/osxdisplay/osxGraphicsPipe.cxx b/panda/src/osxdisplay/osxGraphicsPipe.cxx index 721f54b585..5a56a6259d 100644 --- a/panda/src/osxdisplay/osxGraphicsPipe.cxx +++ b/panda/src/osxdisplay/osxGraphicsPipe.cxx @@ -34,7 +34,7 @@ Boolean GetDictionaryBoolean(CFDictionaryRef theDict, const void* key) { Boolean value = false; CFBooleanRef boolRef; boolRef = (CFBooleanRef)CFDictionaryGetValue(theDict, key); - if (boolRef != NULL) + if (boolRef != nullptr) value = CFBooleanGetValue(boolRef); return value; } @@ -44,7 +44,7 @@ long GetDictionaryLong(CFDictionaryRef theDict, const void* key) { long value = 0; CFNumberRef numRef; numRef = (CFNumberRef)CFDictionaryGetValue(theDict, key); - if (numRef != NULL) + if (numRef != nullptr) CFNumberGetValue(numRef, kCFNumberLongType, &value); return value; } @@ -94,7 +94,7 @@ CFArrayRef GSCGDisplayAvailableModesUsefulForOpenGL(CGDirectDisplayID display) { unsigned int numberOfAvailableModes = CFArrayGetCount(availableModes); // creat mutable array to hold the display modes we are interested int. - CFMutableArrayRef usefulModes = CFArrayCreateMutable(kCFAllocatorDefault, numberOfAvailableModes, NULL); + CFMutableArrayRef usefulModes = CFArrayCreateMutable(kCFAllocatorDefault, numberOfAvailableModes, nullptr); // get the current bits per pixel. long currentModeBitsPerPixel = GetModeBitsPerPixel(CGDisplayCurrentMode(display)); @@ -152,7 +152,7 @@ CFArrayRef GSCGDisplayAvailableModesUsefulForOpenGL(CGDirectDisplayID display) { // now sort the useful mode array, using the comparison callback. CFArraySortValues( usefulModes, CFRangeMake(0, CFArrayGetCount(usefulModes)), - (CFComparatorFunction) CompareModes, NULL); + (CFComparatorFunction) CompareModes, nullptr); // return the CFArray of the useful display modes. return usefulModes; } @@ -202,7 +202,7 @@ osxGraphicsPipe:: * choose between several possible GraphicsPipes available on a particular * platform, so the name should be meaningful and unique for a given platform. */ -string osxGraphicsPipe:: +std::string osxGraphicsPipe:: get_interface_name() const { return "OpenGL"; } @@ -250,7 +250,7 @@ create_cg_image(const PNMImage &pnm_image) { bool has_alpha; bool is_grayscale; - CFStringRef color_space_name = NULL; + CFStringRef color_space_name = nullptr; switch (pnm_image.get_color_type()) { case PNMImage::CT_grayscale: color_space_name = kCGColorSpaceGenericGray; @@ -278,13 +278,13 @@ create_cg_image(const PNMImage &pnm_image) { case PNMImage::CT_invalid: // Shouldn't get here. - nassertr(false, NULL); + nassertr(false, nullptr); break; } - nassertr(color_space_name != NULL, NULL); + nassertr(color_space_name != nullptr, nullptr); CGColorSpaceRef color_space = CGColorSpaceCreateWithName(color_space_name); - nassertr(color_space != NULL, NULL); + nassertr(color_space != nullptr, nullptr); CGBitmapInfo bitmap_info = 0; #ifdef PGM_BIGGRAYS @@ -312,17 +312,17 @@ create_cg_image(const PNMImage &pnm_image) { } } } - nassertr((void *)dp == (void *)(char_array + num_bytes), NULL); + nassertr((void *)dp == (void *)(char_array + num_bytes), nullptr); CGDataProviderRef provider = - CGDataProviderCreateWithData(NULL, char_array, num_bytes, release_data); - nassertr(provider != NULL, NULL); + CGDataProviderCreateWithData(nullptr, char_array, num_bytes, release_data); + nassertr(provider != nullptr, nullptr); CGImageRef image = CGImageCreate (width, height, bits_per_component, bits_per_pixel, bytes_per_row, color_space, bitmap_info, provider, - NULL, false, kCGRenderingIntentDefault); - nassertr(image != NULL, NULL); + nullptr, false, kCGRenderingIntentDefault); + nassertr(image != nullptr, nullptr); CGColorSpaceRelease(color_space); CGDataProviderRelease(provider); @@ -344,7 +344,7 @@ release_data(void *info, const void *data, size_t size) { * Creates a new window on the pipe, if possible. */ PT(GraphicsOutput) osxGraphicsPipe:: -make_output(const string &name, +make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -354,12 +354,12 @@ make_output(const string &name, int retry, bool &precertify) { if (!_is_valid) { - return NULL; + return nullptr; } osxGraphicsStateGuardian *osxgsg = 0; if (gsg != 0) { - DCAST_INTO_R(osxgsg, gsg, NULL); + DCAST_INTO_R(osxgsg, gsg, nullptr); } // First thing to try: an osxGraphicsWindow @@ -372,15 +372,15 @@ make_output(const string &name, ((flags&BF_can_bind_color)!=0)|| ((flags&BF_can_bind_every)!=0)|| ((flags&BF_can_bind_layered)!=0)) { - return NULL; + return nullptr; } WindowHandle *window_handle = win_prop.get_parent_window(); - if (window_handle != NULL) { + if (window_handle != nullptr) { osxdisplay_cat.info() << "Got parent_window " << *window_handle << "\n"; #ifdef SUPPORT_SUBPROCESS_WINDOW WindowHandle::OSHandle *os_handle = window_handle->get_os_handle(); - if (os_handle != NULL && + if (os_handle != nullptr && os_handle->is_of_type(NativeWindowHandle::SubprocessHandle::get_class_type())) { return new SubprocessWindow(engine, this, name, fb_prop, win_prop, flags, gsg, host); @@ -394,9 +394,9 @@ make_output(const string &name, // Second thing to try: a GLGraphicsBuffer if (retry == 1) { - if (!osx_support_gl_buffer || !gl_support_fbo || host == NULL || + if (!osx_support_gl_buffer || !gl_support_fbo || host == nullptr || (flags & (BF_require_parasite | BF_require_window)) != 0) { - return NULL; + return nullptr; } // Early failure - if we are sure that this buffer WONT meet specs, we can // bail out early. @@ -404,13 +404,13 @@ make_output(const string &name, if (fb_prop.get_indexed_color() || fb_prop.get_back_buffers() > 0 || fb_prop.get_accum_bits() > 0) { - return NULL; + return nullptr; } } - if (osxgsg != NULL && osxgsg->is_valid() && !osxgsg->needs_reset()) { + if (osxgsg != nullptr && osxgsg->is_valid() && !osxgsg->needs_reset()) { if (!osxgsg->_supports_framebuffer_object || - osxgsg->_glDrawBuffers == NULL) { - return NULL; + osxgsg->_glDrawBuffers == nullptr) { + return nullptr; } else if (fb_prop.is_basic()) { // Early success - if we are sure that this buffer WILL meet specs, we // can precertify it. @@ -429,14 +429,14 @@ make_output(const string &name, ((flags&BF_size_track_host)!=0)|| ((flags&BF_can_bind_every)!=0)|| ((flags&BF_can_bind_layered)!=0)) { - return NULL; + return nullptr; } return new osxGraphicsBuffer(engine, this, name, fb_prop, win_prop, flags, gsg, host); } // Nothing else left to try. - return NULL; + return nullptr; } /** @@ -447,5 +447,5 @@ make_output(const string &name, */ PT(GraphicsStateGuardian) osxGraphicsPipe:: make_callback_gsg(GraphicsEngine *engine) { - return new osxGraphicsStateGuardian(engine, this, NULL); + return new osxGraphicsStateGuardian(engine, this, nullptr); } diff --git a/panda/src/osxdisplay/osxGraphicsPipe.h b/panda/src/osxdisplay/osxGraphicsPipe.h index 018d1bb0b7..75094778d6 100644 --- a/panda/src/osxdisplay/osxGraphicsPipe.h +++ b/panda/src/osxdisplay/osxGraphicsPipe.h @@ -24,12 +24,12 @@ class PNMImage; * This graphics pipe represents the interface for creating OpenGL graphics * windows on the various OSX's. */ -class EXPCL_PANDAGL osxGraphicsPipe : public GraphicsPipe { +class EXPCL_PANDA_OSXDISPLAY osxGraphicsPipe : public GraphicsPipe { public: osxGraphicsPipe(); virtual ~osxGraphicsPipe(); - virtual string get_interface_name() const; + virtual std::string get_interface_name() const; static PT(GraphicsPipe) pipe_constructor(); virtual PreferredWindowThread get_preferred_window_thread() const; @@ -39,7 +39,7 @@ private: static void release_data(void *info, const void *data, size_t size); protected: - virtual PT(GraphicsOutput) make_output(const string &name, + virtual PT(GraphicsOutput) make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/osxdisplay/osxGraphicsStateGuardian.cxx b/panda/src/osxdisplay/osxGraphicsStateGuardian.cxx index 8099eb5547..2fb60d2d74 100644 --- a/panda/src/osxdisplay/osxGraphicsStateGuardian.cxx +++ b/panda/src/osxdisplay/osxGraphicsStateGuardian.cxx @@ -35,14 +35,14 @@ TypeHandle osxGraphicsStateGuardian::_type_handle; */ void *osxGraphicsStateGuardian:: do_get_extension_func(const char *name) { - string fullname = "_" + string(name); - NSSymbol symbol = NULL; + std::string fullname = "_" + std::string(name); + NSSymbol symbol = nullptr; if (NSIsSymbolNameDefined(fullname.c_str())) { symbol = NSLookupAndBindSymbol(fullname.c_str()); } - return symbol ? NSAddressOfSymbol(symbol) : NULL; + return symbol ? NSAddressOfSymbol(symbol) : nullptr; } /** @@ -53,8 +53,8 @@ osxGraphicsStateGuardian(GraphicsEngine *engine, GraphicsPipe *pipe, osxGraphicsStateGuardian *share_with) : GLGraphicsStateGuardian(engine, pipe), _share_with(share_with), - _aglPixFmt(NULL), - _aglcontext(NULL) + _aglPixFmt(nullptr), + _aglcontext(nullptr) { _shared_buffer = 1011; get_gamma_table(); @@ -65,11 +65,11 @@ osxGraphicsStateGuardian(GraphicsEngine *engine, GraphicsPipe *pipe, */ osxGraphicsStateGuardian:: ~osxGraphicsStateGuardian() { - if (_aglcontext != (AGLContext)NULL) { - aglSetCurrentContext(NULL); + if (_aglcontext != (AGLContext)nullptr) { + aglSetCurrentContext(nullptr); aglDestroyContext(_aglcontext); report_agl_error("aglDestroyContext"); - _aglcontext = (AGLContext)NULL; + _aglcontext = (AGLContext)nullptr; } } @@ -89,7 +89,7 @@ void osxGraphicsStateGuardian::reset() GLGraphicsStateGuardian::reset(); - if (_aglcontext != (AGLContext)NULL) { + if (_aglcontext != (AGLContext)nullptr) { // Apply the video-sync setting. GLint value = sync_video ? 1 : 0; aglSetInteger(_aglcontext, AGL_SWAP_INTERVAL, &value); @@ -106,15 +106,15 @@ void osxGraphicsStateGuardian:: draw_resize_box() { // This state is created, once, and never freed. static CPT(RenderState) state; - if (state == (RenderState *)NULL) { + if (state == nullptr) { state = RenderState::make(TransparencyAttrib::make(TransparencyAttrib::M_alpha), DepthWriteAttrib::make(DepthWriteAttrib::M_off), DepthTestAttrib::make(DepthTestAttrib::M_none)); // Get the default texture to apply to the resize box; it's compiled into // the code. - string resize_box_string((const char *)resize_box, resize_box_len); - istringstream resize_box_strm(resize_box_string); + std::string resize_box_string((const char *)resize_box, resize_box_len); + std::istringstream resize_box_strm(resize_box_string); PNMImage resize_box_pnm; if (resize_box_pnm.read(resize_box_strm, "resize_box.rgb")) { PT(Texture) tex = new Texture; @@ -229,18 +229,18 @@ build_gl(bool full_screen, bool pbuffer, FrameBufferProperties &fb_props) { attrib.push_back(AGL_NONE); // build context - _aglcontext = NULL; + _aglcontext = nullptr; _aglPixFmt = aglChoosePixelFormat(&display, 1, &attrib[0]); err = report_agl_error("aglChoosePixelFormat"); if (_aglPixFmt) { - if(_share_with == NULL) { - _aglcontext = aglCreateContext(_aglPixFmt, NULL); + if(_share_with == nullptr) { + _aglcontext = aglCreateContext(_aglPixFmt, nullptr); } else { _aglcontext = aglCreateContext(_aglPixFmt, ((osxGraphicsStateGuardian *)_share_with)->_aglcontext); } err = report_agl_error("aglCreateContext"); - if (_aglcontext == NULL) { + if (_aglcontext == nullptr) { osxdisplay_cat.error() << "osxGraphicsStateGuardian::build_gl Error Getting GL Context \n" ; if(err == noErr) { @@ -348,9 +348,9 @@ describe_pixel_format(FrameBufferProperties &fb_props) { GLint ndevs; AGLDevice *gdevs = aglDevicesOfPixelFormat(_aglPixFmt, &ndevs); - if (gdevs != (AGLDevice *)NULL) { + if (gdevs != nullptr) { AGLRendererInfo rinfo = aglQueryRendererInfo(gdevs, ndevs); - if (rinfo != NULL) { + if (rinfo != nullptr) { if (aglDescribeRenderer(rinfo, AGL_ACCELERATED, &value)) { // Now we know whether it's hardware or software. fb_props.set_force_hardware(value); diff --git a/panda/src/osxdisplay/osxGraphicsWindow.h b/panda/src/osxdisplay/osxGraphicsWindow.h index 431f366da1..b797cc10f4 100644 --- a/panda/src/osxdisplay/osxGraphicsWindow.h +++ b/panda/src/osxdisplay/osxGraphicsWindow.h @@ -23,7 +23,7 @@ #include #define HACK_SCREEN_HASH_CONTEXT true -OSStatus report_agl_error(const string &comment); +OSStatus report_agl_error(const std::string &comment); /** * An interface to the osx/ system for managing GL windows under X. @@ -31,7 +31,7 @@ OSStatus report_agl_error(const string &comment); class osxGraphicsWindow : public GraphicsWindow { public: osxGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/pandabase/pandasymbols.h b/panda/src/pandabase/pandasymbols.h index beca549740..ef83b4314e 100644 --- a/panda/src/pandabase/pandasymbols.h +++ b/panda/src/pandabase/pandasymbols.h @@ -105,6 +105,33 @@ #define BUILDING_PANDA_TFORM #endif +/* BUILDING_PANDAEGG for these: */ +#ifdef BUILDING_PANDAEGG + #define BUILDING_PANDA_EGG + #define BUILDING_PANDA_EGG2PG +#endif + +/* BUILDING_PANDAEXPRESS for these: */ +#ifdef BUILDING_PANDAEXPRESS + #define BUILDING_PANDA_DOWNLOADER + #define BUILDING_PANDA_EXPRESS +#endif + +/* BUILDING_PANDAGL for these: */ +#ifdef BUILDING_PANDAGL + #define BUILDING_PANDA_COCOADISPLAY + #define BUILDING_PANDA_GLGSG + #define BUILDING_PANDA_GLXDISPLAY + #define BUILDING_PANDA_OSXDISPLAY + #define BUILDING_PANDA_WGLDISPLAY +#endif + +/* BUILDING_PANDAPHYSICS for these: */ +#ifdef BUILDING_PANDAPHYSICS + #define BUILDING_PANDA_PARTICLESYSTEM + #define BUILDING_PANDA_PHYSICS +#endif + #ifdef BUILDING_LIBPANDA #define EXPCL_LIBPANDA EXPORT_CLASS #define EXPTP_LIBPANDA EXPORT_TEMPL @@ -137,6 +164,14 @@ #define EXPTP_PANDA_CHAR IMPORT_TEMPL #endif +#ifdef BUILDING_PANDA_COCOADISPLAY + #define EXPCL_PANDA_COCOADISPLAY EXPORT_CLASS + #define EXPTP_PANDA_COCOADISPLAY EXPORT_TEMPL +#else + #define EXPCL_PANDA_COCOADISPLAY IMPORT_CLASS + #define EXPTP_PANDA_COCOADISPLAY IMPORT_TEMPL +#endif + #ifdef BUILDING_PANDA_COLLIDE #define EXPCL_PANDA_COLLIDE EXPORT_CLASS #define EXPTP_PANDA_COLLIDE EXPORT_TEMPL @@ -177,6 +212,14 @@ #define EXPTP_PANDA_DISPLAY IMPORT_TEMPL #endif +#ifdef BUILDING_PANDA_DOWNLOADER + #define EXPCL_PANDA_DOWNLOADER EXPORT_CLASS + #define EXPTP_PANDA_DOWNLOADER EXPORT_TEMPL +#else + #define EXPCL_PANDA_DOWNLOADER IMPORT_CLASS + #define EXPTP_PANDA_DOWNLOADER IMPORT_TEMPL +#endif + #ifdef BUILDING_PANDA_DXML #define EXPCL_PANDA_DXML EXPORT_CLASS #define EXPTP_PANDA_DXML EXPORT_TEMPL @@ -185,6 +228,22 @@ #define EXPTP_PANDA_DXML IMPORT_TEMPL #endif +#ifdef BUILDING_PANDA_EGG + #define EXPCL_PANDA_EGG EXPORT_CLASS + #define EXPTP_PANDA_EGG EXPORT_TEMPL +#else + #define EXPCL_PANDA_EGG IMPORT_CLASS + #define EXPTP_PANDA_EGG IMPORT_TEMPL +#endif + +#ifdef BUILDING_PANDA_EGG2PG + #define EXPCL_PANDA_EGG2PG EXPORT_CLASS + #define EXPTP_PANDA_EGG2PG EXPORT_TEMPL +#else + #define EXPCL_PANDA_EGG2PG IMPORT_CLASS + #define EXPTP_PANDA_EGG2PG IMPORT_TEMPL +#endif + #ifdef BUILDING_PANDA_EVENT #define EXPCL_PANDA_EVENT EXPORT_CLASS #define EXPTP_PANDA_EVENT EXPORT_TEMPL @@ -193,6 +252,30 @@ #define EXPTP_PANDA_EVENT IMPORT_TEMPL #endif +#ifdef BUILDING_PANDA_EXPRESS + #define EXPCL_PANDA_EXPRESS EXPORT_CLASS + #define EXPTP_PANDA_EXPRESS EXPORT_TEMPL +#else + #define EXPCL_PANDA_EXPRESS IMPORT_CLASS + #define EXPTP_PANDA_EXPRESS IMPORT_TEMPL +#endif + +#ifdef BUILDING_PANDA_GLGSG + #define EXPCL_PANDA_GLGSG EXPORT_CLASS + #define EXPTP_PANDA_GLGSG EXPORT_TEMPL +#else + #define EXPCL_PANDA_GLGSG IMPORT_CLASS + #define EXPTP_PANDA_GLGSG IMPORT_TEMPL +#endif + +#ifdef BUILDING_PANDA_GLXDISPLAY + #define EXPCL_PANDA_GLXDISPLAY EXPORT_CLASS + #define EXPTP_PANDA_GLXDISPLAY EXPORT_TEMPL +#else + #define EXPCL_PANDA_GLXDISPLAY IMPORT_CLASS + #define EXPTP_PANDA_GLXDISPLAY IMPORT_TEMPL +#endif + #ifdef BUILDING_PANDA_GOBJ #define EXPCL_PANDA_GOBJ EXPORT_CLASS #define EXPTP_PANDA_GOBJ EXPORT_TEMPL @@ -257,6 +340,14 @@ #define EXPTP_PANDA_NET IMPORT_TEMPL #endif +#ifdef BUILDING_PANDA_OSXDISPLAY + #define EXPCL_PANDA_OSXDISPLAY EXPORT_CLASS + #define EXPTP_PANDA_OSXDISPLAY EXPORT_TEMPL +#else + #define EXPCL_PANDA_OSXDISPLAY IMPORT_CLASS + #define EXPTP_PANDA_OSXDISPLAY IMPORT_TEMPL +#endif + #ifdef BUILDING_PANDA_PARAMETRICS #define EXPCL_PANDA_PARAMETRICS EXPORT_CLASS #define EXPTP_PANDA_PARAMETRICS EXPORT_TEMPL @@ -265,6 +356,14 @@ #define EXPTP_PANDA_PARAMETRICS IMPORT_TEMPL #endif +#ifdef BUILDING_PANDA_PARTICLESYSTEM + #define EXPCL_PANDA_PARTICLESYSTEM EXPORT_CLASS + #define EXPTP_PANDA_PARTICLESYSTEM EXPORT_TEMPL +#else + #define EXPCL_PANDA_PARTICLESYSTEM IMPORT_CLASS + #define EXPTP_PANDA_PARTICLESYSTEM IMPORT_TEMPL +#endif + #ifdef BUILDING_PANDA_PGRAPH #define EXPCL_PANDA_PGRAPH EXPORT_CLASS #define EXPTP_PANDA_PGRAPH EXPORT_TEMPL @@ -289,6 +388,14 @@ #define EXPTP_PANDA_PGUI IMPORT_TEMPL #endif +#ifdef BUILDING_PANDA_PHYSICS + #define EXPCL_PANDA_PHYSICS EXPORT_CLASS + #define EXPTP_PANDA_PHYSICS EXPORT_TEMPL +#else + #define EXPCL_PANDA_PHYSICS IMPORT_CLASS + #define EXPTP_PANDA_PHYSICS IMPORT_TEMPL +#endif + #ifdef BUILDING_PANDA_PIPELINE #define EXPCL_PANDA_PIPELINE EXPORT_CLASS #define EXPTP_PANDA_PIPELINE EXPORT_TEMPL @@ -361,6 +468,14 @@ #define EXPTP_PANDA_TFORM IMPORT_TEMPL #endif +#ifdef BUILDING_PANDA_WGLDISPLAY + #define EXPCL_PANDA_WGLDISPLAY EXPORT_CLASS + #define EXPTP_PANDA_WGLDISPLAY EXPORT_TEMPL +#else + #define EXPCL_PANDA_WGLDISPLAY IMPORT_CLASS + #define EXPTP_PANDA_WGLDISPLAY IMPORT_TEMPL +#endif + #ifdef BUILDING_PANDAAWESOMIUM #define EXPCL_PANDAAWESOMIUM EXPORT_CLASS #define EXPTP_PANDAAWESOMIUM EXPORT_TEMPL @@ -369,6 +484,14 @@ #define EXPTP_PANDAAWESOMIUM IMPORT_TEMPL #endif +#ifdef BUILDING_PANDAGL + #define EXPCL_PANDAGL EXPORT_CLASS + #define EXPTP_PANDAGL EXPORT_TEMPL +#else + #define EXPCL_PANDAGL IMPORT_CLASS + #define EXPTP_PANDAGL IMPORT_TEMPL +#endif + #ifdef BUILDING_PANDABULLET #define EXPCL_PANDABULLET EXPORT_CLASS #define EXPTP_PANDABULLET EXPORT_TEMPL @@ -393,14 +516,6 @@ #define EXPTP_PANDAEGG IMPORT_TEMPL #endif -#ifdef BUILDING_PANDAEXPRESS - #define EXPCL_PANDAEXPRESS EXPORT_CLASS - #define EXPTP_PANDAEXPRESS EXPORT_TEMPL -#else - #define EXPCL_PANDAEXPRESS IMPORT_CLASS - #define EXPTP_PANDAEXPRESS IMPORT_TEMPL -#endif - #ifdef BUILDING_PANDAFX #define EXPCL_PANDAFX EXPORT_CLASS #define EXPTP_PANDAFX EXPORT_TEMPL @@ -409,14 +524,6 @@ #define EXPTP_PANDAFX IMPORT_TEMPL #endif -#ifdef BUILDING_PANDAGL - #define EXPCL_PANDAGL EXPORT_CLASS - #define EXPTP_PANDAGL EXPORT_TEMPL -#else - #define EXPCL_PANDAGL IMPORT_CLASS - #define EXPTP_PANDAGL IMPORT_TEMPL -#endif - #ifdef BUILDING_PANDAGLES #define EXPCL_PANDAGLES EXPORT_CLASS #define EXPTP_PANDAGLES EXPORT_TEMPL diff --git a/panda/src/parametrics/cubicCurveseg.cxx b/panda/src/parametrics/cubicCurveseg.cxx index 6bd2dcef6f..dcb5905cfa 100644 --- a/panda/src/parametrics/cubicCurveseg.cxx +++ b/panda/src/parametrics/cubicCurveseg.cxx @@ -234,7 +234,7 @@ compute_nurbs_basis(int order, if (mink==maxk) { // Huh. What were you thinking? This is a trivial NURBS. parametrics_cat->warning() - << "Trivial NURBS curve specified." << endl; + << "Trivial NURBS curve specified." << std::endl; memset((void *)&basis, 0, sizeof(LMatrix4)); return; } @@ -409,7 +409,7 @@ compute_seg_col(int c, break; default: - cerr << "Invalid rebuild type in compute_seg\n"; + std::cerr << "Invalid rebuild type in compute_seg\n"; return false; } diff --git a/panda/src/parametrics/curveFitter.I b/panda/src/parametrics/curveFitter.I index 24c4874338..57e645cd08 100644 --- a/panda/src/parametrics/curveFitter.I +++ b/panda/src/parametrics/curveFitter.I @@ -28,7 +28,7 @@ DataPoint() : * */ INLINE void CurveFitter::DataPoint:: -output(ostream &out) const { +output(std::ostream &out) const { out << "Time " << _t << " xyz " << _xyz << " hpr " << _hpr << " tan " << _tangent; } diff --git a/panda/src/parametrics/curveFitter.cxx b/panda/src/parametrics/curveFitter.cxx index 6592d7aff2..275a270a4b 100644 --- a/panda/src/parametrics/curveFitter.cxx +++ b/panda/src/parametrics/curveFitter.cxx @@ -137,8 +137,8 @@ get_sample_tangent(int n) const { */ void CurveFitter:: remove_samples(int begin, int end) { - begin = max(0, min((int)_data.size(), begin)); - end = max(0, min((int)_data.size(), end)); + begin = std::max(0, std::min((int)_data.size(), begin)); + end = std::max(0, std::min((int)_data.size(), end)); nassertv(begin <= end); @@ -152,7 +152,7 @@ remove_samples(int begin, int end) { */ void CurveFitter:: sample(ParametricCurveCollection *curves, int count) { - nassertv(curves != (ParametricCurveCollection *)NULL); + nassertv(curves != nullptr); PN_stdfloat max_t = curves->get_max_t(); PN_stdfloat t; DataPoint dp; @@ -166,10 +166,10 @@ sample(ParametricCurveCollection *curves, int count) { } } - if (curves->get_xyz_curve() != (ParametricCurve *)NULL) { + if (curves->get_xyz_curve() != nullptr) { _got_xyz = true; } - if (curves->get_hpr_curve() != (ParametricCurve *)NULL) { + if (curves->get_hpr_curve() != nullptr) { _got_hpr = true; } } @@ -411,7 +411,7 @@ make_nurbs() const { * */ void CurveFitter:: -output(ostream &out) const { +output(std::ostream &out) const { out << "CurveFitter, " << _data.size() << " samples.\n"; } @@ -419,7 +419,7 @@ output(ostream &out) const { * */ void CurveFitter:: -write(ostream &out) const { +write(std::ostream &out) const { out << "CurveFitter, " << _data.size() << " samples:\n"; Data::const_iterator di; for (di = _data.begin(); di != _data.end(); ++di) { diff --git a/panda/src/parametrics/curveFitter.h b/panda/src/parametrics/curveFitter.h index a83778951f..0e63525ab8 100644 --- a/panda/src/parametrics/curveFitter.h +++ b/panda/src/parametrics/curveFitter.h @@ -30,7 +30,7 @@ class NurbsCurve; /** * */ -class EXPCL_PANDA_GOBJ CurveFitter { +class EXPCL_PANDA_PARAMETRICS CurveFitter { PUBLISHED: CurveFitter(); ~CurveFitter(); @@ -56,14 +56,14 @@ PUBLISHED: PT(ParametricCurveCollection) make_hermite() const; PT(ParametricCurveCollection) make_nurbs() const; - void output(ostream &out) const; - void write(ostream &out) const; + void output(std::ostream &out) const; + void write(std::ostream &out) const; public: class DataPoint { public: INLINE DataPoint(); - INLINE void output(ostream &out) const; + INLINE void output(std::ostream &out) const; INLINE bool operator < (const DataPoint &other) const; PN_stdfloat _t; @@ -91,12 +91,12 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const CurveFitter::DataPoint &dp) { +INLINE std::ostream &operator << (std::ostream &out, const CurveFitter::DataPoint &dp) { dp.output(out); return out; } -INLINE ostream &operator << (ostream &out, const CurveFitter &cf) { +INLINE std::ostream &operator << (std::ostream &out, const CurveFitter &cf) { cf.output(out); return out; } diff --git a/panda/src/parametrics/hermiteCurve.cxx b/panda/src/parametrics/hermiteCurve.cxx index 73931ab001..7bb2399368 100644 --- a/panda/src/parametrics/hermiteCurve.cxx +++ b/panda/src/parametrics/hermiteCurve.cxx @@ -24,6 +24,9 @@ #include +using std::ostream; +using std::string; + TypeHandle HermiteCurve::_type_handle; static const LVecBase3 zerovec_3 = LVecBase3(0.0f, 0.0f, 0.0f); @@ -246,7 +249,7 @@ HermiteCurve(const ParametricCurve &nc) { if (!nc.convert_to_hermite(this)) { parametrics_cat->warning() << "Cannot make a Hermite from the indicated curve." - << endl; + << std::endl; } } @@ -291,7 +294,7 @@ insert_cv(PN_stdfloat t) { return n; } - t = min(max(t, (PN_stdfloat)0.0), get_max_t()); + t = std::min(std::max(t, (PN_stdfloat)0.0), get_max_t()); int n = find_cv(t); nassertr(n+1= 0 && i < (int)_vertices.size()); _vertices[i].set_space(space); } @@ -175,8 +175,8 @@ get_num_segments() const { return _basis.get_num_segments(); } -INLINE ostream & -operator << (ostream &out, const NurbsCurveEvaluator &n) { +INLINE std::ostream & +operator << (std::ostream &out, const NurbsCurveEvaluator &n) { n.output(out); return out; } diff --git a/panda/src/parametrics/nurbsCurveEvaluator.cxx b/panda/src/parametrics/nurbsCurveEvaluator.cxx index d04df9ab9e..89641483b2 100644 --- a/panda/src/parametrics/nurbsCurveEvaluator.cxx +++ b/panda/src/parametrics/nurbsCurveEvaluator.cxx @@ -177,7 +177,7 @@ evaluate(const NodePath &rel_to, const LMatrix4 &mat) const { * */ void NurbsCurveEvaluator:: -output(ostream &out) const { +output(std::ostream &out) const { out << "NurbsCurve, " << get_num_knots() << " knots."; } diff --git a/panda/src/parametrics/nurbsCurveEvaluator.h b/panda/src/parametrics/nurbsCurveEvaluator.h index 86e3a79996..1a4192242d 100644 --- a/panda/src/parametrics/nurbsCurveEvaluator.h +++ b/panda/src/parametrics/nurbsCurveEvaluator.h @@ -54,7 +54,7 @@ PUBLISHED: MAKE_SEQ(get_vertices, get_num_vertices, get_vertex); INLINE void set_vertex_space(int i, const NodePath &space); - INLINE void set_vertex_space(int i, const string &space); + INLINE void set_vertex_space(int i, const std::string &space); NodePath get_vertex_space(int i, const NodePath &rel_to) const; INLINE void set_extended_vertex(int i, int d, PN_stdfloat value); @@ -74,7 +74,7 @@ PUBLISHED: PT(NurbsCurveResult) evaluate(const NodePath &rel_to, const LMatrix4 &mat) const; - void output(ostream &out) const; + void output(std::ostream &out) const; public: typedef epvector Vert4Array; @@ -99,7 +99,7 @@ private: NurbsBasisVector _basis; }; -INLINE ostream &operator << (ostream &out, const NurbsCurveEvaluator &n); +INLINE std::ostream &operator << (std::ostream &out, const NurbsCurveEvaluator &n); #include "nurbsCurveEvaluator.I" diff --git a/panda/src/parametrics/nurbsCurveInterface.cxx b/panda/src/parametrics/nurbsCurveInterface.cxx index 9c9affa03d..19b60957f4 100644 --- a/panda/src/parametrics/nurbsCurveInterface.cxx +++ b/panda/src/parametrics/nurbsCurveInterface.cxx @@ -44,7 +44,7 @@ set_cv_weight(int n, PN_stdfloat w) { * */ void NurbsCurveInterface:: -write_cv(ostream &out, int n) const { +write_cv(std::ostream &out, int n) const { nassertv(n >= 0 && n < get_num_cvs()); out << "CV " << n << ": " << get_cv_point(n) << ", weight " @@ -55,7 +55,7 @@ write_cv(ostream &out, int n) const { * */ void NurbsCurveInterface:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level); PN_stdfloat min_t = 0.0f; @@ -93,7 +93,7 @@ write(ostream &out, int indent_level) const { * Formats the Nurbs curve for output to an Egg file. */ bool NurbsCurveInterface:: -format_egg(ostream &out, const string &name, const string &curve_type, +format_egg(std::ostream &out, const std::string &name, const std::string &curve_type, int indent_level) const { indent(out, indent_level) << " " << name << ".pool {\n"; @@ -156,7 +156,7 @@ format_egg(ostream &out, const string &name, const string &curve_type, bool NurbsCurveInterface:: convert_to_nurbs(ParametricCurve *nc) const { NurbsCurveInterface *nurbs = nc->get_nurbs_interface(); - nassertr(nurbs != (NurbsCurveInterface *)NULL, false); + nassertr(nurbs != nullptr, false); nurbs->remove_all_cvs(); nurbs->set_order(get_order()); diff --git a/panda/src/parametrics/nurbsCurveInterface.h b/panda/src/parametrics/nurbsCurveInterface.h index ef09c78275..e37a24d07e 100644 --- a/panda/src/parametrics/nurbsCurveInterface.h +++ b/panda/src/parametrics/nurbsCurveInterface.h @@ -61,14 +61,14 @@ PUBLISHED: MAKE_SEQ(get_cvs, get_num_cvs, get_cv); MAKE_SEQ(get_knots, get_num_knots, get_knot); - void write_cv(ostream &out, int n) const; + void write_cv(std::ostream &out, int n) const; protected: virtual int append_cv_impl(const LVecBase4 &v)=0; - void write(ostream &out, int indent_level) const; - bool format_egg(ostream &out, const string &name, - const string &curve_type, int indent_level) const; + void write(std::ostream &out, int indent_level) const; + bool format_egg(std::ostream &out, const std::string &name, + const std::string &curve_type, int indent_level) const; bool convert_to_nurbs(ParametricCurve *nc) const; diff --git a/panda/src/parametrics/nurbsSurfaceEvaluator.I b/panda/src/parametrics/nurbsSurfaceEvaluator.I index c00408dd5f..26c0f9c0e0 100644 --- a/panda/src/parametrics/nurbsSurfaceEvaluator.I +++ b/panda/src/parametrics/nurbsSurfaceEvaluator.I @@ -155,7 +155,7 @@ set_vertex_space(int ui, int vi, const NodePath &space) { * node relative to the rel_to NodePath when the surface is evaluated. */ INLINE void NurbsSurfaceEvaluator:: -set_vertex_space(int ui, int vi, const string &space) { +set_vertex_space(int ui, int vi, const std::string &space) { nassertv(ui >= 0 && ui < _num_u_vertices && vi >= 0 && vi < _num_v_vertices); vert(ui, vi).set_space(space); @@ -255,8 +255,8 @@ vert(int ui, int vi) const { return _vertices[ui * _num_v_vertices + vi]; } -INLINE ostream & -operator << (ostream &out, const NurbsSurfaceEvaluator &n) { +INLINE std::ostream & +operator << (std::ostream &out, const NurbsSurfaceEvaluator &n) { n.output(out); return out; } diff --git a/panda/src/parametrics/nurbsSurfaceEvaluator.cxx b/panda/src/parametrics/nurbsSurfaceEvaluator.cxx index 12ed399a9d..33d1ce0a81 100644 --- a/panda/src/parametrics/nurbsSurfaceEvaluator.cxx +++ b/panda/src/parametrics/nurbsSurfaceEvaluator.cxx @@ -212,7 +212,7 @@ evaluate(const NodePath &rel_to) const { * */ void NurbsSurfaceEvaluator:: -output(ostream &out) const { +output(std::ostream &out) const { out << "NurbsSurface, (" << get_num_u_knots() << ", " << get_num_v_knots() << ") knots."; } diff --git a/panda/src/parametrics/nurbsSurfaceEvaluator.h b/panda/src/parametrics/nurbsSurfaceEvaluator.h index a2f468d716..ced1013016 100644 --- a/panda/src/parametrics/nurbsSurfaceEvaluator.h +++ b/panda/src/parametrics/nurbsSurfaceEvaluator.h @@ -52,7 +52,7 @@ PUBLISHED: INLINE LVecBase4 get_vertex(int ui, int vi, const NodePath &rel_to) const; INLINE void set_vertex_space(int ui, int vi, const NodePath &space); - INLINE void set_vertex_space(int ui, int vi, const string &space); + INLINE void set_vertex_space(int ui, int vi, const std::string &space); NodePath get_vertex_space(int ui, int vi, const NodePath &rel_to) const; INLINE void set_extended_vertex(int ui, int vi, int d, PN_stdfloat value); @@ -77,7 +77,7 @@ PUBLISHED: PT(NurbsSurfaceResult) evaluate(const NodePath &rel_to = NodePath()) const; - void output(ostream &out) const; + void output(std::ostream &out) const; MAKE_PROPERTY(u_order, get_u_order, set_u_order); MAKE_PROPERTY(v_order, get_v_order, set_v_order); @@ -119,7 +119,7 @@ private: NurbsBasisVector _v_basis; }; -INLINE ostream &operator << (ostream &out, const NurbsSurfaceEvaluator &n); +INLINE std::ostream &operator << (std::ostream &out, const NurbsSurfaceEvaluator &n); #include "nurbsSurfaceEvaluator.I" diff --git a/panda/src/parametrics/nurbsSurfaceResult.cxx b/panda/src/parametrics/nurbsSurfaceResult.cxx index e1bfccb168..86b6f6615f 100644 --- a/panda/src/parametrics/nurbsSurfaceResult.cxx +++ b/panda/src/parametrics/nurbsSurfaceResult.cxx @@ -62,10 +62,10 @@ NurbsSurfaceResult(const NurbsBasisVector &u_basis, // Create four geometry matrices from our (up to) sixteen involved // vertices. LMatrix4 geom_x, geom_y, geom_z, geom_w; - memset(&geom_x, 0, sizeof(geom_x)); - memset(&geom_y, 0, sizeof(geom_y)); - memset(&geom_z, 0, sizeof(geom_z)); - memset(&geom_w, 0, sizeof(geom_w)); + geom_x.fill(0); + geom_y.fill(0); + geom_z.fill(0); + geom_w.fill(0); for (int uni = 0; uni < 4; uni++) { for (int vni = 0; vni < 4; vni++) { @@ -178,7 +178,7 @@ eval_segment_extended_point(int ui, int vi, PN_stdfloat u, PN_stdfloat v, int d) int vn = _v_basis.get_vertex_index(vi); LMatrix4 geom; - memset(&geom, 0, sizeof(geom)); + geom.fill(0); for (int uni = 0; uni < 4; uni++) { for (int vni = 0; vni < 4; vni++) { @@ -223,7 +223,7 @@ eval_segment_extended_points(int ui, int vi, PN_stdfloat u, PN_stdfloat v, int d for (int n = 0; n < num_values; n++) { LMatrix4 geom; - memset(&geom, 0, sizeof(geom)); + geom.fill(0); for (int uni = 0; uni < 4; uni++) { for (int vni = 0; vni < 4; vni++) { diff --git a/panda/src/parametrics/nurbsVertex.I b/panda/src/parametrics/nurbsVertex.I index cd6c344ac9..75a23a59e1 100644 --- a/panda/src/parametrics/nurbsVertex.I +++ b/panda/src/parametrics/nurbsVertex.I @@ -69,14 +69,14 @@ get_vertex() const { INLINE void NurbsVertex:: set_space(const NodePath &space) { _space = space; - _space_path = string(); + _space_path = std::string(); } /** * Sets the space of this vertex as a relative path from the rel_to node. */ INLINE void NurbsVertex:: -set_space(const string &space) { +set_space(const std::string &space) { _space = NodePath(); _space_path = space; } diff --git a/panda/src/parametrics/nurbsVertex.h b/panda/src/parametrics/nurbsVertex.h index 7369f3a1e6..751b36f335 100644 --- a/panda/src/parametrics/nurbsVertex.h +++ b/panda/src/parametrics/nurbsVertex.h @@ -40,7 +40,7 @@ public: INLINE const LVecBase4 &get_vertex() const; INLINE void set_space(const NodePath &space); - INLINE void set_space(const string &space); + INLINE void set_space(const std::string &space); INLINE NodePath get_space(const NodePath &rel_to) const; void set_extended_vertex(int d, PN_stdfloat value); @@ -49,7 +49,7 @@ public: private: LVecBase4 _vertex; NodePath _space; - string _space_path; + std::string _space_path; typedef pmap Extended; Extended _extended; }; diff --git a/panda/src/parametrics/parametricCurve.cxx b/panda/src/parametrics/parametricCurve.cxx index 403f9e8c04..9893c65604 100644 --- a/panda/src/parametrics/parametricCurve.cxx +++ b/panda/src/parametrics/parametricCurve.cxx @@ -321,8 +321,8 @@ write_egg(Filename filename, CoordinateSystem cs) { * stream. Returns true if the file is successfully written. */ bool ParametricCurve:: -write_egg(ostream &out, const Filename &filename, CoordinateSystem cs) { - string curve_type; +write_egg(std::ostream &out, const Filename &filename, CoordinateSystem cs) { + std::string curve_type; switch (get_curve_type()) { case PCT_XYZ: curve_type = "xyz"; @@ -339,7 +339,7 @@ write_egg(ostream &out, const Filename &filename, CoordinateSystem cs) { if (!has_name()) { // If we don't have a name, come up with one. - string name = filename.get_basename_wo_extension(); + std::string name = filename.get_basename_wo_extension(); if (!curve_type.empty()) { name += "_"; @@ -418,7 +418,7 @@ get_bezier_seg(ParametricCurve::BezierSeg &) const { */ NurbsCurveInterface *ParametricCurve:: get_nurbs_interface() { - return (NurbsCurveInterface *)NULL; + return nullptr; } /** @@ -497,7 +497,7 @@ convert_to_hermite(HermiteCurve *hc) const { bool ParametricCurve:: convert_to_nurbs(ParametricCurve *nc) const { NurbsCurveInterface *nurbs = nc->get_nurbs_interface(); - nassertr(nurbs != (NurbsCurveInterface *)NULL, false); + nassertr(nurbs != nullptr, false); BezierSegs bz_segs; if (!get_bezier_segs(bz_segs)) { @@ -602,7 +602,7 @@ invalidate_all() { * Returns true on success, false on failure. */ bool ParametricCurve:: -format_egg(ostream &, const string &, const string &, int) const { +format_egg(std::ostream &, const std::string &, const std::string &, int) const { return false; } diff --git a/panda/src/parametrics/parametricCurve.h b/panda/src/parametrics/parametricCurve.h index aa4dfc8f2d..0cb5d7fb9d 100644 --- a/panda/src/parametrics/parametricCurve.h +++ b/panda/src/parametrics/parametricCurve.h @@ -93,7 +93,7 @@ PUBLISHED: virtual bool stitch(const ParametricCurve *a, const ParametricCurve *b); bool write_egg(Filename filename, CoordinateSystem cs = CS_default); - bool write_egg(ostream &out, const Filename &filename, CoordinateSystem cs); + bool write_egg(std::ostream &out, const Filename &filename, CoordinateSystem cs); public: struct BezierSeg { @@ -117,8 +117,8 @@ protected: void invalidate(PN_stdfloat t1, PN_stdfloat t2); void invalidate_all(); - virtual bool format_egg(ostream &out, const string &name, - const string &curve_type, int indent_level) const; + virtual bool format_egg(std::ostream &out, const std::string &name, + const std::string &curve_type, int indent_level) const; private: PN_stdfloat r_calc_length(PN_stdfloat t1, PN_stdfloat t2, diff --git a/panda/src/parametrics/parametricCurveCollection.I b/panda/src/parametrics/parametricCurveCollection.I index 07fd5e9f26..711b43b67b 100644 --- a/panda/src/parametrics/parametricCurveCollection.I +++ b/panda/src/parametrics/parametricCurveCollection.I @@ -31,7 +31,7 @@ get_num_curves() const { */ INLINE ParametricCurve *ParametricCurveCollection:: get_curve(int index) const { - nassertr(index >= 0 && index < (int)_curves.size(), (ParametricCurve *)NULL); + nassertr(index >= 0 && index < (int)_curves.size(), nullptr); return _curves[index]; } @@ -42,7 +42,7 @@ get_curve(int index) const { */ INLINE void ParametricCurveCollection:: add_curve(ParametricCurve *curve, int index) { - insert_curve(max(index, 0), curve); + insert_curve(std::max(index, 0), curve); } /** diff --git a/panda/src/parametrics/parametricCurveCollection.cxx b/panda/src/parametrics/parametricCurveCollection.cxx index 45d61ccfe8..96ce9bd503 100644 --- a/panda/src/parametrics/parametricCurveCollection.cxx +++ b/panda/src/parametrics/parametricCurveCollection.cxx @@ -44,7 +44,7 @@ add_curve(ParametricCurve *curve) { void ParametricCurveCollection:: insert_curve(size_t index, ParametricCurve *curve) { prepare_add_curve(curve); - index = min(index, _curves.size()); + index = std::min(index, _curves.size()); _curves.insert(_curves.begin() + index, curve); redraw(); } @@ -150,8 +150,8 @@ clear() { */ void ParametricCurveCollection:: clear_timewarps() { - PT(ParametricCurve) xyz_curve = (ParametricCurve *)NULL; - PT(ParametricCurve) hpr_curve = (ParametricCurve *)NULL; + PT(ParametricCurve) xyz_curve = nullptr; + PT(ParametricCurve) hpr_curve = nullptr; ParametricCurves::iterator ci; for (ci = _curves.begin(); ci != _curves.end(); ++ci) { @@ -159,7 +159,7 @@ clear_timewarps() { switch (curve->get_curve_type()) { case PCT_XYZ: - if (xyz_curve == (ParametricCurve *)NULL) { + if (xyz_curve == nullptr) { xyz_curve = curve; } else { prepare_remove_curve(curve); @@ -167,7 +167,7 @@ clear_timewarps() { break; case PCT_HPR: - if (hpr_curve == (ParametricCurve *)NULL) { + if (hpr_curve == nullptr) { hpr_curve = curve; } else { prepare_remove_curve(curve); @@ -182,7 +182,7 @@ clear_timewarps() { _curves.clear(); _curves.push_back(xyz_curve); - if (hpr_curve != (ParametricCurve *)NULL) { + if (hpr_curve != nullptr) { _curves.push_back(hpr_curve); } @@ -202,7 +202,7 @@ get_xyz_curve() const { return curve; } } - return (ParametricCurve *)NULL; + return nullptr; } /** @@ -218,7 +218,7 @@ get_hpr_curve() const { return curve; } } - return (ParametricCurve *)NULL; + return nullptr; } /** @@ -229,7 +229,7 @@ get_hpr_curve() const { ParametricCurve *ParametricCurveCollection:: get_default_curve() const { ParametricCurve *xyz_curve = get_xyz_curve(); - if (xyz_curve != (ParametricCurve *)NULL) { + if (xyz_curve != nullptr) { return xyz_curve; } @@ -240,7 +240,7 @@ get_default_curve() const { return curve; } } - return (ParametricCurve *)NULL; + return nullptr; } /** @@ -276,8 +276,8 @@ get_timewarp_curve(int n) const { n--; } } - nassertr(false, (ParametricCurve *)NULL); - return (ParametricCurve *)NULL; + nassertr(false, nullptr); + return nullptr; } /** @@ -295,7 +295,7 @@ get_timewarp_curve(int n) const { void ParametricCurveCollection:: make_even(PN_stdfloat max_t, PN_stdfloat segments_per_unit) { ParametricCurve *xyz_curve = get_xyz_curve(); - if (xyz_curve == (ParametricCurve *)NULL) { + if (xyz_curve == nullptr) { parametrics_cat.error() << "No XYZ curve for make_even().\n"; return; @@ -307,7 +307,7 @@ make_even(PN_stdfloat max_t, PN_stdfloat segments_per_unit) { // the same length as all the others. CurveFitter fitter; - int num_segments = max(1, (int)cfloor(segments_per_unit * xyz_curve->get_max_t() + 0.5f)); + int num_segments = std::max(1, (int)cfloor(segments_per_unit * xyz_curve->get_max_t() + 0.5f)); if (parametrics_cat.is_debug()) { parametrics_cat.debug() @@ -349,7 +349,7 @@ make_even(PN_stdfloat max_t, PN_stdfloat segments_per_unit) { fitter.compute_tangents(1); PT(ParametricCurveCollection) fit = fitter.make_nurbs(); ParametricCurve *t_curve = fit->get_xyz_curve(); - nassertv(t_curve != (ParametricCurve *)NULL); + nassertv(t_curve != nullptr); t_curve->set_curve_type(PCT_T); add_curve(t_curve); } @@ -362,7 +362,7 @@ make_even(PN_stdfloat max_t, PN_stdfloat segments_per_unit) { void ParametricCurveCollection:: face_forward(PN_stdfloat segments_per_unit) { ParametricCurve *xyz_curve = get_xyz_curve(); - if (xyz_curve == (ParametricCurve *)NULL) { + if (xyz_curve == nullptr) { parametrics_cat.error() << "No XYZ curve for face_forward().\n"; return; @@ -412,7 +412,7 @@ face_forward(PN_stdfloat segments_per_unit) { fitter.compute_tangents(1); PT(ParametricCurveCollection) fit = fitter.make_nurbs(); ParametricCurve *hpr_curve = fit->get_hpr_curve(); - nassertv(hpr_curve != (ParametricCurve *)NULL); + nassertv(hpr_curve != nullptr); add_curve(hpr_curve, xyz_index + 1); } @@ -452,9 +452,9 @@ bool ParametricCurveCollection:: evaluate(PN_stdfloat t, LVecBase3 &xyz, LVecBase3 &hpr) const { // First, apply all the timewarps in sequence, from back to front. Also // take note of the XYZ and HPR curves. - ParametricCurve *xyz_curve = (ParametricCurve *)NULL; - ParametricCurve *hpr_curve = (ParametricCurve *)NULL; - ParametricCurve *default_curve = (ParametricCurve *)NULL; + ParametricCurve *xyz_curve = nullptr; + ParametricCurve *hpr_curve = nullptr; + ParametricCurve *default_curve = nullptr; PN_stdfloat t0 = t; LVecBase3 point; @@ -484,18 +484,18 @@ evaluate(PN_stdfloat t, LVecBase3 &xyz, LVecBase3 &hpr) const { } } - if (xyz_curve == (ParametricCurve *)NULL) { + if (xyz_curve == nullptr) { xyz_curve = default_curve; } // Now compute the position and orientation. - if (xyz_curve != (ParametricCurve *)NULL) { + if (xyz_curve != nullptr) { if (!xyz_curve->get_point(t0, xyz)) { return false; } } - if (hpr_curve != (ParametricCurve *)NULL) { + if (hpr_curve != nullptr) { if (!hpr_curve->get_point(t0, hpr)) { return false; } @@ -564,7 +564,7 @@ evaluate_t(PN_stdfloat t) const { bool ParametricCurveCollection:: adjust_xyz(PN_stdfloat t, const LVecBase3 &xyz) { ParametricCurve *xyz_curve = get_xyz_curve(); - if (xyz_curve == (ParametricCurve *)NULL) { + if (xyz_curve == nullptr) { return false; } @@ -583,7 +583,7 @@ adjust_xyz(PN_stdfloat t, const LVecBase3 &xyz) { bool ParametricCurveCollection:: adjust_hpr(PN_stdfloat t, const LVecBase3 &hpr) { ParametricCurve *hpr_curve = get_hpr_curve(); - if (hpr_curve == (ParametricCurve *)NULL) { + if (hpr_curve == nullptr) { return false; } @@ -631,7 +631,7 @@ stitch(const ParametricCurveCollection *a, clear(); - if (a_xyz != (ParametricCurve *)NULL && b_xyz != (ParametricCurve *)NULL) { + if (a_xyz != nullptr && b_xyz != nullptr) { PT(NurbsCurve) new_xyz = new NurbsCurve; if (!new_xyz->stitch(a_xyz, b_xyz)) { return false; @@ -640,7 +640,7 @@ stitch(const ParametricCurveCollection *a, add_curve(new_xyz); } - if (a_hpr != (ParametricCurve *)NULL && b_hpr != (ParametricCurve *)NULL) { + if (a_hpr != nullptr && b_hpr != nullptr) { PT(NurbsCurve) new_hpr = new NurbsCurve; if (!new_hpr->stitch(a_hpr, b_hpr)) { return false; @@ -657,7 +657,7 @@ stitch(const ParametricCurveCollection *a, * indicated output stream. */ void ParametricCurveCollection:: -output(ostream &out) const { +output(std::ostream &out) const { if (get_num_curves() == 1) { out << "1 ParametricCurve"; } else { @@ -670,7 +670,7 @@ output(ostream &out) const { * to the indicated output stream. */ void ParametricCurveCollection:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { ParametricCurves::const_iterator ci; for (ci = _curves.begin(); ci != _curves.end(); ++ci) { ParametricCurve *curve = (*ci); @@ -700,7 +700,7 @@ write_egg(Filename filename, CoordinateSystem cs) { * specified output stream. Returns true if the file is successfully written. */ bool ParametricCurveCollection:: -write_egg(ostream &out, const Filename &filename, CoordinateSystem cs) { +write_egg(std::ostream &out, const Filename &filename, CoordinateSystem cs) { if (cs == CS_default) { cs = get_default_coordinate_system(); } @@ -740,7 +740,7 @@ write_egg(ostream &out, const Filename &filename, CoordinateSystem cs) { if (!curve->has_name()) { // If we don't have a name, come up with one. - string name = filename.get_basename_wo_extension(); + std::string name = filename.get_basename_wo_extension(); switch (curve->get_curve_type()) { case PCT_XYZ: diff --git a/panda/src/parametrics/parametricCurveCollection.h b/panda/src/parametrics/parametricCurveCollection.h index 44e588dd89..18a79c5dc8 100644 --- a/panda/src/parametrics/parametricCurveCollection.h +++ b/panda/src/parametrics/parametricCurveCollection.h @@ -91,11 +91,11 @@ PUBLISHED: bool stitch(const ParametricCurveCollection *a, const ParametricCurveCollection *b); - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; bool write_egg(Filename filename, CoordinateSystem cs = CS_default); - bool write_egg(ostream &out, const Filename &filename, CoordinateSystem cs); + bool write_egg(std::ostream &out, const Filename &filename, CoordinateSystem cs); public: int r_add_curves(PandaNode *node); @@ -115,8 +115,8 @@ private: DrawerList _drawers; }; -INLINE ostream & -operator << (ostream &out, const ParametricCurveCollection &col) { +INLINE std::ostream & +operator << (std::ostream &out, const ParametricCurveCollection &col) { col.output(out); return out; } diff --git a/panda/src/parametrics/piecewiseCurve.cxx b/panda/src/parametrics/piecewiseCurve.cxx index cbaa7497f6..f5e2fadad9 100644 --- a/panda/src/parametrics/piecewiseCurve.cxx +++ b/panda/src/parametrics/piecewiseCurve.cxx @@ -20,6 +20,8 @@ #include "bamWriter.h" #include "bamReader.h" +using std::cerr; + TypeHandle PiecewiseCurve::_type_handle; /** @@ -68,7 +70,7 @@ bool PiecewiseCurve:: get_point(PN_stdfloat t, LVecBase3 &point) const { const ParametricCurve *curve; bool result = find_curve(curve, t); - if (curve == NULL){ + if (curve == nullptr){ return false; } // We use | instead of || so we won't short-circuit this calculation. @@ -438,7 +440,7 @@ find_curve(const ParametricCurve *&curve, PN_stdfloat &t) const { if (ti >= (int)_segs.size()) { if (_segs.empty()) { - curve = NULL; + curve = nullptr; t = 0.0f; return false; } else { @@ -523,7 +525,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { for (i = 0; i < num_segs; i++) { Curveseg seg; manager->read_pointer(scan); - seg._curve = (ParametricCurve *)NULL; + seg._curve = nullptr; seg._tend = scan.get_float64(); _segs.push_back(seg); } diff --git a/panda/src/parametrics/ropeNode.cxx b/panda/src/parametrics/ropeNode.cxx index 365795adf7..ffb2c83119 100644 --- a/panda/src/parametrics/ropeNode.cxx +++ b/panda/src/parametrics/ropeNode.cxx @@ -50,7 +50,7 @@ void RopeNode::CData:: write_datagram(BamWriter *writer, Datagram &dg) const { // For now, we write a NULL pointer. Eventually we will write out the // NurbsCurveEvaluator pointer. - writer->write_pointer(dg, (TypedWritable *)NULL); + writer->write_pointer(dg, nullptr); } /** @@ -67,7 +67,7 @@ fillin(DatagramIterator &scan, BamReader *reader) { * */ RopeNode:: -RopeNode(const string &name) : +RopeNode(const std::string &name) : PandaNode(name) { set_cull_callback(); @@ -129,7 +129,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { // Create some geometry on-the-fly to render the rope. if (get_num_subdiv() > 0) { NurbsCurveEvaluator *curve = get_curve(); - if (curve != (NurbsCurveEvaluator *)NULL) { + if (curve != nullptr) { PT(NurbsCurveResult) result; if (has_matrix()) { result = curve->evaluate(data.get_node_path(), get_matrix()); @@ -177,10 +177,10 @@ is_renderable() const { * */ void RopeNode:: -output(ostream &out) const { +output(std::ostream &out) const { PandaNode::output(out); NurbsCurveEvaluator *curve = get_curve(); - if (curve != (NurbsCurveEvaluator *)NULL) { + if (curve != nullptr) { out << " " << *curve; } else { out << " (no curve)"; @@ -191,7 +191,7 @@ output(ostream &out) const { * */ void RopeNode:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { PandaNode::write(out, indent_level); indent(out, indent_level) << *get_curve() << "\n"; } @@ -270,7 +270,7 @@ do_recompute_bounds(const NodePath &rel_to, int pipeline_stage, PT(BoundingVolume) bound = new BoundingSphere; NurbsCurveEvaluator *curve = get_curve(); - if (curve != (NurbsCurveEvaluator *)NULL) { + if (curve != nullptr) { NurbsCurveEvaluator::Vert3Array verts; get_curve()->get_vertices(verts, rel_to); @@ -519,14 +519,14 @@ get_connected_segments(RopeNode::CurveSegments &curve_segments, bool use_vertex_color = get_use_vertex_color(); bool use_vertex_thickness = get_use_vertex_thickness(); - CurveSegment *curve_segment = NULL; + CurveSegment *curve_segment = nullptr; LPoint3 last_point; for (int segment = 0; segment < num_segments; ++segment) { LPoint3 point; result->eval_segment_point(segment, 0.0f, point); - if (curve_segment == (CurveSegment *)NULL || + if (curve_segment == nullptr || !point.almost_equal(last_point)) { // If the first point of this segment is different from the last point // of the previous segment, end the previous segment and begin a new diff --git a/panda/src/parametrics/ropeNode.h b/panda/src/parametrics/ropeNode.h index 063070c802..e4647e304d 100644 --- a/panda/src/parametrics/ropeNode.h +++ b/panda/src/parametrics/ropeNode.h @@ -33,13 +33,13 @@ class GeomVertexData; */ class EXPCL_PANDA_PARAMETRICS RopeNode : public PandaNode { PUBLISHED: - explicit RopeNode(const string &name); + explicit RopeNode(const std::string &name); protected: RopeNode(const RopeNode ©); public: - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; virtual PandaNode *make_copy() const; diff --git a/panda/src/parametrics/sheetNode.cxx b/panda/src/parametrics/sheetNode.cxx index b4e4cc5a4d..eec44c0cda 100644 --- a/panda/src/parametrics/sheetNode.cxx +++ b/panda/src/parametrics/sheetNode.cxx @@ -48,7 +48,7 @@ void SheetNode::CData:: write_datagram(BamWriter *writer, Datagram &dg) const { // For now, we write a NULL pointer. Eventually we will write out the // NurbsSurfaceEvaluator pointer. - writer->write_pointer(dg, (TypedWritable *)NULL); + writer->write_pointer(dg, nullptr); } /** @@ -66,7 +66,7 @@ fillin(DatagramIterator &scan, BamReader *reader) { * */ SheetNode:: -SheetNode(const string &name) : +SheetNode(const std::string &name) : PandaNode(name) { set_cull_callback(); @@ -128,7 +128,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { // Create some geometry on-the-fly to render the sheet. if (get_num_u_subdiv() > 0 && get_num_v_subdiv() > 0) { NurbsSurfaceEvaluator *surface = get_surface(); - if (surface != (NurbsSurfaceEvaluator *)NULL) { + if (surface != nullptr) { PT(NurbsSurfaceResult) result = surface->evaluate(data.get_node_path()); if (result->get_num_u_segments() > 0 && result->get_num_v_segments() > 0) { @@ -155,10 +155,10 @@ is_renderable() const { * */ void SheetNode:: -output(ostream &out) const { +output(std::ostream &out) const { PandaNode::output(out); NurbsSurfaceEvaluator *surface = get_surface(); - if (surface != (NurbsSurfaceEvaluator *)NULL) { + if (surface != nullptr) { out << " " << *surface; } else { out << " (no surface)"; @@ -169,10 +169,10 @@ output(ostream &out) const { * */ void SheetNode:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { PandaNode::write(out, indent_level); NurbsSurfaceEvaluator *surface = get_surface(); - if (surface != (NurbsSurfaceEvaluator *)NULL) { + if (surface != nullptr) { indent(out, indent_level + 2) << *surface << "\n"; } else { indent(out, indent_level + 2) << "(no surface)\n"; @@ -224,7 +224,7 @@ do_recompute_bounds(const NodePath &rel_to, int pipeline_stage, PT(BoundingVolume) bound = new BoundingSphere; NurbsSurfaceEvaluator *surface = get_surface(); - if (surface != (NurbsSurfaceEvaluator *)NULL) { + if (surface != nullptr) { NurbsSurfaceEvaluator::Vert3Array verts; get_surface()->get_vertices(verts, rel_to); diff --git a/panda/src/parametrics/sheetNode.h b/panda/src/parametrics/sheetNode.h index 29374955a7..97a8d80a71 100644 --- a/panda/src/parametrics/sheetNode.h +++ b/panda/src/parametrics/sheetNode.h @@ -31,13 +31,13 @@ */ class EXPCL_PANDA_PARAMETRICS SheetNode : public PandaNode { PUBLISHED: - explicit SheetNode(const string &name); + explicit SheetNode(const std::string &name); protected: SheetNode(const SheetNode ©); public: - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; virtual PandaNode *make_copy() const; diff --git a/panda/src/particlesystem/arcEmitter.cxx b/panda/src/particlesystem/arcEmitter.cxx index cc56b3130e..a87c7376db 100644 --- a/panda/src/particlesystem/arcEmitter.cxx +++ b/panda/src/particlesystem/arcEmitter.cxx @@ -74,7 +74,7 @@ assign_initial_position(LPoint3& pos) { * Write a starc representation of this instance to . */ void ArcEmitter:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"ArcEmitter"; #endif //] NDEBUG @@ -84,7 +84,7 @@ output(ostream &out) const { * Write a starc representation of this instance to . */ void ArcEmitter:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"ArcEmitter:\n"; out.width(indent+2); out<<""; out<<"_start_angle "<. */ void BaseParticle:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"BaseParticle"; #endif //] NDEBUG @@ -61,7 +61,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void BaseParticle:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"BaseParticle:\n"; out.width(indent+2); out<<""; out<<"_age "<<_age<<"\n"; diff --git a/panda/src/particlesystem/baseParticle.h b/panda/src/particlesystem/baseParticle.h index e152536269..487f9ba476 100644 --- a/panda/src/particlesystem/baseParticle.h +++ b/panda/src/particlesystem/baseParticle.h @@ -20,7 +20,7 @@ /** * An individual, physically-modelable particle abstract base class. */ -class EXPCL_PANDAPHYSICS BaseParticle : public PhysicsObject { +class EXPCL_PANDA_PARTICLESYSTEM BaseParticle : public PhysicsObject { public: // local methods INLINE void set_age(PN_stdfloat age); @@ -48,8 +48,8 @@ public: // from PhysicsObject virtual PhysicsObject *make_copy() const = 0; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; protected: BaseParticle(PN_stdfloat lifespan = 1.0f, bool alive = false); diff --git a/panda/src/particlesystem/baseParticleEmitter.cxx b/panda/src/particlesystem/baseParticleEmitter.cxx index 20ef762aa9..c18584b461 100644 --- a/panda/src/particlesystem/baseParticleEmitter.cxx +++ b/panda/src/particlesystem/baseParticleEmitter.cxx @@ -79,7 +79,7 @@ generate(LPoint3& pos, LVector3& vel) { * Write a string representation of this instance to . */ void BaseParticleEmitter:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"BaseParticleEmitter"; #endif //] NDEBUG @@ -89,7 +89,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void BaseParticleEmitter:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"BaseParticleEmitter:\n"; out.width(indent+2); out<<""; out<<"_emission_type "<<_emission_type<<"\n"; diff --git a/panda/src/particlesystem/baseParticleEmitter.h b/panda/src/particlesystem/baseParticleEmitter.h index af16f43274..f1c6665679 100644 --- a/panda/src/particlesystem/baseParticleEmitter.h +++ b/panda/src/particlesystem/baseParticleEmitter.h @@ -22,7 +22,7 @@ #include "mathNumbers.h" -class EXPCL_PANDAPHYSICS BaseParticleEmitter : public ReferenceCount { +class EXPCL_PANDA_PARTICLESYSTEM BaseParticleEmitter : public ReferenceCount { PUBLISHED: enum emissionType { ET_EXPLICIT, // all particles are emitted in parallel along the same vector @@ -49,8 +49,8 @@ PUBLISHED: INLINE LVector3 get_explicit_launch_vector() const; INLINE LPoint3 get_radiate_origin() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; protected: BaseParticleEmitter(); diff --git a/panda/src/particlesystem/baseParticleFactory.cxx b/panda/src/particlesystem/baseParticleFactory.cxx index 162b4df88e..0f0169f99b 100644 --- a/panda/src/particlesystem/baseParticleFactory.cxx +++ b/panda/src/particlesystem/baseParticleFactory.cxx @@ -69,7 +69,7 @@ populate_particle(BaseParticle *bp) { * Write a string representation of this instance to . */ void BaseParticleFactory:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"BaseParticleFactory"; #endif //] NDEBUG @@ -79,7 +79,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void BaseParticleFactory:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"BaseParticleFactory:\n"; out.width(indent+2); out<<""; out<<"_lifespan_base "<<_lifespan_base<<"\n"; diff --git a/panda/src/particlesystem/baseParticleFactory.h b/panda/src/particlesystem/baseParticleFactory.h index bdb7fd6a8c..0271ef91eb 100644 --- a/panda/src/particlesystem/baseParticleFactory.h +++ b/panda/src/particlesystem/baseParticleFactory.h @@ -25,7 +25,7 @@ /** * Pure Virtual base class for creating particles */ -class EXPCL_PANDAPHYSICS BaseParticleFactory : public ReferenceCount { +class EXPCL_PANDA_PARTICLESYSTEM BaseParticleFactory : public ReferenceCount { PUBLISHED: virtual ~BaseParticleFactory(); @@ -47,8 +47,8 @@ PUBLISHED: void populate_particle(BaseParticle* bp); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; protected: BaseParticleFactory(); diff --git a/panda/src/particlesystem/baseParticleRenderer.I b/panda/src/particlesystem/baseParticleRenderer.I index 38d8cf8bbb..7da2037edd 100644 --- a/panda/src/particlesystem/baseParticleRenderer.I +++ b/panda/src/particlesystem/baseParticleRenderer.I @@ -97,7 +97,7 @@ get_cur_alpha(BaseParticle* bp) { return bp->get_parameterized_age(); case PR_ALPHA_IN_OUT: - return 2.0 * min(bp->get_parameterized_age(), + return 2.0 * std::min(bp->get_parameterized_age(), 1.0f - bp->get_parameterized_age()); case PR_ALPHA_USER: diff --git a/panda/src/particlesystem/baseParticleRenderer.cxx b/panda/src/particlesystem/baseParticleRenderer.cxx index 2a2072c2a1..f7f33c41ac 100644 --- a/panda/src/particlesystem/baseParticleRenderer.cxx +++ b/panda/src/particlesystem/baseParticleRenderer.cxx @@ -79,7 +79,7 @@ set_ignore_scale(bool ignore_scale) { * Write a string representation of this instance to . */ void BaseParticleRenderer:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"BaseParticleRenderer"; #endif //] NDEBUG @@ -89,7 +89,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void BaseParticleRenderer:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"BaseParticleRenderer:\n"; out.width(indent+2); out<<""; out<<"_render_node "<<_render_node_path<<"\n"; diff --git a/panda/src/particlesystem/baseParticleRenderer.h b/panda/src/particlesystem/baseParticleRenderer.h index 81926f3a74..8dd8a0a081 100644 --- a/panda/src/particlesystem/baseParticleRenderer.h +++ b/panda/src/particlesystem/baseParticleRenderer.h @@ -29,7 +29,7 @@ /** * Pure virtual particle renderer base class */ -class EXPCL_PANDAPHYSICS BaseParticleRenderer : public ReferenceCount { +class EXPCL_PANDA_PARTICLESYSTEM BaseParticleRenderer : public ReferenceCount { PUBLISHED: enum ParticleRendererAlphaMode { PR_ALPHA_NONE, @@ -62,8 +62,8 @@ PUBLISHED: void set_ignore_scale(bool ignore_scale); INLINE bool get_ignore_scale() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; public: virtual BaseParticleRenderer *make_copy() = 0; diff --git a/panda/src/particlesystem/boxEmitter.cxx b/panda/src/particlesystem/boxEmitter.cxx index 52035e62c7..3b84932dd7 100644 --- a/panda/src/particlesystem/boxEmitter.cxx +++ b/panda/src/particlesystem/boxEmitter.cxx @@ -78,7 +78,7 @@ assign_initial_velocity(LVector3& vel) { * Write a string representation of this instance to . */ void BoxEmitter:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"BoxEmitter"; #endif //] NDEBUG @@ -88,7 +88,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void BoxEmitter:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"BoxEmitter:\n"; out.width(indent+2); out<<""; out<<"_vmin "<<_vmin<<"\n"; diff --git a/panda/src/particlesystem/boxEmitter.h b/panda/src/particlesystem/boxEmitter.h index e9ffbe070c..9899a04978 100644 --- a/panda/src/particlesystem/boxEmitter.h +++ b/panda/src/particlesystem/boxEmitter.h @@ -19,7 +19,7 @@ /** * Describes a voluminous box region in which particles are generated. */ -class EXPCL_PANDAPHYSICS BoxEmitter : public BaseParticleEmitter { +class EXPCL_PANDA_PARTICLESYSTEM BoxEmitter : public BaseParticleEmitter { PUBLISHED: BoxEmitter(); BoxEmitter(const BoxEmitter ©); @@ -33,8 +33,8 @@ PUBLISHED: INLINE LPoint3 get_min_bound() const; INLINE LPoint3 get_max_bound() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: LPoint3 _vmin; diff --git a/panda/src/particlesystem/colorInterpolationManager.I b/panda/src/particlesystem/colorInterpolationManager.I index 4a76521cea..399476ab2d 100644 --- a/panda/src/particlesystem/colorInterpolationManager.I +++ b/panda/src/particlesystem/colorInterpolationManager.I @@ -231,7 +231,7 @@ get_segment(const int seg_id) { if( seg_id == (*iter)->get_id() ) return (*iter); - return NULL; + return nullptr; } /** @@ -239,14 +239,14 @@ get_segment(const int seg_id) { * time. */ -INLINE string ColorInterpolationManager:: +INLINE std::string ColorInterpolationManager:: get_segment_id_list() { pvector::iterator iter; - ostringstream output; + std::ostringstream output; for(iter = _i_segs.begin();iter != _i_segs.end();++iter) output << (*iter)->get_id() << " "; - string str = output.str(); + std::string str = output.str(); return str.substr(0, str.length()-1); } diff --git a/panda/src/particlesystem/colorInterpolationManager.cxx b/panda/src/particlesystem/colorInterpolationManager.cxx index 27268c2ef8..b2e68ba66d 100644 --- a/panda/src/particlesystem/colorInterpolationManager.cxx +++ b/panda/src/particlesystem/colorInterpolationManager.cxx @@ -14,6 +14,9 @@ #include "colorInterpolationManager.h" #include "mathNumbers.h" +using std::max; +using std::min; + TypeHandle ColorInterpolationFunction::_type_handle; TypeHandle ColorInterpolationFunctionConstant::_type_handle; TypeHandle ColorInterpolationFunctionLinear::_type_handle; diff --git a/panda/src/particlesystem/colorInterpolationManager.h b/panda/src/particlesystem/colorInterpolationManager.h index 6c01d95b24..441ec4de7a 100644 --- a/panda/src/particlesystem/colorInterpolationManager.h +++ b/panda/src/particlesystem/colorInterpolationManager.h @@ -24,7 +24,7 @@ * virtual interpolate() function. */ -class EXPCL_PANDAPHYSICS ColorInterpolationFunction : public TypedReferenceCount { +class EXPCL_PANDA_PARTICLESYSTEM ColorInterpolationFunction : public TypedReferenceCount { PUBLISHED: // virtual string get_type(); @@ -57,7 +57,7 @@ private: * Defines a constant color over the lifetime of the segment. */ -class EXPCL_PANDAPHYSICS ColorInterpolationFunctionConstant : public ColorInterpolationFunction { +class EXPCL_PANDA_PARTICLESYSTEM ColorInterpolationFunctionConstant : public ColorInterpolationFunction { PUBLISHED: INLINE LColor get_color_a() const; @@ -96,7 +96,7 @@ private: * Defines a linear interpolation over the lifetime of the segment. */ -class EXPCL_PANDAPHYSICS ColorInterpolationFunctionLinear : public ColorInterpolationFunctionConstant { +class EXPCL_PANDA_PARTICLESYSTEM ColorInterpolationFunctionLinear : public ColorInterpolationFunctionConstant { PUBLISHED: INLINE LColor get_color_b() const; @@ -138,7 +138,7 @@ private: * repeats until the end of the segment. */ -class EXPCL_PANDAPHYSICS ColorInterpolationFunctionStepwave : public ColorInterpolationFunctionLinear { +class EXPCL_PANDA_PARTICLESYSTEM ColorInterpolationFunctionStepwave : public ColorInterpolationFunctionLinear { PUBLISHED: INLINE PN_stdfloat get_width_a() const; INLINE PN_stdfloat get_width_b() const; @@ -183,7 +183,7 @@ private: * result in a higher frequency cycle. */ -class EXPCL_PANDAPHYSICS ColorInterpolationFunctionSinusoid : public ColorInterpolationFunctionLinear { +class EXPCL_PANDA_PARTICLESYSTEM ColorInterpolationFunctionSinusoid : public ColorInterpolationFunctionLinear { PUBLISHED: INLINE PN_stdfloat get_period() const; @@ -224,7 +224,7 @@ private: * segment also has a function associated with it. */ -class EXPCL_PANDAPHYSICS ColorInterpolationSegment : public ReferenceCount { +class EXPCL_PANDA_PARTICLESYSTEM ColorInterpolationSegment : public ReferenceCount { public: ColorInterpolationSegment(ColorInterpolationFunction* function, const PN_stdfloat &time_begin, const PN_stdfloat &time_end, const bool is_modulated, const int id); @@ -266,7 +266,7 @@ protected: * Access to these segments is provided but not necessary general use. */ -class EXPCL_PANDAPHYSICS ColorInterpolationManager : public ReferenceCount { +class EXPCL_PANDA_PARTICLESYSTEM ColorInterpolationManager : public ReferenceCount { PUBLISHED: ColorInterpolationManager(); ColorInterpolationManager(const LColor &c); @@ -280,7 +280,7 @@ ColorInterpolationManager(); INLINE void set_default_color(const LColor &c); INLINE ColorInterpolationSegment* get_segment(const int seg_id); - INLINE string get_segment_id_list(); + INLINE std::string get_segment_id_list(); void clear_segment(const int seg_id); void clear_to_initial(); diff --git a/panda/src/particlesystem/config_particlesystem.cxx b/panda/src/particlesystem/config_particlesystem.cxx index 0eba6c33f1..61f1224ea4 100644 --- a/panda/src/particlesystem/config_particlesystem.cxx +++ b/panda/src/particlesystem/config_particlesystem.cxx @@ -16,8 +16,8 @@ #include "geomParticleRenderer.h" #include "geomNode.h" -#if !defined(CPPPARSER) && !defined(BUILDING_PANDAPHYSICS) - #error Buildsystem error: BUILDING_PANDAPHYSICS not defined +#if !defined(CPPPARSER) && !defined(BUILDING_PANDA_PARTICLESYSTEM) + #error Buildsystem error: BUILDING_PANDA_PARTICLESYSTEM not defined #endif ConfigureDef(config_particlesystem); diff --git a/panda/src/particlesystem/config_particlesystem.h b/panda/src/particlesystem/config_particlesystem.h index 16382b274c..56beffeaf0 100644 --- a/panda/src/particlesystem/config_particlesystem.h +++ b/panda/src/particlesystem/config_particlesystem.h @@ -18,10 +18,10 @@ #include "notifyCategoryProxy.h" #include "dconfig.h" -ConfigureDecl(config_particlesystem, EXPCL_PANDAPHYSICS, EXPTP_PANDAPHYSICS); -NotifyCategoryDecl(particlesystem, EXPCL_PANDAPHYSICS, EXPTP_PANDAPHYSICS); +ConfigureDecl(config_particlesystem, EXPCL_PANDA_PARTICLESYSTEM, EXPTP_PANDA_PARTICLESYSTEM); +NotifyCategoryDecl(particlesystem, EXPCL_PANDA_PARTICLESYSTEM, EXPTP_PANDA_PARTICLESYSTEM); -extern EXPCL_PANDAPHYSICS void init_libparticlesystem(); +extern EXPCL_PANDA_PARTICLESYSTEM void init_libparticlesystem(); #ifndef NDEBUG //[ // Non-release build: diff --git a/panda/src/particlesystem/discEmitter.cxx b/panda/src/particlesystem/discEmitter.cxx index 3b018a2dfe..e07f933bdf 100644 --- a/panda/src/particlesystem/discEmitter.cxx +++ b/panda/src/particlesystem/discEmitter.cxx @@ -115,7 +115,7 @@ assign_initial_velocity(LVector3& vel) { * Write a string representation of this instance to . */ void DiscEmitter:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"DiscEmitter"; #endif //] NDEBUG @@ -125,7 +125,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void DiscEmitter:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"DiscEmitter:\n"; out.width(indent+2); out<<""; out<<"_radius "<<_radius<<"\n"; diff --git a/panda/src/particlesystem/discEmitter.h b/panda/src/particlesystem/discEmitter.h index 2d5c8c1367..fcfcf9b94a 100644 --- a/panda/src/particlesystem/discEmitter.h +++ b/panda/src/particlesystem/discEmitter.h @@ -19,7 +19,7 @@ /** * Describes a planar disc region from which particles are generated */ -class EXPCL_PANDAPHYSICS DiscEmitter : public BaseParticleEmitter { +class EXPCL_PANDA_PARTICLESYSTEM DiscEmitter : public BaseParticleEmitter { PUBLISHED: DiscEmitter(); DiscEmitter(const DiscEmitter ©); @@ -41,8 +41,8 @@ PUBLISHED: INLINE PN_stdfloat get_inner_magnitude() const; INLINE bool get_cubic_lerping() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: PN_stdfloat _radius; diff --git a/panda/src/particlesystem/geomParticleRenderer.I b/panda/src/particlesystem/geomParticleRenderer.I index 25ce5035c3..cdb3906ac0 100644 --- a/panda/src/particlesystem/geomParticleRenderer.I +++ b/panda/src/particlesystem/geomParticleRenderer.I @@ -21,7 +21,7 @@ INLINE void GeomParticleRenderer:: set_geom_node(PandaNode *node) { - nassertv(node != (PandaNode *)NULL); + nassertv(node != nullptr); _geom_node = node; resize_pool(_pool_size); } diff --git a/panda/src/particlesystem/geomParticleRenderer.cxx b/panda/src/particlesystem/geomParticleRenderer.cxx index 92ebc5a218..8db733c58d 100644 --- a/panda/src/particlesystem/geomParticleRenderer.cxx +++ b/panda/src/particlesystem/geomParticleRenderer.cxx @@ -105,7 +105,7 @@ resize_pool(int new_size) { int i; for (i = 0; i < new_size; i++) { - _node_vector.push_back(NULL); + _node_vector.push_back(nullptr); } _pool_size = new_size; @@ -122,7 +122,7 @@ kill_nodes() { PandaNode *render_node = get_render_node(); for (; vec_iter != _node_vector.end(); vec_iter++) { PandaNode *node = *vec_iter; - if (node != (PandaNode *)NULL) { + if (node != nullptr) { render_node->remove_child(node); } } @@ -136,7 +136,7 @@ kill_nodes() { void GeomParticleRenderer:: birth_particle(int index) { - if (_node_vector[index] == (PandaNode *)NULL) { + if (_node_vector[index] == nullptr) { PandaNode *node = new PandaNode(""); get_render_node()->add_child(node); node->add_child(_geom_node); @@ -150,9 +150,9 @@ birth_particle(int index) { void GeomParticleRenderer:: kill_particle(int index) { - if (_node_vector[index] != (PandaNode *)NULL) { + if (_node_vector[index] != nullptr) { get_render_node()->remove_child(_node_vector[index]); - _node_vector[index] = (PandaNode *)NULL; + _node_vector[index] = nullptr; } } @@ -179,11 +179,11 @@ render(pvector< PT(PhysicsObject) >& po_vector, int ttl_particles) { if (cur_particle->get_alive()) { // living particle - if (cur_node == (PandaNode *)NULL) { + if (cur_node == nullptr) { birth_particle(i); cur_node = *cur_node_iter; } - nassertv(cur_node != (PandaNode *)NULL); + nassertv(cur_node != nullptr); cur_node->set_state(_render_state); @@ -200,7 +200,7 @@ render(pvector< PT(PhysicsObject) >& po_vector, int ttl_particles) { if (_alpha_mode == PR_ALPHA_OUT) alpha_scalar = 1.0f - alpha_scalar; else if (_alpha_mode == PR_ALPHA_IN_OUT) - alpha_scalar = 2.0f * min(alpha_scalar, 1.0f - alpha_scalar); + alpha_scalar = 2.0f * std::min(alpha_scalar, 1.0f - alpha_scalar); alpha_scalar *= get_user_alpha(); } @@ -252,7 +252,7 @@ render(pvector< PT(PhysicsObject) >& po_vector, int ttl_particles) { * Write a string representation of this instance to . */ void GeomParticleRenderer:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"GeomParticleRenderer"; #endif //] NDEBUG @@ -262,7 +262,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void GeomParticleRenderer:: -write_linear_forces(ostream &out, int indent) const { +write_linear_forces(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""<<"_node_vector ("<<_node_vector.size()<<" forces)\n"; @@ -278,7 +278,7 @@ write_linear_forces(ostream &out, int indent) const { * Write a string representation of this instance to . */ void GeomParticleRenderer:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"GeomParticleRenderer:\n"; out.width(indent+2); out<<""; out<<"_geom_node "<<_geom_node<<"\n"; diff --git a/panda/src/particlesystem/geomParticleRenderer.h b/panda/src/particlesystem/geomParticleRenderer.h index 54e58a2d65..a9fd906dd4 100644 --- a/panda/src/particlesystem/geomParticleRenderer.h +++ b/panda/src/particlesystem/geomParticleRenderer.h @@ -23,10 +23,10 @@ #include "pvector.h" #include "pStatCollector.h" -class EXPCL_PANDAPHYSICS GeomParticleRenderer : public BaseParticleRenderer { +class EXPCL_PANDA_PARTICLESYSTEM GeomParticleRenderer : public BaseParticleRenderer { PUBLISHED: explicit GeomParticleRenderer(ParticleRendererAlphaMode am = PR_ALPHA_NONE, - PandaNode *geom_node = (PandaNode *) NULL); + PandaNode *geom_node = nullptr); GeomParticleRenderer(const GeomParticleRenderer& copy); virtual ~GeomParticleRenderer(); @@ -57,9 +57,9 @@ PUBLISHED: public: virtual BaseParticleRenderer *make_copy(); - virtual void output(ostream &out) const; - virtual void write_linear_forces(ostream &out, int indent=0) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write_linear_forces(std::ostream &out, int indent=0) const; + virtual void write(std::ostream &out, int indent=0) const; private: PT(PandaNode) _geom_node; diff --git a/panda/src/particlesystem/lineEmitter.cxx b/panda/src/particlesystem/lineEmitter.cxx index 5a236c03e1..6855fc3aeb 100644 --- a/panda/src/particlesystem/lineEmitter.cxx +++ b/panda/src/particlesystem/lineEmitter.cxx @@ -76,7 +76,7 @@ assign_initial_velocity(LVector3& vel) { * Write a string representation of this instance to . */ void LineEmitter:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"LineEmitter"; #endif //] NDEBUG @@ -86,7 +86,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void LineEmitter:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"LineEmitter:\n"; out.width(indent+2); out<<""; out<<"_endpoint1 "<<_endpoint1<<"\n"; diff --git a/panda/src/particlesystem/lineEmitter.h b/panda/src/particlesystem/lineEmitter.h index 8d1d5f9afa..80422654fb 100644 --- a/panda/src/particlesystem/lineEmitter.h +++ b/panda/src/particlesystem/lineEmitter.h @@ -19,7 +19,7 @@ /** * Describes a linear region in which particles are generated. */ -class EXPCL_PANDAPHYSICS LineEmitter : public BaseParticleEmitter { +class EXPCL_PANDA_PARTICLESYSTEM LineEmitter : public BaseParticleEmitter { PUBLISHED: LineEmitter(); LineEmitter(const LineEmitter ©); @@ -33,8 +33,8 @@ PUBLISHED: INLINE LPoint3 get_endpoint1() const; INLINE LPoint3 get_endpoint2() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: LPoint3 _endpoint1; diff --git a/panda/src/particlesystem/lineParticleRenderer.cxx b/panda/src/particlesystem/lineParticleRenderer.cxx index e139e6f2e8..5a2240cfb6 100644 --- a/panda/src/particlesystem/lineParticleRenderer.cxx +++ b/panda/src/particlesystem/lineParticleRenderer.cxx @@ -195,7 +195,7 @@ render(pvector< PT(PhysicsObject) >& po_vector, int ttl_particles) { if (_alpha_mode == PR_ALPHA_OUT) alpha = 1.0f - alpha; else if (_alpha_mode == PR_ALPHA_IN_OUT) - alpha = 2.0f * min(alpha, 1.0f - alpha); + alpha = 2.0f * std::min(alpha, 1.0f - alpha); } head_color[3] = alpha; @@ -232,7 +232,7 @@ render(pvector< PT(PhysicsObject) >& po_vector, int ttl_particles) { * Write a string representation of this instance to . */ void LineParticleRenderer:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"LineParticleRenderer"; #endif //] NDEBUG @@ -242,7 +242,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void LineParticleRenderer:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "LineParticleRenderer:\n"; indent(out, indent_level + 2) << "_head_color "<<_head_color<<"\n"; indent(out, indent_level + 2) << "_tail_color "<<_tail_color<<"\n"; diff --git a/panda/src/particlesystem/lineParticleRenderer.h b/panda/src/particlesystem/lineParticleRenderer.h index ae37a833d5..ecec62fc8e 100644 --- a/panda/src/particlesystem/lineParticleRenderer.h +++ b/panda/src/particlesystem/lineParticleRenderer.h @@ -28,7 +28,7 @@ * sparks, etc. */ -class EXPCL_PANDAPHYSICS LineParticleRenderer : public BaseParticleRenderer { +class EXPCL_PANDA_PARTICLESYSTEM LineParticleRenderer : public BaseParticleRenderer { PUBLISHED: LineParticleRenderer(); LineParticleRenderer(const LineParticleRenderer& copy); @@ -51,8 +51,8 @@ PUBLISHED: INLINE void set_line_scale_factor(PN_stdfloat sf); INLINE PN_stdfloat get_line_scale_factor() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; private: LColor _head_color; diff --git a/panda/src/particlesystem/orientedParticle.cxx b/panda/src/particlesystem/orientedParticle.cxx index bf828f165c..640c244aa7 100644 --- a/panda/src/particlesystem/orientedParticle.cxx +++ b/panda/src/particlesystem/orientedParticle.cxx @@ -71,7 +71,7 @@ update() { * Write a string representation of this instance to . */ void OrientedParticle:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"OrientedParticle"; #endif //] NDEBUG @@ -81,7 +81,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void OrientedParticle:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"OrientedParticle:\n"; BaseParticle::write(out, indent+2); diff --git a/panda/src/particlesystem/orientedParticle.h b/panda/src/particlesystem/orientedParticle.h index 5bdfd88351..740b8e03d6 100644 --- a/panda/src/particlesystem/orientedParticle.h +++ b/panda/src/particlesystem/orientedParticle.h @@ -20,7 +20,7 @@ * Describes a particle that has angular characteristics (velocity, * orientation). */ -class EXPCL_PANDAPHYSICS OrientedParticle : public BaseParticle { +class EXPCL_PANDA_PARTICLESYSTEM OrientedParticle : public BaseParticle { public: OrientedParticle(int lifespan = 0, bool alive = false); OrientedParticle(const OrientedParticle ©); @@ -35,8 +35,8 @@ public: virtual void update(); virtual void die(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; }; #include "orientedParticle.I" diff --git a/panda/src/particlesystem/orientedParticleFactory.cxx b/panda/src/particlesystem/orientedParticleFactory.cxx index 2889a16727..7276d9c2b9 100644 --- a/panda/src/particlesystem/orientedParticleFactory.cxx +++ b/panda/src/particlesystem/orientedParticleFactory.cxx @@ -59,7 +59,7 @@ alloc_particle() const { * Write a string representation of this instance to . */ void OrientedParticleFactory:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"OrientedParticleFactory"; #endif //] NDEBUG @@ -69,7 +69,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void OrientedParticleFactory:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"OrientedParticleFactory:\n"; BaseParticleFactory::write(out, indent+2); diff --git a/panda/src/particlesystem/orientedParticleFactory.h b/panda/src/particlesystem/orientedParticleFactory.h index 0df2326ed4..d33f18009b 100644 --- a/panda/src/particlesystem/orientedParticleFactory.h +++ b/panda/src/particlesystem/orientedParticleFactory.h @@ -21,7 +21,7 @@ /** * Creates particles that are affected by angular forces. */ -class EXPCL_PANDAPHYSICS OrientedParticleFactory : public BaseParticleFactory { +class EXPCL_PANDA_PARTICLESYSTEM OrientedParticleFactory : public BaseParticleFactory { PUBLISHED: OrientedParticleFactory(); OrientedParticleFactory(const OrientedParticleFactory ©); @@ -32,8 +32,8 @@ PUBLISHED: INLINE LOrientation get_initial_orientation() const; INLINE LOrientation get_final_orientation() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: virtual void populate_child_particle(BaseParticle *bp) const; diff --git a/panda/src/particlesystem/particleSystem.cxx b/panda/src/particlesystem/particleSystem.cxx index 7e22ac9180..32a9480fc0 100644 --- a/panda/src/particlesystem/particleSystem.cxx +++ b/panda/src/particlesystem/particleSystem.cxx @@ -30,6 +30,10 @@ #include "sphereSurfaceEmitter.h" #include "pStatTimer.h" +using std::cout; +using std::endl; +using std::ostream; + TypeHandle ParticleSystem::_type_handle; PStatCollector ParticleSystem::_update_collector("App:Particles:Update"); @@ -594,7 +598,7 @@ sanity_check() { #endif result++; } - pool_size = min(_particle_pool_size, _physics_objects.size()); + pool_size = std::min(_particle_pool_size, _physics_objects.size()); // find out how many particles are REALLY alive and dead int real_live_particle_count = 0; diff --git a/panda/src/particlesystem/particleSystem.h b/panda/src/particlesystem/particleSystem.h index e2689cf361..a7b4af64ef 100644 --- a/panda/src/particlesystem/particleSystem.h +++ b/panda/src/particlesystem/particleSystem.h @@ -37,7 +37,7 @@ class ParticleSystemManager; /** * Contains and manages a particle system. */ -class EXPCL_PANDAPHYSICS ParticleSystem : public Physical { +class EXPCL_PANDA_PARTICLESYSTEM ParticleSystem : public Physical { PUBLISHED: // constructordestructor @@ -104,10 +104,10 @@ PUBLISHED: INLINE void soft_start(PN_stdfloat br = 0.0); void update(PN_stdfloat dt); - virtual void output(ostream &out) const; - virtual void write_free_particle_fifo(ostream &out, int indent=0) const; - virtual void write_spawn_templates(ostream &out, int indent=0) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write_free_particle_fifo(std::ostream &out, int indent=0) const; + virtual void write_spawn_templates(std::ostream &out, int indent=0) const; + virtual void write(std::ostream &out, int indent=0) const; private: #ifdef PSSANITYCHECK diff --git a/panda/src/particlesystem/particleSystemManager.cxx b/panda/src/particlesystem/particleSystemManager.cxx index e6dbf53fef..b96c7d6105 100644 --- a/panda/src/particlesystem/particleSystemManager.cxx +++ b/panda/src/particlesystem/particleSystemManager.cxx @@ -145,7 +145,7 @@ do_particles(PN_stdfloat dt, ParticleSystem *ps, bool do_render) { * Write a string representation of this instance to . */ void ParticleSystemManager:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"ParticleSystemManager"; #endif //] NDEBUG @@ -155,7 +155,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void ParticleSystemManager:: -write_ps_list(ostream &out, int indent) const { +write_ps_list(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""<<"_ps_list ("<<_ps_list.size()<<" systems)\n"; @@ -171,7 +171,7 @@ write_ps_list(ostream &out, int indent) const { * Write a string representation of this instance to . */ void ParticleSystemManager:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"ParticleSystemManager:\n"; out.width(indent+2); out<<""; out<<"_nth_frame "<<_nth_frame<<"\n"; diff --git a/panda/src/particlesystem/particleSystemManager.h b/panda/src/particlesystem/particleSystemManager.h index 1b03fdbc06..5bfbe09ec7 100644 --- a/panda/src/particlesystem/particleSystemManager.h +++ b/panda/src/particlesystem/particleSystemManager.h @@ -24,7 +24,7 @@ * one doesn't have to be updated and rendered every frame See Also : * particleSystemManager.cxx */ -class EXPCL_PANDAPHYSICS ParticleSystemManager { +class EXPCL_PANDA_PARTICLESYSTEM ParticleSystemManager { PUBLISHED: explicit ParticleSystemManager(int every_nth_frame = 1); virtual ~ParticleSystemManager(); @@ -39,9 +39,9 @@ PUBLISHED: void do_particles(PN_stdfloat dt); void do_particles(PN_stdfloat dt, ParticleSystem * ps, bool do_render = true); - virtual void output(ostream &out) const; - virtual void write_ps_list(ostream &out, int indent=0) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write_ps_list(std::ostream &out, int indent=0) const; + virtual void write(std::ostream &out, int indent=0) const; private: plist< PT(ParticleSystem) > _ps_list; diff --git a/panda/src/particlesystem/pointEmitter.cxx b/panda/src/particlesystem/pointEmitter.cxx index 9c3664e7c7..376cec9a82 100644 --- a/panda/src/particlesystem/pointEmitter.cxx +++ b/panda/src/particlesystem/pointEmitter.cxx @@ -66,7 +66,7 @@ assign_initial_velocity(LVector3& vel) { * Write a string representation of this instance to . */ void PointEmitter:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"PointEmitter"; #endif //] NDEBUG @@ -76,7 +76,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void PointEmitter:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"PointEmitter:\n"; out.width(indent+2); out<<""; out<<"_location "<<_location<<"\n"; diff --git a/panda/src/particlesystem/pointEmitter.h b/panda/src/particlesystem/pointEmitter.h index 145dff2344..90af2a899a 100644 --- a/panda/src/particlesystem/pointEmitter.h +++ b/panda/src/particlesystem/pointEmitter.h @@ -19,7 +19,7 @@ /** * Describes a planar ring region in which particles are generated. */ -class EXPCL_PANDAPHYSICS PointEmitter : public BaseParticleEmitter { +class EXPCL_PANDA_PARTICLESYSTEM PointEmitter : public BaseParticleEmitter { PUBLISHED: PointEmitter(); PointEmitter(const PointEmitter ©); @@ -30,8 +30,8 @@ PUBLISHED: INLINE void set_location(const LPoint3& p); INLINE LPoint3 get_location() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: LPoint3 _location; diff --git a/panda/src/particlesystem/pointParticle.cxx b/panda/src/particlesystem/pointParticle.cxx index 32e1dbf0b2..fac3c5edf2 100644 --- a/panda/src/particlesystem/pointParticle.cxx +++ b/panda/src/particlesystem/pointParticle.cxx @@ -71,7 +71,7 @@ update() { * Write a string representation of this instance to . */ void PointParticle:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"PointParticle"; #endif //] NDEBUG @@ -81,7 +81,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void PointParticle:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"PointParticle:\n"; BaseParticle::write(out, indent+2); diff --git a/panda/src/particlesystem/pointParticle.h b/panda/src/particlesystem/pointParticle.h index f9fe566a40..bf7b70a98b 100644 --- a/panda/src/particlesystem/pointParticle.h +++ b/panda/src/particlesystem/pointParticle.h @@ -20,7 +20,7 @@ * Describes a particle that requires representation by a point (pixel, * sparkle, billboard) */ -class EXPCL_PANDAPHYSICS PointParticle : public BaseParticle { +class EXPCL_PANDA_PARTICLESYSTEM PointParticle : public BaseParticle { public: PointParticle(PN_stdfloat lifespan = 0.0f, bool alive = false); PointParticle(const PointParticle ©); @@ -32,8 +32,8 @@ public: virtual PhysicsObject *make_copy() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; }; #endif // POINTPARTICLE_H diff --git a/panda/src/particlesystem/pointParticleFactory.cxx b/panda/src/particlesystem/pointParticleFactory.cxx index 71a06d763e..2e1b645d88 100644 --- a/panda/src/particlesystem/pointParticleFactory.cxx +++ b/panda/src/particlesystem/pointParticleFactory.cxx @@ -59,7 +59,7 @@ alloc_particle() const { * Write a string representation of this instance to . */ void PointParticleFactory:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"PointParticleFactory"; #endif //] NDEBUG @@ -69,7 +69,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void PointParticleFactory:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"PointParticleFactory:\n"; BaseParticleFactory::write(out, indent+2); diff --git a/panda/src/particlesystem/pointParticleFactory.h b/panda/src/particlesystem/pointParticleFactory.h index 0ce2b6e232..3c2df92ff7 100644 --- a/panda/src/particlesystem/pointParticleFactory.h +++ b/panda/src/particlesystem/pointParticleFactory.h @@ -20,14 +20,14 @@ * Creates point particles to user specs */ -class EXPCL_PANDAPHYSICS PointParticleFactory : public BaseParticleFactory { +class EXPCL_PANDA_PARTICLESYSTEM PointParticleFactory : public BaseParticleFactory { PUBLISHED: PointParticleFactory(); PointParticleFactory(const PointParticleFactory ©); virtual ~PointParticleFactory(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: virtual BaseParticle *alloc_particle() const; diff --git a/panda/src/particlesystem/pointParticleRenderer.cxx b/panda/src/particlesystem/pointParticleRenderer.cxx index 2a5d345d37..04374bf536 100644 --- a/panda/src/particlesystem/pointParticleRenderer.cxx +++ b/panda/src/particlesystem/pointParticleRenderer.cxx @@ -167,7 +167,7 @@ create_color(const BaseParticle *p) { if (_alpha_mode == PR_ALPHA_OUT) { parameterized_age = 1.0f - parameterized_age; } else if (_alpha_mode == PR_ALPHA_IN_OUT) { - parameterized_age = 2.0f * min(parameterized_age, + parameterized_age = 2.0f * std::min(parameterized_age, 1.0f - parameterized_age); } } @@ -257,7 +257,7 @@ render(pvector< PT(PhysicsObject) >& po_vector, int ttl_particles) { * Write a string representation of this instance to . */ void PointParticleRenderer:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"PointParticleRenderer"; #endif //] NDEBUG @@ -267,7 +267,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void PointParticleRenderer:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "PointParticleRenderer:\n"; indent(out, indent_level + 2) << "_start_color "<<_start_color<<"\n"; indent(out, indent_level + 2) << "_end_color "<<_end_color<<"\n"; diff --git a/panda/src/particlesystem/pointParticleRenderer.h b/panda/src/particlesystem/pointParticleRenderer.h index 3f7ed52612..ff2f7b3f98 100644 --- a/panda/src/particlesystem/pointParticleRenderer.h +++ b/panda/src/particlesystem/pointParticleRenderer.h @@ -30,7 +30,7 @@ * BillboardParticleRenderer for that. */ -class EXPCL_PANDAPHYSICS PointParticleRenderer : public BaseParticleRenderer { +class EXPCL_PANDA_PARTICLESYSTEM PointParticleRenderer : public BaseParticleRenderer { PUBLISHED: enum PointParticleBlendType { PP_ONE_COLOR, @@ -64,8 +64,8 @@ PUBLISHED: INLINE PointParticleBlendType get_blend_type() const; INLINE ParticleRendererBlendMethod get_blend_method() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; private: LColor _start_color; diff --git a/panda/src/particlesystem/rectangleEmitter.cxx b/panda/src/particlesystem/rectangleEmitter.cxx index f261662486..d23de128e3 100644 --- a/panda/src/particlesystem/rectangleEmitter.cxx +++ b/panda/src/particlesystem/rectangleEmitter.cxx @@ -76,7 +76,7 @@ assign_initial_velocity(LVector3& vel) { * Write a string representation of this instance to . */ void RectangleEmitter:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"RectangleEmitter"; #endif //] NDEBUG @@ -86,7 +86,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void RectangleEmitter:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"RectangleEmitter:\n"; out.width(indent+2); out<<""; out<<"_vmin "<<_vmin<<"\n"; diff --git a/panda/src/particlesystem/rectangleEmitter.h b/panda/src/particlesystem/rectangleEmitter.h index ecd95728e1..d425c70618 100644 --- a/panda/src/particlesystem/rectangleEmitter.h +++ b/panda/src/particlesystem/rectangleEmitter.h @@ -19,7 +19,7 @@ /** * Describes a planar square region in which particles are generated. */ -class EXPCL_PANDAPHYSICS RectangleEmitter : public BaseParticleEmitter { +class EXPCL_PANDA_PARTICLESYSTEM RectangleEmitter : public BaseParticleEmitter { PUBLISHED: RectangleEmitter(); RectangleEmitter(const RectangleEmitter ©); @@ -33,8 +33,8 @@ PUBLISHED: INLINE LPoint2 get_min_bound() const; INLINE LPoint2 get_max_bound() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: LPoint2 _vmin; diff --git a/panda/src/particlesystem/ringEmitter.cxx b/panda/src/particlesystem/ringEmitter.cxx index c9f7009807..1c4e4ee5fd 100644 --- a/panda/src/particlesystem/ringEmitter.cxx +++ b/panda/src/particlesystem/ringEmitter.cxx @@ -105,7 +105,7 @@ assign_initial_velocity(LVector3& vel) { * Write a string representation of this instance to . */ void RingEmitter:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"RingEmitter"; #endif //] NDEBUG @@ -115,7 +115,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void RingEmitter:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"RingEmitter:\n"; out.width(indent+2); out<<""; out<<"_radius "<<_radius<<"\n"; diff --git a/panda/src/particlesystem/ringEmitter.h b/panda/src/particlesystem/ringEmitter.h index 0278e8ac97..cdd3d484f7 100644 --- a/panda/src/particlesystem/ringEmitter.h +++ b/panda/src/particlesystem/ringEmitter.h @@ -19,7 +19,7 @@ /** * Describes a planar ring region in which particles are generated. */ -class EXPCL_PANDAPHYSICS RingEmitter : public BaseParticleEmitter { +class EXPCL_PANDA_PARTICLESYSTEM RingEmitter : public BaseParticleEmitter { PUBLISHED: RingEmitter(); RingEmitter(const RingEmitter ©); @@ -37,8 +37,8 @@ PUBLISHED: INLINE PN_stdfloat get_radius_spread() const; INLINE int get_uniform_emission() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; protected: PN_stdfloat _radius; diff --git a/panda/src/particlesystem/sparkleParticleRenderer.cxx b/panda/src/particlesystem/sparkleParticleRenderer.cxx index 5dc2d0772b..63a7124b59 100644 --- a/panda/src/particlesystem/sparkleParticleRenderer.cxx +++ b/panda/src/particlesystem/sparkleParticleRenderer.cxx @@ -192,7 +192,7 @@ render(pvector< PT(PhysicsObject) >& po_vector, int ttl_particles) { if (_alpha_mode == PR_ALPHA_OUT) alpha = 1.0f - alpha; else if (_alpha_mode == PR_ALPHA_IN_OUT) - alpha = 2.0f * min(alpha, 1.0f - alpha); + alpha = 2.0f * std::min(alpha, 1.0f - alpha); alpha *= get_user_alpha(); } @@ -262,7 +262,7 @@ render(pvector< PT(PhysicsObject) >& po_vector, int ttl_particles) { * Write a string representation of this instance to . */ void SparkleParticleRenderer:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"SparkleParticleRenderer"; #endif //] NDEBUG @@ -272,7 +272,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void SparkleParticleRenderer:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "SparkleParticleRenderer:\n"; indent(out, indent_level + 2) << "_center_color "<<_center_color<<"\n"; indent(out, indent_level + 2) << "_edge_color "<<_edge_color<<"\n"; diff --git a/panda/src/particlesystem/sparkleParticleRenderer.h b/panda/src/particlesystem/sparkleParticleRenderer.h index 367dd0029d..6b81e07cc5 100644 --- a/panda/src/particlesystem/sparkleParticleRenderer.h +++ b/panda/src/particlesystem/sparkleParticleRenderer.h @@ -31,7 +31,7 @@ enum SparkleParticleLifeScale { /** * pretty sparkly things. */ -class EXPCL_PANDAPHYSICS SparkleParticleRenderer : public BaseParticleRenderer { +class EXPCL_PANDA_PARTICLESYSTEM SparkleParticleRenderer : public BaseParticleRenderer { PUBLISHED: enum SparkleParticleLifeScale { SP_NO_SCALE, @@ -65,8 +65,8 @@ PUBLISHED: INLINE PN_stdfloat get_death_radius() const; INLINE SparkleParticleLifeScale get_life_scale() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; private: LColor _center_color; diff --git a/panda/src/particlesystem/sphereSurfaceEmitter.cxx b/panda/src/particlesystem/sphereSurfaceEmitter.cxx index 37b6a274fb..9fc67113a8 100644 --- a/panda/src/particlesystem/sphereSurfaceEmitter.cxx +++ b/panda/src/particlesystem/sphereSurfaceEmitter.cxx @@ -71,7 +71,7 @@ assign_initial_velocity(LVector3& vel) { * Write a string representation of this instance to . */ void SphereSurfaceEmitter:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"SphereSurfaceEmitter"; #endif //] NDEBUG @@ -81,7 +81,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void SphereSurfaceEmitter:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"SphereSurfaceEmitter:\n"; out.width(indent+2); out<<""; out<<"_radius "<<_radius<<"\n"; diff --git a/panda/src/particlesystem/sphereSurfaceEmitter.h b/panda/src/particlesystem/sphereSurfaceEmitter.h index 50a5dda839..f2ee42488c 100644 --- a/panda/src/particlesystem/sphereSurfaceEmitter.h +++ b/panda/src/particlesystem/sphereSurfaceEmitter.h @@ -19,7 +19,7 @@ /** * Describes a curved space in which particles are generated. */ -class EXPCL_PANDAPHYSICS SphereSurfaceEmitter : public BaseParticleEmitter { +class EXPCL_PANDA_PARTICLESYSTEM SphereSurfaceEmitter : public BaseParticleEmitter { PUBLISHED: SphereSurfaceEmitter(); SphereSurfaceEmitter(const SphereSurfaceEmitter ©); @@ -30,8 +30,8 @@ PUBLISHED: INLINE void set_radius(PN_stdfloat r); INLINE PN_stdfloat get_radius() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: PN_stdfloat _radius; diff --git a/panda/src/particlesystem/sphereVolumeEmitter.cxx b/panda/src/particlesystem/sphereVolumeEmitter.cxx index 5b541ce220..985b96c21d 100644 --- a/panda/src/particlesystem/sphereVolumeEmitter.cxx +++ b/panda/src/particlesystem/sphereVolumeEmitter.cxx @@ -85,7 +85,7 @@ assign_initial_velocity(LVector3& vel) { * Write a string representation of this instance to . */ void SphereVolumeEmitter:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"SphereVolumeEmitter"; #endif //] NDEBUG @@ -95,7 +95,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void SphereVolumeEmitter:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"SphereVolumeEmitter:\n"; out.width(indent+2); out<<""; out<<"_radius "<<_radius<<"\n"; diff --git a/panda/src/particlesystem/sphereVolumeEmitter.h b/panda/src/particlesystem/sphereVolumeEmitter.h index 29d49b92a9..9907bbd3cf 100644 --- a/panda/src/particlesystem/sphereVolumeEmitter.h +++ b/panda/src/particlesystem/sphereVolumeEmitter.h @@ -19,7 +19,7 @@ /** * Describes a voluminous spherical region in which particles are generated. */ -class EXPCL_PANDAPHYSICS SphereVolumeEmitter : public BaseParticleEmitter { +class EXPCL_PANDA_PARTICLESYSTEM SphereVolumeEmitter : public BaseParticleEmitter { PUBLISHED: SphereVolumeEmitter(); SphereVolumeEmitter(const SphereVolumeEmitter ©); @@ -30,8 +30,8 @@ PUBLISHED: INLINE void set_radius(PN_stdfloat r); INLINE PN_stdfloat get_radius() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: PN_stdfloat _radius; diff --git a/panda/src/particlesystem/spriteParticleRenderer.I b/panda/src/particlesystem/spriteParticleRenderer.I index 1f1d4e488b..ccdaa9977b 100644 --- a/panda/src/particlesystem/spriteParticleRenderer.I +++ b/panda/src/particlesystem/spriteParticleRenderer.I @@ -21,7 +21,7 @@ */ INLINE void SpriteParticleRenderer:: set_texture(Texture *tex, PN_stdfloat texels_per_unit) { - if (tex != (Texture *)NULL) { + if (tex != nullptr) { // Clear all texture information _anims.clear(); @@ -46,8 +46,8 @@ add_texture(Texture *tex, PN_stdfloat texels_per_unit, bool resize) { if (_anims.size() == 0) { set_texture(tex, texels_per_unit); } else { - if(tex != (Texture *)NULL) { - if (tex != (Texture *)NULL) { + if(tex != nullptr) { + if (tex != nullptr) { _anims.push_back(new SpriteAnim(tex,LTexCoord(0.0f, 0.0f),LTexCoord(1.0f, 1.0f))); } if(resize) { @@ -269,9 +269,9 @@ get_texture() const { INLINE Texture *SpriteParticleRenderer:: get_texture(const int anim, const int frame) const { if(_anims.size() == 0) { - return (Texture*)NULL; + return nullptr; } - nassertr(anim < (int)_anims.size() && anim >= 0, (Texture*)NULL); + nassertr(anim < (int)_anims.size() && anim >= 0, nullptr); nassertr(frame < (int)_anims[anim]->get_num_frames() && frame >= 0,_anims[anim]->get_frame(0)); return _anims[anim]->get_frame(frame); } @@ -283,7 +283,7 @@ get_num_anims() const { INLINE SpriteAnim *SpriteParticleRenderer:: get_anim(const int n) const { - nassertr(n < (int)_anims.size(), (SpriteAnim*)NULL); + nassertr(n < (int)_anims.size(), nullptr); return _anims[n]; } @@ -292,7 +292,7 @@ get_last_anim() const { if (_anims.size()) { return *(_anims.end()-1); } else { - return (SpriteAnim *)NULL; + return nullptr; } } diff --git a/panda/src/particlesystem/spriteParticleRenderer.cxx b/panda/src/particlesystem/spriteParticleRenderer.cxx index 7c5756bc6f..cdd340c989 100644 --- a/panda/src/particlesystem/spriteParticleRenderer.cxx +++ b/panda/src/particlesystem/spriteParticleRenderer.cxx @@ -30,6 +30,9 @@ #include "config_particlesystem.h" #include "pStatTimer.h" +using std::max; +using std::min; + PStatCollector SpriteParticleRenderer::_render_collector("App:Particles:Sprite:Render"); /** @@ -189,7 +192,7 @@ extract_textures_from_node(const NodePath &node_path, NodePathCollection &np_col * match the new geometry. */ void SpriteParticleRenderer:: -set_from_node(const NodePath &node_path, const string &model, const string &node, bool size_from_texels) { +set_from_node(const NodePath &node_path, const std::string &model, const std::string &node, bool size_from_texels) { // Clear all texture information _anims.clear(); add_from_node(node_path,model,node,size_from_texels,true); @@ -241,7 +244,7 @@ set_from_node(const NodePath &node_path, bool size_from_texels) { * now on. (Default is false) */ void SpriteParticleRenderer:: -add_from_node(const NodePath &node_path, const string &model, const string &node, bool size_from_texels, bool resize) { +add_from_node(const NodePath &node_path, const std::string &model, const std::string &node, bool size_from_texels, bool resize) { int anim_count = _anims.size(); if (anim_count == 0) resize = true; @@ -272,7 +275,7 @@ add_from_node(const NodePath &node_path, bool size_from_texels, bool resize) { // Load the found textures into the renderer. if (extract_textures_from_node(node_path,np_col,tex_col)) { pvector< LTexCoord > ll,ur; - GeomNode *gnode = NULL; + GeomNode *gnode = nullptr; const Geom *geom; const GeomPrimitive *primitive; @@ -291,7 +294,7 @@ add_from_node(const NodePath &node_path, bool size_from_texels, bool resize) { GeomVertexReader texcoord(geom->get_vertex_data(), InternalName::get_texcoord()); if (texcoord.has_column()) { - for (int pi = 0; pi < geom->get_num_primitives(); ++pi) { + for (size_t pi = 0; pi < geom->get_num_primitives(); ++pi) { primitive = geom->get_primitive(pi); for (int vi = 0; vi < primitive->get_num_vertices(); ++vi) { int vert = primitive->get_vertex(vi); @@ -335,7 +338,7 @@ add_from_node(const NodePath &node_path, bool size_from_texels, bool resize) { GeomVertexReader vertex(geom->get_vertex_data(), InternalName::get_vertex()); if (vertex.has_column()) { - for (int pi = 0; pi < geom->get_num_primitives(); ++pi) { + for (size_t pi = 0; pi < geom->get_num_primitives(); ++pi) { primitive = geom->get_primitive(pi); for (int vi = 0; vi < primitive->get_num_vertices(); ++vi) { int vert = primitive->get_vertex(vi); @@ -479,7 +482,7 @@ init_geoms() { _sprite_writer[i].push_back(SpriteWriter()); state = state->add_attrib(RenderModeAttrib::make(RenderModeAttrib::M_unchanged, _base_y_scale * _height, true)); - if (anim->get_frame(j) != (Texture *)NULL) { + if (anim->get_frame(j) != nullptr) { state = state->add_attrib(TextureAttrib::make(anim->get_frame(j))); state = state->add_attrib(TexGenAttrib::make(TextureStage::get_default(), TexGenAttrib::M_point_sprite)); @@ -744,7 +747,7 @@ render(pvector< PT(PhysicsObject) >& po_vector, int ttl_particles) { * Write a string representation of this instance to . */ void SpriteParticleRenderer:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"SpriteParticleRenderer"; #endif //] NDEBUG @@ -754,7 +757,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void SpriteParticleRenderer:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "SpriteParticleRenderer:\n"; // indent(out, indent_level + 2) << "_sprite_primitive // "<<_sprite_primitive<<"\n"; diff --git a/panda/src/particlesystem/spriteParticleRenderer.h b/panda/src/particlesystem/spriteParticleRenderer.h index 4ab65c02fb..0de03533d6 100644 --- a/panda/src/particlesystem/spriteParticleRenderer.h +++ b/panda/src/particlesystem/spriteParticleRenderer.h @@ -75,12 +75,12 @@ PUBLISHED: ST_from_node, }; - void set_source_info(const string &tex) { + void set_source_info(const std::string &tex) { _source_type = ST_texture; _source_tex = tex; } - void set_source_info(const string &model, const string &node) { + void set_source_info(const std::string &model, const std::string &node) { _source_type = ST_from_node; _source_model = model; _source_node = node; @@ -90,15 +90,15 @@ PUBLISHED: return _source_type; } - string get_tex_source() const { + std::string get_tex_source() const { return _source_tex; } - string get_model_source() const { + std::string get_model_source() const { return _source_model; } - string get_node_source() const { + std::string get_node_source() const { return _source_node; } @@ -145,15 +145,15 @@ private: pvector< PT(Texture) > textures; pvector< LTexCoord > ll,ur; SourceType _source_type; - string _source_tex,_source_model,_source_node; + std::string _source_tex,_source_model,_source_node; }; /** * Renders a particle system with high-speed nasty trick sprites. */ -class EXPCL_PANDAPHYSICS SpriteParticleRenderer : public BaseParticleRenderer { +class EXPCL_PANDA_PARTICLESYSTEM SpriteParticleRenderer : public BaseParticleRenderer { PUBLISHED: - explicit SpriteParticleRenderer(Texture *tex = (Texture *) NULL); + explicit SpriteParticleRenderer(Texture *tex = nullptr); SpriteParticleRenderer(const SpriteParticleRenderer ©); virtual ~SpriteParticleRenderer(); @@ -162,9 +162,9 @@ public: PUBLISHED: void set_from_node(const NodePath &node_path, bool size_from_texels = false); - void set_from_node(const NodePath &node_path, const string &model, const string &node, bool size_from_texels = false); + void set_from_node(const NodePath &node_path, const std::string &model, const std::string &node, bool size_from_texels = false); void add_from_node(const NodePath &node_path, bool size_from_texels = false, bool resize = false); - void add_from_node(const NodePath &node_path, const string &model, const string &node, bool size_from_texels = false, bool resize = false); + void add_from_node(const NodePath &node_path, const std::string &model, const std::string &node, bool size_from_texels = false, bool resize = false); INLINE void set_texture(Texture *tex, PN_stdfloat texels_per_unit = 1.0f); INLINE void add_texture(Texture *tex, PN_stdfloat texels_per_unit = 1.0f, bool resize = false); @@ -217,8 +217,8 @@ PUBLISHED: INLINE PN_stdfloat get_animate_frames_rate() const; INLINE int get_animate_frames_index() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; private: pvector< pvector< PT(Geom) > > _sprite_primitive; diff --git a/panda/src/particlesystem/tangentRingEmitter.cxx b/panda/src/particlesystem/tangentRingEmitter.cxx index 5c77c5491e..13bbf6f8bc 100644 --- a/panda/src/particlesystem/tangentRingEmitter.cxx +++ b/panda/src/particlesystem/tangentRingEmitter.cxx @@ -73,7 +73,7 @@ assign_initial_velocity(LVector3& vel) { * Write a string representation of this instance to . */ void TangentRingEmitter:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"TangentRingEmitter"; #endif //] NDEBUG @@ -83,7 +83,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void TangentRingEmitter:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"TangentRingEmitter:\n"; out.width(indent+2); out<<""; out<<"_radius "<<_radius<<"\n"; diff --git a/panda/src/particlesystem/tangentRingEmitter.h b/panda/src/particlesystem/tangentRingEmitter.h index 0bea13ee17..51bd8112b3 100644 --- a/panda/src/particlesystem/tangentRingEmitter.h +++ b/panda/src/particlesystem/tangentRingEmitter.h @@ -20,7 +20,7 @@ * Describes a planar ring region in which tangent particles are generated, * and particles fly off tangential to the ring. */ -class EXPCL_PANDAPHYSICS TangentRingEmitter : public BaseParticleEmitter { +class EXPCL_PANDA_PARTICLESYSTEM TangentRingEmitter : public BaseParticleEmitter { PUBLISHED: TangentRingEmitter(); TangentRingEmitter(const TangentRingEmitter ©); @@ -34,8 +34,8 @@ PUBLISHED: INLINE PN_stdfloat get_radius() const; INLINE PN_stdfloat get_radius_spread() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: PN_stdfloat _radius; diff --git a/panda/src/particlesystem/zSpinParticle.cxx b/panda/src/particlesystem/zSpinParticle.cxx index 560fa12a72..7808c2833e 100644 --- a/panda/src/particlesystem/zSpinParticle.cxx +++ b/panda/src/particlesystem/zSpinParticle.cxx @@ -108,7 +108,7 @@ get_theta() const { * Write a string representation of this instance to . */ void ZSpinParticle:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"ZSpinParticle"; #endif //] NDEBUG @@ -118,7 +118,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void ZSpinParticle:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"ZSpinParticle:\n"; out.width(indent+2); out<<""; out<<"_initial_angle "<<_initial_angle<<"\n"; diff --git a/panda/src/particlesystem/zSpinParticle.h b/panda/src/particlesystem/zSpinParticle.h index 302aedc5d9..da5d39197b 100644 --- a/panda/src/particlesystem/zSpinParticle.h +++ b/panda/src/particlesystem/zSpinParticle.h @@ -22,7 +22,7 @@ * your sprites to spin without having them be full-blown oriented (i.e. * angry quat math), use this. */ -class EXPCL_PANDAPHYSICS ZSpinParticle : public BaseParticle { +class EXPCL_PANDA_PARTICLESYSTEM ZSpinParticle : public BaseParticle { public: ZSpinParticle(); ZSpinParticle(const ZSpinParticle ©); @@ -50,8 +50,8 @@ public: INLINE void enable_angular_velocity(bool bEnabled); INLINE bool get_angular_velocity_enabled() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: PN_stdfloat _initial_angle; diff --git a/panda/src/particlesystem/zSpinParticleFactory.cxx b/panda/src/particlesystem/zSpinParticleFactory.cxx index f8c21efccb..5f260714d7 100644 --- a/panda/src/particlesystem/zSpinParticleFactory.cxx +++ b/panda/src/particlesystem/zSpinParticleFactory.cxx @@ -76,7 +76,7 @@ populate_child_particle(BaseParticle *bp) const { * Write a string representation of this instance to . */ void ZSpinParticleFactory:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"ZSpinParticleFactory"; #endif //] NDEBUG @@ -86,7 +86,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void ZSpinParticleFactory:: -write(ostream &out, int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"ZSpinParticleFactory:\n"; out.width(indent+2); out<<""; out<<"_initial_angle "<<_initial_angle<<"\n"; diff --git a/panda/src/particlesystem/zSpinParticleFactory.h b/panda/src/particlesystem/zSpinParticleFactory.h index ca6aa5b8d8..491b1bf65f 100644 --- a/panda/src/particlesystem/zSpinParticleFactory.h +++ b/panda/src/particlesystem/zSpinParticleFactory.h @@ -19,7 +19,7 @@ /** * */ -class EXPCL_PANDAPHYSICS ZSpinParticleFactory : public BaseParticleFactory { +class EXPCL_PANDA_PARTICLESYSTEM ZSpinParticleFactory : public BaseParticleFactory { PUBLISHED: ZSpinParticleFactory(); ZSpinParticleFactory(const ZSpinParticleFactory ©); @@ -44,8 +44,8 @@ PUBLISHED: INLINE void enable_angular_velocity(bool bEnabled); INLINE bool get_angular_velocity_enabled() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: PN_stdfloat _initial_angle; diff --git a/panda/src/pgraph/accumulatedAttribs.cxx b/panda/src/pgraph/accumulatedAttribs.cxx index ea35b495ab..94faa3072a 100644 --- a/panda/src/pgraph/accumulatedAttribs.cxx +++ b/panda/src/pgraph/accumulatedAttribs.cxx @@ -85,40 +85,40 @@ operator = (const AccumulatedAttribs ©) { * */ void AccumulatedAttribs:: -write(ostream &out, int attrib_types, int indent_level) const { +write(std::ostream &out, int attrib_types, int indent_level) const { if ((attrib_types & SceneGraphReducer::TT_transform) != 0) { _transform->write(out, indent_level); } if ((attrib_types & SceneGraphReducer::TT_color) != 0) { - if (_color == (const RenderAttrib *)NULL) { + if (_color == nullptr) { indent(out, indent_level) << "no color\n"; } else { _color->write(out, indent_level); } } if ((attrib_types & SceneGraphReducer::TT_color_scale) != 0) { - if (_color_scale == (const RenderAttrib *)NULL) { + if (_color_scale == nullptr) { indent(out, indent_level) << "no color scale\n"; } else { _color_scale->write(out, indent_level); } } if ((attrib_types & SceneGraphReducer::TT_tex_matrix) != 0) { - if (_tex_matrix == (const RenderAttrib *)NULL) { + if (_tex_matrix == nullptr) { indent(out, indent_level) << "no tex matrix\n"; } else { _tex_matrix->write(out, indent_level); } } if ((attrib_types & SceneGraphReducer::TT_clip_plane) != 0) { - if (_clip_plane == (const RenderAttrib *)NULL) { + if (_clip_plane == nullptr) { indent(out, indent_level) << "no clip plane\n"; } else { _clip_plane->write(out, indent_level); } } if ((attrib_types & SceneGraphReducer::TT_cull_face) != 0) { - if (_cull_face == (const RenderAttrib *)NULL) { + if (_cull_face == nullptr) { indent(out, indent_level) << "no cull face\n"; } else { _cull_face->write(out, indent_level); @@ -137,7 +137,7 @@ void AccumulatedAttribs:: collect(PandaNode *node, int attrib_types) { if ((attrib_types & SceneGraphReducer::TT_transform) != 0) { // Collect the node's transform. - nassertv(_transform != (TransformState *)NULL); + nassertv(_transform != nullptr); _transform = _transform->compose(node->get_transform()); node->set_transform(TransformState::make_identity()); node->set_prev_transform(TransformState::make_identity()); @@ -158,12 +158,12 @@ collect(const RenderState *state, int attrib_types) { if ((attrib_types & SceneGraphReducer::TT_color) != 0) { const RenderAttrib *node_attrib = new_state->get_attrib(ColorAttrib::get_class_slot()); - if (node_attrib != (const RenderAttrib *)NULL) { + if (node_attrib != nullptr) { int color_override = new_state->get_override(ColorAttrib::get_class_slot()); if (color_override >= _color_override || - _color == (const RenderAttrib *)NULL) { + _color == nullptr) { // The node has a color attribute; apply it. - if (_color == (const RenderAttrib *)NULL) { + if (_color == nullptr) { _color = node_attrib; } else { _color = _color->compose(node_attrib); @@ -177,11 +177,11 @@ collect(const RenderState *state, int attrib_types) { if ((attrib_types & SceneGraphReducer::TT_color_scale) != 0) { const RenderAttrib *node_attrib = new_state->get_attrib(ColorScaleAttrib::get_class_slot()); - if (node_attrib != (const RenderAttrib *)NULL) { + if (node_attrib != nullptr) { int color_scale_override = new_state->get_override(ColorScaleAttrib::get_class_slot()); if (color_scale_override >= _color_scale_override || - _color_scale == (const RenderAttrib *)NULL) { - if (_color_scale == (const RenderAttrib *)NULL) { + _color_scale == nullptr) { + if (_color_scale == nullptr) { _color_scale = node_attrib; } else { _color_scale = _color_scale->compose(node_attrib); @@ -195,11 +195,11 @@ collect(const RenderState *state, int attrib_types) { if ((attrib_types & SceneGraphReducer::TT_tex_matrix) != 0) { const RenderAttrib *node_attrib = new_state->get_attrib(TexMatrixAttrib::get_class_slot()); - if (node_attrib != (const RenderAttrib *)NULL) { + if (node_attrib != nullptr) { int tex_matrix_override = new_state->get_override(TexMatrixAttrib::get_class_slot()); if (tex_matrix_override >= _tex_matrix_override || - _tex_matrix == (const RenderAttrib *)NULL) { - if (_tex_matrix == (const RenderAttrib *)NULL) { + _tex_matrix == nullptr) { + if (_tex_matrix == nullptr) { _tex_matrix = node_attrib; } else { _tex_matrix = _tex_matrix->compose(node_attrib); @@ -213,11 +213,11 @@ collect(const RenderState *state, int attrib_types) { // texture matrix. const RenderAttrib *tex_attrib = new_state->get_attrib(TextureAttrib::get_class_slot()); - if (tex_attrib != (const RenderAttrib *)NULL) { + if (tex_attrib != nullptr) { int texture_override = new_state->get_override(TextureAttrib::get_class_slot()); if (texture_override >= _texture_override || - _texture == (const RenderAttrib *)NULL) { - if (_texture == (const RenderAttrib *)NULL) { + _texture == nullptr) { + if (_texture == nullptr) { _texture = tex_attrib; } else { _texture = _texture->compose(tex_attrib); @@ -234,11 +234,11 @@ collect(const RenderState *state, int attrib_types) { if ((attrib_types & SceneGraphReducer::TT_clip_plane) != 0) { const RenderAttrib *node_attrib = new_state->get_attrib(ClipPlaneAttrib::get_class_slot()); - if (node_attrib != (const RenderAttrib *)NULL) { + if (node_attrib != nullptr) { int clip_plane_override = new_state->get_override(ClipPlaneAttrib::get_class_slot()); if (clip_plane_override >= _clip_plane_override || - _clip_plane == (const RenderAttrib *)NULL) { - if (_clip_plane == (const RenderAttrib *)NULL) { + _clip_plane == nullptr) { + if (_clip_plane == nullptr) { _clip_plane = node_attrib; } else { _clip_plane = _clip_plane->compose(node_attrib); @@ -252,11 +252,11 @@ collect(const RenderState *state, int attrib_types) { if ((attrib_types & SceneGraphReducer::TT_cull_face) != 0) { const RenderAttrib *node_attrib = new_state->get_attrib(CullFaceAttrib::get_class_slot()); - if (node_attrib != (const RenderAttrib *)NULL) { + if (node_attrib != nullptr) { int cull_face_override = new_state->get_override(CullFaceAttrib::get_class_slot()); if (cull_face_override >= _cull_face_override || - _cull_face == (const RenderAttrib *)NULL) { - if (_cull_face == (const RenderAttrib *)NULL) { + _cull_face == nullptr) { + if (_cull_face == nullptr) { _cull_face = node_attrib; } else { _cull_face = _cull_face->compose(node_attrib); @@ -269,7 +269,7 @@ collect(const RenderState *state, int attrib_types) { if ((attrib_types & SceneGraphReducer::TT_other) != 0) { // Collect everything else. - nassertr(_other != (RenderState *)NULL, new_state); + nassertr(_other != nullptr, new_state); _other = _other->compose(new_state); new_state = RenderState::make_empty(); } @@ -291,67 +291,67 @@ apply_to_node(PandaNode *node, int attrib_types) { } if ((attrib_types & SceneGraphReducer::TT_color) != 0) { - if (_color != (RenderAttrib *)NULL) { + if (_color != nullptr) { const RenderAttrib *node_attrib = node->get_attrib(ColorAttrib::get_class_slot()); - if (node_attrib != (RenderAttrib *)NULL) { + if (node_attrib != nullptr) { node->set_attrib(_color->compose(node_attrib)->get_unique()); } else { node->set_attrib(_color->get_unique()); } - _color = (RenderAttrib *)NULL; + _color = nullptr; } } if ((attrib_types & SceneGraphReducer::TT_color_scale) != 0) { - if (_color_scale != (RenderAttrib *)NULL) { + if (_color_scale != nullptr) { const RenderAttrib *node_attrib = node->get_attrib(ColorScaleAttrib::get_class_slot()); - if (node_attrib != (RenderAttrib *)NULL) { + if (node_attrib != nullptr) { node->set_attrib(_color_scale->compose(node_attrib)->get_unique()); } else { node->set_attrib(_color_scale->get_unique()); } - _color_scale = (RenderAttrib *)NULL; + _color_scale = nullptr; } } if ((attrib_types & SceneGraphReducer::TT_tex_matrix) != 0) { - if (_tex_matrix != (RenderAttrib *)NULL) { + if (_tex_matrix != nullptr) { const RenderAttrib *node_attrib = node->get_attrib(TexMatrixAttrib::get_class_slot()); - if (node_attrib != (RenderAttrib *)NULL) { + if (node_attrib != nullptr) { node->set_attrib(_tex_matrix->compose(node_attrib)->get_unique()); } else { node->set_attrib(_tex_matrix->get_unique()); } - _tex_matrix = (RenderAttrib *)NULL; + _tex_matrix = nullptr; } } if ((attrib_types & SceneGraphReducer::TT_clip_plane) != 0) { - if (_clip_plane != (RenderAttrib *)NULL) { + if (_clip_plane != nullptr) { const RenderAttrib *node_attrib = node->get_attrib(ClipPlaneAttrib::get_class_slot()); - if (node_attrib != (RenderAttrib *)NULL) { + if (node_attrib != nullptr) { node->set_attrib(_clip_plane->compose(node_attrib)->get_unique()); } else { node->set_attrib(_clip_plane->get_unique()); } - _clip_plane = (RenderAttrib *)NULL; + _clip_plane = nullptr; } } if ((attrib_types & SceneGraphReducer::TT_cull_face) != 0) { - if (_cull_face != (RenderAttrib *)NULL) { + if (_cull_face != nullptr) { const RenderAttrib *node_attrib = node->get_attrib(CullFaceAttrib::get_class_slot()); - if (node_attrib != (RenderAttrib *)NULL) { + if (node_attrib != nullptr) { node->set_attrib(_cull_face->compose(node_attrib)->get_unique()); } else { node->set_attrib(_cull_face->get_unique()); } - _cull_face = (RenderAttrib *)NULL; + _cull_face = nullptr; } } diff --git a/panda/src/pgraph/accumulatedAttribs.h b/panda/src/pgraph/accumulatedAttribs.h index d71da61111..3d7680cb9a 100644 --- a/panda/src/pgraph/accumulatedAttribs.h +++ b/panda/src/pgraph/accumulatedAttribs.h @@ -33,7 +33,7 @@ public: AccumulatedAttribs(const AccumulatedAttribs ©); void operator = (const AccumulatedAttribs ©); - void write(ostream &out, int attrib_types, int indent_level) const; + void write(std::ostream &out, int attrib_types, int indent_level) const; void collect(PandaNode *node, int attrib_types); CPT(RenderState) collect(const RenderState *state, int attrib_types); diff --git a/panda/src/pgraph/alphaTestAttrib.cxx b/panda/src/pgraph/alphaTestAttrib.cxx index a302026623..331b709478 100644 --- a/panda/src/pgraph/alphaTestAttrib.cxx +++ b/panda/src/pgraph/alphaTestAttrib.cxx @@ -46,7 +46,7 @@ make_default() { * */ void AlphaTestAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; output_comparefunc(out,_mode); out << "," << _reference_alpha; diff --git a/panda/src/pgraph/alphaTestAttrib.h b/panda/src/pgraph/alphaTestAttrib.h index d9aae7ec5b..96225fe902 100644 --- a/panda/src/pgraph/alphaTestAttrib.h +++ b/panda/src/pgraph/alphaTestAttrib.h @@ -41,7 +41,7 @@ PUBLISHED: MAKE_PROPERTY(mode, get_mode); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/antialiasAttrib.cxx b/panda/src/pgraph/antialiasAttrib.cxx index ef35490753..260b4fdef1 100644 --- a/panda/src/pgraph/antialiasAttrib.cxx +++ b/panda/src/pgraph/antialiasAttrib.cxx @@ -69,7 +69,7 @@ make_default() { * */ void AntialiasAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; int type = get_mode_type(); diff --git a/panda/src/pgraph/antialiasAttrib.h b/panda/src/pgraph/antialiasAttrib.h index af149af5f6..454210516d 100644 --- a/panda/src/pgraph/antialiasAttrib.h +++ b/panda/src/pgraph/antialiasAttrib.h @@ -58,7 +58,7 @@ PUBLISHED: MAKE_PROPERTY(mode_quality, get_mode_quality); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/attribNodeRegistry.I b/panda/src/pgraph/attribNodeRegistry.I index 30e66ca84c..04a540466b 100644 --- a/panda/src/pgraph/attribNodeRegistry.I +++ b/panda/src/pgraph/attribNodeRegistry.I @@ -16,7 +16,7 @@ */ INLINE AttribNodeRegistry *AttribNodeRegistry:: get_global_ptr() { - if (_global_ptr == (AttribNodeRegistry *)NULL) { + if (_global_ptr == nullptr) { make_global_ptr(); } return _global_ptr; @@ -37,7 +37,7 @@ Entry(const NodePath &node) : * */ INLINE AttribNodeRegistry::Entry:: -Entry(TypeHandle type, const string &name) : +Entry(TypeHandle type, const std::string &name) : _type(type), _name(name) { diff --git a/panda/src/pgraph/attribNodeRegistry.cxx b/panda/src/pgraph/attribNodeRegistry.cxx index 0d540c19d2..721feb5572 100644 --- a/panda/src/pgraph/attribNodeRegistry.cxx +++ b/panda/src/pgraph/attribNodeRegistry.cxx @@ -41,7 +41,7 @@ add_node(const NodePath &attrib_node) { nassertv(!attrib_node.is_empty()); LightMutexHolder holder(_lock); - pair result = _entries.insert(Entry(attrib_node)); + std::pair result = _entries.insert(Entry(attrib_node)); if (!result.second) { // Replace an existing node. (*result.first)._node = attrib_node; @@ -119,10 +119,10 @@ get_node_type(int n) const { * be the node name as it was at the time the node was recorded; if the node * has changed names since then, this will still return the original name. */ -string AttribNodeRegistry:: +std::string AttribNodeRegistry:: get_node_name(int n) const { LightMutexHolder holder(_lock); - nassertr(n >= 0 && n < (int)_entries.size(), string()); + nassertr(n >= 0 && n < (int)_entries.size(), std::string()); return _entries[n]._name; } @@ -148,7 +148,7 @@ find_node(const NodePath &attrib_node) const { * the registry, or -1 if there is no such node in the registry. */ int AttribNodeRegistry:: -find_node(TypeHandle type, const string &name) const { +find_node(TypeHandle type, const std::string &name) const { LightMutexHolder holder(_lock); Entries::const_iterator ei = _entries.find(Entry(type, name)); if (ei != _entries.end()) { @@ -180,7 +180,7 @@ clear() { * */ void AttribNodeRegistry:: -output(ostream &out) const { +output(std::ostream &out) const { LightMutexHolder holder(_lock); typedef pmap Counts; @@ -211,7 +211,7 @@ output(ostream &out) const { * */ void AttribNodeRegistry:: -write(ostream &out) const { +write(std::ostream &out) const { LightMutexHolder holder(_lock); Entries::const_iterator ei; @@ -229,10 +229,10 @@ void AttribNodeRegistry:: make_global_ptr() { AttribNodeRegistry *ptr = new AttribNodeRegistry; void *result = AtomicAdjust::compare_and_exchange_ptr - ((void * TVOLATILE &)_global_ptr, (void *)NULL, (void *)ptr); - if (result != NULL) { + ((void * TVOLATILE &)_global_ptr, nullptr, (void *)ptr); + if (result != nullptr) { // Someone else got there first. delete ptr; } - assert(_global_ptr != (AttribNodeRegistry *)NULL); + assert(_global_ptr != nullptr); } diff --git a/panda/src/pgraph/attribNodeRegistry.h b/panda/src/pgraph/attribNodeRegistry.h index 46170e1ea9..51efa8ead0 100644 --- a/panda/src/pgraph/attribNodeRegistry.h +++ b/panda/src/pgraph/attribNodeRegistry.h @@ -43,15 +43,15 @@ PUBLISHED: NodePath get_node(int n) const; MAKE_SEQ(get_nodes, get_num_nodes, get_node); TypeHandle get_node_type(int n) const; - string get_node_name(int n) const; + std::string get_node_name(int n) const; int find_node(const NodePath &attrib_node) const; - int find_node(TypeHandle type, const string &name) const; + int find_node(TypeHandle type, const std::string &name) const; void remove_node(int n); void clear(); - void output(ostream &out) const; - void write(ostream &out) const; + void output(std::ostream &out) const; + void write(std::ostream &out) const; INLINE static AttribNodeRegistry *get_global_ptr(); @@ -61,11 +61,11 @@ private: class Entry { public: INLINE Entry(const NodePath &node); - INLINE Entry(TypeHandle type, const string &name); + INLINE Entry(TypeHandle type, const std::string &name); INLINE bool operator < (const Entry &other) const; TypeHandle _type; - string _name; + std::string _name; NodePath _node; }; diff --git a/panda/src/pgraph/audioVolumeAttrib.cxx b/panda/src/pgraph/audioVolumeAttrib.cxx index 1f545cef8e..23c6a4d7d8 100644 --- a/panda/src/pgraph/audioVolumeAttrib.cxx +++ b/panda/src/pgraph/audioVolumeAttrib.cxx @@ -43,7 +43,7 @@ CPT(RenderAttrib) AudioVolumeAttrib:: make_identity() { // We make identity a special case and store a pointer forever once we find // it the first time. - if (_identity_attrib == (AudioVolumeAttrib *)NULL) { + if (_identity_attrib == nullptr) { AudioVolumeAttrib *attrib = new AudioVolumeAttrib(false, 1.0f);; _identity_attrib = return_new(attrib); } @@ -99,7 +99,7 @@ set_volume(PN_stdfloat volume) const { * */ void AudioVolumeAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; if (is_off()) { out << "off"; diff --git a/panda/src/pgraph/audioVolumeAttrib.h b/panda/src/pgraph/audioVolumeAttrib.h index abf1216130..564db9748e 100644 --- a/panda/src/pgraph/audioVolumeAttrib.h +++ b/panda/src/pgraph/audioVolumeAttrib.h @@ -44,7 +44,7 @@ PUBLISHED: MAKE_PROPERTY2(volume, has_volume, get_volume); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/auxBitplaneAttrib.cxx b/panda/src/pgraph/auxBitplaneAttrib.cxx index 8f8e2d8a9f..16f87b03f2 100644 --- a/panda/src/pgraph/auxBitplaneAttrib.cxx +++ b/panda/src/pgraph/auxBitplaneAttrib.cxx @@ -28,7 +28,7 @@ CPT(RenderAttrib) AuxBitplaneAttrib::_default; */ CPT(RenderAttrib) AuxBitplaneAttrib:: make() { - if (_default == 0) { + if (_default == nullptr) { AuxBitplaneAttrib *attrib = new AuxBitplaneAttrib(0); _default = return_new(attrib); } @@ -57,7 +57,7 @@ make_default() { * */ void AuxBitplaneAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << "(" << _outputs << ")"; } diff --git a/panda/src/pgraph/auxBitplaneAttrib.h b/panda/src/pgraph/auxBitplaneAttrib.h index 26ce021110..6283b09587 100644 --- a/panda/src/pgraph/auxBitplaneAttrib.h +++ b/panda/src/pgraph/auxBitplaneAttrib.h @@ -67,7 +67,7 @@ PUBLISHED: MAKE_PROPERTY(outputs, get_outputs); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/auxSceneData.I b/panda/src/pgraph/auxSceneData.I index e80d5f6469..f2e7912cfc 100644 --- a/panda/src/pgraph/auxSceneData.I +++ b/panda/src/pgraph/auxSceneData.I @@ -68,8 +68,8 @@ get_expiration_time() const { return _last_render_time + _duration; } -INLINE ostream & -operator << (ostream &out, const AuxSceneData &data) { +INLINE std::ostream & +operator << (std::ostream &out, const AuxSceneData &data) { data.output(out); return out; } diff --git a/panda/src/pgraph/auxSceneData.cxx b/panda/src/pgraph/auxSceneData.cxx index b0a50cb1c0..2ef626c270 100644 --- a/panda/src/pgraph/auxSceneData.cxx +++ b/panda/src/pgraph/auxSceneData.cxx @@ -20,7 +20,7 @@ TypeHandle AuxSceneData::_type_handle; * */ void AuxSceneData:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << " expires " << get_expiration_time(); } @@ -28,6 +28,6 @@ output(ostream &out) const { * */ void AuxSceneData:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << *this << "\n"; } diff --git a/panda/src/pgraph/auxSceneData.h b/panda/src/pgraph/auxSceneData.h index ec117bdc17..90741dde05 100644 --- a/panda/src/pgraph/auxSceneData.h +++ b/panda/src/pgraph/auxSceneData.h @@ -41,8 +41,8 @@ PUBLISHED: INLINE double get_expiration_time() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; protected: double _duration; @@ -66,7 +66,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const AuxSceneData &data); +INLINE std::ostream &operator << (std::ostream &out, const AuxSceneData &data); #include "auxSceneData.I" diff --git a/panda/src/pgraph/bamFile.I b/panda/src/pgraph/bamFile.I index b3305cbe48..70e264358e 100644 --- a/panda/src/pgraph/bamFile.I +++ b/panda/src/pgraph/bamFile.I @@ -17,7 +17,7 @@ */ INLINE bool BamFile:: is_valid_read() const { - return (_reader != (BamReader *)NULL); + return (_reader != nullptr); } @@ -27,5 +27,5 @@ is_valid_read() const { */ INLINE bool BamFile:: is_valid_write() const { - return (_writer != (BamWriter *)NULL); + return (_writer != nullptr); } diff --git a/panda/src/pgraph/bamFile.cxx b/panda/src/pgraph/bamFile.cxx index 871ec94587..5bf0d5af88 100644 --- a/panda/src/pgraph/bamFile.cxx +++ b/panda/src/pgraph/bamFile.cxx @@ -24,13 +24,15 @@ #include "virtualFileSystem.h" #include "dcast.h" +using std::string; + /** * */ BamFile:: BamFile() { - _reader = NULL; - _writer = NULL; + _reader = nullptr; + _writer = nullptr; } /** @@ -61,7 +63,7 @@ open_read(const Filename &bam_filename, bool report_errors) { * for information purposes only. Returns true if successful, false on error. */ bool BamFile:: -open_read(istream &in, const string &bam_filename, bool report_errors) { +open_read(std::istream &in, const string &bam_filename, bool report_errors) { close(); if (!_din.open(in)) { @@ -81,8 +83,8 @@ open_read(istream &in, const string &bam_filename, bool report_errors) { */ TypedWritable *BamFile:: read_object() { - if (_reader == (BamReader *)NULL) { - return NULL; + if (_reader == nullptr) { + return nullptr; } return _reader->read_object(); @@ -94,7 +96,7 @@ read_object() { */ bool BamFile:: is_eof() const { - return _reader != (BamReader *)NULL && _reader->is_eof(); + return _reader != nullptr && _reader->is_eof(); } /** @@ -106,7 +108,7 @@ is_eof() const { */ bool BamFile:: resolve() { - if (_reader == (BamReader *)NULL) { + if (_reader == nullptr) { return false; } @@ -134,7 +136,7 @@ read_node(bool report_errors) { TypedWritable *object = read_object(); - if (object != (TypedWritable *)NULL && + if (object != nullptr && object->is_exact_type(BamCacheRecord::get_class_type())) { // Here's a special case: if the first object in the file is a // BamCacheRecord, it's really a cache data file and not a true bam file; @@ -172,7 +174,7 @@ read_node(bool report_errors) { loader_cat.error() << "Unable to resolve Bam file.\n"; } - result = (PandaNode *)NULL; + result = nullptr; } return result; @@ -205,7 +207,7 @@ open_write(const Filename &bam_filename, bool report_errors) { * for information purposes only. Returns true if successful, false on error. */ bool BamFile:: -open_write(ostream &out, const string &bam_filename, bool report_errors) { +open_write(std::ostream &out, const string &bam_filename, bool report_errors) { close(); if (!_dout.open(out)) { @@ -222,7 +224,7 @@ open_write(ostream &out, const string &bam_filename, bool report_errors) { */ bool BamFile:: write_object(const TypedWritable *object) { - if (_writer == (BamWriter *)NULL) { + if (_writer == nullptr) { return false; } @@ -239,14 +241,14 @@ write_object(const TypedWritable *object) { */ void BamFile:: close() { - if (_reader != (BamReader *)NULL) { + if (_reader != nullptr) { // resolve(); delete _reader; - _reader = NULL; + _reader = nullptr; } - if (_writer != (BamWriter *)NULL) { + if (_writer != nullptr) { delete _writer; - _writer = NULL; + _writer = nullptr; } _din.close(); _dout.close(); @@ -260,7 +262,7 @@ close() { */ int BamFile:: get_file_major_ver() { - if (_reader == (BamReader *)NULL) { + if (_reader == nullptr) { return _bam_major_ver; } return _reader->get_file_major_ver(); @@ -273,7 +275,7 @@ get_file_major_ver() { */ int BamFile:: get_file_minor_ver() { - if (_reader == (BamReader *)NULL) { + if (_reader == nullptr) { return _bam_minor_ver; } return _reader->get_file_minor_ver(); @@ -285,10 +287,10 @@ get_file_minor_ver() { */ BamFile::BamEndian BamFile:: get_file_endian() const { - if (_writer != (BamWriter *)NULL) { + if (_writer != nullptr) { return _writer->get_file_endian(); } - if (_reader != (BamReader *)NULL) { + if (_reader != nullptr) { return _reader->get_file_endian(); } @@ -301,10 +303,10 @@ get_file_endian() const { */ bool BamFile:: get_file_stdfloat_double() const { - if (_writer != (BamWriter *)NULL) { + if (_writer != nullptr) { return _writer->get_file_stdfloat_double(); } - if (_reader != (BamReader *)NULL) { + if (_reader != nullptr) { return _reader->get_file_stdfloat_double(); } diff --git a/panda/src/pgraph/bamFile.h b/panda/src/pgraph/bamFile.h index e96581729e..a244ab3fa3 100644 --- a/panda/src/pgraph/bamFile.h +++ b/panda/src/pgraph/bamFile.h @@ -44,7 +44,7 @@ PUBLISHED: ~BamFile(); bool open_read(const Filename &bam_filename, bool report_errors = true); - bool open_read(istream &in, const string &bam_filename = "stream", + bool open_read(std::istream &in, const std::string &bam_filename = "stream", bool report_errors = true); TypedWritable *read_object(); @@ -55,7 +55,7 @@ PUBLISHED: PT(PandaNode) read_node(bool report_errors = true); bool open_write(const Filename &bam_filename, bool report_errors = true); - bool open_write(ostream &out, const string &bam_filename = "stream", + bool open_write(std::ostream &out, const std::string &bam_filename = "stream", bool report_errors = true); bool write_object(const TypedWritable *object); @@ -82,10 +82,10 @@ PUBLISHED: MAKE_PROPERTY(writer, get_writer); private: - bool continue_open_read(const string &bam_filename, bool report_errors); - bool continue_open_write(const string &bam_filename, bool report_errors); + bool continue_open_read(const std::string &bam_filename, bool report_errors); + bool continue_open_write(const std::string &bam_filename, bool report_errors); - string _bam_filename; + std::string _bam_filename; DatagramInputFile _din; DatagramOutputFile _dout; BamReader *_reader; diff --git a/panda/src/pgraph/billboardEffect.cxx b/panda/src/pgraph/billboardEffect.cxx index 737b370c42..c5843bb667 100644 --- a/panda/src/pgraph/billboardEffect.cxx +++ b/panda/src/pgraph/billboardEffect.cxx @@ -66,7 +66,7 @@ prepare_flatten_transform(const TransformState *net_transform) const { * */ void BillboardEffect:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; if (is_off()) { out << "(off)"; diff --git a/panda/src/pgraph/billboardEffect.h b/panda/src/pgraph/billboardEffect.h index 284182ba91..f83ecc5323 100644 --- a/panda/src/pgraph/billboardEffect.h +++ b/panda/src/pgraph/billboardEffect.h @@ -50,7 +50,7 @@ PUBLISHED: public: virtual bool safe_to_transform() const; virtual CPT(TransformState) prepare_flatten_transform(const TransformState *net_transform) const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; virtual bool has_cull_callback() const; virtual void cull_callback(CullTraverser *trav, CullTraverserData &data, diff --git a/panda/src/pgraph/cacheStats.I b/panda/src/pgraph/cacheStats.I index a83e480757..e84ff83878 100644 --- a/panda/src/pgraph/cacheStats.I +++ b/panda/src/pgraph/cacheStats.I @@ -17,7 +17,7 @@ INLINE void CacheStats:: maybe_report(const char *name) { #ifndef NDEBUG - if (_cache_report) { + if (UNLIKELY(_cache_report)) { double now = ClockObject::get_global_clock()->get_real_time(); if (now - _last_reset < _cache_report_interval) { return; diff --git a/panda/src/pgraph/cacheStats.cxx b/panda/src/pgraph/cacheStats.cxx index 88a5498384..4721171e86 100644 --- a/panda/src/pgraph/cacheStats.cxx +++ b/panda/src/pgraph/cacheStats.cxx @@ -22,10 +22,7 @@ void CacheStats:: init() { #ifndef NDEBUG // Let's not use the clock at static init time. - reset(0.0); - // reset(ClockObject::get_global_clock()->get_real_time()); - _total_cache_size = 0; - _num_states = 0; + //reset(ClockObject::get_global_clock()->get_real_time()); _cache_report = ConfigVariableBool("cache-report", false); _cache_report_interval = ConfigVariableDouble("cache-report-interval", 5.0); @@ -52,7 +49,7 @@ reset(double now) { * */ void CacheStats:: -write(ostream &out, const char *name) const { +write(std::ostream &out, const char *name) const { #ifndef NDEBUG out << name << " cache: " << _cache_hits << " hits, " << _cache_misses << " misses\n" diff --git a/panda/src/pgraph/cacheStats.h b/panda/src/pgraph/cacheStats.h index 45fb1e6043..daeeb5340d 100644 --- a/panda/src/pgraph/cacheStats.h +++ b/panda/src/pgraph/cacheStats.h @@ -24,9 +24,10 @@ */ class EXPCL_PANDA_PGRAPH CacheStats { public: + CacheStats() = default; void init(); void reset(double now); - void write(ostream &out, const char *name) const; + void write(std::ostream &out, const char *name) const; INLINE void maybe_report(const char *name); INLINE void inc_hits(); @@ -38,17 +39,17 @@ public: private: #ifndef NDEBUG - int _cache_hits; - int _cache_misses; - int _cache_adds; - int _cache_new_adds; - int _cache_dels; - int _total_cache_size; - int _num_states; - double _last_reset; + int _cache_hits = 0; + int _cache_misses = 0; + int _cache_adds = 0; + int _cache_new_adds = 0; + int _cache_dels = 0; + int _total_cache_size = 0; + int _num_states = 0; + double _last_reset = 0.0; - bool _cache_report; - double _cache_report_interval; + bool _cache_report = false; + double _cache_report_interval = 0.0; #endif // NDEBUG }; diff --git a/panda/src/pgraph/camera.I b/panda/src/pgraph/camera.I index 0cfcd6277d..7d32f433d3 100644 --- a/panda/src/pgraph/camera.I +++ b/panda/src/pgraph/camera.I @@ -64,7 +64,7 @@ get_num_display_regions() const { */ INLINE DisplayRegion *Camera:: get_display_region(size_t n) const { - nassertr(n < (int)_display_regions.size(), nullptr); + nassertr(n < _display_regions.size(), nullptr); return _display_regions[n]; } @@ -180,14 +180,14 @@ get_initial_state() const { * the value of the tag (as specified to set_tag_state()). */ INLINE void Camera:: -set_tag_state_key(const string &tag_state_key) { +set_tag_state_key(const std::string &tag_state_key) { _tag_state_key = tag_state_key; } /** * Returns the tag key as set by a previous call to set_tag_state_key(). */ -INLINE const string &Camera:: +INLINE const std::string &Camera:: get_tag_state_key() const { return _tag_state_key; } diff --git a/panda/src/pgraph/camera.cxx b/panda/src/pgraph/camera.cxx index aabf56eda2..5a10d6145e 100644 --- a/panda/src/pgraph/camera.cxx +++ b/panda/src/pgraph/camera.cxx @@ -16,6 +16,8 @@ #include "lens.h" #include "throw_event.h" +using std::string; + TypeHandle Camera::_type_handle; /** @@ -153,7 +155,7 @@ get_tag_state(const string &tag_state) const { */ void Camera:: set_aux_scene_data(const NodePath &node_path, AuxSceneData *data) { - if (data == (AuxSceneData *)NULL) { + if (data == nullptr) { clear_aux_scene_data(node_path); } else { _aux_data[node_path] = data; @@ -188,14 +190,14 @@ get_aux_scene_data(const NodePath &node_path) const { return (*ai).second; } - return NULL; + return nullptr; } /** * Outputs all of the NodePaths and AuxSceneDatas in use. */ void Camera:: -list_aux_scene_data(ostream &out) const { +list_aux_scene_data(std::ostream &out) const { out << _aux_data.size() << " data objects held:\n"; AuxData::const_iterator ai; for (ai = _aux_data.begin(); ai != _aux_data.end(); ++ai) { diff --git a/panda/src/pgraph/camera.h b/panda/src/pgraph/camera.h index 84b33bf55b..9182f4415c 100644 --- a/panda/src/pgraph/camera.h +++ b/panda/src/pgraph/camera.h @@ -34,7 +34,7 @@ class DisplayRegion; */ class EXPCL_PANDA_PGRAPH Camera : public LensNode { PUBLISHED: - explicit Camera(const string &name, Lens *lens = new PerspectiveLens()); + explicit Camera(const std::string &name, Lens *lens = new PerspectiveLens()); Camera(const Camera ©); public: @@ -78,26 +78,26 @@ PUBLISHED: INLINE CPT(RenderState) get_initial_state() const; MAKE_PROPERTY(initial_state, get_initial_state, set_initial_state); - INLINE void set_tag_state_key(const string &tag_state_key); - INLINE const string &get_tag_state_key() const; + INLINE void set_tag_state_key(const std::string &tag_state_key); + INLINE const std::string &get_tag_state_key() const; MAKE_PROPERTY(tag_state_key, get_tag_state_key, set_tag_state_key); INLINE void set_lod_scale(PN_stdfloat value); INLINE PN_stdfloat get_lod_scale() const; MAKE_PROPERTY(lod_scale, get_lod_scale, set_lod_scale); - void set_tag_state(const string &tag_state, const RenderState *state); - void clear_tag_state(const string &tag_state); + void set_tag_state(const std::string &tag_state, const RenderState *state); + void clear_tag_state(const std::string &tag_state); void clear_tag_states(); - bool has_tag_state(const string &tag_state) const; - CPT(RenderState) get_tag_state(const string &tag_state) const; + bool has_tag_state(const std::string &tag_state) const; + CPT(RenderState) get_tag_state(const std::string &tag_state) const; MAKE_MAP_PROPERTY(tag_states, has_tag_state, get_tag_state, set_tag_state, clear_tag_state); void set_aux_scene_data(const NodePath &node_path, AuxSceneData *data); bool clear_aux_scene_data(const NodePath &node_path); AuxSceneData *get_aux_scene_data(const NodePath &node_path) const; - void list_aux_scene_data(ostream &out) const; + void list_aux_scene_data(std::ostream &out) const; int cleanup_aux_scene_data(Thread *current_thread = Thread::get_current_thread()); MAKE_MAP_PROPERTY(aux_scene_data, get_aux_scene_data, get_aux_scene_data, set_aux_scene_data, clear_aux_scene_data); @@ -119,9 +119,9 @@ private: DisplayRegions _display_regions; CPT(RenderState) _initial_state; - string _tag_state_key; + std::string _tag_state_key; - typedef pmap TagStates; + typedef pmap TagStates; TagStates _tag_states; typedef pmap AuxData; diff --git a/panda/src/pgraph/clipPlaneAttrib.cxx b/panda/src/pgraph/clipPlaneAttrib.cxx index 726b5472b7..de3f1183c9 100644 --- a/panda/src/pgraph/clipPlaneAttrib.cxx +++ b/panda/src/pgraph/clipPlaneAttrib.cxx @@ -35,7 +35,7 @@ public: nassertr(!a.is_empty() && !b.is_empty(), a < b); PlaneNode *pa = DCAST(PlaneNode, a.node()); PlaneNode *pb = DCAST(PlaneNode, b.node()); - nassertr(pa != (PlaneNode *)NULL && pb != (PlaneNode *)NULL, a < b); + nassertr(pa != nullptr && pb != nullptr, a < b); return pa->get_priority() > pb->get_priority(); } @@ -340,7 +340,7 @@ CPT(RenderAttrib) ClipPlaneAttrib:: make() { // We make it a special case and store a pointer to the empty attrib forever // once we find it the first time, as an optimization. - if (_empty_attrib == (RenderAttrib *)NULL) { + if (_empty_attrib == nullptr) { _empty_attrib = return_new(new ClipPlaneAttrib); } @@ -355,7 +355,7 @@ CPT(RenderAttrib) ClipPlaneAttrib:: make_all_off() { // We make it a special case and store a pointer to the off attrib forever // once we find it the first time, as an optimization. - if (_all_off_attrib == (RenderAttrib *)NULL) { + if (_all_off_attrib == nullptr) { ClipPlaneAttrib *attrib = new ClipPlaneAttrib; attrib->_off_all_planes = true; _all_off_attrib = return_new(attrib); @@ -375,7 +375,7 @@ add_on_plane(const NodePath &plane) const { attrib->_on_planes.insert(plane); attrib->_off_planes.erase(plane); - pair insert_result = + std::pair insert_result = attrib->_on_planes.insert(Planes::value_type(plane)); if (insert_result.second) { // Also ensure it is removed from the off_planes list. @@ -487,7 +487,7 @@ filter_to_max(int max_clip_planes) const { CPT(RenderAttrib) ClipPlaneAttrib:: compose_off(const RenderAttrib *other) const { const ClipPlaneAttrib *ta; - DCAST_INTO_R(ta, other, NULL); + DCAST_INTO_R(ta, other, nullptr); if (_off_all_planes || (!ta->_off_all_planes && ta->_off_planes.empty())) { // If we turn off all planes, or the other turns none off, the result is @@ -505,8 +505,8 @@ compose_off(const RenderAttrib *other) const { // Create a new ClipPlaneAttrib that will hold the result. ClipPlaneAttrib *new_attrib = new ClipPlaneAttrib; - back_insert_iterator result = - back_inserter(new_attrib->_on_planes); + std::back_insert_iterator result = + std::back_inserter(new_attrib->_on_planes); while (ai != _off_planes.end() && bi != ta->_off_planes.end()) { @@ -552,7 +552,7 @@ compose_off(const RenderAttrib *other) const { * */ void ClipPlaneAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; if (_off_planes.empty()) { if (_on_planes.empty()) { @@ -701,7 +701,7 @@ get_hash_impl() const { CPT(RenderAttrib) ClipPlaneAttrib:: compose_impl(const RenderAttrib *other) const { const ClipPlaneAttrib *ta; - DCAST_INTO_R(ta, other, NULL); + DCAST_INTO_R(ta, other, nullptr); if (ta->_off_all_planes) { // If the other type turns off all planes, it doesn't matter what we are. @@ -717,8 +717,8 @@ compose_impl(const RenderAttrib *other) const { // Create a new ClipPlaneAttrib that will hold the result. ClipPlaneAttrib *new_attrib = new ClipPlaneAttrib; - back_insert_iterator result = - back_inserter(new_attrib->_on_planes); + std::back_insert_iterator result = + std::back_inserter(new_attrib->_on_planes); while (ai != _on_planes.end() && bi != ta->_on_planes.end() && @@ -912,7 +912,7 @@ complete_pointers(TypedWritable **p_list, BamReader *manager) { } else { BamAuxData *aux = (BamAuxData *)manager->get_aux_data(this, "planes"); - nassertr(aux != NULL, pi); + nassertr(aux != nullptr, pi); int i; aux->_off_list.reserve(aux->_num_off_planes); @@ -964,7 +964,7 @@ finalize(BamReader *manager) { } else { // Now it's safe to convert our saved PandaNodes into NodePaths. BamAuxData *aux = (BamAuxData *)manager->get_aux_data(this, "planes"); - nassertv(aux != NULL); + nassertv(aux != nullptr); nassertv(aux->_num_off_planes == (int)aux->_off_list.size()); nassertv(aux->_num_on_planes == (int)aux->_on_list.size()); diff --git a/panda/src/pgraph/clipPlaneAttrib.h b/panda/src/pgraph/clipPlaneAttrib.h index b59bb34f9b..511ea34b01 100644 --- a/panda/src/pgraph/clipPlaneAttrib.h +++ b/panda/src/pgraph/clipPlaneAttrib.h @@ -91,7 +91,7 @@ PUBLISHED: public: CPT(RenderAttrib) compose_off(const RenderAttrib *other) const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/colorAttrib.cxx b/panda/src/pgraph/colorAttrib.cxx index 42e7c5578d..7bfbecee79 100644 --- a/panda/src/pgraph/colorAttrib.cxx +++ b/panda/src/pgraph/colorAttrib.cxx @@ -30,7 +30,7 @@ CPT(RenderAttrib) ColorAttrib::_vertex; */ CPT(RenderAttrib) ColorAttrib:: make_vertex() { - if (_vertex != 0) { + if (_vertex != nullptr) { return _vertex; } ColorAttrib *attrib = new ColorAttrib(T_vertex, LColor::zero()); @@ -54,7 +54,7 @@ make_flat(const LColor &color) { */ CPT(RenderAttrib) ColorAttrib:: make_off() { - if (_off != 0) { + if (_off != nullptr) { return _off; } ColorAttrib *attrib = new ColorAttrib(T_off, LColor(1.0f, 1.0f, 1.0f, 1.0f)); @@ -75,7 +75,7 @@ make_default() { * */ void ColorAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; switch (get_color_type()) { case T_vertex: diff --git a/panda/src/pgraph/colorAttrib.h b/panda/src/pgraph/colorAttrib.h index df8c1b84ce..a92543c855 100644 --- a/panda/src/pgraph/colorAttrib.h +++ b/panda/src/pgraph/colorAttrib.h @@ -47,7 +47,7 @@ PUBLISHED: MAKE_PROPERTY(color, get_color); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/colorBlendAttrib.cxx b/panda/src/pgraph/colorBlendAttrib.cxx index 9341f2d808..f9a24d96bf 100644 --- a/panda/src/pgraph/colorBlendAttrib.cxx +++ b/panda/src/pgraph/colorBlendAttrib.cxx @@ -19,6 +19,8 @@ #include "datagram.h" #include "datagramIterator.h" +using std::ostream; + TypeHandle ColorBlendAttrib::_type_handle; int ColorBlendAttrib::_attrib_slot; diff --git a/panda/src/pgraph/colorBlendAttrib.h b/panda/src/pgraph/colorBlendAttrib.h index 641633561c..87b680425f 100644 --- a/panda/src/pgraph/colorBlendAttrib.h +++ b/panda/src/pgraph/colorBlendAttrib.h @@ -116,7 +116,7 @@ PUBLISHED: MAKE_PROPERTY(color, get_color); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; @@ -168,8 +168,8 @@ private: static int _attrib_slot; }; -EXPCL_PANDA_PGRAPH ostream &operator << (ostream &out, ColorBlendAttrib::Mode mode); -EXPCL_PANDA_PGRAPH ostream &operator << (ostream &out, ColorBlendAttrib::Operand operand); +EXPCL_PANDA_PGRAPH std::ostream &operator << (std::ostream &out, ColorBlendAttrib::Mode mode); +EXPCL_PANDA_PGRAPH std::ostream &operator << (std::ostream &out, ColorBlendAttrib::Operand operand); #include "colorBlendAttrib.I" diff --git a/panda/src/pgraph/colorScaleAttrib.cxx b/panda/src/pgraph/colorScaleAttrib.cxx index 79394a51f1..088c3142ef 100644 --- a/panda/src/pgraph/colorScaleAttrib.cxx +++ b/panda/src/pgraph/colorScaleAttrib.cxx @@ -45,7 +45,7 @@ CPT(RenderAttrib) ColorScaleAttrib:: make_identity() { // We make identity a special case and store a pointer forever once we find // it the first time. - if (_identity_attrib == (ColorScaleAttrib *)NULL) { + if (_identity_attrib == nullptr) { ColorScaleAttrib *attrib = new ColorScaleAttrib(false, LVecBase4(1.0f, 1.0f, 1.0f, 1.0f));; _identity_attrib = return_new(attrib); } @@ -129,7 +129,7 @@ lower_attrib_can_override() const { * */ void ColorScaleAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; if (is_off()) { out << "off"; diff --git a/panda/src/pgraph/colorScaleAttrib.h b/panda/src/pgraph/colorScaleAttrib.h index e8dded108b..918bbe9874 100644 --- a/panda/src/pgraph/colorScaleAttrib.h +++ b/panda/src/pgraph/colorScaleAttrib.h @@ -48,7 +48,7 @@ PUBLISHED: public: virtual bool lower_attrib_can_override() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/colorWriteAttrib.cxx b/panda/src/pgraph/colorWriteAttrib.cxx index 98c889a0de..671fa82629 100644 --- a/panda/src/pgraph/colorWriteAttrib.cxx +++ b/panda/src/pgraph/colorWriteAttrib.cxx @@ -44,7 +44,7 @@ make_default() { * */ void ColorWriteAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; if (_channels == 0) { out << "off"; diff --git a/panda/src/pgraph/colorWriteAttrib.h b/panda/src/pgraph/colorWriteAttrib.h index a426a01659..02d4fd2ca9 100644 --- a/panda/src/pgraph/colorWriteAttrib.h +++ b/panda/src/pgraph/colorWriteAttrib.h @@ -52,7 +52,7 @@ PUBLISHED: MAKE_PROPERTY(channels, get_channels); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/compassEffect.cxx b/panda/src/pgraph/compassEffect.cxx index d972e7f45a..41bd9af880 100644 --- a/panda/src/pgraph/compassEffect.cxx +++ b/panda/src/pgraph/compassEffect.cxx @@ -50,7 +50,7 @@ safe_to_transform() const { * */ void CompassEffect:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; if (_properties == 0) { out << " none"; diff --git a/panda/src/pgraph/compassEffect.h b/panda/src/pgraph/compassEffect.h index 6600820bb1..adba81f9e6 100644 --- a/panda/src/pgraph/compassEffect.h +++ b/panda/src/pgraph/compassEffect.h @@ -68,7 +68,7 @@ PUBLISHED: public: virtual bool safe_to_transform() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; virtual bool has_cull_callback() const; virtual void cull_callback(CullTraverser *trav, CullTraverserData &data, diff --git a/panda/src/pgraph/cullBin.I b/panda/src/pgraph/cullBin.I index 12f18c6e37..28f7b6542e 100644 --- a/panda/src/pgraph/cullBin.I +++ b/panda/src/pgraph/cullBin.I @@ -28,7 +28,7 @@ CullBin(const CullBin ©) : * */ INLINE CullBin:: -CullBin(const string &name, CullBin::BinType bin_type, +CullBin(const std::string &name, CullBin::BinType bin_type, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector) : _name(name), @@ -42,7 +42,7 @@ CullBin(const string &name, CullBin::BinType bin_type, /** * */ -INLINE const string &CullBin:: +INLINE const std::string &CullBin:: get_name() const { return _name; } diff --git a/panda/src/pgraph/cullBin.cxx b/panda/src/pgraph/cullBin.cxx index 4d5cea887a..1c73c952b6 100644 --- a/panda/src/pgraph/cullBin.cxx +++ b/panda/src/pgraph/cullBin.cxx @@ -41,7 +41,7 @@ CullBin:: */ PT(CullBin) CullBin:: make_next() const { - return (CullBin *)NULL; + return nullptr; } /** diff --git a/panda/src/pgraph/cullBin.h b/panda/src/pgraph/cullBin.h index 3f9615cccb..05e0fbb19e 100644 --- a/panda/src/pgraph/cullBin.h +++ b/panda/src/pgraph/cullBin.h @@ -20,6 +20,7 @@ #include "pStatCollector.h" #include "pointerTo.h" #include "luse.h" +#include "geomNode.h" class CullableObject; class GraphicsStateGuardianBase; @@ -27,7 +28,6 @@ class SceneSetup; class TransformState; class RenderState; class PandaNode; -class GeomNode; /** * A collection of Geoms and their associated state, for a particular scene. @@ -41,12 +41,12 @@ class EXPCL_PANDA_PGRAPH CullBin : public TypedReferenceCount, public CullBinEnu protected: INLINE CullBin(const CullBin ©); public: - INLINE CullBin(const string &name, BinType bin_type, + INLINE CullBin(const std::string &name, BinType bin_type, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector); virtual ~CullBin(); - INLINE const string &get_name() const; + INLINE const std::string &get_name() const; INLINE BinType get_bin_type() const; virtual PT(CullBin) make_next() const; @@ -69,12 +69,12 @@ private: void check_flash_color(); protected: - string _name; + std::string _name; BinType _bin_type; GraphicsStateGuardianBase *_gsg; // Used in make_result_graph() and fill_result_graph(). - class ResultGraphBuilder { + class EXPCL_PANDA_PGRAPH ResultGraphBuilder { public: ResultGraphBuilder(PandaNode *root_node); void add_object(CullableObject *object); diff --git a/panda/src/pgraph/cullBinAttrib.I b/panda/src/pgraph/cullBinAttrib.I index 945d3244ca..5c5a3714cd 100644 --- a/panda/src/pgraph/cullBinAttrib.I +++ b/panda/src/pgraph/cullBinAttrib.I @@ -23,7 +23,7 @@ CullBinAttrib() { * Returns the name of the bin this attribute specifies. If this is the empty * string, it refers to the default bin. */ -INLINE const string &CullBinAttrib:: +INLINE const std::string &CullBinAttrib:: get_bin_name() const { return _bin_name; } diff --git a/panda/src/pgraph/cullBinAttrib.cxx b/panda/src/pgraph/cullBinAttrib.cxx index f8eb40626d..27238c9c31 100644 --- a/panda/src/pgraph/cullBinAttrib.cxx +++ b/panda/src/pgraph/cullBinAttrib.cxx @@ -28,7 +28,7 @@ int CullBinAttrib::_attrib_slot; * only to certain kinds of bins (in particular CullBinFixed type bins). */ CPT(RenderAttrib) CullBinAttrib:: -make(const string &bin_name, int draw_order) { +make(const std::string &bin_name, int draw_order) { CullBinAttrib *attrib = new CullBinAttrib; attrib->_bin_name = bin_name; attrib->_draw_order = draw_order; @@ -48,7 +48,7 @@ make_default() { * */ void CullBinAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; if (_bin_name.empty()) { out << "(default)"; diff --git a/panda/src/pgraph/cullBinAttrib.h b/panda/src/pgraph/cullBinAttrib.h index b3590ac1c5..1104f21af7 100644 --- a/panda/src/pgraph/cullBinAttrib.h +++ b/panda/src/pgraph/cullBinAttrib.h @@ -29,10 +29,10 @@ private: INLINE CullBinAttrib(); PUBLISHED: - static CPT(RenderAttrib) make(const string &bin_name, int draw_order); + static CPT(RenderAttrib) make(const std::string &bin_name, int draw_order); static CPT(RenderAttrib) make_default(); - INLINE const string &get_bin_name() const; + INLINE const std::string &get_bin_name() const; INLINE int get_draw_order() const; PUBLISHED: @@ -40,14 +40,14 @@ PUBLISHED: MAKE_PROPERTY(draw_order, get_draw_order); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; virtual size_t get_hash_impl() const; private: - string _bin_name; + std::string _bin_name; int _draw_order; PUBLISHED: diff --git a/panda/src/pgraph/cullBinManager.I b/panda/src/pgraph/cullBinManager.I index 7bafdea5d6..cea6cc12b1 100644 --- a/panda/src/pgraph/cullBinManager.I +++ b/panda/src/pgraph/cullBinManager.I @@ -63,10 +63,10 @@ get_bin(int n) const { * was retrieved by get_bin() or find_bin()). The bin's name may not be * changed during the life of the bin. */ -INLINE string CullBinManager:: +INLINE std::string CullBinManager:: get_bin_name(int bin_index) const { - nassertr(bin_index >= 0 && bin_index < (int)_bin_definitions.size(), string()); - nassertr(_bin_definitions[bin_index]._in_use, string()); + nassertr(bin_index >= 0 && bin_index < (int)_bin_definitions.size(), std::string()); + nassertr(_bin_definitions[bin_index]._in_use, std::string()); return _bin_definitions[bin_index]._name; } @@ -85,7 +85,7 @@ get_bin_type(int bin_index) const { * Returns the type of the bin with the indicated name. */ INLINE CullBinManager::BinType CullBinManager:: -get_bin_type(const string &name) const { +get_bin_type(const std::string &name) const { int bin_index = find_bin(name); nassertr(bin_index != -1, BT_invalid); return get_bin_type(bin_index); @@ -112,7 +112,7 @@ set_bin_type(int bin_index, CullBinManager::BinType type) { * frame, depending on the bin type. */ INLINE void CullBinManager:: -set_bin_type(const string &name, CullBinManager::BinType type) { +set_bin_type(const std::string &name, CullBinManager::BinType type) { int bin_index = find_bin(name); nassertv(bin_index != -1); set_bin_type(bin_index, type); @@ -139,7 +139,7 @@ get_bin_sort(int bin_index) const { * may be changed from time to time to reorder the bins. */ INLINE int CullBinManager:: -get_bin_sort(const string &name) const { +get_bin_sort(const std::string &name) const { int bin_index = find_bin(name); nassertr(bin_index != -1, 0); return get_bin_sort(bin_index); @@ -167,7 +167,7 @@ set_bin_sort(int bin_index, int sort) { * may be changed from time to time to reorder the bins. */ INLINE void CullBinManager:: -set_bin_sort(const string &name, int sort) { +set_bin_sort(const std::string &name, int sort) { int bin_index = find_bin(name); nassertv(bin_index != -1); set_bin_sort(bin_index, sort); @@ -192,7 +192,7 @@ get_bin_active(int bin_index) const { * When a bin is marked inactive, all geometry assigned to it is not rendered. */ INLINE bool CullBinManager:: -get_bin_active(const string &name) const { +get_bin_active(const std::string &name) const { int bin_index = find_bin(name); nassertr(bin_index != -1, false); return get_bin_active(bin_index); @@ -217,7 +217,7 @@ set_bin_active(int bin_index, bool active) { * When a bin is marked inactive, all geometry assigned to it is not rendered. */ INLINE void CullBinManager:: -set_bin_active(const string &name, bool active) { +set_bin_active(const std::string &name, bool active) { int bin_index = find_bin(name); nassertv(bin_index != -1); set_bin_active(bin_index, active); @@ -279,7 +279,7 @@ set_bin_flash_color(int bin_index, const LColor &color) { */ INLINE CullBinManager *CullBinManager:: get_global_ptr() { - if (_global_ptr == (CullBinManager *)NULL) { + if (_global_ptr == nullptr) { _global_ptr = new CullBinManager; } return _global_ptr; diff --git a/panda/src/pgraph/cullBinManager.cxx b/panda/src/pgraph/cullBinManager.cxx index 0d979cf7e7..5826905c89 100644 --- a/panda/src/pgraph/cullBinManager.cxx +++ b/panda/src/pgraph/cullBinManager.cxx @@ -18,7 +18,9 @@ #include "string_utils.h" #include "configVariableColor.h" -CullBinManager *CullBinManager::_global_ptr = (CullBinManager *)NULL; +using std::string; + +CullBinManager *CullBinManager::_global_ptr = nullptr; /** * The constructor is not intended to be called directly; there is only one @@ -165,7 +167,7 @@ find_bin(const string &name) const { * */ void CullBinManager:: -write(ostream &out) const { +write(std::ostream &out) const { if (!_bins_are_sorted) { ((CullBinManager *)this)->do_sort_bins(); } @@ -185,8 +187,8 @@ write(ostream &out) const { PT(CullBin) CullBinManager:: make_new_bin(int bin_index, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector) { - nassertr(bin_index >= 0 && bin_index < (int)_bin_definitions.size(), NULL); - nassertr(_bin_definitions[bin_index]._in_use, NULL); + nassertr(bin_index >= 0 && bin_index < (int)_bin_definitions.size(), nullptr); + nassertr(_bin_definitions[bin_index]._in_use, nullptr); string name = get_bin_name(bin_index); BinType type = _bin_definitions[bin_index]._type; @@ -197,8 +199,8 @@ make_new_bin(int bin_index, GraphicsStateGuardianBase *gsg, } // Hmm, unknown (or unregistered) bin type. - nassertr(false, NULL); - return NULL; + nassertr(false, nullptr); + return nullptr; } /** @@ -316,8 +318,8 @@ parse_bin_type(const string &bin_type) { /** * */ -ostream & -operator << (ostream &out, CullBinManager::BinType bin_type) { +std::ostream & +operator << (std::ostream &out, CullBinManager::BinType bin_type) { switch (bin_type) { case CullBinManager::BT_invalid: return out << "invalid"; diff --git a/panda/src/pgraph/cullBinManager.h b/panda/src/pgraph/cullBinManager.h index 79ac5d9749..1bc203ab84 100644 --- a/panda/src/pgraph/cullBinManager.h +++ b/panda/src/pgraph/cullBinManager.h @@ -39,30 +39,30 @@ protected: PUBLISHED: typedef CullBin::BinType BinType; - int add_bin(const string &name, BinType type, int sort); + int add_bin(const std::string &name, BinType type, int sort); void remove_bin(int bin_index); INLINE int get_num_bins() const; INLINE int get_bin(int n) const; MAKE_SEQ(get_bins, get_num_bins, get_bin); - int find_bin(const string &name) const; + int find_bin(const std::string &name) const; - INLINE string get_bin_name(int bin_index) const; + INLINE std::string get_bin_name(int bin_index) const; INLINE BinType get_bin_type(int bin_index) const; - INLINE BinType get_bin_type(const string &name) const; + INLINE BinType get_bin_type(const std::string &name) const; INLINE void set_bin_type(int bin_index, BinType type); - INLINE void set_bin_type(const string &name, BinType type); + INLINE void set_bin_type(const std::string &name, BinType type); INLINE int get_bin_sort(int bin_index) const; - INLINE int get_bin_sort(const string &name) const; + INLINE int get_bin_sort(const std::string &name) const; INLINE void set_bin_sort(int bin_index, int sort); - INLINE void set_bin_sort(const string &name, int sort); + INLINE void set_bin_sort(const std::string &name, int sort); INLINE bool get_bin_active(int bin_index) const; - INLINE bool get_bin_active(const string &name) const; + INLINE bool get_bin_active(const std::string &name) const; INLINE void set_bin_active(int bin_index, bool active); - INLINE void set_bin_active(const string &name, bool active); + INLINE void set_bin_active(const std::string &name, bool active); #ifndef NDEBUG INLINE bool get_bin_flash_active(int bin_index) const; @@ -71,7 +71,7 @@ PUBLISHED: INLINE void set_bin_flash_color(int bin_index, const LColor &color); #endif - void write(ostream &out) const; + void write(std::ostream &out) const; INLINE static CullBinManager *get_global_ptr(); @@ -83,7 +83,7 @@ public: // This defines the factory interface for defining constructors to bin types // (the implementations are in the cull directory, not here in pgraph, so we // can't call the constructors directly). - typedef CullBin *BinConstructor(const string &name, + typedef CullBin *BinConstructor(const std::string &name, GraphicsStateGuardianBase *gsg, const PStatCollector &draw_region_pcollector); @@ -92,7 +92,7 @@ public: private: void do_sort_bins(); void setup_initial_bins(); - static BinType parse_bin_type(const string &bin_type); + static BinType parse_bin_type(const std::string &bin_type); class EXPCL_PANDA_PGRAPH BinDefinition { public: @@ -101,7 +101,7 @@ private: bool _flash_active; #endif bool _in_use; - string _name; + std::string _name; BinType _type; int _sort; bool _active; @@ -116,7 +116,7 @@ private: CullBinManager *_manager; }; - typedef pmap BinsByName; + typedef pmap BinsByName; BinsByName _bins_by_name; typedef vector_int SortedBins; @@ -131,8 +131,8 @@ private: friend class SortBins; }; -EXPCL_PANDA_PGRAPH ostream & -operator << (ostream &out, CullBinManager::BinType bin_type); +EXPCL_PANDA_PGRAPH std::ostream & +operator << (std::ostream &out, CullBinManager::BinType bin_type); #include "cullBinManager.I" diff --git a/panda/src/pgraph/cullFaceAttrib.cxx b/panda/src/pgraph/cullFaceAttrib.cxx index db3527a653..054d8061b3 100644 --- a/panda/src/pgraph/cullFaceAttrib.cxx +++ b/panda/src/pgraph/cullFaceAttrib.cxx @@ -99,7 +99,7 @@ get_effective_mode() const { * */ void CullFaceAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; switch (get_actual_mode()) { case M_cull_none: diff --git a/panda/src/pgraph/cullFaceAttrib.h b/panda/src/pgraph/cullFaceAttrib.h index 1ed0450db2..def2216976 100644 --- a/panda/src/pgraph/cullFaceAttrib.h +++ b/panda/src/pgraph/cullFaceAttrib.h @@ -50,7 +50,7 @@ PUBLISHED: MAKE_PROPERTY(effective_mode, get_effective_mode); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/cullPlanes.cxx b/panda/src/pgraph/cullPlanes.cxx index 43a249403b..fafbae6cfa 100644 --- a/panda/src/pgraph/cullPlanes.cxx +++ b/panda/src/pgraph/cullPlanes.cxx @@ -18,13 +18,16 @@ #include "occluderEffect.h" #include "boundingBox.h" +using std::max; +using std::min; + /** * Returns a pointer to an empty CullPlanes object. */ CPT(CullPlanes) CullPlanes:: make_empty() { static CPT(CullPlanes) empty; - if (empty == NULL) { + if (empty == nullptr) { empty = new CullPlanes; // Artificially tick the reference count, just to ensure we won't // accidentally modify this object in any of the copy-on-write operations @@ -81,7 +84,7 @@ apply_state(const CullTraverser *trav, const CullTraverserData *data, const ClipPlaneAttrib *net_attrib, const ClipPlaneAttrib *off_attrib, const OccluderEffect *node_effect) const { - if (net_attrib == (ClipPlaneAttrib *)NULL && node_effect == (OccluderEffect *)NULL) { + if (net_attrib == nullptr && node_effect == nullptr) { return this; } @@ -92,9 +95,9 @@ apply_state(const CullTraverser *trav, const CullTraverserData *data, new_planes = new CullPlanes(*this); } - CPT(TransformState) net_transform = NULL; + CPT(TransformState) net_transform = nullptr; - if (net_attrib != (ClipPlaneAttrib *)NULL) { + if (net_attrib != nullptr) { int num_on_planes = net_attrib->get_num_on_planes(); for (int i = 0; i < num_on_planes; ++i) { NodePath clip_plane = net_attrib->get_on_plane(i); @@ -103,7 +106,7 @@ apply_state(const CullTraverser *trav, const CullTraverserData *data, if (!off_attrib->has_off_plane(clip_plane)) { // Here's a new clip plane; add it to the list. For this we need // the net transform to this node. - if (net_transform == (TransformState *)NULL) { + if (net_transform == nullptr) { net_transform = data->get_net_transform(trav); } @@ -118,8 +121,8 @@ apply_state(const CullTraverser *trav, const CullTraverserData *data, } } - if (node_effect != (OccluderEffect *)NULL) { - CPT(TransformState) center_transform = NULL; + if (node_effect != nullptr) { + CPT(TransformState) center_transform = nullptr; // We'll need to know the occluder's frustum in cull-center space. SceneSetup *scene = trav->get_scene(); const Lens *lens = scene->get_lens(); @@ -137,8 +140,8 @@ apply_state(const CullTraverser *trav, const CullTraverserData *data, // And the transform from cull-center space into the current node's // coordinate space. - if (center_transform == (TransformState *)NULL) { - if (net_transform == (TransformState *)NULL) { + if (center_transform == nullptr) { + if (net_transform == nullptr) { net_transform = data->get_net_transform(trav); } @@ -177,7 +180,7 @@ apply_state(const CullTraverser *trav, const CullTraverserData *data, occluder_gbv = new BoundingBox(ccp_min, ccp_max); - if (data->_view_frustum != (GeometricBoundingVolume *)NULL) { + if (data->_view_frustum != nullptr) { int occluder_result = data->_view_frustum->contains(occluder_gbv); if (occluder_result == BoundingVolume::IF_no_intersection) { // This occluder is outside the view frustum; ignore it. @@ -200,8 +203,8 @@ apply_state(const CullTraverser *trav, const CullTraverserData *data, if (plane.get_normal().dot(LVector3::forward()) >= 0.0) { if (occluder_node->is_double_sided()) { - swap(points_near[0], points_near[3]); - swap(points_near[1], points_near[2]); + std::swap(points_near[0], points_near[3]); + std::swap(points_near[1], points_near[2]); plane = LPlane(points_near[0], points_near[1], points_near[2]); } else { // This occluder is facing the wrong direction. Ignore it. @@ -289,7 +292,7 @@ apply_state(const CullTraverser *trav, const CullTraverserData *data, if (show_occluder_volumes) { // Draw the frustum for visualization. - nassertr(net_transform != NULL, new_planes); + nassertr(net_transform != nullptr, new_planes); trav->draw_bounding_volume(frustum, data->get_internal_transform(trav)); } } @@ -429,7 +432,7 @@ remove_occluder(const NodePath &occluder) const { * */ void CullPlanes:: -write(ostream &out) const { +write(std::ostream &out) const { out << "CullPlanes (" << _planes.size() << " planes and " << _occluders.size() << " occluders):\n"; Planes::const_iterator pi; diff --git a/panda/src/pgraph/cullPlanes.h b/panda/src/pgraph/cullPlanes.h index 4b29fb7794..9480854853 100644 --- a/panda/src/pgraph/cullPlanes.h +++ b/panda/src/pgraph/cullPlanes.h @@ -64,7 +64,7 @@ public: CPT(CullPlanes) remove_plane(const NodePath &clip_plane) const; CPT(CullPlanes) remove_occluder(const NodePath &occluder) const; - void write(ostream &out) const; + void write(std::ostream &out) const; private: typedef pmap Planes; diff --git a/panda/src/pgraph/cullResult.I b/panda/src/pgraph/cullResult.I index 92b60a88b4..303a06dfd8 100644 --- a/panda/src/pgraph/cullResult.I +++ b/panda/src/pgraph/cullResult.I @@ -26,7 +26,7 @@ INLINE CullResult:: INLINE CullBin *CullResult:: get_bin(int bin_index) { if (bin_index >= 0 && bin_index < (int)_bins.size() && - _bins[bin_index] != (CullBin *)NULL) { + _bins[bin_index] != nullptr) { return _bins[bin_index]; } return make_new_bin(bin_index); diff --git a/panda/src/pgraph/cullResult.cxx b/panda/src/pgraph/cullResult.cxx index 7dbe002c9e..faee06ee53 100644 --- a/panda/src/pgraph/cullResult.cxx +++ b/panda/src/pgraph/cullResult.cxx @@ -83,9 +83,9 @@ make_next() const { for (size_t i = 0; i < _bins.size(); ++i) { CullBin *old_bin = _bins[i]; - if (old_bin == (CullBin *)NULL || + if (old_bin == nullptr || old_bin->get_bin_type() != bin_manager->get_bin_type(i)) { - new_result->_bins.push_back((CullBin *)NULL); + new_result->_bins.push_back(nullptr); } else { new_result->_bins.push_back(old_bin->make_next()); } @@ -140,7 +140,7 @@ add_object(CullableObject *object, const CullTraverser *traverser) { traverser, force)) { int wireframe_bin_index = bin_manager->find_bin("fixed"); CullBin *bin = get_bin(wireframe_bin_index); - nassertv(bin != (CullBin *)NULL); + nassertv(bin != nullptr); check_flash_bin(wireframe_part->_state, bin_manager, wireframe_bin_index); bin->add_object(wireframe_part, current_thread); } else { @@ -211,7 +211,7 @@ add_object(CullableObject *object, const CullTraverser *traverser) { traverser, force)) { int transparent_bin_index = transparent_part->_state->get_bin_index(); CullBin *bin = get_bin(transparent_bin_index); - nassertv(bin != (CullBin *)NULL); + nassertv(bin != nullptr); check_flash_bin(transparent_part->_state, bin_manager, transparent_bin_index); bin->add_object(transparent_part, current_thread); } else { @@ -241,7 +241,7 @@ add_object(CullableObject *object, const CullTraverser *traverser) { int bin_index = object->_state->get_bin_index(); CullBin *bin = get_bin(bin_index); - nassertv(bin != (CullBin *)NULL); + nassertv(bin != nullptr); check_flash_bin(object->_state, bin_manager, bin_index); // Munge vertices as needed for the GSG's requirements, and the object's @@ -269,11 +269,11 @@ finish_cull(SceneSetup *scene_setup, Thread *current_thread) { if (!bin_manager->get_bin_active(i)) { // If the bin isn't active, don't sort it, and don't draw it. In fact, // clear it. - _bins[i] = NULL; + _bins[i] = nullptr; } else { CullBin *bin = _bins[i]; - if (bin != (CullBin *)NULL) { + if (bin != nullptr) { bin->finish_cull(scene_setup, current_thread); } } @@ -294,7 +294,7 @@ draw(Thread *current_thread) { int bin_index = bin_manager->get_bin(i); nassertv(bin_index >= 0); - if (bin_index < (int)_bins.size() && _bins[bin_index] != (CullBin *)NULL) { + if (bin_index < (int)_bins.size() && _bins[bin_index] != nullptr) { _bins[bin_index]->draw(force, current_thread); } } @@ -319,9 +319,9 @@ make_result_graph() { int num_bins = bin_manager->get_num_bins(); for (int i = 0; i < num_bins; i++) { int bin_index = bin_manager->get_bin(i); - nassertr(bin_index >= 0, NULL); + nassertr(bin_index >= 0, nullptr); - if (bin_index < (int)_bins.size() && _bins[bin_index] != (CullBin *)NULL) { + if (bin_index < (int)_bins.size() && _bins[bin_index] != nullptr) { root_node->add_child(_bins[bin_index]->make_result_graph()); } } @@ -351,15 +351,15 @@ make_new_bin(int bin_index) { _draw_region_pcollector); CullBin *bin_ptr = bin.p(); - if (bin_ptr != (CullBin *)NULL) { + if (bin_ptr != nullptr) { // Now store it in the vector. while (bin_index >= (int)_bins.size()) { - _bins.push_back((CullBin *)NULL); + _bins.push_back(nullptr); } - nassertr(bin_index >= 0 && bin_index < (int)_bins.size(), NULL); + nassertr(bin_index >= 0 && bin_index < (int)_bins.size(), nullptr); // Prevent unnecessary refunref by swapping the PointerTos. - swap(_bins[bin_index], bin); + std::swap(_bins[bin_index], bin); } return bin_ptr; @@ -384,8 +384,8 @@ get_rescale_normal_state(RescaleNormalAttrib::Mode mode) { */ const RenderState *CullResult:: get_alpha_state() { - static CPT(RenderState) state = NULL; - if (state == (const RenderState *)NULL) { + static CPT(RenderState) state = nullptr; + if (state == nullptr) { // We don't monkey with the priority, since we want to allow the user to // override this if he desires. state = RenderState::make(AlphaTestAttrib::make(AlphaTestAttrib::M_greater, 0.0f)); @@ -398,8 +398,8 @@ get_alpha_state() { */ const RenderState *CullResult:: get_binary_state() { - static CPT(RenderState) state = NULL; - if (state == (const RenderState *)NULL) { + static CPT(RenderState) state = nullptr; + if (state == nullptr) { state = RenderState::make(AlphaTestAttrib::make(AlphaTestAttrib::M_greater_equal, 0.5f), TransparencyAttrib::make(TransparencyAttrib::M_none), RenderState::get_max_priority()); @@ -431,8 +431,8 @@ apply_flash_color(CPT(RenderState) &state, const LColor &flash_color) { */ const RenderState *CullResult:: get_dual_transparent_state() { - static CPT(RenderState) state = NULL; - if (state == (const RenderState *)NULL) { + static CPT(RenderState) state = nullptr; + if (state == nullptr) { // The alpha test for > 0 prevents us from drawing empty pixels, and hence // filling up the depth buffer with large empty spaces that may obscure // other things. However, this does mean we draw pixels twice where the @@ -448,8 +448,8 @@ get_dual_transparent_state() { if (m_dual_flash) { int cycle = (int)(ClockObject::get_global_clock()->get_frame_time() * bin_color_flash_rate); if ((cycle & 1) == 0) { - static CPT(RenderState) flash_state = NULL; - if (flash_state == (const RenderState *)NULL) { + static CPT(RenderState) flash_state = nullptr; + if (flash_state == nullptr) { flash_state = state->add_attrib(ColorAttrib::make_flat(LColor(0.8f, 0.2, 0.2, 1.0f)), RenderState::get_max_priority()); @@ -473,8 +473,8 @@ get_dual_transparent_state() { */ const RenderState *CullResult:: get_dual_opaque_state() { - static CPT(RenderState) state = NULL; - if (state == (const RenderState *)NULL) { + static CPT(RenderState) state = nullptr; + if (state == nullptr) { state = RenderState::make(AlphaTestAttrib::make(AlphaTestAttrib::M_greater_equal, dual_opaque_level), TransparencyAttrib::make(TransparencyAttrib::M_none), RenderState::get_max_priority()); @@ -484,8 +484,8 @@ get_dual_opaque_state() { if (m_dual_flash) { int cycle = (int)(ClockObject::get_global_clock()->get_frame_time() * bin_color_flash_rate); if ((cycle & 1) == 0) { - static CPT(RenderState) flash_state = NULL; - if (flash_state == (const RenderState *)NULL) { + static CPT(RenderState) flash_state = nullptr; + if (flash_state == nullptr) { flash_state = state->add_attrib(ColorAttrib::make_flat(LColor(0.2, 0.2, 0.8f, 1.0f)), RenderState::get_max_priority()); flash_state = flash_state->add_attrib(ColorScaleAttrib::make(LVecBase4(1.0f, 1.0f, 1.0f, 1.0f)), diff --git a/panda/src/pgraph/cullTraverser.I b/panda/src/pgraph/cullTraverser.I index 5da999d673..bb7bb35e36 100644 --- a/panda/src/pgraph/cullTraverser.I +++ b/panda/src/pgraph/cullTraverser.I @@ -49,7 +49,7 @@ has_tag_state_key() const { * Returns the tag state key that has been specified for the scene's camera, * if any. */ -INLINE const string &CullTraverser:: +INLINE const std::string &CullTraverser:: get_tag_state_key() const { return _tag_state_key; } @@ -224,7 +224,7 @@ do_traverse(CullTraverserData &data) { const FogAttrib *fog = (const FogAttrib *) node_reader->get_state()->get_attrib(FogAttrib::get_class_slot()); - if (fog != (const FogAttrib *)NULL && fog->get_fog() != (Fog *)NULL) { + if (fog != nullptr && fog->get_fog() != nullptr) { // If we just introduced a FogAttrib here, call adjust_to_camera() // now. This maybe isn't the perfect time to call it, but it's good // enough; and at this time we have all the information we need for diff --git a/panda/src/pgraph/cullTraverser.cxx b/panda/src/pgraph/cullTraverser.cxx index 7ed990637b..0ecf27666a 100644 --- a/panda/src/pgraph/cullTraverser.cxx +++ b/panda/src/pgraph/cullTraverser.cxx @@ -47,14 +47,14 @@ TypeHandle CullTraverser::_type_handle; */ CullTraverser:: CullTraverser() : - _gsg(NULL), + _gsg(nullptr), _current_thread(Thread::get_current_thread()) { _camera_mask = DrawMask::all_on(); _has_tag_state_key = false; _initial_state = RenderState::make_empty(); - _cull_handler = (CullHandler *)NULL; - _portal_clipper = (PortalClipper *)NULL; + _cull_handler = nullptr; + _portal_clipper = nullptr; _effective_incomplete_render = true; } @@ -104,14 +104,14 @@ set_scene(SceneSetup *scene_setup, GraphicsStateGuardianBase *gsg, */ void CullTraverser:: traverse(const NodePath &root) { - nassertv(_cull_handler != (CullHandler *)NULL); - nassertv(_scene_setup != (SceneSetup *)NULL); + nassertv(_cull_handler != nullptr); + nassertv(_scene_setup != nullptr); if (allow_portal_cull) { // This _view_frustum is in cull_center space Erik: obsolete? // PT(GeometricBoundingVolume) vf = _view_frustum; - GeometricBoundingVolume *local_frustum = NULL; + GeometricBoundingVolume *local_frustum = nullptr; PT(BoundingVolume) bv = _scene_setup->get_lens()->make_bounds(); if (bv != nullptr) { local_frustum = bv->as_geometric_bounding_volume(); @@ -229,7 +229,7 @@ draw_bounding_volume(const BoundingVolume *vol, const TransformState *internal_transform) const { PT(Geom) bounds_viz = make_bounds_viz(vol); - if (bounds_viz != (Geom *)NULL) { + if (bounds_viz != nullptr) { _geoms_pcollector.add_level(2); CullableObject *outer_viz = new CullableObject(bounds_viz, get_bounds_outer_viz_state(), @@ -237,7 +237,7 @@ draw_bounding_volume(const BoundingVolume *vol, _cull_handler->record_object(outer_viz, this); CullableObject *inner_viz = - new CullableObject(move(bounds_viz), get_bounds_inner_viz_state(), + new CullableObject(std::move(bounds_viz), get_bounds_inner_viz_state(), internal_transform); _cull_handler->record_object(inner_viz, this); } @@ -264,10 +264,10 @@ show_bounds(CullTraverserData &data, bool tight) { if (tight) { PT(Geom) bounds_viz = make_tight_bounds_viz(node); - if (bounds_viz != (Geom *)NULL) { + if (bounds_viz != nullptr) { _geoms_pcollector.add_level(1); CullableObject *outer_viz = - new CullableObject(move(bounds_viz), get_bounds_outer_viz_state(), + new CullableObject(std::move(bounds_viz), get_bounds_outer_viz_state(), internal_transform); _cull_handler->record_object(outer_viz, this); } @@ -489,8 +489,8 @@ CPT(RenderState) CullTraverser:: get_bounds_outer_viz_state() { // Once someone asks for this pointer, we hold its reference count and never // free it. - static CPT(RenderState) state = (const RenderState *)NULL; - if (state == (const RenderState *)NULL) { + static CPT(RenderState) state = nullptr; + if (state == nullptr) { state = RenderState::make (ColorAttrib::make_flat(LColor(0.3, 1.0f, 0.5f, 1.0f)), RenderModeAttrib::make(RenderModeAttrib::M_wireframe), @@ -507,8 +507,8 @@ CPT(RenderState) CullTraverser:: get_bounds_inner_viz_state() { // Once someone asks for this pointer, we hold its reference count and never // free it. - static CPT(RenderState) state = (const RenderState *)NULL; - if (state == (const RenderState *)NULL) { + static CPT(RenderState) state = nullptr; + if (state == nullptr) { state = RenderState::make (ColorAttrib::make_flat(LColor(0.15f, 0.5f, 0.25f, 1.0f)), RenderModeAttrib::make(RenderModeAttrib::M_wireframe), @@ -524,8 +524,8 @@ CPT(RenderState) CullTraverser:: get_depth_offset_state() { // Once someone asks for this pointer, we hold its reference count and never // free it. - static CPT(RenderState) state = (const RenderState *)NULL; - if (state == (const RenderState *)NULL) { + static CPT(RenderState) state = nullptr; + if (state == nullptr) { state = RenderState::make (DepthOffsetAttrib::make(1)); } diff --git a/panda/src/pgraph/cullTraverser.h b/panda/src/pgraph/cullTraverser.h index c137ecbbbf..b8ecbe084b 100644 --- a/panda/src/pgraph/cullTraverser.h +++ b/panda/src/pgraph/cullTraverser.h @@ -55,7 +55,7 @@ PUBLISHED: bool dr_incomplete_render); INLINE SceneSetup *get_scene() const; INLINE bool has_tag_state_key() const; - INLINE const string &get_tag_state_key() const; + INLINE const std::string &get_tag_state_key() const; INLINE void set_camera_mask(const DrawMask &camera_mask); INLINE const DrawMask &get_camera_mask() const; @@ -115,7 +115,7 @@ private: PT(SceneSetup) _scene_setup; DrawMask _camera_mask; bool _has_tag_state_key; - string _tag_state_key; + std::string _tag_state_key; CPT(RenderState) _initial_state; PT(GeometricBoundingVolume) _view_frustum; CullHandler *_cull_handler; diff --git a/panda/src/pgraph/cullTraverserData.I b/panda/src/pgraph/cullTraverserData.I index e2a9a64c95..c985e3bda9 100644 --- a/panda/src/pgraph/cullTraverserData.I +++ b/panda/src/pgraph/cullTraverserData.I @@ -31,7 +31,7 @@ CullTraverserData(const NodePath &start, _portal_depth(0) { // Only update the bounding volume if we're going to end up needing it. - bool check_bounds = (view_frustum != (GeometricBoundingVolume *)NULL); + bool check_bounds = (view_frustum != nullptr); _node_reader.check_cached(check_bounds); } @@ -55,7 +55,7 @@ CullTraverserData(const CullTraverserData &parent, PandaNode *child) : { // Only update the bounding volume if we're going to end up needing it. bool check_bounds = !_cull_planes->is_empty() || - (_view_frustum != (GeometricBoundingVolume *)NULL); + (_view_frustum != nullptr); _node_reader.check_cached(check_bounds); } @@ -140,7 +140,7 @@ is_in_view(const DrawMask &camera_mask) { return false; } - if (_view_frustum == (GeometricBoundingVolume *)NULL && + if (_view_frustum == nullptr && _cull_planes->is_empty()) { // If the transform is valid, but we don't have a frustum or any clip // planes or occluders, it's always in. diff --git a/panda/src/pgraph/cullTraverserData.cxx b/panda/src/pgraph/cullTraverserData.cxx index 1a8280948f..8d54308af8 100644 --- a/panda/src/pgraph/cullTraverserData.cxx +++ b/panda/src/pgraph/cullTraverserData.cxx @@ -41,7 +41,7 @@ apply_transform_and_state(CullTraverser *trav) { // camera. This indicates some special state transition for this node, // which is unique to this camera. const Camera *camera = trav->get_scene()->get_camera_node(); - string tag_state = _node_reader.get_tag(trav->get_tag_state_key()); + std::string tag_state = _node_reader.get_tag(trav->get_tag_state_key()); node_state = node_state->compose(camera->get_tag_state(tag_state)); } _node_reader.compose_draw_mask(_draw_mask); @@ -76,14 +76,14 @@ apply_transform(const TransformState *node_transform) { if (!node_transform->is_identity()) { _net_transform = _net_transform->compose(node_transform); - if ((_view_frustum != (GeometricBoundingVolume *)NULL) || + if ((_view_frustum != nullptr) || (!_cull_planes->is_empty())) { // We need to move the viewing frustums into the node's coordinate space // by applying the node's inverse transform. if (node_transform->is_singular()) { // But we can't invert a singular transform! Instead of trying, we'll // just give up on frustum culling from this point down. - _view_frustum = (GeometricBoundingVolume *)NULL; + _view_frustum = nullptr; _cull_planes = CullPlanes::make_empty(); } else { @@ -92,9 +92,9 @@ apply_transform(const TransformState *node_transform) { // Copy the bounding volumes for the frustums so we can transform // them. - if (_view_frustum != (GeometricBoundingVolume *)NULL) { + if (_view_frustum != nullptr) { _view_frustum = _view_frustum->make_copy()->as_geometric_bounding_volume(); - nassertv(_view_frustum != (GeometricBoundingVolume *)NULL); + nassertv(_view_frustum != nullptr); _view_frustum->xform(inv_transform->get_mat()); } @@ -144,17 +144,17 @@ r_get_node_path() const { */ bool CullTraverserData:: is_in_view_impl() { - const GeometricBoundingVolume *node_gbv = NULL; + const GeometricBoundingVolume *node_gbv = nullptr; - if (_view_frustum != (GeometricBoundingVolume *)NULL) { + if (_view_frustum != nullptr) { node_gbv = _node_reader.get_bounds()->as_geometric_bounding_volume(); - nassertr(node_gbv != (const GeometricBoundingVolume *)NULL, false); + nassertr(node_gbv != nullptr, false); int result = _view_frustum->contains(node_gbv); if (pgraph_cat.is_spam()) { pgraph_cat.spam() - << get_node_path() << " cull result = " << hex << result << dec << "\n"; + << get_node_path() << " cull result = " << std::hex << result << std::dec << "\n"; } if (result == BoundingVolume::IF_no_intersection) { @@ -168,14 +168,14 @@ is_in_view_impl() { // If we have fake view-frustum culling enabled, instead of actually // culling an object we simply force it to be drawn in red wireframe. - _view_frustum = (GeometricBoundingVolume *)NULL; + _view_frustum = nullptr; _state = _state->compose(get_fake_view_frustum_cull_state()); #endif } else if ((result & BoundingVolume::IF_all) != 0) { // The node and its descendents are completely enclosed within the // frustum. No need to cull further. - _view_frustum = (GeometricBoundingVolume *)NULL; + _view_frustum = nullptr; } else { // The node is partially, but not completely, within the viewing @@ -185,15 +185,15 @@ is_in_view_impl() { // down. But this node has the "final" flag, so the user is claiming // that there is some important reason we should consider everything // visible at this point. So be it. - _view_frustum = (GeometricBoundingVolume *)NULL; + _view_frustum = nullptr; } } } if (!_cull_planes->is_empty()) { - if (node_gbv == (const GeometricBoundingVolume *)NULL) { + if (node_gbv == nullptr) { node_gbv = _node_reader.get_bounds()->as_geometric_bounding_volume(); - nassertr(node_gbv != (const GeometricBoundingVolume *)NULL, false); + nassertr(node_gbv != nullptr, false); } // Also cull against the current clip planes. @@ -202,8 +202,8 @@ is_in_view_impl() { if (pgraph_cat.is_spam()) { pgraph_cat.spam() - << get_node_path() << " cull planes cull result = " << hex - << result << dec << "\n"; + << get_node_path() << " cull planes cull result = " << std::hex + << result << std::dec << "\n"; _cull_planes->write(pgraph_cat.spam(false)); } diff --git a/panda/src/pgraph/cullableObject.I b/panda/src/pgraph/cullableObject.I index e5e7229d09..51c0c8d80a 100644 --- a/panda/src/pgraph/cullableObject.I +++ b/panda/src/pgraph/cullableObject.I @@ -28,9 +28,9 @@ CullableObject() { INLINE CullableObject:: CullableObject(CPT(Geom) geom, CPT(RenderState) state, CPT(TransformState) internal_transform) : - _geom(move(geom)), - _state(move(state)), - _internal_transform(move(internal_transform)) + _geom(std::move(geom)), + _state(std::move(state)), + _internal_transform(std::move(internal_transform)) { #ifdef DO_MEMORY_USAGE MemoryUsage::record_pointer(this, get_class_type()); @@ -70,7 +70,7 @@ operator = (const CullableObject ©) { */ INLINE void CullableObject:: draw(GraphicsStateGuardianBase *gsg, bool force, Thread *current_thread) { - if (_draw_callback != (CallbackObject *)NULL) { + if (_draw_callback != nullptr) { // It has a callback associated. gsg->clear_before_callback(); gsg->set_state_and_transform(_state, _internal_transform); @@ -82,7 +82,7 @@ draw(GraphicsStateGuardianBase *gsg, bool force, Thread *current_thread) { } // Now the callback has taken care of drawing. } else { - nassertv(_geom != (Geom *)NULL); + nassertv(_geom != nullptr); gsg->set_state_and_transform(_state, _internal_transform); draw_inline(gsg, force, current_thread); } diff --git a/panda/src/pgraph/cullableObject.cxx b/panda/src/pgraph/cullableObject.cxx index d38fc4f5a4..dae73b00ed 100644 --- a/panda/src/pgraph/cullableObject.cxx +++ b/panda/src/pgraph/cullableObject.cxx @@ -114,8 +114,8 @@ munge_geom(GraphicsStateGuardianBase *gsg, GeomMunger *munger, if (pgraph_cat.is_spam()) { pgraph_cat.spam() << "munge_points_to_quads() for geometry with bits: " - << hex << geom_rendering << ", unsupported: " - << (unsupported_bits & Geom::GR_point_bits) << dec << "\n"; + << std::hex << geom_rendering << ", unsupported: " + << (unsupported_bits & Geom::GR_point_bits) << std::dec << "\n"; } if (!munge_points_to_quads(traverser, force)) { return false; @@ -161,7 +161,7 @@ munge_geom(GraphicsStateGuardianBase *gsg, GeomMunger *munger, _munged_data->animate_vertices(force, current_thread); if (animated_vertices != _munged_data) { cpu_animated = true; - swap(_munged_data, animated_vertices); + std::swap(_munged_data, animated_vertices); } #ifndef NDEBUG @@ -187,8 +187,8 @@ munge_geom(GraphicsStateGuardianBase *gsg, GeomMunger *munger, * */ void CullableObject:: -output(ostream &out) const { - if (_geom != (Geom *)NULL) { +output(std::ostream &out) const { + if (_geom != nullptr) { out << *_geom; } else { out << "(null)"; @@ -243,7 +243,7 @@ munge_points_to_quads(const CullTraverser *traverser, bool force) { bool sprite_texcoord = false; const TexGenAttrib *tex_gen = DCAST(TexGenAttrib, _state->get_attrib(TexGenAttrib::get_class_slot())); - if (tex_gen != (TexGenAttrib *)NULL) { + if (tex_gen != nullptr) { if (tex_gen->get_mode(TextureStage::get_default()) == TexGenAttrib::M_point_sprite) { sprite_texcoord = true; @@ -255,7 +255,7 @@ munge_points_to_quads(const CullTraverser *traverser, bool force) { PN_stdfloat point_size = 1; bool perspective = false; const RenderModeAttrib *render_mode = DCAST(RenderModeAttrib, _state->get_attrib(RenderModeAttrib::get_class_slot())); - if (render_mode != (RenderModeAttrib *)NULL) { + if (render_mode != nullptr) { point_size = render_mode->get_thickness(); perspective = render_mode->get_perspective(); @@ -491,7 +491,7 @@ munge_points_to_quads(const CullTraverser *traverser, bool force) { // Determine the format we should use to store the indices. Don't choose // NT_uint8, as Direct3D 9 doesn't support it. - const GeomVertexArrayFormat *new_prim_format = NULL; + const GeomVertexArrayFormat *new_prim_format = nullptr; if (new_verts < 0xffff) { new_prim_format = GeomPrimitive::get_index_format(GeomEnums::NT_uint16); @@ -545,7 +545,7 @@ munge_points_to_quads(const CullTraverser *traverser, bool force) { // Now sort the points in order from back-to-front so they will render // properly with transparency, at least with each other. - sort(vertices, vertices_end, SortPoints(points)); + std::sort(vertices, vertices_end, SortPoints(points)); // Go through the points, now in sorted order, and generate a pair of // triangles for each one. We generate indexed triangles instead of @@ -575,7 +575,7 @@ munge_points_to_quads(const CullTraverser *traverser, bool force) { int min_vi = primitive->get_min_vertex(); int max_vi = primitive->get_max_vertex(); - new_primitive->set_minmax(min_vi * 4, max_vi * 4 + 3, NULL, NULL); + new_primitive->set_minmax(min_vi * 4, max_vi * 4 + 3, nullptr, nullptr); new_geom->add_primitive(new_primitive); } @@ -583,12 +583,7 @@ munge_points_to_quads(const CullTraverser *traverser, bool force) { } _geom = new_geom.p(); - -#ifdef USE_MOVE_SEMANTICS - _munged_data = move(new_data); -#else - _munged_data = new_data; -#endif + _munged_data = std::move(new_data); return true; } @@ -603,8 +598,8 @@ get_flash_cpu_state() { // Once someone asks for this pointer, we hold its reference count and never // free it. - static CPT(RenderState) flash_cpu_state = (const RenderState *)NULL; - if (flash_cpu_state == (const RenderState *)NULL) { + static CPT(RenderState) flash_cpu_state = nullptr; + if (flash_cpu_state == nullptr) { flash_cpu_state = RenderState::make (LightAttrib::make_all_off(), TextureAttrib::make_off(), @@ -624,8 +619,8 @@ get_flash_hardware_state() { // Once someone asks for this pointer, we hold its reference count and never // free it. - static CPT(RenderState) flash_hardware_state = (const RenderState *)NULL; - if (flash_hardware_state == (const RenderState *)NULL) { + static CPT(RenderState) flash_hardware_state = nullptr; + if (flash_hardware_state == nullptr) { flash_hardware_state = RenderState::make (LightAttrib::make_all_off(), TextureAttrib::make_off(), diff --git a/panda/src/pgraph/cullableObject.h b/panda/src/pgraph/cullableObject.h index b02d7c79be..efde2dba5e 100644 --- a/panda/src/pgraph/cullableObject.h +++ b/panda/src/pgraph/cullableObject.h @@ -65,7 +65,7 @@ public: public: ALLOC_DELETED_CHAIN(CullableObject); - void output(ostream &out) const; + void output(std::ostream &out) const; public: CPT(Geom) _geom; @@ -127,7 +127,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const CullableObject &object) { +INLINE std::ostream &operator << (std::ostream &out, const CullableObject &object) { object.output(out); return out; } diff --git a/panda/src/pgraph/depthOffsetAttrib.cxx b/panda/src/pgraph/depthOffsetAttrib.cxx index ed6f942b1c..5516dd52ff 100644 --- a/panda/src/pgraph/depthOffsetAttrib.cxx +++ b/panda/src/pgraph/depthOffsetAttrib.cxx @@ -41,8 +41,8 @@ make(int offset) { */ CPT(RenderAttrib) DepthOffsetAttrib:: make(int offset, PN_stdfloat min_value, PN_stdfloat max_value) { - nassertr(min_value >= 0.0f && min_value <= 1.0f, NULL); - nassertr(max_value >= 0.0f && max_value <= 1.0f, NULL); + nassertr(min_value >= 0.0f && min_value <= 1.0f, nullptr); + nassertr(max_value >= 0.0f && max_value <= 1.0f, nullptr); DepthOffsetAttrib *attrib = new DepthOffsetAttrib(offset, min_value, max_value); return return_new(attrib); } @@ -60,7 +60,7 @@ make_default() { * */ void DepthOffsetAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":(" << get_offset() << ", " << get_min_value() << ", " << get_max_value() << ")"; } diff --git a/panda/src/pgraph/depthOffsetAttrib.h b/panda/src/pgraph/depthOffsetAttrib.h index 9ae6a6ce6f..54fef347d5 100644 --- a/panda/src/pgraph/depthOffsetAttrib.h +++ b/panda/src/pgraph/depthOffsetAttrib.h @@ -66,7 +66,7 @@ PUBLISHED: MAKE_PROPERTY(max_value, get_max_value); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/depthTestAttrib.cxx b/panda/src/pgraph/depthTestAttrib.cxx index b75f63b436..eb4093b168 100644 --- a/panda/src/pgraph/depthTestAttrib.cxx +++ b/panda/src/pgraph/depthTestAttrib.cxx @@ -44,7 +44,7 @@ make_default() { * */ void DepthTestAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; output_comparefunc(out,_mode); } diff --git a/panda/src/pgraph/depthTestAttrib.h b/panda/src/pgraph/depthTestAttrib.h index 2dfa4763e1..f4d6c52352 100644 --- a/panda/src/pgraph/depthTestAttrib.h +++ b/panda/src/pgraph/depthTestAttrib.h @@ -37,7 +37,7 @@ PUBLISHED: MAKE_PROPERTY(mode, get_mode); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/depthWriteAttrib.cxx b/panda/src/pgraph/depthWriteAttrib.cxx index eef6264d47..b12d0c30b8 100644 --- a/panda/src/pgraph/depthWriteAttrib.cxx +++ b/panda/src/pgraph/depthWriteAttrib.cxx @@ -44,7 +44,7 @@ make_default() { * */ void DepthWriteAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; switch (get_mode()) { case M_off: diff --git a/panda/src/pgraph/depthWriteAttrib.h b/panda/src/pgraph/depthWriteAttrib.h index d1cdbdc98f..50e31e764d 100644 --- a/panda/src/pgraph/depthWriteAttrib.h +++ b/panda/src/pgraph/depthWriteAttrib.h @@ -43,7 +43,7 @@ PUBLISHED: MAKE_PROPERTY(mode, get_mode); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/findApproxLevelEntry.I b/panda/src/pgraph/findApproxLevelEntry.I index 6404f93be4..9a9fb61a49 100644 --- a/panda/src/pgraph/findApproxLevelEntry.I +++ b/panda/src/pgraph/findApproxLevelEntry.I @@ -20,7 +20,7 @@ FindApproxLevelEntry(const WorkingNodePath &node_path, FindApproxPath &approx_pa _approx_path(approx_path) { _i = 0; - _next = NULL; + _next = nullptr; nassertv(_node_path.is_valid()); } @@ -50,7 +50,7 @@ FindApproxLevelEntry(const FindApproxLevelEntry ©) : _i(copy._i), _approx_path(copy._approx_path) { - _next = NULL; + _next = nullptr; nassertv(_node_path.is_valid()); } diff --git a/panda/src/pgraph/findApproxLevelEntry.cxx b/panda/src/pgraph/findApproxLevelEntry.cxx index 2b5679e271..07c8f1f931 100644 --- a/panda/src/pgraph/findApproxLevelEntry.cxx +++ b/panda/src/pgraph/findApproxLevelEntry.cxx @@ -22,7 +22,7 @@ TypeHandle FindApproxLevelEntry::_type_handle; * Formats the entry for meaningful output. For debugging only. */ void FindApproxLevelEntry:: -output(ostream &out) const { +output(std::ostream &out) const { out << "(" << _node_path << "):"; if (is_solution(0)) { out << " solution!"; @@ -38,9 +38,9 @@ output(ostream &out) const { * For debugging only. */ void FindApproxLevelEntry:: -write_level(ostream &out, int indent_level) const { +write_level(std::ostream &out, int indent_level) const { for (const FindApproxLevelEntry *entry = this; - entry != (const FindApproxLevelEntry *)NULL; + entry != nullptr; entry = entry->_next) { indent(out, indent_level); out << *entry << "\n"; @@ -92,7 +92,7 @@ consider_node(NodePathCollection &result, FindApproxLevelEntry *&next_level, } PandaNode *this_node = _node_path.node(); - nassertr(this_node != (PandaNode *)NULL, false); + nassertr(this_node != nullptr, false); bool stashed_only = next_is_stashed(increment); diff --git a/panda/src/pgraph/findApproxLevelEntry.h b/panda/src/pgraph/findApproxLevelEntry.h index 48c8663869..a5c3758bd9 100644 --- a/panda/src/pgraph/findApproxLevelEntry.h +++ b/panda/src/pgraph/findApproxLevelEntry.h @@ -47,8 +47,8 @@ public: int increment) const; INLINE bool is_solution(int increment) const; - void output(ostream &out) const; - void write_level(ostream &out, int indent_level) const; + void output(std::ostream &out) const; + void write_level(std::ostream &out, int indent_level) const; // _node_path represents the most recent node that we have previously // accepted as being a partial solution. @@ -73,8 +73,8 @@ private: static TypeHandle _type_handle; }; -INLINE ostream & -operator << (ostream &out, const FindApproxLevelEntry &entry) { +INLINE std::ostream & +operator << (std::ostream &out, const FindApproxLevelEntry &entry) { entry.output(out); return out; } diff --git a/panda/src/pgraph/findApproxPath.I b/panda/src/pgraph/findApproxPath.I index 616766a3ea..d8b9ea20c4 100644 --- a/panda/src/pgraph/findApproxPath.I +++ b/panda/src/pgraph/findApproxPath.I @@ -93,7 +93,7 @@ case_insensitive() const { * Formats the nth component of the path to the indicated output stream. */ INLINE void FindApproxPath:: -output_component(ostream &out, int index) const { +output_component(std::ostream &out, int index) const { nassertv(index >= 0 && index < (int)_path.size()); out << _path[index]; } diff --git a/panda/src/pgraph/findApproxPath.cxx b/panda/src/pgraph/findApproxPath.cxx index 0b8d035580..093a160f32 100644 --- a/panda/src/pgraph/findApproxPath.cxx +++ b/panda/src/pgraph/findApproxPath.cxx @@ -17,6 +17,9 @@ #include "string_utils.h" #include "pandaNode.h" +using std::ostream; +using std::string; + /** * Returns true if the indicated node matches this component, false otherwise. diff --git a/panda/src/pgraph/findApproxPath.h b/panda/src/pgraph/findApproxPath.h index 7b0d138d94..fe3ac5d765 100644 --- a/panda/src/pgraph/findApproxPath.h +++ b/panda/src/pgraph/findApproxPath.h @@ -32,16 +32,16 @@ class FindApproxPath { public: INLINE FindApproxPath(); - bool add_string(const string &str_path); - bool add_flags(const string &str_flags); - bool add_component(string str_component); + bool add_string(const std::string &str_path); + bool add_flags(const std::string &str_flags); + bool add_component(std::string str_component); - void add_match_name(const string &name, int flags); - void add_match_name_glob(const string &glob, int flags); + void add_match_name(const std::string &name, int flags); + void add_match_name_glob(const std::string &glob, int flags); void add_match_exact_type(TypeHandle type, int flags); void add_match_inexact_type(TypeHandle type, int flags); - void add_match_tag(const string &key, int flags); - void add_match_tag_value(const string &key, const string &value, int flags); + void add_match_tag(const std::string &key, int flags); + void add_match_tag_value(const std::string &key, const std::string &value, int flags); void add_match_one(int flags); void add_match_many(int flags); @@ -56,8 +56,8 @@ public: INLINE bool return_stashed() const; INLINE bool case_insensitive() const; - void output(ostream &out) const; - INLINE void output_component(ostream &out, int index) const; + void output(std::ostream &out) const; + INLINE void output_component(std::ostream &out, int index) const; #if !defined(WIN32_VC) && !defined(WIN64_VC) // Visual C++ won't let us define the ostream operator functions for these @@ -83,10 +83,10 @@ private: class Component { public: bool matches(PandaNode *node) const; - void output(ostream &out) const; + void output(std::ostream &out) const; ComponentType _type; - string _name; + std::string _name; GlobPattern _glob; TypeHandle _type_handle; PandaNode *_pointer; @@ -100,21 +100,21 @@ private: bool _return_stashed; bool _case_insensitive; -friend ostream &operator << (ostream &, FindApproxPath::ComponentType); -friend INLINE ostream &operator << (ostream &, const FindApproxPath::Component &); +friend std::ostream &operator << (std::ostream &, FindApproxPath::ComponentType); +friend INLINE std::ostream &operator << (std::ostream &, const FindApproxPath::Component &); }; -ostream & -operator << (ostream &out, FindApproxPath::ComponentType type); +std::ostream & +operator << (std::ostream &out, FindApproxPath::ComponentType type); -INLINE ostream & -operator << (ostream &out, const FindApproxPath::Component &component) { +INLINE std::ostream & +operator << (std::ostream &out, const FindApproxPath::Component &component) { component.output(out); return out; } -INLINE ostream & -operator << (ostream &out, const FindApproxPath &path) { +INLINE std::ostream & +operator << (std::ostream &out, const FindApproxPath &path) { path.output(out); return out; } diff --git a/panda/src/pgraph/fog.cxx b/panda/src/pgraph/fog.cxx index 06c831f337..dc45af63ee 100644 --- a/panda/src/pgraph/fog.cxx +++ b/panda/src/pgraph/fog.cxx @@ -27,8 +27,8 @@ TypeHandle Fog::_type_handle; -ostream & -operator << (ostream &out, Fog::Mode mode) { +std::ostream & +operator << (std::ostream &out, Fog::Mode mode) { switch (mode) { case Fog::M_linear: return out << "linear"; @@ -47,7 +47,7 @@ operator << (ostream &out, Fog::Mode mode) { * */ Fog:: -Fog(const string &name) : +Fog(const std::string &name) : PandaNode(name) { _mode = M_linear; @@ -112,7 +112,7 @@ xform(const LMatrix4 &mat) { * */ void Fog:: -output(ostream &out) const { +output(std::ostream &out) const { out << "fog: " << _mode; switch (_mode) { case M_linear: @@ -136,7 +136,6 @@ void Fog:: adjust_to_camera(const TransformState *camera_transform) { LVector3 forward = LVector3::forward(); - LPoint3 onset_point, opaque_point; if (get_num_parents() != 0) { // Linear fog is relative to the fog's net transform in the scene graph. NodePath this_np(this); diff --git a/panda/src/pgraph/fog.h b/panda/src/pgraph/fog.h index 3eb75603ba..5788df409f 100644 --- a/panda/src/pgraph/fog.h +++ b/panda/src/pgraph/fog.h @@ -40,7 +40,7 @@ class TransformState; */ class EXPCL_PANDA_PGRAPH Fog : public PandaNode { PUBLISHED: - explicit Fog(const string &name); + explicit Fog(const std::string &name); protected: Fog(const Fog ©); @@ -85,7 +85,7 @@ PUBLISHED: INLINE void set_exp_density(PN_stdfloat exp_density); MAKE_PROPERTY(exp_density, get_exp_density, set_exp_density); - void output(ostream &out) const; + void output(std::ostream &out) const; public: void adjust_to_camera(const TransformState *camera_transform); @@ -132,9 +132,9 @@ private: static TypeHandle _type_handle; }; -EXPCL_PANDA_PGRAPH ostream &operator << (ostream &out, Fog::Mode mode); +EXPCL_PANDA_PGRAPH std::ostream &operator << (std::ostream &out, Fog::Mode mode); -INLINE ostream &operator << (ostream &out, const Fog &fog) { +INLINE std::ostream &operator << (std::ostream &out, const Fog &fog) { fog.output(out); return out; } diff --git a/panda/src/pgraph/fogAttrib.I b/panda/src/pgraph/fogAttrib.I index e19a72a376..863d5c153a 100644 --- a/panda/src/pgraph/fogAttrib.I +++ b/panda/src/pgraph/fogAttrib.I @@ -24,7 +24,7 @@ FogAttrib() { */ INLINE bool FogAttrib:: is_off() const { - return _fog == (const Fog *)NULL; + return _fog == nullptr; } /** diff --git a/panda/src/pgraph/fogAttrib.cxx b/panda/src/pgraph/fogAttrib.cxx index 87e12086d4..3a511f7d19 100644 --- a/panda/src/pgraph/fogAttrib.cxx +++ b/panda/src/pgraph/fogAttrib.cxx @@ -54,7 +54,7 @@ make_off() { * */ void FogAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; if (is_off()) { out << "(off)"; @@ -128,7 +128,7 @@ complete_pointers(TypedWritable **p_list, BamReader *manager) { int pi = RenderAttrib::complete_pointers(p_list, manager); TypedWritable *fog = p_list[pi++]; - if (fog != (TypedWritable *)NULL) { + if (fog != nullptr) { _fog = DCAST(Fog, fog); } diff --git a/panda/src/pgraph/fogAttrib.h b/panda/src/pgraph/fogAttrib.h index 7f659b6336..8dac86fd6a 100644 --- a/panda/src/pgraph/fogAttrib.h +++ b/panda/src/pgraph/fogAttrib.h @@ -38,7 +38,7 @@ PUBLISHED: MAKE_PROPERTY(fog, get_fog); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/geomDrawCallbackData.cxx b/panda/src/pgraph/geomDrawCallbackData.cxx index 1b6dc76082..b8bdae2d78 100644 --- a/panda/src/pgraph/geomDrawCallbackData.cxx +++ b/panda/src/pgraph/geomDrawCallbackData.cxx @@ -21,7 +21,7 @@ TypeHandle GeomDrawCallbackData::_type_handle; * */ void GeomDrawCallbackData:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << "(" << (void *)_obj << ", " << (void *)_gsg << ", " << _force << ")"; } diff --git a/panda/src/pgraph/geomDrawCallbackData.h b/panda/src/pgraph/geomDrawCallbackData.h index 7e45f9eef2..87e9fbc401 100644 --- a/panda/src/pgraph/geomDrawCallbackData.h +++ b/panda/src/pgraph/geomDrawCallbackData.h @@ -31,7 +31,7 @@ public: GraphicsStateGuardianBase *gsg, bool force); PUBLISHED: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; INLINE CullableObject *get_object() const; INLINE GraphicsStateGuardianBase *get_gsg() const; diff --git a/panda/src/pgraph/geomNode.I b/panda/src/pgraph/geomNode.I index 431d5e1d2e..5b86d95155 100644 --- a/panda/src/pgraph/geomNode.I +++ b/panda/src/pgraph/geomNode.I @@ -48,7 +48,7 @@ INLINE CPT(Geom) GeomNode:: get_geom(int n) const { CDReader cdata(_cycler); CPT(GeomList) geoms = cdata->get_geoms(); - nassertr(n >= 0 && n < (int)geoms->size(), NULL); + nassertr(n >= 0 && n < (int)geoms->size(), nullptr); return (*geoms)[n]._geom.get_read_pointer(); } @@ -68,7 +68,7 @@ INLINE PT(Geom) GeomNode:: modify_geom(int n) { CDWriter cdata(_cycler, true); PT(GeomList) geoms = cdata->modify_geoms(); - nassertr(n >= 0 && n < (int)geoms->size(), NULL); + nassertr(n >= 0 && n < (int)geoms->size(), nullptr); mark_internal_bounds_stale(); return (*geoms)[n]._geom.get_write_pointer(); } @@ -83,7 +83,7 @@ INLINE const RenderState *GeomNode:: get_geom_state(int n) const { CDReader cdata(_cycler); CPT(GeomList) geoms = cdata->get_geoms(); - nassertr(n >= 0 && n < (int)geoms->size(), NULL); + nassertr(n >= 0 && n < (int)geoms->size(), nullptr); return (*geoms)[n]._state; } @@ -142,7 +142,7 @@ get_default_collide_mask() { */ INLINE void GeomNode:: count_name(GeomNode::NameCount &name_count, const InternalName *name) { - pair result = + std::pair result = name_count.insert(NameCount::value_type(name, 1)); if (!result.second) { (*result.first).second++; @@ -255,13 +255,12 @@ operator = (const GeomNode::Geoms ©) { _geoms = copy._geoms; } -#ifdef USE_MOVE_SEMANTICS /** * */ INLINE GeomNode::Geoms:: -Geoms(GeomNode::Geoms &&from) NOEXCEPT : - _geoms(move(from._geoms)) +Geoms(GeomNode::Geoms &&from) noexcept : + _geoms(std::move(from._geoms)) { } @@ -269,10 +268,9 @@ Geoms(GeomNode::Geoms &&from) NOEXCEPT : * */ INLINE void GeomNode::Geoms:: -operator = (GeomNode::Geoms &&from) NOEXCEPT { - _geoms = move(from._geoms); +operator = (GeomNode::Geoms &&from) noexcept { + _geoms = std::move(from._geoms); } -#endif // USE_MOVE_SEMANTICS /** * Returns the number of geoms of the node. @@ -289,8 +287,8 @@ get_num_geoms() const { */ INLINE CPT(Geom) GeomNode::Geoms:: get_geom(int n) const { - nassertr(!_geoms.is_null(), NULL); - nassertr(n >= 0 && n < (int)_geoms->size(), NULL); + nassertr(!_geoms.is_null(), nullptr); + nassertr(n >= 0 && n < (int)_geoms->size(), nullptr); return (*_geoms)[n]._geom.get_read_pointer(); } @@ -302,7 +300,7 @@ get_geom(int n) const { */ INLINE const RenderState *GeomNode::Geoms:: get_geom_state(int n) const { - nassertr(!_geoms.is_null(), NULL); - nassertr(n >= 0 && n < (int)_geoms->size(), NULL); + nassertr(!_geoms.is_null(), nullptr); + nassertr(n >= 0 && n < (int)_geoms->size(), nullptr); return (*_geoms)[n]._state; } diff --git a/panda/src/pgraph/geomNode.cxx b/panda/src/pgraph/geomNode.cxx index 8c9da5d331..328870364a 100644 --- a/panda/src/pgraph/geomNode.cxx +++ b/panda/src/pgraph/geomNode.cxx @@ -51,7 +51,7 @@ TypeHandle GeomNode::_type_handle; * */ GeomNode:: -GeomNode(const string &name) : +GeomNode(const std::string &name) : PandaNode(name) { _preserved = preserve_geom_nodes; @@ -134,7 +134,7 @@ apply_attribs_to_vertices(const AccumulatedAttribs &attribs, int attrib_types, if ((attrib_types & SceneGraphReducer::TT_color) != 0) { CPT(RenderAttrib) ra = geom_attribs._color; - if (ra != (const RenderAttrib *)NULL) { + if (ra != nullptr) { int override = geom_attribs._color_override; entry->_state = entry->_state->add_attrib(ra, override); } @@ -155,7 +155,7 @@ apply_attribs_to_vertices(const AccumulatedAttribs &attribs, int attrib_types, } } if ((attrib_types & SceneGraphReducer::TT_color_scale) != 0) { - if (geom_attribs._color_scale != (const RenderAttrib *)NULL) { + if (geom_attribs._color_scale != nullptr) { CPT(ColorScaleAttrib) csa = DCAST(ColorScaleAttrib, geom_attribs._color_scale); if (csa->get_scale() != LVecBase4(1.0f, 1.0f, 1.0f, 1.0f)) { @@ -198,7 +198,7 @@ apply_attribs_to_vertices(const AccumulatedAttribs &attribs, int attrib_types, } if ((attrib_types & SceneGraphReducer::TT_tex_matrix) != 0) { - if (geom_attribs._tex_matrix != (const RenderAttrib *)NULL) { + if (geom_attribs._tex_matrix != nullptr) { // Determine which texture coordinate names are used more than once. // This assumes we have discovered all of the textures that are in // effect on the GeomNode; this may not be true if there is a @@ -206,7 +206,7 @@ apply_attribs_to_vertices(const AccumulatedAttribs &attribs, int attrib_types, // started the flatten operation, but caveat programmer. NameCount name_count; - if (geom_attribs._texture != (RenderAttrib *)NULL) { + if (geom_attribs._texture != nullptr) { const TextureAttrib *ta = DCAST(TextureAttrib, geom_attribs._texture); int num_on_stages = ta->get_num_on_stages(); for (int si = 0; si < num_on_stages; si++) { @@ -254,7 +254,7 @@ apply_attribs_to_vertices(const AccumulatedAttribs &attribs, int attrib_types, // applied in the above. if ((attrib_types & SceneGraphReducer::TT_cull_face) != 0) { - if (geom_attribs._cull_face != (const RenderAttrib *)NULL) { + if (geom_attribs._cull_face != nullptr) { const CullFaceAttrib *cfa = DCAST(CullFaceAttrib, geom_attribs._cull_face); CullFaceAttrib::Mode mode = cfa->get_effective_mode(); switch (mode) { @@ -532,7 +532,7 @@ add_for_draw(CullTraverser *trav, CullTraverserData &data) { // otherwise the bounding volume of the GeomNode is (probably) the same as // that of the one Geom, and we've already culled against that. if (num_geoms > 1) { - if (data._view_frustum != (GeometricBoundingVolume *)NULL) { + if (data._view_frustum != nullptr) { // Cull the individual Geom against the view frustum. CPT(BoundingVolume) geom_volume = geom->get_bounds(); const GeometricBoundingVolume *geom_gbv = @@ -559,7 +559,7 @@ add_for_draw(CullTraverser *trav, CullTraverserData &data) { } CullableObject *object = - new CullableObject(move(geom), move(state), internal_transform); + new CullableObject(std::move(geom), std::move(state), internal_transform); trav->get_cull_handler()->record_object(object, trav); } } @@ -584,9 +584,9 @@ get_legal_collide_mask() const { */ void GeomNode:: add_geom(Geom *geom, const RenderState *state) { - nassertv(geom != (Geom *)NULL); + nassertv(geom != nullptr); nassertv(geom->check_valid()); - nassertv(state != (RenderState *)NULL); + nassertv(state != nullptr); Thread *current_thread = Thread::get_current_thread(); OPEN_ITERATE_CURRENT_AND_UPSTREAM(_cycler, current_thread) { @@ -635,7 +635,7 @@ add_geoms_from(const GeomNode *other) { */ void GeomNode:: set_geom(int n, Geom *geom) { - nassertv(geom != (Geom *)NULL); + nassertv(geom != nullptr); nassertv(geom->check_valid()); CDWriter cdata(_cycler, true); @@ -782,7 +782,7 @@ unify(int max_indices, bool preserve_order) { * Writes a short description of all the Geoms in the node. */ void GeomNode:: -write_geoms(ostream &out, int indent_level) const { +write_geoms(std::ostream &out, int indent_level) const { CDReader cdata(_cycler); write(out, indent_level); GeomList::const_iterator gi; @@ -798,7 +798,7 @@ write_geoms(ostream &out, int indent_level) const { * Writes a detailed description of all the Geoms in the node. */ void GeomNode:: -write_verbose(ostream &out, int indent_level) const { +write_verbose(std::ostream &out, int indent_level) const { CDReader cdata(_cycler); write(out, indent_level); GeomList::const_iterator gi; @@ -816,7 +816,7 @@ write_verbose(ostream &out, int indent_level) const { * */ void GeomNode:: -output(ostream &out) const { +output(std::ostream &out) const { // Accumulate the total set of RenderAttrib types that are applied to any of // our Geoms, so we can output them too. The result will be the list of // attrib types that might be applied to some Geoms, but not necessarily to @@ -1144,7 +1144,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { for (int i = 0; i < num_geoms; i++) { manager->read_pointer(scan); manager->read_pointer(scan); - geoms->push_back(GeomEntry(NULL, NULL)); + geoms->push_back(GeomEntry(nullptr, nullptr)); } _geoms = geoms; } diff --git a/panda/src/pgraph/geomNode.h b/panda/src/pgraph/geomNode.h index d17903027a..1402d07b5a 100644 --- a/panda/src/pgraph/geomNode.h +++ b/panda/src/pgraph/geomNode.h @@ -33,7 +33,7 @@ class GraphicsStateGuardianBase; */ class EXPCL_PANDA_PGRAPH GeomNode : public PandaNode { PUBLISHED: - explicit GeomNode(const string &name); + explicit GeomNode(const std::string &name); protected: GeomNode(const GeomNode ©); @@ -85,14 +85,14 @@ PUBLISHED: void decompose(); void unify(int max_indices, bool preserve_order); - void write_geoms(ostream &out, int indent_level) const; - void write_verbose(ostream &out, int indent_level) const; + void write_geoms(std::ostream &out, int indent_level) const; + void write_verbose(std::ostream &out, int indent_level) const; INLINE static CollideMask get_default_collide_mask(); MAKE_PROPERTY(default_collide_mask, get_default_collide_mask); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; virtual bool is_geom_node() const; @@ -164,12 +164,10 @@ public: INLINE Geoms(); INLINE Geoms(const CData *cdata); INLINE Geoms(const Geoms ©); - INLINE void operator = (const Geoms ©); + INLINE Geoms(Geoms &&from) noexcept; -#ifdef USE_MOVE_SEMANTICS - INLINE Geoms(Geoms &&from) NOEXCEPT; - INLINE void operator = (Geoms &&from) NOEXCEPT; -#endif + INLINE void operator = (const Geoms ©); + INLINE void operator = (Geoms &&from) noexcept; INLINE int get_num_geoms() const; INLINE CPT(Geom) get_geom(int n) const; diff --git a/panda/src/pgraph/geomTransformer.cxx b/panda/src/pgraph/geomTransformer.cxx index 65c1ca6c80..cfc023b528 100644 --- a/panda/src/pgraph/geomTransformer.cxx +++ b/panda/src/pgraph/geomTransformer.cxx @@ -108,7 +108,7 @@ bool GeomTransformer:: transform_vertices(Geom *geom, const LMatrix4 &mat) { PStatTimer timer(_apply_vertex_collector); - nassertr(geom != (Geom *)NULL, false); + nassertr(geom != nullptr, false); SourceVertices sv; sv._mat = mat; sv._vertex_data = geom->get_vertex_data(); @@ -151,7 +151,7 @@ transform_vertices(GeomNode *node, const LMatrix4 &mat) { GeomNode::GeomEntry &entry = (*gi); PT(Geom) new_geom = entry._geom.get_read_pointer()->make_copy(); if (transform_vertices(new_geom, mat)) { - entry._geom = move(new_geom); + entry._geom = std::move(new_geom); any_changed = true; } } @@ -175,7 +175,7 @@ transform_texcoords(Geom *geom, const InternalName *from_name, InternalName *to_name, const LMatrix4 &mat) { PStatTimer timer(_apply_texcoord_collector); - nassertr(geom != (Geom *)NULL, false); + nassertr(geom != nullptr, false); SourceTexCoords st; st._mat = mat; @@ -319,7 +319,7 @@ bool GeomTransformer:: transform_colors(Geom *geom, const LVecBase4 &scale) { PStatTimer timer(_apply_scale_color_collector); - nassertr(geom != (Geom *)NULL, false); + nassertr(geom != nullptr, false); SourceColors sc; sc._color = scale; @@ -384,10 +384,10 @@ apply_texture_colors(Geom *geom, TextureStage *ts, Texture *tex, bool keep_vertex_color) { PStatTimer timer(_apply_texture_color_collector); - nassertr(geom != (Geom *)NULL, false); + nassertr(geom != nullptr, false); PT(TexturePeeker) peeker = tex->peek(); - if (peeker == (TexturePeeker *)NULL) { + if (peeker == nullptr) { return false; } @@ -411,7 +411,7 @@ apply_texture_colors(Geom *geom, TextureStage *ts, Texture *tex, bool got_mat = false; LMatrix4 mat = LMatrix4::ident_mat(); - if (tma != (TexMatrixAttrib *)NULL && tma->has_stage(ts)) { + if (tma != nullptr && tma->has_stage(ts)) { mat = tma->get_mat(ts); got_mat = !mat.almost_equal(LMatrix4::ident_mat()); } @@ -478,7 +478,7 @@ apply_texture_colors(Geom *geom, TextureStage *ts, Texture *tex, // Check whether it has 2-d or 3-d texture coordinates. bool tex3d = false; const GeomVertexColumn *column = vdata->get_format()->get_column(ts->get_texcoord_name()); - if (column == (GeomVertexColumn *)NULL) { + if (column == nullptr) { return false; } if (column->get_num_components() >= 3) { @@ -585,7 +585,7 @@ apply_texture_colors(GeomNode *node, const RenderState *state) { CPT(RenderState) geom_state = state->compose(entry._state); const TextureAttrib *ta = DCAST(TextureAttrib, geom_state->get_attrib(TextureAttrib::get_class_slot())); - if (ta != (TextureAttrib *)NULL) { + if (ta != nullptr) { CPT(TextureAttrib) ta2 = ta->filter_to_max(1); if (ta2->get_num_on_stages() > 0) { TextureStage *ts = ta2->get_on_stage(0); @@ -595,7 +595,7 @@ apply_texture_colors(GeomNode *node, const RenderState *state) { const ColorAttrib *ca = DCAST(ColorAttrib, geom_state->get_attrib(ColorAttrib::get_class_slot())); LColor base_color(1.0f, 1.0f, 1.0f, 1.0f); bool keep_vertex_color = true; - if (ca != (ColorAttrib *)NULL && ca->get_color_type() == ColorAttrib::T_flat) { + if (ca != nullptr && ca->get_color_type() == ColorAttrib::T_flat) { base_color = ca->get_color(); keep_vertex_color = false; } @@ -659,7 +659,7 @@ bool GeomTransformer:: set_format(Geom *geom, const GeomVertexFormat *new_format) { PStatTimer timer(_apply_set_format_collector); - nassertr(geom != (Geom *)NULL, false); + nassertr(geom != nullptr, false); SourceFormat sf; sf._format = new_format; @@ -819,7 +819,7 @@ make_compatible_state(GeomNode *node) { */ bool GeomTransformer:: reverse_normals(Geom *geom) { - nassertr(geom != (Geom *)NULL, false); + nassertr(geom != nullptr, false); CPT(GeomVertexData) orig_data = geom->get_vertex_data(); NewVertexData &new_data = _reversed_normals[orig_data]; if (new_data._vdata.is_null()) { @@ -1047,7 +1047,7 @@ collect_vertex_data(Geom *geom, int collect_bits, bool format_only) { int GeomTransformer:: collect_vertex_data(GeomNode *node, int collect_bits, bool format_only) { int num_adjusted = 0; - GeomTransformer *dynamic = NULL; + GeomTransformer *dynamic = nullptr; GeomNode::CDWriter cdata(node->_cycler); GeomNode::GeomList::iterator gi; @@ -1061,7 +1061,7 @@ collect_vertex_data(GeomNode *node, int collect_bits, bool format_only) { new_geom->get_vertex_data()->get_usage_hint() < Geom::UH_static) { // This one has some dynamic properties. Collect it independently of // the outside world. - if (dynamic == (GeomTransformer *)NULL) { + if (dynamic == nullptr) { dynamic = new GeomTransformer(*this); } num_adjusted += dynamic->collect_vertex_data(new_geom, collect_bits, format_only); @@ -1071,7 +1071,7 @@ collect_vertex_data(GeomNode *node, int collect_bits, bool format_only) { } } - if (dynamic != (GeomTransformer *)NULL) { + if (dynamic != nullptr) { num_adjusted += dynamic->finish_collect(format_only); delete dynamic; } @@ -1222,7 +1222,7 @@ apply_collect_changes() { nassertr(vertex_offset == _num_vertices, 0); - if (_new_btable != (TransformBlendTable *)NULL) { + if (_new_btable != nullptr) { _new_btable->set_rows(_new_btable_rows); _new_data->set_transform_blend_table(_new_btable); } @@ -1242,7 +1242,7 @@ apply_collect_changes() { */ void GeomTransformer::NewCollectedData:: append_vdata(const GeomVertexData *vdata, int vertex_offset) { - for (int i = 0; i < vdata->get_num_arrays(); ++i) { + for (size_t i = 0; i < vdata->get_num_arrays(); ++i) { PT(GeomVertexArrayDataHandle) new_handle = _new_data->modify_array_handle(i); CPT(GeomVertexArrayDataHandle) old_handle = vdata->get_array_handle(i); size_t stride = (size_t)_new_format->get_array(i)->get_stride(); @@ -1258,11 +1258,11 @@ append_vdata(const GeomVertexData *vdata, int vertex_offset) { // in the vertices. Each of these has a slightly different way to handle // the remapping, because they have slightly different kinds of data. - if (vdata->get_transform_table() != (TransformTable *)NULL || - _new_data->get_transform_table() != (TransformTable *)NULL) { + if (vdata->get_transform_table() != nullptr || + _new_data->get_transform_table() != nullptr) { // The TransformTable. CPT(TransformTable) old_table; - if (vdata->get_transform_table() != (TransformTable *)NULL) { + if (vdata->get_transform_table() != nullptr) { old_table = vdata->get_transform_table(); } else { PT(TransformTable) temp_table = new TransformTable; @@ -1287,7 +1287,7 @@ append_vdata(const GeomVertexData *vdata, int vertex_offset) { // modifying the existing one, since a registered TransformTable cannot be // modified. PT(TransformTable) new_table; - if (_new_data->get_transform_table() != (TransformTable *)NULL) { + if (_new_data->get_transform_table() != nullptr) { new_table = new TransformTable(*_new_data->get_transform_table()); } else { new_table = new TransformTable; @@ -1335,7 +1335,7 @@ append_vdata(const GeomVertexData *vdata, int vertex_offset) { } } - if (vdata->get_transform_blend_table() != (TransformBlendTable *)NULL) { + if (vdata->get_transform_blend_table() != nullptr) { // The TransformBlendTable. This one is the easiest, because we can // modify it directly, and it will uniquify blend objects for us. @@ -1345,7 +1345,7 @@ append_vdata(const GeomVertexData *vdata, int vertex_offset) { CPT(TransformBlendTable) old_btable = vdata->get_transform_blend_table(); - if (_new_btable == (TransformBlendTable *)NULL) { + if (_new_btable == nullptr) { _new_btable = new TransformBlendTable; _new_btable->add_blend(TransformBlend()); } @@ -1380,7 +1380,7 @@ append_vdata(const GeomVertexData *vdata, int vertex_offset) { } } - if (vdata->get_slider_table() != (SliderTable *)NULL) { + if (vdata->get_slider_table() != nullptr) { // The SliderTable. This one requires making a copy, like the // TransformTable (since it can't be modified once registered either), but // at least it uniquifies sliders added to it. Also, it doesn't require @@ -1388,7 +1388,7 @@ append_vdata(const GeomVertexData *vdata, int vertex_offset) { // vertices with. const SliderTable *old_sliders = vdata->get_slider_table(); PT(SliderTable) new_sliders; - if (_new_data->get_slider_table() != (SliderTable *)NULL) { + if (_new_data->get_slider_table() != nullptr) { new_sliders = new SliderTable(*_new_data->get_slider_table()); } else { new_sliders = new SliderTable; @@ -1479,7 +1479,7 @@ remove_unused_vertices(const GeomVertexData *vdata) { PT(GeomVertexData) new_vdata = new GeomVertexData(*vdata); new_vdata->unclean_set_num_rows(new_num_vertices); - int num_arrays = vdata->get_num_arrays(); + size_t num_arrays = vdata->get_num_arrays(); nassertv(num_arrays == new_vdata->get_num_arrays()); GeomVertexDataPipelineReader reader(vdata, current_thread); @@ -1487,7 +1487,7 @@ remove_unused_vertices(const GeomVertexData *vdata) { GeomVertexDataPipelineWriter writer(new_vdata, true, current_thread); writer.check_array_writers(); - for (int a = 0; a < num_arrays; ++a) { + for (size_t a = 0; a < num_arrays; ++a) { const GeomVertexArrayDataHandle *array_reader = reader.get_array_reader(a); GeomVertexArrayDataHandle *array_writer = writer.get_array_writer(a); diff --git a/panda/src/pgraph/geomTransformer.h b/panda/src/pgraph/geomTransformer.h index e20732764f..120a4ca5f8 100644 --- a/panda/src/pgraph/geomTransformer.h +++ b/panda/src/pgraph/geomTransformer.h @@ -194,7 +194,7 @@ private: public: INLINE bool operator < (const NewCollectedKey &other) const; - string _name; + std::string _name; CPT(GeomVertexFormat) _format; Geom::UsageHint _usage_hint; Geom::AnimationType _animation_type; @@ -222,7 +222,7 @@ private: int apply_collect_changes(); CPT(GeomVertexFormat) _new_format; - string _vdata_name; + std::string _vdata_name; GeomEnums::UsageHint _usage_hint; SourceDatas _source_datas; SourceGeoms _source_geoms; diff --git a/panda/src/pgraph/internalNameCollection.cxx b/panda/src/pgraph/internalNameCollection.cxx index f1ab629206..9c3779c88e 100644 --- a/panda/src/pgraph/internalNameCollection.cxx +++ b/panda/src/pgraph/internalNameCollection.cxx @@ -181,7 +181,7 @@ get_num_names() const { */ const InternalName *InternalNameCollection:: get_name(int index) const { - nassertr(index >= 0 && index < (int)_names.size(), NULL); + nassertr(index >= 0 && index < (int)_names.size(), nullptr); return _names[index]; } @@ -192,7 +192,7 @@ get_name(int index) const { */ const InternalName *InternalNameCollection:: operator [] (int index) const { - nassertr(index >= 0 && index < (int)_names.size(), NULL); + nassertr(index >= 0 && index < (int)_names.size(), nullptr); return _names[index]; } @@ -211,7 +211,7 @@ size() const { * indicated output stream. */ void InternalNameCollection:: -output(ostream &out) const { +output(std::ostream &out) const { if (get_num_names() == 1) { out << "1 InternalName"; } else { @@ -224,7 +224,7 @@ output(ostream &out) const { * the indicated output stream. */ void InternalNameCollection:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { for (int i = 0; i < get_num_names(); i++) { indent(out, indent_level) << *get_name(i) << "\n"; } diff --git a/panda/src/pgraph/internalNameCollection.h b/panda/src/pgraph/internalNameCollection.h index 0c024cfaed..c409e35022 100644 --- a/panda/src/pgraph/internalNameCollection.h +++ b/panda/src/pgraph/internalNameCollection.h @@ -44,15 +44,15 @@ PUBLISHED: INLINE void operator += (const InternalNameCollection &other); INLINE InternalNameCollection operator + (const InternalNameCollection &other) const; - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; private: typedef PTA(CPT(InternalName)) InternalNames; InternalNames _names; }; -INLINE ostream &operator << (ostream &out, const InternalNameCollection &col) { +INLINE std::ostream &operator << (std::ostream &out, const InternalNameCollection &col) { col.output(out); return out; } diff --git a/panda/src/pgraph/lensNode.I b/panda/src/pgraph/lensNode.I index fd7c67f192..c1bb15afd1 100644 --- a/panda/src/pgraph/lensNode.I +++ b/panda/src/pgraph/lensNode.I @@ -45,12 +45,12 @@ set_lens(Lens *lens) { */ INLINE Lens *LensNode:: get_lens(int index) const { - nassertr(index >= 0 && index < max_lenses, NULL); // Sanity check + nassertr(index >= 0 && index < max_lenses, nullptr); // Sanity check if (index < (int)_lenses.size()) { return _lenses[index]._lens; } - return NULL; + return nullptr; } /** diff --git a/panda/src/pgraph/lensNode.cxx b/panda/src/pgraph/lensNode.cxx index 4fa15e2aa7..1b428d9e98 100644 --- a/panda/src/pgraph/lensNode.cxx +++ b/panda/src/pgraph/lensNode.cxx @@ -26,10 +26,10 @@ TypeHandle LensNode::_type_handle; * */ LensNode:: -LensNode(const string &name, Lens *lens) : +LensNode(const std::string &name, Lens *lens) : PandaNode(name) { - if (lens == NULL) { + if (lens == nullptr) { lens = new PerspectiveLens; } set_lens(0, lens); @@ -84,7 +84,7 @@ set_lens(int index, Lens *lens) { _lenses[index]._lens = lens; _lenses[index]._is_active = true; - if (_shown_frustum != (PandaNode *)NULL) { + if (_shown_frustum != nullptr) { show_frustum(); } } @@ -111,7 +111,7 @@ set_lens_active(int index, bool flag) { _lenses[index]._is_active = flag; - if (_shown_frustum != (PandaNode *)NULL) { + if (_shown_frustum != nullptr) { show_frustum(); } return true; @@ -124,9 +124,9 @@ set_lens_active(int index, bool flag) { bool LensNode:: is_in_view(int index, const LPoint3 &pos) { Lens *lens = get_lens(index); - nassertr(lens != (Lens *)NULL, false); + nassertr(lens != nullptr, false); PT(BoundingVolume) bv = lens->make_bounds(); - if (bv == (BoundingVolume *)NULL) { + if (bv == nullptr) { return false; } GeometricBoundingVolume *gbv = DCAST(GeometricBoundingVolume, bv); @@ -140,7 +140,7 @@ is_in_view(int index, const LPoint3 &pos) { */ void LensNode:: show_frustum() { - if (_shown_frustum != (PandaNode *)NULL) { + if (_shown_frustum != nullptr) { hide_frustum(); } PT(GeomNode) geom_node = new GeomNode("frustum"); @@ -150,7 +150,7 @@ show_frustum() { for (Lenses::const_iterator li = _lenses.begin(); li != _lenses.end(); ++li) { - if ((*li)._is_active && (*li)._lens != (Lens *)NULL) { + if ((*li)._is_active && (*li)._lens != nullptr) { geom_node->add_geom((*li)._lens->make_geometry()); } } @@ -161,9 +161,9 @@ show_frustum() { */ void LensNode:: hide_frustum() { - if (_shown_frustum != (PandaNode *)NULL) { + if (_shown_frustum != nullptr) { remove_child(_shown_frustum); - _shown_frustum = (PandaNode *)NULL; + _shown_frustum = nullptr; } } @@ -171,14 +171,14 @@ hide_frustum() { * */ void LensNode:: -output(ostream &out) const { +output(std::ostream &out) const { PandaNode::output(out); out << " ("; for (Lenses::const_iterator li = _lenses.begin(); li != _lenses.end(); ++li) { - if ((*li)._is_active && (*li)._lens != (Lens *)NULL) { + if ((*li)._is_active && (*li)._lens != nullptr) { out << " "; (*li)._lens->output(out); } @@ -190,13 +190,13 @@ output(ostream &out) const { * */ void LensNode:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { PandaNode::write(out, indent_level); for (Lenses::const_iterator li = _lenses.begin(); li != _lenses.end(); ++li) { - if ((*li)._is_active && (*li)._lens != (Lens *)NULL) { + if ((*li)._is_active && (*li)._lens != nullptr) { (*li)._lens->write(out, indent_level + 2); } } @@ -245,7 +245,7 @@ complete_pointers(TypedWritable **p_list, BamReader *manager) { (*li)._lens = DCAST(Lens, p_list[pi++]); } - if (_shown_frustum != (PandaNode *)NULL) { + if (_shown_frustum != nullptr) { show_frustum(); } diff --git a/panda/src/pgraph/lensNode.h b/panda/src/pgraph/lensNode.h index da9d9ef5f6..acc4c483be 100644 --- a/panda/src/pgraph/lensNode.h +++ b/panda/src/pgraph/lensNode.h @@ -28,13 +28,13 @@ */ class EXPCL_PANDA_PGRAPH LensNode : public PandaNode { PUBLISHED: - explicit LensNode(const string &name, Lens *lens = NULL); + explicit LensNode(const std::string &name, Lens *lens = nullptr); protected: LensNode(const LensNode ©); public: - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; virtual void xform(const LMatrix4 &mat); virtual PandaNode *make_copy() const; diff --git a/panda/src/pgraph/light.h b/panda/src/pgraph/light.h index ee6e906356..8cea78067d 100644 --- a/panda/src/pgraph/light.h +++ b/panda/src/pgraph/light.h @@ -67,8 +67,8 @@ public: virtual void attrib_ref(); virtual void attrib_unref(); - virtual void output(ostream &out) const=0; - virtual void write(ostream &out, int indent_level) const=0; + virtual void output(std::ostream &out) const=0; + virtual void write(std::ostream &out, int indent_level) const=0; virtual void bind(GraphicsStateGuardianBase *gsg, const NodePath &light, int light_id)=0; @@ -151,7 +151,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const Light &light) { +INLINE std::ostream &operator << (std::ostream &out, const Light &light) { light.output(out); return out; } diff --git a/panda/src/pgraph/lightAttrib.cxx b/panda/src/pgraph/lightAttrib.cxx index 40014c53ee..1d6fce8cf7 100644 --- a/panda/src/pgraph/lightAttrib.cxx +++ b/panda/src/pgraph/lightAttrib.cxx @@ -38,7 +38,7 @@ public: nassertr(!a.is_empty() && !b.is_empty(), a < b); Light *la = a.node()->as_light(); Light *lb = b.node()->as_light(); - nassertr(la != (Light *)NULL && lb != (Light *)NULL, a < b); + nassertr(la != nullptr && lb != nullptr, a < b); if (la->get_priority() != lb->get_priority()) { return la->get_priority() > lb->get_priority(); @@ -384,7 +384,7 @@ CPT(RenderAttrib) LightAttrib:: make() { // We make it a special case and store a pointer to the empty attrib forever // once we find it the first time, as an optimization. - if (_empty_attrib == (RenderAttrib *)NULL) { + if (_empty_attrib == nullptr) { _empty_attrib = return_new(new LightAttrib); } @@ -399,7 +399,7 @@ CPT(RenderAttrib) LightAttrib:: make_all_off() { // We make it a special case and store a pointer to the off attrib forever // once we find it the first time, as an optimization. - if (_all_off_attrib == (RenderAttrib *)NULL) { + if (_all_off_attrib == nullptr) { LightAttrib *attrib = new LightAttrib; attrib->_off_all_lights = true; _all_off_attrib = return_new(attrib); @@ -420,7 +420,7 @@ add_on_light(const NodePath &light) const { LightAttrib *attrib = new LightAttrib(*this); - pair insert_result = + std::pair insert_result = attrib->_on_lights.insert(Lights::value_type(light)); if (insert_result.second) { lobj->attrib_ref(); @@ -475,7 +475,7 @@ add_off_light(const NodePath &light) const { */ CPT(RenderAttrib) LightAttrib:: remove_off_light(const NodePath &light) const { - nassertr(!light.is_empty() && light.node()->as_light() != (Light *)NULL, this); + nassertr(!light.is_empty() && light.node()->as_light() != nullptr, this); LightAttrib *attrib = new LightAttrib(*this); attrib->_off_lights.erase(light); return return_new(attrib); @@ -523,7 +523,7 @@ get_ambient_contribution() const { * */ void LightAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; if (_off_lights.empty()) { if (_on_lights.empty()) { @@ -572,7 +572,7 @@ output(ostream &out) const { * */ void LightAttrib:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type() << ":"; if (_off_lights.empty()) { if (_on_lights.empty()) { @@ -734,8 +734,8 @@ compose_impl(const RenderAttrib *other) const { // Create a new LightAttrib that will hold the result. LightAttrib *new_attrib = new LightAttrib; - back_insert_iterator result = - back_inserter(new_attrib->_on_lights); + std::back_insert_iterator result = + std::back_inserter(new_attrib->_on_lights); while (ai != _on_lights.end() && bi != ta->_on_lights.end() && @@ -967,7 +967,7 @@ complete_pointers(TypedWritable **p_list, BamReader *manager) { } else { BamAuxData *aux = (BamAuxData *)manager->get_aux_data(this, "lights"); - nassertr(aux != NULL, pi); + nassertr(aux != nullptr, pi); int i; aux->_off_list.reserve(aux->_num_off_lights); @@ -1023,7 +1023,7 @@ finalize(BamReader *manager) { } else { // Now it's safe to convert our saved PandaNodes into NodePaths. BamAuxData *aux = (BamAuxData *)manager->get_aux_data(this, "lights"); - nassertv(aux != NULL); + nassertv(aux != nullptr); nassertv(aux->_num_off_lights == (int)aux->_off_list.size()); nassertv(aux->_num_on_lights == (int)aux->_on_list.size()); diff --git a/panda/src/pgraph/lightAttrib.h b/panda/src/pgraph/lightAttrib.h index 8d8b87bfb6..4872ebc623 100644 --- a/panda/src/pgraph/lightAttrib.h +++ b/panda/src/pgraph/lightAttrib.h @@ -95,8 +95,8 @@ PUBLISHED: MAKE_SEQ_PROPERTY(off_lights, get_num_off_lights, get_off_light); public: - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/lightRampAttrib.cxx b/panda/src/pgraph/lightRampAttrib.cxx index 7a7637a35f..3f5caee8d9 100644 --- a/panda/src/pgraph/lightRampAttrib.cxx +++ b/panda/src/pgraph/lightRampAttrib.cxx @@ -29,7 +29,7 @@ CPT(RenderAttrib) LightRampAttrib::_default; */ CPT(RenderAttrib) LightRampAttrib:: make_default() { - if (_default == 0) { + if (_default == nullptr) { LightRampAttrib *attrib = new LightRampAttrib(); _default = return_new(attrib); } @@ -176,7 +176,7 @@ make_hdr2() { * */ void LightRampAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; switch (_mode) { case LRT_default: diff --git a/panda/src/pgraph/lightRampAttrib.h b/panda/src/pgraph/lightRampAttrib.h index 65a894e582..d6859676bf 100644 --- a/panda/src/pgraph/lightRampAttrib.h +++ b/panda/src/pgraph/lightRampAttrib.h @@ -56,7 +56,7 @@ PUBLISHED: MAKE_PROPERTY(mode, get_mode); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/loader.I b/panda/src/pgraph/loader.I index c86753b3be..8ca4fc8f50 100644 --- a/panda/src/pgraph/loader.I +++ b/panda/src/pgraph/loader.I @@ -72,7 +72,7 @@ get_file(int n) const { */ INLINE LoaderFileType *Loader::Results:: get_file_type(int n) const { - nassertr(n >= 0 && n < (int)_files.size(), NULL); + nassertr(n >= 0 && n < (int)_files.size(), nullptr); return _files[n]._type; } @@ -109,14 +109,14 @@ get_task_manager() const { * is the initial name of the Loader object. */ INLINE void Loader:: -set_task_chain(const string &task_chain) { +set_task_chain(const std::string &task_chain) { _task_chain = task_chain; } /** * Returns the task chain that is used for asynchronous loads. */ -INLINE const string &Loader:: +INLINE const std::string &Loader:: get_task_chain() const { return _task_chain; } @@ -127,7 +127,7 @@ get_task_chain() const { INLINE void Loader:: stop_threads() { PT(AsyncTaskChain) chain = _task_manager->find_task_chain(_task_chain); - if (chain != (AsyncTaskChain *)NULL) { + if (chain != nullptr) { chain->stop_threads(); } } @@ -210,7 +210,7 @@ save_async(AsyncTask *request) { */ INLINE Loader *Loader:: get_global_ptr() { - if (_global_ptr == (Loader *)NULL) { + if (_global_ptr == nullptr) { make_global_ptr(); } return _global_ptr; diff --git a/panda/src/pgraph/loader.cxx b/panda/src/pgraph/loader.cxx index dbab28477d..c339d4918e 100644 --- a/panda/src/pgraph/loader.cxx +++ b/panda/src/pgraph/loader.cxx @@ -32,6 +32,8 @@ #include "configVariableInt.h" #include "configVariableEnum.h" +using std::string; + bool Loader::_file_types_loaded = false; PT(Loader) Loader::_global_ptr; TypeHandle Loader::_type_handle; @@ -46,7 +48,7 @@ Loader(const string &name) : _task_manager = AsyncTaskManager::get_global_ptr(); _task_chain = name; - if (_task_manager->find_task_chain(_task_chain) == NULL) { + if (_task_manager->find_task_chain(_task_chain) == nullptr) { PT(AsyncTaskChain) chain = _task_manager->make_task_chain(_task_chain); ConfigVariableInt loader_num_threads @@ -96,10 +98,10 @@ make_async_save_request(const Filename &filename, const LoaderOptions &options, * graph defined there. */ PT(PandaNode) Loader:: -load_bam_stream(istream &in) { +load_bam_stream(std::istream &in) { BamFile bam_file; if (!bam_file.open_read(in)) { - return NULL; + return nullptr; } return bam_file.read_node(); @@ -109,7 +111,7 @@ load_bam_stream(istream &in) { * */ void Loader:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << " " << get_name(); int num_tasks = _task_manager->make_task_chain(_task_chain)->get_num_tasks(); @@ -204,7 +206,7 @@ load_file(const Filename &filename, const LoaderOptions &options) const { Filename pathname(model_path.get_directory(i), this_filename); PT(PandaNode) result = try_load_file(pathname, this_options, requested_type); - if (result != (PandaNode *)NULL) { + if (result != nullptr) { return result; } } @@ -244,7 +246,7 @@ load_file(const Filename &filename, const LoaderOptions &options) const { // Look for the file only where it is. VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); PT(PandaNode) result = try_load_file(this_filename, this_options, requested_type); - if (result != (PandaNode *)NULL) { + if (result != nullptr) { return result; } if (report_errors) { @@ -265,7 +267,7 @@ load_file(const Filename &filename, const LoaderOptions &options) const { } } } - return NULL; + return nullptr; } /** @@ -283,7 +285,7 @@ try_load_file(const Filename &pathname, const LoaderOptions &options, if (allow_ram_cache) { // If we're allowing a RAM cache, use the ModelPool to load the file. PT(PandaNode) node = ModelPool::get_model(pathname, true); - if (node != (PandaNode *)NULL) { + if (node != nullptr) { if ((options.get_flags() & LoaderOptions::LF_allow_instance) == 0) { if (loader_cat.is_debug()) { loader_cat.debug() @@ -303,7 +305,7 @@ try_load_file(const Filename &pathname, const LoaderOptions &options, (options.get_flags() & LoaderOptions::LF_no_disk_cache) == 0) { // See if the model can be found in the on-disk cache, if it is active. record = cache->lookup(pathname, "bam"); - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { if (record->has_data()) { if (report_errors) { loader_cat.info() @@ -444,7 +446,7 @@ save_file(const Filename &filename, const LoaderOptions &options, LoaderFileType *requested_type = reg->get_type_from_extension(extension); - if (requested_type == (LoaderFileType *)NULL) { + if (requested_type == nullptr) { if (report_errors) { loader_cat.error() << "Extension of file " << this_filename @@ -514,15 +516,15 @@ load_file_types() { string name = words[0]; Filename dlname = Filename::dso_filename("lib" + name + ".so"); loader_cat.info() - << "loading file type module: " << name << endl; + << "loading file type module: " << name << std::endl; void *tmp = load_dso(get_plugin_path().get_value(), dlname); - if (tmp == (void *)NULL) { + if (tmp == nullptr) { loader_cat.warning() << "Unable to load " << dlname.to_os_specific() - << ": " << load_dso_error() << endl; + << ": " << load_dso_error() << std::endl; } else if (loader_cat.is_debug()) { loader_cat.debug() - << "done loading file type module: " << name << endl; + << "done loading file type module: " << name << std::endl; } } else if (words.size() > 1) { @@ -553,7 +555,7 @@ load_file_types() { */ void Loader:: make_global_ptr() { - nassertv(_global_ptr == (Loader *)NULL); + nassertv(_global_ptr == nullptr); _global_ptr = new Loader("loader"); } diff --git a/panda/src/pgraph/loader.h b/panda/src/pgraph/loader.h index 46de9ff8eb..9758151ec1 100644 --- a/panda/src/pgraph/loader.h +++ b/panda/src/pgraph/loader.h @@ -70,12 +70,12 @@ PUBLISHED: Files _files; }; - explicit Loader(const string &name = "loader"); + explicit Loader(const std::string &name = "loader"); INLINE void set_task_manager(AsyncTaskManager *task_manager); INLINE AsyncTaskManager *get_task_manager() const; - INLINE void set_task_chain(const string &task_chain); - INLINE const string &get_task_chain() const; + INLINE void set_task_chain(const std::string &task_chain); + INLINE const std::string &get_task_chain() const; BLOCKING INLINE void stop_threads(); INLINE bool remove(AsyncTask *task); @@ -94,9 +94,9 @@ PUBLISHED: PandaNode *node); INLINE void save_async(AsyncTask *request); - BLOCKING PT(PandaNode) load_bam_stream(istream &in); + BLOCKING PT(PandaNode) load_bam_stream(std::istream &in); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; INLINE static Loader *get_global_ptr(); @@ -113,7 +113,7 @@ private: static void make_global_ptr(); PT(AsyncTaskManager) _task_manager; - string _task_chain; + std::string _task_chain; static void load_file_types(); static bool _file_types_loaded; diff --git a/panda/src/pgraph/loaderFileType.cxx b/panda/src/pgraph/loaderFileType.cxx index 326dce8720..262da5859f 100644 --- a/panda/src/pgraph/loaderFileType.cxx +++ b/panda/src/pgraph/loaderFileType.cxx @@ -41,9 +41,9 @@ LoaderFileType:: * Returns a space-separated list of extension, in addition to the one * returned by get_extension(), that are recognized by this loader. */ -string LoaderFileType:: +std::string LoaderFileType:: get_additional_extensions() const { - return string(); + return std::string(); } /** @@ -101,7 +101,7 @@ load_file(const Filename &path, const LoaderOptions &options, BamCacheRecord *record) const { loader_cat.error() << get_type() << " cannot read PandaNode objects.\n"; - return NULL; + return nullptr; } /** diff --git a/panda/src/pgraph/loaderFileType.h b/panda/src/pgraph/loaderFileType.h index af1c21e2e7..fe2dcbfd2c 100644 --- a/panda/src/pgraph/loaderFileType.h +++ b/panda/src/pgraph/loaderFileType.h @@ -38,9 +38,9 @@ public: virtual ~LoaderFileType(); PUBLISHED: - virtual string get_name() const=0; - virtual string get_extension() const=0; - virtual string get_additional_extensions() const; + virtual std::string get_name() const=0; + virtual std::string get_extension() const=0; + virtual std::string get_additional_extensions() const; virtual bool supports_compressed() const; virtual bool get_allow_disk_cache(const LoaderOptions &options) const; diff --git a/panda/src/pgraph/loaderFileTypeBam.cxx b/panda/src/pgraph/loaderFileTypeBam.cxx index 9394c69357..7d2f6fd2cd 100644 --- a/panda/src/pgraph/loaderFileTypeBam.cxx +++ b/panda/src/pgraph/loaderFileTypeBam.cxx @@ -32,7 +32,7 @@ LoaderFileTypeBam() { /** * */ -string LoaderFileTypeBam:: +std::string LoaderFileTypeBam:: get_name() const { return "Bam"; } @@ -40,7 +40,7 @@ get_name() const { /** * */ -string LoaderFileTypeBam:: +std::string LoaderFileTypeBam:: get_extension() const { return "bam"; } @@ -80,7 +80,7 @@ supports_save() const { PT(PandaNode) LoaderFileTypeBam:: load_file(const Filename &path, const LoaderOptions &options, BamCacheRecord *record) const { - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { record->add_dependent_file(path); } @@ -88,13 +88,13 @@ load_file(const Filename &path, const LoaderOptions &options, BamFile bam_file; if (!bam_file.open_read(path, report_errors)) { - return NULL; + return nullptr; } bam_file.get_reader()->set_loader_options(options); time_t timestamp = bam_file.get_reader()->get_source()->get_timestamp(); PT(PandaNode) node = bam_file.read_node(report_errors); - if (node != (PandaNode *)NULL && node->is_of_type(ModelRoot::get_class_type())) { + if (node != nullptr && node->is_of_type(ModelRoot::get_class_type())) { ModelRoot *model_root = DCAST(ModelRoot, node.p()); model_root->set_fullpath(path); model_root->set_timestamp(timestamp); diff --git a/panda/src/pgraph/loaderFileTypeBam.h b/panda/src/pgraph/loaderFileTypeBam.h index 11c5687229..3a42508709 100644 --- a/panda/src/pgraph/loaderFileTypeBam.h +++ b/panda/src/pgraph/loaderFileTypeBam.h @@ -25,8 +25,8 @@ class EXPCL_PANDA_PGRAPH LoaderFileTypeBam : public LoaderFileType { public: LoaderFileTypeBam(); - virtual string get_name() const; - virtual string get_extension() const; + virtual std::string get_name() const; + virtual std::string get_extension() const; virtual bool supports_compressed() const; virtual bool supports_load() const; diff --git a/panda/src/pgraph/loaderFileTypeRegistry.cxx b/panda/src/pgraph/loaderFileTypeRegistry.cxx index 8ed3774368..c7df6731eb 100644 --- a/panda/src/pgraph/loaderFileTypeRegistry.cxx +++ b/panda/src/pgraph/loaderFileTypeRegistry.cxx @@ -21,6 +21,8 @@ #include +using std::string; + LoaderFileTypeRegistry *LoaderFileTypeRegistry::_global_ptr; /** @@ -124,7 +126,7 @@ get_num_types() const { */ LoaderFileType *LoaderFileTypeRegistry:: get_type(int n) const { - nassertr(n >= 0 && n < (int)_types.size(), NULL); + nassertr(n >= 0 && n < (int)_types.size(), nullptr); return _types[n]; } @@ -152,16 +154,16 @@ get_type_from_extension(const string &extension) { _deferred_types.erase(di); loader_cat->info() - << "loading file type module: " << name << endl; + << "loading file type module: " << name << std::endl; void *tmp = load_dso(get_plugin_path().get_value(), dlname); - if (tmp == (void *)NULL) { + if (tmp == nullptr) { loader_cat->warning() << "Unable to load " << dlname.to_os_specific() << ": " - << load_dso_error() << endl; - return NULL; + << load_dso_error() << std::endl; + return nullptr; } else if (loader_cat.is_debug()) { loader_cat.debug() - << "done loading file type module: " << name << endl; + << "done loading file type module: " << name << std::endl; } // Now try again to find the LoaderFileType. @@ -172,7 +174,7 @@ get_type_from_extension(const string &extension) { if (ei == _extensions.end()) { // Nothing matches that extension, even after we've checked for a deferred // type description. - return NULL; + return nullptr; } return (*ei).second; @@ -183,7 +185,7 @@ get_type_from_extension(const string &extension) { * per line. */ void LoaderFileTypeRegistry:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { if (_types.empty()) { indent(out, indent_level) << "(No file types are known).\n"; } else { @@ -192,7 +194,7 @@ write(ostream &out, int indent_level) const { LoaderFileType *type = (*ti); string name = type->get_name(); indent(out, indent_level) << name; - indent(out, max(30 - (int)name.length(), 0)) << " "; + indent(out, std::max(30 - (int)name.length(), 0)) << " "; bool comma = false; if (!type->get_extension().empty()) { @@ -231,7 +233,7 @@ write(ostream &out, int indent_level) const { */ LoaderFileTypeRegistry *LoaderFileTypeRegistry:: get_global_ptr() { - if (_global_ptr == (LoaderFileTypeRegistry *)NULL) { + if (_global_ptr == nullptr) { _global_ptr = new LoaderFileTypeRegistry; } return _global_ptr; diff --git a/panda/src/pgraph/loaderFileTypeRegistry.h b/panda/src/pgraph/loaderFileTypeRegistry.h index 6fedc09406..1cc1cd8f6f 100644 --- a/panda/src/pgraph/loaderFileTypeRegistry.h +++ b/panda/src/pgraph/loaderFileTypeRegistry.h @@ -33,30 +33,30 @@ public: ~LoaderFileTypeRegistry(); void register_type(LoaderFileType *type); - void register_deferred_type(const string &extension, const string &library); + void register_deferred_type(const std::string &extension, const std::string &library); PUBLISHED: int get_num_types() const; LoaderFileType *get_type(int n) const; MAKE_SEQ(get_types, get_num_types, get_type); MAKE_SEQ_PROPERTY(types, get_num_types, get_type); - LoaderFileType *get_type_from_extension(const string &extension); + LoaderFileType *get_type_from_extension(const std::string &extension); - void write(ostream &out, int indent_level = 0) const; + void write(std::ostream &out, int indent_level = 0) const; static LoaderFileTypeRegistry *get_global_ptr(); private: - void record_extension(const string &extension, LoaderFileType *type); + void record_extension(const std::string &extension, LoaderFileType *type); private: typedef pvector Types; Types _types; - typedef pmap Extensions; + typedef pmap Extensions; Extensions _extensions; - typedef pmap DeferredTypes; + typedef pmap DeferredTypes; DeferredTypes _deferred_types; static LoaderFileTypeRegistry *_global_ptr; diff --git a/panda/src/pgraph/logicOpAttrib.cxx b/panda/src/pgraph/logicOpAttrib.cxx index 28381dfc5b..75aff15fce 100644 --- a/panda/src/pgraph/logicOpAttrib.cxx +++ b/panda/src/pgraph/logicOpAttrib.cxx @@ -53,7 +53,7 @@ make_default() { * */ void LogicOpAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":" << get_operation(); } @@ -138,8 +138,8 @@ fillin(DatagramIterator &scan, BamReader *manager) { /** * */ -ostream & -operator << (ostream &out, LogicOpAttrib::Operation op) { +std::ostream & +operator << (std::ostream &out, LogicOpAttrib::Operation op) { switch (op) { case LogicOpAttrib::O_none: return out << "none"; diff --git a/panda/src/pgraph/logicOpAttrib.h b/panda/src/pgraph/logicOpAttrib.h index 99ab79d029..f5bd2ce5d9 100644 --- a/panda/src/pgraph/logicOpAttrib.h +++ b/panda/src/pgraph/logicOpAttrib.h @@ -59,7 +59,7 @@ PUBLISHED: MAKE_PROPERTY(operation, get_operation); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; @@ -105,7 +105,7 @@ private: static int _attrib_slot; }; -EXPCL_PANDA_PGRAPH ostream &operator << (ostream &out, LogicOpAttrib::Operation op); +EXPCL_PANDA_PGRAPH std::ostream &operator << (std::ostream &out, LogicOpAttrib::Operation op); #include "logicOpAttrib.I" diff --git a/panda/src/pgraph/materialAttrib.cxx b/panda/src/pgraph/materialAttrib.cxx index baeac4dc38..2ff453b8c6 100644 --- a/panda/src/pgraph/materialAttrib.cxx +++ b/panda/src/pgraph/materialAttrib.cxx @@ -56,7 +56,7 @@ make_default() { * */ void MaterialAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; if (_material != nullptr) { out << *_material; diff --git a/panda/src/pgraph/materialAttrib.h b/panda/src/pgraph/materialAttrib.h index 88c4a4363d..0e65498d70 100644 --- a/panda/src/pgraph/materialAttrib.h +++ b/panda/src/pgraph/materialAttrib.h @@ -40,7 +40,7 @@ PUBLISHED: MAKE_PROPERTY(material, get_material); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/materialCollection.cxx b/panda/src/pgraph/materialCollection.cxx index 665a924cbc..37fbd79c80 100644 --- a/panda/src/pgraph/materialCollection.cxx +++ b/panda/src/pgraph/materialCollection.cxx @@ -173,7 +173,7 @@ clear() { * NULL if no material has that name. */ Material *MaterialCollection:: -find_material(const string &name) const { +find_material(const std::string &name) const { int num_materials = get_num_materials(); for (int i = 0; i < num_materials; i++) { Material *material = get_material(i); @@ -181,7 +181,7 @@ find_material(const string &name) const { return material; } } - return NULL; + return nullptr; } /** @@ -197,7 +197,7 @@ get_num_materials() const { */ Material *MaterialCollection:: get_material(int index) const { - nassertr(index >= 0 && index < (int)_materials.size(), NULL); + nassertr(index >= 0 && index < (int)_materials.size(), nullptr); return _materials[index]; } @@ -208,7 +208,7 @@ get_material(int index) const { */ Material *MaterialCollection:: operator [] (int index) const { - nassertr(index >= 0 && index < (int)_materials.size(), NULL); + nassertr(index >= 0 && index < (int)_materials.size(), nullptr); return _materials[index]; } @@ -227,7 +227,7 @@ size() const { * indicated output stream. */ void MaterialCollection:: -output(ostream &out) const { +output(std::ostream &out) const { if (get_num_materials() == 1) { out << "1 Material"; } else { @@ -240,7 +240,7 @@ output(ostream &out) const { * indicated output stream. */ void MaterialCollection:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { for (int i = 0; i < get_num_materials(); i++) { indent(out, indent_level) << *get_material(i) << "\n"; } diff --git a/panda/src/pgraph/materialCollection.h b/panda/src/pgraph/materialCollection.h index 97bfcd71a1..1dc46aeca2 100644 --- a/panda/src/pgraph/materialCollection.h +++ b/panda/src/pgraph/materialCollection.h @@ -36,7 +36,7 @@ PUBLISHED: bool has_material(Material *material) const; void clear(); - Material *find_material(const string &name) const; + Material *find_material(const std::string &name) const; int get_num_materials() const; Material *get_material(int index) const; @@ -45,15 +45,15 @@ PUBLISHED: INLINE void operator += (const MaterialCollection &other); INLINE MaterialCollection operator + (const MaterialCollection &other) const; - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; private: typedef PTA(PT(Material)) Materials; Materials _materials; }; -INLINE ostream &operator << (ostream &out, const MaterialCollection &col) { +INLINE std::ostream &operator << (std::ostream &out, const MaterialCollection &col) { col.output(out); return out; } diff --git a/panda/src/pgraph/modelLoadRequest.cxx b/panda/src/pgraph/modelLoadRequest.cxx index 4feba702ef..0bbec06161 100644 --- a/panda/src/pgraph/modelLoadRequest.cxx +++ b/panda/src/pgraph/modelLoadRequest.cxx @@ -22,7 +22,7 @@ TypeHandle ModelLoadRequest::_type_handle; * to begin an asynchronous load. */ ModelLoadRequest:: -ModelLoadRequest(const string &name, +ModelLoadRequest(const std::string &name, const Filename &filename, const LoaderOptions &options, Loader *loader) : AsyncTask(name), diff --git a/panda/src/pgraph/modelLoadRequest.h b/panda/src/pgraph/modelLoadRequest.h index e743623fa3..f99dc7c38d 100644 --- a/panda/src/pgraph/modelLoadRequest.h +++ b/panda/src/pgraph/modelLoadRequest.h @@ -34,7 +34,7 @@ public: ALLOC_DELETED_CHAIN(ModelLoadRequest); PUBLISHED: - explicit ModelLoadRequest(const string &name, + explicit ModelLoadRequest(const std::string &name, const Filename &filename, const LoaderOptions &options, Loader *loader); diff --git a/panda/src/pgraph/modelNode.I b/panda/src/pgraph/modelNode.I index da0f61b0d4..929bedd6fc 100644 --- a/panda/src/pgraph/modelNode.I +++ b/panda/src/pgraph/modelNode.I @@ -15,7 +15,7 @@ * */ INLINE ModelNode:: -ModelNode(const string &name) : +ModelNode(const std::string &name) : PandaNode(name) { _preserve_transform = PT_none; diff --git a/panda/src/pgraph/modelNode.h b/panda/src/pgraph/modelNode.h index 177f1cffb6..c57d98476c 100644 --- a/panda/src/pgraph/modelNode.h +++ b/panda/src/pgraph/modelNode.h @@ -30,7 +30,7 @@ */ class EXPCL_PANDA_PGRAPH ModelNode : public PandaNode { PUBLISHED: - explicit INLINE ModelNode(const string &name); + explicit INLINE ModelNode(const std::string &name); protected: INLINE ModelNode(const ModelNode ©); diff --git a/panda/src/pgraph/modelPool.I b/panda/src/pgraph/modelPool.I index 26efd0a8c8..717c3eedba 100644 --- a/panda/src/pgraph/modelPool.I +++ b/panda/src/pgraph/modelPool.I @@ -33,7 +33,7 @@ has_model(const Filename &filename) { */ INLINE bool ModelPool:: verify_model(const Filename &filename) { - return load_model(filename) != (ModelRoot *)NULL; + return load_model(filename) != nullptr; } /** @@ -130,7 +130,7 @@ garbage_collect() { * Lists the contents of the model pool to the indicated output stream. */ INLINE void ModelPool:: -list_contents(ostream &out) { +list_contents(std::ostream &out) { get_ptr()->ns_list_contents(out); } @@ -139,7 +139,7 @@ list_contents(ostream &out) { */ INLINE void ModelPool:: list_contents() { - get_ptr()->ns_list_contents(cout); + get_ptr()->ns_list_contents(std::cout); } /** diff --git a/panda/src/pgraph/modelPool.cxx b/panda/src/pgraph/modelPool.cxx index 70d7b318c9..c53e2b867f 100644 --- a/panda/src/pgraph/modelPool.cxx +++ b/panda/src/pgraph/modelPool.cxx @@ -18,14 +18,14 @@ #include "virtualFileSystem.h" -ModelPool *ModelPool::_global_ptr = (ModelPool *)NULL; +ModelPool *ModelPool::_global_ptr = nullptr; /** * Lists the contents of the model pool to the indicated output stream. Helps * with debugging. */ void ModelPool:: -write(ostream &out) { +write(std::ostream &out) { get_ptr()->ns_list_contents(out); } @@ -37,7 +37,7 @@ ns_has_model(const Filename &filename) { LightMutexHolder holder(_lock); Models::const_iterator ti; ti = _models.find(filename); - if (ti != _models.end() && (*ti).second != (ModelRoot *)NULL) { + if (ti != _models.end() && (*ti).second != nullptr) { // This model was previously loaded. return true; } @@ -71,7 +71,7 @@ ns_get_model(const Filename &filename, bool verify) { << "ModelPool found " << cached_model << " for " << filename << "\n"; } - if (cached_model == NULL) { + if (cached_model == nullptr) { // This filename was previously attempted, but it did not exist (or the // model could not be loaded for some reason). if (cache_check_timestamps) { @@ -89,7 +89,7 @@ ns_get_model(const Filename &filename, bool verify) { // Compare the timestamp to the file on-disk. VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); PT(VirtualFile) vfile = vfs->get_file(cached_model->get_fullpath()); - if (vfile == NULL) { + if (vfile == nullptr) { // The file has disappeared! Look further along the model-path. got_cached_model = false; @@ -109,7 +109,7 @@ ns_get_model(const Filename &filename, bool verify) { } return cached_model; } else { - return NULL; + return nullptr; } } @@ -121,7 +121,7 @@ ns_load_model(const Filename &filename, const LoaderOptions &options) { // First check if it has already been loaded and is still current. PT(ModelRoot) cached_model = ns_get_model(filename, true); - if (cached_model != (ModelRoot *)NULL) { + if (cached_model != nullptr) { return cached_model; } @@ -239,7 +239,7 @@ ns_garbage_collect() { Models::iterator ti; for (ti = _models.begin(); ti != _models.end(); ++ti) { ModelRoot *node = (*ti).second; - if (node == (ModelRoot *)NULL || + if (node == nullptr || node->get_model_ref_count() == 1) { if (loader_cat.is_debug()) { loader_cat.debug() @@ -259,7 +259,7 @@ ns_garbage_collect() { * The nonstatic implementation of list_contents(). */ void ModelPool:: -ns_list_contents(ostream &out) const { +ns_list_contents(std::ostream &out) const { LightMutexHolder holder(_lock); out << "model pool contents:\n"; @@ -267,7 +267,7 @@ ns_list_contents(ostream &out) const { Models::const_iterator ti; int num_models = 0; for (ti = _models.begin(); ti != _models.end(); ++ti) { - if ((*ti).second != NULL) { + if ((*ti).second != nullptr) { ++num_models; out << (*ti).first << "\n" << " (count = " << (*ti).second->get_model_ref_count() @@ -285,7 +285,7 @@ ns_list_contents(ostream &out) const { */ ModelPool *ModelPool:: get_ptr() { - if (_global_ptr == (ModelPool *)NULL) { + if (_global_ptr == nullptr) { _global_ptr = new ModelPool; } return _global_ptr; diff --git a/panda/src/pgraph/modelPool.h b/panda/src/pgraph/modelPool.h index 34eefba0b5..8e0476c682 100644 --- a/panda/src/pgraph/modelPool.h +++ b/panda/src/pgraph/modelPool.h @@ -57,9 +57,9 @@ PUBLISHED: INLINE static int garbage_collect(); - INLINE static void list_contents(ostream &out); + INLINE static void list_contents(std::ostream &out); INLINE static void list_contents(); - static void write(ostream &out); + static void write(std::ostream &out); private: INLINE ModelPool(); @@ -76,7 +76,7 @@ private: void ns_release_all_models(); int ns_garbage_collect(); - void ns_list_contents(ostream &out) const; + void ns_list_contents(std::ostream &out) const; static ModelPool *get_ptr(); diff --git a/panda/src/pgraph/modelRoot.I b/panda/src/pgraph/modelRoot.I index df1bedaf7b..4478702a28 100644 --- a/panda/src/pgraph/modelRoot.I +++ b/panda/src/pgraph/modelRoot.I @@ -15,7 +15,7 @@ * */ INLINE ModelRoot:: -ModelRoot(const string &name) : +ModelRoot(const std::string &name) : ModelNode(name), _fullpath(name), _timestamp(0), diff --git a/panda/src/pgraph/modelRoot.h b/panda/src/pgraph/modelRoot.h index 7895dcab85..c73363c108 100644 --- a/panda/src/pgraph/modelRoot.h +++ b/panda/src/pgraph/modelRoot.h @@ -26,7 +26,7 @@ */ class EXPCL_PANDA_PGRAPH ModelRoot : public ModelNode { PUBLISHED: - INLINE explicit ModelRoot(const string &name); + INLINE explicit ModelRoot(const std::string &name); INLINE explicit ModelRoot(const Filename &fullpath, time_t timestamp); INLINE int get_model_ref_count() const; diff --git a/panda/src/pgraph/modelSaveRequest.cxx b/panda/src/pgraph/modelSaveRequest.cxx index 31c50cfdf6..eefca944d4 100644 --- a/panda/src/pgraph/modelSaveRequest.cxx +++ b/panda/src/pgraph/modelSaveRequest.cxx @@ -22,7 +22,7 @@ TypeHandle ModelSaveRequest::_type_handle; * to begin an asynchronous save. */ ModelSaveRequest:: -ModelSaveRequest(const string &name, +ModelSaveRequest(const std::string &name, const Filename &filename, const LoaderOptions &options, PandaNode *node, Loader *loader) : AsyncTask(name), diff --git a/panda/src/pgraph/modelSaveRequest.h b/panda/src/pgraph/modelSaveRequest.h index 7bbe1e331d..f15225e159 100644 --- a/panda/src/pgraph/modelSaveRequest.h +++ b/panda/src/pgraph/modelSaveRequest.h @@ -33,7 +33,7 @@ public: ALLOC_DELETED_CHAIN(ModelSaveRequest); PUBLISHED: - explicit ModelSaveRequest(const string &name, + explicit ModelSaveRequest(const std::string &name, const Filename &filename, const LoaderOptions &options, PandaNode *node, Loader *loader); diff --git a/panda/src/pgraph/nodePath.I b/panda/src/pgraph/nodePath.I index c7d75da2c1..5b7e80f7b7 100644 --- a/panda/src/pgraph/nodePath.I +++ b/panda/src/pgraph/nodePath.I @@ -16,9 +16,9 @@ */ INLINE NodePath:: NodePath() : - _error_type(ET_ok) + _error_type(ET_ok), + _backup_key(0) { - _backup_key = 0; } /** @@ -26,7 +26,7 @@ NodePath() : * PandaNode is created with the indicated name. */ INLINE NodePath:: -NodePath(const string &top_node_name, Thread *current_thread) : +NodePath(const std::string &top_node_name, Thread *current_thread) : _error_type(ET_ok) { PandaNode *top_node = new PandaNode(top_node_name); @@ -46,7 +46,7 @@ INLINE NodePath:: NodePath(PandaNode *node, Thread *current_thread) : _error_type(ET_ok) { - if (node != (PandaNode *)NULL) { + if (node != nullptr) { int pipeline_stage = current_thread->get_pipeline_stage(); _head = node->get_generic_component(false, pipeline_stage, current_thread); } @@ -61,7 +61,7 @@ NodePath(PandaNode *node, Thread *current_thread) : INLINE NodePath NodePath:: any_path(PandaNode *node, Thread *current_thread) { NodePath result; - if (node != (PandaNode *)NULL) { + if (node != nullptr) { int pipeline_stage = current_thread->get_pipeline_stage(); result._head = node->get_generic_component(true, pipeline_stage, current_thread); @@ -90,13 +90,12 @@ operator = (const NodePath ©) { _error_type = copy._error_type; } -#ifdef USE_MOVE_SEMANTICS /** * */ INLINE NodePath:: -NodePath(NodePath &&from) NOEXCEPT : - _head(move(from._head)), +NodePath(NodePath &&from) noexcept : + _head(std::move(from._head)), _backup_key(from._backup_key), _error_type(from._error_type) { @@ -106,12 +105,11 @@ NodePath(NodePath &&from) NOEXCEPT : * */ INLINE void NodePath:: -operator = (NodePath &&from) NOEXCEPT { - _head = move(from._head); +operator = (NodePath &&from) noexcept { + _head = std::move(from._head); _backup_key = from._backup_key; _error_type = from._error_type; } -#endif // USE_MOVE_SEMANTICS /** * Sets this NodePath to the empty NodePath. It will no longer point to any @@ -188,7 +186,7 @@ get_max_search_depth() { */ INLINE bool NodePath:: is_empty() const { - return (_head == (NodePathComponent *)NULL); + return (_head == nullptr); } /** @@ -197,7 +195,7 @@ is_empty() const { INLINE bool NodePath:: is_singleton(Thread *current_thread) const { int pipeline_stage = current_thread->get_pipeline_stage(); - return (_head != (NodePathComponent *)NULL && _head->is_top_node(pipeline_stage, current_thread)); + return (_head != nullptr && _head->is_top_node(pipeline_stage, current_thread)); } /** @@ -216,7 +214,7 @@ get_error_type() const { INLINE PandaNode *NodePath:: get_top_node(Thread *current_thread) const { if (is_empty()) { - return (PandaNode *)NULL; + return nullptr; } return get_top(current_thread).node(); @@ -227,7 +225,7 @@ get_top_node(Thread *current_thread) const { */ INLINE PandaNode *NodePath:: node() const { - nassertr_always(!is_empty(), (PandaNode *)NULL); + nassertr_always(!is_empty(), nullptr); return _head->get_node(); } @@ -285,7 +283,7 @@ is_same_graph(const NodePath &other, Thread *current_thread) const { // different instance of render that appears to have the same top node. But // this is a very rare thing to do. int a_count, b_count; - return (find_common_ancestor(*this, other, a_count, b_count, current_thread) != (NodePathComponent *)NULL); + return (find_common_ancestor(*this, other, a_count, b_count, current_thread) != nullptr); } /** @@ -295,7 +293,7 @@ is_same_graph(const NodePath &other, Thread *current_thread) const { INLINE bool NodePath:: is_ancestor_of(const NodePath &other, Thread *current_thread) const { int a_count, b_count; - if (find_common_ancestor(*this, other, a_count, b_count, current_thread) == (NodePathComponent *)NULL) { + if (find_common_ancestor(*this, other, a_count, b_count, current_thread) == nullptr) { // Not related. return false; } @@ -314,7 +312,7 @@ INLINE NodePath NodePath:: get_common_ancestor(const NodePath &other, Thread *current_thread) const { int a_count, b_count; NodePathComponent *common = find_common_ancestor(*this, other, a_count, b_count, current_thread); - if (common == (NodePathComponent *)NULL) { + if (common == nullptr) { return NodePath::not_found(); } @@ -388,7 +386,7 @@ get_parent(Thread *current_thread) const { * returning a new NodePath that references it. */ INLINE NodePath NodePath:: -attach_new_node(const string &name, int sort, Thread *current_thread) const { +attach_new_node(const std::string &name, int sort, Thread *current_thread) const { nassertr(verify_complete(current_thread), NodePath::fail()); return attach_new_node(new PandaNode(name), sort, current_thread); @@ -406,7 +404,7 @@ ls() const { * Lists the hierarchy at and below the referenced node. */ INLINE void NodePath:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { if (is_empty()) { out << "(empty)\n"; } else { @@ -459,7 +457,7 @@ set_attrib(const RenderAttrib *attrib, int priority) { */ INLINE const RenderAttrib *NodePath:: get_attrib(TypeHandle type) const { - nassertr_always(!is_empty(), NULL); + nassertr_always(!is_empty(), nullptr); return node()->get_attrib(type); } @@ -500,7 +498,7 @@ set_effect(const RenderEffect *effect) { */ INLINE const RenderEffect *NodePath:: get_effect(TypeHandle type) const { - nassertr_always(!is_empty(), NULL); + nassertr_always(!is_empty(), nullptr); return node()->get_effect(type); } @@ -1080,7 +1078,7 @@ get_sa() const { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, const PTA_float &v, int priority) { - set_shader_input(ShaderInput(move(id), v, priority)); + set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -1088,7 +1086,7 @@ set_shader_input(CPT_InternalName id, const PTA_float &v, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, const PTA_double &v, int priority) { - set_shader_input(ShaderInput(move(id), v, priority)); + set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -1096,7 +1094,7 @@ set_shader_input(CPT_InternalName id, const PTA_double &v, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, const PTA_int &v, int priority) { - set_shader_input(ShaderInput(move(id), v, priority)); + set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -1104,7 +1102,7 @@ set_shader_input(CPT_InternalName id, const PTA_int &v, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, const PTA_LVecBase4 &v, int priority) { - set_shader_input(ShaderInput(move(id), v, priority)); + set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -1112,7 +1110,7 @@ set_shader_input(CPT_InternalName id, const PTA_LVecBase4 &v, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, const PTA_LVecBase3 &v, int priority) { - set_shader_input(ShaderInput(move(id), v, priority)); + set_shader_input(ShaderInput(std::move(id), v, priority)); } @@ -1121,7 +1119,7 @@ set_shader_input(CPT_InternalName id, const PTA_LVecBase3 &v, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, const PTA_LVecBase2 &v, int priority) { - set_shader_input(ShaderInput(move(id), v, priority)); + set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -1129,7 +1127,7 @@ set_shader_input(CPT_InternalName id, const PTA_LVecBase2 &v, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, const LVecBase4 &v, int priority) { - set_shader_input(ShaderInput(move(id), v, priority)); + set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -1137,7 +1135,7 @@ set_shader_input(CPT_InternalName id, const LVecBase4 &v, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, const LVecBase3 &v, int priority) { - set_shader_input(ShaderInput(move(id), v, priority)); + set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -1145,7 +1143,7 @@ set_shader_input(CPT_InternalName id, const LVecBase3 &v, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, const LVecBase2 &v, int priority) { - set_shader_input(ShaderInput(move(id), v, priority)); + set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -1153,7 +1151,7 @@ set_shader_input(CPT_InternalName id, const LVecBase2 &v, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, const PTA_LVecBase4i &v, int priority) { - set_shader_input(ShaderInput(move(id), v, priority)); + set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -1161,7 +1159,7 @@ set_shader_input(CPT_InternalName id, const PTA_LVecBase4i &v, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, const PTA_LVecBase3i &v, int priority) { - set_shader_input(ShaderInput(move(id), v, priority)); + set_shader_input(ShaderInput(std::move(id), v, priority)); } @@ -1170,7 +1168,7 @@ set_shader_input(CPT_InternalName id, const PTA_LVecBase3i &v, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, const PTA_LVecBase2i &v, int priority) { - set_shader_input(ShaderInput(move(id), v, priority)); + set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -1178,7 +1176,7 @@ set_shader_input(CPT_InternalName id, const PTA_LVecBase2i &v, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, const LVecBase4i &v, int priority) { - set_shader_input(ShaderInput(move(id), v, priority)); + set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -1186,7 +1184,7 @@ set_shader_input(CPT_InternalName id, const LVecBase4i &v, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, const LVecBase3i &v, int priority) { - set_shader_input(ShaderInput(move(id), v, priority)); + set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -1194,7 +1192,7 @@ set_shader_input(CPT_InternalName id, const LVecBase3i &v, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, const LVecBase2i &v, int priority) { - set_shader_input(ShaderInput(move(id), v, priority)); + set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -1202,7 +1200,7 @@ set_shader_input(CPT_InternalName id, const LVecBase2i &v, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, const PTA_LMatrix4 &v, int priority) { - set_shader_input(ShaderInput(move(id), v, priority)); + set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -1210,7 +1208,7 @@ set_shader_input(CPT_InternalName id, const PTA_LMatrix4 &v, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, const PTA_LMatrix3 &v, int priority) { - set_shader_input(ShaderInput(move(id), v, priority)); + set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -1218,7 +1216,7 @@ set_shader_input(CPT_InternalName id, const PTA_LMatrix3 &v, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, const LMatrix4 &v, int priority) { - set_shader_input(ShaderInput(move(id), v, priority)); + set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -1226,7 +1224,7 @@ set_shader_input(CPT_InternalName id, const LMatrix4 &v, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, const LMatrix3 &v, int priority) { - set_shader_input(ShaderInput(move(id), v, priority)); + set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -1234,7 +1232,7 @@ set_shader_input(CPT_InternalName id, const LMatrix3 &v, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, Texture *tex, int priority) { - set_shader_input(ShaderInput(move(id), tex, priority)); + set_shader_input(ShaderInput(std::move(id), tex, priority)); } /** @@ -1242,7 +1240,7 @@ set_shader_input(CPT_InternalName id, Texture *tex, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, Texture *tex, const SamplerState &sampler, int priority) { - set_shader_input(ShaderInput(move(id), tex, sampler, priority)); + set_shader_input(ShaderInput(std::move(id), tex, sampler, priority)); } /** @@ -1250,7 +1248,7 @@ set_shader_input(CPT_InternalName id, Texture *tex, const SamplerState &sampler, */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, Texture *tex, bool read, bool write, int z, int n, int priority) { - set_shader_input(ShaderInput(move(id), tex, read, write, z, n, priority)); + set_shader_input(ShaderInput(std::move(id), tex, read, write, z, n, priority)); } /** @@ -1258,7 +1256,7 @@ set_shader_input(CPT_InternalName id, Texture *tex, bool read, bool write, int z */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, ShaderBuffer *buf, int priority) { - set_shader_input(ShaderInput(move(id), buf, priority)); + set_shader_input(ShaderInput(std::move(id), buf, priority)); } /** @@ -1266,7 +1264,7 @@ set_shader_input(CPT_InternalName id, ShaderBuffer *buf, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, const NodePath &np, int priority) { - set_shader_input(ShaderInput(move(id), np, priority)); + set_shader_input(ShaderInput(std::move(id), np, priority)); } /** @@ -1274,7 +1272,7 @@ set_shader_input(CPT_InternalName id, const NodePath &np, int priority) { */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, int n1, int n2, int n3, int n4, int priority) { - set_shader_input(ShaderInput(move(id), LVecBase4i(n1, n2, n3, n4), priority)); + set_shader_input(ShaderInput(std::move(id), LVecBase4i(n1, n2, n3, n4), priority)); } /** @@ -1282,7 +1280,7 @@ set_shader_input(CPT_InternalName id, int n1, int n2, int n3, int n4, int priori */ INLINE void NodePath:: set_shader_input(CPT_InternalName id, PN_stdfloat n1, PN_stdfloat n2, PN_stdfloat n3, PN_stdfloat n4, int priority) { - set_shader_input(ShaderInput(move(id), LVecBase4(n1, n2, n3, n4), priority)); + set_shader_input(ShaderInput(std::move(id), LVecBase4(n1, n2, n3, n4), priority)); } /** @@ -1735,7 +1733,7 @@ clear_project_texture(TextureStage *stage) { * string for the default texture coordinate set. */ INLINE bool NodePath:: -has_texcoord(const string &texcoord_name) const { +has_texcoord(const std::string &texcoord_name) const { return has_vertex_column(InternalName::get_texcoord_name(texcoord_name)); } @@ -1988,7 +1986,7 @@ clear_model_nodes() { * of any one key's value. */ INLINE void NodePath:: -set_tag(const string &key, const string &value) { +set_tag(const std::string &key, const std::string &value) { nassertv_always(!is_empty()); node()->set_tag(key, value); } @@ -1998,12 +1996,12 @@ set_tag(const string &key, const string &value) { * the particular key, if any. If no value has been previously set, returns * the empty string. See also get_net_tag(). */ -INLINE string NodePath:: -get_tag(const string &key) const { +INLINE std::string NodePath:: +get_tag(const std::string &key) const { // An empty NodePath quietly returns no tags. This makes get_net_tag() // easier to implement. if (is_empty()) { - return string(); + return std::string(); } return node()->get_tag(key); } @@ -2026,7 +2024,7 @@ get_tag_keys(vector_string &keys) const { * set. See also has_net_tag(). */ INLINE bool NodePath:: -has_tag(const string &key) const { +has_tag(const std::string &key) const { // An empty NodePath quietly has no tags. This makes has_net_tag() easier // to implement. if (is_empty()) { @@ -2040,7 +2038,7 @@ has_tag(const string &key) const { * call to clear_tag(), has_tag() will return false for the indicated key. */ INLINE void NodePath:: -clear_tag(const string &key) { +clear_tag(const std::string &key) { nassertv_always(!is_empty()); node()->clear_tag(key); } @@ -2051,8 +2049,8 @@ clear_tag(const string &key) { * indicated key on any ancestor node, returns the empty string. See also * get_tag(). */ -INLINE string NodePath:: -get_net_tag(const string &key) const { +INLINE std::string NodePath:: +get_net_tag(const std::string &key) const { return find_net_tag(key).get_tag(key); } @@ -2061,7 +2059,7 @@ get_net_tag(const string &key) const { * any ancestor node, or false otherwise. See also has_tag(). */ INLINE bool NodePath:: -has_net_tag(const string &key) const { +has_net_tag(const std::string &key) const { return !find_net_tag(key).is_empty(); } @@ -2081,7 +2079,7 @@ list_tags() const { * Changes the name of the referenced node. */ INLINE void NodePath:: -set_name(const string &name) { +set_name(const std::string &name) { nassertv_always(!is_empty()); node()->set_name(name); } @@ -2089,9 +2087,9 @@ set_name(const string &name) { /** * Returns the name of the referenced node. */ -INLINE string NodePath:: +INLINE std::string NodePath:: get_name() const { - nassertr_always(!is_empty(), string()); + nassertr_always(!is_empty(), std::string()); return node()->get_name(); } @@ -2113,7 +2111,7 @@ encode_to_bam_stream() const { } -INLINE ostream &operator << (ostream &out, const NodePath &node_path) { +INLINE std::ostream &operator << (std::ostream &out, const NodePath &node_path) { node_path.output(out); return out; } diff --git a/panda/src/pgraph/nodePath.cxx b/panda/src/pgraph/nodePath.cxx index 71bbb3a561..9123a951b5 100644 --- a/panda/src/pgraph/nodePath.cxx +++ b/panda/src/pgraph/nodePath.cxx @@ -71,6 +71,13 @@ #include "bam.h" #include "bamWriter.h" #include "datagramBuffer.h" +#include "weakNodePath.h" + +using std::max; +using std::move; +using std::ostream; +using std::ostringstream; +using std::string; // stack seems to overflow on Intel C++ at 7000. If we need more than 7000, // need to increase stack size. @@ -89,7 +96,7 @@ NodePath(const NodePath &parent, PandaNode *child_node, Thread *current_thread) : _error_type(ET_fail) { - nassertv(child_node != (PandaNode *)NULL); + nassertv(child_node != nullptr); int pipeline_stage = current_thread->get_pipeline_stage(); if (parent.is_empty()) { @@ -101,9 +108,9 @@ NodePath(const NodePath &parent, PandaNode *child_node, _head = PandaNode::get_component(parent._head, child_node, pipeline_stage, current_thread); } - nassertv(_head != (NodePathComponent *)NULL); + nassertv(_head != nullptr); - if (_head != (NodePathComponent *)NULL) { + if (_head != nullptr) { _error_type = ET_ok; } _backup_key = 0; @@ -144,7 +151,7 @@ get_num_nodes(Thread *current_thread) const { */ PandaNode *NodePath:: get_node(int index, Thread *current_thread) const { - nassertr(index >= 0 && index < get_num_nodes(), NULL); + nassertr(index >= 0 && index < get_num_nodes(), nullptr); int pipeline_stage = current_thread->get_pipeline_stage(); @@ -152,14 +159,14 @@ get_node(int index, Thread *current_thread) const { while (index > 0) { // If this assertion fails, the index was out of range; the component's // length must have been invalid. - nassertr(comp != (NodePathComponent *)NULL, NULL); + nassertr(comp != nullptr, nullptr); comp = comp->get_next(pipeline_stage, current_thread); index--; } // If this assertion fails, the index was out of range; the component's // length must have been invalid. - nassertr(comp != (NodePathComponent *)NULL, NULL); + nassertr(comp != nullptr, nullptr); return comp->get_node(); } @@ -180,14 +187,14 @@ get_ancestor(int index, Thread *current_thread) const { while (index > 0) { // If this assertion fails, the index was out of range; the component's // length must have been invalid. - nassertr(comp != (NodePathComponent *)NULL, NodePath::fail()); + nassertr(comp != nullptr, NodePath::fail()); comp = comp->get_next(pipeline_stage, current_thread); index--; } // If this assertion fails, the index was out of range; the component's // length must have been invalid. - nassertr(comp != (NodePathComponent *)NULL, NodePath::fail()); + nassertr(comp != nullptr, NodePath::fail()); NodePath result; result._head = comp; @@ -209,7 +216,7 @@ get_top(Thread *current_thread) const { NodePathComponent *comp = _head; while (!comp->is_top_node(pipeline_stage, current_thread)) { comp = comp->get_next(pipeline_stage, current_thread); - nassertr(comp != (NodePathComponent *)NULL, NodePath::fail()); + nassertr(comp != nullptr, NodePath::fail()); } NodePath top; @@ -283,7 +290,7 @@ get_sort(Thread *current_thread) const { PandaNode *parent = _head->get_next(pipeline_stage, current_thread)->get_node(); PandaNode *child = node(); - nassertr(parent != (PandaNode *)NULL && child != (PandaNode *)NULL, 0); + nassertr(parent != nullptr && child != nullptr, 0); int child_index = parent->find_child(child); if (child_index != -1) { return parent->get_child_sort(child_index); @@ -324,7 +331,7 @@ find(const string &path) const { NodePath NodePath:: find_path_to(PandaNode *node) const { nassertr_always(!is_empty(), fail()); - nassertr(node != (PandaNode *)NULL, fail()); + nassertr(node != nullptr, fail()); NodePathCollection col; FindApproxPath approx_path; @@ -361,7 +368,7 @@ find_all_paths_to(PandaNode *node) const { NodePathCollection col; nassertr_always(!is_empty(), col); nassertr(verify_complete(), col); - nassertr(node != (PandaNode *)NULL, col); + nassertr(node != nullptr, col); FindApproxPath approx_path; approx_path.add_match_many(0); approx_path.add_match_pointer(node, 0); @@ -471,7 +478,7 @@ instance_to(const NodePath &other, int sort, Thread *current_thread) const { // First, we'll attach to NULL, to guarantee we get a brand new instance. int pipeline_stage = current_thread->get_pipeline_stage(); - new_instance._head = PandaNode::attach(NULL, node(), sort, pipeline_stage, + new_instance._head = PandaNode::attach(nullptr, node(), sort, pipeline_stage, current_thread); // Now, we'll reparent the new instance to the target node. @@ -533,7 +540,7 @@ copy_to(const NodePath &other, int sort, Thread *current_thread) const { PandaNode *source_node = node(); PT(PandaNode) copy_node = source_node->copy_subgraph(current_thread); - nassertr(copy_node != (PandaNode *)NULL, fail()); + nassertr(copy_node != nullptr, fail()); copy_node->reset_prev_transform(current_thread); @@ -556,7 +563,7 @@ NodePath NodePath:: attach_new_node(PandaNode *node, int sort, Thread *current_thread) const { nassertr(verify_complete(current_thread), NodePath::fail()); nassertr(_error_type == ET_ok, NodePath::fail()); - nassertr(node != (PandaNode *)NULL, NodePath::fail()); + nassertr(node != nullptr, NodePath::fail()); NodePath new_path(*this); int pipeline_stage = current_thread->get_pipeline_stage(); @@ -665,7 +672,7 @@ output(ostream &out) const { break; } - if (_head == (NodePathComponent *)NULL) { + if (_head == nullptr) { out << "(empty)"; } else { _head->output(out); @@ -704,7 +711,7 @@ get_state(const NodePath &other, Thread *current_thread) const { #endif int a_count, b_count; - if (find_common_ancestor(*this, other, a_count, b_count, current_thread) == (NodePathComponent *)NULL) { + if (find_common_ancestor(*this, other, a_count, b_count, current_thread) == nullptr) { if (allow_unrelated_wrt) { pgraph_cat.debug() << *this << " is not related to " << other << "\n"; @@ -776,7 +783,7 @@ get_transform(const NodePath &other, Thread *current_thread) const { #endif int a_count, b_count; - if (find_common_ancestor(*this, other, a_count, b_count, current_thread) == (NodePathComponent *)NULL) { + if (find_common_ancestor(*this, other, a_count, b_count, current_thread) == nullptr) { if (allow_unrelated_wrt) { if (pgraph_cat.is_debug()) { pgraph_cat.debug() @@ -792,10 +799,10 @@ get_transform(const NodePath &other, Thread *current_thread) const { CPT(TransformState) a_transform, b_transform; a_transform = r_get_partial_transform(_head, a_count, current_thread); - if (a_transform != (TransformState *)NULL) { + if (a_transform != nullptr) { b_transform = r_get_partial_transform(other._head, b_count, current_thread); } - if (b_transform == (TransformState *)NULL) { + if (b_transform == nullptr) { // If either path involved a node with a net_transform RenderEffect // applied, we have to go all the way up to the root to get the right // answer. @@ -863,7 +870,7 @@ get_prev_transform(const NodePath &other, Thread *current_thread) const { #endif int a_count, b_count; - if (find_common_ancestor(*this, other, a_count, b_count, current_thread) == (NodePathComponent *)NULL) { + if (find_common_ancestor(*this, other, a_count, b_count, current_thread) == nullptr) { if (allow_unrelated_wrt) { pgraph_cat.debug() << *this << " is not related to " << other << "\n"; @@ -1997,7 +2004,7 @@ get_color() const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(ColorAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const ColorAttrib *ca = DCAST(ColorAttrib, attrib); if (ca->get_color_type() == ColorAttrib::T_flat) { return ca->get_color(); @@ -2042,7 +2049,7 @@ compose_color_scale(const LVecBase4 &scale, int priority) { const RenderAttrib *attrib = node()->get_attrib(ColorScaleAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { priority = max(priority, node()->get_state()->get_override(ColorScaleAttrib::get_class_slot())); const ColorScaleAttrib *csa = DCAST(ColorScaleAttrib, attrib); @@ -2072,7 +2079,7 @@ set_color_scale(const LVecBase4 &scale, int priority) { const RenderAttrib *attrib = node()->get_attrib(ColorScaleAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { priority = max(priority, node()->get_state()->get_override(ColorScaleAttrib::get_class_slot())); const ColorScaleAttrib *csa = DCAST(ColorScaleAttrib, attrib); @@ -2114,7 +2121,7 @@ set_alpha_scale(PN_stdfloat scale, int priority) { const RenderAttrib *attrib = node()->get_attrib(ColorScaleAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { priority = max(priority, node()->get_state()->get_override(ColorScaleAttrib::get_class_slot())); const ColorScaleAttrib *csa = DCAST(ColorScaleAttrib, attrib); @@ -2140,7 +2147,7 @@ set_all_color_scale(PN_stdfloat scale, int priority) { const RenderAttrib *attrib = node()->get_attrib(ColorScaleAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { priority = max(priority, node()->get_state()->get_override(ColorScaleAttrib::get_class_slot())); const ColorScaleAttrib *csa = DCAST(ColorScaleAttrib, attrib); @@ -2166,7 +2173,7 @@ get_color_scale() const { nassertr_always(!is_empty(), ident_scale); const RenderAttrib *attrib = node()->get_attrib(ColorScaleAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const ColorScaleAttrib *csa = DCAST(ColorScaleAttrib, attrib); return csa->get_scale(); } @@ -2185,11 +2192,11 @@ set_light(const NodePath &light, int priority) { nassertv_always(!is_empty()); if (!light.is_empty()) { Light *light_obj = light.node()->as_light(); - if (light_obj != (Light *)NULL) { + if (light_obj != nullptr) { // It's an actual Light object. const RenderAttrib *attrib = node()->get_attrib(LightAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { priority = max(priority, node()->get_state()->get_override(LightAttrib::get_class_slot())); const LightAttrib *la = DCAST(LightAttrib, attrib); @@ -2215,7 +2222,7 @@ set_light(const NodePath &light, int priority) { const RenderEffect *effect = node()->get_effect(PolylightEffect::get_class_type()); - if (effect != (const RenderEffect *)NULL) { + if (effect != nullptr) { const PolylightEffect *ple = DCAST(PolylightEffect, effect); // Modify the existing PolylightEffect to add the indicated light. @@ -2263,10 +2270,10 @@ set_light_off(const NodePath &light, int priority) { if (!light.is_empty()) { Light *light_obj = light.node()->as_light(); - if (light_obj != (Light *)NULL) { + if (light_obj != nullptr) { const RenderAttrib *attrib = node()->get_attrib(LightAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { priority = max(priority, node()->get_state()->get_override(LightAttrib::get_class_slot())); const LightAttrib *la = DCAST(LightAttrib, attrib); @@ -2309,10 +2316,10 @@ clear_light(const NodePath &light) { if (!light.is_empty()) { Light *light_obj = light.node()->as_light(); - if (light_obj != (Light *)NULL) { + if (light_obj != nullptr) { const RenderAttrib *attrib = node()->get_attrib(LightAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { CPT(LightAttrib) la = DCAST(LightAttrib, attrib); la = DCAST(LightAttrib, la->remove_on_light(light)); la = DCAST(LightAttrib, la->remove_off_light(light)); @@ -2330,7 +2337,7 @@ clear_light(const NodePath &light) { } else if (light.node()->is_of_type(PolylightNode::get_class_type())) { const RenderEffect *effect = node()->get_effect(PolylightEffect::get_class_type()); - if (effect != (const RenderEffect *)NULL) { + if (effect != nullptr) { CPT(PolylightEffect) ple = DCAST(PolylightEffect, effect); ple = DCAST(PolylightEffect, ple->remove_light(light)); node()->set_effect(ple); @@ -2352,10 +2359,10 @@ has_light(const NodePath &light) const { if (!light.is_empty()) { Light *light_obj = light.node()->as_light(); - if (light_obj != (Light *)NULL) { + if (light_obj != nullptr) { const RenderAttrib *attrib = node()->get_attrib(LightAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const LightAttrib *la = DCAST(LightAttrib, attrib); return la->has_on_light(light); } @@ -2364,7 +2371,7 @@ has_light(const NodePath &light) const { } else if (light.node()->is_of_type(PolylightNode::get_class_type())) { const RenderEffect *effect = node()->get_effect(PolylightEffect::get_class_type()); - if (effect != (const RenderEffect *)NULL) { + if (effect != nullptr) { const PolylightEffect *ple = DCAST(PolylightEffect, effect); return ple->has_light(light); } @@ -2386,7 +2393,7 @@ has_light_off() const { const RenderAttrib *attrib = node()->get_attrib(LightAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const LightAttrib *la = DCAST(LightAttrib, attrib); return la->has_all_off(); } @@ -2407,10 +2414,10 @@ has_light_off(const NodePath &light) const { nassertr_always(!is_empty(), false); if (!light.is_empty()) { Light *light_obj = light.node()->as_light(); - if (light_obj != (Light *)NULL) { + if (light_obj != nullptr) { const RenderAttrib *attrib = node()->get_attrib(LightAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const LightAttrib *la = DCAST(LightAttrib, attrib); return la->has_off_light(light); } @@ -2433,7 +2440,7 @@ set_clip_plane(const NodePath &clip_plane, int priority) { if (!clip_plane.is_empty() && clip_plane.node()->is_of_type(PlaneNode::get_class_type())) { const RenderAttrib *attrib = node()->get_attrib(ClipPlaneAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { priority = max(priority, node()->get_state()->get_override(ClipPlaneAttrib::get_class_slot())); const ClipPlaneAttrib *la = DCAST(ClipPlaneAttrib, attrib); @@ -2481,7 +2488,7 @@ set_clip_plane_off(const NodePath &clip_plane, int priority) { if (!clip_plane.is_empty() && clip_plane.node()->is_of_type(PlaneNode::get_class_type())) { const RenderAttrib *attrib = node()->get_attrib(ClipPlaneAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { priority = max(priority, node()->get_state()->get_override(ClipPlaneAttrib::get_class_slot())); const ClipPlaneAttrib *la = DCAST(ClipPlaneAttrib, attrib); @@ -2522,7 +2529,7 @@ clear_clip_plane(const NodePath &clip_plane) { if (!clip_plane.is_empty() && clip_plane.node()->is_of_type(PlaneNode::get_class_type())) { const RenderAttrib *attrib = node()->get_attrib(ClipPlaneAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { CPT(ClipPlaneAttrib) la = DCAST(ClipPlaneAttrib, attrib); la = DCAST(ClipPlaneAttrib, la->remove_on_plane(clip_plane)); la = DCAST(ClipPlaneAttrib, la->remove_off_plane(clip_plane)); @@ -2552,7 +2559,7 @@ has_clip_plane(const NodePath &clip_plane) const { if (!clip_plane.is_empty() && clip_plane.node()->is_of_type(PlaneNode::get_class_type())) { const RenderAttrib *attrib = node()->get_attrib(ClipPlaneAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const ClipPlaneAttrib *la = DCAST(ClipPlaneAttrib, attrib); return la->has_on_plane(clip_plane); } @@ -2573,7 +2580,7 @@ has_clip_plane_off() const { const RenderAttrib *attrib = node()->get_attrib(ClipPlaneAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const ClipPlaneAttrib *la = DCAST(ClipPlaneAttrib, attrib); return la->has_all_off(); } @@ -2592,7 +2599,7 @@ has_clip_plane_off(const NodePath &clip_plane) const { if (!clip_plane.is_empty() && clip_plane.node()->is_of_type(PlaneNode::get_class_type())) { const RenderAttrib *attrib = node()->get_attrib(ClipPlaneAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const ClipPlaneAttrib *la = DCAST(ClipPlaneAttrib, attrib); return la->has_off_plane(clip_plane); } @@ -2614,7 +2621,7 @@ set_occluder(const NodePath &occluder) { if (!occluder.is_empty() && occluder.node()->is_of_type(OccluderNode::get_class_type())) { const RenderEffect *effect = node()->get_effect(OccluderEffect::get_class_type()); - if (effect != (const RenderEffect *)NULL) { + if (effect != nullptr) { const OccluderEffect *la = DCAST(OccluderEffect, effect); // Modify the existing OccluderEffect to add the indicated occluder. @@ -2650,7 +2657,7 @@ clear_occluder(const NodePath &occluder) { if (!occluder.is_empty() && occluder.node()->is_of_type(OccluderNode::get_class_type())) { const RenderEffect *effect = node()->get_effect(OccluderEffect::get_class_type()); - if (effect != (const RenderEffect *)NULL) { + if (effect != nullptr) { CPT(OccluderEffect) la = DCAST(OccluderEffect, effect); la = DCAST(OccluderEffect, la->remove_on_occluder(occluder)); @@ -2678,7 +2685,7 @@ has_occluder(const NodePath &occluder) const { if (!occluder.is_empty() && occluder.node()->is_of_type(OccluderNode::get_class_type())) { const RenderEffect *effect = node()->get_effect(OccluderEffect::get_class_type()); - if (effect != (const RenderEffect *)NULL) { + if (effect != nullptr) { const OccluderEffect *la = DCAST(OccluderEffect, effect); return la->has_on_occluder(occluder); } @@ -2823,7 +2830,7 @@ get_bin_name() const { nassertr_always(!is_empty(), string()); const RenderAttrib *attrib = node()->get_attrib(CullBinAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const CullBinAttrib *ba = DCAST(CullBinAttrib, attrib); return ba->get_bin_name(); } @@ -2841,7 +2848,7 @@ get_bin_draw_order() const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(CullBinAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const CullBinAttrib *ba = DCAST(CullBinAttrib, attrib); return ba->get_draw_order(); } @@ -2877,7 +2884,7 @@ set_texture(TextureStage *stage, Texture *tex, int priority) { const RenderAttrib *attrib = node()->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TextureAttrib *tsa = DCAST(TextureAttrib, attrib); int sg_priority = node()->get_state()->get_override(TextureAttrib::get_class_slot()); @@ -2927,7 +2934,7 @@ set_texture(TextureStage *stage, Texture *tex, const SamplerState &sampler, int const RenderAttrib *attrib = node()->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TextureAttrib *tsa = DCAST(TextureAttrib, attrib); int sg_priority = node()->get_state()->get_override(TextureAttrib::get_class_slot()); @@ -2965,7 +2972,7 @@ set_texture_off(TextureStage *stage, int priority) { const RenderAttrib *attrib = node()->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TextureAttrib *tsa = DCAST(TextureAttrib, attrib); int sg_priority = node()->get_state()->get_override(TextureAttrib::get_class_slot()); @@ -3003,7 +3010,7 @@ clear_texture(TextureStage *stage) { const RenderAttrib *attrib = node()->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { CPT(TextureAttrib) tsa = DCAST(TextureAttrib, attrib); tsa = DCAST(TextureAttrib, tsa->remove_on_stage(stage)); tsa = DCAST(TextureAttrib, tsa->remove_off_stage(stage)); @@ -3026,7 +3033,7 @@ clear_texture(TextureStage *stage) { */ bool NodePath:: has_texture() const { - return get_texture() != (Texture *)NULL; + return get_texture() != nullptr; } /** @@ -3041,7 +3048,7 @@ has_texture(TextureStage *stage) const { const RenderAttrib *attrib = node()->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); return ta->has_on_stage(stage); } @@ -3060,7 +3067,7 @@ has_texture_off() const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); return ta->has_all_off(); } @@ -3080,7 +3087,7 @@ has_texture_off(TextureStage *stage) const { const RenderAttrib *attrib = node()->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); return ta->has_off_stage(stage); } @@ -3098,15 +3105,15 @@ has_texture_off(TextureStage *stage) const { */ Texture *NodePath:: get_texture() const { - nassertr_always(!is_empty(), NULL); + nassertr_always(!is_empty(), nullptr); const RenderAttrib *attrib = node()->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); return ta->get_texture(); } - return NULL; + return nullptr; } /** @@ -3115,15 +3122,15 @@ get_texture() const { */ Texture *NodePath:: get_texture(TextureStage *stage) const { - nassertr_always(!is_empty(), NULL); + nassertr_always(!is_empty(), nullptr); const RenderAttrib *attrib = node()->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); return ta->get_on_texture(stage); } - return NULL; + return nullptr; } /** @@ -3152,7 +3159,7 @@ get_texture_sampler(TextureStage *stage) const { nassertr_always(!is_empty(), SamplerState::get_default()); const RenderAttrib *attrib = node()->get_attrib(TextureAttrib::get_class_slot()); - nassertr_always(attrib != NULL, SamplerState::get_default()); + nassertr_always(attrib != nullptr, SamplerState::get_default()); const TextureAttrib *ta = DCAST(TextureAttrib, attrib); return ta->get_on_sampler(stage); @@ -3167,7 +3174,7 @@ set_shader(const Shader *sha, int priority) { const RenderAttrib *attrib = node()->get_attrib(ShaderAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { priority = max(priority, node()->get_state()->get_override(ShaderAttrib::get_class_slot())); const ShaderAttrib *sa = DCAST(ShaderAttrib, attrib); @@ -3184,7 +3191,7 @@ set_shader(const Shader *sha, int priority) { */ void NodePath:: set_shader_off(int priority) { - set_shader(NULL, priority); + set_shader(nullptr, priority); } /** @@ -3196,7 +3203,7 @@ set_shader_auto(int priority) { const RenderAttrib *attrib = node()->get_attrib(ShaderAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { priority = max(priority, node()->get_state()->get_override(ShaderAttrib::get_class_slot())); const ShaderAttrib *sa = DCAST(ShaderAttrib, attrib); @@ -3217,7 +3224,7 @@ set_shader_auto(BitMask32 shader_switch, int priority) { const RenderAttrib *attrib = node()->get_attrib(ShaderAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { priority = max(priority, node()->get_state()->get_override(ShaderAttrib::get_class_slot())); const ShaderAttrib *sa = DCAST(ShaderAttrib, attrib); @@ -3237,7 +3244,7 @@ clear_shader() { const RenderAttrib *attrib = node()->get_attrib(ShaderAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const ShaderAttrib *sa = DCAST(ShaderAttrib, attrib); node()->set_attrib(sa->clear_shader()); } @@ -3248,14 +3255,14 @@ clear_shader() { */ const Shader *NodePath:: get_shader() const { - nassertr_always(!is_empty(), NULL); + nassertr_always(!is_empty(), nullptr); const RenderAttrib *attrib = node()->get_attrib(ShaderAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const ShaderAttrib *sa = DCAST(ShaderAttrib, attrib); return sa->get_shader(); } - return NULL; + return nullptr; } /** @@ -3325,7 +3332,7 @@ get_instance_count() const { const RenderAttrib *attrib = node()->get_attrib(ShaderAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const ShaderAttrib *sa = DCAST(ShaderAttrib, attrib); return sa->get_instance_count(); } @@ -3342,7 +3349,7 @@ clear_shader_input(CPT_InternalName id) { const RenderAttrib *attrib = node()->get_attrib(ShaderAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const ShaderAttrib *sa = DCAST(ShaderAttrib, attrib); node()->set_attrib(sa->clear_shader_input(id)); } @@ -3359,7 +3366,7 @@ set_instance_count(int instance_count) { const RenderAttrib *attrib = node()->get_attrib(ShaderAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const ShaderAttrib *sa = DCAST(ShaderAttrib, attrib); node()->set_attrib(sa->set_instance_count(instance_count)); } else { @@ -3379,7 +3386,7 @@ set_tex_transform(TextureStage *stage, const TransformState *transform) { const RenderAttrib *attrib = node()->get_attrib(TexMatrixAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TexMatrixAttrib *tma = DCAST(TexMatrixAttrib, attrib); // Modify the existing TexMatrixAttrib to add the indicated stage. @@ -3409,7 +3416,7 @@ clear_tex_transform(TextureStage *stage) { const RenderAttrib *attrib = node()->get_attrib(TexMatrixAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { CPT(TexMatrixAttrib) tma = DCAST(TexMatrixAttrib, attrib); tma = DCAST(TexMatrixAttrib, tma->remove_stage(stage)); @@ -3432,7 +3439,7 @@ has_tex_transform(TextureStage *stage) const { const RenderAttrib *attrib = node()->get_attrib(TexMatrixAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TexMatrixAttrib *tma = DCAST(TexMatrixAttrib, attrib); return tma->has_stage(stage); } @@ -3447,11 +3454,11 @@ has_tex_transform(TextureStage *stage) const { */ CPT(TransformState) NodePath:: get_tex_transform(TextureStage *stage) const { - nassertr_always(!is_empty(), NULL); + nassertr_always(!is_empty(), nullptr); const RenderAttrib *attrib = node()->get_attrib(TexMatrixAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TexMatrixAttrib *tma = DCAST(TexMatrixAttrib, attrib); return tma->get_transform(stage); } @@ -3471,7 +3478,7 @@ set_tex_transform(const NodePath &other, TextureStage *stage, const TransformSta CPT(RenderState) state = get_state(other); const RenderAttrib *attrib = state->get_attrib(TexMatrixAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TexMatrixAttrib *tma = DCAST(TexMatrixAttrib, attrib); // Modify the existing TexMatrixAttrib to add the indicated stage. @@ -3507,7 +3514,7 @@ get_tex_transform(const NodePath &other, TextureStage *stage) const { CPT(RenderState) state = get_state(other); const RenderAttrib *attrib = state->get_attrib(TexMatrixAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TexMatrixAttrib *tma = DCAST(TexMatrixAttrib, attrib); return tma->get_transform(stage); } @@ -3528,7 +3535,7 @@ set_tex_gen(TextureStage *stage, RenderAttrib::TexGenMode mode, int priority) { CPT(TexGenAttrib) tga; - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { priority = max(priority, node()->get_state()->get_override(TextureAttrib::get_class_slot())); tga = DCAST(TexGenAttrib, attrib); @@ -3555,7 +3562,7 @@ set_tex_gen(TextureStage *stage, RenderAttrib::TexGenMode mode, CPT(TexGenAttrib) tga; - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { priority = max(priority, node()->get_state()->get_override(TextureAttrib::get_class_slot())); tga = DCAST(TexGenAttrib, attrib); @@ -3587,7 +3594,7 @@ clear_tex_gen(TextureStage *stage) { const RenderAttrib *attrib = node()->get_attrib(TexGenAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { CPT(TexGenAttrib) tga = DCAST(TexGenAttrib, attrib); tga = DCAST(TexGenAttrib, tga->remove_stage(stage)); @@ -3610,7 +3617,7 @@ has_tex_gen(TextureStage *stage) const { const RenderAttrib *attrib = node()->get_attrib(TexGenAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TexGenAttrib *tga = DCAST(TexGenAttrib, attrib); return tga->has_stage(stage); } @@ -3628,7 +3635,7 @@ get_tex_gen(TextureStage *stage) const { const RenderAttrib *attrib = node()->get_attrib(TexGenAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TexGenAttrib *tga = DCAST(TexGenAttrib, attrib); return tga->get_mode(stage); } @@ -3657,7 +3664,7 @@ set_tex_projector(TextureStage *stage, const NodePath &from, const NodePath &to, CPT(TexProjectorEffect) tpe; - if (effect != (const RenderEffect *)NULL) { + if (effect != nullptr) { tpe = DCAST(TexProjectorEffect, effect); } else { @@ -3676,7 +3683,7 @@ clear_tex_projector(TextureStage *stage) { const RenderEffect *effect = node()->get_effect(TexProjectorEffect::get_class_type()); - if (effect != (const RenderEffect *)NULL) { + if (effect != nullptr) { CPT(TexProjectorEffect) tpe = DCAST(TexProjectorEffect, effect); tpe = DCAST(TexProjectorEffect, tpe->remove_stage(stage)); @@ -3708,7 +3715,7 @@ has_tex_projector(TextureStage *stage) const { const RenderEffect *effect = node()->get_effect(TexProjectorEffect::get_class_type()); - if (effect != (const RenderEffect *)NULL) { + if (effect != nullptr) { const TexProjectorEffect *tpe = DCAST(TexProjectorEffect, effect); return tpe->has_stage(stage); } @@ -3727,7 +3734,7 @@ get_tex_projector_from(TextureStage *stage) const { const RenderEffect *effect = node()->get_effect(TexProjectorEffect::get_class_type()); - if (effect != (const RenderEffect *)NULL) { + if (effect != nullptr) { const TexProjectorEffect *tpe = DCAST(TexProjectorEffect, effect); return tpe->get_from(stage); } @@ -3746,7 +3753,7 @@ get_tex_projector_to(TextureStage *stage) const { const RenderEffect *effect = node()->get_effect(TexProjectorEffect::get_class_type()); - if (effect != (const RenderEffect *)NULL) { + if (effect != nullptr) { const TexProjectorEffect *tpe = DCAST(TexProjectorEffect, effect); return tpe->get_to(stage); } @@ -3885,7 +3892,7 @@ find_all_texcoords(const string &name) const { */ Texture *NodePath:: find_texture(const string &name) const { - nassertr_always(!is_empty(), NULL); + nassertr_always(!is_empty(), nullptr); GlobPattern glob(name); return r_find_texture(node(), get_net_state(), glob); } @@ -3897,7 +3904,7 @@ find_texture(const string &name) const { */ Texture *NodePath:: find_texture(TextureStage *stage) const { - nassertr_always(!is_empty(), NULL); + nassertr_always(!is_empty(), nullptr); return r_find_texture(node(), stage); } @@ -3967,7 +3974,7 @@ find_all_textures(TextureStage *stage) const { */ TextureStage *NodePath:: find_texture_stage(const string &name) const { - nassertr_always(!is_empty(), NULL); + nassertr_always(!is_empty(), nullptr); GlobPattern glob(name); return r_find_texture_stage(node(), get_net_state(), glob); } @@ -4034,7 +4041,7 @@ find_all_texture_stages(const string &name) const { */ Material *NodePath:: find_material(const string &name) const { - nassertr_always(!is_empty(), NULL); + nassertr_always(!is_empty(), nullptr); GlobPattern glob(name); return r_find_material(node(), get_net_state(), glob); } @@ -4089,7 +4096,7 @@ find_all_materials(const string &name) const { void NodePath:: set_material(Material *mat, int priority) { nassertv_always(!is_empty()); - nassertv(mat != NULL); + nassertv(mat != nullptr); node()->set_attrib(MaterialAttrib::make(mat), priority); } @@ -4124,7 +4131,7 @@ has_material() const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(MaterialAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const MaterialAttrib *ma = DCAST(MaterialAttrib, attrib); return !ma->is_off(); } @@ -4142,15 +4149,15 @@ has_material() const { */ PT(Material) NodePath:: get_material() const { - nassertr_always(!is_empty(), NULL); + nassertr_always(!is_empty(), nullptr); const RenderAttrib *attrib = node()->get_attrib(MaterialAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const MaterialAttrib *ma = DCAST(MaterialAttrib, attrib); return ma->get_material(); } - return NULL; + return nullptr; } /** @@ -4197,7 +4204,7 @@ has_fog() const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(FogAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const FogAttrib *fa = DCAST(FogAttrib, attrib); return !fa->is_off(); } @@ -4216,7 +4223,7 @@ has_fog_off() const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(FogAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const FogAttrib *fa = DCAST(FogAttrib, attrib); return fa->is_off(); } @@ -4232,15 +4239,15 @@ has_fog_off() const { */ Fog *NodePath:: get_fog() const { - nassertr_always(!is_empty(), NULL); + nassertr_always(!is_empty(), nullptr); const RenderAttrib *attrib = node()->get_attrib(FogAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const FogAttrib *fa = DCAST(FogAttrib, attrib); return fa->get_fog(); } - return NULL; + return nullptr; } /** @@ -4355,7 +4362,7 @@ get_render_mode() const { nassertr_always(!is_empty(), RenderModeAttrib::M_unchanged); const RenderAttrib *attrib = node()->get_attrib(RenderModeAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const RenderModeAttrib *ta = DCAST(RenderModeAttrib, attrib); return ta->get_mode(); } @@ -4372,7 +4379,7 @@ get_render_mode_thickness() const { nassertr_always(!is_empty(), 0.0f); const RenderAttrib *attrib = node()->get_attrib(RenderModeAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const RenderModeAttrib *ta = DCAST(RenderModeAttrib, attrib); return ta->get_thickness(); } @@ -4389,7 +4396,7 @@ get_render_mode_perspective() const { nassertr_always(!is_empty(), 0.0f); const RenderAttrib *attrib = node()->get_attrib(RenderModeAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const RenderModeAttrib *ta = DCAST(RenderModeAttrib, attrib); return ta->get_perspective(); } @@ -4450,7 +4457,7 @@ get_two_sided() const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(CullFaceAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const CullFaceAttrib *cfa = DCAST(CullFaceAttrib, attrib); return (cfa->get_actual_mode() == CullFaceAttrib::M_cull_none); } @@ -4507,7 +4514,7 @@ get_depth_test() const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(DepthTestAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const DepthTestAttrib *dta = DCAST(DepthTestAttrib, attrib); return (dta->get_mode() != DepthTestAttrib::M_none); } @@ -4564,7 +4571,7 @@ get_depth_write() const { nassertr_always(!is_empty(), false); const RenderAttrib *attrib = node()->get_attrib(DepthWriteAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const DepthWriteAttrib *dta = DCAST(DepthWriteAttrib, attrib); return (dta->get_mode() != DepthWriteAttrib::M_off); } @@ -4618,7 +4625,7 @@ get_depth_offset() const { nassertr_always(!is_empty(), 0); const RenderAttrib *attrib = node()->get_attrib(DepthOffsetAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const DepthOffsetAttrib *doa = DCAST(DepthOffsetAttrib, attrib); return doa->get_offset(); } @@ -4852,7 +4859,7 @@ get_transparency() const { nassertr_always(!is_empty(), TransparencyAttrib::M_none); const RenderAttrib *attrib = node()->get_attrib(TransparencyAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TransparencyAttrib *ta = DCAST(TransparencyAttrib, attrib); return ta->get_mode(); } @@ -4908,7 +4915,7 @@ get_logic_op() const { nassertr_always(!is_empty(), LogicOpAttrib::O_none); const RenderAttrib *attrib = node()->get_attrib(LogicOpAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const LogicOpAttrib *ta = DCAST(LogicOpAttrib, attrib); return ta->get_operation(); } @@ -4957,7 +4964,7 @@ get_antialias() const { nassertr_always(!is_empty(), AntialiasAttrib::M_none); const RenderAttrib *attrib = node()->get_attrib(AntialiasAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const AntialiasAttrib *ta = DCAST(AntialiasAttrib, attrib); return ta->get_mode(); } @@ -4996,7 +5003,7 @@ set_audio_volume(PN_stdfloat volume, int priority) { const RenderAttrib *attrib = node()->get_attrib(AudioVolumeAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { priority = max(priority, node()->get_state()->get_override(AudioVolumeAttrib::get_class_slot())); CPT(AudioVolumeAttrib) ava = DCAST(AudioVolumeAttrib, attrib); @@ -5034,7 +5041,7 @@ PN_stdfloat NodePath:: get_audio_volume() const { const RenderAttrib *attrib = node()->get_attrib(AudioVolumeAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const AudioVolumeAttrib *ava = DCAST(AudioVolumeAttrib, attrib); return ava->get_volume(); } @@ -5050,9 +5057,9 @@ PN_stdfloat NodePath:: get_net_audio_volume() const { CPT(RenderState) net_state = get_net_state(); const RenderAttrib *attrib = net_state->get_attrib(AudioVolumeAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const AudioVolumeAttrib *ava = DCAST(AudioVolumeAttrib, attrib); - if (ava != (const AudioVolumeAttrib *)NULL) { + if (ava != nullptr) { return ava->get_volume(); } } @@ -5071,7 +5078,7 @@ get_hidden_ancestor(DrawMask camera_mask, Thread *current_thread) const { NodePathComponent *comp; for (comp = _head; - comp != (NodePathComponent *)NULL; + comp != nullptr; comp = comp->get_next(pipeline_stage, current_thread)) { PandaNode *node = comp->get_node(); if (node->is_overall_hidden() || @@ -5142,11 +5149,11 @@ unstash_all(Thread *current_thread) { NodePath NodePath:: get_stashed_ancestor(Thread *current_thread) const { NodePathComponent *comp = _head; - if (comp != (NodePathComponent *)NULL) { + if (comp != nullptr) { int pipeline_stage = current_thread->get_pipeline_stage(); NodePathComponent *next = comp->get_next(pipeline_stage, current_thread); - while (next != (NodePathComponent *)NULL) { + while (next != nullptr) { PandaNode *node = comp->get_node(); PandaNode *parent_node = next->get_node(); @@ -5164,6 +5171,55 @@ get_stashed_ancestor(Thread *current_thread) const { return not_found(); } +/** + * Returns true if the two paths are equivalent; that is, if they contain the + * same list of nodes in the same order. + */ +bool NodePath:: +operator == (const WeakNodePath &other) const { + return _head == other._head; +} + +/** + * Returns true if the two paths are not equivalent. + */ +bool NodePath:: +operator != (const WeakNodePath &other) const { + return _head != other._head; +} + +/** + * Returns true if this NodePath sorts before the other one, false otherwise. + * The sorting order of two nonequivalent NodePaths is consistent but + * undefined, and is useful only for storing NodePaths in a sorted container + * like an STL set. + */ +bool NodePath:: +operator < (const WeakNodePath &other) const { + return _head < other._head; +} + +/** + * Returns a number less than zero if this NodePath sorts before the other + * one, greater than zero if it sorts after, or zero if they are equivalent. + * + * Two NodePaths are considered equivalent if they consist of exactly the same + * list of nodes in the same order. Otherwise, they are different; different + * NodePaths will be ranked in a consistent but undefined ordering; the + * ordering is useful only for placing the NodePaths in a sorted container + * like an STL set. + */ +int NodePath:: +compare_to(const WeakNodePath &other) const { + // Nowadays, the NodePathComponents at the head are pointerwise equivalent + // if and only if the NodePaths are equivalent. So we only have to compare + // pointers. + if (_head != other._head) { + return _head < other._head ? -1 : 1; + } + return 0; +} + /** * Returns true if all of the nodes described in the NodePath are connected, * or false otherwise. @@ -5187,19 +5243,19 @@ verify_complete(Thread *current_thread) const { PStatTimer timer(_verify_complete_pcollector); const NodePathComponent *comp = _head; - nassertr(comp != (const NodePathComponent *)NULL, false); + nassertr(comp != nullptr, false); int pipeline_stage = current_thread->get_pipeline_stage(); PandaNode *node = comp->get_node(); - nassertr(node != (const PandaNode *)NULL, false); + nassertr(node != nullptr, false); int length = comp->get_length(pipeline_stage, current_thread); comp = comp->get_next(pipeline_stage, current_thread); length--; - while (comp != (const NodePathComponent *)NULL) { + while (comp != nullptr) { PandaNode *next_node = comp->get_node(); - nassertr(next_node != (const PandaNode *)NULL, false); + nassertr(next_node != nullptr, false); if (node->find_parent(next_node) < 0) { pgraph_cat.warning() @@ -5362,7 +5418,7 @@ calc_tight_bounds(LPoint3 &min_point, LPoint3 &max_point, bool found_any = false; node()->calc_tight_bounds(min_point, max_point, found_any, - MOVE(transform), current_thread); + move(transform), current_thread); return found_any; } @@ -5604,7 +5660,7 @@ encode_to_bam_stream(vector_uchar &data, BamWriter *writer) const { DatagramBuffer buffer; BamWriter local_writer; bool used_local_writer = false; - if (writer == NULL) { + if (writer == nullptr) { // Create our own writer. if (!buffer.write_header(_bam_header)) { @@ -5633,20 +5689,20 @@ encode_to_bam_stream(vector_uchar &data, BamWriter *writer) const { dg.add_int32(num_nodes); if (!buffer.put_datagram(dg)) { - writer->set_target(NULL); + writer->set_target(nullptr); return false; } // Now write the nodes, one at a time. for (int i = 0; i < num_nodes; ++i) { PandaNode *node = get_node(num_nodes - i - 1); - nassertr(node != NULL, false); + nassertr(node != nullptr, false); if (!writer->write_object(node)) { - writer->set_target(NULL); + writer->set_target(nullptr); return false; } } - writer->set_target(NULL); + writer->set_target(nullptr); buffer.swap_data(data); return true; @@ -5663,7 +5719,7 @@ decode_from_bam_stream(vector_uchar data, BamReader *reader) { DatagramBuffer buffer(move(data)); BamReader local_reader; - if (reader == NULL) { + if (reader == nullptr) { // Create a local reader. string head; @@ -5698,14 +5754,14 @@ decode_from_bam_stream(vector_uchar data, BamReader *reader) { for (int i = 0; i < num_nodes; ++i) { TypedWritable *object = reader->read_object(); - if (object == (TypedWritable *)NULL || + if (object == nullptr || !object->is_of_type(PandaNode::get_class_type())) { - reader->set_source(NULL); + reader->set_source(nullptr); return NodePath::fail(); } if (!reader->resolve()) { - reader->set_source(NULL); + reader->set_source(nullptr); return NodePath::fail(); } @@ -5714,7 +5770,7 @@ decode_from_bam_stream(vector_uchar data, BamReader *reader) { } } - reader->set_source(NULL); + reader->set_source(nullptr); return result; } @@ -5730,7 +5786,7 @@ decode_from_bam_stream(vector_uchar data, BamReader *reader) { NodePathComponent *NodePath:: find_common_ancestor(const NodePath &a, const NodePath &b, int &a_count, int &b_count, Thread *current_thread) { - nassertr(!a.is_empty() && !b.is_empty(), NULL); + nassertr(!a.is_empty() && !b.is_empty(), nullptr); NodePathComponent *ac = a._head; NodePathComponent *bc = b._head; a_count = 0; @@ -5740,12 +5796,12 @@ find_common_ancestor(const NodePath &a, const NodePath &b, // Shorten up the longer one until they are the same length. while (ac->get_length(pipeline_stage, current_thread) > bc->get_length(pipeline_stage, current_thread)) { - nassertr(ac != (NodePathComponent *)NULL, NULL); + nassertr(ac != nullptr, nullptr); ac = ac->get_next(pipeline_stage, current_thread); a_count++; } while (bc->get_length(pipeline_stage, current_thread) > ac->get_length(pipeline_stage, current_thread)) { - nassertr(bc != (NodePathComponent *)NULL, NULL); + nassertr(bc != nullptr, nullptr); bc = bc->get_next(pipeline_stage, current_thread); b_count++; } @@ -5753,8 +5809,8 @@ find_common_ancestor(const NodePath &a, const NodePath &b, // Now shorten them both up until we reach the same component. while (ac != bc) { // These shouldn't go to NULL unless they both go there together. - nassertr(ac != (NodePathComponent *)NULL, NULL); - nassertr(bc != (NodePathComponent *)NULL, NULL); + nassertr(ac != nullptr, nullptr); + nassertr(bc != nullptr, nullptr); ac = ac->get_next(pipeline_stage, current_thread); a_count++; bc = bc->get_next(pipeline_stage, current_thread); @@ -5770,7 +5826,7 @@ find_common_ancestor(const NodePath &a, const NodePath &b, */ CPT(RenderState) NodePath:: r_get_net_state(NodePathComponent *comp, Thread *current_thread) const { - if (comp == (NodePathComponent *)NULL) { + if (comp == nullptr) { return RenderState::make_empty(); } else { CPT(RenderState) state = comp->get_node()->get_state(current_thread); @@ -5787,7 +5843,7 @@ r_get_net_state(NodePathComponent *comp, Thread *current_thread) const { CPT(RenderState) NodePath:: r_get_partial_state(NodePathComponent *comp, int n, Thread *current_thread) const { - if (n == 0 || comp == (NodePathComponent *)NULL) { + if (n == 0 || comp == nullptr) { return RenderState::make_empty(); } else { CPT(RenderState) state = comp->get_node()->get_state(current_thread); @@ -5802,7 +5858,7 @@ r_get_partial_state(NodePathComponent *comp, int n, */ CPT(TransformState) NodePath:: r_get_net_transform(NodePathComponent *comp, Thread *current_thread) const { - if (comp == (NodePathComponent *)NULL) { + if (comp == nullptr) { return TransformState::make_identity(); } else { PandaNode *node = comp->get_node(); @@ -5835,18 +5891,18 @@ r_get_net_transform(NodePathComponent *comp, Thread *current_thread) const { CPT(TransformState) NodePath:: r_get_partial_transform(NodePathComponent *comp, int n, Thread *current_thread) const { - if (n == 0 || comp == (NodePathComponent *)NULL) { + if (n == 0 || comp == nullptr) { return TransformState::make_identity(); } else { PandaNode *node = comp->get_node(); PandaNode::CDReader node_cdata(node->_cycler, current_thread); if (node_cdata->_effects->has_adjust_transform()) { - return NULL; + return nullptr; } int pipeline_stage = current_thread->get_pipeline_stage(); CPT(TransformState) partial = r_get_partial_transform(comp->get_next(pipeline_stage, current_thread), n - 1, current_thread); - if (partial == (const TransformState *)NULL) { - return NULL; + if (partial == nullptr) { + return nullptr; } if (node_cdata->_transform->is_identity()) { return partial; @@ -5862,7 +5918,7 @@ r_get_partial_transform(NodePathComponent *comp, int n, */ CPT(TransformState) NodePath:: r_get_net_prev_transform(NodePathComponent *comp, Thread *current_thread) const { - if (comp == (NodePathComponent *)NULL) { + if (comp == nullptr) { return TransformState::make_identity(); } else { CPT(TransformState) transform = comp->get_node()->get_prev_transform(current_thread); @@ -5878,7 +5934,7 @@ r_get_net_prev_transform(NodePathComponent *comp, Thread *current_thread) const */ CPT(TransformState) NodePath:: r_get_partial_prev_transform(NodePathComponent *comp, int n, Thread *current_thread) const { - if (n == 0 || comp == (NodePathComponent *)NULL) { + if (n == 0 || comp == nullptr) { return TransformState::make_identity(); } else { CPT(TransformState) transform = comp->get_node()->get_prev_transform(current_thread); @@ -5939,9 +5995,9 @@ find_matches(NodePathCollection &result, FindApproxLevelEntry *level, int num_levels_remaining = _max_search_depth; - FindApproxLevelEntry *deleted_entries = NULL; + FindApproxLevelEntry *deleted_entries = nullptr; - while (num_levels_remaining > 0 && level != NULL) { + while (num_levels_remaining > 0 && level != nullptr) { if (pgraph_cat.is_spam()) { pgraph_cat.spam() << "find_matches pass: " << result << ", " @@ -5951,27 +6007,27 @@ find_matches(NodePathCollection &result, FindApproxLevelEntry *level, num_levels_remaining--; - FindApproxLevelEntry *next_level = NULL; + FindApproxLevelEntry *next_level = nullptr; // For each node in the current level, build up the set of possible // matches in the next level. FindApproxLevelEntry *entry = level; - while (entry != (FindApproxLevelEntry *)NULL) { + while (entry != nullptr) { if (entry->consider_node(result, next_level, max_matches, 0)) { // If we found the requisite number of matches, we can stop. Delete // all remaining entries and return immediately. - while (entry != (FindApproxLevelEntry *)NULL) { + while (entry != nullptr) { FindApproxLevelEntry *next = entry->_next; delete entry; entry = next; } - while (next_level != (FindApproxLevelEntry *)NULL) { + while (next_level != nullptr) { FindApproxLevelEntry *next = next_level->_next; delete next_level; next_level = next; } - while (deleted_entries != (FindApproxLevelEntry *)NULL) { + while (deleted_entries != nullptr) { FindApproxLevelEntry *next = deleted_entries->_next; delete deleted_entries; deleted_entries = next; @@ -5992,7 +6048,7 @@ find_matches(NodePathCollection &result, FindApproxLevelEntry *level, // Make sure the remaining entries from this level are added to the delete // chain. - while (entry != (FindApproxLevelEntry *)NULL) { + while (entry != nullptr) { FindApproxLevelEntry *next = entry->_next; entry->_next = deleted_entries; deleted_entries = entry; @@ -6004,7 +6060,7 @@ find_matches(NodePathCollection &result, FindApproxLevelEntry *level, } // Now it's safe to delete all entries on the delete chain. - while (deleted_entries != (FindApproxLevelEntry *)NULL) { + while (deleted_entries != nullptr) { FindApproxLevelEntry *next = deleted_entries->_next; delete deleted_entries; deleted_entries = next; @@ -6181,7 +6237,7 @@ r_find_texture(PandaNode *node, const RenderState *state, const GlobPattern &glob) const { if (node->is_geom_node()) { GeomNode *gnode; - DCAST_INTO_R(gnode, node, NULL); + DCAST_INTO_R(gnode, node, nullptr); int num_geoms = gnode->get_num_geoms(); for (int i = 0; i < num_geoms; i++) { @@ -6191,11 +6247,11 @@ r_find_texture(PandaNode *node, const RenderState *state, // Look for a TextureAttrib on the state. const RenderAttrib *attrib = geom_state->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); for (int i = 0; i < ta->get_num_on_stages(); i++) { Texture *texture = ta->get_on_texture(ta->get_on_stage(i)); - if (texture != (Texture *)NULL) { + if (texture != nullptr) { if (glob.matches(texture->get_name())) { return texture; } @@ -6213,12 +6269,12 @@ r_find_texture(PandaNode *node, const RenderState *state, CPT(RenderState) next_state = state->compose(child->get_state()); Texture *result = r_find_texture(child, next_state, glob); - if (result != (Texture *)NULL) { + if (result != nullptr) { return result; } } - return NULL; + return nullptr; } /** @@ -6239,11 +6295,11 @@ r_find_all_textures(PandaNode *node, const RenderState *state, // Look for a TextureAttrib on the state. const RenderAttrib *attrib = geom_state->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); for (int i = 0; i < ta->get_num_on_stages(); i++) { Texture *texture = ta->get_on_texture(ta->get_on_stage(i)); - if (texture != (Texture *)NULL) { + if (texture != nullptr) { textures.insert(texture); } } @@ -6269,7 +6325,7 @@ r_find_texture(PandaNode *node, TextureStage *stage) const { // Look for a TextureAttrib on the node. const RenderAttrib *attrib = node->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); if (ta->has_on_stage(stage)) { return ta->get_on_texture(stage); @@ -6278,7 +6334,7 @@ r_find_texture(PandaNode *node, TextureStage *stage) const { if (node->is_geom_node()) { GeomNode *gnode; - DCAST_INTO_R(gnode, node, NULL); + DCAST_INTO_R(gnode, node, nullptr); int num_geoms = gnode->get_num_geoms(); for (int i = 0; i < num_geoms; i++) { @@ -6287,7 +6343,7 @@ r_find_texture(PandaNode *node, TextureStage *stage) const { // Look for a TextureAttrib on the state. const RenderAttrib *attrib = geom_state->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); if (ta->has_on_stage(stage)) { return ta->get_on_texture(stage); @@ -6303,12 +6359,12 @@ r_find_texture(PandaNode *node, TextureStage *stage) const { PandaNode *child = cr.get_child(i); Texture *result = r_find_texture(child, stage); - if (result != (Texture *)NULL) { + if (result != nullptr) { return result; } } - return NULL; + return nullptr; } /** @@ -6320,7 +6376,7 @@ r_find_all_textures(PandaNode *node, TextureStage *stage, // Look for a TextureAttrib on the node. const RenderAttrib *attrib = node->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); if (ta->has_on_stage(stage)) { textures.insert(ta->get_on_texture(stage)); @@ -6338,7 +6394,7 @@ r_find_all_textures(PandaNode *node, TextureStage *stage, // Look for a TextureAttrib on the state. const RenderAttrib *attrib = geom_state->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); if (ta->has_on_stage(stage)) { textures.insert(ta->get_on_texture(stage)); @@ -6364,7 +6420,7 @@ r_find_texture_stage(PandaNode *node, const RenderState *state, const GlobPattern &glob) const { if (node->is_geom_node()) { GeomNode *gnode; - DCAST_INTO_R(gnode, node, NULL); + DCAST_INTO_R(gnode, node, nullptr); int num_geoms = gnode->get_num_geoms(); for (int i = 0; i < num_geoms; i++) { @@ -6374,11 +6430,11 @@ r_find_texture_stage(PandaNode *node, const RenderState *state, // Look for a TextureAttrib on the state. const RenderAttrib *attrib = geom_state->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); for (int i = 0; i < ta->get_num_on_stages(); i++) { TextureStage *texture_stage = ta->get_on_stage(i); - if (texture_stage != (TextureStage *)NULL) { + if (texture_stage != nullptr) { if (glob.matches(texture_stage->get_name())) { return texture_stage; } @@ -6396,12 +6452,12 @@ r_find_texture_stage(PandaNode *node, const RenderState *state, CPT(RenderState) next_state = state->compose(child->get_state()); TextureStage *result = r_find_texture_stage(child, next_state, glob); - if (result != (TextureStage *)NULL) { + if (result != nullptr) { return result; } } - return NULL; + return nullptr; } /** @@ -6422,11 +6478,11 @@ r_find_all_texture_stages(PandaNode *node, const RenderState *state, // Look for a TextureAttrib on the state. const RenderAttrib *attrib = geom_state->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); for (int i = 0; i < ta->get_num_on_stages(); i++) { TextureStage *texture_stage = ta->get_on_stage(i); - if (texture_stage != (TextureStage *)NULL) { + if (texture_stage != nullptr) { texture_stages.insert(texture_stage); } } @@ -6452,7 +6508,7 @@ r_unify_texture_stages(PandaNode *node, TextureStage *stage) { // Look for a TextureAttrib on the state. const RenderAttrib *attrib = node->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); CPT(RenderAttrib) new_attrib = ta->unify_texture_stages(stage); if (new_attrib != ta) { @@ -6471,7 +6527,7 @@ r_unify_texture_stages(PandaNode *node, TextureStage *stage) { // Look for a TextureAttrib on the state. const RenderAttrib *attrib = state->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); CPT(RenderAttrib) new_attrib = ta->unify_texture_stages(stage); if (new_attrib != ta) { @@ -6499,7 +6555,7 @@ r_find_material(PandaNode *node, const RenderState *state, const GlobPattern &glob) const { if (node->is_geom_node()) { GeomNode *gnode; - DCAST_INTO_R(gnode, node, NULL); + DCAST_INTO_R(gnode, node, nullptr); int num_geoms = gnode->get_num_geoms(); for (int i = 0; i < num_geoms; i++) { @@ -6509,11 +6565,11 @@ r_find_material(PandaNode *node, const RenderState *state, // Look for a MaterialAttrib on the state. const RenderAttrib *attrib = geom_state->get_attrib(MaterialAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const MaterialAttrib *ta = DCAST(MaterialAttrib, attrib); if (!ta->is_off()) { Material *material = ta->get_material(); - if (material != (Material *)NULL) { + if (material != nullptr) { if (glob.matches(material->get_name())) { return material; } @@ -6531,12 +6587,12 @@ r_find_material(PandaNode *node, const RenderState *state, CPT(RenderState) next_state = state->compose(child->get_state()); Material *result = r_find_material(child, next_state, glob); - if (result != (Material *)NULL) { + if (result != nullptr) { return result; } } - return NULL; + return nullptr; } /** @@ -6557,11 +6613,11 @@ r_find_all_materials(PandaNode *node, const RenderState *state, // Look for a MaterialAttrib on the state. const RenderAttrib *attrib = geom_state->get_attrib(MaterialAttrib::get_class_slot()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const MaterialAttrib *ta = DCAST(MaterialAttrib, attrib); if (!ta->is_off()) { Material *material = ta->get_material(); - if (material != (Material *)NULL) { + if (material != nullptr) { materials.insert(material); } } @@ -6588,9 +6644,9 @@ write_datagram(BamWriter *manager, Datagram &dg) const { PandaNode *root = DCAST(PandaNode, manager->get_root_node()); // We have no root node to measure from. - if (root == (PandaNode *)NULL || root == node()) { + if (root == nullptr || root == node()) { manager->write_pointer(dg, node()); - manager->write_pointer(dg, NULL); + manager->write_pointer(dg, nullptr); return; } @@ -6600,7 +6656,7 @@ write_datagram(BamWriter *manager, Datagram &dg) const { // Record the chain of nodes from the root to this node. pvector path; NodePathComponent *comp = _head; - while (comp != NULL) { + while (comp != nullptr) { PandaNode *node = comp->get_node(); path.push_back(node); @@ -6611,10 +6667,10 @@ write_datagram(BamWriter *manager, Datagram &dg) const { comp = comp->get_next(pipeline_stage, current_thread); } - if (comp == (NodePathComponent *)NULL) { + if (comp == nullptr) { // We did not encounter the root node. Not much we can do. manager->write_pointer(dg, node()); - manager->write_pointer(dg, NULL); + manager->write_pointer(dg, nullptr); return; } @@ -6622,7 +6678,7 @@ write_datagram(BamWriter *manager, Datagram &dg) const { for (int i = path.size() - 1; i >= 0; --i) { manager->write_pointer(dg, path[i]); } - manager->write_pointer(dg, NULL); + manager->write_pointer(dg, nullptr); } /** @@ -6635,7 +6691,7 @@ complete_pointers(TypedWritable **p_list, BamReader *manager) { PT(PandaNode) node = DCAST(PandaNode, p_list[pi++]); if (node.is_null()) { // An empty NodePath. - _head = (NodePathComponent *)NULL; + _head = nullptr; return pi; } @@ -6652,7 +6708,7 @@ complete_pointers(TypedWritable **p_list, BamReader *manager) { } // Build up the chain of NodePathComponents leading up to this node. - while (p_list[pi] != NULL) { + while (p_list[pi] != nullptr) { PT(PandaNode) node = DCAST(PandaNode, p_list[pi++]); LightReMutexHolder holder(node->_paths_lock); diff --git a/panda/src/pgraph/nodePath.h b/panda/src/pgraph/nodePath.h index c5a3902c32..cf159972c5 100644 --- a/panda/src/pgraph/nodePath.h +++ b/panda/src/pgraph/nodePath.h @@ -63,6 +63,7 @@ class SamplerState; class Shader; class ShaderBuffer; class ShaderInput; +class WeakNodePath; // // A NodePath is the fundamental unit of high-level interaction with the scene @@ -169,20 +170,19 @@ PUBLISHED: }; INLINE NodePath(); - INLINE explicit NodePath(const string &top_node_name, Thread *current_thread = Thread::get_current_thread()); + INLINE explicit NodePath(const std::string &top_node_name, Thread *current_thread = Thread::get_current_thread()); INLINE explicit NodePath(PandaNode *node, Thread *current_thread = Thread::get_current_thread()); INLINE static NodePath any_path(PandaNode *node, Thread *current_thread = Thread::get_current_thread()); explicit NodePath(const NodePath &parent, PandaNode *child_node, Thread *current_thread = Thread::get_current_thread()); INLINE NodePath(const NodePath ©); - INLINE void operator = (const NodePath ©); - INLINE void clear(); + INLINE NodePath(NodePath &&from) noexcept; -#ifdef USE_MOVE_SEMANTICS - INLINE NodePath(NodePath &&from) NOEXCEPT; - INLINE void operator = (NodePath &&from) NOEXCEPT; -#endif + INLINE void operator = (const NodePath ©); + INLINE void operator = (NodePath &&from) noexcept; + + INLINE void clear(); EXTENSION(NodePath __copy__() const); EXTENSION(PyObject *__deepcopy__(PyObject *self, PyObject *memo) const); @@ -244,9 +244,9 @@ PUBLISHED: MAKE_PROPERTY2(parent, has_parent, get_parent); MAKE_PROPERTY(sort, get_sort); - NodePath find(const string &path) const; + NodePath find(const std::string &path) const; NodePath find_path_to(PandaNode *node) const; - NodePathCollection find_all_matches(const string &path) const; + NodePathCollection find_all_matches(const std::string &path) const; NodePathCollection find_all_paths_to(PandaNode *node) const; // Methods that actually move nodes around in the scene graph. The optional @@ -262,26 +262,26 @@ PUBLISHED: Thread *current_thread = Thread::get_current_thread()); NodePath instance_to(const NodePath &other, int sort = 0, Thread *current_thread = Thread::get_current_thread()) const; - NodePath instance_under_node(const NodePath &other, const string &name, + NodePath instance_under_node(const NodePath &other, const std::string &name, int sort = 0, Thread *current_thread = Thread::get_current_thread()) const; NodePath copy_to(const NodePath &other, int sort = 0, Thread *current_thread = Thread::get_current_thread()) const; NodePath attach_new_node(PandaNode *node, int sort = 0, Thread *current_thread = Thread::get_current_thread()) const; - INLINE NodePath attach_new_node(const string &name, int sort = 0, + INLINE NodePath attach_new_node(const std::string &name, int sort = 0, Thread *current_thread = Thread::get_current_thread()) const; void remove_node(Thread *current_thread = Thread::get_current_thread()); void detach_node(Thread *current_thread = Thread::get_current_thread()); // Handy ways to look at what's there, and other miscellaneous operations. - void output(ostream &out) const; + void output(std::ostream &out) const; INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level = 0) const; + INLINE void ls(std::ostream &out, int indent_level = 0) const; INLINE void reverse_ls() const; - int reverse_ls(ostream &out, int indent_level = 0) const; + int reverse_ls(std::ostream &out, int indent_level = 0) const; // Aggregate transform and state information. const RenderState *get_state(Thread *current_thread = Thread::get_current_thread()) const; @@ -600,10 +600,10 @@ PUBLISHED: void clear_occluder(const NodePath &occluder); bool has_occluder(const NodePath &occluder) const; - void set_bin(const string &bin_name, int draw_order, int priority = 0); + void set_bin(const std::string &bin_name, int draw_order, int priority = 0); void clear_bin(); bool has_bin() const; - string get_bin_name() const; + std::string get_bin_name() const; int get_bin_draw_order() const; void set_texture(Texture *tex, int priority = 0); @@ -743,28 +743,28 @@ PUBLISHED: void project_texture(TextureStage *stage, Texture *tex, const NodePath &projector); INLINE void clear_project_texture(TextureStage *stage); - INLINE bool has_texcoord(const string &texcoord_name) const; + INLINE bool has_texcoord(const std::string &texcoord_name) const; bool has_vertex_column(const InternalName *name) const; InternalNameCollection find_all_vertex_columns() const; - InternalNameCollection find_all_vertex_columns(const string &name) const; + InternalNameCollection find_all_vertex_columns(const std::string &name) const; InternalNameCollection find_all_texcoords() const; - InternalNameCollection find_all_texcoords(const string &name) const; + InternalNameCollection find_all_texcoords(const std::string &name) const; - Texture *find_texture(const string &name) const; + Texture *find_texture(const std::string &name) const; Texture *find_texture(TextureStage *stage) const; TextureCollection find_all_textures() const; - TextureCollection find_all_textures(const string &name) const; + TextureCollection find_all_textures(const std::string &name) const; TextureCollection find_all_textures(TextureStage *stage) const; - TextureStage *find_texture_stage(const string &name) const; + TextureStage *find_texture_stage(const std::string &name) const; TextureStageCollection find_all_texture_stages() const; - TextureStageCollection find_all_texture_stages(const string &name) const; + TextureStageCollection find_all_texture_stages(const std::string &name) const; void unify_texture_stages(TextureStage *stage); - Material *find_material(const string &name) const; + Material *find_material(const std::string &name) const; MaterialCollection find_all_materials() const; - MaterialCollection find_all_materials(const string &name) const; + MaterialCollection find_all_materials(const std::string &name) const; void set_material(Material *tex, int priority = 0); void set_material_off(int priority = 0); @@ -879,10 +879,15 @@ PUBLISHED: INLINE bool operator < (const NodePath &other) const; INLINE int compare_to(const NodePath &other) const; + bool operator == (const WeakNodePath &other) const; + bool operator != (const WeakNodePath &other) const; + bool operator < (const WeakNodePath &other) const; + int compare_to(const WeakNodePath &other) const; + // Miscellaneous bool verify_complete(Thread *current_thread = Thread::get_current_thread()) const; - void premunge_scene(GraphicsStateGuardianBase *gsg = NULL); + void premunge_scene(GraphicsStateGuardianBase *gsg = nullptr); void prepare_scene(GraphicsStateGuardianBase *gsg); void show_bounds(); @@ -890,7 +895,7 @@ PUBLISHED: void hide_bounds(); PT(BoundingVolume) get_bounds(Thread *current_thread = Thread::get_current_thread()) const; void force_recompute_bounds(); - void write_bounds(ostream &out) const; + void write_bounds(std::ostream &out) const; bool calc_tight_bounds(LPoint3 &min_point, LPoint3 &max_point, const NodePath &other = NodePath(), Thread *current_thread = Thread::get_current_thread()) const; @@ -905,14 +910,14 @@ PUBLISHED: void apply_texture_colors(); INLINE int clear_model_nodes(); - INLINE void set_tag(const string &key, const string &value); - INLINE string get_tag(const string &key) const; + INLINE void set_tag(const std::string &key, const std::string &value); + INLINE std::string get_tag(const std::string &key) const; INLINE void get_tag_keys(vector_string &keys) const; - INLINE bool has_tag(const string &key) const; - INLINE void clear_tag(const string &key); - INLINE string get_net_tag(const string &key) const; - INLINE bool has_net_tag(const string &key) const; - NodePath find_net_tag(const string &key) const; + INLINE bool has_tag(const std::string &key) const; + INLINE void clear_tag(const std::string &key); + INLINE std::string get_net_tag(const std::string &key) const; + INLINE bool has_net_tag(const std::string &key) const; + NodePath find_net_tag(const std::string &key) const; MAKE_MAP_PROPERTY(net_tags, has_net_tag, get_net_tag); @@ -935,12 +940,12 @@ PUBLISHED: INLINE void list_tags() const; - INLINE void set_name(const string &name); - INLINE string get_name() const; + INLINE void set_name(const std::string &name); + INLINE std::string get_name() const; MAKE_PROPERTY(name, get_name, set_name); BLOCKING bool write_bam_file(const Filename &filename) const; - BLOCKING bool write_bam_stream(ostream &out) const; + BLOCKING bool write_bam_stream(std::ostream &out) const; INLINE vector_uchar encode_to_bam_stream() const; bool encode_to_bam_stream(vector_uchar &data, BamWriter *writer = nullptr) const; @@ -966,7 +971,7 @@ private: int n, Thread *current_thread) const; void find_matches(NodePathCollection &result, - const string &approx_path_str, + const std::string &approx_path_str, int max_matches) const; void find_matches(NodePathCollection &result, FindApproxPath &approx_path, @@ -1042,7 +1047,7 @@ private: friend class CullTraverserData; }; -INLINE ostream &operator << (ostream &out, const NodePath &node_path); +INLINE std::ostream &operator << (std::ostream &out, const NodePath &node_path); #include "nodePath.I" diff --git a/panda/src/pgraph/nodePathCollection.cxx b/panda/src/pgraph/nodePathCollection.cxx index 40efb80192..545691d0fc 100644 --- a/panda/src/pgraph/nodePathCollection.cxx +++ b/panda/src/pgraph/nodePathCollection.cxx @@ -19,6 +19,9 @@ #include "colorAttrib.h" #include "indent.h" +using std::max; +using std::min; + /** * Adds a new NodePath to the collection. */ @@ -188,8 +191,8 @@ get_path(int index) const { * get_path(), but it may be a more convenient way to access it. */ NodePath NodePathCollection:: -operator [] (int index) const { - nassertr(index >= 0 && index < (int)_node_paths.size(), NodePath()); +operator [] (size_t index) const { + nassertr(index < _node_paths.size(), NodePath()); return _node_paths[index]; } @@ -198,7 +201,7 @@ operator [] (int index) const { * Returns the number of paths in the collection. This is the same thing as * get_num_paths(). */ -int NodePathCollection:: +size_t NodePathCollection:: size() const { return _node_paths.size(); } @@ -208,7 +211,7 @@ size() const { * hierarchically. */ void NodePathCollection:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { for (int i = 0; i < get_num_paths(); i++) { NodePath path = get_path(i); indent(out, indent_level) << path << "\n"; @@ -223,13 +226,13 @@ ls(ostream &out, int indent_level) const { * listed first. */ NodePathCollection NodePathCollection:: -find_all_matches(const string &path) const { +find_all_matches(const std::string &path) const { NodePathCollection result; FindApproxPath approx_path; if (approx_path.add_string(path)) { if (!is_empty()) { - FindApproxLevelEntry *level = NULL; + FindApproxLevelEntry *level = nullptr; for (int i = 0; i < get_num_paths(); i++) { FindApproxLevelEntry *start = new FindApproxLevelEntry(get_path(i), approx_path); @@ -557,7 +560,7 @@ set_attrib(const RenderAttrib *attrib, int priority) { * indicated output stream. */ void NodePathCollection:: -output(ostream &out) const { +output(std::ostream &out) const { if (get_num_paths() == 1) { out << "1 NodePath"; } else { @@ -570,7 +573,7 @@ output(ostream &out) const { * indicated output stream. */ void NodePathCollection:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { for (int i = 0; i < get_num_paths(); i++) { indent(out, indent_level) << get_path(i) << "\n"; } diff --git a/panda/src/pgraph/nodePathCollection.h b/panda/src/pgraph/nodePathCollection.h index 9eb0c1ce90..6dd4e76b12 100644 --- a/panda/src/pgraph/nodePathCollection.h +++ b/panda/src/pgraph/nodePathCollection.h @@ -25,7 +25,7 @@ */ class EXPCL_PANDA_PGRAPH NodePathCollection { PUBLISHED: - NodePathCollection() DEFAULT_CTOR; + NodePathCollection() = default; #ifdef HAVE_PYTHON EXTENSION(NodePathCollection(PyObject *self, PyObject *sequence)); @@ -45,8 +45,8 @@ PUBLISHED: int get_num_paths() const; NodePath get_path(int index) const; MAKE_SEQ(get_paths, get_num_paths, get_path); - NodePath operator [] (int index) const; - int size() const; + NodePath operator [] (size_t index) const; + size_t size() const; INLINE void operator += (const NodePathCollection &other); INLINE NodePathCollection operator + (const NodePathCollection &other) const; @@ -56,9 +56,9 @@ PUBLISHED: // Handy operations on many NodePaths at once. INLINE void ls() const; - void ls(ostream &out, int indent_level = 0) const; + void ls(std::ostream &out, int indent_level = 0) const; - NodePathCollection find_all_matches(const string &path) const; + NodePathCollection find_all_matches(const std::string &path) const; void reparent_to(const NodePath &other); void wrt_reparent_to(const NodePath &other); @@ -95,8 +95,8 @@ PUBLISHED: void set_attrib(const RenderAttrib *attrib, int priority = 0); - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; private: typedef PTA(NodePath) NodePaths; @@ -106,7 +106,7 @@ private: typedef pmap StateMap; }; -INLINE ostream &operator << (ostream &out, const NodePathCollection &col) { +INLINE std::ostream &operator << (std::ostream &out, const NodePathCollection &col) { col.output(out); return out; } diff --git a/panda/src/pgraph/nodePathCollection_ext.cxx b/panda/src/pgraph/nodePathCollection_ext.cxx index 32f5ac0d13..836e2959e0 100644 --- a/panda/src/pgraph/nodePathCollection_ext.cxx +++ b/panda/src/pgraph/nodePathCollection_ext.cxx @@ -32,7 +32,7 @@ extern struct Dtool_PyTypedObject Dtool_LPoint3f; void Extension:: __init__(PyObject *self, PyObject *sequence) { PyObject *fast = PySequence_Fast(sequence, "NodePathCollection constructor requires a sequence"); - if (fast == NULL) { + if (fast == nullptr) { return; } @@ -41,16 +41,16 @@ __init__(PyObject *self, PyObject *sequence) { for (int i = 0; i < size; ++i) { PyObject *item = PySequence_Fast_GET_ITEM(fast, i); - if (item == NULL) { + if (item == nullptr) { return; } NodePath *path; if (!DtoolInstance_GetPointer(item, path, Dtool_NodePath)) { // Unable to add item--probably it wasn't of the appropriate type. - ostringstream stream; + std::ostringstream stream; stream << "Element " << i << " in sequence passed to NodePathCollection constructor is not a NodePath"; - string str = stream.str(); + std::string str = stream.str(); PyErr_SetString(PyExc_TypeError, str.c_str()); Py_DECREF(fast); return; @@ -76,13 +76,13 @@ __reduce__(PyObject *self) const { // necessary to reconstruct this object. PyObject *this_class = (PyObject *)self->ob_type; - if (this_class == NULL) { - return NULL; + if (this_class == nullptr) { + return nullptr; } PyObject *self_iter = PyObject_GetIter(self); - if (self_iter == NULL) { - return NULL; + if (self_iter == nullptr) { + return nullptr; } // Since a NodePathCollection is itself an iterator, we can simply pass it diff --git a/panda/src/pgraph/nodePathComponent.I b/panda/src/pgraph/nodePathComponent.I index d3abe36c07..0a14e1ddd0 100644 --- a/panda/src/pgraph/nodePathComponent.I +++ b/panda/src/pgraph/nodePathComponent.I @@ -29,29 +29,12 @@ CData(const NodePathComponent::CData ©) : { } -/** - * NodePathComponents should not be copied. - */ -INLINE NodePathComponent:: -NodePathComponent(const NodePathComponent ©) { - nassertv(false); -} - -/** - * NodePathComponents should not be copied. - */ -INLINE void NodePathComponent:: -operator = (const NodePathComponent ©) { - nassertv(false); -} - - /** * */ INLINE NodePathComponent:: ~NodePathComponent() { - nassertv(_node != (PandaNode *)NULL); + nassertv(_node != nullptr); _node->delete_component(this); } @@ -60,7 +43,7 @@ INLINE NodePathComponent:: */ INLINE PandaNode *NodePathComponent:: get_node() const { - nassertr(_node != (PandaNode *)NULL, _node); + nassertr(_node != nullptr, _node); return _node; } @@ -84,7 +67,7 @@ get_next(int pipeline_stage, Thread *current_thread) const { return cdata->_next; } -INLINE ostream &operator << (ostream &out, const NodePathComponent &comp) { +INLINE std::ostream &operator << (std::ostream &out, const NodePathComponent &comp) { comp.output(out); return out; } diff --git a/panda/src/pgraph/nodePathComponent.cxx b/panda/src/pgraph/nodePathComponent.cxx index a9f8a38788..fa578ba53f 100644 --- a/panda/src/pgraph/nodePathComponent.cxx +++ b/panda/src/pgraph/nodePathComponent.cxx @@ -50,7 +50,7 @@ NodePathComponent(PandaNode *node, NodePathComponent *next, CDStageWriter cdata(_cycler, pipeline_stage_i, current_thread); cdata->_next = next; - if (next != (NodePathComponent *)NULL) { + if (next != nullptr) { cdata->_length = next->get_length(pipeline_stage_i, current_thread) + 1; } } @@ -80,7 +80,7 @@ get_key() const { bool NodePathComponent:: is_top_node(int pipeline_stage, Thread *current_thread) const { CDStageReader cdata(_cycler, pipeline_stage, current_thread); - return (cdata->_next == (NodePathComponent *)NULL); + return (cdata->_next == nullptr); } /** @@ -102,7 +102,7 @@ fix_length(int pipeline_stage, Thread *current_thread) { CDLockedStageReader cdata(_cycler, pipeline_stage, current_thread); int length_should_be = 1; - if (cdata->_next != (NodePathComponent *)NULL) { + if (cdata->_next != nullptr) { length_should_be = cdata->_next->get_length(pipeline_stage, current_thread) + 1; } @@ -121,13 +121,13 @@ fix_length(int pipeline_stage, Thread *current_thread) { * the end of the linked list and then outputting from there. */ void NodePathComponent:: -output(ostream &out) const { +output(std::ostream &out) const { Thread *current_thread = Thread::get_current_thread(); int pipeline_stage = current_thread->get_pipeline_stage(); PandaNode *node = get_node(); NodePathComponent *next = get_next(pipeline_stage, current_thread); - if (next != (NodePathComponent *)NULL) { + if (next != nullptr) { // This is not the head of the list; keep going up. next->output(out); out << "/"; @@ -157,7 +157,7 @@ output(ostream &out) const { */ void NodePathComponent:: set_next(NodePathComponent *next, int pipeline_stage, Thread *current_thread) { - nassertv(next != (NodePathComponent *)NULL); + nassertv(next != nullptr); CDStageWriter cdata(_cycler, pipeline_stage, current_thread); cdata->_next = next; } @@ -169,5 +169,5 @@ set_next(NodePathComponent *next, int pipeline_stage, Thread *current_thread) { void NodePathComponent:: set_top_node(int pipeline_stage, Thread *current_thread) { CDStageWriter cdata(_cycler, pipeline_stage, current_thread); - cdata->_next = (NodePathComponent *)NULL; + cdata->_next = nullptr; } diff --git a/panda/src/pgraph/nodePathComponent.h b/panda/src/pgraph/nodePathComponent.h index 2106430b7d..37b30c9562 100644 --- a/panda/src/pgraph/nodePathComponent.h +++ b/panda/src/pgraph/nodePathComponent.h @@ -39,17 +39,19 @@ * graph, and the NodePathComponents are stored in the nodes themselves to * allow the nodes to keep these up to date as the scene graph is manipulated. */ -class EXPCL_PANDA_PGRAPH NodePathComponent FINAL : public ReferenceCount { +class EXPCL_PANDA_PGRAPH NodePathComponent final : public ReferenceCount { private: NodePathComponent(PandaNode *node, NodePathComponent *next, int pipeline_stage, Thread *current_thread); - INLINE NodePathComponent(const NodePathComponent ©); - INLINE void operator = (const NodePathComponent ©); public: + NodePathComponent(const NodePathComponent ©) = delete; INLINE ~NodePathComponent(); + ALLOC_DELETED_CHAIN(NodePathComponent); + NodePathComponent &operator = (const NodePathComponent ©) = delete; + INLINE PandaNode *get_node() const; INLINE bool has_key() const; int get_key() const; @@ -60,7 +62,7 @@ public: bool fix_length(int pipeline_stage, Thread *current_thread); - void output(ostream &out) const; + void output(std::ostream &out) const; private: void set_next(NodePathComponent *next, int pipeline_stage, Thread *current_thread); @@ -129,7 +131,7 @@ private: template<> INLINE void PointerToBase::update_type(To *ptr) {} -INLINE ostream &operator << (ostream &out, const NodePathComponent &comp); +INLINE std::ostream &operator << (std::ostream &out, const NodePathComponent &comp); #include "nodePathComponent.I" diff --git a/panda/src/pgraph/nodePath_ext.cxx b/panda/src/pgraph/nodePath_ext.cxx index 1c7576290a..4be58f3201 100644 --- a/panda/src/pgraph/nodePath_ext.cxx +++ b/panda/src/pgraph/nodePath_ext.cxx @@ -16,6 +16,8 @@ #include "shaderInput_ext.h" #include "shaderAttrib.h" +using std::move; + #ifdef HAVE_PYTHON #ifndef CPPPARSER @@ -57,7 +59,7 @@ __deepcopy__(PyObject *self, PyObject *memo) const { // Borrowed reference. PyObject *dupe = PyDict_GetItem(memo, self); - if (dupe != NULL) { + if (dupe != nullptr) { // Already in the memo dictionary. Py_INCREF(dupe); return dupe; @@ -74,7 +76,7 @@ __deepcopy__(PyObject *self, PyObject *memo) const { true, false); if (PyDict_SetItem(memo, self, dupe) != 0) { Py_DECREF(dupe); - return NULL; + return nullptr; } return dupe; @@ -89,7 +91,7 @@ __deepcopy__(PyObject *self, PyObject *memo) const { */ PyObject *Extension:: __reduce__(PyObject *self) const { - return __reduce_persist__(self, NULL); + return __reduce_persist__(self, nullptr); } /** @@ -107,10 +109,10 @@ __reduce_persist__(PyObject *self, PyObject *pickler) const { // object whose constructor we should call (e.g. this), and the arguments // necessary to reconstruct this object. - BamWriter *writer = NULL; - if (pickler != NULL) { + BamWriter *writer = nullptr; + if (pickler != nullptr) { PyObject *py_writer = PyObject_GetAttrString(pickler, "bamWriter"); - if (py_writer == NULL) { + if (py_writer == nullptr) { // It's OK if there's no bamWriter. PyErr_Clear(); } else { @@ -123,37 +125,37 @@ __reduce_persist__(PyObject *self, PyObject *pickler) const { vector_uchar bam_stream; if (!_this->encode_to_bam_stream(bam_stream, writer)) { - ostringstream stream; + std::ostringstream stream; stream << "Could not bamify " << _this; - string message = stream.str(); + std::string message = stream.str(); PyErr_SetString(PyExc_TypeError, message.c_str()); - return NULL; + return nullptr; } // Start by getting this class object. PyObject *this_class = (PyObject *)Py_TYPE(self); - if (this_class == NULL) { - return NULL; + if (this_class == nullptr) { + return nullptr; } PyObject *func; - if (writer != NULL) { + if (writer != nullptr) { // The modified pickle support: call the "persistent" version of this // function, which receives the unpickler itself as an additional // parameter. func = Extension::find_global_decode(this_class, "py_decode_NodePath_from_bam_stream_persist"); - if (func == NULL) { + if (func == nullptr) { PyErr_SetString(PyExc_TypeError, "Couldn't find py_decode_NodePath_from_bam_stream_persist()"); - return NULL; + return nullptr; } } else { // The traditional pickle support: call the non-persistent version of this // function. func = Extension::find_global_decode(this_class, "py_decode_NodePath_from_bam_stream"); - if (func == NULL) { + if (func == nullptr) { PyErr_SetString(PyExc_TypeError, "Couldn't find py_decode_NodePath_from_bam_stream()"); - return NULL; + return nullptr; } } @@ -221,10 +223,10 @@ py_decode_NodePath_from_bam_stream(vector_uchar data) { */ NodePath py_decode_NodePath_from_bam_stream_persist(PyObject *unpickler, vector_uchar data) { - BamReader *reader = NULL; - if (unpickler != NULL) { + BamReader *reader = nullptr; + if (unpickler != nullptr) { PyObject *py_reader = PyObject_GetAttrString(unpickler, "bamReader"); - if (py_reader == NULL) { + if (py_reader == nullptr) { // It's OK if there's no bamReader. PyErr_Clear(); } else { @@ -294,7 +296,7 @@ set_shader_inputs(PyObject *args, PyObject *kwargs) { return; } - CPT_InternalName name(string(buffer, length)); + CPT_InternalName name(std::string(buffer, length)); ShaderInput &input = attrib->_inputs[name]; invoke_extension(&input).__init__(move(name), value); } diff --git a/panda/src/pgraph/occluderEffect.cxx b/panda/src/pgraph/occluderEffect.cxx index f27c486d88..eceb1afd6e 100644 --- a/panda/src/pgraph/occluderEffect.cxx +++ b/panda/src/pgraph/occluderEffect.cxx @@ -31,7 +31,7 @@ CPT(RenderEffect) OccluderEffect:: make() { // We make it a special case and store a pointer to the empty effect forever // once we find it the first time, as an optimization. - if (_empty_effect == (RenderEffect *)NULL) { + if (_empty_effect == nullptr) { _empty_effect = return_new(new OccluderEffect); } @@ -66,7 +66,7 @@ remove_on_occluder(const NodePath &occluder) const { * */ void OccluderEffect:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; if (_on_occluders.empty()) { out << "identity"; diff --git a/panda/src/pgraph/occluderEffect.h b/panda/src/pgraph/occluderEffect.h index af2230832f..befdcee8e0 100644 --- a/panda/src/pgraph/occluderEffect.h +++ b/panda/src/pgraph/occluderEffect.h @@ -48,7 +48,7 @@ PUBLISHED: CPT(RenderEffect) remove_on_occluder(const NodePath &occluder) const; public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderEffect *other) const; diff --git a/panda/src/pgraph/occluderNode.cxx b/panda/src/pgraph/occluderNode.cxx index c1a4c4d9da..09f8bbd038 100644 --- a/panda/src/pgraph/occluderNode.cxx +++ b/panda/src/pgraph/occluderNode.cxx @@ -51,7 +51,7 @@ PT(Texture) OccluderNode::_viz_tex; * vertices with set_vertices(). */ OccluderNode:: -OccluderNode(const string &name) : +OccluderNode(const std::string &name) : PandaNode(name) { set_cull_callback(); @@ -146,7 +146,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { trav->get_cull_handler()->record_object(occluder_viz, trav); // Also get the frame. - nassertr(_frame_viz != (Geom *)NULL, false); + nassertr(_frame_viz != nullptr, false); CullableObject *frame_viz = new CullableObject(_frame_viz, get_frame_viz_state(trav, data), data.get_internal_transform(trav)); @@ -174,7 +174,7 @@ is_renderable() const { * classes to include some information relevant to the class. */ void OccluderNode:: -output(ostream &out) const { +output(std::ostream &out) const { PandaNode::output(out); } @@ -210,8 +210,8 @@ compute_internal_bounds(CPT(BoundingVolume) &internal_bounds, */ PT(Geom) OccluderNode:: get_occluder_viz(CullTraverser *trav, CullTraverserData &data) { - if (_occluder_viz == (Geom *)NULL) { - nassertr(_vertices.size() == 4, NULL); + if (_occluder_viz == nullptr) { + nassertr(_vertices.size() == 4, nullptr); if (pgraph_cat.is_debug()) { pgraph_cat.debug() @@ -270,7 +270,7 @@ get_occluder_viz(CullTraverser *trav, CullTraverserData &data) { */ CPT(RenderState) OccluderNode:: get_occluder_viz_state(CullTraverser *trav, CullTraverserData &data) { - if (_viz_tex == NULL) { + if (_viz_tex == nullptr) { // Create a default texture. We set it up as a 2x2 graytone checkerboard, // since that's real easy, and it doesn't look like a CollisionPolygon. _viz_tex = new Texture("occluder_viz"); @@ -283,7 +283,7 @@ get_occluder_viz_state(CullTraverser *trav, CullTraverserData &data) { } static CPT(RenderState) viz_state; - if (viz_state == NULL) { + if (viz_state == nullptr) { viz_state = RenderState::make (ColorAttrib::make_flat(LVecBase4(1.0f, 1.0f, 1.0f, 0.5f)), TransparencyAttrib::make(TransparencyAttrib::M_alpha), @@ -308,7 +308,7 @@ get_occluder_viz_state(CullTraverser *trav, CullTraverserData &data) { CPT(RenderState) OccluderNode:: get_frame_viz_state(CullTraverser *trav, CullTraverserData &data) { static CPT(RenderState) viz_state; - if (viz_state == NULL) { + if (viz_state == nullptr) { viz_state = RenderState::make (ColorAttrib::make_flat(LVecBase4(0.0f, 0.0f, 0.0f, 1.0f)), TextureAttrib::make_off()); diff --git a/panda/src/pgraph/occluderNode.h b/panda/src/pgraph/occluderNode.h index 0bc4381f4d..ebc5db9bc3 100644 --- a/panda/src/pgraph/occluderNode.h +++ b/panda/src/pgraph/occluderNode.h @@ -30,7 +30,7 @@ */ class EXPCL_PANDA_PGRAPH OccluderNode : public PandaNode { PUBLISHED: - explicit OccluderNode(const string &name); + explicit OccluderNode(const std::string &name); protected: OccluderNode(const OccluderNode ©); @@ -44,7 +44,7 @@ public: virtual bool cull_callback(CullTraverser *trav, CullTraverserData &data); virtual bool is_renderable() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; PUBLISHED: INLINE void set_double_sided(bool value); diff --git a/panda/src/pgraph/pandaNode.I b/panda/src/pgraph/pandaNode.I index de6682e911..8cbea5c871 100644 --- a/panda/src/pgraph/pandaNode.I +++ b/panda/src/pgraph/pandaNode.I @@ -32,7 +32,7 @@ INLINE PandaNode *PandaNode:: get_parent(int n, Thread *current_thread) const { CDReader cdata(_cycler, current_thread); CPT(Up) up = cdata->get_up(); - nassertr(n >= 0 && n < (int)up->size(), NULL); + nassertr(n >= 0 && n < (int)up->size(), nullptr); return (*up)[n].get_parent(); } @@ -66,7 +66,7 @@ INLINE PandaNode *PandaNode:: get_child(int n, Thread *current_thread) const { CDReader cdata(_cycler, current_thread); CPT(Down) down = cdata->get_down(); - nassertr(n >= 0 && n < (int)down->size(), NULL); + nassertr(n >= 0 && n < (int)down->size(), nullptr); return (*down)[n].get_child(); } @@ -154,7 +154,7 @@ INLINE PandaNode *PandaNode:: get_stashed(int n, Thread *current_thread) const { CDReader cdata(_cycler, current_thread); CPT(Down) stashed = cdata->get_stashed(); - nassertr(n >= 0 && n < (int)stashed->size(), NULL); + nassertr(n >= 0 && n < (int)stashed->size(), nullptr); return (*stashed)[n].get_child(); } @@ -247,7 +247,7 @@ get_effect(TypeHandle type) const { if (index >= 0) { return cdata->_effects->get_effect(index); } - return NULL; + return nullptr; } /** @@ -345,14 +345,14 @@ has_dirty_prev_transform() const { * the particular key, if any. If no value has been previously set, returns * the empty string. */ -INLINE string PandaNode:: -get_tag(const string &key, Thread *current_thread) const { +INLINE std::string PandaNode:: +get_tag(const std::string &key, Thread *current_thread) const { CDReader cdata(_cycler, current_thread); int index = cdata->_tag_data.find(key); if (index >= 0) { return cdata->_tag_data.get_data((size_t)index); } else { - return string(); + return std::string(); } } @@ -362,7 +362,7 @@ get_tag(const string &key, Thread *current_thread) const { * set. */ INLINE bool PandaNode:: -has_tag(const string &key, Thread *current_thread) const { +has_tag(const std::string &key, Thread *current_thread) const { CDReader cdata(_cycler, current_thread); return cdata->_tag_data.find(key) >= 0; } @@ -379,7 +379,7 @@ get_num_tags() const { /** * Returns the key of the nth tag applied to this node. */ -INLINE string PandaNode:: +INLINE std::string PandaNode:: get_tag_key(size_t i) const { CDReader cdata(_cycler); return cdata->_tag_data.get_key(i); @@ -410,7 +410,7 @@ has_tags() const { * Lists all the nodes at and below the current path hierarchically. */ INLINE void PandaNode:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { r_list_descendants(out, indent_level); } @@ -496,7 +496,7 @@ get_into_collide_mask() const { */ INLINE void PandaNode:: clear_bounds() { - set_bounds((BoundingVolume *)NULL); + set_bounds(nullptr); } /** @@ -806,7 +806,7 @@ get_parent() const { */ INLINE PandaNode::BoundsData:: BoundsData() : - _internal_bounds(NULL), + _internal_bounds(nullptr), _internal_vertices(0) { ++_internal_bounds_mark; @@ -929,13 +929,12 @@ operator = (const PandaNode::Children ©) { _down = copy._down; } -#ifdef USE_MOVE_SEMANTICS /** * */ INLINE PandaNode::Children:: -Children(PandaNode::Children &&from) NOEXCEPT : - _down(move(from._down)) +Children(PandaNode::Children &&from) noexcept : + _down(std::move(from._down)) { } @@ -943,17 +942,16 @@ Children(PandaNode::Children &&from) NOEXCEPT : * */ INLINE void PandaNode::Children:: -operator = (PandaNode::Children &&from) NOEXCEPT { - _down = move(from._down); +operator = (PandaNode::Children &&from) noexcept { + _down = std::move(from._down); } -#endif // USE_MOVE_SEMANTICS /** * Returns the number of children of the node. */ INLINE size_t PandaNode::Children:: get_num_children() const { - nassertr(_down != (Down *)NULL, 0); + nassertr(_down != nullptr, 0); return _down->size(); } @@ -962,8 +960,8 @@ get_num_children() const { */ INLINE PandaNode *PandaNode::Children:: get_child(size_t n) const { - nassertr(_down != (Down *)NULL, NULL); - nassertr(n < (size_t)_down->size(), NULL); + nassertr(_down != nullptr, nullptr); + nassertr(n < (size_t)_down->size(), nullptr); return (*_down)[n].get_child(); } @@ -973,7 +971,7 @@ get_child(size_t n) const { */ INLINE int PandaNode::Children:: get_child_sort(size_t n) const { - nassertr(_down != (Down *)NULL, -1); + nassertr(_down != nullptr, -1); nassertr(n < _down->size(), -1); return (*_down)[n].get_sort(); } @@ -1011,13 +1009,12 @@ operator = (const PandaNode::Stashed ©) { _stashed = copy._stashed; } -#ifdef USE_MOVE_SEMANTICS /** * */ INLINE PandaNode::Stashed:: -Stashed(PandaNode::Stashed &&from) NOEXCEPT : - _stashed(move(from._stashed)) +Stashed(PandaNode::Stashed &&from) noexcept : + _stashed(std::move(from._stashed)) { } @@ -1025,17 +1022,16 @@ Stashed(PandaNode::Stashed &&from) NOEXCEPT : * */ INLINE void PandaNode::Stashed:: -operator = (PandaNode::Stashed &&from) NOEXCEPT { - _stashed = move(from._stashed); +operator = (PandaNode::Stashed &&from) noexcept { + _stashed = std::move(from._stashed); } -#endif // USE_MOVE_SEMANTICS /** * Returns the number of stashed children of the node. */ INLINE size_t PandaNode::Stashed:: get_num_stashed() const { - nassertr(_stashed != (Down *)NULL, 0); + nassertr(_stashed != nullptr, 0); return _stashed->size(); } @@ -1044,8 +1040,8 @@ get_num_stashed() const { */ INLINE PandaNode *PandaNode::Stashed:: get_stashed(size_t n) const { - nassertr(_stashed != (Down *)NULL, NULL); - nassertr(n < _stashed->size(), NULL); + nassertr(_stashed != nullptr, nullptr); + nassertr(n < _stashed->size(), nullptr); return (*_stashed)[n].get_child(); } @@ -1055,7 +1051,7 @@ get_stashed(size_t n) const { */ INLINE int PandaNode::Stashed:: get_stashed_sort(size_t n) const { - nassertr(_stashed != (Down *)NULL, -1); + nassertr(_stashed != nullptr, -1); nassertr(n < _stashed->size(), -1); return (*_stashed)[n].get_sort(); } @@ -1093,13 +1089,12 @@ operator = (const PandaNode::Parents ©) { _up = copy._up; } -#ifdef USE_MOVE_SEMANTICS /** * */ INLINE PandaNode::Parents:: -Parents(PandaNode::Parents &&from) NOEXCEPT : - _up(move(from._up)) +Parents(PandaNode::Parents &&from) noexcept : + _up(std::move(from._up)) { } @@ -1107,17 +1102,16 @@ Parents(PandaNode::Parents &&from) NOEXCEPT : * */ INLINE void PandaNode::Parents:: -operator = (PandaNode::Parents &&from) NOEXCEPT { - _up = move(from._up); +operator = (PandaNode::Parents &&from) noexcept { + _up = std::move(from._up); } -#endif // USE_MOVE_SEMANTICS /** * Returns the number of parents of the node. */ INLINE size_t PandaNode::Parents:: get_num_parents() const { - nassertr(_up != (Up *)NULL, 0); + nassertr(_up != nullptr, 0); return _up->size(); } @@ -1126,8 +1120,8 @@ get_num_parents() const { */ INLINE PandaNode *PandaNode::Parents:: get_parent(size_t n) const { - nassertr(_up != (Up *)NULL, NULL); - nassertr(n < _up->size(), NULL); + nassertr(_up != nullptr, nullptr); + nassertr(n < _up->size(), nullptr); return (*_up)[n].get_parent(); } @@ -1219,8 +1213,8 @@ INLINE PandaNodePipelineReader:: #endif // DO_PIPELINING #ifdef _DEBUG - _node = NULL; - _cdata = NULL; + _node = nullptr; + _cdata = nullptr; #endif // _DEBUG } @@ -1260,7 +1254,7 @@ release() { */ INLINE void PandaNodePipelineReader:: compose_draw_mask(DrawMask &running_draw_mask) const { - nassertv(_cdata != (PandaNode::CData *)NULL); + nassertv(_cdata != nullptr); running_draw_mask = (running_draw_mask & ~_cdata->_draw_control_mask) | (_cdata->_draw_show_mask & _cdata->_draw_control_mask); } @@ -1273,7 +1267,7 @@ compose_draw_mask(DrawMask &running_draw_mask) const { */ INLINE bool PandaNodePipelineReader:: compare_draw_mask(DrawMask running_draw_mask, DrawMask camera_mask) const { - nassertr(_cdata != (PandaNode::CData *)NULL, false); + nassertr(_cdata != nullptr, false); nassertr(_cdata->_last_update == _cdata->_next_update, false); // As a special case, if net_draw_show_mask is all 0, it means either that @@ -1322,7 +1316,7 @@ get_num_parents() const { INLINE PandaNode *PandaNodePipelineReader:: get_parent(int n) const { CPT(PandaNode::Up) up = _cdata->get_up(); - nassertr(n >= 0 && n < (int)up->size(), NULL); + nassertr(n >= 0 && n < (int)up->size(), nullptr); return (*up)[n].get_parent(); } @@ -1353,7 +1347,7 @@ get_num_children() const { INLINE PandaNode *PandaNodePipelineReader:: get_child(int n) const { CPT(PandaNode::Down) down = _cdata->get_down(); - nassertr(n >= 0 && n < (int)down->size(), NULL); + nassertr(n >= 0 && n < (int)down->size(), nullptr); return (*down)[n].get_child(); } @@ -1395,7 +1389,7 @@ get_num_stashed() const { INLINE PandaNode *PandaNodePipelineReader:: get_stashed(int n) const { CPT(PandaNode::Down) stashed = _cdata->get_stashed(); - nassertr(n >= 0 && n < (int)stashed->size(), NULL); + nassertr(n >= 0 && n < (int)stashed->size(), nullptr); return (*stashed)[n].get_child(); } @@ -1462,13 +1456,13 @@ get_prev_transform() const { * the particular key, if any. If no value has been previously set, returns * the empty string. */ -INLINE string PandaNodePipelineReader:: -get_tag(const string &key) const { +INLINE std::string PandaNodePipelineReader:: +get_tag(const std::string &key) const { int index = _cdata->_tag_data.find(key); if (index >= 0) { return _cdata->_tag_data.get_data((size_t)index); } else { - return string(); + return std::string(); } } @@ -1478,7 +1472,7 @@ get_tag(const string &key) const { * set. */ INLINE bool PandaNodePipelineReader:: -has_tag(const string &key) const { +has_tag(const std::string &key) const { return _cdata->_tag_data.find(key) >= 0; } diff --git a/panda/src/pgraph/pandaNode.cxx b/panda/src/pgraph/pandaNode.cxx index 96b94dd0c2..6994e643f8 100644 --- a/panda/src/pgraph/pandaNode.cxx +++ b/panda/src/pgraph/pandaNode.cxx @@ -28,6 +28,10 @@ #include "lightReMutexHolder.h" #include "graphicsStateGuardianBase.h" +using std::ostream; +using std::ostringstream; +using std::string; + // This category is just temporary for debugging convenience. NotifyCategoryDecl(drawmask, EXPCL_PANDA_PGRAPH, EXPTP_PANDA_PGRAPH); NotifyCategoryDef(drawmask, ""); @@ -166,7 +170,7 @@ PandaNode(const PandaNode ©) : cdata->_into_collide_mask = copy_cdata->_into_collide_mask; cdata->_bounds_type = copy_cdata->_bounds_type; cdata->_user_bounds = copy_cdata->_user_bounds; - cdata->_internal_bounds = NULL; + cdata->_internal_bounds = nullptr; cdata->_internal_bounds_computed = UpdateSeq::initial(); cdata->_internal_bounds_mark = UpdateSeq::initial(); ++cdata->_internal_bounds_mark; @@ -175,15 +179,6 @@ PandaNode(const PandaNode ©) : } } -/** - * Do not call the copy assignment operator at all. Use make_copy() or - * copy_subgraph() to make a copy of a node. - */ -void PandaNode:: -operator = (const PandaNode ©) { - nassertv(false); -} - /** * This is similar to make_copy(), but it makes a copy for the specific * purpose of flatten. Typically, this will be a new PandaNode with a new @@ -342,7 +337,7 @@ combine_with(PandaNode *other) { } // We're something other than an ordinary PandaNode. Don't combine. - return (PandaNode *)NULL; + return nullptr; } /** @@ -532,7 +527,7 @@ count_num_descendants() const { */ void PandaNode:: add_child(PandaNode *child_node, int sort, Thread *current_thread) { - nassertv(child_node != (PandaNode *)NULL); + nassertv(child_node != nullptr); if (!verify_child_no_cycles(child_node)) { // Whoops, adding this child node would introduce a cycle in the scene @@ -605,7 +600,7 @@ remove_child(int child_index, Thread *current_thread) { */ bool PandaNode:: remove_child(PandaNode *child_node, Thread *current_thread) { - nassertr(child_node != (PandaNode *)NULL, false); + nassertr(child_node != nullptr, false); // Make sure the child node is not destructed during the execution of this // method. @@ -642,8 +637,8 @@ remove_child(PandaNode *child_node, Thread *current_thread) { bool PandaNode:: replace_child(PandaNode *orig_child, PandaNode *new_child, Thread *current_thread) { - nassertr(orig_child != (PandaNode *)NULL, false); - nassertr(new_child != (PandaNode *)NULL, false); + nassertr(orig_child != nullptr, false); + nassertr(new_child != nullptr, false); if (orig_child == new_child) { // Trivial no-op. @@ -1191,8 +1186,8 @@ reset_all_prev_transform(Thread *current_thread) { list_node = panda_node->_next; #ifndef NDEBUG - panda_node->_prev = NULL; - panda_node->_next = NULL; + panda_node->_prev = nullptr; + panda_node->_next = nullptr; #endif // NDEBUG panda_node->mark_bam_modified(); } @@ -1777,7 +1772,7 @@ is_scene_root() const { // This function pointer has to be filled in when the global GraphicsEngine // is created, because we can't link with the GraphicsEngine functions // directly. - if (_scene_root_func != (SceneRootFunc *)NULL) { + if (_scene_root_func != nullptr) { return (*_scene_root_func)(this); } return false; @@ -1915,8 +1910,8 @@ set_bounds(const BoundingVolume *volume) { Thread *current_thread = Thread::get_current_thread(); OPEN_ITERATE_CURRENT_AND_UPSTREAM(_cycler, current_thread) { CDStageWriter cdata(_cycler, pipeline_stage, current_thread); - if (volume == NULL) { - cdata->_user_bounds = NULL; + if (volume == nullptr) { + cdata->_user_bounds = nullptr; } else { cdata->_user_bounds = volume->make_copy(); } @@ -2100,7 +2095,7 @@ is_collision_node() const { */ Light *PandaNode:: as_light() { - return NULL; + return nullptr; } /** @@ -2127,7 +2122,7 @@ decode_from_bam_stream(vector_uchar data, BamReader *reader) { TypedWritable *object; ReferenceCount *ref_ptr; - if (TypedWritable::decode_raw_from_bam_stream(object, ref_ptr, move(data), reader)) { + if (TypedWritable::decode_raw_from_bam_stream(object, ref_ptr, std::move(data), reader)) { return DCAST(PandaNode, object); } else { return nullptr; @@ -2144,7 +2139,7 @@ get_internal_bounds(int pipeline_stage, Thread *current_thread) const { UpdateSeq mark; { CDStageReader cdata(_cycler, pipeline_stage, current_thread); - if (cdata->_user_bounds != (BoundingVolume *)NULL) { + if (cdata->_user_bounds != nullptr) { return cdata->_user_bounds; } @@ -2161,7 +2156,7 @@ get_internal_bounds(int pipeline_stage, Thread *current_thread) const { int internal_vertices; compute_internal_bounds(internal_bounds, internal_vertices, pipeline_stage, current_thread); - nassertr(!internal_bounds.is_null(), NULL); + nassertr(!internal_bounds.is_null(), nullptr); // Now, acquire the lock, and apply the above-computed bounds. CDStageWriter cdataw(((PandaNode *)this)->_cycler, pipeline_stage); @@ -2382,13 +2377,13 @@ draw_mask_changed() { PT(PandaNode) PandaNode:: r_copy_subgraph(PandaNode::InstanceMap &inst_map, Thread *current_thread) const { PT(PandaNode) copy = make_copy(); - nassertr(copy != (PandaNode *)NULL, NULL); + nassertr(copy != nullptr, nullptr); if (copy->get_type() != get_type()) { pgraph_cat.warning() << "Don't know how to copy nodes of type " << get_type() << "\n"; if (no_unsupported_copy) { - nassertr(false, NULL); + nassertr(false, nullptr); } } @@ -2675,11 +2670,11 @@ find_node_above(PandaNode *node) { PT(NodePathComponent) PandaNode:: attach(NodePathComponent *parent, PandaNode *child_node, int sort, int pipeline_stage, Thread *current_thread) { - if (parent == (NodePathComponent *)NULL) { + if (parent == nullptr) { // Attaching to NULL means to create a new "instance" with no attachments, // and no questions asked. PT(NodePathComponent) child = - new NodePathComponent(child_node, (NodePathComponent *)NULL, + new NodePathComponent(child_node, nullptr, pipeline_stage, current_thread); LightReMutexHolder holder(child_node->_paths_lock); child_node->_paths.insert(child); @@ -2690,7 +2685,7 @@ attach(NodePathComponent *parent, PandaNode *child_node, int sort, // use that same NodePathComponent. PT(NodePathComponent) child = get_component(parent, child_node, pipeline_stage, current_thread); - if (child == (NodePathComponent *)NULL) { + if (child == nullptr) { // The child was not already attached to the parent, so get a new // component. child = get_top_component(child_node, true, pipeline_stage, current_thread); @@ -2709,7 +2704,7 @@ attach(NodePathComponent *parent, PandaNode *child_node, int sort, */ void PandaNode:: detach(NodePathComponent *child, int pipeline_stage, Thread *current_thread) { - nassertv(child != (NodePathComponent *)NULL); + nassertv(child != nullptr); for (int pipeline_stage_i = pipeline_stage; pipeline_stage_i >= 0; @@ -2729,7 +2724,7 @@ detach(NodePathComponent *child, int pipeline_stage, Thread *current_thread) { void PandaNode:: detach_one_stage(NodePathComponent *child, int pipeline_stage, Thread *current_thread) { - nassertv(child != (NodePathComponent *)NULL); + nassertv(child != nullptr); if (child->is_top_node(pipeline_stage, current_thread)) { return; } @@ -2795,7 +2790,7 @@ reparent(NodePathComponent *new_parent, NodePathComponent *child, int sort, bool as_stashed, int pipeline_stage, Thread *current_thread) { bool any_ok = false; - if (new_parent != (NodePathComponent *)NULL && + if (new_parent != nullptr && !new_parent->get_node()->verify_child_no_cycles(child->get_node())) { // Whoops, adding this child node would introduce a cycle in the scene // graph. @@ -2811,7 +2806,7 @@ reparent(NodePathComponent *new_parent, NodePathComponent *child, int sort, } } - if (new_parent != (NodePathComponent *)NULL) { + if (new_parent != nullptr) { new_parent->get_node()->children_changed(); new_parent->get_node()->mark_bam_modified(); } @@ -2834,7 +2829,7 @@ bool PandaNode:: reparent_one_stage(NodePathComponent *new_parent, NodePathComponent *child, int sort, bool as_stashed, int pipeline_stage, Thread *current_thread) { - nassertr(child != (NodePathComponent *)NULL, false); + nassertr(child != nullptr, false); // Keep a reference count to the new parent, since detaching the child might // lose the count. @@ -2844,7 +2839,7 @@ reparent_one_stage(NodePathComponent *new_parent, NodePathComponent *child, detach(child, pipeline_stage, current_thread); } - if (new_parent != (NodePathComponent *)NULL) { + if (new_parent != nullptr) { PandaNode *child_node = child->get_node(); PandaNode *parent_node = new_parent->get_node(); @@ -2896,7 +2891,7 @@ reparent_one_stage(NodePathComponent *new_parent, NodePathComponent *child, PT(NodePathComponent) PandaNode:: get_component(NodePathComponent *parent, PandaNode *child_node, int pipeline_stage, Thread *current_thread) { - nassertr(parent != (NodePathComponent *)NULL, (NodePathComponent *)NULL); + nassertr(parent != nullptr, nullptr); PandaNode *parent_node = parent->get_node(); LightReMutexHolder holder(child_node->_paths_lock); @@ -2925,7 +2920,7 @@ get_component(NodePathComponent *parent, PandaNode *child_node, return child; } else { // They aren't related. Return NULL. - return NULL; + return nullptr; } } @@ -2957,13 +2952,13 @@ get_top_component(PandaNode *child_node, bool force, int pipeline_stage, if (!force) { // If we don't care to force the point, return NULL to indicate there's // not already a top component. - return NULL; + return nullptr; } // We don't already have such a NodePathComponent; create and return a new // one. PT(NodePathComponent) child = - new NodePathComponent(child_node, (NodePathComponent *)NULL, + new NodePathComponent(child_node, nullptr, pipeline_stage, current_thread); child_node->_paths.insert(child); @@ -3178,7 +3173,7 @@ r_list_descendants(ostream &out, int indent_level) const { */ int PandaNode:: do_find_child(PandaNode *node, const PandaNode::Down *down) const { - nassertr(node != (PandaNode *)NULL, -1); + nassertr(node != nullptr, -1); // We have to search for the child by brute force, since we don't know what // sort index it was added as. @@ -3241,7 +3236,7 @@ update_cached(bool update_bounds, int pipeline_stage, PandaNode::CDLockedStageRe << "\n"; } CPT(RenderAttrib) off_clip_planes = cdata->_state->get_attrib(ClipPlaneAttrib::get_class_slot()); - if (off_clip_planes == (RenderAttrib *)NULL) { + if (off_clip_planes == nullptr) { off_clip_planes = ClipPlaneAttrib::make(); } @@ -3270,7 +3265,7 @@ update_cached(bool update_bounds, int pipeline_stage, PandaNode::CDLockedStageRe int child_volumes_i = 0; bool all_box = true; - CPT(BoundingVolume) internal_bounds = NULL; + CPT(BoundingVolume) internal_bounds = nullptr; if (update_bounds) { child_volumes = (const BoundingVolume **)alloca(sizeof(BoundingVolume *) * (num_children + 1)); @@ -3282,7 +3277,7 @@ update_cached(bool update_bounds, int pipeline_stage, PandaNode::CDLockedStageRe #endif nassertr(child_volumes_i < num_children + 1, CDStageWriter(_cycler, pipeline_stage, cdata)); child_volumes[child_volumes_i++] = internal_bounds; - if (internal_bounds->as_bounding_box() == NULL) { + if (internal_bounds->as_bounding_box() == nullptr) { all_box = false; } } @@ -3380,7 +3375,7 @@ update_cached(bool update_bounds, int pipeline_stage, PandaNode::CDLockedStageRe #endif nassertr(child_volumes_i < num_children + 1, CDStageWriter(_cycler, pipeline_stage, cdata)); child_volumes[child_volumes_i++] = child_cdataw->_external_bounds; - if (child_cdataw->_external_bounds->as_bounding_box() == NULL) { + if (child_cdataw->_external_bounds->as_bounding_box() == nullptr) { all_box = false; } } @@ -3435,7 +3430,7 @@ update_cached(bool update_bounds, int pipeline_stage, PandaNode::CDLockedStageRe #endif nassertr(child_volumes_i < num_children + 1, CDStageWriter(_cycler, pipeline_stage, cdata)); child_volumes[child_volumes_i++] = child_cdata->_external_bounds; - if (child_cdata->_external_bounds->as_bounding_box() == NULL) { + if (child_cdata->_external_bounds->as_bounding_box() == nullptr) { all_box = false; } } @@ -3677,7 +3672,7 @@ CData() : _draw_show_mask(DrawMask::all_on()), _into_collide_mask(CollideMask::all_off()), _bounds_type(BoundingVolume::BT_default), - _user_bounds(NULL), + _user_bounds(nullptr), _final_bounds(false), _fancy_bits(0), @@ -4084,7 +4079,7 @@ fillin_down_list(PandaNode::Down &down_list, const string &tag, for (int i = 0; i < num_children; i++) { manager->read_pointer(scan); int sort = scan.get_int32(); - DownConnection connection(NULL, sort); + DownConnection connection(nullptr, sort); new_down_list.push_back(connection); } @@ -4113,7 +4108,7 @@ check_cached(bool update_bounds) const { #ifdef DO_PIPELINING node_unref_delete((CycleData *)_cdata); #endif // DO_PIPELINING - ((PandaNodePipelineReader *)this)->_cdata = NULL; + ((PandaNodePipelineReader *)this)->_cdata = nullptr; int pipeline_stage = _current_thread->get_pipeline_stage(); PandaNode::CDLockedStageReader fresh_cdata(_node->_cycler, pipeline_stage, _current_thread); if (fresh_cdata->_last_update == fresh_cdata->_next_update && diff --git a/panda/src/pgraph/pandaNode.h b/panda/src/pgraph/pandaNode.h index 1b42e5ed2d..4011680178 100644 --- a/panda/src/pgraph/pandaNode.h +++ b/panda/src/pgraph/pandaNode.h @@ -64,15 +64,15 @@ class GraphicsStateGuardianBase; class EXPCL_PANDA_PGRAPH PandaNode : public TypedWritableReferenceCount, public Namable, public LinkedListNode { PUBLISHED: - explicit PandaNode(const string &name); + explicit PandaNode(const std::string &name); virtual ~PandaNode(); // published so that characters can be combined. virtual PandaNode *combine_with(PandaNode *other); protected: PandaNode(const PandaNode ©); -private: - void operator = (const PandaNode ©); + + PandaNode &operator = (const PandaNode ©) = delete; public: virtual PandaNode *dupe_for_flatten() const; @@ -189,19 +189,19 @@ PUBLISHED: static void reset_all_prev_transform(Thread *current_thread = Thread::get_current_thread()); MAKE_PROPERTY(prev_transform, get_prev_transform); - void set_tag(const string &key, const string &value, + void set_tag(const std::string &key, const std::string &value, Thread *current_thread = Thread::get_current_thread()); - INLINE string get_tag(const string &key, + INLINE std::string get_tag(const std::string &key, Thread *current_thread = Thread::get_current_thread()) const; - INLINE bool has_tag(const string &key, + INLINE bool has_tag(const std::string &key, Thread *current_thread = Thread::get_current_thread()) const; - void clear_tag(const string &key, + void clear_tag(const std::string &key, Thread *current_thread = Thread::get_current_thread()); public: void get_tag_keys(vector_string &keys) const; INLINE size_t get_num_tags() const; - INLINE string get_tag_key(size_t i) const; + INLINE std::string get_tag_key(size_t i) const; PUBLISHED: MAKE_MAP_PROPERTY(tags, has_tag, get_tag, set_tag, clear_tag); @@ -221,7 +221,7 @@ PUBLISHED: INLINE bool has_tags() const; void copy_tags(PandaNode *other); - void list_tags(ostream &out, const string &separator = "\n") const; + void list_tags(std::ostream &out, const std::string &separator = "\n") const; int compare_tags(const PandaNode *other) const; @@ -272,10 +272,10 @@ PUBLISHED: bool is_scene_root() const; bool is_under_scene_root() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; - INLINE void ls(ostream &out, int indent_level) const; + INLINE void ls(std::ostream &out, int indent_level) const; // A node has three bounding volumes: an "external" bounding volume that // represents the node and all of its children, an "internal" bounding @@ -437,7 +437,7 @@ private: static void new_connection(PandaNode *parent_node, PandaNode *child_node, int pipeline_stage, Thread *current_thread); void fix_path_lengths(int pipeline_stage, Thread *current_thread); - void r_list_descendants(ostream &out, int indent_level) const; + void r_list_descendants(std::ostream &out, int indent_level) const; INLINE void do_set_dirty_prev_transform(); INLINE void do_clear_dirty_prev_transform(); @@ -520,7 +520,7 @@ private: // This is used to maintain a table of keyed data on each node, for the // user's purposes. - typedef SimpleHashMap TagData; + typedef SimpleHashMap TagData; // This is actually implemented in pandaNode_ext.h, but defined here so // that we can destruct it from the C++ side. Note that it isn't cycled, @@ -647,13 +647,13 @@ private: BamWriter *manager, Datagram &dg) const; void update_up_list(const Up &up_list, BamWriter *manager) const; void update_down_list(const Down &down_list, BamWriter *manager) const; - int complete_up_list(Up &up_list, const string &tag, + int complete_up_list(Up &up_list, const std::string &tag, TypedWritable **p_list, BamReader *manager); - int complete_down_list(Down &down_list, const string &tag, + int complete_down_list(Down &down_list, const std::string &tag, TypedWritable **p_list, BamReader *manager); - void fillin_up_list(Up &up_list, const string &tag, + void fillin_up_list(Up &up_list, const std::string &tag, DatagramIterator &scan, BamReader *manager); - void fillin_down_list(Down &down_list, const string &tag, + void fillin_down_list(Down &down_list, const std::string &tag, DatagramIterator &scan, BamReader *manager); INLINE CPT(Down) get_down() const; @@ -710,12 +710,10 @@ PUBLISHED: INLINE Children(); INLINE Children(const CData *cdata); INLINE Children(const Children ©); - INLINE void operator = (const Children ©); + INLINE Children(Children &&from) noexcept; -#ifdef USE_MOVE_SEMANTICS - INLINE Children(Children &&from) NOEXCEPT; - INLINE void operator = (Children &&from) NOEXCEPT; -#endif + INLINE void operator = (const Children ©); + INLINE void operator = (Children &&from) noexcept; INLINE size_t get_num_children() const; INLINE PandaNode *get_child(size_t n) const; @@ -735,12 +733,10 @@ PUBLISHED: INLINE Stashed(); INLINE Stashed(const CData *cdata); INLINE Stashed(const Stashed ©); - INLINE void operator = (const Stashed ©); + INLINE Stashed(Stashed &&from) noexcept; -#ifdef USE_MOVE_SEMANTICS - INLINE Stashed(Stashed &&from) NOEXCEPT; - INLINE void operator = (Stashed &&from) NOEXCEPT; -#endif + INLINE void operator = (const Stashed ©); + INLINE void operator = (Stashed &&from) noexcept; INLINE size_t get_num_stashed() const; INLINE PandaNode *get_stashed(size_t n) const; @@ -760,12 +756,10 @@ PUBLISHED: INLINE Parents(); INLINE Parents(const CData *cdata); INLINE Parents(const Parents ©); - INLINE void operator = (const Parents ©); + INLINE Parents(Parents &&from) noexcept; -#ifdef USE_MOVE_SEMANTICS - INLINE Parents(Parents &&from) NOEXCEPT; - INLINE void operator = (Parents &&from) NOEXCEPT; -#endif + INLINE void operator = (const Parents ©); + INLINE void operator = (Parents &&from) noexcept; INLINE size_t get_num_parents() const; INLINE PandaNode *get_parent(size_t n) const; @@ -885,8 +879,8 @@ public: INLINE const TransformState *get_transform() const; INLINE const TransformState *get_prev_transform() const; - INLINE string get_tag(const string &key) const; - INLINE bool has_tag(const string &key) const; + INLINE std::string get_tag(const std::string &key) const; + INLINE bool has_tag(const std::string &key) const; INLINE CollideMask get_net_collide_mask() const; INLINE const RenderAttrib *get_off_clip_planes() const; @@ -922,7 +916,7 @@ private: template<> INLINE void PointerToBase::update_type(To *ptr) {} -INLINE ostream &operator << (ostream &out, const PandaNode &node) { +INLINE std::ostream &operator << (std::ostream &out, const PandaNode &node) { node.output(out); return out; } diff --git a/panda/src/pgraph/pandaNodeChain.I b/panda/src/pgraph/pandaNodeChain.I index 8a401d3a80..c53beec7e7 100644 --- a/panda/src/pgraph/pandaNodeChain.I +++ b/panda/src/pgraph/pandaNodeChain.I @@ -26,6 +26,6 @@ PandaNodeChain(const char *lock_name) : */ INLINE PandaNodeChain:: ~PandaNodeChain() { - _next = NULL; - _prev = NULL; + _next = nullptr; + _prev = nullptr; } diff --git a/panda/src/pgraph/pandaNode_ext.cxx b/panda/src/pgraph/pandaNode_ext.cxx index aa24e623ee..bc6427b1d0 100644 --- a/panda/src/pgraph/pandaNode_ext.cxx +++ b/panda/src/pgraph/pandaNode_ext.cxx @@ -48,7 +48,7 @@ __deepcopy__(PyObject *self, PyObject *memo) const { // Borrowed reference. PyObject *dupe = PyDict_GetItem(memo, self); - if (dupe != NULL) { + if (dupe != nullptr) { // Already in the memo dictionary. Py_INCREF(dupe); return dupe; @@ -64,7 +64,7 @@ __deepcopy__(PyObject *self, PyObject *memo) const { if (PyDict_SetItem(memo, self, dupe) != 0) { Py_DECREF(dupe); - return NULL; + return nullptr; } return dupe; @@ -94,14 +94,9 @@ get_tag_keys() const { */ PyObject *Extension:: get_python_tags() { - if (_this->_python_tag_data == NULL) { - _this->_python_tag_data = new PythonTagDataImpl; - - } else if (_this->_python_tag_data->get_ref_count() > 1) { - // Copy-on-write. - _this->_python_tag_data = new PythonTagDataImpl(*(PythonTagDataImpl *)_this->_python_tag_data.p()); - } - return ((PythonTagDataImpl *)_this->_python_tag_data.p())->_dict; + PyObject *dict = do_get_python_tags(); + Py_INCREF(dict); + return dict; } /** @@ -116,7 +111,7 @@ get_python_tags() { */ int Extension:: set_python_tag(PyObject *key, PyObject *value) { - return PyDict_SetItem(get_python_tags(), key, value); + return PyDict_SetItem(do_get_python_tags(), key, value); } /** @@ -125,14 +120,14 @@ set_python_tag(PyObject *key, PyObject *value) { */ PyObject *Extension:: get_python_tag(PyObject *key) const { - if (_this->_python_tag_data == NULL) { + if (_this->_python_tag_data == nullptr) { Py_INCREF(Py_None); return Py_None; } PyObject *dict = ((PythonTagDataImpl *)_this->_python_tag_data.p())->_dict; PyObject *value = PyDict_GetItem(dict, key); - if (value == NULL) { + if (value == nullptr) { value = Py_None; } // PyDict_GetItem returns a borrowed reference. @@ -147,12 +142,12 @@ get_python_tag(PyObject *key) const { */ bool Extension:: has_python_tag(PyObject *key) const { - if (_this->_python_tag_data == NULL) { + if (_this->_python_tag_data == nullptr) { return false; } PyObject *dict = ((PythonTagDataImpl *)_this->_python_tag_data.p())->_dict; - return (PyDict_GetItem(dict, key) != NULL); + return (PyDict_GetItem(dict, key) != nullptr); } /** @@ -162,12 +157,12 @@ has_python_tag(PyObject *key) const { */ void Extension:: clear_python_tag(PyObject *key) { - if (_this->_python_tag_data == NULL) { + if (_this->_python_tag_data == nullptr) { return; } - PyObject *dict = get_python_tags(); - if (PyDict_GetItem(dict, key) != NULL) { + PyObject *dict = do_get_python_tags(); + if (PyDict_GetItem(dict, key) != nullptr) { PyDict_DelItem(dict, key); } } @@ -177,7 +172,7 @@ clear_python_tag(PyObject *key) { */ PyObject *Extension:: get_python_tag_keys() const { - if (_this->_python_tag_data == NULL) { + if (_this->_python_tag_data == nullptr) { return PyTuple_New(0); } @@ -195,12 +190,27 @@ __traverse__(visitproc visit, void *arg) { // quite expensive, so I'd rather not do it unless we had some optimization // that would allow us to quickly find out whether there are children with // Python tags. - if (_this->_python_tag_data != NULL) { + if (_this->_python_tag_data != nullptr) { Py_VISIT(((PythonTagDataImpl *)_this->_python_tag_data.p())->_dict); } return 0; } +/** + * Same as get_python_tags, without incrementing the reference count. + */ +PyObject *Extension:: +do_get_python_tags() { + if (_this->_python_tag_data == nullptr) { + _this->_python_tag_data = new PythonTagDataImpl; + + } else if (_this->_python_tag_data->get_ref_count() > 1) { + // Copy-on-write. + _this->_python_tag_data = new PythonTagDataImpl(*(PythonTagDataImpl *)_this->_python_tag_data.p()); + } + return ((PythonTagDataImpl *)_this->_python_tag_data.p())->_dict; +} + /** * Destroys the tags associated with the node. */ diff --git a/panda/src/pgraph/pandaNode_ext.h b/panda/src/pgraph/pandaNode_ext.h index 86527d42d4..d19bc5475f 100644 --- a/panda/src/pgraph/pandaNode_ext.h +++ b/panda/src/pgraph/pandaNode_ext.h @@ -45,6 +45,8 @@ public: int __traverse__(visitproc visit, void *arg); private: + PyObject *do_get_python_tags(); + // This is what actually stores the Python tags. class PythonTagDataImpl : public PandaNode::PythonTagData { public: diff --git a/panda/src/pgraph/paramNodePath.I b/panda/src/pgraph/paramNodePath.I index beaa9c5c85..89d6a9e67b 100644 --- a/panda/src/pgraph/paramNodePath.I +++ b/panda/src/pgraph/paramNodePath.I @@ -20,16 +20,14 @@ ParamNodePath(const NodePath &node_path) : { } -#ifdef USE_MOVE_SEMANTICS /** * Creates a new ParamNodePath storing the given node path object. */ INLINE ParamNodePath:: -ParamNodePath(NodePath &&node_path) NOEXCEPT : - _node_path(move(node_path)) +ParamNodePath(NodePath &&node_path) noexcept : + _node_path(std::move(node_path)) { } -#endif // USE_MOVE_SEMANTICS /** * Returns NodePath::get_class_type(). diff --git a/panda/src/pgraph/paramNodePath.cxx b/panda/src/pgraph/paramNodePath.cxx index a620144a14..72a3563b22 100644 --- a/panda/src/pgraph/paramNodePath.cxx +++ b/panda/src/pgraph/paramNodePath.cxx @@ -21,7 +21,7 @@ TypeHandle ParamNodePath::_type_handle; * */ void ParamNodePath:: -output(ostream &out) const { +output(std::ostream &out) const { out << "node path " << _node_path; } @@ -45,7 +45,7 @@ write_datagram(BamWriter *manager, Datagram &dg) { // Before bam 6.40, we did not support writing NodePaths. Instaed, we // write the PandaNode pointer and pray there is an unambiguous path. if (_node_path.is_empty()) { - manager->write_pointer(dg, NULL); + manager->write_pointer(dg, nullptr); } else { manager->write_pointer(dg, _node_path.node()); } diff --git a/panda/src/pgraph/paramNodePath.h b/panda/src/pgraph/paramNodePath.h index 25812d8b0f..bd0967d5f8 100644 --- a/panda/src/pgraph/paramNodePath.h +++ b/panda/src/pgraph/paramNodePath.h @@ -21,21 +21,18 @@ /** * A class object for storing a NodePath as a parameter. */ -class EXPCL_PANDA_GOBJ ParamNodePath : public ParamValueBase { +class EXPCL_PANDA_PGRAPH ParamNodePath : public ParamValueBase { protected: INLINE ParamNodePath() {}; PUBLISHED: INLINE ParamNodePath(const NodePath &node_path); - -#ifdef USE_MOVE_SEMANTICS - INLINE ParamNodePath(NodePath &&node_path) NOEXCEPT; -#endif + INLINE ParamNodePath(NodePath &&node_path) noexcept; INLINE virtual TypeHandle get_value_type() const; INLINE const NodePath &get_value() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: NodePath _node_path; diff --git a/panda/src/pgraph/planeNode.I b/panda/src/pgraph/planeNode.I index e3983c1305..fd4e8d4634 100644 --- a/panda/src/pgraph/planeNode.I +++ b/panda/src/pgraph/planeNode.I @@ -42,8 +42,8 @@ set_plane(const LPlane &plane) { CDWriter cdata(_cycler); if (cdata->_plane != plane) { cdata->_plane = plane; - cdata->_front_viz = NULL; - cdata->_back_viz = NULL; + cdata->_front_viz = nullptr; + cdata->_back_viz = nullptr; } } @@ -65,8 +65,8 @@ set_viz_scale(PN_stdfloat viz_scale) { CDWriter cdata(_cycler); if (cdata->_viz_scale != viz_scale) { cdata->_viz_scale = viz_scale; - cdata->_front_viz = NULL; - cdata->_back_viz = NULL; + cdata->_front_viz = nullptr; + cdata->_back_viz = nullptr; } } diff --git a/panda/src/pgraph/planeNode.cxx b/panda/src/pgraph/planeNode.cxx index c096eaeb49..9513b23509 100644 --- a/panda/src/pgraph/planeNode.cxx +++ b/panda/src/pgraph/planeNode.cxx @@ -59,7 +59,7 @@ fillin(DatagramIterator &scan, BamReader *) { * */ PlaneNode:: -PlaneNode(const string &name, const LPlane &plane) : +PlaneNode(const std::string &name, const LPlane &plane) : PandaNode(name), _priority(0), _clip_effect(~0) @@ -88,7 +88,7 @@ PlaneNode(const PlaneNode ©) : * */ void PlaneNode:: -output(ostream &out) const { +output(std::ostream &out) const { PandaNode::output(out); out << " " << get_plane(); } @@ -112,8 +112,8 @@ xform(const LMatrix4 &mat) { PandaNode::xform(mat); CDWriter cdata(_cycler); cdata->_plane = cdata->_plane * mat; - cdata->_front_viz = NULL; - cdata->_back_viz = NULL; + cdata->_front_viz = nullptr; + cdata->_back_viz = nullptr; } /** @@ -186,7 +186,7 @@ get_viz(CullTraverser *trav, CullTraverserData &data) { LPlane eye_plane = cdata->_plane * data.get_modelview_transform(trav)->get_mat(); bool front = (eye_plane.dist_to_plane(lens->get_nodal_point()) >= 0.0f); - if (cdata->_front_viz != (Geom *)NULL) { + if (cdata->_front_viz != nullptr) { return front ? cdata->_front_viz : cdata->_back_viz; } diff --git a/panda/src/pgraph/planeNode.h b/panda/src/pgraph/planeNode.h index 463fc39b22..2b58225abd 100644 --- a/panda/src/pgraph/planeNode.h +++ b/panda/src/pgraph/planeNode.h @@ -35,12 +35,12 @@ */ class EXPCL_PANDA_PGRAPH PlaneNode : public PandaNode { PUBLISHED: - explicit PlaneNode(const string &name, const LPlane &plane = LPlane()); + explicit PlaneNode(const std::string &name, const LPlane &plane = LPlane()); protected: PlaneNode(const PlaneNode ©); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; virtual PandaNode *make_copy() const; virtual void xform(const LMatrix4 &mat); diff --git a/panda/src/pgraph/polylightEffect.cxx b/panda/src/pgraph/polylightEffect.cxx index acbd41b18f..f940a62c8c 100644 --- a/panda/src/pgraph/polylightEffect.cxx +++ b/panda/src/pgraph/polylightEffect.cxx @@ -22,6 +22,8 @@ #include +using std::endl; + TypeHandle PolylightEffect::_type_handle; /** @@ -334,7 +336,7 @@ do_poly_light(const SceneSetup *scene, const CullTraverserData *data, const Tran * */ void PolylightEffect:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; LightGroup::const_iterator li; @@ -461,8 +463,8 @@ has_light(const NodePath &light) const { return (li != _lightgroup.end()); } -ostream & -operator << (ostream &out, PolylightEffect::ContribType ct) { +std::ostream & +operator << (std::ostream &out, PolylightEffect::ContribType ct) { switch (ct) { case PolylightEffect::CT_proximal: return out << "proximal"; diff --git a/panda/src/pgraph/polylightEffect.h b/panda/src/pgraph/polylightEffect.h index 418ac2f5db..7416938acd 100644 --- a/panda/src/pgraph/polylightEffect.h +++ b/panda/src/pgraph/polylightEffect.h @@ -70,7 +70,7 @@ public: // CPT(RenderAttrib) do_poly_light(const NodePath &root, const // CullTraverserData *data, const TransformState *node_transform) const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: ContribType _contribution_type; @@ -101,6 +101,6 @@ private: #include "polylightEffect.I" -ostream &operator << (ostream &out, PolylightEffect::ContribType ct); +std::ostream &operator << (std::ostream &out, PolylightEffect::ContribType ct); #endif diff --git a/panda/src/pgraph/polylightNode.I b/panda/src/pgraph/polylightNode.I index 7a4fcb5899..26eafa9898 100644 --- a/panda/src/pgraph/polylightNode.I +++ b/panda/src/pgraph/polylightNode.I @@ -322,7 +322,7 @@ get_color_scenegraph() const { const RenderAttrib *attrib = PandaNode::get_attrib(ColorAttrib::get_class_type()); - if (attrib != (const RenderAttrib *)NULL) { + if (attrib != nullptr) { const ColorAttrib *ca = DCAST(ColorAttrib, attrib); if (ca->get_color_type() == ColorAttrib::T_flat) { return ca->get_color(); diff --git a/panda/src/pgraph/polylightNode.cxx b/panda/src/pgraph/polylightNode.cxx index e7b857367b..73242aab04 100644 --- a/panda/src/pgraph/polylightNode.cxx +++ b/panda/src/pgraph/polylightNode.cxx @@ -29,7 +29,7 @@ TypeHandle PolylightNode::_type_handle; * Use PolylightNode() to construct a new PolylightNode object. */ PolylightNode:: -PolylightNode(const string &name) : +PolylightNode(const std::string &name) : PandaNode(name) { _enabled = true; @@ -100,12 +100,12 @@ LColor PolylightNode::flicker() const { variation = (rand()%100); // a value between 0-99 variation /= 100.0; if (polylight_info) - pgraph_cat.info() << "Random Variation: " << variation << endl; + pgraph_cat.info() << "Random Variation: " << variation << std::endl; } else if (_flicker_type == FSIN) { double now = ClockObject::get_global_clock()->get_frame_time(); variation = sinf(now*_sin_freq); if (polylight_info) - pgraph_cat.info() << "Variation: " << variation << endl; + pgraph_cat.info() << "Variation: " << variation << std::endl; // can't use negative variation, so make it positive if (variation < 0.0) variation *= -1.0; @@ -134,7 +134,7 @@ LColor PolylightNode::flicker() const { b = color[2]; } */ - pgraph_cat.debug() << "Color R:" << r << "; G:" << g << "; B:" << b << endl; + pgraph_cat.debug() << "Color R:" << r << "; G:" << g << "; B:" << b << std::endl; return LColor(r,g,b,1.0); } @@ -277,7 +277,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { * */ void PolylightNode:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; // out << "Position: " << get_x() << " " << get_y() << " " << get_z() << // "\n"; out << "Color: " << get_r() << " " << get_g() << " " << get_b() << diff --git a/panda/src/pgraph/polylightNode.h b/panda/src/pgraph/polylightNode.h index cb01427e58..e5caf30735 100644 --- a/panda/src/pgraph/polylightNode.h +++ b/panda/src/pgraph/polylightNode.h @@ -52,7 +52,7 @@ PUBLISHED: AQUADRATIC, }; - explicit PolylightNode(const string &name); + explicit PolylightNode(const std::string &name); INLINE void enable(); INLINE void disable(); INLINE void set_pos(const LPoint3 &position); @@ -120,7 +120,7 @@ private: public: static void register_with_read_factory(); virtual void write_datagram(BamWriter *manager, Datagram &dg); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: static TypedWritable *make_from_bam(const FactoryParams ¶ms); diff --git a/panda/src/pgraph/portalClipper.I b/panda/src/pgraph/portalClipper.I index 221119feb5..6dd31056e2 100644 --- a/panda/src/pgraph/portalClipper.I +++ b/panda/src/pgraph/portalClipper.I @@ -161,7 +161,7 @@ is_whole_portal_in_view(const LMatrix4 &cmat) { int result = _reduced_frustum->contains(gbv); - portal_cat.spam() << "1st level test if portal: " << *_reduced_frustum << " is in view " << result << endl; + portal_cat.spam() << "1st level test if portal: " << *_reduced_frustum << " is in view " << result << std::endl; return (result != 0); } diff --git a/panda/src/pgraph/portalClipper.cxx b/panda/src/pgraph/portalClipper.cxx index f6d45aab8f..d9d1af727d 100644 --- a/panda/src/pgraph/portalClipper.cxx +++ b/panda/src/pgraph/portalClipper.cxx @@ -30,6 +30,10 @@ #include "geomLinestrips.h" #include "geomPoints.h" +using std::endl; +using std::max; +using std::min; + TypeHandle PortalClipper::_type_handle; /** @@ -39,7 +43,7 @@ PortalClipper:: PortalClipper(GeometricBoundingVolume *frustum, SceneSetup *scene_setup): _reduced_viewport_min(-1,-1), _reduced_viewport_max(1,1), -_clip_state(NULL) +_clip_state(nullptr) { _previous = new GeomNode("my_frustum"); @@ -140,7 +144,7 @@ draw_current_portal() void PortalClipper:: draw_lines() { if (!_list.empty()) { - _created_data = NULL; + _created_data = nullptr; PT(GeomVertexData) vdata = new GeomVertexData ("portal", GeomVertexFormat::get_v3cp(), Geom::UH_static); @@ -200,7 +204,7 @@ prepare_portal(const NodePath &node_path) { // Get the Portal Node from this node_path PandaNode *node = node_path.node(); - _portal_node = NULL; + _portal_node = nullptr; if (node->is_of_type(PortalNode::get_class_type())) { _portal_node = DCAST(PortalNode, node); } diff --git a/panda/src/pgraph/portalNode.cxx b/panda/src/pgraph/portalNode.cxx index dccfef23c4..c7ad0444fe 100644 --- a/panda/src/pgraph/portalNode.cxx +++ b/panda/src/pgraph/portalNode.cxx @@ -30,6 +30,8 @@ #include "plane.h" +using std::endl; + TypeHandle PortalNode::_type_handle; @@ -39,7 +41,7 @@ TypeHandle PortalNode::_type_handle; * Then you can set the vertices yourself, with addVertex. */ PortalNode:: -PortalNode(const string &name) : +PortalNode(const std::string &name) : PandaNode(name), _from_portal_mask(PortalMask::all_on()), _into_portal_mask(PortalMask::all_on()), @@ -58,7 +60,7 @@ PortalNode(const string &name) : * portal and setup from Python */ PortalNode:: -PortalNode(const string &name, LPoint3 pos, PN_stdfloat scale) : +PortalNode(const std::string &name, LPoint3 pos, PN_stdfloat scale) : PandaNode(name), _from_portal_mask(PortalMask::all_on()), _into_portal_mask(PortalMask::all_on()), @@ -180,7 +182,7 @@ combine_with(PandaNode *other) { } // Two PortalNodes with different names can't combine. - return (PandaNode *)NULL; + return nullptr; } return PandaNode::combine_with(other); @@ -273,7 +275,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { // undo parent clip state and compose our new clip state ito the new // state - if (old_clip_state != NULL) { + if (old_clip_state != nullptr) { next_state = old_clip_state->invert_compose(next_state); portal_cat.spam() << "next state after removing parent state " << *next_state << endl; } @@ -323,7 +325,7 @@ is_renderable() const { * classes to include some information relevant to the class. */ void PortalNode:: -output(ostream &out) const { +output(std::ostream &out) const { PandaNode::output(out); } @@ -376,8 +378,8 @@ CPT(RenderState) PortalNode:: get_last_pos_state() { // Once someone asks for this pointer, we hold its reference count and never // free it. - static CPT(RenderState) state = (const RenderState *)NULL; - if (state == (const RenderState *)NULL) { + static CPT(RenderState) state = nullptr; + if (state == nullptr) { state = RenderState::make (ColorScaleAttrib::make(LVecBase4(1.0f, 1.0f, 1.0f, 0.5f)), TransparencyAttrib::make(TransparencyAttrib::M_alpha)); diff --git a/panda/src/pgraph/portalNode.h b/panda/src/pgraph/portalNode.h index fefe5b6bdb..de78847dab 100644 --- a/panda/src/pgraph/portalNode.h +++ b/panda/src/pgraph/portalNode.h @@ -29,8 +29,8 @@ */ class EXPCL_PANDA_PGRAPH PortalNode : public PandaNode { PUBLISHED: - explicit PortalNode(const string &name); - explicit PortalNode(const string &name, LPoint3 pos, PN_stdfloat scale=10.0); + explicit PortalNode(const std::string &name); + explicit PortalNode(const std::string &name, LPoint3 pos, PN_stdfloat scale=10.0); protected: PortalNode(const PortalNode ©); @@ -47,7 +47,7 @@ public: virtual bool cull_callback(CullTraverser *trav, CullTraverserData &data); virtual bool is_renderable() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; PUBLISHED: INLINE void set_portal_mask(PortalMask mask); diff --git a/panda/src/pgraph/renderAttrib.cxx b/panda/src/pgraph/renderAttrib.cxx index 385d7ee740..73b1e4b392 100644 --- a/panda/src/pgraph/renderAttrib.cxx +++ b/panda/src/pgraph/renderAttrib.cxx @@ -18,8 +18,10 @@ #include "lightReMutexHolder.h" #include "pStatTimer.h" -LightReMutex *RenderAttrib::_attribs_lock = NULL; -RenderAttrib::Attribs *RenderAttrib::_attribs = NULL; +using std::ostream; + +LightReMutex *RenderAttrib::_attribs_lock = nullptr; +RenderAttrib::Attribs *RenderAttrib::_attribs = nullptr; TypeHandle RenderAttrib::_type_handle; size_t RenderAttrib::_garbage_index = 0; @@ -31,28 +33,12 @@ PStatCollector RenderAttrib::_garbage_collect_pcollector("*:State Cache:Garbage */ RenderAttrib:: RenderAttrib() { - if (_attribs == (Attribs *)NULL) { + if (_attribs == nullptr) { init_attribs(); } _saved_entry = -1; } -/** - * RenderAttribs are not meant to be copied. - */ -RenderAttrib:: -RenderAttrib(const RenderAttrib &) { - nassertv(false); -} - -/** - * RenderAttribs are not meant to be copied. - */ -void RenderAttrib:: -operator = (const RenderAttrib &) { - nassertv(false); -} - /** * The destructor is responsible for removing the RenderAttrib from the global * set if it is there. @@ -171,7 +157,7 @@ int RenderAttrib:: get_num_attribs() { LightReMutexHolder holder(*_attribs_lock); - if (_attribs == (Attribs *)NULL) { + if (_attribs == nullptr) { return 0; } return _attribs->get_num_entries(); @@ -200,7 +186,7 @@ list_attribs(ostream &out) { */ int RenderAttrib:: garbage_collect() { - if (_attribs == (Attribs *)NULL || !garbage_collect_states) { + if (_attribs == nullptr || !garbage_collect_states) { return 0; } LightReMutexHolder holder(*_attribs_lock); @@ -214,7 +200,7 @@ garbage_collect() { // How many elements to process this pass? size_t size = orig_size; - size_t num_this_pass = max(0, int(size * garbage_collect_states_rate)); + size_t num_this_pass = std::max(0, int(size * garbage_collect_states_rate)); if (num_this_pass <= 0) { return 0; } @@ -224,7 +210,7 @@ garbage_collect() { si = 0; } - num_this_pass = min(num_this_pass, size); + num_this_pass = std::min(num_this_pass, size); size_t stop_at_element = (_garbage_index + num_this_pass) % size; do { @@ -282,7 +268,7 @@ validate_attribs() { for (size_t si = 0; si < size; ++si) { const RenderAttrib *attrib = _attribs->get_key(si); //cerr << si << ": " << attrib << "\n"; - attrib->write(cerr, 2); + attrib->write(std::cerr, 2); } return false; @@ -329,7 +315,7 @@ validate_attribs() { */ CPT(RenderAttrib) RenderAttrib:: return_new(RenderAttrib *attrib) { - nassertr(attrib != (RenderAttrib *)NULL, attrib); + nassertr(attrib != nullptr, attrib); if (!uniquify_attribs) { attrib->calc_hash(); return attrib; @@ -350,7 +336,7 @@ return_new(RenderAttrib *attrib) { */ CPT(RenderAttrib) RenderAttrib:: return_unique(RenderAttrib *attrib) { - nassertr(attrib != (RenderAttrib *)NULL, attrib); + nassertr(attrib != nullptr, attrib); attrib->calc_hash(); diff --git a/panda/src/pgraph/renderAttrib.h b/panda/src/pgraph/renderAttrib.h index 5bf54cf32f..98b9de315c 100644 --- a/panda/src/pgraph/renderAttrib.h +++ b/panda/src/pgraph/renderAttrib.h @@ -51,13 +51,13 @@ class RenderState; class EXPCL_PANDA_PGRAPH RenderAttrib : public TypedWritableReferenceCount { protected: RenderAttrib(); -private: - RenderAttrib(const RenderAttrib ©); - void operator = (const RenderAttrib ©); public: + RenderAttrib(const RenderAttrib ©) = delete; virtual ~RenderAttrib(); + RenderAttrib &operator = (const RenderAttrib ©) = delete; + PUBLISHED: INLINE CPT(RenderAttrib) compose(const RenderAttrib *other) const; INLINE CPT(RenderAttrib) invert_compose(const RenderAttrib *other) const; @@ -72,13 +72,13 @@ PUBLISHED: INLINE size_t get_hash() const; INLINE CPT(RenderAttrib) get_unique() const; - virtual bool unref() const FINAL; + virtual bool unref() const final; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; static int get_num_attribs(); - static void list_attribs(ostream &out); + static void list_attribs(std::ostream &out); static int garbage_collect(); static bool validate_attribs(); @@ -170,7 +170,7 @@ protected: virtual size_t get_hash_impl() const; virtual CPT(RenderAttrib) compose_impl(const RenderAttrib *other) const; virtual CPT(RenderAttrib) invert_compose_impl(const RenderAttrib *other) const; - void output_comparefunc(ostream &out, PandaCompareFunc fn) const; + void output_comparefunc(std::ostream &out, PandaCompareFunc fn) const; public: INLINE static int register_slot(TypeHandle type_handle, int sort, @@ -185,7 +185,7 @@ public: private: // This mutex protects _attribs. static LightReMutex *_attribs_lock; - typedef SimpleHashMap > Attribs; + typedef SimpleHashMap > Attribs; static Attribs *_attribs; int _saved_entry; @@ -226,7 +226,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const RenderAttrib &attrib) { +INLINE std::ostream &operator << (std::ostream &out, const RenderAttrib &attrib) { attrib.output(out); return out; } diff --git a/panda/src/pgraph/renderAttribRegistry.I b/panda/src/pgraph/renderAttribRegistry.I index 1a807794a9..e90c306821 100644 --- a/panda/src/pgraph/renderAttribRegistry.I +++ b/panda/src/pgraph/renderAttribRegistry.I @@ -24,19 +24,6 @@ get_slot(TypeHandle type_handle) const { return _slots_by_type[(size_t)type_index]; } -/** - * Returns the maximum number that any slot number is allowed to grow. - * Actually, this number will be one higher than the highest possible slot - * number. This puts an upper bound on the number of RenderAttrib slots that - * may be allocated, and allows other code to define an array of slots. - * - * This number will not change during the lifetime of the application. - */ -CONSTEXPR int RenderAttribRegistry:: -get_max_slots() { - return _max_slots; -} - /** * Returns the number of RenderAttrib slots that have been allocated. This is * one more than the highest slot number in use. @@ -99,7 +86,7 @@ get_sorted_slot(int n) const { */ INLINE RenderAttribRegistry *RenderAttribRegistry:: get_global_ptr() { - if (_global_ptr == (RenderAttribRegistry *)NULL) { + if (_global_ptr == nullptr) { init_global_ptr(); } return _global_ptr; diff --git a/panda/src/pgraph/renderAttribRegistry.cxx b/panda/src/pgraph/renderAttribRegistry.cxx index 4c27e4c0a7..939f9753f7 100644 --- a/panda/src/pgraph/renderAttribRegistry.cxx +++ b/panda/src/pgraph/renderAttribRegistry.cxx @@ -28,7 +28,7 @@ RenderAttribRegistry() { // Reserve slot 0 for TypeHandle::none(), and for types that exceed // max_slots. - _registry.push_back(RegistryNode(TypeHandle::none(), 0, NULL)); + _registry.push_back(RegistryNode(TypeHandle::none(), 0, nullptr)); } /** @@ -86,7 +86,7 @@ register_slot(TypeHandle type_handle, int sort, RenderAttrib *default_attrib) { // it even if the state cache is disabled, because we can't read the // state_cache config variable yet at this time. It probably doesn't hurt // to have these 32 entries around in the attrib cache. - if (default_attrib != (RenderAttrib *)NULL) { + if (default_attrib != nullptr) { default_attrib->calc_hash(); if (default_attrib->_saved_entry == -1) { @@ -105,7 +105,7 @@ register_slot(TypeHandle type_handle, int sort, RenderAttrib *default_attrib) { _registry.push_back(RegistryNode(type_handle, sort, default_attrib)); _sorted_slots.push_back(slot); - ::sort(_sorted_slots.begin(), _sorted_slots.end(), SortSlots(this)); + std::sort(_sorted_slots.begin(), _sorted_slots.end(), SortSlots(this)); return slot; } @@ -123,7 +123,7 @@ set_slot_sort(int slot, int sort) { for (int i = 1; i < (int)_registry.size(); ++i) { _sorted_slots.push_back(i); } - ::sort(_sorted_slots.begin(), _sorted_slots.end(), SortSlots(this)); + std::sort(_sorted_slots.begin(), _sorted_slots.end(), SortSlots(this)); } /** diff --git a/panda/src/pgraph/renderAttribRegistry.h b/panda/src/pgraph/renderAttribRegistry.h index 59194fd278..c7cf71b044 100644 --- a/panda/src/pgraph/renderAttribRegistry.h +++ b/panda/src/pgraph/renderAttribRegistry.h @@ -54,7 +54,7 @@ public: PUBLISHED: INLINE int get_slot(TypeHandle type_handle) const; - static CONSTEXPR int get_max_slots(); + static constexpr int get_max_slots() { return _max_slots; } INLINE int get_num_slots() const; INLINE TypeHandle get_slot_type(int slot) const; diff --git a/panda/src/pgraph/renderEffect.cxx b/panda/src/pgraph/renderEffect.cxx index 09572cc445..da052c0073 100644 --- a/panda/src/pgraph/renderEffect.cxx +++ b/panda/src/pgraph/renderEffect.cxx @@ -16,7 +16,7 @@ #include "indent.h" #include "config_pgraph.h" -RenderEffect::Effects *RenderEffect::_effects = NULL; +RenderEffect::Effects *RenderEffect::_effects = nullptr; TypeHandle RenderEffect::_type_handle; /** @@ -24,7 +24,7 @@ TypeHandle RenderEffect::_type_handle; */ RenderEffect:: RenderEffect() { - if (_effects == (Effects *)NULL) { + if (_effects == nullptr) { // Make sure the global _effects map is allocated. This only has to be // done once. We could make this map static, but then we run into // problems if anyone creates a RenderState object at static init time; it @@ -35,22 +35,6 @@ RenderEffect() { _saved_entry = _effects->end(); } -/** - * RenderEffects are not meant to be copied. - */ -RenderEffect:: -RenderEffect(const RenderEffect &) { - nassertv(false); -} - -/** - * RenderEffects are not meant to be copied. - */ -void RenderEffect:: -operator = (const RenderEffect &) { - nassertv(false); -} - /** * The destructor is responsible for removing the RenderEffect from the global * set if it is there. @@ -167,7 +151,7 @@ adjust_transform(CPT(TransformState) &, CPT(TransformState) &, * */ void RenderEffect:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type(); } @@ -175,7 +159,7 @@ output(ostream &out) const { * */ void RenderEffect:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << *this << "\n"; } @@ -185,7 +169,7 @@ write(ostream &out, int indent_level) const { */ int RenderEffect:: get_num_effects() { - if (_effects == (Effects *)NULL) { + if (_effects == nullptr) { return 0; } return _effects->size(); @@ -197,7 +181,7 @@ get_num_effects() { * prepared. */ void RenderEffect:: -list_effects(ostream &out) { +list_effects(std::ostream &out) { out << _effects->size() << " effects:\n"; Effects::const_iterator si; for (si = _effects->begin(); si != _effects->end(); ++si) { @@ -247,7 +231,7 @@ validate_effects() { */ CPT(RenderEffect) RenderEffect:: return_new(RenderEffect *effect) { - nassertr(effect != (RenderEffect *)NULL, effect); + nassertr(effect != nullptr, effect); // This should be a newly allocated pointer, not one that was used for // anything else. @@ -263,7 +247,7 @@ return_new(RenderEffect *effect) { // of this function if no one else uses it. CPT(RenderEffect) pt_effect = effect; - pair result = _effects->insert(effect); + std::pair result = _effects->insert(effect); if (result.second) { // The effect was inserted; save the iterator and return the input effect. effect->_saved_entry = result.first; diff --git a/panda/src/pgraph/renderEffect.h b/panda/src/pgraph/renderEffect.h index d739f5cee7..f3d3f8bd93 100644 --- a/panda/src/pgraph/renderEffect.h +++ b/panda/src/pgraph/renderEffect.h @@ -48,13 +48,13 @@ class PandaNode; class EXPCL_PANDA_PGRAPH RenderEffect : public TypedWritableReferenceCount { protected: RenderEffect(); -private: - RenderEffect(const RenderEffect ©); - void operator = (const RenderEffect ©); public: + RenderEffect(const RenderEffect ©) = delete; virtual ~RenderEffect(); + RenderEffect &operator = (const RenderEffect ©) = delete; + virtual bool safe_to_transform() const; virtual CPT(TransformState) prepare_flatten_transform(const TransformState *net_transform) const; virtual bool safe_to_combine() const; @@ -73,11 +73,11 @@ public: PUBLISHED: INLINE int compare_to(const RenderEffect &other) const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; static int get_num_effects(); - static void list_effects(ostream &out); + static void list_effects(std::ostream &out); static bool validate_effects(); protected: @@ -118,7 +118,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const RenderEffect &effect) { +INLINE std::ostream &operator << (std::ostream &out, const RenderEffect &effect) { effect.output(out); return out; } diff --git a/panda/src/pgraph/renderEffects.I b/panda/src/pgraph/renderEffects.I index 23c00f9a3b..a0ae6af279 100644 --- a/panda/src/pgraph/renderEffects.I +++ b/panda/src/pgraph/renderEffects.I @@ -37,7 +37,7 @@ Effect() { INLINE RenderEffects::Effect:: Effect(TypeHandle type) : _type(type), - _effect(NULL) + _effect(nullptr) { } diff --git a/panda/src/pgraph/renderEffects.cxx b/panda/src/pgraph/renderEffects.cxx index 639f11be9b..3c1b1066bb 100644 --- a/panda/src/pgraph/renderEffects.cxx +++ b/panda/src/pgraph/renderEffects.cxx @@ -29,8 +29,8 @@ #include -LightReMutex *RenderEffects::_states_lock = NULL; -RenderEffects::States *RenderEffects::_states = NULL; +LightReMutex *RenderEffects::_states_lock = nullptr; +RenderEffects::States *RenderEffects::_states = nullptr; CPT(RenderEffects) RenderEffects::_empty_state; TypeHandle RenderEffects::_type_handle; @@ -41,29 +41,13 @@ TypeHandle RenderEffects::_type_handle; */ RenderEffects:: RenderEffects() : _lock("RenderEffects") { - if (_states == (States *)NULL) { + if (_states == nullptr) { init_states(); } _saved_entry = _states->end(); _flags = 0; } -/** - * RenderEffects are not meant to be copied. - */ -RenderEffects:: -RenderEffects(const RenderEffects &) { - nassertv(false); -} - -/** - * RenderEffects are not meant to be copied. - */ -void RenderEffects:: -operator = (const RenderEffects &) { - nassertv(false); -} - /** * The destructor is responsible for removing the RenderEffects from the * global set if it is there. @@ -139,8 +123,8 @@ xform(const LMatrix4 &mat) const { } RenderEffects *new_state = new RenderEffects; - back_insert_iterator result = - back_inserter(new_state->_effects); + std::back_insert_iterator result = + std::back_inserter(new_state->_effects); Effects::const_iterator ai; for (ai = _effects.begin(); ai != _effects.end(); ++ai) { @@ -192,7 +176,7 @@ CPT(RenderEffects) RenderEffects:: make_empty() { // The empty state is asked for so often, we make it a special case and // store a pointer forever once we find it the first time. - if (_empty_state == (RenderEffects *)NULL) { + if (_empty_state == nullptr) { RenderEffects *state = new RenderEffects; _empty_state = return_new(state); } @@ -267,8 +251,8 @@ make(const RenderEffect *effect1, CPT(RenderEffects) RenderEffects:: add_effect(const RenderEffect *effect) const { RenderEffects *new_state = new RenderEffects; - back_insert_iterator result = - back_inserter(new_state->_effects); + std::back_insert_iterator result = + std::back_inserter(new_state->_effects); Effect new_effect(effect); Effects::const_iterator ai = _effects.begin(); @@ -304,8 +288,8 @@ add_effect(const RenderEffect *effect) const { CPT(RenderEffects) RenderEffects:: remove_effect(TypeHandle type) const { RenderEffects *new_state = new RenderEffects; - back_insert_iterator result = - back_inserter(new_state->_effects); + std::back_insert_iterator result = + std::back_inserter(new_state->_effects); Effects::const_iterator ai = _effects.begin(); @@ -331,7 +315,7 @@ get_effect(TypeHandle type) const { if (ai != _effects.end()) { return (*ai)._effect; } - return NULL; + return nullptr; } /** @@ -367,7 +351,7 @@ unref() const { * */ void RenderEffects:: -output(ostream &out) const { +output(std::ostream &out) const { out << "E:"; if (_effects.empty()) { out << "(empty)"; @@ -388,7 +372,7 @@ output(ostream &out) const { * */ void RenderEffects:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << _effects.size() << " effects:\n"; Effects::const_iterator ai; for (ai = _effects.begin(); ai != _effects.end(); ++ai) { @@ -403,7 +387,7 @@ write(ostream &out, int indent_level) const { */ int RenderEffects:: get_num_states() { - if (_states == (States *)NULL) { + if (_states == nullptr) { return 0; } LightReMutexHolder holder(*_states_lock); @@ -416,7 +400,7 @@ get_num_states() { * prepared. */ void RenderEffects:: -list_states(ostream &out) { +list_states(std::ostream &out) { out << _states->size() << " states:\n"; States::const_iterator si; for (si = _states->begin(); si != _states->end(); ++si) { @@ -530,7 +514,7 @@ init_states() { */ CPT(RenderEffects) RenderEffects:: return_new(RenderEffects *state) { - nassertr(state != (RenderEffects *)NULL, state); + nassertr(state != nullptr, state); #ifndef NDEBUG if (!state_cache) { @@ -554,7 +538,7 @@ return_new(RenderEffects *state) { // of this function if no one else uses it. CPT(RenderEffects) pt_state = state; - pair result = _states->insert(state); + std::pair result = _states->insert(state); if (result.second) { // The state was inserted; save the iterator and return the input state. state->_saved_entry = result.first; @@ -596,7 +580,7 @@ determine_decal() { } const RenderEffect *effect = get_effect(DecalEffect::get_class_type()); - if (effect != (const RenderEffect *)NULL) { + if (effect != nullptr) { _flags |= F_has_decal; } _flags |= F_checked_decal; @@ -614,7 +598,7 @@ determine_show_bounds() { } const RenderEffect *effect = get_effect(ShowBoundsEffect::get_class_type()); - if (effect != (const RenderEffect *)NULL) { + if (effect != nullptr) { _flags |= F_has_show_bounds; const ShowBoundsEffect *sba = DCAST(ShowBoundsEffect, effect); if (sba->get_tight()) { @@ -710,7 +694,7 @@ complete_pointers(TypedWritable **p_list, BamReader *manager) { Effect &effect = _effects[i]; effect._effect = DCAST(RenderEffect, p_list[pi++]); - if (effect._effect == (RenderEffect *)NULL) { + if (effect._effect == nullptr) { // Remove this bogus RenderEffect pointer (it must have been from an // unwritable class). _effects.erase(_effects.begin() + i); diff --git a/panda/src/pgraph/renderEffects.h b/panda/src/pgraph/renderEffects.h index 1e54c30533..404a402975 100644 --- a/panda/src/pgraph/renderEffects.h +++ b/panda/src/pgraph/renderEffects.h @@ -42,13 +42,12 @@ class EXPCL_PANDA_PGRAPH RenderEffects : public TypedWritableReferenceCount { protected: RenderEffects(); -private: - RenderEffects(const RenderEffects ©); - void operator = (const RenderEffects ©); - public: + RenderEffects(const RenderEffects ©) = delete; virtual ~RenderEffects(); + RenderEffects &operator = (const RenderEffects ©) = delete; + bool safe_to_transform() const; virtual CPT(TransformState) prepare_flatten_transform(const TransformState *net_transform) const; bool safe_to_combine() const; @@ -86,11 +85,11 @@ PUBLISHED: virtual bool unref() const; - void output(ostream &out) const; - void write(ostream &out, int indent_level) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level) const; static int get_num_states(); - static void list_states(ostream &out); + static void list_states(std::ostream &out); static bool validate_states(); public: @@ -198,7 +197,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const RenderEffects &state) { +INLINE std::ostream &operator << (std::ostream &out, const RenderEffects &state) { state.output(out); return out; } diff --git a/panda/src/pgraph/renderModeAttrib.cxx b/panda/src/pgraph/renderModeAttrib.cxx index efdf3e7434..1b2b41c9ad 100644 --- a/panda/src/pgraph/renderModeAttrib.cxx +++ b/panda/src/pgraph/renderModeAttrib.cxx @@ -60,7 +60,7 @@ make_default() { * */ void RenderModeAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; switch (get_mode()) { case M_unchanged: diff --git a/panda/src/pgraph/renderModeAttrib.h b/panda/src/pgraph/renderModeAttrib.h index 21a32ee5de..9684ee5176 100644 --- a/panda/src/pgraph/renderModeAttrib.h +++ b/panda/src/pgraph/renderModeAttrib.h @@ -72,7 +72,7 @@ PUBLISHED: MAKE_PROPERTY(wireframe_color, get_wireframe_color); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/renderState.I b/panda/src/pgraph/renderState.I index 185b18b24d..d232ecb00a 100644 --- a/panda/src/pgraph/renderState.I +++ b/panda/src/pgraph/renderState.I @@ -67,7 +67,7 @@ remove_attrib(TypeHandle type) const { */ INLINE bool RenderState:: has_attrib(TypeHandle type) const { - return get_attrib(type) != (RenderAttrib *)NULL; + return get_attrib(type) != nullptr; } /** @@ -76,7 +76,7 @@ has_attrib(TypeHandle type) const { */ INLINE bool RenderState:: has_attrib(int slot) const { - return get_attrib(slot) != (RenderAttrib *)NULL; + return get_attrib(slot) != nullptr; } /** @@ -105,7 +105,7 @@ get_attrib(int slot) const { */ INLINE const RenderAttrib *RenderState:: get_attrib_def(int slot) const { - if (_attributes[slot]._attrib != (RenderAttrib *)NULL) { + if (_attributes[slot]._attrib != nullptr) { return _attributes[slot]._attrib; } RenderAttribRegistry *reg = RenderAttribRegistry::quick_get_global_ptr(); @@ -448,9 +448,9 @@ operator = (const Attribute ©) { INLINE int RenderState::Attribute:: compare_to(const Attribute &other) const { if (_attrib != other._attrib) { - if (_attrib == NULL) { + if (_attrib == nullptr) { return -1; - } else if (other._attrib == NULL) { + } else if (other._attrib == nullptr) { return 1; } @@ -483,24 +483,35 @@ flush_level() { #ifndef CPPPARSER /** - * Handy templated version of get_attrib that costs to the right type. + * Handy templated version of get_attrib that casts to the right type. * Returns true if the attribute was present, false otherwise. */ template INLINE bool RenderState:: get_attrib(const AttribType *&attrib) const { attrib = (const AttribType *)get_attrib((int)AttribType::get_class_slot()); - return (attrib != (const AttribType *)NULL); + return (attrib != nullptr); +} +template +INLINE bool RenderState:: +get_attrib(CPT(AttribType) &attrib) const { + attrib = (const AttribType *)get_attrib((int)AttribType::get_class_slot()); + return (attrib != nullptr); } /** - * Handy templated version of get_attrib_def that costs to the right type. + * Handy templated version of get_attrib_def that casts to the right type. */ template INLINE void RenderState:: get_attrib_def(const AttribType *&attrib) const { attrib = (const AttribType *)get_attrib_def((int)AttribType::get_class_slot()); } +template +INLINE void RenderState:: +get_attrib_def(CPT(AttribType) &attrib) const { + attrib = (const AttribType *)get_attrib_def((int)AttribType::get_class_slot()); +} #endif // CPPPARSER /** diff --git a/panda/src/pgraph/renderState.cxx b/panda/src/pgraph/renderState.cxx index 6f035a6557..927d1e7073 100644 --- a/panda/src/pgraph/renderState.cxx +++ b/panda/src/pgraph/renderState.cxx @@ -36,9 +36,11 @@ #include "thread.h" #include "renderAttribRegistry.h" -LightReMutex *RenderState::_states_lock = NULL; -RenderState::States *RenderState::_states = NULL; -const RenderState *RenderState::_empty_state = NULL; +using std::ostream; + +LightReMutex *RenderState::_states_lock = nullptr; +RenderState::States *RenderState::_states = nullptr; +const RenderState *RenderState::_empty_state = nullptr; UpdateSeq RenderState::_last_cycle_detect; size_t RenderState::_garbage_index = 0; @@ -66,14 +68,14 @@ RenderState() : _flags(0), _lock("RenderState") { - if (_states == (States *)NULL) { + if (_states == nullptr) { init_states(); } _saved_entry = -1; _last_mi = -1; _cache_stats.add_num_states(1); - _read_overrides = NULL; - _generated_shader = NULL; + _read_overrides = nullptr; + _generated_shader = nullptr; #ifdef DO_MEMORY_USAGE MemoryUsage::update_type(this, this); @@ -97,22 +99,14 @@ RenderState(const RenderState ©) : _saved_entry = -1; _last_mi = -1; _cache_stats.add_num_states(1); - _read_overrides = NULL; - _generated_shader = NULL; + _read_overrides = nullptr; + _generated_shader = nullptr; #ifdef DO_MEMORY_USAGE MemoryUsage::update_type(this, this); #endif } -/** - * RenderStates are not meant to be copied. - */ -void RenderState:: -operator = (const RenderState &) { - nassertv(false); -} - /** * The destructor is responsible for removing the RenderState from the global * set if it is there. @@ -177,7 +171,7 @@ compare_sort(const RenderState &other) const { int num_sorted_slots = reg->get_num_sorted_slots(); for (int n = 0; n < num_sorted_slots; ++n) { int slot = reg->get_sorted_slot(n); - nassertr((_attributes[slot]._attrib != NULL) == _filled_slots.get_bit(slot), 0); + nassertr((_attributes[slot]._attrib != nullptr) == _filled_slots.get_bit(slot), 0); const RenderAttrib *a = _attributes[slot]._attrib; const RenderAttrib *b = other._attributes[slot]._attrib; @@ -222,7 +216,7 @@ cull_callback(CullTraverser *trav, const CullTraverserData &data) const { int slot = mask.get_lowest_on_bit(); while (slot >= 0) { const Attribute &attrib = _attributes[slot]; - nassertr(attrib._attrib != NULL, false); + nassertr(attrib._attrib != nullptr, false); if (!attrib._attrib->cull_callback(trav, data)) { return false; } @@ -370,7 +364,7 @@ compose(const RenderState *other) const { int index = _composition_cache.find(other); if (index != -1) { Composition &comp = ((RenderState *)this)->_composition_cache.modify_data(index); - if (comp._result == (const RenderState *)NULL) { + if (comp._result == nullptr) { // Well, it wasn't cached already, but we already had an entry (probably // created for the reverse direction), so use the same entry to store // the new result. @@ -405,7 +399,7 @@ compose(const RenderState *other) const { if (other != this) { _cache_stats.add_total_size(1); _cache_stats.inc_adds(other->_composition_cache.is_empty()); - ((RenderState *)other)->_composition_cache[this]._result = NULL; + ((RenderState *)other)->_composition_cache[this]._result = nullptr; } if (result != (const RenderState *)this) { @@ -459,7 +453,7 @@ invert_compose(const RenderState *other) const { int index = _invert_composition_cache.find(other); if (index != -1) { Composition &comp = ((RenderState *)this)->_invert_composition_cache.modify_data(index); - if (comp._result == (const RenderState *)NULL) { + if (comp._result == nullptr) { // Well, it wasn't cached already, but we already had an entry (probably // created for the reverse direction), so use the same entry to store // the new result. @@ -493,7 +487,7 @@ invert_compose(const RenderState *other) const { if (other != this) { _cache_stats.add_total_size(1); _cache_stats.inc_adds(other->_invert_composition_cache.is_empty()); - ((RenderState *)other)->_invert_composition_cache[this]._result = NULL; + ((RenderState *)other)->_invert_composition_cache[this]._result = nullptr; } if (result != (const RenderState *)this) { @@ -567,7 +561,7 @@ set_attrib(const RenderAttrib *attrib, int override) const { */ CPT(RenderState) RenderState:: remove_attrib(int slot) const { - if (_attributes[slot]._attrib == NULL) { + if (_attributes[slot]._attrib == nullptr) { // Already removed. return this; } @@ -578,7 +572,7 @@ remove_attrib(int slot) const { } RenderState *new_state = new RenderState(*this); - new_state->_attributes[slot].set(NULL, 0); + new_state->_attributes[slot].set(nullptr, 0); new_state->_filled_slots.clear_bit(slot); return return_new(new_state); } @@ -597,8 +591,8 @@ adjust_all_priorities(int adjustment) const { int slot = mask.get_lowest_on_bit(); while (slot >= 0) { Attribute &attrib = new_state->_attributes[slot]; - nassertr(attrib._attrib != (RenderAttrib *)NULL, this); - attrib._override = max(attrib._override + adjustment, 0); + nassertr(attrib._attrib != nullptr, this); + attrib._override = std::max(attrib._override + adjustment, 0); mask.clear_bit(slot); slot = mask.get_lowest_on_bit(); @@ -672,7 +666,7 @@ output(ostream &out) const { int slot = mask.get_lowest_on_bit(); while (slot >= 0) { const Attribute &attrib = _attributes[slot]; - nassertv(attrib._attrib != (RenderAttrib *)NULL); + nassertv(attrib._attrib != nullptr); out << sep << attrib._attrib->get_type(); sep = " "; @@ -697,7 +691,7 @@ write(ostream &out, int indent_level) const { int slot = mask.get_lowest_on_bit(); while (slot >= 0) { const Attribute &attrib = _attributes[slot]; - nassertv(attrib._attrib != (RenderAttrib *)NULL); + nassertv(attrib._attrib != nullptr); attrib._attrib->write(out, indent_level); mask.clear_bit(slot); @@ -722,7 +716,7 @@ get_max_priority() { */ int RenderState:: get_num_states() { - if (_states == (States *)NULL) { + if (_states == nullptr) { return 0; } LightReMutexHolder holder(*_states_lock); @@ -744,7 +738,7 @@ get_num_states() { */ int RenderState:: get_num_unused_states() { - if (_states == (States *)NULL) { + if (_states == nullptr) { return 0; } LightReMutexHolder holder(*_states_lock); @@ -762,9 +756,9 @@ get_num_unused_states() { size_t cache_size = state->_composition_cache.get_num_entries(); for (i = 0; i < cache_size; ++i) { const RenderState *result = state->_composition_cache.get_data(i)._result; - if (result != (const RenderState *)NULL && result != state) { + if (result != nullptr && result != state) { // Here's a RenderState that's recorded in the cache. Count it. - pair ir = + std::pair ir = state_count.insert(StateCount::value_type(result, 1)); if (!ir.second) { // If the above insert operation fails, then it's already in the @@ -776,8 +770,8 @@ get_num_unused_states() { cache_size = state->_invert_composition_cache.get_num_entries(); for (i = 0; i < cache_size; ++i) { const RenderState *result = state->_invert_composition_cache.get_data(i)._result; - if (result != (const RenderState *)NULL && result != state) { - pair ir = + if (result != nullptr && result != state) { + std::pair ir = state_count.insert(StateCount::value_type(result, 1)); if (!ir.second) { (*(ir.first)).second++; @@ -827,7 +821,7 @@ get_num_unused_states() { */ int RenderState:: clear_cache() { - if (_states == (States *)NULL) { + if (_states == nullptr) { return 0; } LightReMutexHolder holder(*_states_lock); @@ -860,7 +854,7 @@ clear_cache() { size_t cache_size = (int)state->_composition_cache.get_num_entries(); for (i = 0; i < cache_size; ++i) { const RenderState *result = state->_composition_cache.get_data(i)._result; - if (result != (const RenderState *)NULL && result != state) { + if (result != nullptr && result != state) { result->cache_unref(); nassertr(result->get_ref_count() > 0, 0); } @@ -871,7 +865,7 @@ clear_cache() { cache_size = (int)state->_invert_composition_cache.get_num_entries(); for (i = 0; i < cache_size; ++i) { const RenderState *result = state->_invert_composition_cache.get_data(i)._result; - if (result != (const RenderState *)NULL && result != state) { + if (result != nullptr && result != state) { result->cache_unref(); nassertr(result->get_ref_count() > 0, 0); } @@ -901,7 +895,7 @@ int RenderState:: garbage_collect() { int num_attribs = RenderAttrib::garbage_collect(); - if (_states == (States *)NULL || !garbage_collect_states) { + if (_states == nullptr || !garbage_collect_states) { return num_attribs; } @@ -912,7 +906,7 @@ garbage_collect() { // How many elements to process this pass? size_t size = orig_size; - size_t num_this_pass = max(0, int(size * garbage_collect_states_rate)); + size_t num_this_pass = std::max(0, int(size * garbage_collect_states_rate)); if (num_this_pass <= 0) { return num_attribs; } @@ -924,7 +918,7 @@ garbage_collect() { si = 0; } - num_this_pass = min(num_this_pass, size); + num_this_pass = std::min(num_this_pass, size); size_t stop_at_element = (si + num_this_pass) % size; do { @@ -1007,7 +1001,7 @@ clear_munger_cache() { */ void RenderState:: list_cycles(ostream &out) { - if (_states == (States *)NULL) { + if (_states == nullptr) { return; } LightReMutexHolder holder(*_states_lock); @@ -1084,7 +1078,7 @@ list_cycles(ostream &out) { */ void RenderState:: list_states(ostream &out) { - if (_states == (States *)NULL) { + if (_states == nullptr) { out << "0 states:\n"; return; } @@ -1106,7 +1100,7 @@ list_states(ostream &out) { */ bool RenderState:: validate_states() { - if (_states == (States *)NULL) { + if (_states == nullptr) { return true; } @@ -1202,7 +1196,7 @@ validate_filled_slots() const { int max_slots = reg->get_max_slots(); for (int slot = 1; slot < max_slots; ++slot) { const Attribute &attribute = _attributes[slot]; - if (attribute._attrib != (RenderAttrib *)NULL) { + if (attribute._attrib != nullptr) { mask.set_bit(slot); } } @@ -1221,7 +1215,7 @@ do_calc_hash() { int slot = mask.get_lowest_on_bit(); while (slot >= 0) { const Attribute &attrib = _attributes[slot]; - nassertv(attrib._attrib != (RenderAttrib *)NULL); + nassertv(attrib._attrib != nullptr); _hash = pointer_hash::add_hash(_hash, attrib._attrib); _hash = int_hash::add_hash(_hash, attrib._override); @@ -1241,12 +1235,12 @@ do_calc_hash() { */ CPT(RenderState) RenderState:: return_new(RenderState *state) { - nassertr(state != (RenderState *)NULL, state); + nassertr(state != nullptr, state); // Make sure we don't have anything in the 0 slot. If we did, that would // indicate an uninitialized slot number. #ifndef NDEBUG - if (state->_attributes[0]._attrib != (RenderAttrib *)NULL) { + if (state->_attributes[0]._attrib != nullptr) { const RenderAttrib *attrib = state->_attributes[0]._attrib; if (attrib->get_type() == TypeHandle::none()) { ((RenderAttrib *)attrib)->force_init_type(); @@ -1263,7 +1257,7 @@ return_new(RenderState *state) { } } #endif - state->_attributes[0]._attrib = NULL; + state->_attributes[0]._attrib = nullptr; state->_filled_slots.clear_bit(0); #ifndef NDEBUG @@ -1287,7 +1281,7 @@ return_new(RenderState *state) { */ CPT(RenderState) RenderState:: return_unique(RenderState *state) { - nassertr(state != (RenderState *)NULL, NULL); + nassertr(state != nullptr, nullptr); if (!state_cache) { return state; @@ -1314,7 +1308,7 @@ return_unique(RenderState *state) { int slot = mask.get_lowest_on_bit(); while (slot >= 0) { Attribute &attrib = state->_attributes[slot]; - nassertd(attrib._attrib != (RenderAttrib *)NULL) continue; + nassertd(attrib._attrib != nullptr) continue; attrib._attrib = attrib._attrib->get_unique(); mask.clear_bit(slot); slot = mask.get_lowest_on_bit(); @@ -1365,12 +1359,12 @@ do_compose(const RenderState *other) const { const Attribute &b = other->_attributes[slot]; Attribute &result = new_state->_attributes[slot]; - if (a._attrib == NULL) { - nassertr(b._attrib != NULL, this); + if (a._attrib == nullptr) { + nassertr(b._attrib != nullptr, this); // B wins. result = b; - } else if (b._attrib == NULL) { + } else if (b._attrib == nullptr) { // A wins. result = a; @@ -1419,12 +1413,12 @@ do_invert_compose(const RenderState *other) const { const Attribute &b = other->_attributes[slot]; Attribute &result = new_state->_attributes[slot]; - if (a._attrib == NULL) { - nassertr(b._attrib != NULL, this); + if (a._attrib == nullptr) { + nassertr(b._attrib != nullptr, this); // B wins. result = b; - } else if (b._attrib == NULL) { + } else if (b._attrib == nullptr) { // A wins. Invert it. RenderAttribRegistry *reg = RenderAttribRegistry::quick_get_global_ptr(); result.set(a._attrib->invert_compose(reg->get_slot_default(slot)), 0); @@ -1449,7 +1443,7 @@ detect_and_break_cycles() { PStatTimer timer(_state_break_cycles_pcollector); ++_last_cycle_detect; - if (r_detect_cycles(this, this, 1, _last_cycle_detect, NULL)) { + if (r_detect_cycles(this, this, 1, _last_cycle_detect, nullptr)) { // Ok, we have a cycle. This will be a leak unless we break the cycle by // freeing the cache on this object. if (pgraph_cat.is_debug()) { @@ -1460,7 +1454,7 @@ detect_and_break_cycles() { ((RenderState *)this)->remove_cache_pointers(); } else { ++_last_cycle_detect; - if (r_detect_reverse_cycles(this, this, 1, _last_cycle_detect, NULL)) { + if (r_detect_reverse_cycles(this, this, 1, _last_cycle_detect, nullptr)) { if (pgraph_cat.is_debug()) { pgraph_cat.debug() << "Breaking cycle involving " << (*this) << "\n"; @@ -1497,11 +1491,11 @@ r_detect_cycles(const RenderState *start_state, size_t cache_size = current_state->_composition_cache.get_num_entries(); for (i = 0; i < cache_size; ++i) { const RenderState *result = current_state->_composition_cache.get_data(i)._result; - if (result != (const RenderState *)NULL) { + if (result != nullptr) { if (r_detect_cycles(start_state, result, length + 1, this_seq, cycle_desc)) { // Cycle detected. - if (cycle_desc != (CompositionCycleDesc *)NULL) { + if (cycle_desc != nullptr) { const RenderState *other = current_state->_composition_cache.get_key(i); CompositionCycleDescEntry entry(other, result, false); cycle_desc->push_back(entry); @@ -1514,11 +1508,11 @@ r_detect_cycles(const RenderState *start_state, cache_size = current_state->_invert_composition_cache.get_num_entries(); for (i = 0; i < cache_size; ++i) { const RenderState *result = current_state->_invert_composition_cache.get_data(i)._result; - if (result != (const RenderState *)NULL) { + if (result != nullptr) { if (r_detect_cycles(start_state, result, length + 1, this_seq, cycle_desc)) { // Cycle detected. - if (cycle_desc != (CompositionCycleDesc *)NULL) { + if (cycle_desc != nullptr) { const RenderState *other = current_state->_invert_composition_cache.get_key(i); CompositionCycleDescEntry entry(other, result, true); cycle_desc->push_back(entry); @@ -1561,11 +1555,11 @@ r_detect_reverse_cycles(const RenderState *start_state, nassertr(oi != -1, false); const RenderState *result = other->_composition_cache.get_data(oi)._result; - if (result != (const RenderState *)NULL) { + if (result != nullptr) { if (r_detect_reverse_cycles(start_state, result, length + 1, this_seq, cycle_desc)) { // Cycle detected. - if (cycle_desc != (CompositionCycleDesc *)NULL) { + if (cycle_desc != nullptr) { const RenderState *other = current_state->_composition_cache.get_key(i); CompositionCycleDescEntry entry(other, result, false); cycle_desc->push_back(entry); @@ -1584,11 +1578,11 @@ r_detect_reverse_cycles(const RenderState *start_state, nassertr(oi != -1, false); const RenderState *result = other->_invert_composition_cache.get_data(oi)._result; - if (result != (const RenderState *)NULL) { + if (result != nullptr) { if (r_detect_reverse_cycles(start_state, result, length + 1, this_seq, cycle_desc)) { // Cycle detected. - if (cycle_desc != (CompositionCycleDesc *)NULL) { + if (cycle_desc != nullptr) { const RenderState *other = current_state->_invert_composition_cache.get_key(i); CompositionCycleDescEntry entry(other, result, false); cycle_desc->push_back(entry); @@ -1690,7 +1684,7 @@ remove_cache_pointers() { // It's finally safe to let our held pointers go away. This may have // cascading effects as other RenderState objects are destructed, but // there will be no harm done if they destruct now. - if (ocomp._result != (const RenderState *)NULL && ocomp._result != other) { + if (ocomp._result != nullptr && ocomp._result != other) { cache_unref_delete(ocomp._result); } } @@ -1698,7 +1692,7 @@ remove_cache_pointers() { // It's finally safe to let our held pointers go away. (See comment // above.) - if (comp._result != (const RenderState *)NULL && comp._result != this) { + if (comp._result != nullptr && comp._result != this) { cache_unref_delete(comp._result); } } @@ -1719,12 +1713,12 @@ remove_cache_pointers() { other->_invert_composition_cache.remove_element(oi); _cache_stats.add_total_size(-1); _cache_stats.inc_dels(); - if (ocomp._result != (const RenderState *)NULL && ocomp._result != other) { + if (ocomp._result != nullptr && ocomp._result != other) { cache_unref_delete(ocomp._result); } } } - if (comp._result != (const RenderState *)NULL && comp._result != this) { + if (comp._result != nullptr && comp._result != this) { cache_unref_delete(comp._result); } } @@ -1741,7 +1735,7 @@ determine_bin_index() { return; } - string bin_name; + std::string bin_name; _draw_order = 0; const CullBinAttrib *bin; @@ -1796,7 +1790,7 @@ determine_cull_callback() { int slot = mask.get_lowest_on_bit(); while (slot >= 0) { const Attribute &attrib = _attributes[slot]; - nassertv(attrib._attrib != (RenderAttrib *)NULL); + nassertv(attrib._attrib != nullptr); if (attrib._attrib->has_cull_callback()) { _flags |= F_has_cull_callback; break; @@ -1896,7 +1890,7 @@ write_datagram(BamWriter *manager, Datagram &dg) { int slot = mask.get_lowest_on_bit(); while (slot >= 0) { const Attribute &attrib = _attributes[slot]; - nassertv(attrib._attrib != (RenderAttrib *)NULL); + nassertv(attrib._attrib != nullptr); manager->write_pointer(dg, attrib._attrib); dg.add_int32(attrib._override); @@ -1920,7 +1914,7 @@ complete_pointers(TypedWritable **p_list, BamReader *manager) { int override = (*_read_overrides)[i]; RenderAttrib *attrib = DCAST(RenderAttrib, p_list[pi++]); - if (attrib != (RenderAttrib *)NULL) { + if (attrib != nullptr) { int slot = attrib->get_slot(); if (slot > 0 && slot < reg->get_max_slots()) { _attributes[slot].set(attrib, override); @@ -1931,7 +1925,7 @@ complete_pointers(TypedWritable **p_list, BamReader *manager) { } delete _read_overrides; - _read_overrides = NULL; + _read_overrides = nullptr; return pi; } diff --git a/panda/src/pgraph/renderState.h b/panda/src/pgraph/renderState.h index 1052687314..c9e3719082 100644 --- a/panda/src/pgraph/renderState.h +++ b/panda/src/pgraph/renderState.h @@ -50,12 +50,13 @@ protected: private: RenderState(const RenderState ©); - void operator = (const RenderState ©); public: virtual ~RenderState(); ALLOC_DELETED_CHAIN(RenderState); + RenderState &operator = (const RenderState ©) = delete; + typedef RenderAttribRegistry::SlotMask SlotMask; PUBLISHED: @@ -130,8 +131,8 @@ PUBLISHED: EXTENSION(PyObject *get_composition_cache() const); EXTENSION(PyObject *get_invert_composition_cache() const); - void output(ostream &out) const; - void write(ostream &out, int indent_level) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level) const; static int get_max_priority(); @@ -140,8 +141,8 @@ PUBLISHED: static int clear_cache(); static void clear_munger_cache(); static int garbage_collect(); - static void list_cycles(ostream &out); - static void list_states(ostream &out); + static void list_cycles(std::ostream &out); + static void list_states(std::ostream &out); static bool validate_states(); EXTENSION(static PyObject *get_states()); @@ -161,7 +162,11 @@ public: template INLINE bool get_attrib(const AttribType *&attrib) const; template + INLINE bool get_attrib(CPT(AttribType) &attrib) const; + template INLINE void get_attrib_def(const AttribType *&attrib) const; + template + INLINE void get_attrib_def(CPT(AttribType) &attrib) const; #endif // CPPPARSER private: @@ -226,7 +231,7 @@ private: // cache, which is encoded in _composition_cache and // _invert_composition_cache. static LightReMutex *_states_lock; - typedef SimpleHashMap > States; + typedef SimpleHashMap > States; static States *_states; static const RenderState *_empty_state; @@ -372,7 +377,7 @@ private: template<> INLINE void PointerToBase::update_type(To *ptr) {} -INLINE ostream &operator << (ostream &out, const RenderState &state) { +INLINE std::ostream &operator << (std::ostream &out, const RenderState &state) { state.output(out); return out; } diff --git a/panda/src/pgraph/renderState_ext.cxx b/panda/src/pgraph/renderState_ext.cxx index 0dc0d8acc5..2b7e3a4791 100644 --- a/panda/src/pgraph/renderState_ext.cxx +++ b/panda/src/pgraph/renderState_ext.cxx @@ -37,7 +37,7 @@ get_composition_cache() const { PyObject *tuple = PyTuple_New(2); PyObject *a, *b; const RenderState *source = _this->_composition_cache.get_key(i); - if (source == (RenderState *)NULL) { + if (source == nullptr) { a = Py_None; Py_INCREF(a); } else { @@ -46,7 +46,7 @@ get_composition_cache() const { true, true, source->get_type_index()); } const RenderState *result = _this->_composition_cache.get_data(i)._result; - if (result == (RenderState *)NULL) { + if (result == nullptr) { b = Py_None; Py_INCREF(b); } else { @@ -85,7 +85,7 @@ get_invert_composition_cache() const { PyObject *tuple = PyTuple_New(2); PyObject *a, *b; const RenderState *source = _this->_invert_composition_cache.get_key(i); - if (source == (RenderState *)NULL) { + if (source == nullptr) { a = Py_None; Py_INCREF(a); } else { @@ -94,7 +94,7 @@ get_invert_composition_cache() const { true, true, source->get_type_index()); } const RenderState *result = _this->_invert_composition_cache.get_data(i)._result; - if (result == (RenderState *)NULL) { + if (result == nullptr) { b = Py_None; Py_INCREF(b); } else { @@ -118,7 +118,7 @@ get_invert_composition_cache() const { PyObject *Extension:: get_states() { extern struct Dtool_PyTypedObject Dtool_RenderState; - if (RenderState::_states == (RenderState::States *)NULL) { + if (RenderState::_states == nullptr) { return PyList_New(0); } LightReMutexHolder holder(*RenderState::_states_lock); diff --git a/panda/src/pgraph/rescaleNormalAttrib.cxx b/panda/src/pgraph/rescaleNormalAttrib.cxx index fbc4d59274..0b93da7a23 100644 --- a/panda/src/pgraph/rescaleNormalAttrib.cxx +++ b/panda/src/pgraph/rescaleNormalAttrib.cxx @@ -22,6 +22,10 @@ #include "configVariableEnum.h" #include "config_pgraph.h" +using std::istream; +using std::ostream; +using std::string; + TypeHandle RescaleNormalAttrib::_type_handle; int RescaleNormalAttrib::_attrib_slot; CPT(RenderAttrib) RescaleNormalAttrib::_attribs[RescaleNormalAttrib::M_auto + 1]; diff --git a/panda/src/pgraph/rescaleNormalAttrib.h b/panda/src/pgraph/rescaleNormalAttrib.h index 589f5351cc..7f87219285 100644 --- a/panda/src/pgraph/rescaleNormalAttrib.h +++ b/panda/src/pgraph/rescaleNormalAttrib.h @@ -52,7 +52,7 @@ PUBLISHED: MAKE_PROPERTY(mode, get_mode); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; @@ -97,8 +97,8 @@ private: static int _attrib_slot; }; -EXPCL_PANDA_PGRAPH ostream &operator << (ostream &out, RescaleNormalAttrib::Mode mode); -EXPCL_PANDA_PGRAPH istream &operator >> (istream &in, RescaleNormalAttrib::Mode &mode); +EXPCL_PANDA_PGRAPH std::ostream &operator << (std::ostream &out, RescaleNormalAttrib::Mode mode); +EXPCL_PANDA_PGRAPH std::istream &operator >> (std::istream &in, RescaleNormalAttrib::Mode &mode); #include "rescaleNormalAttrib.I" diff --git a/panda/src/pgraph/sceneGraphReducer.I b/panda/src/pgraph/sceneGraphReducer.I index 4319b118df..2db336c546 100644 --- a/panda/src/pgraph/sceneGraphReducer.I +++ b/panda/src/pgraph/sceneGraphReducer.I @@ -77,7 +77,7 @@ get_combine_radius() const { INLINE void SceneGraphReducer:: apply_attribs(PandaNode *node, int attrib_types) { nassertv(check_live_flatten(node)); - nassertv(node != (PandaNode *)NULL); + nassertv(node != nullptr); PStatTimer timer(_apply_collector); AccumulatedAttribs attribs; r_apply_attribs(node, attribs, attrib_types, _transformer); @@ -93,7 +93,7 @@ apply_attribs(PandaNode *node, int attrib_types) { INLINE void SceneGraphReducer:: apply_attribs(PandaNode *node, const AccumulatedAttribs &attribs, int attrib_types, GeomTransformer &transformer) { - nassertv(node != (PandaNode *)NULL); + nassertv(node != nullptr); r_apply_attribs(node, attribs, attrib_types, transformer); } @@ -115,7 +115,7 @@ apply_attribs(PandaNode *node, const AccumulatedAttribs &attribs, */ INLINE int SceneGraphReducer:: make_compatible_format(PandaNode *root, int collect_bits) { - nassertr(root != (PandaNode *)NULL, 0); + nassertr(root != nullptr, 0); nassertr(check_live_flatten(root), 0); PStatTimer timer(_collect_collector); int count = 0; @@ -137,7 +137,7 @@ make_compatible_format(PandaNode *root, int collect_bits) { */ INLINE int SceneGraphReducer:: collect_vertex_data(PandaNode *root, int collect_bits) { - nassertr(root != (PandaNode *)NULL, 0); + nassertr(root != nullptr, 0); nassertr(check_live_flatten(root), 0); PStatTimer timer(_collect_collector); int count = 0; @@ -155,7 +155,7 @@ collect_vertex_data(PandaNode *root, int collect_bits) { */ INLINE int SceneGraphReducer:: make_nonindexed(PandaNode *root, int nonindexed_bits) { - nassertr(root != (PandaNode *)NULL, 0); + nassertr(root != nullptr, 0); nassertr(check_live_flatten(root), 0); PStatTimer timer(_make_nonindexed_collector); return r_make_nonindexed(root, nonindexed_bits); @@ -171,9 +171,9 @@ make_nonindexed(PandaNode *root, int nonindexed_bits) { */ INLINE void SceneGraphReducer:: premunge(PandaNode *root, const RenderState *initial_state) { - nassertv(root != (PandaNode *)NULL); + nassertv(root != nullptr); nassertv(check_live_flatten(root)); - if (_gsg != (GraphicsStateGuardianBase *)NULL) { + if (_gsg != nullptr) { PStatTimer timer(_premunge_collector); r_premunge(root, initial_state); } diff --git a/panda/src/pgraph/sceneGraphReducer.cxx b/panda/src/pgraph/sceneGraphReducer.cxx index d0dc3e4411..03179d38dd 100644 --- a/panda/src/pgraph/sceneGraphReducer.cxx +++ b/panda/src/pgraph/sceneGraphReducer.cxx @@ -42,7 +42,7 @@ PStatCollector SceneGraphReducer::_premunge_collector("*:Premunge"); */ void SceneGraphReducer:: set_gsg(GraphicsStateGuardianBase *gsg) { - if (gsg != (GraphicsStateGuardianBase *)NULL) { + if (gsg != nullptr) { _gsg = gsg; } else { _gsg = GraphicsStateGuardianBase::get_default_gsg(); @@ -50,8 +50,8 @@ set_gsg(GraphicsStateGuardianBase *gsg) { int max_vertices = max_collect_vertices; - if (_gsg != (GraphicsStateGuardianBase *)NULL) { - max_vertices = min(max_vertices, _gsg->get_max_vertices_per_array()); + if (_gsg != nullptr) { + max_vertices = std::min(max_vertices, _gsg->get_max_vertices_per_array()); } _transformer.set_max_collect_vertices(max_vertices); @@ -64,7 +64,7 @@ set_gsg(GraphicsStateGuardianBase *gsg) { */ void SceneGraphReducer:: clear_gsg() { - _gsg = NULL; + _gsg = nullptr; _transformer.set_max_collect_vertices(max_collect_vertices); } @@ -180,8 +180,8 @@ unify(PandaNode *root, bool preserve_order) { PStatTimer timer(_unify_collector); int max_indices = max_collect_indices; - if (_gsg != (GraphicsStateGuardianBase *)NULL) { - max_indices = min(max_indices, _gsg->get_max_vertices_per_primitive()); + if (_gsg != nullptr) { + max_indices = std::min(max_indices, _gsg->get_max_vertices_per_primitive()); } r_unify(root, max_indices, preserve_order); } @@ -376,7 +376,7 @@ r_flatten(PandaNode *grandparent_node, PandaNode *parent_node, if (pgraph_cat.is_spam()) { pgraph_cat.spam() << "SceneGraphReducer::r_flatten(" << *grandparent_node << ", " - << *parent_node << ", " << hex << combine_siblings_bits << dec + << *parent_node << ", " << std::hex << combine_siblings_bits << std::dec << ")\n"; } @@ -578,7 +578,7 @@ flatten_siblings(PandaNode *parent_node, int combine_siblings_bits) { if (consider_siblings(parent_node, child1, child2)) { PT(PandaNode) new_node = do_flatten_siblings(parent_node, child1, child2); - if (new_node != (PandaNode *)NULL) { + if (new_node != nullptr) { // We successfully collapsed a node. (*ai1_hold) = new_node; nodes.erase(ai2_hold); @@ -655,7 +655,7 @@ do_flatten_child(PandaNode *grandparent_node, PandaNode *parent_node, } PT(PandaNode) new_parent = collapse_nodes(parent_node, child_node, false); - if (new_parent == (PandaNode *)NULL) { + if (new_parent == nullptr) { if (pgraph_cat.is_spam()) { pgraph_cat.spam() << "Decided not to collapse " << *parent_node @@ -689,12 +689,12 @@ do_flatten_siblings(PandaNode *parent_node, PandaNode *child1, } PT(PandaNode) new_child = collapse_nodes(child2, child1, true); - if (new_child == (PandaNode *)NULL) { + if (new_child == nullptr) { if (pgraph_cat.is_spam()) { pgraph_cat.spam() << "Decided not to collapse " << *child1 << " and " << *child2 << "\n"; } - return NULL; + return nullptr; } choose_name(new_child, child2, child1); @@ -717,7 +717,7 @@ do_flatten_siblings(PandaNode *parent_node, PandaNode *child1, PT(PandaNode) SceneGraphReducer:: collapse_nodes(PandaNode *node1, PandaNode *node2, bool siblings) { PT(PandaNode) result = node2->combine_with(node1); - if (result == NULL) { + if (result == nullptr) { result = node1->combine_with(node2); } return result; @@ -730,7 +730,7 @@ collapse_nodes(PandaNode *node1, PandaNode *node2, bool siblings) { */ void SceneGraphReducer:: choose_name(PandaNode *preserve, PandaNode *source1, PandaNode *source2) { - string name; + std::string name; bool got_name = false; name = source1->get_name(); diff --git a/panda/src/pgraph/sceneGraphReducer.h b/panda/src/pgraph/sceneGraphReducer.h index 5d9550856a..ec898d5820 100644 --- a/panda/src/pgraph/sceneGraphReducer.h +++ b/panda/src/pgraph/sceneGraphReducer.h @@ -38,7 +38,7 @@ class PandaNode; */ class EXPCL_PANDA_PGRAPH SceneGraphReducer { PUBLISHED: - INLINE explicit SceneGraphReducer(GraphicsStateGuardianBase *gsg = NULL); + INLINE explicit SceneGraphReducer(GraphicsStateGuardianBase *gsg = nullptr); INLINE ~SceneGraphReducer(); enum AttribTypes { diff --git a/panda/src/pgraph/sceneSetup.I b/panda/src/pgraph/sceneSetup.I index 425c538d85..cf420ee132 100644 --- a/panda/src/pgraph/sceneSetup.I +++ b/panda/src/pgraph/sceneSetup.I @@ -16,7 +16,7 @@ */ INLINE SceneSetup:: SceneSetup() { - _display_region = NULL; + _display_region = nullptr; _viewport_width = 0; _viewport_height = 0; _inverted = false; @@ -175,7 +175,7 @@ get_cull_center() const { INLINE PT(BoundingVolume) SceneSetup:: get_cull_bounds() const { PT(BoundingVolume) bounds = _camera_node->get_cull_bounds(); - if (bounds != (BoundingVolume *)NULL) { + if (bounds != nullptr) { return bounds; } diff --git a/panda/src/pgraph/scissorAttrib.cxx b/panda/src/pgraph/scissorAttrib.cxx index e1c3c29e01..4e137eec5b 100644 --- a/panda/src/pgraph/scissorAttrib.cxx +++ b/panda/src/pgraph/scissorAttrib.cxx @@ -19,6 +19,9 @@ #include "datagram.h" #include "datagramIterator.h" +using std::max; +using std::min; + TypeHandle ScissorAttrib::_type_handle; int ScissorAttrib::_attrib_slot; CPT(RenderAttrib) ScissorAttrib::_off_attrib; @@ -44,7 +47,7 @@ ScissorAttrib(const LVecBase4 &frame) : */ CPT(RenderAttrib) ScissorAttrib:: make_off() { - if (_off_attrib != NULL) { + if (_off_attrib != nullptr) { return _off_attrib; } ScissorAttrib *attrib = new ScissorAttrib(LVecBase4(0.0f, 1.0f, 0.0f, 1.0f)); @@ -78,7 +81,7 @@ make_default() { * */ void ScissorAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":[" << _frame << "]"; } diff --git a/panda/src/pgraph/scissorAttrib.h b/panda/src/pgraph/scissorAttrib.h index 9ea128e765..c7c3ff3c4e 100644 --- a/panda/src/pgraph/scissorAttrib.h +++ b/panda/src/pgraph/scissorAttrib.h @@ -51,7 +51,7 @@ PUBLISHED: MAKE_PROPERTY(frame, get_frame); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/scissorEffect.cxx b/panda/src/pgraph/scissorEffect.cxx index 9794250346..dbfa96cf9e 100644 --- a/panda/src/pgraph/scissorEffect.cxx +++ b/panda/src/pgraph/scissorEffect.cxx @@ -23,6 +23,9 @@ #include "boundingHexahedron.h" #include "lens.h" +using std::max; +using std::min; + TypeHandle ScissorEffect::_type_handle; /** @@ -58,7 +61,7 @@ ScissorEffect(const ScissorEffect ©) : */ CPT(RenderEffect) ScissorEffect:: make_screen(const LVecBase4 &frame, bool clip) { - ScissorEffect *effect = new ScissorEffect(true, frame, NULL, 0, clip); + ScissorEffect *effect = new ScissorEffect(true, frame, nullptr, 0, clip); return return_new(effect); } @@ -69,7 +72,7 @@ make_screen(const LVecBase4 &frame, bool clip) { */ CPT(RenderEffect) ScissorEffect:: make_node(bool clip) { - ScissorEffect *effect = new ScissorEffect(false, LVecBase4::zero(), NULL, 0, clip); + ScissorEffect *effect = new ScissorEffect(false, LVecBase4::zero(), nullptr, 0, clip); return return_new(effect); } @@ -155,7 +158,7 @@ xform(const LMatrix4 &mat) const { * */ void ScissorEffect:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; if (is_screen()) { out << "screen [" << _frame << "]"; @@ -273,7 +276,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data, // Set up the culling. We do this by extruding the four corners of the // frame into the eight corners of the bounding frustum. PT(GeometricBoundingVolume) frustum = make_frustum(lens, frame); - if (frustum != (GeometricBoundingVolume *)NULL) { + if (frustum != nullptr) { frustum->xform(modelview_transform->get_inverse()->get_mat()); data._view_frustum = frustum; } @@ -362,7 +365,7 @@ write_datagram(BamWriter *manager, Datagram &dg) { */ TypedWritable *ScissorEffect:: make_from_bam(const FactoryParams ¶ms) { - ScissorEffect *effect = new ScissorEffect(true, LVecBase4::zero(), NULL, 0, false); + ScissorEffect *effect = new ScissorEffect(true, LVecBase4::zero(), nullptr, 0, false); DatagramIterator scan; BamReader *manager; @@ -415,28 +418,28 @@ make_frustum(const Lens *lens, const LVecBase4 &frame) const{ // Upper left. if (!lens->extrude(corner, nul, ful)) { - return (GeometricBoundingVolume *)NULL; + return nullptr; } corner[0] = f2[1]; corner[1] = f2[3]; // Upper right. if (!lens->extrude(corner, nur, fur)) { - return (GeometricBoundingVolume *)NULL; + return nullptr; } corner[0] = f2[1]; corner[1] = f2[2]; // Lower right. if (!lens->extrude(corner, nlr, flr)) { - return (GeometricBoundingVolume *)NULL; + return nullptr; } corner[0] = f2[0]; corner[1] = f2[2]; // Lower left. if (!lens->extrude(corner, nll, fll)) { - return (GeometricBoundingVolume *)NULL; + return nullptr; } return new BoundingHexahedron(fll, flr, fur, ful, nll, nlr, nur, nul); diff --git a/panda/src/pgraph/scissorEffect.h b/panda/src/pgraph/scissorEffect.h index 4ac2e9a87d..aec8084917 100644 --- a/panda/src/pgraph/scissorEffect.h +++ b/panda/src/pgraph/scissorEffect.h @@ -60,7 +60,7 @@ PUBLISHED: public: virtual CPT(RenderEffect) xform(const LMatrix4 &mat) const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; virtual bool has_cull_callback() const; virtual void cull_callback(CullTraverser *trav, CullTraverserData &data, diff --git a/panda/src/pgraph/shadeModelAttrib.cxx b/panda/src/pgraph/shadeModelAttrib.cxx index dea61a8521..26fac679b4 100644 --- a/panda/src/pgraph/shadeModelAttrib.cxx +++ b/panda/src/pgraph/shadeModelAttrib.cxx @@ -45,7 +45,7 @@ make_default() { * */ void ShadeModelAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; switch (get_mode()) { case M_flat: diff --git a/panda/src/pgraph/shadeModelAttrib.h b/panda/src/pgraph/shadeModelAttrib.h index 8f8cd8a570..c5e0819141 100644 --- a/panda/src/pgraph/shadeModelAttrib.h +++ b/panda/src/pgraph/shadeModelAttrib.h @@ -42,7 +42,7 @@ PUBLISHED: MAKE_PROPERTY(mode, get_mode); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/shaderAttrib.I b/panda/src/pgraph/shaderAttrib.I index 6513604ae9..fccfb98569 100644 --- a/panda/src/pgraph/shaderAttrib.I +++ b/panda/src/pgraph/shaderAttrib.I @@ -18,7 +18,7 @@ */ INLINE ShaderAttrib:: ShaderAttrib() : - _shader(NULL), + _shader(nullptr), _shader_priority(0), _auto_shader(false), _has_shader(false), @@ -110,7 +110,7 @@ has_shader_input(CPT_InternalName id) const { */ INLINE CPT(RenderAttrib) ShaderAttrib:: set_shader_input(CPT_InternalName id, const PTA_float &v, int priority) const { - return set_shader_input(ShaderInput(move(id), v, priority)); + return set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -118,7 +118,7 @@ set_shader_input(CPT_InternalName id, const PTA_float &v, int priority) const { */ INLINE CPT(RenderAttrib) ShaderAttrib:: set_shader_input(CPT_InternalName id, const PTA_double &v, int priority) const { - return set_shader_input(ShaderInput(move(id), v, priority)); + return set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -126,7 +126,7 @@ set_shader_input(CPT_InternalName id, const PTA_double &v, int priority) const { */ INLINE CPT(RenderAttrib) ShaderAttrib:: set_shader_input(CPT_InternalName id, const PTA_LVecBase4 &v, int priority) const { - return set_shader_input(ShaderInput(move(id), v, priority)); + return set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -134,7 +134,7 @@ set_shader_input(CPT_InternalName id, const PTA_LVecBase4 &v, int priority) cons */ INLINE CPT(RenderAttrib) ShaderAttrib:: set_shader_input(CPT_InternalName id, const PTA_LVecBase3 &v, int priority) const { - return set_shader_input(ShaderInput(move(id), v, priority)); + return set_shader_input(ShaderInput(std::move(id), v, priority)); } @@ -143,7 +143,7 @@ set_shader_input(CPT_InternalName id, const PTA_LVecBase3 &v, int priority) cons */ INLINE CPT(RenderAttrib) ShaderAttrib:: set_shader_input(CPT_InternalName id, const PTA_LVecBase2 &v, int priority) const { - return set_shader_input(ShaderInput(move(id), v, priority)); + return set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -151,7 +151,7 @@ set_shader_input(CPT_InternalName id, const PTA_LVecBase2 &v, int priority) cons */ INLINE CPT(RenderAttrib) ShaderAttrib:: set_shader_input(CPT_InternalName id, const LVecBase4 &v, int priority) const { - return set_shader_input(ShaderInput(move(id), v, priority)); + return set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -159,7 +159,7 @@ set_shader_input(CPT_InternalName id, const LVecBase4 &v, int priority) const { */ INLINE CPT(RenderAttrib) ShaderAttrib:: set_shader_input(CPT_InternalName id, const LVecBase3 &v, int priority) const { - return set_shader_input(ShaderInput(move(id), v, priority)); + return set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -167,7 +167,7 @@ set_shader_input(CPT_InternalName id, const LVecBase3 &v, int priority) const { */ INLINE CPT(RenderAttrib) ShaderAttrib:: set_shader_input(CPT_InternalName id, const LVecBase2 &v, int priority) const { - return set_shader_input(ShaderInput(move(id), v, priority)); + return set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -175,7 +175,7 @@ set_shader_input(CPT_InternalName id, const LVecBase2 &v, int priority) const { */ INLINE CPT(RenderAttrib) ShaderAttrib:: set_shader_input(CPT_InternalName id, const PTA_LMatrix4 &v, int priority) const { - return set_shader_input(ShaderInput(move(id), v, priority)); + return set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -183,7 +183,7 @@ set_shader_input(CPT_InternalName id, const PTA_LMatrix4 &v, int priority) const */ INLINE CPT(RenderAttrib) ShaderAttrib:: set_shader_input(CPT_InternalName id, const PTA_LMatrix3 &v, int priority) const { - return set_shader_input(ShaderInput(move(id), v, priority)); + return set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -191,7 +191,7 @@ set_shader_input(CPT_InternalName id, const PTA_LMatrix3 &v, int priority) const */ INLINE CPT(RenderAttrib) ShaderAttrib:: set_shader_input(CPT_InternalName id, const LMatrix4 &v, int priority) const { - return set_shader_input(ShaderInput(move(id), v, priority)); + return set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -199,7 +199,7 @@ set_shader_input(CPT_InternalName id, const LMatrix4 &v, int priority) const { */ INLINE CPT(RenderAttrib) ShaderAttrib:: set_shader_input(CPT_InternalName id, const LMatrix3 &v, int priority) const { - return set_shader_input(ShaderInput(move(id), v, priority)); + return set_shader_input(ShaderInput(std::move(id), v, priority)); } /** @@ -207,7 +207,7 @@ set_shader_input(CPT_InternalName id, const LMatrix3 &v, int priority) const { */ INLINE CPT(RenderAttrib) ShaderAttrib:: set_shader_input(CPT_InternalName id, Texture *tex, int priority) const { - return set_shader_input(ShaderInput(move(id), tex, priority)); + return set_shader_input(ShaderInput(std::move(id), tex, priority)); } /** @@ -215,7 +215,7 @@ set_shader_input(CPT_InternalName id, Texture *tex, int priority) const { */ INLINE CPT(RenderAttrib) ShaderAttrib:: set_shader_input(CPT_InternalName id, const NodePath &np, int priority) const { - return set_shader_input(ShaderInput(move(id), np, priority)); + return set_shader_input(ShaderInput(std::move(id), np, priority)); } /** @@ -223,7 +223,7 @@ set_shader_input(CPT_InternalName id, const NodePath &np, int priority) const { */ INLINE CPT(RenderAttrib) ShaderAttrib:: set_shader_input(CPT_InternalName id, double n1, double n2, double n3, double n4, int priority) const { - return set_shader_input(ShaderInput(move(id), LVecBase4((PN_stdfloat)n1, (PN_stdfloat)n2, (PN_stdfloat)n3, (PN_stdfloat)n4), priority)); + return set_shader_input(ShaderInput(std::move(id), LVecBase4((PN_stdfloat)n1, (PN_stdfloat)n2, (PN_stdfloat)n3, (PN_stdfloat)n4), priority)); } INLINE bool ShaderAttrib:: diff --git a/panda/src/pgraph/shaderAttrib.cxx b/panda/src/pgraph/shaderAttrib.cxx index 130d85c1b8..e519289b28 100644 --- a/panda/src/pgraph/shaderAttrib.cxx +++ b/panda/src/pgraph/shaderAttrib.cxx @@ -29,6 +29,9 @@ #include "paramTexture.h" #include "shaderBuffer.h" +using std::ostream; +using std::ostringstream; + TypeHandle ShaderAttrib::_type_handle; int ShaderAttrib::_attrib_slot; @@ -39,7 +42,7 @@ int ShaderAttrib::_attrib_slot; CPT(RenderAttrib) ShaderAttrib:: make_off() { static CPT(RenderAttrib) _off_attrib; - if (_off_attrib == 0) { + if (_off_attrib == nullptr) { ShaderAttrib *attrib = new ShaderAttrib; attrib->_has_shader = true; _off_attrib = return_new(attrib); @@ -53,12 +56,12 @@ make_off() { CPT(RenderAttrib) ShaderAttrib:: make(const Shader *shader, int priority) { static CPT(RenderAttrib) _null_attrib; - if (_null_attrib == 0) { + if (_null_attrib == nullptr) { ShaderAttrib *attrib = new ShaderAttrib; _null_attrib = return_new(attrib); } - if (shader == NULL) { + if (shader == nullptr) { return _null_attrib; } else { return DCAST(ShaderAttrib, _null_attrib)->set_shader(shader, priority); @@ -93,7 +96,7 @@ set_shader(const Shader *s, int priority) const { CPT(RenderAttrib) ShaderAttrib:: set_shader_off(int priority) const { ShaderAttrib *result = new ShaderAttrib(*this); - result->_shader = NULL; + result->_shader = nullptr; result->_shader_priority = priority; result->_auto_shader = false; result->_auto_normal_on = false; @@ -112,7 +115,7 @@ set_shader_off(int priority) const { CPT(RenderAttrib) ShaderAttrib:: set_shader_auto(int priority) const { ShaderAttrib *result = new ShaderAttrib(*this); - result->_shader = NULL; + result->_shader = nullptr; result->_shader_priority = priority; result->_auto_shader = true; result->_has_shader = true; @@ -132,7 +135,7 @@ CPT(RenderAttrib) ShaderAttrib:: set_shader_auto(BitMask32 shader_switch, int priority) const { ShaderAttrib *result = new ShaderAttrib(*this); - result->_shader = NULL; + result->_shader = nullptr; result->_shader_priority = priority; result->_auto_shader = true; result->_has_shader = true; @@ -151,7 +154,7 @@ set_shader_auto(BitMask32 shader_switch, int priority) const { CPT(RenderAttrib) ShaderAttrib:: clear_shader() const { ShaderAttrib *result = new ShaderAttrib(*this); - result->_shader = NULL; + result->_shader = nullptr; result->_shader_priority = 0; result->_auto_shader = false; result->_has_shader = false; @@ -214,9 +217,9 @@ set_shader_input(ShaderInput &&input) const { ShaderAttrib *result = new ShaderAttrib(*this); Inputs::iterator i = result->_inputs.find(input.get_name()); if (i == result->_inputs.end()) { - result->_inputs.insert(Inputs::value_type(input.get_name(), move(input))); + result->_inputs.insert(Inputs::value_type(input.get_name(), std::move(input))); } else { - i->second = move(input); + i->second = std::move(input); } return return_new(result); } @@ -247,7 +250,7 @@ clear_shader_input(const InternalName *id) const { * */ CPT(RenderAttrib) ShaderAttrib:: -clear_shader_input(const string &id) const { +clear_shader_input(const std::string &id) const { return clear_shader_input(InternalName::make(id)); } @@ -280,7 +283,7 @@ get_shader_input(const InternalName *id) const { * function does not return NULL --- it returns the "blank" ShaderInput. */ const ShaderInput &ShaderAttrib:: -get_shader_input(const string &id) const { +get_shader_input(const std::string &id) const { return get_shader_input(InternalName::make(id)); } @@ -355,7 +358,7 @@ get_shader_input_vector(InternalName *id) const { } else if (p.get_value_type() == ShaderInput::M_param) { // Temporary solution until the new param system TypedWritableReferenceCount *param = p.get_value(); - if (param != NULL && param->is_of_type(ParamVecBase4::get_class_type())) { + if (param != nullptr && param->is_of_type(ParamVecBase4::get_class_type())) { return ((const ParamVecBase4 *)param)->get_value(); } } @@ -385,14 +388,14 @@ get_shader_input_ptr(const InternalName *id) const { ostringstream strm; strm << "Shader input " << id->get_name() << " is not a PTA(float/double) type.\n"; nassert_raise(strm.str()); - return NULL; + return nullptr; } return &(p.get_ptr()); } else { ostringstream strm; strm << "Shader input " << id->get_name() << " is not present.\n"; nassert_raise(strm.str()); - return NULL; + return nullptr; } } @@ -431,14 +434,14 @@ get_shader_input_texture(const InternalName *id, SamplerState *sampler) const { ostringstream strm; strm << "Shader input " << id->get_name() << " is not a texture.\n"; nassert_raise(strm.str()); - return NULL; + return nullptr; } } else { ostringstream strm; strm << "Shader input " << id->get_name() << " is not present.\n"; nassert_raise(strm.str()); - return NULL; + return nullptr; } } @@ -506,20 +509,20 @@ get_shader_input_buffer(const InternalName *id) const { ostringstream strm; strm << "Shader input " << id->get_name() << " is not present.\n"; nassert_raise(strm.str()); - return NULL; + return nullptr; } else { const ShaderInput &p = (*i).second; if (p.get_value_type() == ShaderInput::M_buffer) { ShaderBuffer *value; - DCAST_INTO_R(value, p._value, NULL); + DCAST_INTO_R(value, p._value, nullptr); return value; } ostringstream strm; strm << "Shader input " << id->get_name() << " is not a ShaderBuffer.\n"; nassert_raise(strm.str()); - return NULL; + return nullptr; } } diff --git a/panda/src/pgraph/shaderAttrib.h b/panda/src/pgraph/shaderAttrib.h index 02a3189233..6cd04c6d99 100644 --- a/panda/src/pgraph/shaderAttrib.h +++ b/panda/src/pgraph/shaderAttrib.h @@ -42,7 +42,7 @@ private: INLINE ShaderAttrib(const ShaderAttrib ©); PUBLISHED: - static CPT(RenderAttrib) make(const Shader *shader = NULL, int priority = 0); + static CPT(RenderAttrib) make(const Shader *shader = nullptr, int priority = 0); static CPT(RenderAttrib) make_off(); static CPT(RenderAttrib) make_default(); @@ -102,7 +102,7 @@ PUBLISHED: CPT(RenderAttrib) clear_flag(int flag) const; CPT(RenderAttrib) clear_shader_input(const InternalName *id) const; - CPT(RenderAttrib) clear_shader_input(const string &id) const; + CPT(RenderAttrib) clear_shader_input(const std::string &id) const; CPT(RenderAttrib) clear_all_shader_inputs() const; @@ -111,11 +111,11 @@ PUBLISHED: const Shader *get_shader() const; const ShaderInput &get_shader_input(const InternalName *id) const; - const ShaderInput &get_shader_input(const string &id) const; + const ShaderInput &get_shader_input(const std::string &id) const; const NodePath &get_shader_input_nodepath(const InternalName *id) const; LVecBase4 get_shader_input_vector(InternalName *id) const; - Texture *get_shader_input_texture(const InternalName *id, SamplerState *sampler=NULL) const; + Texture *get_shader_input_texture(const InternalName *id, SamplerState *sampler=nullptr) const; const Shader::ShaderPtrData *get_shader_input_ptr(const InternalName *id) const; const LMatrix4 &get_shader_input_matrix(const InternalName *id, LMatrix4 &matrix) const; ShaderBuffer *get_shader_input_buffer(const InternalName *id) const; @@ -127,7 +127,7 @@ PUBLISHED: MAKE_PROPERTY(instance_count, get_instance_count); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/shaderAttrib_ext.cxx b/panda/src/pgraph/shaderAttrib_ext.cxx index b98badf71b..54acefe0ec 100644 --- a/panda/src/pgraph/shaderAttrib_ext.cxx +++ b/panda/src/pgraph/shaderAttrib_ext.cxx @@ -24,7 +24,7 @@ set_shader_input(CPT_InternalName name, PyObject *value, int priority) const { ShaderAttrib *attrib = new ShaderAttrib(*_this); ShaderInput &input = attrib->_inputs[name]; - invoke_extension(&input).__init__(move(name), value); + invoke_extension(&input).__init__(std::move(name), value); return ShaderAttrib::return_new(attrib); } @@ -60,9 +60,9 @@ set_shader_inputs(PyObject *args, PyObject *kwargs) const { return nullptr; } - CPT_InternalName name(string(buffer, length)); + CPT_InternalName name(std::string(buffer, length)); ShaderInput &input = attrib->_inputs[name]; - invoke_extension(&input).__init__(move(name), value); + invoke_extension(&input).__init__(std::move(name), value); } return ShaderAttrib::return_new(attrib); diff --git a/panda/src/pgraph/shaderInput.I b/panda/src/pgraph/shaderInput.I index 8c37322082..b8e182421f 100644 --- a/panda/src/pgraph/shaderInput.I +++ b/panda/src/pgraph/shaderInput.I @@ -18,7 +18,7 @@ */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_invalid), _priority(priority) { @@ -29,7 +29,7 @@ ShaderInput(CPT_InternalName name, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, Texture *tex, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_texture), _priority(priority), _value(tex) @@ -41,7 +41,7 @@ ShaderInput(CPT_InternalName name, Texture *tex, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, ParamValueBase *param, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_param), _priority(priority), _value(param) @@ -53,7 +53,7 @@ ShaderInput(CPT_InternalName name, ParamValueBase *param, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, ShaderBuffer *buf, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_buffer), _priority(priority), _value(buf) @@ -65,7 +65,7 @@ ShaderInput(CPT_InternalName name, ShaderBuffer *buf, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const PTA_float &ptr, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(ptr) @@ -77,7 +77,7 @@ ShaderInput(CPT_InternalName name, const PTA_float &ptr, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const PTA_LVecBase4f &ptr, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(ptr) @@ -89,7 +89,7 @@ ShaderInput(CPT_InternalName name, const PTA_LVecBase4f &ptr, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const PTA_LVecBase3f &ptr, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(ptr) @@ -101,7 +101,7 @@ ShaderInput(CPT_InternalName name, const PTA_LVecBase3f &ptr, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const PTA_LVecBase2f &ptr, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(ptr) @@ -113,7 +113,7 @@ ShaderInput(CPT_InternalName name, const PTA_LVecBase2f &ptr, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const LVecBase4f &vec, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_vector), _priority(priority), _stored_ptr(vec), @@ -126,7 +126,7 @@ ShaderInput(CPT_InternalName name, const LVecBase4f &vec, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const LVecBase3f &vec, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_vector), _priority(priority), _stored_ptr(vec), @@ -139,7 +139,7 @@ ShaderInput(CPT_InternalName name, const LVecBase3f &vec, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const LVecBase2f &vec, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_vector), _priority(priority), _stored_ptr(vec), @@ -152,7 +152,7 @@ ShaderInput(CPT_InternalName name, const LVecBase2f &vec, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const PTA_LMatrix4f &ptr, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(ptr) @@ -164,7 +164,7 @@ ShaderInput(CPT_InternalName name, const PTA_LMatrix4f &ptr, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const PTA_LMatrix3f &ptr, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(ptr) @@ -176,7 +176,7 @@ ShaderInput(CPT_InternalName name, const PTA_LMatrix3f &ptr, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const LMatrix4f &mat, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(mat) @@ -188,7 +188,7 @@ ShaderInput(CPT_InternalName name, const LMatrix4f &mat, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const LMatrix3f &mat, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(mat) @@ -200,7 +200,7 @@ ShaderInput(CPT_InternalName name, const LMatrix3f &mat, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const PTA_double &ptr, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(ptr) @@ -212,7 +212,7 @@ ShaderInput(CPT_InternalName name, const PTA_double &ptr, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const PTA_LVecBase4d &ptr, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(ptr) @@ -224,7 +224,7 @@ ShaderInput(CPT_InternalName name, const PTA_LVecBase4d &ptr, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const PTA_LVecBase3d &ptr, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(ptr) @@ -236,7 +236,7 @@ ShaderInput(CPT_InternalName name, const PTA_LVecBase3d &ptr, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const PTA_LVecBase2d &ptr, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(ptr) @@ -248,7 +248,7 @@ ShaderInput(CPT_InternalName name, const PTA_LVecBase2d &ptr, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const LVecBase4d &vec, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(vec), @@ -261,7 +261,7 @@ ShaderInput(CPT_InternalName name, const LVecBase4d &vec, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const LVecBase3d &vec, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(vec), @@ -274,7 +274,7 @@ ShaderInput(CPT_InternalName name, const LVecBase3d &vec, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const LVecBase2d &vec, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(vec), @@ -287,7 +287,7 @@ ShaderInput(CPT_InternalName name, const LVecBase2d &vec, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const PTA_LMatrix4d &ptr, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(ptr) @@ -299,7 +299,7 @@ ShaderInput(CPT_InternalName name, const PTA_LMatrix4d &ptr, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const PTA_LMatrix3d &ptr, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(ptr) @@ -311,7 +311,7 @@ ShaderInput(CPT_InternalName name, const PTA_LMatrix3d &ptr, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const LMatrix4d &mat, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(mat) @@ -323,7 +323,7 @@ ShaderInput(CPT_InternalName name, const LMatrix4d &mat, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const LMatrix3d &mat, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(mat) @@ -335,7 +335,7 @@ ShaderInput(CPT_InternalName name, const LMatrix3d &mat, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const PTA_int &ptr, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(ptr) @@ -347,7 +347,7 @@ ShaderInput(CPT_InternalName name, const PTA_int &ptr, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const PTA_LVecBase4i &ptr, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(ptr) @@ -359,7 +359,7 @@ ShaderInput(CPT_InternalName name, const PTA_LVecBase4i &ptr, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const PTA_LVecBase3i &ptr, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(ptr) @@ -371,7 +371,7 @@ ShaderInput(CPT_InternalName name, const PTA_LVecBase3i &ptr, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const PTA_LVecBase2i &ptr, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(ptr) @@ -383,7 +383,7 @@ ShaderInput(CPT_InternalName name, const PTA_LVecBase2i &ptr, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const LVecBase4i &vec, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(vec), @@ -396,7 +396,7 @@ ShaderInput(CPT_InternalName name, const LVecBase4i &vec, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const LVecBase3i &vec, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(vec), @@ -409,7 +409,7 @@ ShaderInput(CPT_InternalName name, const LVecBase3i &vec, int priority) : */ INLINE ShaderInput:: ShaderInput(CPT_InternalName name, const LVecBase2i &vec, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_numeric), _priority(priority), _stored_ptr(vec), diff --git a/panda/src/pgraph/shaderInput.cxx b/panda/src/pgraph/shaderInput.cxx index 44fb91cf23..b017045b22 100644 --- a/panda/src/pgraph/shaderInput.cxx +++ b/panda/src/pgraph/shaderInput.cxx @@ -30,7 +30,7 @@ get_blank() { */ ShaderInput:: ShaderInput(CPT_InternalName name, const NodePath &np, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_nodepath), _priority(priority), _value(new ParamNodePath(np)) @@ -42,7 +42,7 @@ ShaderInput(CPT_InternalName name, const NodePath &np, int priority) : */ ShaderInput:: ShaderInput(CPT_InternalName name, Texture *tex, bool read, bool write, int z, int n, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_texture_image), _priority(priority), _value(new ParamTextureImage(tex, read, write, z, n)) @@ -54,7 +54,7 @@ ShaderInput(CPT_InternalName name, Texture *tex, bool read, bool write, int z, i */ ShaderInput:: ShaderInput(CPT_InternalName name, Texture *tex, const SamplerState &sampler, int priority) : - _name(MOVE(name)), + _name(std::move(name)), _type(M_texture_sampler), _priority(priority), _value(new ParamTextureSampler(tex, sampler)) @@ -110,7 +110,7 @@ get_texture() const { return DCAST(Texture, _value); default: - return NULL; + return nullptr; } } diff --git a/panda/src/pgraph/shaderInput.h b/panda/src/pgraph/shaderInput.h index 39a4e32fe8..39ae9ba835 100644 --- a/panda/src/pgraph/shaderInput.h +++ b/panda/src/pgraph/shaderInput.h @@ -124,7 +124,7 @@ PUBLISHED: const SamplerState &get_sampler() const; public: - ShaderInput() DEFAULT_CTOR; + ShaderInput() = default; INLINE ParamValueBase *get_param() const; INLINE TypedWritableReferenceCount *get_value() const; diff --git a/panda/src/pgraph/shaderInput_ext.cxx b/panda/src/pgraph/shaderInput_ext.cxx index d09a971b46..72a4d74de3 100644 --- a/panda/src/pgraph/shaderInput_ext.cxx +++ b/panda/src/pgraph/shaderInput_ext.cxx @@ -58,7 +58,7 @@ extern struct Dtool_PyTypedObject Dtool_ParamValueBase; */ void Extension:: __init__(CPT_InternalName name, PyObject *value, int priority) { - _this->_name = move(name); + _this->_name = std::move(name); _this->_priority = priority; if (PyTuple_CheckExact(value) && PyTuple_GET_SIZE(value) <= 4) { diff --git a/panda/src/pgraph/shaderPool.I b/panda/src/pgraph/shaderPool.I index 3139ff2daf..03a07d448d 100644 --- a/panda/src/pgraph/shaderPool.I +++ b/panda/src/pgraph/shaderPool.I @@ -27,7 +27,7 @@ has_shader(const Filename &filename) { */ INLINE bool ShaderPool:: verify_shader(const Filename &filename) { - return load_shader(filename) != (Shader *)NULL; + return load_shader(filename) != nullptr; } /** @@ -84,7 +84,7 @@ garbage_collect() { * Lists the contents of the shader pool to the indicated output stream. */ INLINE void ShaderPool:: -list_contents(ostream &out) { +list_contents(std::ostream &out) { get_ptr()->ns_list_contents(out); } diff --git a/panda/src/pgraph/shaderPool.cxx b/panda/src/pgraph/shaderPool.cxx index ba9f99e8c2..0806b5ed32 100644 --- a/panda/src/pgraph/shaderPool.cxx +++ b/panda/src/pgraph/shaderPool.cxx @@ -19,13 +19,13 @@ #include "shader.h" #include "string_utils.h" -ShaderPool *ShaderPool::_global_ptr = (ShaderPool *)NULL; +ShaderPool *ShaderPool::_global_ptr = nullptr; /** * Lists the contents of the shader pool to the indicated output stream. */ void ShaderPool:: -write(ostream &out) { +write(std::ostream &out) { get_ptr()->ns_list_contents(out); } @@ -77,7 +77,7 @@ ns_load_shader(const Filename &orig_filename) { // the file extension. This is really just guesswork - there are no // standardized extensions for shaders, especially for GLSL. These are the // ones that appear to be closest to "standard". - string ext = downcase(filename.get_extension()); + std::string ext = downcase(filename.get_extension()); if (ext == "cg" || ext == "sha") { // "sha" is for historical reasons. lang = Shader::SL_Cg; @@ -89,9 +89,9 @@ ns_load_shader(const Filename &orig_filename) { } PT(Shader) shader = Shader::load(filename, lang); - if (shader == (Shader *)NULL) { + if (shader == nullptr) { // This shader was not found or could not be read. - return NULL; + return nullptr; } { @@ -182,7 +182,7 @@ ns_garbage_collect() { * The nonstatic implementation of list_contents(). */ void ShaderPool:: -ns_list_contents(ostream &out) const { +ns_list_contents(std::ostream &out) const { LightMutexHolder holder(_lock); out << _shaders.size() << " shaders:\n"; @@ -211,7 +211,7 @@ resolve_filename(Filename &new_filename, const Filename &orig_filename) { */ ShaderPool *ShaderPool:: get_ptr() { - if (_global_ptr == (ShaderPool *)NULL) { + if (_global_ptr == nullptr) { _global_ptr = new ShaderPool; } return _global_ptr; diff --git a/panda/src/pgraph/shaderPool.h b/panda/src/pgraph/shaderPool.h index ca9ee694fc..def32ab2d6 100644 --- a/panda/src/pgraph/shaderPool.h +++ b/panda/src/pgraph/shaderPool.h @@ -36,8 +36,8 @@ PUBLISHED: INLINE static int garbage_collect(); - INLINE static void list_contents(ostream &out); - static void write(ostream &out); + INLINE static void list_contents(std::ostream &out); + static void write(std::ostream &out); private: INLINE ShaderPool(); @@ -48,7 +48,7 @@ private: void ns_release_shader(const Filename &orig_filename); void ns_release_all_shaders(); int ns_garbage_collect(); - void ns_list_contents(ostream &out) const; + void ns_list_contents(std::ostream &out) const; void resolve_filename(Filename &new_filename, const Filename &orig_filename); diff --git a/panda/src/pgraph/stateMunger.cxx b/panda/src/pgraph/stateMunger.cxx index db94c81ba8..5b52442db0 100644 --- a/panda/src/pgraph/stateMunger.cxx +++ b/panda/src/pgraph/stateMunger.cxx @@ -32,15 +32,15 @@ munge_state(const RenderState *state) { int id = get_gsg()->_id; int mi = munged_states.find(id); if (mi != -1) { - if (!munged_states.get_data(mi).was_deleted()) { - return munged_states.get_data(mi).p(); + if (auto munged_state = munged_states.get_data(mi).lock()) { + return munged_state; } else { munged_states.remove_element(mi); } } CPT(RenderState) result = munge_state_impl(state); - munged_states.store(id, result.p()); + munged_states.store(id, result); return result; } diff --git a/panda/src/pgraph/stencilAttrib.cxx b/panda/src/pgraph/stencilAttrib.cxx index 13a00165ed..52b047652b 100644 --- a/panda/src/pgraph/stencilAttrib.cxx +++ b/panda/src/pgraph/stencilAttrib.cxx @@ -264,7 +264,7 @@ make_2_sided_with_clear( * */ void StencilAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { int index; for (index = 0; index < SRS_total; index++) { diff --git a/panda/src/pgraph/stencilAttrib.h b/panda/src/pgraph/stencilAttrib.h index 6b0b773581..6382bc3cd3 100644 --- a/panda/src/pgraph/stencilAttrib.h +++ b/panda/src/pgraph/stencilAttrib.h @@ -139,7 +139,7 @@ PUBLISHED: public: static const char *stencil_render_state_name_array [SRS_total]; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/test_pgraph.cxx b/panda/src/pgraph/test_pgraph.cxx index 45df2fe578..cb2e3a4dde 100644 --- a/panda/src/pgraph/test_pgraph.cxx +++ b/panda/src/pgraph/test_pgraph.cxx @@ -17,13 +17,15 @@ #include "findApproxLevelEntry.h" #include "clockObject.h" +using std::cerr; + NodePath -build_tree(const string &name, int depth) { +build_tree(const std::string &name, int depth) { NodePath node(name); if (depth > 1) { for (int i = 0; i < 3; i++) { char letter = 'a' + i; - string child_name = name + string(1, letter); + std::string child_name = name + std::string(1, letter); NodePath child = build_tree(child_name, depth - 1); child.reparent_to(node); } diff --git a/panda/src/pgraph/texGenAttrib.cxx b/panda/src/pgraph/texGenAttrib.cxx index 451eacab83..32216dab88 100644 --- a/panda/src/pgraph/texGenAttrib.cxx +++ b/panda/src/pgraph/texGenAttrib.cxx @@ -38,7 +38,7 @@ CPT(RenderAttrib) TexGenAttrib:: make() { // We make it a special case and store a pointer to the empty attrib forever // once we find it the first time, as an optimization. - if (_empty_attrib == (RenderAttrib *)NULL) { + if (_empty_attrib == nullptr) { _empty_attrib = return_new(new TexGenAttrib); } @@ -190,7 +190,7 @@ get_constant_value(TextureStage *stage) const { * */ void TexGenAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; Stages::const_iterator mi; diff --git a/panda/src/pgraph/texGenAttrib.h b/panda/src/pgraph/texGenAttrib.h index b9e1cd273a..0bd9e463e8 100644 --- a/panda/src/pgraph/texGenAttrib.h +++ b/panda/src/pgraph/texGenAttrib.h @@ -61,7 +61,7 @@ PUBLISHED: INLINE int get_geom_rendering(int geom_rendering) const; public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; @@ -79,7 +79,7 @@ private: INLINE ModeDef(); INLINE int compare_to(const ModeDef &other) const; Mode _mode; - string _source_name; + std::string _source_name; NodePath _light; LTexCoord3 _constant_value; }; diff --git a/panda/src/pgraph/texMatrixAttrib.cxx b/panda/src/pgraph/texMatrixAttrib.cxx index 4e2e1adba8..f32e0a8b97 100644 --- a/panda/src/pgraph/texMatrixAttrib.cxx +++ b/panda/src/pgraph/texMatrixAttrib.cxx @@ -38,7 +38,7 @@ CPT(RenderAttrib) TexMatrixAttrib:: make() { // We make it a special case and store a pointer to the empty attrib forever // once we find it the first time, as an optimization. - if (_empty_attrib == (RenderAttrib *)NULL) { + if (_empty_attrib == nullptr) { _empty_attrib = return_new(new TexMatrixAttrib); } @@ -148,7 +148,7 @@ get_num_stages() const { */ TextureStage *TexMatrixAttrib:: get_stage(int n) const { - nassertr(n >= 0 && n < (int)_stages.size(), NULL); + nassertr(n >= 0 && n < (int)_stages.size(), nullptr); return _stages[n]._stage; } @@ -179,7 +179,7 @@ get_transform(TextureStage *stage) const { * */ void TexMatrixAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; Stages::const_iterator mi; @@ -504,7 +504,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { override = scan.get_int32(); } - StageNode sn(NULL); + StageNode sn(nullptr); sn._override = override; _stages.push_back(sn); } diff --git a/panda/src/pgraph/texMatrixAttrib.h b/panda/src/pgraph/texMatrixAttrib.h index f68238cf9f..28034a5afa 100644 --- a/panda/src/pgraph/texMatrixAttrib.h +++ b/panda/src/pgraph/texMatrixAttrib.h @@ -60,7 +60,7 @@ PUBLISHED: INLINE int get_geom_rendering(int geom_rendering) const; public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/texProjectorEffect.I b/panda/src/pgraph/texProjectorEffect.I index 35e699476e..067d023574 100644 --- a/panda/src/pgraph/texProjectorEffect.I +++ b/panda/src/pgraph/texProjectorEffect.I @@ -34,7 +34,7 @@ TexProjectorEffect(const TexProjectorEffect ©) : */ INLINE TexProjectorEffect::StageDef:: StageDef() : - _to_lens_node(NULL) + _to_lens_node(nullptr) { } diff --git a/panda/src/pgraph/texProjectorEffect.cxx b/panda/src/pgraph/texProjectorEffect.cxx index a8f0078dea..456c6556e2 100644 --- a/panda/src/pgraph/texProjectorEffect.cxx +++ b/panda/src/pgraph/texProjectorEffect.cxx @@ -39,7 +39,7 @@ CPT(RenderEffect) TexProjectorEffect:: make() { // We make it a special case and store a pointer to the empty effect forever // once we find it the first time, as an optimization. - if (_empty_effect == (RenderEffect *)NULL) { + if (_empty_effect == nullptr) { _empty_effect = return_new(new TexProjectorEffect); } @@ -142,7 +142,7 @@ get_lens_index(TextureStage *stage) const { * */ void TexProjectorEffect:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; Stages::const_iterator mi; @@ -189,18 +189,18 @@ cull_callback(CullTraverser *trav, CullTraverserData &data, CPT(TransformState) transform = def._from.get_transform(def._to); - if (def._to_lens_node != (LensNode *)NULL && - def._to_lens_node->get_lens() != (Lens *)NULL) { + if (def._to_lens_node != nullptr && + def._to_lens_node->get_lens() != nullptr) { // Get the lens's projection matrix, as a TransformState. Lens *lens = def._to_lens_node->get_lens(def._lens_index); - if (lens != NULL) { + if (lens != nullptr) { CPT(TransformState) projmat = TransformState::make_mat(lens->get_projection_mat()); // We need a special transform to convert the -0.5, 0.5 centering of // the lens's projection matrix to UV's in the range of (0, 1). static CPT(TransformState) fixmat; - if (fixmat == (TransformState *)NULL) { + if (fixmat == nullptr) { fixmat = TransformState::make_pos_hpr_scale (LVecBase3(0.5f, 0.5f, 0.0f), LVecBase3(0.0f, 0.0f, 0.0f), @@ -357,6 +357,6 @@ set_to(const NodePath &to) { if (!_to.is_empty() && _to.node()->is_of_type(LensNode::get_class_type())) { DCAST_INTO_V(_to_lens_node, _to.node()); } else { - _to_lens_node = (LensNode *)NULL; + _to_lens_node = nullptr; } } diff --git a/panda/src/pgraph/texProjectorEffect.h b/panda/src/pgraph/texProjectorEffect.h index faf70caf82..40418b60af 100644 --- a/panda/src/pgraph/texProjectorEffect.h +++ b/panda/src/pgraph/texProjectorEffect.h @@ -68,7 +68,7 @@ PUBLISHED: int get_lens_index(TextureStage *stage) const; public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; virtual bool has_cull_callback() const; virtual void cull_callback(CullTraverser *trav, CullTraverserData &data, diff --git a/panda/src/pgraph/textureAttrib.I b/panda/src/pgraph/textureAttrib.I index da1feca0be..9ee2f69f62 100644 --- a/panda/src/pgraph/textureAttrib.I +++ b/panda/src/pgraph/textureAttrib.I @@ -60,7 +60,7 @@ is_off() const { INLINE Texture *TextureAttrib:: get_texture() const { if (_on_stages.empty()) { - return NULL; + return nullptr; } check_sorted(); return get_on_texture(filter_to_max(1)->get_on_stage(0)); @@ -80,7 +80,7 @@ get_num_on_stages() const { */ INLINE TextureStage *TextureAttrib:: get_on_stage(int n) const { - nassertr(n >= 0 && n < (int)_render_stages.size(), (TextureStage *)NULL); + nassertr(n >= 0 && n < (int)_render_stages.size(), nullptr); return _render_stages[n]->_stage; } @@ -101,7 +101,7 @@ get_num_on_ff_stages() const { */ INLINE TextureStage *TextureAttrib:: get_on_ff_stage(int n) const { - nassertr(n >= 0 && n < (int)_render_ff_stages.size(), (TextureStage *)NULL); + nassertr(n >= 0 && n < (int)_render_ff_stages.size(), nullptr); return _render_ff_stages[n]->_stage; } @@ -137,7 +137,7 @@ get_on_texture(TextureStage *stage) const { if (si != _on_stages.end()) { return (*si)._texture; } - return NULL; + return nullptr; } /** @@ -183,7 +183,7 @@ get_num_off_stages() const { */ INLINE TextureStage *TextureAttrib:: get_off_stage(int n) const { - nassertr(n >= 0 && n < (int)_off_stages.size(), (TextureStage *)NULL); + nassertr(n >= 0 && n < (int)_off_stages.size(), nullptr); return _off_stages[n]._stage; } diff --git a/panda/src/pgraph/textureAttrib.cxx b/panda/src/pgraph/textureAttrib.cxx index ee3c5a8165..7f9c6ff8b8 100644 --- a/panda/src/pgraph/textureAttrib.cxx +++ b/panda/src/pgraph/textureAttrib.cxx @@ -52,7 +52,7 @@ CPT(RenderAttrib) TextureAttrib:: make() { // We make it a special case and store a pointer to the empty attrib forever // once we find it the first time, as an optimization. - if (_empty_attrib == (RenderAttrib *)NULL) { + if (_empty_attrib == nullptr) { _empty_attrib = return_new(new TextureAttrib); } @@ -67,7 +67,7 @@ CPT(RenderAttrib) TextureAttrib:: make_all_off() { // We make it a special case and store a pointer to the off attrib forever // once we find it the first time, as an optimization. - if (_all_off_attrib == (RenderAttrib *)NULL) { + if (_all_off_attrib == nullptr) { TextureAttrib *attrib = new TextureAttrib; attrib->_off_all_stages = true; _all_off_attrib = return_new(attrib); @@ -345,7 +345,7 @@ lower_attrib_can_override() const { * */ void TextureAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { check_sorted(); out << get_type() << ":"; @@ -768,7 +768,7 @@ write_datagram(BamWriter *manager, Datagram &dg) { for (si = _on_stages.begin(); si != _on_stages.end(); ++si) { TextureStage *stage = (*si)._stage; Texture *tex = (*si)._texture; - nassertv(tex != (Texture *)NULL); + nassertv(tex != nullptr); manager->write_pointer(dg, stage); manager->write_pointer(dg, tex); @@ -811,7 +811,7 @@ complete_pointers(TypedWritable **p_list, BamReader *manager) { // have to do anything special here. Texture *tex = DCAST(Texture, p_list[pi++]); - if (tex != (Texture *)NULL) { + if (tex != nullptr) { StageNode &sn = _on_stages[sni]; sn._stage = ts; sn._texture = tex; @@ -867,7 +867,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { _off_stages.reserve(num_off_stages); for (i = 0; i < num_off_stages; i++) { manager->read_pointer(scan); - _off_stages.push_back(StageNode(NULL)); + _off_stages.push_back(StageNode(nullptr)); } // Read the _on_stages data. @@ -891,9 +891,9 @@ fillin(DatagramIterator &scan, BamReader *manager) { override = scan.get_int32(); } - _next_implicit_sort = max(_next_implicit_sort, implicit_sort + 1); + _next_implicit_sort = std::max(_next_implicit_sort, implicit_sort + 1); Stages::iterator si = - _on_stages.insert_nonunique(StageNode(NULL, _next_implicit_sort, override)); + _on_stages.insert_nonunique(StageNode(nullptr, _next_implicit_sort, override)); ++_next_implicit_sort; if (manager->get_file_minor_ver() >= 36) { @@ -923,8 +923,8 @@ sort_on_stages() { StageNode &sn = (*si); TextureStage *stage = sn._stage; Texture *texture = sn._texture; - nassertv(stage != NULL); - nassertv(texture != NULL); + nassertv(stage != nullptr); + nassertv(texture != nullptr); if (stage->is_fixed_function() && texture->get_texture_type() != Texture::TT_2d_texture_array) { const InternalName *name = stage->get_texcoord_name(); diff --git a/panda/src/pgraph/textureAttrib.h b/panda/src/pgraph/textureAttrib.h index 0938df8d96..908e4c50af 100644 --- a/panda/src/pgraph/textureAttrib.h +++ b/panda/src/pgraph/textureAttrib.h @@ -94,7 +94,7 @@ public: CPT(TextureAttrib) filter_to_max(int max_texture_stages) const; virtual bool lower_attrib_can_override() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; virtual bool has_cull_callback() const; virtual bool cull_callback(CullTraverser *trav, const CullTraverserData &data) const; diff --git a/panda/src/pgraph/textureStageCollection.cxx b/panda/src/pgraph/textureStageCollection.cxx index 4f707efe63..b7fe96d885 100644 --- a/panda/src/pgraph/textureStageCollection.cxx +++ b/panda/src/pgraph/textureStageCollection.cxx @@ -176,7 +176,7 @@ clear() { * any, or NULL if no texture_stage has that name. */ TextureStage *TextureStageCollection:: -find_texture_stage(const string &name) const { +find_texture_stage(const std::string &name) const { int num_texture_stages = get_num_texture_stages(); for (int i = 0; i < num_texture_stages; i++) { TextureStage *texture_stage = get_texture_stage(i); @@ -184,7 +184,7 @@ find_texture_stage(const string &name) const { return texture_stage; } } - return NULL; + return nullptr; } /** @@ -200,7 +200,7 @@ get_num_texture_stages() const { */ TextureStage *TextureStageCollection:: get_texture_stage(int index) const { - nassertr(index >= 0 && index < (int)_texture_stages.size(), NULL); + nassertr(index >= 0 && index < (int)_texture_stages.size(), nullptr); return _texture_stages[index]; } @@ -211,7 +211,7 @@ get_texture_stage(int index) const { */ TextureStage *TextureStageCollection:: operator [] (int index) const { - nassertr(index >= 0 && index < (int)_texture_stages.size(), NULL); + nassertr(index >= 0 && index < (int)_texture_stages.size(), nullptr); return _texture_stages[index]; } @@ -231,8 +231,8 @@ size() const { */ void TextureStageCollection:: sort() { - ::sort(_texture_stages.begin(), _texture_stages.end(), - CompareTextureStageSort()); + std::sort(_texture_stages.begin(), _texture_stages.end(), + CompareTextureStageSort()); } /** @@ -240,7 +240,7 @@ sort() { * indicated output stream. */ void TextureStageCollection:: -output(ostream &out) const { +output(std::ostream &out) const { if (get_num_texture_stages() == 1) { out << "1 TextureStage"; } else { @@ -253,7 +253,7 @@ output(ostream &out) const { * the indicated output stream. */ void TextureStageCollection:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { for (int i = 0; i < get_num_texture_stages(); i++) { indent(out, indent_level) << *get_texture_stage(i) << "\n"; } diff --git a/panda/src/pgraph/textureStageCollection.h b/panda/src/pgraph/textureStageCollection.h index 002447decc..d29a5c222d 100644 --- a/panda/src/pgraph/textureStageCollection.h +++ b/panda/src/pgraph/textureStageCollection.h @@ -36,7 +36,7 @@ PUBLISHED: bool has_texture_stage(TextureStage *texture_stage) const; void clear(); - TextureStage *find_texture_stage(const string &name) const; + TextureStage *find_texture_stage(const std::string &name) const; int get_num_texture_stages() const; TextureStage *get_texture_stage(int index) const; @@ -48,8 +48,8 @@ PUBLISHED: void sort(); - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; private: typedef PTA(PT(TextureStage)) TextureStages; @@ -62,7 +62,7 @@ private: }; -INLINE ostream &operator << (ostream &out, const TextureStageCollection &col) { +INLINE std::ostream &operator << (std::ostream &out, const TextureStageCollection &col) { col.output(out); return out; } diff --git a/panda/src/pgraph/transformState.cxx b/panda/src/pgraph/transformState.cxx index bff497298e..453fb505b4 100644 --- a/panda/src/pgraph/transformState.cxx +++ b/panda/src/pgraph/transformState.cxx @@ -24,8 +24,10 @@ #include "lightMutexHolder.h" #include "thread.h" -LightReMutex *TransformState::_states_lock = NULL; -TransformState::States *TransformState::_states = NULL; +using std::ostream; + +LightReMutex *TransformState::_states_lock = nullptr; +TransformState::States *TransformState::_states = nullptr; CPT(TransformState) TransformState::_identity_state; CPT(TransformState) TransformState::_invalid_state; UpdateSeq TransformState::_last_cycle_detect; @@ -55,12 +57,12 @@ TypeHandle TransformState::_type_handle; */ TransformState:: TransformState() : _lock("TransformState") { - if (_states == (States *)NULL) { + if (_states == nullptr) { init_states(); } _saved_entry = -1; _flags = F_is_identity | F_singular_known | F_is_2d; - _inv_mat = (LMatrix4 *)NULL; + _inv_mat = nullptr; _cache_stats.add_num_states(1); #ifdef DO_MEMORY_USAGE @@ -68,22 +70,6 @@ TransformState() : _lock("TransformState") { #endif } -/** - * TransformStates are not meant to be copied. - */ -TransformState:: -TransformState(const TransformState &) { - nassertv(false); -} - -/** - * TransformStates are not meant to be copied. - */ -void TransformState:: -operator = (const TransformState &) { - nassertv(false); -} - /** * The destructor is responsible for removing the TransformState from the * global set if it is there. @@ -95,9 +81,9 @@ TransformState:: set_destructing(); // Free the inverse matrix computation, if it has been stored. - if (_inv_mat != (LMatrix4 *)NULL) { + if (_inv_mat != nullptr) { delete _inv_mat; - _inv_mat = (LMatrix4 *)NULL; + _inv_mat = nullptr; } LightReMutexHolder holder(*_states_lock); @@ -251,7 +237,7 @@ CPT(TransformState) TransformState:: make_identity() { // The identity state is asked for so often, we make it a special case and // store a pointer forever once we find it the first time. - if (_identity_state == (TransformState *)NULL) { + if (_identity_state == nullptr) { TransformState *state = new TransformState; _identity_state = return_unique(state); } @@ -265,7 +251,7 @@ make_identity() { */ CPT(TransformState) TransformState:: make_invalid() { - if (_invalid_state == (TransformState *)NULL) { + if (_invalid_state == nullptr) { TransformState *state = new TransformState; state->_flags = F_is_invalid | F_singular_known | F_is_singular | F_components_known | F_mat_known; _invalid_state = return_unique(state); @@ -663,7 +649,7 @@ compose(const TransformState *other) const { if (other != this) { _cache_stats.add_total_size(1); _cache_stats.inc_adds(other->_composition_cache.is_empty()); - other->_composition_cache[this]._result = NULL; + other->_composition_cache[this]._result = nullptr; } if (result != (TransformState *)this) { @@ -769,7 +755,7 @@ invert_compose(const TransformState *other) const { if (other != this) { _cache_stats.add_total_size(1); _cache_stats.inc_adds(other->_invert_composition_cache.is_empty()); - other->_invert_composition_cache[this]._result = NULL; + other->_invert_composition_cache[this]._result = nullptr; } if (result != (TransformState *)this) { @@ -845,7 +831,7 @@ validate_composition_cache() const { size_t size = _composition_cache.get_num_entries(); for (size_t i = 0; i < size; ++i) { const TransformState *source = _composition_cache.get_key(i); - if (source != (TransformState *)NULL) { + if (source != nullptr) { // Check that the source also has a pointer back to this one. We always // add entries to the composition cache in pairs. int ri = source->_composition_cache.find(this); @@ -865,7 +851,7 @@ validate_composition_cache() const { size = _invert_composition_cache.get_num_entries(); for (size_t i = 0; i < size; ++i) { const TransformState *source = _invert_composition_cache.get_key(i); - if (source != (TransformState *)NULL) { + if (source != nullptr) { // Check that the source also has a pointer back to this one. We always // add entries to the composition cache in pairs. int ri = source->_invert_composition_cache.find(this); @@ -998,7 +984,7 @@ write_composition_cache(ostream &out, int indent_level) const { */ int TransformState:: get_num_states() { - if (_states == (States *)NULL) { + if (_states == nullptr) { return 0; } LightReMutexHolder holder(*_states_lock); @@ -1020,7 +1006,7 @@ get_num_states() { */ int TransformState:: get_num_unused_states() { - if (_states == (States *)NULL) { + if (_states == nullptr) { return 0; } LightReMutexHolder holder(*_states_lock); @@ -1039,9 +1025,9 @@ get_num_unused_states() { size_t cache_size = state->_composition_cache.get_num_entries(); for (i = 0; i < cache_size; ++i) { const TransformState *result = state->_composition_cache.get_data(i)._result; - if (result != (const TransformState *)NULL && result != state) { + if (result != nullptr && result != state) { // Here's a TransformState that's recorded in the cache. Count it. - pair ir = + std::pair ir = state_count.insert(StateCount::value_type(result, 1)); if (!ir.second) { // If the above insert operation fails, then it's already in the @@ -1053,8 +1039,8 @@ get_num_unused_states() { cache_size = state->_invert_composition_cache.get_num_entries(); for (i = 0; i < cache_size; ++i) { const TransformState *result = state->_invert_composition_cache.get_data(i)._result; - if (result != (const TransformState *)NULL && result != state) { - pair ir = + if (result != nullptr && result != state) { + std::pair ir = state_count.insert(StateCount::value_type(result, 1)); if (!ir.second) { (*(ir.first)).second++; @@ -1105,7 +1091,7 @@ get_num_unused_states() { */ int TransformState:: clear_cache() { - if (_states == (States *)NULL) { + if (_states == nullptr) { return 0; } LightReMutexHolder holder(*_states_lock); @@ -1138,7 +1124,7 @@ clear_cache() { size_t cache_size = state->_composition_cache.get_num_entries(); for (i = 0; i < cache_size; ++i) { const TransformState *result = state->_composition_cache.get_data(i)._result; - if (result != (const TransformState *)NULL && result != state) { + if (result != nullptr && result != state) { result->cache_unref(); nassertr(result->get_ref_count() > 0, 0); } @@ -1149,7 +1135,7 @@ clear_cache() { cache_size = state->_invert_composition_cache.get_num_entries(); for (i = 0; i < cache_size; ++i) { const TransformState *result = state->_invert_composition_cache.get_data(i)._result; - if (result != (const TransformState *)NULL && result != state) { + if (result != nullptr && result != state) { result->cache_unref(); nassertr(result->get_ref_count() > 0, 0); } @@ -1175,7 +1161,7 @@ clear_cache() { */ int TransformState:: garbage_collect() { - if (_states == (States *)NULL || !garbage_collect_states) { + if (_states == nullptr || !garbage_collect_states) { return 0; } @@ -1186,7 +1172,7 @@ garbage_collect() { // How many elements to process this pass? size_t size = orig_size; - size_t num_this_pass = max(0, int(size * garbage_collect_states_rate)); + size_t num_this_pass = std::max(0, int(size * garbage_collect_states_rate)); if (num_this_pass <= 0) { return 0; } @@ -1198,7 +1184,7 @@ garbage_collect() { si = 0; } - num_this_pass = min(num_this_pass, size); + num_this_pass = std::min(num_this_pass, size); size_t stop_at_element = (si + num_this_pass) % size; do { @@ -1264,7 +1250,7 @@ garbage_collect() { */ void TransformState:: list_cycles(ostream &out) { - if (_states == (States *)NULL) { + if (_states == nullptr) { return; } LightReMutexHolder holder(*_states_lock); @@ -1341,7 +1327,7 @@ list_cycles(ostream &out) { */ void TransformState:: list_states(ostream &out) { - if (_states == (States *)NULL) { + if (_states == nullptr) { out << "0 states:\n"; return; } @@ -1363,7 +1349,7 @@ list_states(ostream &out) { */ bool TransformState:: validate_states() { - if (_states == (States *)NULL) { + if (_states == nullptr) { return true; } @@ -1454,7 +1440,7 @@ init_states() { */ CPT(TransformState) TransformState:: return_new(TransformState *state) { - nassertr(state != (TransformState *)NULL, state); + nassertr(state != nullptr, state); if (!uniquify_transforms && !state->is_identity()) { return state; } @@ -1473,7 +1459,7 @@ return_new(TransformState *state) { */ CPT(TransformState) TransformState:: return_unique(TransformState *state) { - nassertr(state != (TransformState *)NULL, state); + nassertr(state != nullptr, state); if (!transform_cache) { return state; @@ -1679,7 +1665,7 @@ do_invert_compose(const TransformState *other) const { pgraph_cat.warning() << "Unexpected singular matrix found for " << *this << "\n"; } else { - nassertr(_inv_mat != (LMatrix4 *)NULL, make_invalid()); + nassertr(_inv_mat != nullptr, make_invalid()); LMatrix4 new_mat; new_mat.multiply(other->get_mat(), *_inv_mat); if (!new_mat.almost_equal(result->get_mat(), 0.1)) { @@ -1703,7 +1689,7 @@ do_invert_compose(const TransformState *other) const { // Now that is_singular() has returned false, we can assume that _inv_mat // has been allocated and filled in. - nassertr(_inv_mat != (LMatrix4 *)NULL, make_invalid()); + nassertr(_inv_mat != nullptr, make_invalid()); if (is_2d() && other->is_2d()) { const LMatrix4 &i = *_inv_mat; @@ -1733,7 +1719,7 @@ detect_and_break_cycles() { PStatTimer timer(_transform_break_cycles_pcollector); ++_last_cycle_detect; - if (r_detect_cycles(this, this, 1, _last_cycle_detect, NULL)) { + if (r_detect_cycles(this, this, 1, _last_cycle_detect, nullptr)) { // Ok, we have a cycle. This will be a leak unless we break the cycle by // freeing the cache on this object. if (pgraph_cat.is_debug()) { @@ -1744,7 +1730,7 @@ detect_and_break_cycles() { remove_cache_pointers(); } else { ++_last_cycle_detect; - if (r_detect_reverse_cycles(this, this, 1, _last_cycle_detect, NULL)) { + if (r_detect_reverse_cycles(this, this, 1, _last_cycle_detect, nullptr)) { if (pgraph_cat.is_debug()) { pgraph_cat.debug() << "Breaking cycle involving " << (*this) << "\n"; @@ -1781,11 +1767,11 @@ r_detect_cycles(const TransformState *start_state, size_t cache_size = current_state->_composition_cache.get_num_entries(); for (i = 0; i < cache_size; ++i) { const TransformState *result = current_state->_composition_cache.get_data(i)._result; - if (result != (const TransformState *)NULL) { + if (result != nullptr) { if (r_detect_cycles(start_state, result, length + 1, this_seq, cycle_desc)) { // Cycle detected. - if (cycle_desc != (CompositionCycleDesc *)NULL) { + if (cycle_desc != nullptr) { const TransformState *other = current_state->_composition_cache.get_key(i); CompositionCycleDescEntry entry(other, result, false); cycle_desc->push_back(entry); @@ -1798,11 +1784,11 @@ r_detect_cycles(const TransformState *start_state, cache_size = current_state->_invert_composition_cache.get_num_entries(); for (i = 0; i < cache_size; ++i) { const TransformState *result = current_state->_invert_composition_cache.get_data(i)._result; - if (result != (const TransformState *)NULL) { + if (result != nullptr) { if (r_detect_cycles(start_state, result, length + 1, this_seq, cycle_desc)) { // Cycle detected. - if (cycle_desc != (CompositionCycleDesc *)NULL) { + if (cycle_desc != nullptr) { const TransformState *other = current_state->_invert_composition_cache.get_key(i); CompositionCycleDescEntry entry(other, result, true); cycle_desc->push_back(entry); @@ -1845,11 +1831,11 @@ r_detect_reverse_cycles(const TransformState *start_state, nassertr(oi != -1, false); const TransformState *result = other->_composition_cache.get_data(oi)._result; - if (result != (const TransformState *)NULL) { + if (result != nullptr) { if (r_detect_reverse_cycles(start_state, result, length + 1, this_seq, cycle_desc)) { // Cycle detected. - if (cycle_desc != (CompositionCycleDesc *)NULL) { + if (cycle_desc != nullptr) { const TransformState *other = current_state->_composition_cache.get_key(i); CompositionCycleDescEntry entry(other, result, false); cycle_desc->push_back(entry); @@ -1868,11 +1854,11 @@ r_detect_reverse_cycles(const TransformState *start_state, nassertr(oi != -1, false); const TransformState *result = other->_invert_composition_cache.get_data(oi)._result; - if (result != (const TransformState *)NULL) { + if (result != nullptr) { if (r_detect_reverse_cycles(start_state, result, length + 1, this_seq, cycle_desc)) { // Cycle detected. - if (cycle_desc != (CompositionCycleDesc *)NULL) { + if (cycle_desc != nullptr) { const TransformState *other = current_state->_invert_composition_cache.get_key(i); CompositionCycleDescEntry entry(other, result, false); cycle_desc->push_back(entry); @@ -1977,7 +1963,7 @@ remove_cache_pointers() { // It's finally safe to let our held pointers go away. This may have // cascading effects as other TransformState objects are destructed, // but there will be no harm done if they destruct now. - if (ocomp._result != (const TransformState *)NULL && ocomp._result != other) { + if (ocomp._result != nullptr && ocomp._result != other) { cache_unref_delete(ocomp._result); } } @@ -1985,7 +1971,7 @@ remove_cache_pointers() { // It's finally safe to let our held pointers go away. (See comment // above.) - if (comp._result != (const TransformState *)NULL && comp._result != this) { + if (comp._result != nullptr && comp._result != this) { cache_unref_delete(comp._result); } } @@ -2006,12 +1992,12 @@ remove_cache_pointers() { other->_invert_composition_cache.remove_element(oi); _cache_stats.add_total_size(-1); _cache_stats.inc_dels(); - if (ocomp._result != (const TransformState *)NULL && ocomp._result != other) { + if (ocomp._result != nullptr && ocomp._result != other) { cache_unref_delete(ocomp._result); } } } - if (comp._result != (const TransformState *)NULL && comp._result != this) { + if (comp._result != nullptr && comp._result != this) { cache_unref_delete(comp._result); } } @@ -2093,7 +2079,7 @@ calc_singular() { // is asking whether we're singular). // This should be NULL if no one has called calc_singular() yet. - nassertv(_inv_mat == (LMatrix4 *)NULL); + nassertv(_inv_mat == nullptr); _inv_mat = new LMatrix4; if ((_flags & F_mat_known) == 0) { @@ -2104,7 +2090,7 @@ calc_singular() { if (!inverted) { _flags |= F_is_singular; delete _inv_mat; - _inv_mat = (LMatrix4 *)NULL; + _inv_mat = nullptr; } _flags |= F_singular_known; } diff --git a/panda/src/pgraph/transformState.h b/panda/src/pgraph/transformState.h index b770e7bf52..75b4fedb0e 100644 --- a/panda/src/pgraph/transformState.h +++ b/panda/src/pgraph/transformState.h @@ -51,18 +51,17 @@ class FactoryParams; * directly. Instead, call one of the make() functions to create one for you. * And instead of modifying a TransformState object, create a new one. */ -class EXPCL_PANDA_PGRAPH TransformState FINAL : public NodeCachedReferenceCount { +class EXPCL_PANDA_PGRAPH TransformState final : public NodeCachedReferenceCount { protected: TransformState(); -private: - TransformState(const TransformState ©); - void operator = (const TransformState ©); - public: + TransformState(const TransformState ©) = delete; virtual ~TransformState(); ALLOC_DELETED_CHAIN(TransformState); + TransformState &operator = (const TransformState ©) = delete; + PUBLISHED: INLINE bool operator != (const TransformState &other) const; INLINE int compare_to(const TransformState &other) const; @@ -195,16 +194,16 @@ PUBLISHED: EXTENSION(PyObject *get_composition_cache() const); EXTENSION(PyObject *get_invert_composition_cache() const); - void output(ostream &out) const; - void write(ostream &out, int indent_level) const; - void write_composition_cache(ostream &out, int indent_level) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level) const; + void write_composition_cache(std::ostream &out, int indent_level) const; static int get_num_states(); static int get_num_unused_states(); static int clear_cache(); static int garbage_collect(); - static void list_cycles(ostream &out); - static void list_states(ostream &out); + static void list_cycles(std::ostream &out); + static void list_states(std::ostream &out); static bool validate_states(); EXTENSION(static PyObject *get_states()); EXTENSION(static PyObject *get_unused_states()); @@ -253,7 +252,7 @@ private: // cache, which is encoded in _composition_cache and // _invert_composition_cache. static LightReMutex *_states_lock; - typedef SimpleHashMap > States; + typedef SimpleHashMap > States; static States *_states; static CPT(TransformState) _identity_state; static CPT(TransformState) _invalid_state; @@ -408,7 +407,7 @@ private: template<> INLINE void PointerToBase::update_type(To *ptr) {} -INLINE ostream &operator << (ostream &out, const TransformState &state) { +INLINE std::ostream &operator << (std::ostream &out, const TransformState &state) { state.output(out); return out; } diff --git a/panda/src/pgraph/transformState_ext.cxx b/panda/src/pgraph/transformState_ext.cxx index 44ddfd71f8..08a47b92cd 100644 --- a/panda/src/pgraph/transformState_ext.cxx +++ b/panda/src/pgraph/transformState_ext.cxx @@ -41,7 +41,7 @@ get_composition_cache() const { PyObject *a, *b; const TransformState *source = _this->_composition_cache.get_key(si); - if (source == (TransformState *)NULL) { + if (source == nullptr) { a = Py_None; Py_INCREF(a); } else { @@ -50,7 +50,7 @@ get_composition_cache() const { true, true, source->get_type_index()); } const TransformState *result = _this->_composition_cache.get_data(si)._result; - if (result == (TransformState *)NULL) { + if (result == nullptr) { b = Py_None; Py_INCREF(b); } else { @@ -96,7 +96,7 @@ get_invert_composition_cache() const { PyObject *a, *b; const TransformState *source = _this->_invert_composition_cache.get_key(si); - if (source == (TransformState *)NULL) { + if (source == nullptr) { a = Py_None; Py_INCREF(a); } else { @@ -105,7 +105,7 @@ get_invert_composition_cache() const { true, true, source->get_type_index()); } const TransformState *result = _this->_invert_composition_cache.get_data(si)._result; - if (result == (TransformState *)NULL) { + if (result == nullptr) { b = Py_None; Py_INCREF(b); } else { @@ -132,7 +132,7 @@ get_invert_composition_cache() const { PyObject *Extension:: get_states() { extern struct Dtool_PyTypedObject Dtool_TransformState; - if (TransformState::_states == (TransformState::States *)NULL) { + if (TransformState::_states == nullptr) { return PyList_New(0); } LightReMutexHolder holder(*TransformState::_states_lock); @@ -163,7 +163,7 @@ get_states() { PyObject *Extension:: get_unused_states() { extern struct Dtool_PyTypedObject Dtool_TransformState; - if (TransformState::_states == (TransformState::States *)NULL) { + if (TransformState::_states == nullptr) { return PyList_New(0); } LightReMutexHolder holder(*TransformState::_states_lock); diff --git a/panda/src/pgraph/transparencyAttrib.cxx b/panda/src/pgraph/transparencyAttrib.cxx index ad105f3214..146e0aa5b4 100644 --- a/panda/src/pgraph/transparencyAttrib.cxx +++ b/panda/src/pgraph/transparencyAttrib.cxx @@ -44,7 +44,7 @@ make_default() { * */ void TransparencyAttrib:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << ":"; switch (get_mode()) { case M_none: diff --git a/panda/src/pgraph/transparencyAttrib.h b/panda/src/pgraph/transparencyAttrib.h index 75af58c64e..4021697596 100644 --- a/panda/src/pgraph/transparencyAttrib.h +++ b/panda/src/pgraph/transparencyAttrib.h @@ -54,7 +54,7 @@ PUBLISHED: MAKE_PROPERTY(mode, get_mode); public: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual int compare_to_impl(const RenderAttrib *other) const; diff --git a/panda/src/pgraph/weakNodePath.I b/panda/src/pgraph/weakNodePath.I index 36cdbdbf60..c2d4b0a523 100644 --- a/panda/src/pgraph/weakNodePath.I +++ b/panda/src/pgraph/weakNodePath.I @@ -56,12 +56,30 @@ operator = (const WeakNodePath ©) { _backup_key = copy._backup_key; } +/** + * Sets this NodePath to the empty NodePath. It will no longer point to any + * node. + */ +INLINE void WeakNodePath:: +clear() { + _head.clear(); + _backup_key = 0; +} + +/** + * Returns true if this NodePath points to a valid, non-null node. + */ +INLINE WeakNodePath:: +operator bool () const { + return _head.is_valid_pointer(); +} + /** * Returns true if the NodePath contains no nodes, or if it has been deleted. */ INLINE bool WeakNodePath:: is_empty() const { - return _head == (NodePathComponent *)NULL || _head.was_deleted(); + return _head == nullptr || _head.was_deleted(); } /** @@ -70,27 +88,34 @@ is_empty() const { */ INLINE bool WeakNodePath:: was_deleted() const { - return _head != (NodePathComponent *)NULL && _head.was_deleted(); + return _head != nullptr && _head.was_deleted(); } /** - * Returns the NodePath held within this object. + * Returns the NodePath held within this object, or an empty NodePath with the + * error flag set if the object was deleted. */ INLINE NodePath WeakNodePath:: get_node_path() const { - nassertr_always(!was_deleted(), NodePath::fail()); NodePath result; - result._head = _head; + result._head = _head.lock(); + if (!_head.is_null() && result._head == nullptr) { + result._error_type = NodePath::ET_fail; + } return result; } /** - * Returns the PandaNode held within this object. + * Returns the PandaNode held within this object, or nullptr if the object was + * deleted. */ -INLINE PandaNode *WeakNodePath:: +INLINE PT(PandaNode) WeakNodePath:: node() const { - nassertr_always(!is_empty(), (PandaNode *)NULL); - return _head->get_node(); + if (auto head = _head.lock()) { + return head->get_node(); + } else { + return nullptr; + } } /** @@ -190,14 +215,13 @@ compare_to(const WeakNodePath &other) const { */ INLINE int WeakNodePath:: get_key() const { - if (is_empty() || was_deleted()) { - return _backup_key; + if (auto head = _head.lock()) { + _backup_key = head->get_key(); } - ((WeakNodePath *)this)->_backup_key = _head->get_key(); return _backup_key; } -INLINE ostream &operator << (ostream &out, const WeakNodePath &node_path) { +INLINE std::ostream &operator << (std::ostream &out, const WeakNodePath &node_path) { node_path.output(out); return out; } diff --git a/panda/src/pgraph/weakNodePath.cxx b/panda/src/pgraph/weakNodePath.cxx index a83d797cc9..c4d75aad5e 100644 --- a/panda/src/pgraph/weakNodePath.cxx +++ b/panda/src/pgraph/weakNodePath.cxx @@ -17,7 +17,7 @@ * */ void WeakNodePath:: -output(ostream &out) const { +output(std::ostream &out) const { if (was_deleted()) { out << "deleted"; } else { diff --git a/panda/src/pgraph/weakNodePath.h b/panda/src/pgraph/weakNodePath.h index e5b9b79c90..1137c8f46b 100644 --- a/panda/src/pgraph/weakNodePath.h +++ b/panda/src/pgraph/weakNodePath.h @@ -30,7 +30,7 @@ * associated NodePath. */ class EXPCL_PANDA_PGRAPH WeakNodePath { -public: +PUBLISHED: INLINE WeakNodePath(const NodePath &node_path); INLINE WeakNodePath(const WeakNodePath ©); INLINE ~WeakNodePath(); @@ -38,11 +38,14 @@ public: INLINE void operator = (const NodePath &node_path); INLINE void operator = (const WeakNodePath ©); + INLINE void clear(); + + INLINE operator bool () const; INLINE bool is_empty() const; INLINE bool was_deleted() const; INLINE NodePath get_node_path() const; - INLINE PandaNode *node() const; + INLINE PT(PandaNode) node() const; INLINE bool operator == (const NodePath &other) const; INLINE bool operator != (const NodePath &other) const; @@ -56,14 +59,16 @@ public: INLINE int get_key() const; - void output(ostream &out) const; + void output(std::ostream &out) const; private: WPT(NodePathComponent) _head; - int _backup_key; + mutable int _backup_key; + + friend class NodePath; }; -INLINE ostream &operator << (ostream &out, const WeakNodePath &node_path); +INLINE std::ostream &operator << (std::ostream &out, const WeakNodePath &node_path); #include "weakNodePath.I" diff --git a/panda/src/pgraph/workingNodePath.I b/panda/src/pgraph/workingNodePath.I index b74921827b..1b545c29b8 100644 --- a/panda/src/pgraph/workingNodePath.I +++ b/panda/src/pgraph/workingNodePath.I @@ -19,7 +19,7 @@ INLINE WorkingNodePath:: WorkingNodePath(const NodePath &start) { nassertv(!start.is_empty()); - _next = (WorkingNodePath *)NULL; + _next = nullptr; _start = start._head; _node = start.node(); } @@ -33,8 +33,8 @@ WorkingNodePath(const WorkingNodePath ©) : _start(copy._start), _node(copy._node) { - nassertv(_next != (WorkingNodePath *)NULL || - _start != (NodePathComponent *)NULL); + nassertv(_next != nullptr || + _start != nullptr); } /** @@ -66,8 +66,8 @@ operator = (const WorkingNodePath ©) { _start = copy._start; _node = copy._node; - nassertv(_next != (WorkingNodePath *)NULL || - _start != (NodePathComponent *)NULL); + nassertv(_next != nullptr || + _start != nullptr); } /** @@ -78,7 +78,7 @@ INLINE NodePath WorkingNodePath:: get_node_path() const { NodePath result; result._head = r_get_node_path(); - nassertr(result._head != (NodePathComponent *)NULL, NodePath::fail()); + nassertr(result._head != nullptr, NodePath::fail()); return result; } @@ -90,8 +90,8 @@ node() const { return _node; } -INLINE ostream & -operator << (ostream &out, const WorkingNodePath &node_path) { +INLINE std::ostream & +operator << (std::ostream &out, const WorkingNodePath &node_path) { node_path.output(out); return out; } diff --git a/panda/src/pgraph/workingNodePath.cxx b/panda/src/pgraph/workingNodePath.cxx index 42e8bd7141..0431a1fb85 100644 --- a/panda/src/pgraph/workingNodePath.cxx +++ b/panda/src/pgraph/workingNodePath.cxx @@ -20,11 +20,11 @@ */ bool WorkingNodePath:: is_valid() const { - if (_node == (PandaNode *)NULL) { + if (_node == nullptr) { return false; } - if (_next == (WorkingNodePath *)NULL) { - return (_start != (NodePathComponent *)NULL); + if (_next == nullptr) { + return (_start != nullptr); } nassertr(_node != _next->_node, false); @@ -39,7 +39,7 @@ is_valid() const { */ int WorkingNodePath:: get_num_nodes() const { - if (_next == (WorkingNodePath *)NULL) { + if (_next == nullptr) { Thread *current_thread = Thread::get_current_thread(); int pipeline_stage = current_thread->get_pipeline_stage(); return _start->get_length(pipeline_stage, current_thread); @@ -55,12 +55,12 @@ get_num_nodes() const { */ PandaNode *WorkingNodePath:: get_node(int index) const { - nassertr(index >= 0, NULL); + nassertr(index >= 0, nullptr); if (index == 0) { return _node; } - if (_next == (WorkingNodePath *)NULL) { + if (_next == nullptr) { return get_node_path().get_node(index - 1); } @@ -71,7 +71,7 @@ get_node(int index) const { * */ void WorkingNodePath:: -output(ostream &out) const { +output(std::ostream &out) const { // Cheesy and slow, but when you're outputting the thing, presumably you're // not in a hurry. get_node_path().output(out); @@ -83,22 +83,22 @@ output(ostream &out) const { */ PT(NodePathComponent) WorkingNodePath:: r_get_node_path() const { - if (_next == (WorkingNodePath *)NULL) { - nassertr(_start != (NodePathComponent *)NULL, NULL); + if (_next == nullptr) { + nassertr(_start != nullptr, nullptr); return _start; } - nassertr(_start == (NodePathComponent *)NULL, NULL); - nassertr(_node != (PandaNode *)NULL, NULL); + nassertr(_start == nullptr, nullptr); + nassertr(_node != nullptr, nullptr); PT(NodePathComponent) comp = _next->r_get_node_path(); - nassertr(comp != (NodePathComponent *)NULL, NULL); + nassertr(comp != nullptr, nullptr); Thread *current_thread = Thread::get_current_thread(); int pipeline_stage = current_thread->get_pipeline_stage(); PT(NodePathComponent) result = PandaNode::get_component(comp, _node, pipeline_stage, current_thread); - if (result == (NodePathComponent *)NULL) { + if (result == nullptr) { // This means we found a disconnected chain in the WorkingNodePath's // ancestry: the node above this node isn't connected. In this case, // don't attempt to go higher; just truncate the NodePath at the bottom of diff --git a/panda/src/pgraph/workingNodePath.h b/panda/src/pgraph/workingNodePath.h index fefcb6b687..9e698897f5 100644 --- a/panda/src/pgraph/workingNodePath.h +++ b/panda/src/pgraph/workingNodePath.h @@ -53,7 +53,7 @@ public: int get_num_nodes() const; PandaNode *get_node(int index) const; - void output(ostream &out) const; + void output(std::ostream &out) const; PUBLISHED: MAKE_PROPERTY(valid, is_valid); @@ -71,7 +71,7 @@ private: PT(PandaNode) _node; }; -INLINE ostream &operator << (ostream &out, const WorkingNodePath &node_path); +INLINE std::ostream &operator << (std::ostream &out, const WorkingNodePath &node_path); #include "workingNodePath.I" diff --git a/panda/src/pgraphnodes/ambientLight.cxx b/panda/src/pgraphnodes/ambientLight.cxx index d3aae3fb54..deb6eed6cc 100644 --- a/panda/src/pgraphnodes/ambientLight.cxx +++ b/panda/src/pgraphnodes/ambientLight.cxx @@ -23,7 +23,7 @@ TypeHandle AmbientLight::_type_handle; * */ AmbientLight:: -AmbientLight(const string &name) : +AmbientLight(const std::string &name) : LightNode(name) { } @@ -63,7 +63,7 @@ make_copy() const { * */ void AmbientLight:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << *this << ":\n"; indent(out, indent_level + 2) << "color " << get_color() << "\n"; diff --git a/panda/src/pgraphnodes/ambientLight.h b/panda/src/pgraphnodes/ambientLight.h index f3582e54fd..6c9d494b0c 100644 --- a/panda/src/pgraphnodes/ambientLight.h +++ b/panda/src/pgraphnodes/ambientLight.h @@ -25,15 +25,15 @@ */ class EXPCL_PANDA_PGRAPHNODES AmbientLight : public LightNode { PUBLISHED: - explicit AmbientLight(const string &name); + explicit AmbientLight(const std::string &name); protected: AmbientLight(const AmbientLight ©); public: virtual PandaNode *make_copy() const; - virtual void write(ostream &out, int indent_level) const; - virtual bool is_ambient_light() const FINAL; + virtual void write(std::ostream &out, int indent_level) const; + virtual bool is_ambient_light() const final; PUBLISHED: virtual int get_class_priority() const; @@ -68,7 +68,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const AmbientLight &light) { +INLINE std::ostream &operator << (std::ostream &out, const AmbientLight &light) { light.output(out); return out; } diff --git a/panda/src/pgraphnodes/callbackNode.I b/panda/src/pgraphnodes/callbackNode.I index 4db6cb59de..6314f124e3 100644 --- a/panda/src/pgraphnodes/callbackNode.I +++ b/panda/src/pgraphnodes/callbackNode.I @@ -44,7 +44,7 @@ set_cull_callback(CallbackObject *object) { */ INLINE void CallbackNode:: clear_cull_callback() { - set_cull_callback(NULL); + set_cull_callback(nullptr); } /** @@ -86,7 +86,7 @@ set_draw_callback(CallbackObject *object) { */ INLINE void CallbackNode:: clear_draw_callback() { - set_draw_callback(NULL); + set_draw_callback(nullptr); } /** diff --git a/panda/src/pgraphnodes/callbackNode.cxx b/panda/src/pgraphnodes/callbackNode.cxx index 17424d5a0a..bf0a233f3c 100644 --- a/panda/src/pgraphnodes/callbackNode.cxx +++ b/panda/src/pgraphnodes/callbackNode.cxx @@ -26,7 +26,7 @@ TypeHandle CallbackNode::_type_handle; * */ CallbackNode:: -CallbackNode(const string &name) : +CallbackNode(const std::string &name) : PandaNode(name) { PandaNode::set_cull_callback(); @@ -90,7 +90,7 @@ safe_to_combine() const { bool CallbackNode:: cull_callback(CullTraverser *trav, CullTraverserData &data) { CallbackObject *cbobj = get_cull_callback(); - if (cbobj != (CallbackObject *)NULL) { + if (cbobj != nullptr) { NodeCullCallbackData cbdata(trav, data); cbobj->do_callback(&cbdata); @@ -130,9 +130,9 @@ add_for_draw(CullTraverser *trav, CullTraverserData &data) { // CullableObject for the draw_callback, if any. We don't need to pass any // Geoms, however. CallbackObject *cbobj = get_draw_callback(); - if (cbobj != (CallbackObject *)NULL) { + if (cbobj != nullptr) { CullableObject *object = - new CullableObject(NULL, data._state, + new CullableObject(nullptr, data._state, data.get_internal_transform(trav)); object->set_draw_callback(cbobj); trav->get_cull_handler()->record_object(object, trav); @@ -145,7 +145,7 @@ add_for_draw(CullTraverser *trav, CullTraverserData &data) { * classes to include some information relevant to the class. */ void CallbackNode:: -output(ostream &out) const { +output(std::ostream &out) const { PandaNode::output(out); } diff --git a/panda/src/pgraphnodes/callbackNode.h b/panda/src/pgraphnodes/callbackNode.h index ba2baec389..0a4d101903 100644 --- a/panda/src/pgraphnodes/callbackNode.h +++ b/panda/src/pgraphnodes/callbackNode.h @@ -25,7 +25,7 @@ */ class EXPCL_PANDA_PGRAPHNODES CallbackNode : public PandaNode { PUBLISHED: - explicit CallbackNode(const string &name); + explicit CallbackNode(const std::string &name); INLINE void set_cull_callback(CallbackObject *object); INLINE void clear_cull_callback(); @@ -47,7 +47,7 @@ public: virtual bool is_renderable() const; virtual void add_for_draw(CullTraverser *trav, CullTraverserData &data); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: class EXPCL_PANDA_PGRAPHNODES CData : public CycleData { diff --git a/panda/src/pgraphnodes/computeNode.cxx b/panda/src/pgraphnodes/computeNode.cxx index 7962378afa..560e1a8365 100644 --- a/panda/src/pgraphnodes/computeNode.cxx +++ b/panda/src/pgraphnodes/computeNode.cxx @@ -27,7 +27,7 @@ TypeHandle ComputeNode::_type_handle; * assign a shader using a ShaderAttrib. */ ComputeNode:: -ComputeNode(const string &name) : +ComputeNode(const std::string &name) : PandaNode(name), _dispatcher(new ComputeNode::Dispatcher) { @@ -93,7 +93,7 @@ add_for_draw(CullTraverser *trav, CullTraverserData &data) { // CullableObject for the Dispatcher. We don't need to pass any Geoms, // however. CullableObject *object = - new CullableObject(NULL, data._state, + new CullableObject(nullptr, data._state, data.get_internal_transform(trav)); object->set_draw_callback(_dispatcher); trav->get_cull_handler()->record_object(object, trav); @@ -105,7 +105,7 @@ add_for_draw(CullTraverser *trav, CullTraverserData &data) { * classes to include some information relevant to the class. */ void ComputeNode:: -output(ostream &out) const { +output(std::ostream &out) const { PandaNode::output(out); } diff --git a/panda/src/pgraphnodes/computeNode.h b/panda/src/pgraphnodes/computeNode.h index 83f7297216..475aca2355 100644 --- a/panda/src/pgraphnodes/computeNode.h +++ b/panda/src/pgraphnodes/computeNode.h @@ -26,7 +26,7 @@ */ class EXPCL_PANDA_PGRAPHNODES ComputeNode : public PandaNode { PUBLISHED: - explicit ComputeNode(const string &name); + explicit ComputeNode(const std::string &name); INLINE void add_dispatch(const LVecBase3i &num_groups); INLINE void add_dispatch(int num_groups_x, int num_groups_y, int num_groups_z); @@ -50,7 +50,7 @@ public: virtual bool is_renderable() const; virtual void add_for_draw(CullTraverser *trav, CullTraverserData &data); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; public: class EXPCL_PANDA_PGRAPHNODES Dispatcher : public CallbackObject { diff --git a/panda/src/pgraphnodes/directionalLight.cxx b/panda/src/pgraphnodes/directionalLight.cxx index 9d198fac6f..062d2d364d 100644 --- a/panda/src/pgraphnodes/directionalLight.cxx +++ b/panda/src/pgraphnodes/directionalLight.cxx @@ -55,7 +55,7 @@ fillin(DatagramIterator &scan, BamReader *) { * */ DirectionalLight:: -DirectionalLight(const string &name) : +DirectionalLight(const std::string &name) : LightLensNode(name, new OrthographicLens()) { _lenses[0]._lens->set_interocular_distance(0); } @@ -98,7 +98,7 @@ xform(const LMatrix4 &mat) { * */ void DirectionalLight:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << *this << ":\n"; indent(out, indent_level + 2) << "color " << get_color() << "\n"; diff --git a/panda/src/pgraphnodes/directionalLight.h b/panda/src/pgraphnodes/directionalLight.h index df2a198273..f5453399ef 100644 --- a/panda/src/pgraphnodes/directionalLight.h +++ b/panda/src/pgraphnodes/directionalLight.h @@ -24,7 +24,7 @@ */ class EXPCL_PANDA_PGRAPHNODES DirectionalLight : public LightLensNode { PUBLISHED: - explicit DirectionalLight(const string &name); + explicit DirectionalLight(const std::string &name); protected: DirectionalLight(const DirectionalLight ©); @@ -32,14 +32,14 @@ protected: public: virtual PandaNode *make_copy() const; virtual void xform(const LMatrix4 &mat); - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; virtual bool get_vector_to_light(LVector3 &result, const LPoint3 &from_object_point, const LMatrix4 &to_object_space); PUBLISHED: - INLINE const LColor &get_specular_color() const FINAL; + INLINE const LColor &get_specular_color() const final; INLINE void set_specular_color(const LColor &color); INLINE void clear_specular_color(); MAKE_PROPERTY(specular_color, get_specular_color, set_specular_color); @@ -106,7 +106,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const DirectionalLight &light) { +INLINE std::ostream &operator << (std::ostream &out, const DirectionalLight &light) { light.output(out); return out; } diff --git a/panda/src/pgraphnodes/fadeLodNode.I b/panda/src/pgraphnodes/fadeLodNode.I index 41f7d79299..0b2b02cd94 100644 --- a/panda/src/pgraphnodes/fadeLodNode.I +++ b/panda/src/pgraphnodes/fadeLodNode.I @@ -32,7 +32,7 @@ get_fade_time() const { * Returns the cull bin that is assigned to the fading part of the geometry * during a transition. */ -INLINE const string &FadeLODNode:: +INLINE const std::string &FadeLODNode:: get_fade_bin_name() const { return _fade_bin_name; } diff --git a/panda/src/pgraphnodes/fadeLodNode.cxx b/panda/src/pgraphnodes/fadeLodNode.cxx index de952457e8..f523d01795 100644 --- a/panda/src/pgraphnodes/fadeLodNode.cxx +++ b/panda/src/pgraphnodes/fadeLodNode.cxx @@ -28,7 +28,7 @@ TypeHandle FadeLODNode::_type_handle; * */ FadeLODNode:: -FadeLODNode(const string &name) : +FadeLODNode(const std::string &name) : LODNode(name) { set_cull_callback(); @@ -99,7 +99,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { double now = ClockObject::get_global_clock()->get_frame_time(); - if (ldata == (AuxSceneData *)NULL || now > ldata->get_expiration_time()) { + if (ldata == nullptr || now > ldata->get_expiration_time()) { // This is the first time we have rendered this instance of this LOD node // in a while. ldata = new FadeLODNodeData; @@ -169,7 +169,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { // drawing the old LOD opaque with z writing on if (out_child >= 0 && out_child < get_num_children()) { PandaNode *child = get_child(out_child); - if (child != (PandaNode *)NULL) { + if (child != nullptr) { CullTraverserData next_data_out(data, child); next_data_out._state = next_data_out._state->compose(get_fade_1_old_state()); @@ -179,7 +179,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { if (in_child >= 0 && in_child < get_num_children()) { PandaNode *child = get_child(in_child); - if (child != (PandaNode *)NULL) { + if (child != nullptr) { CullTraverserData next_data_in(data, child); PN_stdfloat in_alpha = elapsed / half_fade_time; @@ -194,7 +194,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { // draw the opaque new LOD with z write on if (in_child >= 0 && in_child < get_num_children()) { PandaNode *child = get_child(in_child); - if (child != (PandaNode *)NULL) { + if (child != nullptr) { CullTraverserData next_data_in(data, child); next_data_in._state = next_data_in._state->compose(get_fade_2_new_state()); @@ -204,7 +204,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { if (out_child >= 0 && out_child < get_num_children()) { PandaNode *child = get_child(out_child); - if (child != (PandaNode *)NULL) { + if (child != nullptr) { CullTraverserData next_data_out(data, child); PN_stdfloat out_alpha = 1.0f - (elapsed - half_fade_time) / half_fade_time; @@ -224,7 +224,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { int index = ldata->_fade_in; if (index >= 0 && index < get_num_children()) { PandaNode *child = get_child(index); - if (child != (PandaNode *)NULL) { + if (child != nullptr) { CullTraverserData next_data(data, child); trav->traverse(next_data); } @@ -241,7 +241,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { * */ void FadeLODNode:: -output(ostream &out) const { +output(std::ostream &out) const { LODNode::output(out); out << " fade time: " << _fade_time; } @@ -251,7 +251,7 @@ output(ostream &out) const { * of the geometry during a transition. */ void FadeLODNode:: -set_fade_bin(const string &name, int draw_order) { +set_fade_bin(const std::string &name, int draw_order) { _fade_bin_name = name; _fade_bin_draw_order = draw_order; _fade_1_new_state.clear(); @@ -278,7 +278,7 @@ set_fade_state_override(int override) { */ CPT(RenderState) FadeLODNode:: get_fade_1_old_state() { - if (_fade_1_old_state == (const RenderState *)NULL) { + if (_fade_1_old_state == nullptr) { _fade_1_old_state = RenderState::make_empty(); } @@ -291,7 +291,7 @@ get_fade_1_old_state() { */ CPT(RenderState) FadeLODNode:: get_fade_1_new_state(PN_stdfloat in_alpha) { - if (_fade_1_new_state == (const RenderState *)NULL) { + if (_fade_1_new_state == nullptr) { _fade_1_new_state = RenderState::make (TransparencyAttrib::make(TransparencyAttrib::M_alpha), CullBinAttrib::make(_fade_bin_name, _fade_bin_draw_order), @@ -310,7 +310,7 @@ get_fade_1_new_state(PN_stdfloat in_alpha) { */ CPT(RenderState) FadeLODNode:: get_fade_2_old_state(PN_stdfloat out_alpha) { - if (_fade_2_old_state == (const RenderState *)NULL) { + if (_fade_2_old_state == nullptr) { _fade_2_old_state = RenderState::make (TransparencyAttrib::make(TransparencyAttrib::M_alpha), DepthWriteAttrib::make(DepthWriteAttrib::M_off), @@ -329,7 +329,7 @@ get_fade_2_old_state(PN_stdfloat out_alpha) { */ CPT(RenderState) FadeLODNode:: get_fade_2_new_state() { - if (_fade_2_new_state == (const RenderState *)NULL) { + if (_fade_2_new_state == nullptr) { _fade_2_new_state = RenderState::make (DepthOffsetAttrib::make(), _fade_state_override); diff --git a/panda/src/pgraphnodes/fadeLodNode.h b/panda/src/pgraphnodes/fadeLodNode.h index 728cc8f8e6..7f748ace4e 100644 --- a/panda/src/pgraphnodes/fadeLodNode.h +++ b/panda/src/pgraphnodes/fadeLodNode.h @@ -23,22 +23,22 @@ */ class EXPCL_PANDA_PGRAPHNODES FadeLODNode : public LODNode { PUBLISHED: - explicit FadeLODNode(const string &name); + explicit FadeLODNode(const std::string &name); protected: FadeLODNode(const FadeLODNode ©); public: virtual PandaNode *make_copy() const; virtual bool cull_callback(CullTraverser *trav, CullTraverserData &data); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; PUBLISHED: INLINE void set_fade_time(PN_stdfloat t); INLINE PN_stdfloat get_fade_time() const; MAKE_PROPERTY(fade_time, get_fade_time, set_fade_time); - void set_fade_bin(const string &name, int draw_order); - INLINE const string &get_fade_bin_name() const; + void set_fade_bin(const std::string &name, int draw_order); + INLINE const std::string &get_fade_bin_name() const; INLINE int get_fade_bin_draw_order() const; MAKE_PROPERTY(fade_bin_name, get_fade_bin_name); MAKE_PROPERTY(fade_bin_draw_order, get_fade_bin_draw_order); @@ -56,7 +56,7 @@ private: private: PN_stdfloat _fade_time; - string _fade_bin_name; + std::string _fade_bin_name; int _fade_bin_draw_order; int _fade_state_override; diff --git a/panda/src/pgraphnodes/fadeLodNodeData.cxx b/panda/src/pgraphnodes/fadeLodNodeData.cxx index d0f0d09987..5e15112fd3 100644 --- a/panda/src/pgraphnodes/fadeLodNodeData.cxx +++ b/panda/src/pgraphnodes/fadeLodNodeData.cxx @@ -20,7 +20,7 @@ TypeHandle FadeLODNodeData::_type_handle; * */ void FadeLODNodeData:: -output(ostream &out) const { +output(std::ostream &out) const { AuxSceneData::output(out); if (_fade_mode != FM_solid) { out << " fading " << _fade_out << " to " << _fade_in << " since " diff --git a/panda/src/pgraphnodes/fadeLodNodeData.h b/panda/src/pgraphnodes/fadeLodNodeData.h index 7d629d060e..206a08bbe4 100644 --- a/panda/src/pgraphnodes/fadeLodNodeData.h +++ b/panda/src/pgraphnodes/fadeLodNodeData.h @@ -34,7 +34,7 @@ public: int _fade_out; int _fade_in; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; public: static TypeHandle get_class_type() { diff --git a/panda/src/pgraphnodes/lightLensNode.I b/panda/src/pgraphnodes/lightLensNode.I index 1df14eb971..9c59b6c998 100644 --- a/panda/src/pgraphnodes/lightLensNode.I +++ b/panda/src/pgraphnodes/lightLensNode.I @@ -110,7 +110,7 @@ INLINE GraphicsOutputBase *LightLensNode:: get_shadow_buffer(GraphicsStateGuardianBase *gsg) { ShadowBuffers::iterator it = _sbuffers.find(gsg); if (it == _sbuffers.end()) { - return NULL; + return nullptr; } else { return (*it).second; } diff --git a/panda/src/pgraphnodes/lightLensNode.cxx b/panda/src/pgraphnodes/lightLensNode.cxx index b79b5e8dc0..87f9a5bca8 100644 --- a/panda/src/pgraphnodes/lightLensNode.cxx +++ b/panda/src/pgraphnodes/lightLensNode.cxx @@ -26,7 +26,7 @@ TypeHandle LightLensNode::_type_handle; * */ LightLensNode:: -LightLensNode(const string &name, Lens *lens) : +LightLensNode(const std::string &name, Lens *lens) : Camera(name, lens), _has_specular_color(false), _attrib_count(0) @@ -158,7 +158,7 @@ as_light() { * */ void LightLensNode:: -output(ostream &out) const { +output(std::ostream &out) const { LensNode::output(out); } @@ -166,7 +166,7 @@ output(ostream &out) const { * */ void LightLensNode:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { LensNode::write(out, indent_level); } diff --git a/panda/src/pgraphnodes/lightLensNode.h b/panda/src/pgraphnodes/lightLensNode.h index 03c1342927..4398f02bfd 100644 --- a/panda/src/pgraphnodes/lightLensNode.h +++ b/panda/src/pgraphnodes/lightLensNode.h @@ -32,7 +32,7 @@ class GraphicsStateGuardian; */ class EXPCL_PANDA_PGRAPHNODES LightLensNode : public Light, public Camera { PUBLISHED: - explicit LightLensNode(const string &name, Lens *lens = new PerspectiveLens()); + explicit LightLensNode(const std::string &name, Lens *lens = new PerspectiveLens()); virtual ~LightLensNode(); INLINE bool has_specular_color() const; @@ -82,8 +82,8 @@ public: PUBLISHED: // We have to explicitly publish these because they resolve the multiple // inheritance. - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual void write_datagram(BamWriter *manager, Datagram &dg); @@ -113,7 +113,7 @@ private: friend class GraphicsStateGuardian; }; -INLINE ostream &operator << (ostream &out, const LightLensNode &light) { +INLINE std::ostream &operator << (std::ostream &out, const LightLensNode &light) { light.output(out); return out; } diff --git a/panda/src/pgraphnodes/lightNode.cxx b/panda/src/pgraphnodes/lightNode.cxx index 13eae68d6d..cffcb05a2f 100644 --- a/panda/src/pgraphnodes/lightNode.cxx +++ b/panda/src/pgraphnodes/lightNode.cxx @@ -23,7 +23,7 @@ TypeHandle LightNode::_type_handle; * */ LightNode:: -LightNode(const string &name) : +LightNode(const std::string &name) : PandaNode(name) { } @@ -59,7 +59,7 @@ as_light() { * */ void LightNode:: -output(ostream &out) const { +output(std::ostream &out) const { PandaNode::output(out); } @@ -67,7 +67,7 @@ output(ostream &out) const { * */ void LightNode:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { PandaNode::write(out, indent_level); } diff --git a/panda/src/pgraphnodes/lightNode.h b/panda/src/pgraphnodes/lightNode.h index 9e9187ebe0..a3b85a8d90 100644 --- a/panda/src/pgraphnodes/lightNode.h +++ b/panda/src/pgraphnodes/lightNode.h @@ -26,7 +26,7 @@ */ class EXPCL_PANDA_PGRAPHNODES LightNode : public Light, public PandaNode { PUBLISHED: - explicit LightNode(const string &name); + explicit LightNode(const std::string &name); protected: LightNode(const LightNode ©); @@ -38,8 +38,8 @@ public: PUBLISHED: // We have to explicitly publish these because they resolve the multiple // inheritance. - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual void write_datagram(BamWriter *manager, Datagram &dg); @@ -67,7 +67,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const LightNode &light) { +INLINE std::ostream &operator << (std::ostream &out, const LightNode &light) { light.output(out); return out; } diff --git a/panda/src/pgraphnodes/lodNode.I b/panda/src/pgraphnodes/lodNode.I index 3a042c2aa5..92398e35fe 100644 --- a/panda/src/pgraphnodes/lodNode.I +++ b/panda/src/pgraphnodes/lodNode.I @@ -15,7 +15,7 @@ * */ INLINE LODNode:: -LODNode(const string &name) : +LODNode(const std::string &name) : PandaNode(name) { set_cull_callback(); diff --git a/panda/src/pgraphnodes/lodNode.cxx b/panda/src/pgraphnodes/lodNode.cxx index 4c2ca87528..060adac699 100644 --- a/panda/src/pgraphnodes/lodNode.cxx +++ b/panda/src/pgraphnodes/lodNode.cxx @@ -45,7 +45,7 @@ TypeHandle LODNode::_type_handle; * variable. */ PT(LODNode) LODNode:: -make_default_lod(const string &name) { +make_default_lod(const std::string &name) { switch (default_lod_type.get_value()) { case LNT_pop: return new LODNode(name); @@ -146,7 +146,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { LPoint3 center = cdata->_center * rel_transform->get_mat(); PN_stdfloat dist2 = center.dot(center); - int num_children = min(get_num_children(), (int)cdata->_switch_vector.size()); + int num_children = std::min(get_num_children(), (int)cdata->_switch_vector.size()); for (int index = 0; index < num_children; ++index) { const Switch &sw = cdata->_switch_vector[index]; bool in_range; @@ -160,7 +160,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { if (in_range) { // This switch level is in range. Draw its children. PandaNode *child = get_child(index); - if (child != (PandaNode *)NULL) { + if (child != nullptr) { CullTraverserData next_data(data, child); trav->traverse(next_data); } @@ -176,7 +176,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { * */ void LODNode:: -output(ostream &out) const { +output(std::ostream &out) const { PandaNode::output(out); CDReader cdata(_cycler); out << " center(" << cdata->_center << ") "; @@ -384,7 +384,7 @@ show_switches_cull_callback(CullTraverser *trav, CullTraverserData &data) { // wireframe mode. if (index < get_num_children()) { PandaNode *child = get_child(index); - if (child != (PandaNode *)NULL) { + if (child != nullptr) { CullTraverserData next_data3(data, child); next_data3._state = next_data3._state->compose(sw.get_viz_model_state()); trav->traverse(next_data3); @@ -524,7 +524,7 @@ do_verify_child_bounds(const LODNode::CData *cdata, int index, if (index < get_num_children()) { const Switch &sw = cdata->_switch_vector[index]; PandaNode *child = get_child(index); - if (child != (PandaNode *)NULL) { + if (child != nullptr) { UpdateSeq seq; CPT(BoundingVolume) bv = child->get_bounds(seq); @@ -593,7 +593,7 @@ do_verify_child_bounds(const LODNode::CData *cdata, int index, // should definitely fit entirely within a bounding sphere that contains // all the points of the child. LPoint3 box_center = (min_point + max_point) / 2.0f; - PN_stdfloat box_radius = min(min(max_point[0] - box_center[0], + PN_stdfloat box_radius = std::min(std::min(max_point[0] - box_center[0], max_point[1] - box_center[1]), max_point[2] - box_center[2]); @@ -642,7 +642,7 @@ do_auto_verify_lods(CullTraverser *trav, CullTraverserData &data) { PN_stdfloat suggested_radius; if (!do_verify_child_bounds(cdata, index, suggested_radius)) { const Switch &sw = cdata->_switch_vector[index]; - ostringstream strm; + std::ostringstream strm; strm << "Level " << index << " geometry of " << data.get_node_path() << " is larger than its switch radius; suggest radius of " diff --git a/panda/src/pgraphnodes/lodNode.h b/panda/src/pgraphnodes/lodNode.h index 7258ebe447..b7b58dca85 100644 --- a/panda/src/pgraphnodes/lodNode.h +++ b/panda/src/pgraphnodes/lodNode.h @@ -27,9 +27,9 @@ */ class EXPCL_PANDA_PGRAPHNODES LODNode : public PandaNode { PUBLISHED: - INLINE explicit LODNode(const string &name); + INLINE explicit LODNode(const std::string &name); - static PT(LODNode) make_default_lod(const string &name); + static PT(LODNode) make_default_lod(const std::string &name); protected: INLINE LODNode(const LODNode ©); @@ -40,7 +40,7 @@ public: virtual void xform(const LMatrix4 &mat); virtual bool cull_callback(CullTraverser *trav, CullTraverserData &data); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; virtual bool is_lod_node() const; @@ -161,7 +161,7 @@ protected: typedef pvector SwitchVector; private: - class EXPCL_PANDA_PGRAPH CData : public CycleData { + class EXPCL_PANDA_PGRAPHNODES CData : public CycleData { public: INLINE CData(); INLINE CData(const CData ©); diff --git a/panda/src/pgraphnodes/lodNodeType.cxx b/panda/src/pgraphnodes/lodNodeType.cxx index 2798cdd0f4..5c37066cf5 100644 --- a/panda/src/pgraphnodes/lodNodeType.cxx +++ b/panda/src/pgraphnodes/lodNodeType.cxx @@ -15,6 +15,10 @@ #include "string_utils.h" #include "config_pgraph.h" +using std::istream; +using std::ostream; +using std::string; + ostream & operator << (ostream &out, LODNodeType lnt) { switch (lnt) { diff --git a/panda/src/pgraphnodes/lodNodeType.h b/panda/src/pgraphnodes/lodNodeType.h index bc1964d519..ec1dec820b 100644 --- a/panda/src/pgraphnodes/lodNodeType.h +++ b/panda/src/pgraphnodes/lodNodeType.h @@ -25,7 +25,7 @@ enum LODNodeType { END_PUBLISH -EXPCL_PANDA_PGRAPH ostream &operator << (ostream &out, LODNodeType lnt); -EXPCL_PANDA_PGRAPH istream &operator >> (istream &in, LODNodeType &cs); +EXPCL_PANDA_PGRAPHNODES std::ostream &operator << (std::ostream &out, LODNodeType lnt); +EXPCL_PANDA_PGRAPHNODES std::istream &operator >> (std::istream &in, LODNodeType &cs); #endif diff --git a/panda/src/pgraphnodes/nodeCullCallbackData.cxx b/panda/src/pgraphnodes/nodeCullCallbackData.cxx index b0cbd9d980..5a9dbc9e0a 100644 --- a/panda/src/pgraphnodes/nodeCullCallbackData.cxx +++ b/panda/src/pgraphnodes/nodeCullCallbackData.cxx @@ -24,7 +24,7 @@ TypeHandle NodeCullCallbackData::_type_handle; * */ void NodeCullCallbackData:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << "(" << (void *)_trav << ", " << (void *)&_data << ")"; } @@ -47,9 +47,9 @@ upcall() { // CullableObject for the draw_callback, if any. We don't need to pass // any Geoms, however. CallbackObject *cbobj = cbnode->get_draw_callback(); - if (cbobj != (CallbackObject *)NULL) { + if (cbobj != nullptr) { CullableObject *object = - new CullableObject(NULL, _data._state, + new CullableObject(nullptr, _data._state, _data.get_internal_transform(_trav)); object->set_draw_callback(cbobj); _trav->get_cull_handler()->record_object(object, _trav); diff --git a/panda/src/pgraphnodes/nodeCullCallbackData.h b/panda/src/pgraphnodes/nodeCullCallbackData.h index add737d3d6..f78acb86cb 100644 --- a/panda/src/pgraphnodes/nodeCullCallbackData.h +++ b/panda/src/pgraphnodes/nodeCullCallbackData.h @@ -28,7 +28,7 @@ public: INLINE NodeCullCallbackData(CullTraverser *trav, CullTraverserData &data); PUBLISHED: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; INLINE CullTraverser *get_trav() const; INLINE CullTraverserData &get_data() const; diff --git a/panda/src/pgraphnodes/pointLight.cxx b/panda/src/pgraphnodes/pointLight.cxx index 02cc33fda9..8a132515aa 100644 --- a/panda/src/pgraphnodes/pointLight.cxx +++ b/panda/src/pgraphnodes/pointLight.cxx @@ -61,7 +61,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { * */ PointLight:: -PointLight(const string &name) : +PointLight(const std::string &name) : LightLensNode(name) { PT(Lens) lens; lens = new PerspectiveLens(90, 90); @@ -127,7 +127,7 @@ xform(const LMatrix4 &mat) { * */ void PointLight:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << *this << ":\n"; indent(out, indent_level + 2) << "color " << get_color() << "\n"; diff --git a/panda/src/pgraphnodes/pointLight.h b/panda/src/pgraphnodes/pointLight.h index ba3a334d47..d54efc04ba 100644 --- a/panda/src/pgraphnodes/pointLight.h +++ b/panda/src/pgraphnodes/pointLight.h @@ -24,7 +24,7 @@ */ class EXPCL_PANDA_PGRAPHNODES PointLight : public LightLensNode { PUBLISHED: - explicit PointLight(const string &name); + explicit PointLight(const std::string &name); protected: PointLight(const PointLight ©); @@ -32,19 +32,19 @@ protected: public: virtual PandaNode *make_copy() const; virtual void xform(const LMatrix4 &mat); - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; virtual bool get_vector_to_light(LVector3 &result, const LPoint3 &from_object_point, const LMatrix4 &to_object_space); PUBLISHED: - INLINE const LColor &get_specular_color() const FINAL; + INLINE const LColor &get_specular_color() const final; INLINE void set_specular_color(const LColor &color); INLINE void clear_specular_color(); MAKE_PROPERTY(specular_color, get_specular_color, set_specular_color); - INLINE const LVecBase3 &get_attenuation() const FINAL; + INLINE const LVecBase3 &get_attenuation() const final; INLINE void set_attenuation(const LVecBase3 &attenuation); MAKE_PROPERTY(attenuation, get_attenuation, set_attenuation); @@ -113,7 +113,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const PointLight &light) { +INLINE std::ostream &operator << (std::ostream &out, const PointLight &light) { light.output(out); return out; } diff --git a/panda/src/pgraphnodes/rectangleLight.cxx b/panda/src/pgraphnodes/rectangleLight.cxx index 187d35cd2d..1af641788c 100644 --- a/panda/src/pgraphnodes/rectangleLight.cxx +++ b/panda/src/pgraphnodes/rectangleLight.cxx @@ -50,7 +50,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { * */ RectangleLight:: -RectangleLight(const string &name) : +RectangleLight(const std::string &name) : LightLensNode(name) { } @@ -80,7 +80,7 @@ make_copy() const { * */ void RectangleLight:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { LightLensNode::write(out, indent_level); indent(out, indent_level) << *this << "\n"; } diff --git a/panda/src/pgraphnodes/rectangleLight.h b/panda/src/pgraphnodes/rectangleLight.h index 3870b4f8f7..9fafe875d6 100644 --- a/panda/src/pgraphnodes/rectangleLight.h +++ b/panda/src/pgraphnodes/rectangleLight.h @@ -25,17 +25,17 @@ */ class EXPCL_PANDA_PGRAPHNODES RectangleLight : public LightLensNode { PUBLISHED: - explicit RectangleLight(const string &name); + explicit RectangleLight(const std::string &name); protected: RectangleLight(const RectangleLight ©); public: virtual PandaNode *make_copy() const; - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; PUBLISHED: - INLINE const LColor &get_specular_color() const FINAL; + INLINE const LColor &get_specular_color() const final; INLINE PN_stdfloat get_max_distance() const; INLINE void set_max_distance(PN_stdfloat max_distance); diff --git a/panda/src/pgraphnodes/sceneGraphAnalyzer.cxx b/panda/src/pgraphnodes/sceneGraphAnalyzer.cxx index b24678b333..915845af86 100644 --- a/panda/src/pgraphnodes/sceneGraphAnalyzer.cxx +++ b/panda/src/pgraphnodes/sceneGraphAnalyzer.cxx @@ -111,7 +111,7 @@ add_node(PandaNode *node) { * Describes all the data collected. */ void SceneGraphAnalyzer:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << _num_nodes << " total nodes (including " << _num_instances << " instances); " << _num_lod_nodes << " LODNodes.\n"; @@ -284,7 +284,7 @@ collect_statistics(PandaNode *node, bool under_instance) { _num_nodes_with_attribs++; const RenderAttrib *attrib = node->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (RenderAttrib *)NULL) { + if (attrib != nullptr) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); for (int i = 0; i < ta->get_num_on_stages(); i++) { collect_statistics(ta->get_on_texture(ta->get_on_stage(i))); @@ -336,7 +336,7 @@ collect_statistics(PandaNode *node, bool under_instance) { */ void SceneGraphAnalyzer:: collect_statistics(GeomNode *geom_node) { - nassertv(geom_node != (GeomNode *)NULL); + nassertv(geom_node != nullptr); ++_num_geom_nodes; @@ -351,7 +351,7 @@ collect_statistics(GeomNode *geom_node) { const RenderAttrib *attrib = geom_state->get_attrib(TextureAttrib::get_class_slot()); - if (attrib != (RenderAttrib *)NULL) { + if (attrib != nullptr) { const TextureAttrib *ta = DCAST(TextureAttrib, attrib); for (int i = 0; i < ta->get_num_on_stages(); i++) { collect_statistics(ta->get_on_texture(ta->get_on_stage(i))); @@ -366,7 +366,7 @@ collect_statistics(GeomNode *geom_node) { void SceneGraphAnalyzer:: collect_statistics(const Geom *geom) { CPT(GeomVertexData) vdata = geom->get_vertex_data(); - pair result = _vdatas.insert(VDatas::value_type(vdata, VDataTracker())); + std::pair result = _vdatas.insert(VDatas::value_type(vdata, VDataTracker())); if (result.second) { // This is the first time we've encountered this vertex data. ++_num_geom_vertex_datas; @@ -477,7 +477,7 @@ collect_statistics(const Geom *geom) { */ void SceneGraphAnalyzer:: collect_statistics(Texture *texture) { - nassertv(texture != (Texture *)NULL); + nassertv(texture != nullptr); Textures::iterator ti = _textures.find(texture); if (ti == _textures.end()) { @@ -506,7 +506,7 @@ collect_statistics(Texture *texture) { */ void SceneGraphAnalyzer:: collect_statistics(const GeomVertexArrayData *vadata) { - nassertv(vadata != NULL); + nassertv(vadata != nullptr); bool inserted = _vadatas.insert(vadata).second; if (inserted) { // This is the first time we've encountered this vertex array. @@ -523,7 +523,7 @@ collect_statistics(const GeomVertexArrayData *vadata) { */ void SceneGraphAnalyzer:: collect_prim_statistics(const GeomVertexArrayData *vadata) { - nassertv(vadata != NULL); + nassertv(vadata != nullptr); bool inserted = _prim_vadatas.insert(vadata).second; if (inserted) { // This is the first time we've encountered this vertex array. diff --git a/panda/src/pgraphnodes/sceneGraphAnalyzer.h b/panda/src/pgraphnodes/sceneGraphAnalyzer.h index 68ca0d14df..a56d34f41c 100644 --- a/panda/src/pgraphnodes/sceneGraphAnalyzer.h +++ b/panda/src/pgraphnodes/sceneGraphAnalyzer.h @@ -52,7 +52,7 @@ PUBLISHED: void clear(); void add_node(PandaNode *node); - void write(ostream &out, int indent_level = 0) const; + void write(std::ostream &out, int indent_level = 0) const; INLINE int get_num_nodes() const; INLINE int get_num_instances() const; diff --git a/panda/src/pgraphnodes/selectiveChildNode.I b/panda/src/pgraphnodes/selectiveChildNode.I index a7b886d61a..beafc0669d 100644 --- a/panda/src/pgraphnodes/selectiveChildNode.I +++ b/panda/src/pgraphnodes/selectiveChildNode.I @@ -15,7 +15,7 @@ * */ INLINE SelectiveChildNode:: -SelectiveChildNode(const string &name) : +SelectiveChildNode(const std::string &name) : PandaNode(name), _selected_child(0) { diff --git a/panda/src/pgraphnodes/selectiveChildNode.h b/panda/src/pgraphnodes/selectiveChildNode.h index 76720aa933..29b0d4581a 100644 --- a/panda/src/pgraphnodes/selectiveChildNode.h +++ b/panda/src/pgraphnodes/selectiveChildNode.h @@ -24,7 +24,7 @@ */ class EXPCL_PANDA_PGRAPHNODES SelectiveChildNode : public PandaNode { PUBLISHED: - INLINE explicit SelectiveChildNode(const string &name); + INLINE explicit SelectiveChildNode(const std::string &name); protected: INLINE SelectiveChildNode(const SelectiveChildNode ©); diff --git a/panda/src/pgraphnodes/sequenceNode.I b/panda/src/pgraphnodes/sequenceNode.I index 823a19ea4c..68fb10120e 100644 --- a/panda/src/pgraphnodes/sequenceNode.I +++ b/panda/src/pgraphnodes/sequenceNode.I @@ -15,7 +15,7 @@ * */ INLINE SequenceNode:: -SequenceNode(const string &name) : +SequenceNode(const std::string &name) : SelectiveChildNode(name) { set_cull_callback(); diff --git a/panda/src/pgraphnodes/sequenceNode.cxx b/panda/src/pgraphnodes/sequenceNode.cxx index b8f3ffb8e0..06f0019e6d 100644 --- a/panda/src/pgraphnodes/sequenceNode.cxx +++ b/panda/src/pgraphnodes/sequenceNode.cxx @@ -134,7 +134,7 @@ get_visible_child() const { * */ void SequenceNode:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << " " << get_name() << ": "; AnimInterface::output(out); } diff --git a/panda/src/pgraphnodes/sequenceNode.h b/panda/src/pgraphnodes/sequenceNode.h index ce05b792f2..db511dd4ae 100644 --- a/panda/src/pgraphnodes/sequenceNode.h +++ b/panda/src/pgraphnodes/sequenceNode.h @@ -26,7 +26,7 @@ */ class EXPCL_PANDA_PGRAPHNODES SequenceNode : public SelectiveChildNode, public AnimInterface { PUBLISHED: - INLINE explicit SequenceNode(const string &name); + INLINE explicit SequenceNode(const std::string &name); protected: SequenceNode(const SequenceNode ©); @@ -45,7 +45,7 @@ public: virtual bool has_single_child_visibility() const; virtual int get_visible_child() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; public: static void register_with_read_factory(); diff --git a/panda/src/pgraphnodes/shaderGenerator.cxx b/panda/src/pgraphnodes/shaderGenerator.cxx index 372bd89e1d..22d0b32259 100644 --- a/panda/src/pgraphnodes/shaderGenerator.cxx +++ b/panda/src/pgraphnodes/shaderGenerator.cxx @@ -47,6 +47,8 @@ #include "config_pgraphnodes.h" #include "pStatTimer.h" +using std::string; + TypeHandle ShaderGenerator::_type_handle; #ifdef HAVE_CG @@ -259,7 +261,7 @@ analyze_renderstate(ShaderKey &key, const RenderState *rs) { rs->get_attrib_def(la); bool have_ambient = false; - for (int i = 0; i < la->get_num_on_lights(); ++i) { + for (size_t i = 0; i < la->get_num_on_lights(); ++i) { NodePath np = la->get_on_light(i); nassertv(!np.is_empty()); PandaNode *node = np.node(); @@ -288,8 +290,6 @@ analyze_renderstate(ShaderKey &key, const RenderState *rs) { } } - bool normal_mapping = key._lighting && shader_attrib->auto_normal_on(); - // See if there is a normal map, height map, gloss map, or glow map. Also // check if anything has TexGen. @@ -355,7 +355,7 @@ analyze_renderstate(ShaderKey &key, const RenderState *rs) { if (parallax_mapping_samples == 0) { info._mode = TextureStage::M_normal; } else if (!shader_attrib->auto_normal_on() || - (!key._lighting && (key._outputs & AuxBitplaneAttrib::ABO_aux_normal) == 0)) { + (key._lights.empty() && (key._outputs & AuxBitplaneAttrib::ABO_aux_normal) == 0)) { info._mode = TextureStage::M_height; info._flags = ShaderKey::TF_has_alpha; } else { @@ -364,7 +364,7 @@ analyze_renderstate(ShaderKey &key, const RenderState *rs) { break; case TextureStage::M_normal_gloss: - if (!shader_attrib->auto_gloss_on() || !key._lighting) { + if (!shader_attrib->auto_gloss_on() || key._lights.empty()) { info._mode = TextureStage::M_normal; } else if (!shader_attrib->auto_normal_on()) { info._mode = TextureStage::M_gloss; @@ -406,6 +406,9 @@ analyze_renderstate(ShaderKey &key, const RenderState *rs) { info._flags |= ShaderKey::TF_uses_last_saved_result; } break; + + default: + break; } // In fact, perhaps this stage should be disabled altogether? @@ -413,7 +416,7 @@ analyze_renderstate(ShaderKey &key, const RenderState *rs) { switch (info._mode) { case TextureStage::M_normal: if (!shader_attrib->auto_normal_on() || - (!key._lighting && (key._outputs & AuxBitplaneAttrib::ABO_aux_normal) == 0)) { + (key._lights.empty() && (key._outputs & AuxBitplaneAttrib::ABO_aux_normal) == 0)) { skip = true; } else { info._flags = ShaderKey::TF_map_normal; @@ -427,7 +430,7 @@ analyze_renderstate(ShaderKey &key, const RenderState *rs) { } break; case TextureStage::M_gloss: - if (key._lighting && shader_attrib->auto_gloss_on()) { + if (!key._lights.empty() && shader_attrib->auto_gloss_on()) { info._flags = ShaderKey::TF_map_gloss; } else { skip = true; @@ -440,6 +443,8 @@ analyze_renderstate(ShaderKey &key, const RenderState *rs) { skip = true; } break; + default: + break; } // We can't just drop a disabled slot from the list, since then the // indices for the texture stages will no longer match up. So we keep it, @@ -663,23 +668,23 @@ synthesize_shader(const RenderState *rs, const GeomVertexAnimationSpec &anim) { // These variables will hold the results of register allocation. - const char *tangent_freg = 0; - const char *binormal_freg = 0; + const char *tangent_freg = nullptr; + const char *binormal_freg = nullptr; string tangent_input; string binormal_input; pmap texcoord_fregs; pvector lightcoord_fregs; - const char *world_position_freg = 0; - const char *world_normal_freg = 0; - const char *eye_position_freg = 0; - const char *eye_normal_freg = 0; - const char *hpos_freg = 0; + const char *world_position_freg = nullptr; + const char *world_normal_freg = nullptr; + const char *eye_position_freg = nullptr; + const char *eye_normal_freg = nullptr; + const char *hpos_freg = nullptr; const char *position_vreg; - const char *transform_weight_vreg = 0; + const char *transform_weight_vreg = nullptr; const char *normal_vreg; - const char *color_vreg = 0; - const char *transform_index_vreg = 0; + const char *color_vreg = nullptr; + const char *transform_index_vreg = nullptr; if (_use_generic_attr) { position_vreg = "ATTR0"; @@ -700,7 +705,7 @@ synthesize_shader(const RenderState *rs, const GeomVertexAnimationSpec &anim) { // Generate the shader's text. - ostringstream text; + std::ostringstream text; text << "//Cg\n"; @@ -1619,7 +1624,7 @@ synthesize_shader(const RenderState *rs, const GeomVertexAnimationSpec &anim) { */ string ShaderGenerator:: combine_mode_as_string(const ShaderKey::TextureInfo &info, TextureStage::CombineMode c_mode, bool alpha, short texindex) { - ostringstream text; + std::ostringstream text; switch (c_mode) { case TextureStage::CM_modulate: text << combine_source_as_string(info, 0, alpha, texindex); @@ -1685,7 +1690,7 @@ combine_source_as_string(const ShaderKey::TextureInfo &info, short num, bool alp c_src = UNPACK_COMBINE_SRC(info._combine_alpha, num); c_op = UNPACK_COMBINE_OP(info._combine_alpha, num); } - ostringstream csource; + std::ostringstream csource; if (c_op == TextureStage::CO_one_minus_src_color || c_op == TextureStage::CO_one_minus_src_alpha) { csource << "saturate(1.0f - "; diff --git a/panda/src/pgraphnodes/shaderGenerator.h b/panda/src/pgraphnodes/shaderGenerator.h index 66077c4af8..a3d37c4ad9 100644 --- a/panda/src/pgraphnodes/shaderGenerator.h +++ b/panda/src/pgraphnodes/shaderGenerator.h @@ -168,9 +168,9 @@ protected: void analyze_renderstate(ShaderKey &key, const RenderState *rs); - static string combine_mode_as_string(const ShaderKey::TextureInfo &info, + static std::string combine_mode_as_string(const ShaderKey::TextureInfo &info, TextureStage::CombineMode c_mode, bool alpha, short texindex); - static string combine_source_as_string(const ShaderKey::TextureInfo &info, + static std::string combine_source_as_string(const ShaderKey::TextureInfo &info, short num, bool alpha, short texindex); static const char *texture_type_as_string(Texture::TextureType ttype); diff --git a/panda/src/pgraphnodes/sphereLight.cxx b/panda/src/pgraphnodes/sphereLight.cxx index c4cf01be5a..6cd70c2fbb 100644 --- a/panda/src/pgraphnodes/sphereLight.cxx +++ b/panda/src/pgraphnodes/sphereLight.cxx @@ -50,7 +50,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { * */ SphereLight:: -SphereLight(const string &name) : +SphereLight(const std::string &name) : PointLight(name) { } @@ -92,7 +92,7 @@ xform(const LMatrix4 &mat) { * */ void SphereLight:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { PointLight::write(out, indent_level); indent(out, indent_level) << *this << ":\n"; indent(out, indent_level + 2) diff --git a/panda/src/pgraphnodes/sphereLight.h b/panda/src/pgraphnodes/sphereLight.h index 7efddb9b50..d4b1fb1c32 100644 --- a/panda/src/pgraphnodes/sphereLight.h +++ b/panda/src/pgraphnodes/sphereLight.h @@ -25,7 +25,7 @@ */ class EXPCL_PANDA_PGRAPHNODES SphereLight : public PointLight { PUBLISHED: - explicit SphereLight(const string &name); + explicit SphereLight(const std::string &name); protected: SphereLight(const SphereLight ©); @@ -33,7 +33,7 @@ protected: public: virtual PandaNode *make_copy() const; virtual void xform(const LMatrix4 &mat); - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; PUBLISHED: INLINE PN_stdfloat get_radius() const; diff --git a/panda/src/pgraphnodes/spotlight.cxx b/panda/src/pgraphnodes/spotlight.cxx index 99432a904b..a7d334e721 100644 --- a/panda/src/pgraphnodes/spotlight.cxx +++ b/panda/src/pgraphnodes/spotlight.cxx @@ -64,7 +64,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { * */ Spotlight:: -Spotlight(const string &name) : +Spotlight(const std::string &name) : LightLensNode(name) { _lenses[0]._lens->set_interocular_distance(0); } @@ -104,7 +104,7 @@ xform(const LMatrix4 &mat) { * */ void Spotlight:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << *this << ":\n"; indent(out, indent_level + 2) << "color " << get_color() << "\n"; @@ -123,7 +123,7 @@ write(ostream &out, int indent_level) const { } Lens *lens = get_lens(); - if (lens != (Lens *)NULL) { + if (lens != nullptr) { lens->write(out, indent_level + 2); } } @@ -214,12 +214,12 @@ bind(GraphicsStateGuardianBase *gsg, const NodePath &light, int light_id) { void Spotlight:: fill_viz_geom(GeomNode *viz_geom) { Lens *lens = get_lens(); - if (lens == (Lens *)NULL) { + if (lens == nullptr) { return; } PT(Geom) geom = lens->make_geometry(); - if (geom == (Geom *)NULL) { + if (geom == nullptr) { return; } diff --git a/panda/src/pgraphnodes/spotlight.h b/panda/src/pgraphnodes/spotlight.h index c9a6962b07..a529f1479e 100644 --- a/panda/src/pgraphnodes/spotlight.h +++ b/panda/src/pgraphnodes/spotlight.h @@ -31,7 +31,7 @@ */ class EXPCL_PANDA_PGRAPHNODES Spotlight : public LightLensNode { PUBLISHED: - Spotlight(const string &name); + Spotlight(const std::string &name); protected: Spotlight(const Spotlight ©); @@ -39,23 +39,23 @@ protected: public: virtual PandaNode *make_copy() const; virtual void xform(const LMatrix4 &mat); - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; virtual bool get_vector_to_light(LVector3 &result, const LPoint3 &from_object_point, const LMatrix4 &to_object_space); PUBLISHED: - INLINE PN_stdfloat get_exponent() const FINAL; + INLINE PN_stdfloat get_exponent() const final; INLINE void set_exponent(PN_stdfloat exponent); MAKE_PROPERTY(exponent, get_exponent, set_exponent); - INLINE const LColor &get_specular_color() const FINAL; + INLINE const LColor &get_specular_color() const final; INLINE void set_specular_color(const LColor &color); INLINE void clear_specular_color(); MAKE_PROPERTY(specular_color, get_specular_color, set_specular_color); - INLINE const LVecBase3 &get_attenuation() const FINAL; + INLINE const LVecBase3 &get_attenuation() const final; INLINE void set_attenuation(const LVecBase3 &attenuation); MAKE_PROPERTY(attenuation, get_attenuation, set_attenuation); @@ -127,7 +127,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const Spotlight &light) { +INLINE std::ostream &operator << (std::ostream &out, const Spotlight &light) { light.output(out); return out; } diff --git a/panda/src/pgraphnodes/switchNode.I b/panda/src/pgraphnodes/switchNode.I index 451ec655df..b7943210dc 100644 --- a/panda/src/pgraphnodes/switchNode.I +++ b/panda/src/pgraphnodes/switchNode.I @@ -32,7 +32,7 @@ CData(const SwitchNode::CData ©) : * */ INLINE SwitchNode:: -SwitchNode(const string &name) : +SwitchNode(const std::string &name) : SelectiveChildNode(name) { set_cull_callback(); diff --git a/panda/src/pgraphnodes/switchNode.h b/panda/src/pgraphnodes/switchNode.h index b2fefd7750..2df989cbd7 100644 --- a/panda/src/pgraphnodes/switchNode.h +++ b/panda/src/pgraphnodes/switchNode.h @@ -24,7 +24,7 @@ */ class EXPCL_PANDA_PGRAPHNODES SwitchNode : public SelectiveChildNode { PUBLISHED: - INLINE explicit SwitchNode(const string &name); + INLINE explicit SwitchNode(const std::string &name); public: SwitchNode(const SwitchNode ©); diff --git a/panda/src/pgraphnodes/uvScrollNode.I b/panda/src/pgraphnodes/uvScrollNode.I index 3fb849edc9..893f76e2cc 100644 --- a/panda/src/pgraphnodes/uvScrollNode.I +++ b/panda/src/pgraphnodes/uvScrollNode.I @@ -15,7 +15,7 @@ * */ INLINE UvScrollNode:: -UvScrollNode(const string &name, PN_stdfloat u_speed, PN_stdfloat v_speed, PN_stdfloat w_speed, PN_stdfloat r_speed) : +UvScrollNode(const std::string &name, PN_stdfloat u_speed, PN_stdfloat v_speed, PN_stdfloat w_speed, PN_stdfloat r_speed) : PandaNode(name), _u_speed(u_speed), _v_speed(v_speed), @@ -30,7 +30,7 @@ UvScrollNode(const string &name, PN_stdfloat u_speed, PN_stdfloat v_speed, PN_st * */ INLINE UvScrollNode:: -UvScrollNode(const string &name) : +UvScrollNode(const std::string &name) : PandaNode(name), _u_speed(0), _v_speed(0), diff --git a/panda/src/pgraphnodes/uvScrollNode.h b/panda/src/pgraphnodes/uvScrollNode.h index 10dff152b7..51ab828130 100644 --- a/panda/src/pgraphnodes/uvScrollNode.h +++ b/panda/src/pgraphnodes/uvScrollNode.h @@ -23,10 +23,10 @@ /** * This node is placed at key points within the scene graph to animate uvs. */ -class EXPCL_PANDA_PGRAPH UvScrollNode : public PandaNode { +class EXPCL_PANDA_PGRAPHNODES UvScrollNode : public PandaNode { PUBLISHED: - INLINE explicit UvScrollNode(const string &name, PN_stdfloat u_speed, PN_stdfloat v_speed, PN_stdfloat w_speed, PN_stdfloat r_speed); - INLINE explicit UvScrollNode(const string &name); + INLINE explicit UvScrollNode(const std::string &name, PN_stdfloat u_speed, PN_stdfloat v_speed, PN_stdfloat w_speed, PN_stdfloat r_speed); + INLINE explicit UvScrollNode(const std::string &name); protected: INLINE UvScrollNode(const UvScrollNode ©); diff --git a/panda/src/pgui/pgButton.I b/panda/src/pgui/pgButton.I index ab7f44f503..a4939634fe 100644 --- a/panda/src/pgui/pgButton.I +++ b/panda/src/pgui/pgButton.I @@ -61,7 +61,7 @@ setup(const NodePath &ready, const NodePath &depressed, * PGButtons. The click event is the concatenation of this string followed by * get_id(). */ -INLINE string PGButton:: +INLINE std::string PGButton:: get_click_prefix() { return "click-"; } @@ -70,7 +70,7 @@ get_click_prefix() { * Returns the event name that will be thrown when the button is clicked * normally. */ -INLINE string PGButton:: +INLINE std::string PGButton:: get_click_event(const ButtonHandle &button) const { LightReMutexHolder holder(_lock); return get_click_prefix() + button.get_name() + "-" + get_id(); diff --git a/panda/src/pgui/pgButton.cxx b/panda/src/pgui/pgButton.cxx index 14821b017e..d1eba186c0 100644 --- a/panda/src/pgui/pgButton.cxx +++ b/panda/src/pgui/pgButton.cxx @@ -26,7 +26,7 @@ TypeHandle PGButton::_type_handle; * */ PGButton:: -PGButton(const string &name) : PGItem(name) +PGButton(const std::string &name) : PGItem(name) { _button_down = false; _click_buttons.insert(MouseButton::one()); @@ -134,7 +134,7 @@ void PGButton:: click(const MouseWatcherParameter ¶m) { LightReMutexHolder holder(_lock); PGMouseWatcherParameter *ep = new PGMouseWatcherParameter(param); - string event = get_click_event(param.get_button()); + std::string event = get_click_event(param.get_button()); play_sound(event); throw_event(event, EventParameter(ep)); @@ -150,7 +150,7 @@ click(const MouseWatcherParameter ¶m) { * to the size of the text. */ void PGButton:: -setup(const string &label, PN_stdfloat bevel) { +setup(const std::string &label, PN_stdfloat bevel) { LightReMutexHolder holder(_lock); clear_state_def(S_ready); clear_state_def(S_depressed); diff --git a/panda/src/pgui/pgButton.h b/panda/src/pgui/pgButton.h index ece2359762..3405f5b5d1 100644 --- a/panda/src/pgui/pgButton.h +++ b/panda/src/pgui/pgButton.h @@ -28,7 +28,7 @@ */ class EXPCL_PANDA_PGUI PGButton : public PGItem { PUBLISHED: - explicit PGButton(const string &name); + explicit PGButton(const std::string &name); virtual ~PGButton(); protected: @@ -55,7 +55,7 @@ PUBLISHED: S_inactive }; - void setup(const string &label, PN_stdfloat bevel = 0.1f); + void setup(const std::string &label, PN_stdfloat bevel = 0.1f); INLINE void setup(const NodePath &ready); INLINE void setup(const NodePath &ready, const NodePath &depressed); INLINE void setup(const NodePath &ready, const NodePath &depressed, @@ -71,8 +71,8 @@ PUBLISHED: INLINE bool is_button_down(); - INLINE static string get_click_prefix(); - INLINE string get_click_event(const ButtonHandle &button) const; + INLINE static std::string get_click_prefix(); + INLINE std::string get_click_event(const ButtonHandle &button) const; MAKE_PROPERTY(click_prefix, get_click_prefix); private: diff --git a/panda/src/pgui/pgEntry.I b/panda/src/pgui/pgEntry.I index dec418c9fd..7f76e3ef63 100644 --- a/panda/src/pgui/pgEntry.I +++ b/panda/src/pgui/pgEntry.I @@ -20,10 +20,10 @@ * truncated (see set_max_width(), etc.). */ INLINE bool PGEntry:: -set_text(const string &text) { +set_text(const std::string &text) { LightReMutexHolder holder(_lock); TextNode *text_node = get_text_def(S_focus); - nassertr(text_node != (TextNode *)NULL, false); + nassertr(text_node != nullptr, false); return set_wtext(text_node->decode_text(text)); } @@ -34,11 +34,11 @@ set_text(const string &text) { * This uses the Unicode encoding currently specified for the "focus" * TextNode; therefore, the TextNode must exist before calling get_text(). */ -INLINE string PGEntry:: +INLINE std::string PGEntry:: get_plain_text() const { LightReMutexHolder holder(_lock); TextNode *text_node = get_text_def(S_focus); - nassertr(text_node != (TextNode *)NULL, string()); + nassertr(text_node != nullptr, std::string()); return text_node->encode_wtext(get_plain_wtext()); } @@ -47,11 +47,11 @@ get_plain_text() const { * Unicode encoding currently specified for the "focus" TextNode; therefore, * the TextNode must exist before calling get_text(). */ -INLINE string PGEntry:: +INLINE std::string PGEntry:: get_text() const { LightReMutexHolder holder(_lock); TextNode *text_node = get_text_def(S_focus); - nassertr(text_node != (TextNode *)NULL, string()); + nassertr(text_node != nullptr, std::string()); return text_node->encode_wtext(get_wtext()); } @@ -350,7 +350,7 @@ get_overflow_mode() const { * candidate string that the user can actively scroll through. */ INLINE void PGEntry:: -set_candidate_active(const string &candidate_active) { +set_candidate_active(const std::string &candidate_active) { LightReMutexHolder holder(_lock); _candidate_active = candidate_active; } @@ -358,7 +358,7 @@ set_candidate_active(const string &candidate_active) { /** * See set_candidate_active(). */ -INLINE const string &PGEntry:: +INLINE const std::string &PGEntry:: get_candidate_active() const { LightReMutexHolder holder(_lock); return _candidate_active; @@ -377,7 +377,7 @@ get_candidate_active() const { * candidate string that the user is not actively scrolling through. */ INLINE void PGEntry:: -set_candidate_inactive(const string &candidate_inactive) { +set_candidate_inactive(const std::string &candidate_inactive) { LightReMutexHolder holder(_lock); _candidate_inactive = candidate_inactive; } @@ -385,7 +385,7 @@ set_candidate_inactive(const string &candidate_inactive) { /** * See set_candidate_inactive(). */ -INLINE const string &PGEntry:: +INLINE const std::string &PGEntry:: get_candidate_inactive() const { LightReMutexHolder holder(_lock); return _candidate_inactive; @@ -396,7 +396,7 @@ get_candidate_inactive() const { * PGEntries. The accept event is the concatenation of this string followed * by get_id(). */ -INLINE string PGEntry:: +INLINE std::string PGEntry:: get_accept_prefix() { return "accept-"; } @@ -406,7 +406,7 @@ get_accept_prefix() { * PGEntries. This event is the concatenation of this string followed by * get_id(). */ -INLINE string PGEntry:: +INLINE std::string PGEntry:: get_accept_failed_prefix() { return "acceptfailed-"; } @@ -416,7 +416,7 @@ get_accept_failed_prefix() { * PGEntries. The overflow event is the concatenation of this string followed * by get_id(). */ -INLINE string PGEntry:: +INLINE std::string PGEntry:: get_overflow_prefix() { return "overflow-"; } @@ -425,7 +425,7 @@ get_overflow_prefix() { * Returns the prefix that is used to define the type event for all PGEntries. * The type event is the concatenation of this string followed by get_id(). */ -INLINE string PGEntry:: +INLINE std::string PGEntry:: get_type_prefix() { return "type-"; } @@ -435,7 +435,7 @@ get_type_prefix() { * PGEntries. The erase event is the concatenation of this string followed by * get_id(). */ -INLINE string PGEntry:: +INLINE std::string PGEntry:: get_erase_prefix() { return "erase-"; } @@ -445,7 +445,7 @@ get_erase_prefix() { * PGEntries. The cursor event is the concatenation of this string followed * by get_id(). */ -INLINE string PGEntry:: +INLINE std::string PGEntry:: get_cursormove_prefix() { return "cursormove-"; } @@ -454,7 +454,7 @@ get_cursormove_prefix() { * Returns the event name that will be thrown when the entry is accepted * normally. */ -INLINE string PGEntry:: +INLINE std::string PGEntry:: get_accept_event(const ButtonHandle &button) const { return get_accept_prefix() + button.get_name() + "-" + get_id(); } @@ -463,7 +463,7 @@ get_accept_event(const ButtonHandle &button) const { * Returns the event name that will be thrown when the entry cannot accept an * input */ -INLINE string PGEntry:: +INLINE std::string PGEntry:: get_accept_failed_event(const ButtonHandle &button) const { return get_accept_failed_prefix() + button.get_name() + "-" + get_id(); } @@ -473,7 +473,7 @@ get_accept_failed_event(const ButtonHandle &button) const { * to be entered into the PGEntry, exceeding either the limit set via * set_max_chars() or via set_max_width(). */ -INLINE string PGEntry:: +INLINE std::string PGEntry:: get_overflow_event() const { return get_overflow_prefix() + get_id(); } @@ -482,7 +482,7 @@ get_overflow_event() const { * Returns the event name that will be thrown whenever the user extends the * text by typing. */ -INLINE string PGEntry:: +INLINE std::string PGEntry:: get_type_event() const { return get_type_prefix() + get_id(); } @@ -491,7 +491,7 @@ get_type_event() const { * Returns the event name that will be thrown whenever the user erases * characters in the text. */ -INLINE string PGEntry:: +INLINE std::string PGEntry:: get_erase_event() const { return get_erase_prefix() + get_id(); } @@ -499,7 +499,7 @@ get_erase_event() const { /** * Returns the event name that will be thrown whenever the cursor moves */ -INLINE string PGEntry:: +INLINE std::string PGEntry:: get_cursormove_event() const { return get_cursormove_prefix() + get_id(); } @@ -511,14 +511,14 @@ get_cursormove_event() const { * truncated (see set_max_width(), etc.). */ INLINE bool PGEntry:: -set_wtext(const wstring &wtext) { +set_wtext(const std::wstring &wtext) { LightReMutexHolder holder(_lock); bool ret = _text.set_wtext(wtext); if (_obscure_mode) { - ret = _obscure_text.set_wtext(wstring(_text.get_num_characters(), '*')); + ret = _obscure_text.set_wtext(std::wstring(_text.get_num_characters(), '*')); } _text_geom_stale = true; - set_cursor_position(min(_cursor_position, _text.get_num_characters())); + set_cursor_position(std::min(_cursor_position, _text.get_num_characters())); return ret; } @@ -526,7 +526,7 @@ set_wtext(const wstring &wtext) { * Returns the text currently displayed within the entry, without any embedded * properties characters. */ -INLINE wstring PGEntry:: +INLINE std::wstring PGEntry:: get_plain_wtext() const { LightReMutexHolder holder(_lock); return _text.get_plain_wtext(); @@ -535,7 +535,7 @@ get_plain_wtext() const { /** * Returns the text currently displayed within the entry. */ -INLINE wstring PGEntry:: +INLINE std::wstring PGEntry:: get_wtext() const { LightReMutexHolder holder(_lock); return _text.get_wtext(); diff --git a/panda/src/pgui/pgEntry.cxx b/panda/src/pgui/pgEntry.cxx index c9f84fae4f..b6a86754d7 100644 --- a/panda/src/pgui/pgEntry.cxx +++ b/panda/src/pgui/pgEntry.cxx @@ -27,6 +27,11 @@ #include +using std::max; +using std::min; +using std::string; +using std::wstring; + TypeHandle PGEntry::_type_handle; /** @@ -49,7 +54,7 @@ PGEntry(const string &name) : _max_width = 0.0f; _num_lines = 1; _accept_enabled = true; - _last_text_def = (TextNode *)NULL; + _last_text_def = nullptr; _text_geom_stale = true; _text_geom_flattened = true; _blink_start = 0.0f; @@ -117,7 +122,7 @@ PGEntry(const PGEntry ©) : _overflow_mode(copy._overflow_mode) { _cursor_stale = true; - _last_text_def = (TextNode *)NULL; + _last_text_def = nullptr; _text_geom_stale = true; _text_geom_flattened = true; @@ -642,7 +647,7 @@ void PGEntry:: set_text_def(int state, TextNode *node) { LightReMutexHolder holder(_lock); nassertv(state >= 0 && state < 1000); // Sanity check. - if (node == (TextNode *)NULL && state >= (int)_text_defs.size()) { + if (node == nullptr && state >= (int)_text_defs.size()) { // If we're setting it to NULL, we don't need to slot a new one. return; } @@ -662,7 +667,7 @@ get_text_def(int state) const { // If we don't have a definition, use the global one. return get_text_node(); } - if (_text_defs[state] == (TextNode *)NULL) { + if (_text_defs[state] == nullptr) { return get_text_node(); } return _text_defs[state]; @@ -715,7 +720,7 @@ is_wtext() const { void PGEntry:: slot_text_def(int state) { while (state >= (int)_text_defs.size()) { - _text_defs.push_back((TextNode *)NULL); + _text_defs.push_back(nullptr); } } @@ -725,7 +730,7 @@ slot_text_def(int state) { void PGEntry:: update_text() { TextNode *node = get_text_def(get_state()); - nassertv(node != (TextNode *)NULL); + nassertv(node != nullptr); if (_text_geom_stale || node != _last_text_def) { TextProperties props = *node; @@ -846,7 +851,7 @@ update_text() { void PGEntry:: update_cursor() { TextNode *node = get_text_def(get_state()); - nassertv(node != (TextNode *)NULL); + nassertv(node != nullptr); _cursor_scale.set_mat(node->get_transform()); _cursor_scale.set_color(node->get_text_color()); diff --git a/panda/src/pgui/pgEntry.h b/panda/src/pgui/pgEntry.h index 88fd5aaa89..825562aa82 100644 --- a/panda/src/pgui/pgEntry.h +++ b/panda/src/pgui/pgEntry.h @@ -36,7 +36,7 @@ */ class EXPCL_PANDA_PGUI PGEntry : public PGItem { PUBLISHED: - explicit PGEntry(const string &name); + explicit PGEntry(const std::string &name); virtual ~PGEntry(); protected: @@ -68,9 +68,9 @@ PUBLISHED: void setup(PN_stdfloat width, int num_lines); void setup_minimal(PN_stdfloat width, int num_lines); - INLINE bool set_text(const string &text); - INLINE string get_plain_text() const; - INLINE string get_text() const; + INLINE bool set_text(const std::string &text); + INLINE std::string get_plain_text() const; + INLINE std::string get_text() const; INLINE int get_num_characters() const; INLINE wchar_t get_character(int n) const; @@ -105,11 +105,11 @@ PUBLISHED: INLINE void set_overflow_mode(bool flag); INLINE bool get_overflow_mode() const; - INLINE void set_candidate_active(const string &candidate_active); - INLINE const string &get_candidate_active() const; + INLINE void set_candidate_active(const std::string &candidate_active); + INLINE const std::string &get_candidate_active() const; - INLINE void set_candidate_inactive(const string &candidate_inactive); - INLINE const string &get_candidate_inactive() const; + INLINE void set_candidate_inactive(const std::string &candidate_inactive); + INLINE const std::string &get_candidate_inactive() const; void set_text_def(int state, TextNode *node); TextNode *get_text_def(int state) const; @@ -117,24 +117,24 @@ PUBLISHED: virtual void set_active(bool active); virtual void set_focus(bool focus); - INLINE static string get_accept_prefix(); - INLINE static string get_accept_failed_prefix(); - INLINE static string get_overflow_prefix(); - INLINE static string get_type_prefix(); - INLINE static string get_erase_prefix(); - INLINE static string get_cursormove_prefix(); + INLINE static std::string get_accept_prefix(); + INLINE static std::string get_accept_failed_prefix(); + INLINE static std::string get_overflow_prefix(); + INLINE static std::string get_type_prefix(); + INLINE static std::string get_erase_prefix(); + INLINE static std::string get_cursormove_prefix(); - INLINE string get_accept_event(const ButtonHandle &button) const; - INLINE string get_accept_failed_event(const ButtonHandle &button) const; - INLINE string get_overflow_event() const; - INLINE string get_type_event() const; - INLINE string get_erase_event() const; - INLINE string get_cursormove_event() const; + INLINE std::string get_accept_event(const ButtonHandle &button) const; + INLINE std::string get_accept_failed_event(const ButtonHandle &button) const; + INLINE std::string get_overflow_event() const; + INLINE std::string get_type_event() const; + INLINE std::string get_erase_event() const; + INLINE std::string get_cursormove_event() const; - INLINE bool set_wtext(const wstring &wtext); - INLINE wstring get_plain_wtext() const; - INLINE wstring get_wtext() const; + INLINE bool set_wtext(const std::wstring &wtext); + INLINE std::wstring get_plain_wtext() const; + INLINE std::wstring get_wtext() const; INLINE void set_accept_enabled(bool enabled); bool is_wtext() const; @@ -152,7 +152,7 @@ private: bool _cursor_stale; bool _cursor_visible; - wstring _candidate_wtext; + std::wstring _candidate_wtext; size_t _candidate_highlight_start; size_t _candidate_highlight_end; size_t _candidate_cursor_pos; @@ -163,8 +163,8 @@ private: bool _accept_enabled; - string _candidate_active; - string _candidate_inactive; + std::string _candidate_active; + std::string _candidate_inactive; typedef pvector< PT(TextNode) > TextDefs; TextDefs _text_defs; diff --git a/panda/src/pgui/pgFrameStyle.I b/panda/src/pgui/pgFrameStyle.I index 2882d73935..8a5f31250a 100644 --- a/panda/src/pgui/pgFrameStyle.I +++ b/panda/src/pgui/pgFrameStyle.I @@ -222,8 +222,8 @@ get_visible_scale() const { /** * */ -INLINE ostream & -operator << (ostream &out, const PGFrameStyle &pfs) { +INLINE std::ostream & +operator << (std::ostream &out, const PGFrameStyle &pfs) { pfs.output(out); return out; } diff --git a/panda/src/pgui/pgFrameStyle.cxx b/panda/src/pgui/pgFrameStyle.cxx index c2106e3ef2..a8f53478cb 100644 --- a/panda/src/pgui/pgFrameStyle.cxx +++ b/panda/src/pgui/pgFrameStyle.cxx @@ -25,13 +25,16 @@ #include "geomTristrips.h" #include "geomVertexWriter.h" +using std::max; +using std::min; + // Specifies the UV range of textures applied to the frame. Maybe we'll have // a reason to make this a parameter of the frame style one day, but for now // it's hardcoded to fit the entire texture over the rectangular frame. static const LVecBase4 uv_range = LVecBase4(0.0f, 1.0f, 0.0f, 1.0f); -ostream & -operator << (ostream &out, PGFrameStyle::Type type) { +std::ostream & +operator << (std::ostream &out, PGFrameStyle::Type type) { switch (type) { case PGFrameStyle::T_none: return out << "none"; @@ -92,7 +95,7 @@ get_internal_frame(const LVecBase4 &frame) const { * */ void PGFrameStyle:: -output(ostream &out) const { +output(std::ostream &out) const { out << _type << " color = " << _color << " width = " << _width; if (_visible_scale != LVecBase2(1.0f, 1.0f)) { out << "visible_scale = " << get_visible_scale(); @@ -191,7 +194,7 @@ generate_into(const NodePath &parent, const LVecBase4 &frame, break; } - if (new_node != (PandaNode *)NULL && _color[3] != 1.0f) { + if (new_node != nullptr && _color[3] != 1.0f) { // We've got some alpha on the color; we need transparency. new_node->set_attrib(TransparencyAttrib::make(TransparencyAttrib::M_alpha)); } @@ -254,7 +257,7 @@ generate_flat_geom(const LVecBase4 &frame) { geom->add_primitive(strip); gnode->add_geom(geom, state); - return gnode.p(); + return gnode; } /** @@ -428,7 +431,7 @@ generate_bevel_geom(const LVecBase4 &frame, bool in) { } gnode->add_geom(geom, state); - return gnode.p(); + return gnode; } /** @@ -660,7 +663,7 @@ generate_groove_geom(const LVecBase4 &frame, bool in) { } gnode->add_geom(geom, state); - return gnode.p(); + return gnode; } /** @@ -800,5 +803,5 @@ generate_texture_border_geom(const LVecBase4 &frame) { geom->add_primitive(strip); gnode->add_geom(geom, state); - return gnode.p(); + return gnode; } diff --git a/panda/src/pgui/pgFrameStyle.h b/panda/src/pgui/pgFrameStyle.h index 107b217192..19283c962f 100644 --- a/panda/src/pgui/pgFrameStyle.h +++ b/panda/src/pgui/pgFrameStyle.h @@ -70,7 +70,7 @@ PUBLISHED: LVecBase4 get_internal_frame(const LVecBase4 &frame) const; - void output(ostream &out) const; + void output(std::ostream &out) const; public: bool xform(const LMatrix4 &mat); @@ -92,8 +92,8 @@ private: LVecBase2 _visible_scale; }; -INLINE ostream &operator << (ostream &out, const PGFrameStyle &pfs); -ostream &operator << (ostream &out, PGFrameStyle::Type type); +INLINE std::ostream &operator << (std::ostream &out, const PGFrameStyle &pfs); +std::ostream &operator << (std::ostream &out, PGFrameStyle::Type type); #include "pgFrameStyle.I" diff --git a/panda/src/pgui/pgItem.I b/panda/src/pgui/pgItem.I index 7d00a0e595..cfbf10f6b0 100644 --- a/panda/src/pgui/pgItem.I +++ b/panda/src/pgui/pgItem.I @@ -15,7 +15,7 @@ * */ INLINE void PGItem:: -set_name(const string &name) { +set_name(const std::string &name) { Namable::set_name(name); _lock.set_name(name); } @@ -42,11 +42,11 @@ get_region() const { INLINE void PGItem:: set_notify(PGItemNotify *notify) { LightReMutexHolder holder(_lock); - if (_notify != (PGItemNotify *)NULL) { + if (_notify != nullptr) { _notify->remove_item(this); } _notify = notify; - if (_notify != (PGItemNotify *)NULL) { + if (_notify != nullptr) { _notify->add_item(this); } } @@ -58,7 +58,7 @@ set_notify(PGItemNotify *notify) { INLINE bool PGItem:: has_notify() const { LightReMutexHolder holder(_lock); - return (_notify != (PGItemNotify *)NULL); + return (_notify != nullptr); } /** @@ -202,12 +202,25 @@ get_suppress_flags() const { return _region->get_suppress_flags(); } +/** + * Returns the Node that is the root of the subgraph that will be drawn when + * the PGItem is in the indicated state. The first time this is called for a + * particular state index, it may create the Node. + */ +INLINE NodePath &PGItem:: +get_state_def(int state) { + nassertr(state >= 0 && state < 1000, get_state_def(0)); // Sanity check. + + LightReMutexHolder holder(_lock); + return do_get_state_def(state); +} + /** * Returns the unique ID assigned to this PGItem. This will be assigned to * the region created with the MouseWatcher, and will thus be used to generate * event names. */ -INLINE const string &PGItem:: +INLINE const std::string &PGItem:: get_id() const { LightReMutexHolder holder(_lock); return _region->get_name(); @@ -222,7 +235,7 @@ get_id() const { * decide to redefine the ID to be something possibly more meaningful. */ INLINE void PGItem:: -set_id(const string &id) { +set_id(const std::string &id) { LightReMutexHolder holder(_lock); _region->set_name(id); } @@ -231,7 +244,7 @@ set_id(const string &id) { * Returns the prefix that is used to define the enter event for all PGItems. * The enter event is the concatenation of this string followed by get_id(). */ -INLINE string PGItem:: +INLINE std::string PGItem:: get_enter_prefix() { return "enter-"; } @@ -240,7 +253,7 @@ get_enter_prefix() { * Returns the prefix that is used to define the exit event for all PGItems. * The exit event is the concatenation of this string followed by get_id(). */ -INLINE string PGItem:: +INLINE std::string PGItem:: get_exit_prefix() { return "exit-"; } @@ -249,7 +262,7 @@ get_exit_prefix() { * Returns the prefix that is used to define the within event for all PGItems. * The within event is the concatenation of this string followed by get_id(). */ -INLINE string PGItem:: +INLINE std::string PGItem:: get_within_prefix() { return "within-"; } @@ -259,7 +272,7 @@ get_within_prefix() { * PGItems. The without event is the concatenation of this string followed by * get_id(). */ -INLINE string PGItem:: +INLINE std::string PGItem:: get_without_prefix() { return "without-"; } @@ -271,7 +284,7 @@ get_without_prefix() { * * Unlike most item events, this event is thrown with no parameters. */ -INLINE string PGItem:: +INLINE std::string PGItem:: get_focus_in_prefix() { return "fin-"; } @@ -283,7 +296,7 @@ get_focus_in_prefix() { * * Unlike most item events, this event is thrown with no parameters. */ -INLINE string PGItem:: +INLINE std::string PGItem:: get_focus_out_prefix() { return "fout-"; } @@ -293,7 +306,7 @@ get_focus_out_prefix() { * The press event is the concatenation of this string followed by a button * name, followed by a hyphen and get_id(). */ -INLINE string PGItem:: +INLINE std::string PGItem:: get_press_prefix() { return "press-"; } @@ -303,7 +316,7 @@ get_press_prefix() { * The repeat event is the concatenation of this string followed by a button * name, followed by a hyphen and get_id(). */ -INLINE string PGItem:: +INLINE std::string PGItem:: get_repeat_prefix() { return "repeat-"; } @@ -313,7 +326,7 @@ get_repeat_prefix() { * PGItems. The release event is the concatenation of this string followed by * a button name, followed by a hyphen and get_id(). */ -INLINE string PGItem:: +INLINE std::string PGItem:: get_release_prefix() { return "release-"; } @@ -323,7 +336,7 @@ get_release_prefix() { * PGItems. The keystroke event is the concatenation of this string followed * by a hyphen and get_id(). */ -INLINE string PGItem:: +INLINE std::string PGItem:: get_keystroke_prefix() { return "keystroke-"; } @@ -332,7 +345,7 @@ get_keystroke_prefix() { * Returns the event name that will be thrown when the item is active and the * mouse enters its frame, but not any nested frames. */ -INLINE string PGItem:: +INLINE std::string PGItem:: get_enter_event() const { LightReMutexHolder holder(_lock); return get_enter_prefix() + get_id(); @@ -342,7 +355,7 @@ get_enter_event() const { * Returns the event name that will be thrown when the item is active and the * mouse exits its frame, or enters a nested frame. */ -INLINE string PGItem:: +INLINE std::string PGItem:: get_exit_event() const { LightReMutexHolder holder(_lock); return get_exit_prefix() + get_id(); @@ -354,7 +367,7 @@ get_exit_event() const { * enter_event in that the mouse is considered within the frame even if it is * also within a nested frame. */ -INLINE string PGItem:: +INLINE std::string PGItem:: get_within_event() const { LightReMutexHolder holder(_lock); return get_within_prefix() + get_id(); @@ -366,7 +379,7 @@ get_within_event() const { * different from the exit_event in that the mouse is considered within the * frame even if it is also within a nested frame. */ -INLINE string PGItem:: +INLINE std::string PGItem:: get_without_event() const { LightReMutexHolder holder(_lock); return get_without_prefix() + get_id(); @@ -376,7 +389,7 @@ get_without_event() const { * Returns the event name that will be thrown when the item gets the keyboard * focus. */ -INLINE string PGItem:: +INLINE std::string PGItem:: get_focus_in_event() const { LightReMutexHolder holder(_lock); return get_focus_in_prefix() + get_id(); @@ -386,7 +399,7 @@ get_focus_in_event() const { * Returns the event name that will be thrown when the item loses the keyboard * focus. */ -INLINE string PGItem:: +INLINE std::string PGItem:: get_focus_out_event() const { LightReMutexHolder holder(_lock); return get_focus_out_prefix() + get_id(); @@ -397,7 +410,7 @@ get_focus_out_event() const { * indicated mouse or keyboard button is depressed while the mouse is within * the frame. */ -INLINE string PGItem:: +INLINE std::string PGItem:: get_press_event(const ButtonHandle &button) const { LightReMutexHolder holder(_lock); return get_press_prefix() + button.get_name() + "-" + get_id(); @@ -408,7 +421,7 @@ get_press_event(const ButtonHandle &button) const { * indicated mouse or keyboard button is continuously held down while the * mouse is within the frame. */ -INLINE string PGItem:: +INLINE std::string PGItem:: get_repeat_event(const ButtonHandle &button) const { LightReMutexHolder holder(_lock); return get_repeat_prefix() + button.get_name() + "-" + get_id(); @@ -419,7 +432,7 @@ get_repeat_event(const ButtonHandle &button) const { * indicated mouse or keyboard button, formerly clicked down is within the * frame, is released. */ -INLINE string PGItem:: +INLINE std::string PGItem:: get_release_event(const ButtonHandle &button) const { LightReMutexHolder holder(_lock); return get_release_prefix() + button.get_name() + "-" + get_id(); @@ -429,7 +442,7 @@ get_release_event(const ButtonHandle &button) const { * Returns the event name that will be thrown when the item is active and any * key is pressed by the user. */ -INLINE string PGItem:: +INLINE std::string PGItem:: get_keystroke_event() const { LightReMutexHolder holder(_lock); return get_keystroke_prefix() + get_id(); diff --git a/panda/src/pgui/pgItem.cxx b/panda/src/pgui/pgItem.cxx index 53966e26d7..a266547ced 100644 --- a/panda/src/pgui/pgItem.cxx +++ b/panda/src/pgui/pgItem.cxx @@ -35,9 +35,11 @@ #include "audioSound.h" #endif +using std::string; + TypeHandle PGItem::_type_handle; PT(TextNode) PGItem::_text_node; -PGItem *PGItem::_focus_item = (PGItem *)NULL; +PGItem *PGItem::_focus_item = nullptr; PGItem::BackgroundFocus PGItem::_background_focus; @@ -55,16 +57,15 @@ is_right(const LVector2 &v1, const LVector2 &v2) { PGItem:: PGItem(const string &name) : PandaNode(name), - _lock(name) + _lock(name), + _notify(nullptr), + _has_frame(false), + _frame(0, 0, 0, 0), + _region(new PGMouseWatcherRegion(this)), + _state(0), + _flags(0) { set_cull_callback(); - - _notify = NULL; - _has_frame = false; - _frame.set(0, 0, 0, 0); - _region = new PGMouseWatcherRegion(this); - _state = 0; - _flags = 0; } /** @@ -72,17 +73,17 @@ PGItem(const string &name) : */ PGItem:: ~PGItem() { - if (_notify != (PGItemNotify *)NULL) { + if (_notify != nullptr) { _notify->remove_item(this); - _notify = NULL; + _notify = nullptr; } nassertv(_region->_item == this); - _region->_item = (PGItem *)NULL; + _region->_item = nullptr; set_background_focus(false); if (_focus_item == this) { - _focus_item = (PGItem *)NULL; + _focus_item = nullptr; } } @@ -92,17 +93,16 @@ PGItem:: PGItem:: PGItem(const PGItem ©) : PandaNode(copy), + _notify(nullptr), _has_frame(copy._has_frame), _frame(copy._frame), _state(copy._state), - _flags(copy._flags) + _flags(copy._flags), + _region(new PGMouseWatcherRegion(this)) #ifdef HAVE_AUDIO , _sounds(copy._sounds) #endif { - _notify = NULL; - _region = new PGMouseWatcherRegion(this); - // We give our region the same name as the region for the PGItem we're // copying--so that this PGItem will generate the same event names when the // user interacts with it. @@ -186,9 +186,29 @@ draw_mask_changed() { */ bool PGItem:: cull_callback(CullTraverser *trav, CullTraverserData &data) { - LightReMutexHolder holder(_lock); - bool this_node_hidden = data.is_this_node_hidden(trav->get_camera_mask()); - if (!this_node_hidden && has_frame() && get_active()) { + // We try not to hold the lock for longer than necessary. + PT(PandaNode) state_def_root; + bool has_frame; + PGMouseWatcherRegion *region; + { + LightReMutexHolder holder(_lock); + has_frame = _has_frame && ((_flags & F_active) != 0); + region = _region; + + int state = _state; + if (state >= 0 && (size_t)state < _state_defs.size()) { + StateDef &state_def = _state_defs[state]; + if (!state_def._root.is_empty()) { + if (state_def._frame_stale) { + update_frame(state); + } + + state_def_root = state_def._root.node(); + } + } + } + + if (has_frame && !data.is_this_node_hidden(trav->get_camera_mask())) { // The item has a frame, so we want to generate a region for it and update // the MouseWatcher. @@ -198,8 +218,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { PGCullTraverser *pg_trav; DCAST_INTO_R(pg_trav, trav, true); - CPT(TransformState) net_transform = data.get_net_transform(trav); - const LMatrix4 &transform = net_transform->get_mat(); + const LMatrix4 &transform = data.get_net_transform(trav)->get_mat(); // Consider the cull bin this object is in. Since the binning affects // the render order, we want bins that render later to get higher sort @@ -236,19 +255,20 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { // the existing interface which only provides one. sort = (bin_sort << 16) | ((sort + 0x8000) & 0xffff); - if (activate_region(transform, sort, - DCAST(ClipPlaneAttrib, data._state->get_attrib(ClipPlaneAttrib::get_class_slot())), - DCAST(ScissorAttrib, data._state->get_attrib(ScissorAttrib::get_class_slot())))) { - pg_trav->_top->add_region(get_region()); + const ClipPlaneAttrib *clip = nullptr; + const ScissorAttrib *scissor = nullptr; + data._state->get_attrib(clip); + data._state->get_attrib(scissor); + if (activate_region(transform, sort, clip, scissor)) { + pg_trav->_top->add_region(region); } } } - if (has_state_def(get_state())) { + if (state_def_root != nullptr) { // This item has a current state definition that we should use to render // the item. - NodePath &root = get_state_def(get_state()); - CullTraverserData next_data(data, root.node()); + CullTraverserData next_data(data, state_def_root); trav->traverse(next_data); } @@ -302,7 +322,7 @@ compute_internal_bounds(CPT(BoundingVolume) &internal_bounds, // get_state_def() on each one, to ensure that the frames are updated // correctly before we measure their bounding volumes. for (int i = 0; i < (int)_state_defs.size(); i++) { - NodePath &root = ((PGItem *)this)->get_state_def(i); + NodePath &root = ((PGItem *)this)->do_get_state_def(i); if (!root.is_empty()) { PandaNode *node = root.node(); child_volumes.push_back(node->get_bounds(current_thread)); @@ -384,6 +404,9 @@ bool PGItem:: activate_region(const LMatrix4 &transform, int sort, const ClipPlaneAttrib *cpa, const ScissorAttrib *sa) { + using std::min; + using std::max; + LightReMutexHolder holder(_lock); // Transform all four vertices, and get the new bounding box. This way the // region works (mostly) even if has been rotated. @@ -415,7 +438,7 @@ activate_region(const LMatrix4 &transform, int sort, } LVecBase4 frame; - if (cpa != (ClipPlaneAttrib *)NULL && cpa->get_num_on_planes() != 0) { + if (cpa != nullptr && cpa->get_num_on_planes() != 0) { // Apply the clip plane(s) andor scissor region now that we are here in // world space. @@ -462,7 +485,7 @@ activate_region(const LMatrix4 &transform, int sort, max(max(ll[up_axis], lr[up_axis]), max(ul[up_axis], ur[up_axis]))); } - if (sa != (ScissorAttrib *)NULL) { + if (sa != nullptr) { // Also restrict it to within the scissor region. const LVecBase4 &sf = sa->get_frame(); // Expand sf from 0..1 to -1..1. @@ -835,7 +858,7 @@ set_focus(bool focus) { // Set the keyboard focus to this item. if (_focus_item != this) { - if (_focus_item != (PGItem *)NULL) { + if (_focus_item != nullptr) { // Clear the focus from whatever item currently has it. _focus_item->set_focus(false); } @@ -849,7 +872,7 @@ set_focus(bool focus) { } else { if (_focus_item == this) { // Remove this item from the focus. - _focus_item = (PGItem *)NULL; + _focus_item = nullptr; } if (get_focus()) { @@ -931,30 +954,6 @@ clear_state_def(int state) { mark_internal_bounds_stale(); } -/** - * Returns the Node that is the root of the subgraph that will be drawn when - * the PGItem is in the indicated state. The first time this is called for a - * particular state index, it may create the Node. - */ -NodePath &PGItem:: -get_state_def(int state) { - LightReMutexHolder holder(_lock); - nassertr(state >= 0 && state < 1000, get_state_def(0)); // Sanity check. - slot_state_def(state); - - if (_state_defs[state]._root.is_empty()) { - // Create a new node. - _state_defs[state]._root = NodePath("state_" + format_string(state)); - _state_defs[state]._frame_stale = true; - } - - if (_state_defs[state]._frame_stale) { - update_frame(state); - } - - return _state_defs[state]._root; -} - /** * Parents an instance of the bottom node of the indicated NodePath to the * indicated state index. @@ -969,7 +968,7 @@ instance_to_state_def(int state, const NodePath &path) { mark_internal_bounds_stale(); - return path.instance_to(get_state_def(state)); + return path.instance_to(do_get_state_def(state)); } /** @@ -994,7 +993,7 @@ set_frame_style(int state, const PGFrameStyle &style) { LightReMutexHolder holder(_lock); // Get the state def node, mainly to ensure that this state is slotted and // listed as having been defined. - NodePath &root = get_state_def(state); + NodePath &root = do_get_state_def(state); nassertv(!root.is_empty()); _state_defs[state]._frame_style = style; @@ -1033,7 +1032,7 @@ get_sound(const string &event) const { if (si != _sounds.end()) { return (*si).second; } - return (AudioSound *)NULL; + return nullptr; } /** @@ -1054,7 +1053,7 @@ has_sound(const string &event) const { */ TextNode *PGItem:: get_text_node() { - if (_text_node == (TextNode *)NULL) { + if (_text_node == nullptr) { _text_node = new TextNode("pguiText"); _text_node->set_text_color(0.0f, 0.0f, 0.0f, 1.0f); @@ -1093,7 +1092,10 @@ play_sound(const string &event) { */ void PGItem:: reduce_region(LVecBase4 &frame, PGItem *obscurer) const { - if (obscurer != (PGItem *)NULL && !obscurer->is_overall_hidden()) { + using std::min; + using std::max; + + if (obscurer != nullptr && !obscurer->is_overall_hidden()) { LVecBase4 oframe = get_relative_frame(obscurer); // Determine the four rectangular regions on the four sides of the @@ -1120,6 +1122,9 @@ reduce_region(LVecBase4 &frame, PGItem *obscurer) const { */ LVecBase4 PGItem:: get_relative_frame(PGItem *item) const { + using std::min; + using std::max; + NodePath this_np = NodePath::any_path((PGItem *)this); NodePath item_np = this_np.find_path_to(item); if (item_np.is_empty()) { @@ -1170,6 +1175,30 @@ frame_changed() { } } +/** + * Returns the Node that is the root of the subgraph that will be drawn when + * the PGItem is in the indicated state. The first time this is called for a + * particular state index, it may create the Node. + * + * Assumes the lock is already held. + */ +NodePath &PGItem:: +do_get_state_def(int state) { + slot_state_def(state); + + if (_state_defs[state]._root.is_empty()) { + // Create a new node. + _state_defs[state]._root = NodePath("state_" + format_string(state)); + _state_defs[state]._frame_stale = true; + } + + if (_state_defs[state]._frame_stale) { + update_frame(state); + } + + return _state_defs[state]._root; +} + /** * Ensures there is a slot in the array for the given state definition. */ @@ -1196,7 +1225,7 @@ update_frame(int state) { // Now create new frame geometry. if (has_frame()) { - NodePath &root = get_state_def(state); + NodePath &root = do_get_state_def(state); _state_defs[state]._frame = _state_defs[state]._frame_style.generate_into(root, _frame); } diff --git a/panda/src/pgui/pgItem.h b/panda/src/pgui/pgItem.h index c39103154a..2c26f91602 100644 --- a/panda/src/pgui/pgItem.h +++ b/panda/src/pgui/pgItem.h @@ -52,10 +52,10 @@ class ScissorAttrib; */ class EXPCL_PANDA_PGUI PGItem : public PandaNode { PUBLISHED: - explicit PGItem(const string &name); + explicit PGItem(const std::string &name); virtual ~PGItem(); - INLINE void set_name(const string &name); + INLINE void set_name(const std::string &name); protected: PGItem(const PGItem ©); @@ -77,11 +77,12 @@ protected: GeomTransformer &transformer, Thread *current_thread); -public: virtual void xform(const LMatrix4 &mat); bool activate_region(const LMatrix4 &transform, int sort, const ClipPlaneAttrib *cpa, const ScissorAttrib *sa); + +public: INLINE PGMouseWatcherRegion *get_region() const; virtual void enter_region(const MouseWatcherParameter ¶m); @@ -130,45 +131,45 @@ PUBLISHED: int get_num_state_defs() const; void clear_state_def(int state); bool has_state_def(int state) const; - NodePath &get_state_def(int state); + INLINE NodePath &get_state_def(int state); MAKE_SEQ(get_state_defs, get_num_state_defs, get_state_def); NodePath instance_to_state_def(int state, const NodePath &path); PGFrameStyle get_frame_style(int state); void set_frame_style(int state, const PGFrameStyle &style); - INLINE const string &get_id() const; - INLINE void set_id(const string &id); + INLINE const std::string &get_id() const; + INLINE void set_id(const std::string &id); - INLINE static string get_enter_prefix(); - INLINE static string get_exit_prefix(); - INLINE static string get_within_prefix(); - INLINE static string get_without_prefix(); - INLINE static string get_focus_in_prefix(); - INLINE static string get_focus_out_prefix(); - INLINE static string get_press_prefix(); - INLINE static string get_repeat_prefix(); - INLINE static string get_release_prefix(); - INLINE static string get_keystroke_prefix(); + INLINE static std::string get_enter_prefix(); + INLINE static std::string get_exit_prefix(); + INLINE static std::string get_within_prefix(); + INLINE static std::string get_without_prefix(); + INLINE static std::string get_focus_in_prefix(); + INLINE static std::string get_focus_out_prefix(); + INLINE static std::string get_press_prefix(); + INLINE static std::string get_repeat_prefix(); + INLINE static std::string get_release_prefix(); + INLINE static std::string get_keystroke_prefix(); - INLINE string get_enter_event() const; - INLINE string get_exit_event() const; - INLINE string get_within_event() const; - INLINE string get_without_event() const; - INLINE string get_focus_in_event() const; - INLINE string get_focus_out_event() const; - INLINE string get_press_event(const ButtonHandle &button) const; - INLINE string get_repeat_event(const ButtonHandle &button) const; - INLINE string get_release_event(const ButtonHandle &button) const; - INLINE string get_keystroke_event() const; + INLINE std::string get_enter_event() const; + INLINE std::string get_exit_event() const; + INLINE std::string get_within_event() const; + INLINE std::string get_without_event() const; + INLINE std::string get_focus_in_event() const; + INLINE std::string get_focus_out_event() const; + INLINE std::string get_press_event(const ButtonHandle &button) const; + INLINE std::string get_repeat_event(const ButtonHandle &button) const; + INLINE std::string get_release_event(const ButtonHandle &button) const; + INLINE std::string get_keystroke_event() const; INLINE LMatrix4 get_frame_inv_xform() const; #ifdef HAVE_AUDIO - void set_sound(const string &event, AudioSound *sound); - void clear_sound(const string &event); - AudioSound *get_sound(const string &event) const; - bool has_sound(const string &event) const; + void set_sound(const std::string &event, AudioSound *sound); + void clear_sound(const std::string &event); + AudioSound *get_sound(const std::string &event) const; + bool has_sound(const std::string &event) const; #endif static TextNode *get_text_node(); @@ -177,7 +178,7 @@ PUBLISHED: INLINE static PGItem *get_focus_item(); protected: - void play_sound(const string &event); + void play_sound(const std::string &event); void reduce_region(LVecBase4 &clip, PGItem *obscurer) const; void reduce_region(LVecBase4 &frame, PN_stdfloat px, PN_stdfloat py) const; @@ -187,6 +188,7 @@ protected: virtual void frame_changed(); private: + NodePath &do_get_state_def(int state); void slot_state_def(int state); void update_frame(int state); void mark_frames_stale(); @@ -215,7 +217,7 @@ private: }; int _flags; - PT(PGMouseWatcherRegion) _region; + PT(PGMouseWatcherRegion) const _region; LMatrix4 _frame_inv_xform; @@ -231,7 +233,7 @@ private: StateDefs _state_defs; #ifdef HAVE_AUDIO - typedef pmap Sounds; + typedef pmap Sounds; Sounds _sounds; #endif diff --git a/panda/src/pgui/pgItemNotify.cxx b/panda/src/pgui/pgItemNotify.cxx index 52f01dc63b..da232d6a95 100644 --- a/panda/src/pgui/pgItemNotify.cxx +++ b/panda/src/pgui/pgItemNotify.cxx @@ -23,7 +23,7 @@ PGItemNotify:: // Disconnect all of the items that are connected to this object. PGItem *item = (*_items.begin()); nassertv(item->get_notify() == this); - (*_items.begin())->set_notify(NULL); + (*_items.begin())->set_notify(nullptr); } } diff --git a/panda/src/pgui/pgMouseWatcherGroup.I b/panda/src/pgui/pgMouseWatcherGroup.I index db3ce6b80a..f0ae87c891 100644 --- a/panda/src/pgui/pgMouseWatcherGroup.I +++ b/panda/src/pgui/pgMouseWatcherGroup.I @@ -25,5 +25,5 @@ PGMouseWatcherGroup(PGTop *top) : _top(top) { INLINE void PGMouseWatcherGroup:: clear_top(PGTop *top) { nassertv(_top == top); - _top = (PGTop *)NULL; + _top = nullptr; } diff --git a/panda/src/pgui/pgMouseWatcherGroup.cxx b/panda/src/pgui/pgMouseWatcherGroup.cxx index ccc3e91f31..d5f14976ce 100644 --- a/panda/src/pgui/pgMouseWatcherGroup.cxx +++ b/panda/src/pgui/pgMouseWatcherGroup.cxx @@ -23,8 +23,8 @@ PGMouseWatcherGroup:: ~PGMouseWatcherGroup() { // When the MouseWatcherGroup destructs for whatever reason, the PGTop // object should lose its MouseWatcher. - if (_top != (PGTop *)NULL) { - _top->_watcher_group = (PGMouseWatcherGroup *)NULL; - _top->set_mouse_watcher((MouseWatcher *)NULL); + if (_top != nullptr) { + _top->_watcher_group = nullptr; + _top->set_mouse_watcher(nullptr); } } diff --git a/panda/src/pgui/pgMouseWatcherParameter.cxx b/panda/src/pgui/pgMouseWatcherParameter.cxx index 52844f5e23..732d5f01a4 100644 --- a/panda/src/pgui/pgMouseWatcherParameter.cxx +++ b/panda/src/pgui/pgMouseWatcherParameter.cxx @@ -26,6 +26,6 @@ PGMouseWatcherParameter:: * */ void PGMouseWatcherParameter:: -output(ostream &out) const { +output(std::ostream &out) const { MouseWatcherParameter::output(out); } diff --git a/panda/src/pgui/pgMouseWatcherParameter.h b/panda/src/pgui/pgMouseWatcherParameter.h index 930d1d55c2..ff8c41cfba 100644 --- a/panda/src/pgui/pgMouseWatcherParameter.h +++ b/panda/src/pgui/pgMouseWatcherParameter.h @@ -37,7 +37,7 @@ public: virtual ~PGMouseWatcherParameter(); PUBLISHED: - void output(ostream &out) const; + void output(std::ostream &out) const; public: static TypeHandle get_class_type() { diff --git a/panda/src/pgui/pgMouseWatcherRegion.cxx b/panda/src/pgui/pgMouseWatcherRegion.cxx index 6e0a18daad..2f0155722f 100644 --- a/panda/src/pgui/pgMouseWatcherRegion.cxx +++ b/panda/src/pgui/pgMouseWatcherRegion.cxx @@ -47,7 +47,7 @@ PGMouseWatcherRegion:: */ void PGMouseWatcherRegion:: enter_region(const MouseWatcherParameter ¶m) { - if (_item != (PGItem *)NULL) { + if (_item != nullptr) { _item->enter_region(param); } } @@ -60,7 +60,7 @@ enter_region(const MouseWatcherParameter ¶m) { */ void PGMouseWatcherRegion:: exit_region(const MouseWatcherParameter ¶m) { - if (_item != (PGItem *)NULL) { + if (_item != nullptr) { _item->exit_region(param); } } @@ -73,7 +73,7 @@ exit_region(const MouseWatcherParameter ¶m) { */ void PGMouseWatcherRegion:: within_region(const MouseWatcherParameter ¶m) { - if (_item != (PGItem *)NULL) { + if (_item != nullptr) { _item->within_region(param); } } @@ -84,7 +84,7 @@ within_region(const MouseWatcherParameter ¶m) { */ void PGMouseWatcherRegion:: without_region(const MouseWatcherParameter ¶m) { - if (_item != (PGItem *)NULL) { + if (_item != nullptr) { _item->without_region(param); } } @@ -95,7 +95,7 @@ without_region(const MouseWatcherParameter ¶m) { */ void PGMouseWatcherRegion:: press(const MouseWatcherParameter ¶m) { - if (_item != (PGItem *)NULL) { + if (_item != nullptr) { _item->press(param, false); } } @@ -106,7 +106,7 @@ press(const MouseWatcherParameter ¶m) { */ void PGMouseWatcherRegion:: release(const MouseWatcherParameter ¶m) { - if (_item != (PGItem *)NULL) { + if (_item != nullptr) { _item->release(param, false); } } @@ -116,7 +116,7 @@ release(const MouseWatcherParameter ¶m) { */ void PGMouseWatcherRegion:: keystroke(const MouseWatcherParameter ¶m) { - if (_item != (PGItem *)NULL) { + if (_item != nullptr) { _item->keystroke(param, false); } } @@ -127,7 +127,7 @@ keystroke(const MouseWatcherParameter ¶m) { */ void PGMouseWatcherRegion:: candidate(const MouseWatcherParameter ¶m) { - if (_item != (PGItem *)NULL) { + if (_item != nullptr) { _item->candidate(param, false); } } @@ -138,7 +138,7 @@ candidate(const MouseWatcherParameter ¶m) { */ void PGMouseWatcherRegion:: move(const MouseWatcherParameter ¶m) { - if (_item != (PGItem *)NULL) { + if (_item != nullptr) { _item->move(param); } } diff --git a/panda/src/pgui/pgScrollFrame.I b/panda/src/pgui/pgScrollFrame.I index ede2f4201e..69353db31b 100644 --- a/panda/src/pgui/pgScrollFrame.I +++ b/panda/src/pgui/pgScrollFrame.I @@ -127,11 +127,11 @@ get_auto_hide() const { INLINE void PGScrollFrame:: set_horizontal_slider(PGSliderBar *horizontal_slider) { LightReMutexHolder holder(_lock); - if (_horizontal_slider != (PGSliderBar *)NULL) { - _horizontal_slider->set_notify(NULL); + if (_horizontal_slider != nullptr) { + _horizontal_slider->set_notify(nullptr); } _horizontal_slider = horizontal_slider; - if (_horizontal_slider != (PGSliderBar *)NULL) { + if (_horizontal_slider != nullptr) { _horizontal_slider->set_notify(this); } _needs_recompute_clip = true; @@ -143,7 +143,7 @@ set_horizontal_slider(PGSliderBar *horizontal_slider) { */ INLINE void PGScrollFrame:: clear_horizontal_slider() { - set_horizontal_slider(NULL); + set_horizontal_slider(nullptr); } /** @@ -164,11 +164,11 @@ get_horizontal_slider() const { INLINE void PGScrollFrame:: set_vertical_slider(PGSliderBar *vertical_slider) { LightReMutexHolder holder(_lock); - if (_vertical_slider != (PGSliderBar *)NULL) { - _vertical_slider->set_notify(NULL); + if (_vertical_slider != nullptr) { + _vertical_slider->set_notify(nullptr); } _vertical_slider = vertical_slider; - if (_vertical_slider != (PGSliderBar *)NULL) { + if (_vertical_slider != nullptr) { _vertical_slider->set_notify(this); } _needs_recompute_clip = true; @@ -180,7 +180,7 @@ set_vertical_slider(PGSliderBar *vertical_slider) { */ INLINE void PGScrollFrame:: clear_vertical_slider() { - set_vertical_slider(NULL); + set_vertical_slider(nullptr); } /** diff --git a/panda/src/pgui/pgScrollFrame.cxx b/panda/src/pgui/pgScrollFrame.cxx index e930ba3b15..a41916d3c9 100644 --- a/panda/src/pgui/pgScrollFrame.cxx +++ b/panda/src/pgui/pgScrollFrame.cxx @@ -19,7 +19,7 @@ TypeHandle PGScrollFrame::_type_handle; * */ PGScrollFrame:: -PGScrollFrame(const string &name) : PGVirtualFrame(name) +PGScrollFrame(const std::string &name) : PGVirtualFrame(name) { set_cull_callback(); @@ -30,8 +30,8 @@ PGScrollFrame(const string &name) : PGVirtualFrame(name) _virtual_frame.set(0.0f, 0.0f, 0.0f, 0.0f); _manage_pieces = false; _auto_hide = false; - _horizontal_slider = NULL; - _vertical_slider = NULL; + _horizontal_slider = nullptr; + _vertical_slider = nullptr; } /** @@ -39,8 +39,8 @@ PGScrollFrame(const string &name) : PGVirtualFrame(name) */ PGScrollFrame:: ~PGScrollFrame() { - set_horizontal_slider(NULL); - set_vertical_slider(NULL); + set_horizontal_slider(nullptr); + set_vertical_slider(nullptr); } /** @@ -143,13 +143,13 @@ setup(PN_stdfloat width, PN_stdfloat height, set_virtual_frame(left, right, bottom, top); // Remove the slider nodes created by a previous call to setup(), if any. - if (_horizontal_slider != (PGSliderBar *)NULL) { + if (_horizontal_slider != nullptr) { remove_child(_horizontal_slider); - set_horizontal_slider(NULL); + set_horizontal_slider(nullptr); } - if (_vertical_slider != (PGSliderBar *)NULL) { + if (_vertical_slider != nullptr) { remove_child(_vertical_slider); - set_vertical_slider(NULL); + set_vertical_slider(nullptr); } // Create new slider bars. @@ -185,7 +185,7 @@ remanage() { bool got_horizontal = false; PN_stdfloat horizontal_width = 0.0f; - if (_horizontal_slider != (PGSliderBar *)NULL) { + if (_horizontal_slider != nullptr) { got_horizontal = true; const LVecBase4 &slider_frame = _horizontal_slider->get_frame(); horizontal_width = slider_frame[3] - slider_frame[2]; @@ -193,7 +193,7 @@ remanage() { bool got_vertical = false; PN_stdfloat vertical_width = 0.0f; - if (_vertical_slider != (PGSliderBar *)NULL) { + if (_vertical_slider != nullptr) { got_vertical = true; const LVecBase4 &slider_frame = _vertical_slider->get_frame(); vertical_width = slider_frame[1] - slider_frame[0]; @@ -235,7 +235,7 @@ remanage() { } // Now show or hide the sliders appropriately. - if (_horizontal_slider != (PGSliderBar *)NULL) { + if (_horizontal_slider != nullptr) { if (got_horizontal) { _horizontal_slider->set_overall_hidden(false); } else { @@ -244,7 +244,7 @@ remanage() { horizontal_width = 0.0f; } } - if (_vertical_slider != (PGSliderBar *)NULL) { + if (_vertical_slider != nullptr) { if (got_vertical) { _vertical_slider->set_overall_hidden(false); } else { @@ -350,10 +350,10 @@ recompute_clip() { set_clip_frame(clip); - if (_horizontal_slider != (PGSliderBar *)NULL) { + if (_horizontal_slider != nullptr) { _horizontal_slider->set_page_size((clip[1] - clip[0]) / (_virtual_frame[1] - _virtual_frame[0])); } - if (_vertical_slider != (PGSliderBar *)NULL) { + if (_vertical_slider != nullptr) { _vertical_slider->set_page_size((clip[3] - clip[2]) / (_virtual_frame[3] - _virtual_frame[2])); } } @@ -390,7 +390,7 @@ interpolate_canvas(PN_stdfloat clip_min, PN_stdfloat clip_max, PGSliderBar *slider_bar) { LightReMutexHolder holder(_lock); PN_stdfloat t = 0.0f; - if (slider_bar != (PGSliderBar *)NULL) { + if (slider_bar != nullptr) { t = slider_bar->get_ratio(); } diff --git a/panda/src/pgui/pgScrollFrame.h b/panda/src/pgui/pgScrollFrame.h index 7dfae33d1b..de01954e0d 100644 --- a/panda/src/pgui/pgScrollFrame.h +++ b/panda/src/pgui/pgScrollFrame.h @@ -34,7 +34,7 @@ */ class EXPCL_PANDA_PGUI PGScrollFrame : public PGVirtualFrame, public PGSliderBarNotify { PUBLISHED: - explicit PGScrollFrame(const string &name = ""); + explicit PGScrollFrame(const std::string &name = ""); virtual ~PGScrollFrame(); protected: @@ -94,8 +94,6 @@ private: bool _needs_recompute_clip; bool _needs_recompute_canvas; - LVecBase4 _orig_clip_frame; - bool _has_virtual_frame; LVecBase4 _virtual_frame; diff --git a/panda/src/pgui/pgSliderBar.I b/panda/src/pgui/pgSliderBar.I index 927424706f..da5b97c153 100644 --- a/panda/src/pgui/pgSliderBar.I +++ b/panda/src/pgui/pgSliderBar.I @@ -185,7 +185,7 @@ INLINE bool PGSliderBar:: is_button_down() const { LightReMutexHolder holder(_lock); return _dragging || _mouse_button_page || - (_scroll_button_held != (PGItem *)NULL); + (_scroll_button_held != nullptr); } /** @@ -243,11 +243,11 @@ get_manage_pieces() const { INLINE void PGSliderBar:: set_thumb_button(PGButton *thumb_button) { LightReMutexHolder holder(_lock); - if (_thumb_button != (PGButton *)NULL) { - _thumb_button->set_notify(NULL); + if (_thumb_button != nullptr) { + _thumb_button->set_notify(nullptr); } _thumb_button = thumb_button; - if (_thumb_button != (PGButton *)NULL) { + if (_thumb_button != nullptr) { _thumb_button->set_notify(this); } _needs_remanage = true; @@ -260,7 +260,7 @@ set_thumb_button(PGButton *thumb_button) { */ INLINE void PGSliderBar:: clear_thumb_button() { - set_thumb_button(NULL); + set_thumb_button(nullptr); } /** @@ -284,11 +284,11 @@ get_thumb_button() const { INLINE void PGSliderBar:: set_left_button(PGButton *left_button) { LightReMutexHolder holder(_lock); - if (_left_button != (PGButton *)NULL) { - _left_button->set_notify(NULL); + if (_left_button != nullptr) { + _left_button->set_notify(nullptr); } _left_button = left_button; - if (_left_button != (PGButton *)NULL) { + if (_left_button != nullptr) { _left_button->set_notify(this); } _needs_remanage = true; @@ -301,7 +301,7 @@ set_left_button(PGButton *left_button) { */ INLINE void PGSliderBar:: clear_left_button() { - set_left_button(NULL); + set_left_button(nullptr); } /** @@ -325,11 +325,11 @@ get_left_button() const { INLINE void PGSliderBar:: set_right_button(PGButton *right_button) { LightReMutexHolder holder(_lock); - if (_right_button != (PGButton *)NULL) { - _right_button->set_notify(NULL); + if (_right_button != nullptr) { + _right_button->set_notify(nullptr); } _right_button = right_button; - if (_right_button != (PGButton *)NULL) { + if (_right_button != nullptr) { _right_button->set_notify(this); } _needs_remanage = true; @@ -342,7 +342,7 @@ set_right_button(PGButton *right_button) { */ INLINE void PGSliderBar:: clear_right_button() { - set_right_button(NULL); + set_right_button(nullptr); } /** @@ -360,7 +360,7 @@ get_right_button() const { * PGSliderBars. The adjust event is the concatenation of this string * followed by get_id(). */ -INLINE string PGSliderBar:: +INLINE std::string PGSliderBar:: get_adjust_prefix() { return "adjust-"; } @@ -369,7 +369,7 @@ get_adjust_prefix() { * Returns the event name that will be thrown when the slider bar value is * adjusted by the user or programmatically. */ -INLINE string PGSliderBar:: +INLINE std::string PGSliderBar:: get_adjust_event() const { LightReMutexHolder holder(_lock); return get_adjust_prefix() + get_id(); @@ -381,7 +381,7 @@ get_adjust_event() const { */ INLINE void PGSliderBar:: internal_set_ratio(PN_stdfloat ratio) { - _ratio = max(min(ratio, (PN_stdfloat)1.0), (PN_stdfloat)0.0); + _ratio = std::max(std::min(ratio, (PN_stdfloat)1.0), (PN_stdfloat)0.0); _needs_reposition = true; adjust(); } diff --git a/panda/src/pgui/pgSliderBar.cxx b/panda/src/pgui/pgSliderBar.cxx index da09bf73f3..e085f0f91d 100644 --- a/panda/src/pgui/pgSliderBar.cxx +++ b/panda/src/pgui/pgSliderBar.cxx @@ -20,13 +20,16 @@ #include "transformState.h" #include "mouseButton.h" +using std::max; +using std::min; + TypeHandle PGSliderBar::_type_handle; /** * */ PGSliderBar:: -PGSliderBar(const string &name) +PGSliderBar(const std::string &name) : PGItem(name) { set_cull_callback(); @@ -42,7 +45,7 @@ PGSliderBar(const string &name) _needs_remanage = false; _needs_recompute = true; _needs_reposition = false; - _scroll_button_held = NULL; + _scroll_button_held = nullptr; _mouse_button_page = false; _dragging = false; _thumb_width = 0.1f; @@ -76,7 +79,7 @@ PGSliderBar(const PGSliderBar ©) : { _needs_remanage = false; _needs_recompute = true; - _scroll_button_held = NULL; + _scroll_button_held = nullptr; _mouse_button_page = false; _dragging = false; } @@ -109,7 +112,7 @@ press(const MouseWatcherParameter ¶m, bool background) { if (_range_x != 0.0f) { _mouse_button_page = true; - _scroll_button_held = NULL; + _scroll_button_held = nullptr; advance_page(); _next_advance_time = ClockObject::get_global_clock()->get_frame_time() + scroll_initial_delay; @@ -180,7 +183,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { recompute(); } - if (_scroll_button_held != (PGItem *)NULL && + if (_scroll_button_held != nullptr && _next_advance_time <= ClockObject::get_global_clock()->get_frame_time()) { advance_scroll(); } @@ -209,7 +212,7 @@ xform(const LMatrix4 &mat) { // Make sure we set the thumb to identity position first, so it won't be // accidentally flattened. - if (_thumb_button != (PGButton *)NULL) { + if (_thumb_button != nullptr) { _thumb_button->clear_transform(); } @@ -224,7 +227,7 @@ xform(const LMatrix4 &mat) { void PGSliderBar:: adjust() { LightReMutexHolder holder(_lock); - string event = get_adjust_event(); + std::string event = get_adjust_event(); play_sound(event); throw_event(event); @@ -267,17 +270,17 @@ setup_scroll_bar(bool vertical, PN_stdfloat length, PN_stdfloat width, PN_stdflo style.set_width(bevel, bevel); // Remove the button nodes created by a previous call to setup(), if any. - if (_thumb_button != (PGButton *)NULL) { + if (_thumb_button != nullptr) { remove_child(_thumb_button); - set_thumb_button(NULL); + set_thumb_button(nullptr); } - if (_left_button != (PGButton *)NULL) { + if (_left_button != nullptr) { remove_child(_left_button); - set_left_button(NULL); + set_left_button(nullptr); } - if (_right_button != (PGButton *)NULL) { + if (_right_button != nullptr) { remove_child(_right_button); - set_right_button(NULL); + set_right_button(nullptr); } PT(PGButton) thumb = new PGButton("thumb"); @@ -336,17 +339,17 @@ setup_slider(bool vertical, PN_stdfloat length, PN_stdfloat width, PN_stdfloat b set_frame_style(0, style); // Remove the button nodes created by a previous call to setup(), if any. - if (_thumb_button != (PGButton *)NULL) { + if (_thumb_button != nullptr) { remove_child(_thumb_button); - set_thumb_button(NULL); + set_thumb_button(nullptr); } - if (_left_button != (PGButton *)NULL) { + if (_left_button != nullptr) { remove_child(_left_button); - set_left_button(NULL); + set_left_button(nullptr); } - if (_right_button != (PGButton *)NULL) { + if (_right_button != nullptr) { remove_child(_right_button); - set_right_button(NULL); + set_right_button(nullptr); } PT(PGButton) thumb = new PGButton("thumb"); @@ -372,13 +375,13 @@ set_active(bool active) { PGItem::set_active(active); // This also implicitly sets the managed pieces. - if (_thumb_button != (PGButton *)NULL) { + if (_thumb_button != nullptr) { _thumb_button->set_active(active); } - if (_left_button != (PGButton *)NULL) { + if (_left_button != nullptr) { _left_button->set_active(active); } - if (_right_button != (PGButton *)NULL) { + if (_right_button != nullptr) { _right_button->set_active(active); } } @@ -410,19 +413,19 @@ remanage() { 0.0f, (frame[2] + frame[3]) / 2.0f); - if (_left_button != (PGButton *)NULL) { + if (_left_button != nullptr) { _left_button->set_frame(-width / 2.0f, width / 2.0f, -width / 2.0f, width / 2.0f); _left_button->set_transform(TransformState::make_pos(center + ((width - length) / 2.0f) * _axis)); } - if (_right_button != (PGButton *)NULL) { + if (_right_button != nullptr) { _right_button->set_frame(-width / 2.0f, width / 2.0f, -width / 2.0f, width / 2.0f); _right_button->set_transform(TransformState::make_pos(center + ((length - width) / 2.0f) * _axis)); } - if (_thumb_button != (PGButton *)NULL) { + if (_thumb_button != nullptr) { _thumb_button->set_frame(-width / 2.0f, width / 2.0f, -width / 2.0f, width / 2.0f); _thumb_button->set_transform(TransformState::make_pos(center)); @@ -469,7 +472,7 @@ recompute() { PN_stdfloat trough_width = _max_x - _min_x; - if (_thumb_button == (PGButton *)NULL) { + if (_thumb_button == nullptr) { _thumb_width = 0.0f; _range_x = 0.0f; _thumb_start.set(0.0f, 0.0f, 0.0f); @@ -510,7 +513,7 @@ recompute() { PN_stdfloat trough_width = _max_x - _min_x; - if (_thumb_button == (PGButton *)NULL) { + if (_thumb_button == nullptr) { _thumb_width = 0.0f; _range_x = 0.0f; _thumb_start.set(0.0f, 0.0f, 0.0f); @@ -603,7 +606,7 @@ item_press(PGItem *item, const MouseWatcherParameter ¶m) { ClockObject::get_global_clock()->get_frame_time() + scroll_initial_delay; } else if (item == _thumb_button) { - _scroll_button_held = NULL; + _scroll_button_held = nullptr; begin_drag(); } } @@ -616,10 +619,10 @@ void PGSliderBar:: item_release(PGItem *item, const MouseWatcherParameter &) { LightReMutexHolder holder(_lock); if (item == _scroll_button_held) { - _scroll_button_held = NULL; + _scroll_button_held = nullptr; } else if (item == _thumb_button) { - _scroll_button_held = NULL; + _scroll_button_held = nullptr; if (_dragging) { end_drag(); } @@ -651,7 +654,7 @@ reposition() { PN_stdfloat t = get_ratio(); - if (_thumb_button != (PGButton *)NULL) { + if (_thumb_button != nullptr) { LPoint3 pos = (t * _range_x) * _axis + _thumb_start; CPT(TransformState) transform = TransformState::make_pos(pos); CPT(TransformState) orig_transform = _thumb_button->get_transform(); diff --git a/panda/src/pgui/pgSliderBar.h b/panda/src/pgui/pgSliderBar.h index c08a98e172..4049f9aa74 100644 --- a/panda/src/pgui/pgSliderBar.h +++ b/panda/src/pgui/pgSliderBar.h @@ -30,7 +30,7 @@ */ class EXPCL_PANDA_PGUI PGSliderBar : public PGItem, public PGButtonNotify { PUBLISHED: - explicit PGSliderBar(const string &name = ""); + explicit PGSliderBar(const std::string &name = ""); virtual ~PGSliderBar(); protected: @@ -93,8 +93,8 @@ PUBLISHED: INLINE void clear_right_button(); INLINE PGButton *get_right_button() const; - INLINE static string get_adjust_prefix(); - INLINE string get_adjust_event() const; + INLINE static std::string get_adjust_prefix(); + INLINE std::string get_adjust_event() const; virtual void set_active(bool active); diff --git a/panda/src/pgui/pgTop.I b/panda/src/pgui/pgTop.I index 76bee2d409..775e8cf827 100644 --- a/panda/src/pgui/pgTop.I +++ b/panda/src/pgui/pgTop.I @@ -74,6 +74,6 @@ get_start_sort() const { */ INLINE void PGTop:: add_region(MouseWatcherRegion *region) { - nassertv(_watcher_group != (PGMouseWatcherGroup *)NULL); + nassertv(_watcher_group != nullptr); _watcher_group->add_region(region); } diff --git a/panda/src/pgui/pgTop.cxx b/panda/src/pgui/pgTop.cxx index b65aaa81ac..3c0948ebda 100644 --- a/panda/src/pgui/pgTop.cxx +++ b/panda/src/pgui/pgTop.cxx @@ -24,7 +24,7 @@ TypeHandle PGTop::_type_handle; * */ PGTop:: -PGTop(const string &name) : +PGTop(const std::string &name) : PandaNode(name) { set_cull_callback(); @@ -47,7 +47,7 @@ PGTop(const string &name) : */ PGTop:: ~PGTop() { - set_mouse_watcher((MouseWatcher *)NULL); + set_mouse_watcher(nullptr); } /** @@ -83,7 +83,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { // We create a new MouseWatcherGroup for the purposes of collecting a new // set of regions visible onscreen. PT(PGMouseWatcherGroup) old_watcher_group; - if (_watcher_group != (PGMouseWatcherGroup *)NULL) { + if (_watcher_group != nullptr) { _watcher_group->clear_top(this); old_watcher_group = _watcher_group; _watcher_group = new PGMouseWatcherGroup(this); @@ -102,8 +102,8 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { // shouldn't do this until the frame that we're about to render has been // presented; otherwise, we may make regions active before they are actually // visible. But no one has complained about this so far. - if (_watcher_group != (PGMouseWatcherGroup *)NULL) { - nassertr(_watcher != (MouseWatcher *)NULL, false); + if (_watcher_group != nullptr) { + nassertr(_watcher != nullptr, false); _watcher->replace_group(old_watcher_group, _watcher_group); } @@ -130,17 +130,17 @@ is_renderable() const { */ void PGTop:: set_mouse_watcher(MouseWatcher *watcher) { - if (_watcher_group != (PGMouseWatcherGroup *)NULL) { + if (_watcher_group != nullptr) { _watcher_group->clear_top(this); } - if (_watcher != (MouseWatcher *)NULL) { + if (_watcher != nullptr) { _watcher->remove_group(_watcher_group); } _watcher = watcher; - _watcher_group = (PGMouseWatcherGroup *)NULL; + _watcher_group = nullptr; - if (_watcher != (MouseWatcher *)NULL) { + if (_watcher != nullptr) { _watcher_group = new PGMouseWatcherGroup(this); _watcher->add_group(_watcher_group); } diff --git a/panda/src/pgui/pgTop.h b/panda/src/pgui/pgTop.h index 45376e99f5..1d5e739c8e 100644 --- a/panda/src/pgui/pgTop.h +++ b/panda/src/pgui/pgTop.h @@ -37,7 +37,7 @@ class PGMouseWatcherGroup; */ class EXPCL_PANDA_PGUI PGTop : public PandaNode { PUBLISHED: - explicit PGTop(const string &name); + explicit PGTop(const std::string &name); virtual ~PGTop(); protected: diff --git a/panda/src/pgui/pgVirtualFrame.cxx b/panda/src/pgui/pgVirtualFrame.cxx index b6a6d195b0..01013fd87f 100644 --- a/panda/src/pgui/pgVirtualFrame.cxx +++ b/panda/src/pgui/pgVirtualFrame.cxx @@ -21,7 +21,7 @@ TypeHandle PGVirtualFrame::_type_handle; * */ PGVirtualFrame:: -PGVirtualFrame(const string &name) : PGItem(name) +PGVirtualFrame(const std::string &name) : PGItem(name) { _has_clip_frame = false; _clip_frame.set(0.0f, 0.0f, 0.0f, 0.0f); diff --git a/panda/src/pgui/pgVirtualFrame.h b/panda/src/pgui/pgVirtualFrame.h index d6505faaaa..c8aff4fca6 100644 --- a/panda/src/pgui/pgVirtualFrame.h +++ b/panda/src/pgui/pgVirtualFrame.h @@ -42,7 +42,7 @@ class TransformState; */ class EXPCL_PANDA_PGUI PGVirtualFrame : public PGItem { PUBLISHED: - explicit PGVirtualFrame(const string &name = ""); + explicit PGVirtualFrame(const std::string &name = ""); virtual ~PGVirtualFrame(); protected: diff --git a/panda/src/pgui/pgWaitBar.cxx b/panda/src/pgui/pgWaitBar.cxx index 2f6f50a557..8348b692dc 100644 --- a/panda/src/pgui/pgWaitBar.cxx +++ b/panda/src/pgui/pgWaitBar.cxx @@ -22,7 +22,7 @@ TypeHandle PGWaitBar::_type_handle; * */ PGWaitBar:: -PGWaitBar(const string &name) : PGItem(name) +PGWaitBar(const std::string &name) : PGItem(name) { set_cull_callback(); @@ -147,7 +147,7 @@ update() { // And scale the bar according to our value. PN_stdfloat frac = _value / _range; - frac = max(min(frac, (PN_stdfloat)1.0), (PN_stdfloat)0.0); + frac = std::max(std::min(frac, (PN_stdfloat)1.0), (PN_stdfloat)0.0); bar_frame[1] = bar_frame[0] + frac * (bar_frame[1] - bar_frame[0]); _bar = _bar_style.generate_into(root, bar_frame, 1); diff --git a/panda/src/pgui/pgWaitBar.h b/panda/src/pgui/pgWaitBar.h index 92381870dd..9f8415d28c 100644 --- a/panda/src/pgui/pgWaitBar.h +++ b/panda/src/pgui/pgWaitBar.h @@ -25,7 +25,7 @@ */ class EXPCL_PANDA_PGUI PGWaitBar : public PGItem { PUBLISHED: - explicit PGWaitBar(const string &name = ""); + explicit PGWaitBar(const std::string &name = ""); virtual ~PGWaitBar(); protected: diff --git a/panda/src/pgui/test_pgentry.cxx b/panda/src/pgui/test_pgentry.cxx index fb7440c6b4..f00369a603 100644 --- a/panda/src/pgui/test_pgentry.cxx +++ b/panda/src/pgui/test_pgentry.cxx @@ -22,7 +22,7 @@ main(int argc, char *argv[]) { framework.set_window_title("Panda Viewer"); WindowFramework *window = framework.open_window(); - if (window != (WindowFramework *)NULL) { + if (window != nullptr) { window->enable_keyboard(); NodePath aspect2d = window->get_aspect_2d(); diff --git a/panda/src/physics/actorNode.cxx b/panda/src/physics/actorNode.cxx index e77e8e5ca5..ac9a03a69d 100644 --- a/panda/src/physics/actorNode.cxx +++ b/panda/src/physics/actorNode.cxx @@ -23,7 +23,7 @@ TypeHandle ActorNode::_type_handle; * Constructor */ ActorNode:: -ActorNode(const string &name) : +ActorNode(const std::string &name) : PhysicalNode(name) { _contact_vector = LVector3::zero(); add_physical(new Physical(1, true)); @@ -120,7 +120,7 @@ transform_changed() { * Write a string representation of this instance to . */ void ActorNode:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"ActorNode:\n"; out.width(indent+2); out<<""; out<<"_ok_to_callback "<<_ok_to_callback<<"\n"; diff --git a/panda/src/physics/actorNode.h b/panda/src/physics/actorNode.h index aacdec669e..719b6b16f9 100644 --- a/panda/src/physics/actorNode.h +++ b/panda/src/physics/actorNode.h @@ -23,9 +23,9 @@ * will be reflected as transforms. This relation goes both ways; changes in * the transform will update the object's position (shoves). */ -class EXPCL_PANDAPHYSICS ActorNode : public PhysicalNode { +class EXPCL_PANDA_PHYSICS ActorNode : public PhysicalNode { PUBLISHED: - explicit ActorNode(const string &name = ""); + explicit ActorNode(const std::string &name = ""); ActorNode(const ActorNode ©); virtual ~ActorNode(); @@ -39,7 +39,7 @@ PUBLISHED: void update_transform(); void set_transform_limit(PN_stdfloat limit) { _transform_limit = limit; }; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void write(std::ostream &out, int indent=0) const; private: PhysicsObject *_mass_center; diff --git a/panda/src/physics/angularEulerIntegrator.cxx b/panda/src/physics/angularEulerIntegrator.cxx index 9900223d4c..642c2c6b8b 100644 --- a/panda/src/physics/angularEulerIntegrator.cxx +++ b/panda/src/physics/angularEulerIntegrator.cxx @@ -51,7 +51,7 @@ child_integrate(Physical *physical, PhysicsObject *current_object = *current_object_iter; // bail out if this object doesn't exist or doesn't want to be processed. - if (current_object == (PhysicsObject *) NULL) { + if (current_object == nullptr) { continue; } @@ -142,7 +142,7 @@ child_integrate(Physical *physical, * Write a string representation of this instance to . */ void AngularEulerIntegrator:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"AngularEulerIntegrator (id "<. */ void AngularEulerIntegrator:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"AngularEulerIntegrator:\n"; AngularIntegrator::write(out, indent+2); diff --git a/panda/src/physics/angularEulerIntegrator.h b/panda/src/physics/angularEulerIntegrator.h index 5e342b10f9..1710d0841f 100644 --- a/panda/src/physics/angularEulerIntegrator.h +++ b/panda/src/physics/angularEulerIntegrator.h @@ -20,13 +20,13 @@ * Performs Euler integration on a vector of physically modelable objects * given a quantum dt. */ -class EXPCL_PANDAPHYSICS AngularEulerIntegrator : public AngularIntegrator { +class EXPCL_PANDA_PHYSICS AngularEulerIntegrator : public AngularIntegrator { PUBLISHED: AngularEulerIntegrator(); virtual ~AngularEulerIntegrator(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: virtual void child_integrate(Physical *physical, diff --git a/panda/src/physics/angularForce.cxx b/panda/src/physics/angularForce.cxx index 722a4611ab..3be7eafff5 100644 --- a/panda/src/physics/angularForce.cxx +++ b/panda/src/physics/angularForce.cxx @@ -59,7 +59,7 @@ is_linear() const { * Write a string representation of this instance to . */ void AngularForce:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"AngularForce (id "<. */ void AngularForce:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"AngularForce (id "<. */ void AngularIntegrator:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"AngularIntegrator"; #endif //] NDEBUG @@ -59,7 +59,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void AngularIntegrator:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"AngularIntegrator:\n"; out.width(indent+2); out<<""; out<<"_max_angular_dt "<<_max_angular_dt<<" (class const)\n"; diff --git a/panda/src/physics/angularIntegrator.h b/panda/src/physics/angularIntegrator.h index 4ee8d41009..43f65c9581 100644 --- a/panda/src/physics/angularIntegrator.h +++ b/panda/src/physics/angularIntegrator.h @@ -22,7 +22,7 @@ * Pure virtual base class for physical modeling. Takes physically modelable * objects and applies forces to them. */ -class EXPCL_PANDAPHYSICS AngularIntegrator : public BaseIntegrator { +class EXPCL_PANDA_PHYSICS AngularIntegrator : public BaseIntegrator { PUBLISHED: virtual ~AngularIntegrator(); public: @@ -31,8 +31,8 @@ public: PN_stdfloat dt); PUBLISHED: - virtual void output(ostream &out) const; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; protected: AngularIntegrator(); diff --git a/panda/src/physics/angularVectorForce.cxx b/panda/src/physics/angularVectorForce.cxx index d9ab88b054..f917eaaba7 100644 --- a/panda/src/physics/angularVectorForce.cxx +++ b/panda/src/physics/angularVectorForce.cxx @@ -68,7 +68,7 @@ get_child_quat(const PhysicsObject *) { * Write a string representation of this instance to . */ void AngularVectorForce:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"AngularVectorForce"; #endif //] NDEBUG @@ -78,7 +78,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void AngularVectorForce:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"AngularVectorForce:\n"; out.width(indent+2); out<<""; out<<"_fvec "<<_fvec<<"\n"; diff --git a/panda/src/physics/angularVectorForce.h b/panda/src/physics/angularVectorForce.h index aab32eaaae..2c45f5d43c 100644 --- a/panda/src/physics/angularVectorForce.h +++ b/panda/src/physics/angularVectorForce.h @@ -20,7 +20,7 @@ * a simple directed torque force, the angular equivalent of simple vector * force. */ -class EXPCL_PANDAPHYSICS AngularVectorForce : public AngularForce { +class EXPCL_PANDA_PHYSICS AngularVectorForce : public AngularForce { PUBLISHED: explicit AngularVectorForce(const LRotation& quat); explicit AngularVectorForce(PN_stdfloat h, PN_stdfloat p, PN_stdfloat r); @@ -31,8 +31,8 @@ PUBLISHED: INLINE void set_hpr(PN_stdfloat h, PN_stdfloat p, PN_stdfloat r); INLINE LRotation get_local_quat() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: LRotation _fvec; diff --git a/panda/src/physics/baseForce.cxx b/panda/src/physics/baseForce.cxx index 7a7ba6d71b..18bc3ef5e1 100644 --- a/panda/src/physics/baseForce.cxx +++ b/panda/src/physics/baseForce.cxx @@ -21,7 +21,7 @@ TypeHandle BaseForce::_type_handle; */ BaseForce:: BaseForce(bool active) : - _force_node(NULL), + _force_node(nullptr), _active(active) { } @@ -34,7 +34,7 @@ BaseForce(const BaseForce ©) : TypedReferenceCount(copy) { _active = copy._active; - _force_node = (ForceNode *) NULL; + _force_node = nullptr; } /** @@ -48,7 +48,7 @@ BaseForce:: * Write a string representation of this instance to . */ void BaseForce:: -output(ostream &out) const { +output(std::ostream &out) const { out << "BaseForce (id " << this << ")"; } @@ -56,7 +56,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void BaseForce:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "BaseForce (id " << this << "):\n"; diff --git a/panda/src/physics/baseForce.h b/panda/src/physics/baseForce.h index 90d510013b..ffe8f58295 100644 --- a/panda/src/physics/baseForce.h +++ b/panda/src/physics/baseForce.h @@ -26,7 +26,7 @@ class ForceNode; /** * pure virtual base class for all forces that could POSSIBLY exist. */ -class EXPCL_PANDAPHYSICS BaseForce : public TypedReferenceCount { +class EXPCL_PANDA_PHYSICS BaseForce : public TypedReferenceCount { PUBLISHED: virtual ~BaseForce(); @@ -37,8 +37,8 @@ PUBLISHED: INLINE ForceNode *get_force_node() const; INLINE NodePath get_force_node_path() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level=0) const; protected: BaseForce(bool active = true); diff --git a/panda/src/physics/baseIntegrator.cxx b/panda/src/physics/baseIntegrator.cxx index b21fd38612..33bc0b72cb 100644 --- a/panda/src/physics/baseIntegrator.cxx +++ b/panda/src/physics/baseIntegrator.cxx @@ -16,6 +16,8 @@ #include "forceNode.h" #include "nodePath.h" +using std::ostream; + /** * constructor */ @@ -40,16 +42,13 @@ precompute_linear_matrices(Physical *physical, const LinearForceVector &forces) { nassertv(physical); // make sure the physical's in the scene graph, somewhere. - PhysicalNode *physical_node = physical->get_physical_node(); - nassertv(physical_node); + nassertv(physical->get_physical_node() != nullptr); // by global forces, we mean forces not contained in the physical - int global_force_vec_size = forces.size(); + size_t global_force_vec_size = forces.size(); // by local forces, we mean members of the physical's force set. - int local_force_vec_size = physical->get_linear_forces().size(); - - ForceNode *force_node; + size_t local_force_vec_size = physical->get_linear_forces().size(); // prepare the vector _precomputed_linear_matrices.clear(); @@ -63,8 +62,7 @@ precompute_linear_matrices(Physical *physical, LinearForceVector::const_iterator fi; for (fi = forces.begin(); fi != forces.end(); ++fi) { // LinearForce *cur_force = *fi; - force_node = (*fi)->get_force_node(); - nassertv(force_node != (ForceNode *) NULL); + nassertv((*fi)->get_force_node() != nullptr); NodePath force_np = (*fi)->get_force_node_path(); _precomputed_linear_matrices.push_back( @@ -74,8 +72,7 @@ precompute_linear_matrices(Physical *physical, // tally the local xforms const LinearForceVector &force_vector = physical->get_linear_forces(); for (fi = force_vector.begin(); fi != force_vector.end(); ++fi) { - force_node = (*fi)->get_force_node(); - nassertv(force_node != (ForceNode *) NULL); + nassertv((*fi)->get_force_node() != nullptr); NodePath force_np = (*fi)->get_force_node_path(); _precomputed_linear_matrices.push_back( @@ -93,16 +90,13 @@ precompute_angular_matrices(Physical *physical, const AngularForceVector &forces) { nassertv(physical); // make sure the physical's in the scene graph, somewhere. - PhysicalNode *physical_node = physical->get_physical_node(); - nassertv(physical_node != NULL); + nassertv(physical->get_physical_node() != nullptr); // by global forces, we mean forces not contained in the physical - int global_force_vec_size = forces.size(); + size_t global_force_vec_size = forces.size(); // by local forces, we mean members of the physical's force set. - int local_force_vec_size = physical->get_angular_forces().size(); - - ForceNode *force_node; + size_t local_force_vec_size = physical->get_angular_forces().size(); // prepare the vector _precomputed_angular_matrices.clear(); @@ -115,8 +109,7 @@ precompute_angular_matrices(Physical *physical, // tally the global xforms AngularForceVector::const_iterator fi; for (fi = forces.begin(); fi != forces.end(); ++fi) { - force_node = (*fi)->get_force_node(); - nassertv(force_node != (ForceNode *) NULL); + nassertv((*fi)->get_force_node() != nullptr); NodePath force_np = (*fi)->get_force_node_path(); _precomputed_angular_matrices.push_back( @@ -126,8 +119,7 @@ precompute_angular_matrices(Physical *physical, // tally the local xforms const AngularForceVector &force_vector = physical->get_angular_forces(); for (fi = force_vector.begin(); fi != force_vector.end(); ++fi) { - force_node = (*fi)->get_force_node(); - nassertv(force_node != (ForceNode *) NULL); + nassertv((*fi)->get_force_node() != nullptr); NodePath force_np = (*fi)->get_force_node_path(); _precomputed_angular_matrices.push_back( @@ -149,7 +141,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void BaseIntegrator:: -write_precomputed_linear_matrices(ostream &out, unsigned int indent) const { +write_precomputed_linear_matrices(ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""<<"_precomputed_linear_matrices\n"; @@ -165,7 +157,7 @@ write_precomputed_linear_matrices(ostream &out, unsigned int indent) const { * Write a string representation of this instance to . */ void BaseIntegrator:: -write_precomputed_angular_matrices(ostream &out, unsigned int indent) const { +write_precomputed_angular_matrices(ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""<<"_precomputed_angular_matrices\n"; @@ -181,7 +173,7 @@ write_precomputed_angular_matrices(ostream &out, unsigned int indent) const { * Write a string representation of this instance to . */ void BaseIntegrator:: -write(ostream &out, unsigned int indent) const { +write(ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"BaseIntegrator:\n"; write_precomputed_linear_matrices(out, indent+2); diff --git a/panda/src/physics/baseIntegrator.h b/panda/src/physics/baseIntegrator.h index aaedce91cd..5921b6e019 100644 --- a/panda/src/physics/baseIntegrator.h +++ b/panda/src/physics/baseIntegrator.h @@ -31,7 +31,7 @@ class Physical; * pure virtual integrator class that holds cached matrix information that * really should be common to any possible child implementation. */ -class EXPCL_PANDAPHYSICS BaseIntegrator : public ReferenceCount { +class EXPCL_PANDA_PHYSICS BaseIntegrator : public ReferenceCount { public: typedef epvector MatrixVector; typedef pvector LinearForceVector; @@ -40,12 +40,12 @@ public: virtual ~BaseIntegrator(); PUBLISHED: - virtual void output(ostream &out) const; - virtual void write_precomputed_linear_matrices(ostream &out, - unsigned int indent=0) const; - virtual void write_precomputed_angular_matrices(ostream &out, - unsigned int indent=0) const; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write_precomputed_linear_matrices(std::ostream &out, + int indent=0) const; + virtual void write_precomputed_angular_matrices(std::ostream &out, + int indent=0) const; + virtual void write(std::ostream &out, int indent=0) const; protected: BaseIntegrator(); diff --git a/panda/src/physics/config_physics.cxx b/panda/src/physics/config_physics.cxx index 5ce5c905f0..b4ad867f66 100644 --- a/panda/src/physics/config_physics.cxx +++ b/panda/src/physics/config_physics.cxx @@ -26,8 +26,8 @@ #include "dconfig.h" -#if !defined(CPPPARSER) && !defined(BUILDING_PANDAPHYSICS) - #error Buildsystem error: BUILDING_PANDAPHYSICS not defined +#if !defined(CPPPARSER) && !defined(BUILDING_PANDA_PHYSICS) + #error Buildsystem error: BUILDING_PANDA_PHYSICS not defined #endif ConfigureDef(config_physics); diff --git a/panda/src/physics/config_physics.h b/panda/src/physics/config_physics.h index 5b7249d159..1c1b768e83 100644 --- a/panda/src/physics/config_physics.h +++ b/panda/src/physics/config_physics.h @@ -18,10 +18,10 @@ #include "notifyCategoryProxy.h" #include "dconfig.h" -ConfigureDecl(config_physics, EXPCL_PANDAPHYSICS, EXPTP_PANDAPHYSICS); -NotifyCategoryDecl(physics, EXPCL_PANDAPHYSICS, EXPTP_PANDAPHYSICS); +ConfigureDecl(config_physics, EXPCL_PANDA_PHYSICS, EXPTP_PANDA_PHYSICS); +NotifyCategoryDecl(physics, EXPCL_PANDA_PHYSICS, EXPTP_PANDA_PHYSICS); -extern EXPCL_PANDAPHYSICS void init_libphysics(); +extern EXPCL_PANDA_PHYSICS void init_libphysics(); // These macros get stripped out in a non-debug build (like asserts). Use them // like cout but with paranthesis aroud the cout input. e.g. foo_debug("The @@ -32,22 +32,22 @@ extern EXPCL_PANDAPHYSICS void init_libphysics(); #define physics_spam(msg) \ if (physics_cat.is_spam()) { \ - physics_cat->spam() << msg << endl; \ + physics_cat->spam() << msg << std::endl; \ } else {} #define physics_debug(msg) \ if (physics_cat.is_debug()) { \ - physics_cat->debug() << msg << endl; \ + physics_cat->debug() << msg << std::endl; \ } else {} #define physics_info(msg) \ - physics_cat->info() << msg << endl + physics_cat->info() << msg << std::endl #define physics_warning(msg) \ - physics_cat->warning() << msg << endl + physics_cat->warning() << msg << std::endl #define physics_error(msg) \ - physics_cat->error() << msg << endl + physics_cat->error() << msg << std::endl #else //][ // Release build: #undef PHYSICS_DEBUG @@ -60,6 +60,6 @@ extern EXPCL_PANDAPHYSICS void init_libphysics(); #endif //] #define audio_error(msg) \ - audio_cat->error() << msg << endl + audio_cat->error() << msg << std::endl #endif // CONFIG_PHYSICS_H diff --git a/panda/src/physics/forceNode.I b/panda/src/physics/forceNode.I index 8fd6845727..f1c4db3d60 100644 --- a/panda/src/physics/forceNode.I +++ b/panda/src/physics/forceNode.I @@ -24,7 +24,7 @@ clear() { */ INLINE BaseForce *ForceNode:: get_force(size_t index) const { - nassertr(index < _forces.size(), (BaseForce *) NULL); + nassertr(index < _forces.size(), nullptr); return _forces[index]; } diff --git a/panda/src/physics/forceNode.cxx b/panda/src/physics/forceNode.cxx index 0e186a98b3..c8f744f777 100644 --- a/panda/src/physics/forceNode.cxx +++ b/panda/src/physics/forceNode.cxx @@ -20,7 +20,7 @@ TypeHandle ForceNode::_type_handle; * default constructor */ ForceNode:: -ForceNode(const string &name) : +ForceNode(const std::string &name) : PandaNode(name) { } @@ -114,7 +114,7 @@ remove_force(size_t index) { pvector< PT(BaseForce) >::iterator remove; remove = _forces.begin() + index; - (*remove)->_force_node = (ForceNode *) NULL; + (*remove)->_force_node = nullptr; (*remove)->_force_node_path = NodePath(); _forces.erase(remove); @@ -124,7 +124,7 @@ remove_force(size_t index) { * Write a string representation of this instance to . */ void ForceNode:: -output(ostream &out) const { +output(std::ostream &out) const { PandaNode::output(out); out<<" ("<<_forces.size()<<" forces)"; } @@ -133,7 +133,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void ForceNode:: -write_forces(ostream &out, unsigned int indent) const { +write_forces(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""<<"_forces ("<<_forces.size()<<" forces)"<<"\n"; for (ForceVector::const_iterator i=_forces.begin(); @@ -149,7 +149,7 @@ write_forces(ostream &out, unsigned int indent) const { * Write a string representation of this instance to . */ void ForceNode:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"ForceNode (id "<. */ void LinearControlForce:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"LinearControlForce"; #endif //] NDEBUG @@ -81,7 +81,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void LinearControlForce:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"LinearControlForce:\n"; out.width(indent+2); out<<""; out<<"_fvec "<<_fvec<<"\n"; diff --git a/panda/src/physics/linearControlForce.h b/panda/src/physics/linearControlForce.h index d39a9c2581..30c255b769 100644 --- a/panda/src/physics/linearControlForce.h +++ b/panda/src/physics/linearControlForce.h @@ -22,7 +22,7 @@ * not make sense for a physics simulation, but it's very handy for a game. * I.e. this is the force applied by user on the selected object. */ -class EXPCL_PANDAPHYSICS LinearControlForce : public LinearForce { +class EXPCL_PANDA_PHYSICS LinearControlForce : public LinearForce { PUBLISHED: explicit LinearControlForce(const PhysicsObject *po = 0, PN_stdfloat a = 1.0f, bool mass = false); @@ -38,8 +38,8 @@ PUBLISHED: INLINE LVector3 get_local_vector() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: CPT(PhysicsObject) _physics_object; diff --git a/panda/src/physics/linearCylinderVortexForce.cxx b/panda/src/physics/linearCylinderVortexForce.cxx index 9976d6b1eb..c1abcc6c4d 100644 --- a/panda/src/physics/linearCylinderVortexForce.cxx +++ b/panda/src/physics/linearCylinderVortexForce.cxx @@ -117,7 +117,7 @@ get_child_vector(const PhysicsObject *po) { * Write a string representation of this instance to . */ void LinearCylinderVortexForce:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"LinearCylinderVortexForce"; #endif //] NDEBUG @@ -127,7 +127,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void LinearCylinderVortexForce:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"LinearCylinderVortexForce:\n"; LinearForce::write(out, indent+2); diff --git a/panda/src/physics/linearCylinderVortexForce.h b/panda/src/physics/linearCylinderVortexForce.h index 5698aa9d8d..41c7a554f1 100644 --- a/panda/src/physics/linearCylinderVortexForce.h +++ b/panda/src/physics/linearCylinderVortexForce.h @@ -23,7 +23,7 @@ * warned- this will suck anything that it can reach directly into orbit and * will NOT let go. */ -class EXPCL_PANDAPHYSICS LinearCylinderVortexForce : public LinearForce { +class EXPCL_PANDA_PHYSICS LinearCylinderVortexForce : public LinearForce { PUBLISHED: explicit LinearCylinderVortexForce(PN_stdfloat radius = 1.0f, PN_stdfloat length = 0.0f, @@ -42,8 +42,8 @@ PUBLISHED: INLINE void set_length(PN_stdfloat length); INLINE PN_stdfloat get_length() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: PN_stdfloat _radius; diff --git a/panda/src/physics/linearDistanceForce.cxx b/panda/src/physics/linearDistanceForce.cxx index 65922d0a2a..3a7349f094 100644 --- a/panda/src/physics/linearDistanceForce.cxx +++ b/panda/src/physics/linearDistanceForce.cxx @@ -47,7 +47,7 @@ LinearDistanceForce:: * Write a string representation of this instance to . */ void LinearDistanceForce:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"LinearDistanceForce"; #endif //] NDEBUG @@ -57,7 +57,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void LinearDistanceForce:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"LinearDistanceForce:\n"; out.width(indent+2); out<<""; out<<"_force_center "<<_force_center<<"\n"; diff --git a/panda/src/physics/linearDistanceForce.h b/panda/src/physics/linearDistanceForce.h index 4afa6f2d11..fa245db104 100644 --- a/panda/src/physics/linearDistanceForce.h +++ b/panda/src/physics/linearDistanceForce.h @@ -21,7 +21,7 @@ class BamReader; /** * Pure virtual class for sinks and sources */ -class EXPCL_PANDAPHYSICS LinearDistanceForce : public LinearForce { +class EXPCL_PANDA_PHYSICS LinearDistanceForce : public LinearForce { PUBLISHED: enum FalloffType { FT_ONE_OVER_R, @@ -39,8 +39,8 @@ PUBLISHED: INLINE PN_stdfloat get_scalar_term() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: LPoint3 _force_center; diff --git a/panda/src/physics/linearEulerIntegrator.cxx b/panda/src/physics/linearEulerIntegrator.cxx index f208eda299..f9801e3405 100644 --- a/panda/src/physics/linearEulerIntegrator.cxx +++ b/panda/src/physics/linearEulerIntegrator.cxx @@ -72,7 +72,7 @@ child_integrate(Physical *physical, PhysicsObject *current_object = *current_object_iter; // bail out if this object doesn't exist or doesn't want to be processed. - if (current_object == (PhysicsObject *) NULL) { + if (current_object == nullptr) { continue; } @@ -189,7 +189,7 @@ child_integrate(Physical *physical, * Write a string representation of this instance to . */ void LinearEulerIntegrator:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"LinearEulerIntegrator"; #endif //] NDEBUG @@ -199,7 +199,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void LinearEulerIntegrator:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""<<"LinearEulerIntegrator:\n"; diff --git a/panda/src/physics/linearEulerIntegrator.h b/panda/src/physics/linearEulerIntegrator.h index c7b6d3ff47..09430d863d 100644 --- a/panda/src/physics/linearEulerIntegrator.h +++ b/panda/src/physics/linearEulerIntegrator.h @@ -20,13 +20,13 @@ * Performs Euler integration on a vector of physically modelable objects * given a quantum dt. */ -class EXPCL_PANDAPHYSICS LinearEulerIntegrator : public LinearIntegrator { +class EXPCL_PANDA_PHYSICS LinearEulerIntegrator : public LinearIntegrator { PUBLISHED: LinearEulerIntegrator(); virtual ~LinearEulerIntegrator(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: virtual void child_integrate(Physical *physical, diff --git a/panda/src/physics/linearForce.cxx b/panda/src/physics/linearForce.cxx index dde98eba84..cef7f1e543 100644 --- a/panda/src/physics/linearForce.cxx +++ b/panda/src/physics/linearForce.cxx @@ -82,7 +82,7 @@ is_linear() const { * Write a string representation of this instance to . */ void LinearForce:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"LinearForce (id "<. */ void LinearForce:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"LinearForce (id "<. */ void LinearFrictionForce:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"LinearFrictionForce"; #endif //] NDEBUG @@ -83,7 +83,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void LinearFrictionForce:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"LinearFrictionForce:\n"; out.width(indent+2); out<<""; out<<"_coef "<<_coef<<":\n"; diff --git a/panda/src/physics/linearFrictionForce.h b/panda/src/physics/linearFrictionForce.h index 8ba4d19534..cc098c4cce 100644 --- a/panda/src/physics/linearFrictionForce.h +++ b/panda/src/physics/linearFrictionForce.h @@ -19,7 +19,7 @@ /** * Friction-based drag force */ -class EXPCL_PANDAPHYSICS LinearFrictionForce : public LinearForce { +class EXPCL_PANDA_PHYSICS LinearFrictionForce : public LinearForce { PUBLISHED: explicit LinearFrictionForce(PN_stdfloat coef = 1.0f, PN_stdfloat a = 1.0f, bool m = false); LinearFrictionForce(const LinearFrictionForce ©); @@ -28,8 +28,8 @@ PUBLISHED: INLINE void set_coef(PN_stdfloat coef); INLINE PN_stdfloat get_coef() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: PN_stdfloat _coef; diff --git a/panda/src/physics/linearIntegrator.cxx b/panda/src/physics/linearIntegrator.cxx index c58f9a4904..d8841cee9c 100644 --- a/panda/src/physics/linearIntegrator.cxx +++ b/panda/src/physics/linearIntegrator.cxx @@ -53,7 +53,7 @@ integrate(Physical *physical, LinearForceVector &forces, PhysicsObject *current_object = *current_object_iter; // bail out if this object doesn't exist or doesn't want to be processed. - if (current_object == (PhysicsObject *) NULL) { + if (current_object == nullptr) { continue; } @@ -68,7 +68,7 @@ integrate(Physical *physical, LinearForceVector &forces, * Write a string representation of this instance to . */ void LinearIntegrator:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"LinearIntegrator"; #endif //] NDEBUG @@ -78,7 +78,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void LinearIntegrator:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"LinearIntegrator:\n"; out.width(indent+2); out<<""; out<<"_max_linear_dt "<<_max_linear_dt<<" (class static)\n"; diff --git a/panda/src/physics/linearIntegrator.h b/panda/src/physics/linearIntegrator.h index d5e6a1375d..4737ae7014 100644 --- a/panda/src/physics/linearIntegrator.h +++ b/panda/src/physics/linearIntegrator.h @@ -23,7 +23,7 @@ * Pure virtual base class for physical modeling. Takes physically modelable * objects and applies forces to them. */ -class EXPCL_PANDAPHYSICS LinearIntegrator : public BaseIntegrator { +class EXPCL_PANDA_PHYSICS LinearIntegrator : public BaseIntegrator { PUBLISHED: virtual ~LinearIntegrator(); public: @@ -32,8 +32,8 @@ public: PN_stdfloat dt); PUBLISHED: - virtual void output(ostream &out) const; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; protected: LinearIntegrator(); diff --git a/panda/src/physics/linearJitterForce.cxx b/panda/src/physics/linearJitterForce.cxx index d74a14fac6..397092a807 100644 --- a/panda/src/physics/linearJitterForce.cxx +++ b/panda/src/physics/linearJitterForce.cxx @@ -58,7 +58,7 @@ get_child_vector(const PhysicsObject *) { * Write a string representation of this instance to . */ void LinearJitterForce:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"LinearJitterForce"; #endif //] NDEBUG @@ -68,7 +68,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void LinearJitterForce:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"LinearJitterForce:\n"; LinearRandomForce::write(out, indent+2); diff --git a/panda/src/physics/linearJitterForce.h b/panda/src/physics/linearJitterForce.h index 076d7d12ca..32433a3f66 100644 --- a/panda/src/physics/linearJitterForce.h +++ b/panda/src/physics/linearJitterForce.h @@ -20,14 +20,14 @@ * Completely random noise force vector. Not repeatable, reliable, or * predictable. */ -class EXPCL_PANDAPHYSICS LinearJitterForce : public LinearRandomForce { +class EXPCL_PANDA_PHYSICS LinearJitterForce : public LinearRandomForce { PUBLISHED: explicit LinearJitterForce(PN_stdfloat a = 1.0f, bool m = false); LinearJitterForce(const LinearJitterForce ©); virtual ~LinearJitterForce(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: virtual LVector3 get_child_vector(const PhysicsObject *po); diff --git a/panda/src/physics/linearNoiseForce.cxx b/panda/src/physics/linearNoiseForce.cxx index b7d9109f8f..9873494480 100644 --- a/panda/src/physics/linearNoiseForce.cxx +++ b/panda/src/physics/linearNoiseForce.cxx @@ -136,7 +136,7 @@ get_child_vector(const PhysicsObject *po) { * Write a string representation of this instance to . */ void LinearNoiseForce:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<""<<"LinearNoiseForce"; #endif //] NDEBUG @@ -146,7 +146,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void LinearNoiseForce:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""<<"LinearNoiseForce:"; diff --git a/panda/src/physics/linearNoiseForce.h b/panda/src/physics/linearNoiseForce.h index b87fec2256..cfe63183bc 100644 --- a/panda/src/physics/linearNoiseForce.h +++ b/panda/src/physics/linearNoiseForce.h @@ -21,14 +21,14 @@ /** * Repeating noise force vector. */ -class EXPCL_PANDAPHYSICS LinearNoiseForce : public LinearRandomForce { +class EXPCL_PANDA_PHYSICS LinearNoiseForce : public LinearRandomForce { PUBLISHED: explicit LinearNoiseForce(PN_stdfloat a = 1.0f, bool m = false); LinearNoiseForce(const LinearNoiseForce ©); virtual ~LinearNoiseForce(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; public: static ConfigVariableInt _random_seed; diff --git a/panda/src/physics/linearRandomForce.cxx b/panda/src/physics/linearRandomForce.cxx index 252397c5bc..f234b174bd 100644 --- a/panda/src/physics/linearRandomForce.cxx +++ b/panda/src/physics/linearRandomForce.cxx @@ -50,7 +50,7 @@ bounded_rand() { * Write a string representation of this instance to . */ void LinearRandomForce:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"LinearRandomForce"; #endif //] NDEBUG @@ -60,7 +60,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void LinearRandomForce:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"LinearRandomForce:\n"; LinearForce::write(out, indent+2); diff --git a/panda/src/physics/linearRandomForce.h b/panda/src/physics/linearRandomForce.h index 2c05fd9763..c637f4a794 100644 --- a/panda/src/physics/linearRandomForce.h +++ b/panda/src/physics/linearRandomForce.h @@ -22,12 +22,12 @@ /** * Pure virtual, parent to noiseForce and jitterForce */ -class EXPCL_PANDAPHYSICS LinearRandomForce : public LinearForce { +class EXPCL_PANDA_PHYSICS LinearRandomForce : public LinearForce { PUBLISHED: virtual ~LinearRandomForce(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; protected: static PN_stdfloat bounded_rand(); diff --git a/panda/src/physics/linearSinkForce.cxx b/panda/src/physics/linearSinkForce.cxx index bee27f2d48..ab1268cd5c 100644 --- a/panda/src/physics/linearSinkForce.cxx +++ b/panda/src/physics/linearSinkForce.cxx @@ -68,7 +68,7 @@ get_child_vector(const PhysicsObject *po) { * Write a string representation of this instance to . */ void LinearSinkForce:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"LinearSinkForce"; #endif //] NDEBUG @@ -78,7 +78,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void LinearSinkForce:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"LinearSinkForce:\n"; LinearDistanceForce::write(out, indent+2); diff --git a/panda/src/physics/linearSinkForce.h b/panda/src/physics/linearSinkForce.h index 42f158d184..9268e0cdd9 100644 --- a/panda/src/physics/linearSinkForce.h +++ b/panda/src/physics/linearSinkForce.h @@ -19,7 +19,7 @@ /** * Attractor force. Think black hole. */ -class EXPCL_PANDAPHYSICS LinearSinkForce : public LinearDistanceForce { +class EXPCL_PANDA_PHYSICS LinearSinkForce : public LinearDistanceForce { PUBLISHED: explicit LinearSinkForce(const LPoint3& p, FalloffType f, PN_stdfloat r, PN_stdfloat a = 1.0f, bool m = true); @@ -27,8 +27,8 @@ PUBLISHED: LinearSinkForce(const LinearSinkForce ©); virtual ~LinearSinkForce(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: virtual LVector3 get_child_vector(const PhysicsObject *po); diff --git a/panda/src/physics/linearSourceForce.cxx b/panda/src/physics/linearSourceForce.cxx index 88db962127..4bb674dbad 100644 --- a/panda/src/physics/linearSourceForce.cxx +++ b/panda/src/physics/linearSourceForce.cxx @@ -68,7 +68,7 @@ get_child_vector(const PhysicsObject *po) { * Write a string representation of this instance to . */ void LinearSourceForce:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"LinearSourceForce"; #endif //] NDEBUG @@ -78,7 +78,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void LinearSourceForce:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"LinearSourceForce:\n"; LinearDistanceForce::write(out, indent+2); diff --git a/panda/src/physics/linearSourceForce.h b/panda/src/physics/linearSourceForce.h index f6b2358c22..70e764a468 100644 --- a/panda/src/physics/linearSourceForce.h +++ b/panda/src/physics/linearSourceForce.h @@ -19,7 +19,7 @@ /** * Repellant force. */ -class EXPCL_PANDAPHYSICS LinearSourceForce : public LinearDistanceForce { +class EXPCL_PANDA_PHYSICS LinearSourceForce : public LinearDistanceForce { PUBLISHED: explicit LinearSourceForce(const LPoint3& p, FalloffType f, PN_stdfloat r, PN_stdfloat a = 1.0f, bool mass = true); @@ -27,8 +27,8 @@ PUBLISHED: LinearSourceForce(const LinearSourceForce ©); virtual ~LinearSourceForce(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: virtual LVector3 get_child_vector(const PhysicsObject *po); diff --git a/panda/src/physics/linearUserDefinedForce.cxx b/panda/src/physics/linearUserDefinedForce.cxx index 4f6c4f4063..2bab34805a 100644 --- a/panda/src/physics/linearUserDefinedForce.cxx +++ b/panda/src/physics/linearUserDefinedForce.cxx @@ -62,7 +62,7 @@ get_child_vector(const PhysicsObject *po) { * Write a string representation of this instance to . */ void LinearUserDefinedForce:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"LinearUserDefinedForce"; #endif //] NDEBUG @@ -72,7 +72,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void LinearUserDefinedForce:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"LinearUserDefinedForce:\n"; LinearForce::write(out, indent+2); diff --git a/panda/src/physics/linearUserDefinedForce.h b/panda/src/physics/linearUserDefinedForce.h index 3f05b1ea77..e7be671950 100644 --- a/panda/src/physics/linearUserDefinedForce.h +++ b/panda/src/physics/linearUserDefinedForce.h @@ -19,17 +19,17 @@ /** * A programmable force that takes an evaluator function. */ -class EXPCL_PANDAPHYSICS LinearUserDefinedForce : public LinearForce { +class EXPCL_PANDA_PHYSICS LinearUserDefinedForce : public LinearForce { PUBLISHED: - explicit LinearUserDefinedForce(LVector3 (*proc)(const PhysicsObject *) = NULL, + explicit LinearUserDefinedForce(LVector3 (*proc)(const PhysicsObject *) = nullptr, PN_stdfloat a = 1.0f, bool md = false); LinearUserDefinedForce(const LinearUserDefinedForce ©); virtual ~LinearUserDefinedForce(); INLINE void set_proc(LVector3 (*proc)(const PhysicsObject *)); - virtual void output(ostream &out) const; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: LVector3 (*_proc)(const PhysicsObject *po); diff --git a/panda/src/physics/linearVectorForce.cxx b/panda/src/physics/linearVectorForce.cxx index 47848073ec..3247bb5ad5 100644 --- a/panda/src/physics/linearVectorForce.cxx +++ b/panda/src/physics/linearVectorForce.cxx @@ -74,7 +74,7 @@ get_child_vector(const PhysicsObject *) { * Write a string representation of this instance to . */ void LinearVectorForce:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"LinearVectorForce"; #endif //] NDEBUG @@ -84,7 +84,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void LinearVectorForce:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"LinearVectorForce:\n"; out.width(indent+2); out<<""; out<<"_fvec "<<_fvec<<"\n"; diff --git a/panda/src/physics/linearVectorForce.h b/panda/src/physics/linearVectorForce.h index ca12ab6bc5..e68f4599da 100644 --- a/panda/src/physics/linearVectorForce.h +++ b/panda/src/physics/linearVectorForce.h @@ -20,7 +20,7 @@ * Simple directed vector force. Suitable for gravity, non-turbulent wind, * etc... */ -class EXPCL_PANDAPHYSICS LinearVectorForce : public LinearForce { +class EXPCL_PANDA_PHYSICS LinearVectorForce : public LinearForce { PUBLISHED: explicit LinearVectorForce(const LVector3& vec, PN_stdfloat a = 1.0f, bool mass = false); explicit LinearVectorForce(PN_stdfloat x = 0.0f, PN_stdfloat y = 0.0f, PN_stdfloat z = 0.0f, @@ -33,8 +33,8 @@ PUBLISHED: INLINE LVector3 get_local_vector() const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; public: INLINE LinearVectorForce& operator += (const LinearVectorForce &other); diff --git a/panda/src/physics/physical.I b/panda/src/physics/physical.I index 3b44d50917..7232c1ebdf 100644 --- a/panda/src/physics/physical.I +++ b/panda/src/physics/physical.I @@ -167,7 +167,7 @@ get_num_linear_forces() const { */ INLINE PT(LinearForce) Physical:: get_linear_force(int index) const { - nassertr(index >= 0 && index < (int)_linear_forces.size(), NULL); + nassertr(index >= 0 && index < (int)_linear_forces.size(), nullptr); return _linear_forces[index]; } @@ -184,7 +184,7 @@ get_num_angular_forces() const { */ INLINE PT(AngularForce) Physical:: get_angular_force(int index) const { - nassertr(index >= 0 && index < (int)_angular_forces.size(), NULL); + nassertr(index >= 0 && index < (int)_angular_forces.size(), nullptr); return _angular_forces[index]; } diff --git a/panda/src/physics/physical.cxx b/panda/src/physics/physical.cxx index f7e64e0507..afd158ec14 100644 --- a/panda/src/physics/physical.cxx +++ b/panda/src/physics/physical.cxx @@ -16,6 +16,8 @@ #include "physical.h" #include "physicsManager.h" +using std::ostream; + TypeHandle Physical::_type_handle; /** @@ -39,7 +41,7 @@ Physical(int total_objects, bool pre_alloc) : _phys_body = new PhysicsObject; add_physics_object(_phys_body); } else { - _phys_body = (PhysicsObject *) NULL; + _phys_body = nullptr; // allocate each object. if (pre_alloc == true) { for (int i = 0; i < total_objects; ++i) { @@ -87,7 +89,7 @@ Physical(const Physical& copy) : if (_physics_objects.size() == 1) _phys_body = _physics_objects[0]; else - _phys_body = (PhysicsObject *) NULL; + _phys_body = nullptr; } /** @@ -99,7 +101,7 @@ Physical:: // because the physics manager doesn't keep PT's to physicals, simply *'s, // and also means that we don't have to tell the physics manager ourselves // when one of our physicals is dead. - if (_physics_manager != (PhysicsManager *) NULL) { + if (_physics_manager != nullptr) { _physics_manager->remove_physical(this); } } @@ -134,7 +136,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void Physical:: -write_physics_objects(ostream &out, unsigned int indent) const { +write_physics_objects(ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""<<"_physics_objects ("<<_physics_objects.size()<<" objects)\n"; @@ -150,7 +152,7 @@ write_physics_objects(ostream &out, unsigned int indent) const { * Write a string representation of this instance to . */ void Physical:: -write_linear_forces(ostream &out, unsigned int indent) const { +write_linear_forces(ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""<<"_linear_forces ("<<_linear_forces.size()<<" forces)\n"; @@ -166,7 +168,7 @@ write_linear_forces(ostream &out, unsigned int indent) const { * Write a string representation of this instance to . */ void Physical:: -write_angular_forces(ostream &out, unsigned int indent) const { +write_angular_forces(ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""<<"_angular_forces ("<<_angular_forces.size()<<" forces)\n"; @@ -182,7 +184,7 @@ write_angular_forces(ostream &out, unsigned int indent) const { * Write a string representation of this instance to . */ void Physical:: -write(ostream &out, unsigned int indent) const { +write(ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""<<"Physical\n"; write_physics_objects(out, indent+2); diff --git a/panda/src/physics/physical.h b/panda/src/physics/physical.h index 64550823af..fd3b9c343a 100644 --- a/panda/src/physics/physical.h +++ b/panda/src/physics/physical.h @@ -34,7 +34,7 @@ class PhysicsManager; * Defines a set of physically modeled attributes. If you want physics * applied to your class, derive it from this. */ -class EXPCL_PANDAPHYSICS Physical : public TypedReferenceCount { +class EXPCL_PANDA_PHYSICS Physical : public TypedReferenceCount { public: // typedef pvector PhysicsObjectVector; typedef pvector LinearForceVector; @@ -73,14 +73,14 @@ PUBLISHED: const PhysicsObjectCollection get_objects() const; - virtual void output(ostream &out = cout) const; + virtual void output(std::ostream &out = std::cout) const; virtual void write_physics_objects( - ostream &out = cout, unsigned int indent=0) const; + std::ostream &out = std::cout, int indent=0) const; virtual void write_linear_forces( - ostream &out = cout, unsigned int indent=0) const; + std::ostream &out = std::cout, int indent=0) const; virtual void write_angular_forces( - ostream &out = cout, unsigned int indent=0) const; - virtual void write(ostream &out = cout, unsigned int indent=0) const; + std::ostream &out = std::cout, int indent=0) const; + virtual void write(std::ostream &out = std::cout, int indent=0) const; public: INLINE const PhysicsObject::Vector &get_object_vector() const; diff --git a/panda/src/physics/physicalNode.I b/panda/src/physics/physicalNode.I index 700511b1e6..407cf52f5a 100644 --- a/panda/src/physics/physicalNode.I +++ b/panda/src/physics/physicalNode.I @@ -29,7 +29,7 @@ clear() { */ INLINE Physical *PhysicalNode:: get_physical(size_t index) const { - nassertr(index < _physicals.size(), (Physical *) NULL); + nassertr(index < _physicals.size(), nullptr); return _physicals[index]; } diff --git a/panda/src/physics/physicalNode.cxx b/panda/src/physics/physicalNode.cxx index daa454aff1..0fcabeeb8a 100644 --- a/panda/src/physics/physicalNode.cxx +++ b/panda/src/physics/physicalNode.cxx @@ -21,7 +21,7 @@ TypeHandle PhysicalNode::_type_handle; * default constructor */ PhysicalNode:: -PhysicalNode(const string &name) : +PhysicalNode(const std::string &name) : PandaNode(name) { } @@ -124,7 +124,7 @@ remove_physical(size_t index) { pvector< PT(Physical) >::iterator remove; remove = _physicals.begin() + index; - (*remove)->_physical_node = (PhysicalNode *) NULL; + (*remove)->_physical_node = nullptr; _physicals.erase(remove); } @@ -133,7 +133,7 @@ remove_physical(size_t index) { * Write a string representation of this instance to . */ void PhysicalNode:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"PhysicalNode:\n"; // PandaNode::write(out, indent+2); diff --git a/panda/src/physics/physicalNode.h b/panda/src/physics/physicalNode.h index 24bd272fdc..f88d79dda6 100644 --- a/panda/src/physics/physicalNode.h +++ b/panda/src/physics/physicalNode.h @@ -25,9 +25,9 @@ /** * Graph node that encapsulated a series of physical objects */ -class EXPCL_PANDAPHYSICS PhysicalNode : public PandaNode { +class EXPCL_PANDA_PHYSICS PhysicalNode : public PandaNode { PUBLISHED: - explicit PhysicalNode(const string &name); + explicit PhysicalNode(const std::string &name); INLINE void clear(); INLINE Physical *get_physical(size_t index) const; INLINE size_t get_num_physicals() const; @@ -43,7 +43,7 @@ PUBLISHED: MAKE_SEQ_PROPERTY(physicals, get_num_physicals, get_physical, set_physical, remove_physical, insert_physical); - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void write(std::ostream &out, int indent=0) const; public: virtual ~PhysicalNode(); diff --git a/panda/src/physics/physicsCollisionHandler.cxx b/panda/src/physics/physicsCollisionHandler.cxx index f3be69e927..7fe69cd997 100644 --- a/panda/src/physics/physicsCollisionHandler.cxx +++ b/panda/src/physics/physicsCollisionHandler.cxx @@ -20,6 +20,9 @@ #include "actorNode.h" #include "dcast.h" +using std::cerr; +using std::endl; + TypeHandle PhysicsCollisionHandler::_type_handle; /** diff --git a/panda/src/physics/physicsCollisionHandler.h b/panda/src/physics/physicsCollisionHandler.h index 8811a88756..febcede789 100644 --- a/panda/src/physics/physicsCollisionHandler.h +++ b/panda/src/physics/physicsCollisionHandler.h @@ -23,7 +23,7 @@ * that attempt to move into solid walls. This also puts forces onto the * physics objects */ -class EXPCL_PANDAPHYSICS PhysicsCollisionHandler : +class EXPCL_PANDA_PHYSICS PhysicsCollisionHandler : public CollisionHandlerPusher { PUBLISHED: PhysicsCollisionHandler(); diff --git a/panda/src/physics/physicsManager.I b/panda/src/physics/physicsManager.I index e9c128c641..386d53d24c 100644 --- a/panda/src/physics/physicsManager.I +++ b/panda/src/physics/physicsManager.I @@ -16,7 +16,7 @@ */ INLINE void PhysicsManager:: attach_physical(Physical *p) { - nassertv(p && p->_physics_manager == NULL); + nassertv(p && p->_physics_manager == nullptr); p->_physics_manager = this; PhysicalsVector::iterator found; found = find(_physicals.begin(), _physicals.end(), p); @@ -44,10 +44,10 @@ add_linear_force(LinearForce *f) { */ INLINE void PhysicsManager:: attach_physicalnode(PhysicalNode *p) { - cerr<<"attach_physicalnode (aka attachPhysicalnode) has been" + std::cerr<<"attach_physicalnode (aka attachPhysicalnode) has been" <<"replaced with attach_physical_node (aka attachPhysicalNode)." <<" Please change the spelling of the function in your code." - <get_num_physicals(); ++i) { + for (size_t i = 0; i < p->get_num_physicals(); ++i) { attach_physical(p->get_physical(i)); } } diff --git a/panda/src/physics/physicsManager.cxx b/panda/src/physics/physicsManager.cxx index b108176dd6..3286e73539 100644 --- a/panda/src/physics/physicsManager.cxx +++ b/panda/src/physics/physicsManager.cxx @@ -17,6 +17,8 @@ #include #include "pvector.h" +using std::ostream; + ConfigVariableInt PhysicsManager::_random_seed ("physics_manager_random_seed", 139); @@ -38,7 +40,7 @@ PhysicsManager:: PhysicalsVector::iterator pi; for (pi = _physicals.begin(); pi != _physicals.end(); ++pi) { nassertv((*pi)->_physics_manager == this); - (*pi)->_physics_manager = NULL; + (*pi)->_physics_manager = nullptr; } } @@ -100,7 +102,7 @@ remove_physical(Physical *p) { return; } nassertv(p->_physics_manager == this); - p->_physics_manager = (PhysicsManager *) NULL; + p->_physics_manager = nullptr; _physicals.erase(found); } @@ -110,7 +112,7 @@ remove_physical(Physical *p) { void PhysicsManager:: remove_physical_node(PhysicalNode *p) { nassertv(p); - for (int i = 0; i < p->get_num_physicals(); ++i) { + for (size_t i = 0; i < p->get_num_physicals(); ++i) { remove_physical(p->get_physical(i)); } } @@ -186,7 +188,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void PhysicsManager:: -write_physicals(ostream &out, unsigned int indent) const { +write_physicals(ostream &out, int indent) const { #ifndef NDEBUG //[ if (indent>10) { return; @@ -206,7 +208,7 @@ write_physicals(ostream &out, unsigned int indent) const { * Write a string representation of this instance to . */ void PhysicsManager:: -write_linear_forces(ostream &out, unsigned int indent) const { +write_linear_forces(ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""<<"_linear_forces ("<<_linear_forces.size()<<" forces)\n"; @@ -222,7 +224,7 @@ write_linear_forces(ostream &out, unsigned int indent) const { * Write a string representation of this instance to . */ void PhysicsManager:: -write_angular_forces(ostream &out, unsigned int indent) const { +write_angular_forces(ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""<<"_angular_forces ("<<_angular_forces.size()<<" forces)\n"; @@ -238,7 +240,7 @@ write_angular_forces(ostream &out, unsigned int indent) const { * Write a string representation of this instance to . */ void PhysicsManager:: -write(ostream &out, unsigned int indent) const { +write(ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""<<"PhysicsManager:\n"; if (indent>20) { @@ -268,7 +270,7 @@ write(ostream &out, unsigned int indent) const { * Write a string representation of this instance to . */ void PhysicsManager:: -debug_output(ostream &out, unsigned int indent) const { +debug_output(ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""<<"PhysicsManager li"<<(_linear_integrator?1:0)<<" ai"<<(_angular_integrator?1:0)<<"\n"; out<<" _physicals "<<_physicals.size()<<"\n"; diff --git a/panda/src/physics/physicsManager.h b/panda/src/physics/physicsManager.h index 80319ef2f0..b9ca9adf49 100644 --- a/panda/src/physics/physicsManager.h +++ b/panda/src/physics/physicsManager.h @@ -33,7 +33,7 @@ * Physics don't get much higher-level than this. Attach as many Physicals * (particle systems, etc..) as you want, pick an integrator and go. */ -class EXPCL_PANDAPHYSICS PhysicsManager { +class EXPCL_PANDA_PHYSICS PhysicsManager { public: // NOTE that the physicals container is NOT reference counted. this does // indeed mean that you are NOT supposed to use this as a primary storage @@ -71,13 +71,13 @@ PUBLISHED: void do_physics(PN_stdfloat dt, Physical *p); void init_random_seed(); - virtual void output(ostream &out) const; - virtual void write_physicals(ostream &out, unsigned int indent=0) const; - virtual void write_linear_forces(ostream &out, unsigned int indent=0) const; - virtual void write_angular_forces(ostream &out, unsigned int indent=0) const; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write_physicals(std::ostream &out, int indent=0) const; + virtual void write_linear_forces(std::ostream &out, int indent=0) const; + virtual void write_angular_forces(std::ostream &out, int indent=0) const; + virtual void write(std::ostream &out, int indent=0) const; - virtual void debug_output(ostream &out, unsigned int indent=0) const; + virtual void debug_output(std::ostream &out, int indent=0) const; public: friend class Physical; diff --git a/panda/src/physics/physicsObject.cxx b/panda/src/physics/physicsObject.cxx index dc9b663771..9cca9f6d2f 100644 --- a/panda/src/physics/physicsObject.cxx +++ b/panda/src/physics/physicsObject.cxx @@ -112,7 +112,7 @@ add_impact(const LPoint3 &offset, a = a.cross(b); PN_stdfloat angle = a.length(); if (angle) { - LRotation torque; + LRotation torque(0, 0, 0, 0); PN_stdfloat spin = force.length()*0.1; // todo: this should account for // impact distance and mass. a.normalize(); @@ -150,7 +150,7 @@ get_inertial_tensor() const { * Write a string representation of this instance to . */ void PhysicsObject:: -output(ostream &out) const { +output(std::ostream &out) const { #ifndef NDEBUG //[ out<<"PhysicsObject"; #endif //] NDEBUG @@ -160,7 +160,7 @@ output(ostream &out) const { * Write a string representation of this instance to . */ void PhysicsObject:: -write(ostream &out, unsigned int indent) const { +write(std::ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""<<"PhysicsObject "<<_name<<"\n"; diff --git a/panda/src/physics/physicsObject.h b/panda/src/physics/physicsObject.h index 5cb266ae7f..a36eb2660f 100644 --- a/panda/src/physics/physicsObject.h +++ b/panda/src/physics/physicsObject.h @@ -24,7 +24,7 @@ * motion to your class, do NOT derive from this. Derive from Physical * instead. */ -class EXPCL_PANDAPHYSICS PhysicsObject : public TypedReferenceCount { +class EXPCL_PANDA_PHYSICS PhysicsObject : public TypedReferenceCount { public: typedef pvector Vector; @@ -88,16 +88,16 @@ PUBLISHED: virtual PhysicsObject *make_copy() const; #ifndef NDEBUG - void set_name(const string &name) { + void set_name(const std::string &name) { _name = name; } - const string& get_name() { + const std::string& get_name() { return _name; } #endif - virtual void output(ostream &out) const; - virtual void write(ostream &out, unsigned int indent=0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent=0) const; private: // physical @@ -116,7 +116,7 @@ private: bool _oriented; #ifndef NDEBUG - string _name; + std::string _name; #endif public: diff --git a/panda/src/physics/physicsObjectCollection.cxx b/panda/src/physics/physicsObjectCollection.cxx index 17ce51158d..2b810ef8be 100644 --- a/panda/src/physics/physicsObjectCollection.cxx +++ b/panda/src/physics/physicsObjectCollection.cxx @@ -221,7 +221,7 @@ size() const { * indicated output stream. */ void PhysicsObjectCollection:: -output(ostream &out) const { +output(std::ostream &out) const { if (get_num_physics_objects() == 1) { out << "1 PhysicsObject"; } else { @@ -234,7 +234,7 @@ output(ostream &out) const { * the indicated output stream. */ void PhysicsObjectCollection:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { for (int i = 0; i < get_num_physics_objects(); i++) { indent(out, indent_level) << get_physics_object(i) << "\n"; } diff --git a/panda/src/physics/physicsObjectCollection.h b/panda/src/physics/physicsObjectCollection.h index 4901235ee2..8a69d49073 100644 --- a/panda/src/physics/physicsObjectCollection.h +++ b/panda/src/physics/physicsObjectCollection.h @@ -22,7 +22,7 @@ * This is a set of zero or more PhysicsObjects. It's handy for returning * from functions that need to return multiple PhysicsObjects. */ -class EXPCL_PANDAPHYSICS PhysicsObjectCollection { +class EXPCL_PANDA_PHYSICS PhysicsObjectCollection { PUBLISHED: PhysicsObjectCollection(); PhysicsObjectCollection(const PhysicsObjectCollection ©); @@ -46,8 +46,8 @@ PUBLISHED: INLINE void operator += (const PhysicsObjectCollection &other); INLINE PhysicsObjectCollection operator + (const PhysicsObjectCollection &other) const; - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; private: typedef PTA(PT(PhysicsObject)) PhysicsObjects; diff --git a/panda/src/physics/test_physics.cxx b/panda/src/physics/test_physics.cxx index cb2e2f0c9d..21d248575f 100644 --- a/panda/src/physics/test_physics.cxx +++ b/panda/src/physics/test_physics.cxx @@ -16,6 +16,9 @@ #include "physicsManager.h" #include "forces.h" +using std::cout; +using std::endl; + class Baseball : public Physical { public: int ttl_balls; diff --git a/panda/src/physx/physxActor.I b/panda/src/physx/physxActor.I index 9b6896e596..10f4089eaf 100644 --- a/panda/src/physx/physxActor.I +++ b/panda/src/physx/physxActor.I @@ -40,7 +40,7 @@ ls() const { * */ INLINE void PhysxActor:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type().get_name() << " " << _name diff --git a/panda/src/physx/physxActor.cxx b/panda/src/physx/physxActor.cxx index fdbce36aff..2b3075e45a 100644 --- a/panda/src/physx/physxActor.cxx +++ b/panda/src/physx/physxActor.cxx @@ -61,7 +61,7 @@ unlink() { } // Unlink self - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxScene *scene = (PhysxScene *)_ptr->getScene().userData; @@ -78,7 +78,7 @@ release() { unlink(); _ptr->getScene().releaseActor(*_ptr); - _ptr = NULL; + _ptr = nullptr; } /** @@ -358,7 +358,7 @@ get_node_path() const { PhysxScene *PhysxActor:: get_scene() const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); NxScene *scenePtr = &(_ptr->getScene()); PhysxScene *scene = (PhysxScene *)(scenePtr->userData); @@ -387,14 +387,14 @@ get_num_shapes() const { PhysxShape *PhysxActor:: create_shape(PhysxShapeDesc &desc) { - nassertr(_error_type == ET_ok, NULL); - nassertr(desc.is_valid(),NULL); + nassertr(_error_type == ET_ok, nullptr); + nassertr(desc.is_valid(),nullptr); PhysxShape *shape = PhysxShape::factory(desc.ptr()->getType()); - nassertr(shape, NULL); + nassertr(shape, nullptr); NxShape *shapePtr = _ptr->createShape(*desc.ptr()); - nassertr(shapePtr, NULL); + nassertr(shapePtr, nullptr); shape->link(shapePtr); @@ -408,8 +408,8 @@ create_shape(PhysxShapeDesc &desc) { PhysxShape *PhysxActor:: get_shape(unsigned int idx) const { - nassertr(_error_type == ET_ok, NULL); - nassertr_always(idx < _ptr->getNbShapes(), NULL); + nassertr(_error_type == ET_ok, nullptr); + nassertr_always(idx < _ptr->getNbShapes(), nullptr); NxShape * const *shapes = _ptr->getShapes(); NxShape *shapePtr = shapes[idx]; @@ -426,10 +426,10 @@ get_shape(unsigned int idx) const { PhysxShape *PhysxActor:: get_shape_by_name(const char *name) const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); NxShape * const *shapes = _ptr->getShapes(); - NxShape *shapePtr = NULL; + NxShape *shapePtr = nullptr; NxU32 nShapes = _ptr->getNbShapes(); for (NxU32 i=0; i < nShapes; i++) { @@ -440,7 +440,7 @@ get_shape_by_name(const char *name) const { } } - return NULL; + return nullptr; } /** diff --git a/panda/src/physx/physxActor.h b/panda/src/physx/physxActor.h index 5aaa183463..c91f4423c3 100644 --- a/panda/src/physx/physxActor.h +++ b/panda/src/physx/physxActor.h @@ -173,7 +173,7 @@ PUBLISHED: void move_global_hpr(float h, float p, float r); INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; public: void update_transform(const LMatrix4f &m); @@ -194,7 +194,7 @@ private: NxActor *_ptr; NodePath _np; PT(PhysxController) _controller; - string _name; + std::string _name; public: static TypeHandle get_class_type() { diff --git a/panda/src/physx/physxActorDesc.h b/panda/src/physx/physxActorDesc.h index 84a948b815..339134de06 100644 --- a/panda/src/physx/physxActorDesc.h +++ b/panda/src/physx/physxActorDesc.h @@ -53,7 +53,7 @@ public: NxActorDesc _desc; private: - string _name; + std::string _name; }; #include "physxActorDesc.I" diff --git a/panda/src/physx/physxBoxForceFieldShape.cxx b/panda/src/physx/physxBoxForceFieldShape.cxx index 2aff7e32a7..af874e3b4b 100644 --- a/panda/src/physx/physxBoxForceFieldShape.cxx +++ b/panda/src/physx/physxBoxForceFieldShape.cxx @@ -39,7 +39,7 @@ link(NxForceFieldShape *shapePtr) { void PhysxBoxForceFieldShape:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxForceFieldShapeGroup *group = (PhysxForceFieldShapeGroup *)_ptr->getShapeGroup().userData; diff --git a/panda/src/physx/physxBoxShape.cxx b/panda/src/physx/physxBoxShape.cxx index 695ed1fd71..0ec704bc02 100644 --- a/panda/src/physx/physxBoxShape.cxx +++ b/panda/src/physx/physxBoxShape.cxx @@ -39,7 +39,7 @@ link(NxShape *shapePtr) { void PhysxBoxShape:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxActor *actor = (PhysxActor *)_ptr->getActor().userData; diff --git a/panda/src/physx/physxCapsuleForceFieldShape.cxx b/panda/src/physx/physxCapsuleForceFieldShape.cxx index 0aacd1e61b..be0ce986e6 100644 --- a/panda/src/physx/physxCapsuleForceFieldShape.cxx +++ b/panda/src/physx/physxCapsuleForceFieldShape.cxx @@ -38,7 +38,7 @@ link(NxForceFieldShape *shapePtr) { void PhysxCapsuleForceFieldShape:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxForceFieldShapeGroup *group = (PhysxForceFieldShapeGroup *)_ptr->getShapeGroup().userData; diff --git a/panda/src/physx/physxCapsuleShape.cxx b/panda/src/physx/physxCapsuleShape.cxx index ed4dc24d75..29269dd4dd 100644 --- a/panda/src/physx/physxCapsuleShape.cxx +++ b/panda/src/physx/physxCapsuleShape.cxx @@ -38,7 +38,7 @@ link(NxShape *shapePtr) { void PhysxCapsuleShape:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxActor *actor = (PhysxActor *)_ptr->getActor().userData; diff --git a/panda/src/physx/physxCcdSkeleton.I b/panda/src/physx/physxCcdSkeleton.I index 14b4530d41..a6b0ed7314 100644 --- a/panda/src/physx/physxCcdSkeleton.I +++ b/panda/src/physx/physxCcdSkeleton.I @@ -40,7 +40,7 @@ ls() const { * */ INLINE void PhysxCcdSkeleton:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type().get_name() << " (at 0x" << this << ")\n"; diff --git a/panda/src/physx/physxCcdSkeleton.cxx b/panda/src/physx/physxCcdSkeleton.cxx index 22dc3f4173..e18ff74023 100644 --- a/panda/src/physx/physxCcdSkeleton.cxx +++ b/panda/src/physx/physxCcdSkeleton.cxx @@ -49,7 +49,7 @@ release() { unlink(); NxGetPhysicsSDK()->releaseCCDSkeleton(*_ptr); - _ptr = NULL; + _ptr = nullptr; // TODO PhysxMeshPool::release_ccd_skeleton(this); } diff --git a/panda/src/physx/physxCcdSkeleton.h b/panda/src/physx/physxCcdSkeleton.h index bacc319027..e8a0835741 100644 --- a/panda/src/physx/physxCcdSkeleton.h +++ b/panda/src/physx/physxCcdSkeleton.h @@ -32,7 +32,7 @@ PUBLISHED: void release(); INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; public: INLINE PhysxCcdSkeleton(); diff --git a/panda/src/physx/physxCcdSkeletonDesc.I b/panda/src/physx/physxCcdSkeletonDesc.I index 227a6f9684..271e1c94e9 100644 --- a/panda/src/physx/physxCcdSkeletonDesc.I +++ b/panda/src/physx/physxCcdSkeletonDesc.I @@ -20,11 +20,11 @@ PhysxCcdSkeletonDesc() { _desc.flags = 0; _desc.pointStrideBytes = sizeof(NxVec3); _desc.triangleStrideBytes = 3*sizeof(NxU32); - _desc.points = NULL; - _desc.triangles = NULL; + _desc.points = nullptr; + _desc.triangles = nullptr; - _vertices = NULL; - _triangles = NULL; + _vertices = nullptr; + _triangles = nullptr; } /** diff --git a/panda/src/physx/physxCloth.I b/panda/src/physx/physxCloth.I index e1027201cd..8ecec85332 100644 --- a/panda/src/physx/physxCloth.I +++ b/panda/src/physx/physxCloth.I @@ -40,7 +40,7 @@ ls() const { * */ INLINE void PhysxCloth:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type().get_name() << " " << _name diff --git a/panda/src/physx/physxCloth.cxx b/panda/src/physx/physxCloth.cxx index 9f2583f7df..05e77b54b6 100644 --- a/panda/src/physx/physxCloth.cxx +++ b/panda/src/physx/physxCloth.cxx @@ -46,13 +46,13 @@ void PhysxCloth:: unlink() { // Unlink self - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxScene *scene = (PhysxScene *)_ptr->getScene().userData; scene->_cloths.remove(this); - _node = NULL; + _node = nullptr; } /** @@ -65,7 +65,7 @@ release() { unlink(); _ptr->getScene().releaseCloth(*_ptr); - _ptr = NULL; + _ptr = nullptr; } /** @@ -95,7 +95,7 @@ update() { PhysxScene *PhysxCloth:: get_scene() const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); return (PhysxScene *)_ptr->getScene().userData; } @@ -105,7 +105,7 @@ get_scene() const { PhysxClothNode *PhysxCloth:: get_cloth_node() const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); return _node; } @@ -115,7 +115,7 @@ get_cloth_node() const { PhysxClothNode *PhysxCloth:: create_cloth_node(const char *name) { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); _node = new PhysxClothNode(name); _node->allocate(this); @@ -455,11 +455,11 @@ get_vertex_attachment_status(unsigned int vertexId) const { PhysxShape *PhysxCloth:: get_vertex_attachment_shape(unsigned int vertexId) const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); // --TODO-- nassertr(vertexId < _ptr->getNumberOfParticles(), NULL); NxShape *shapePtr = _ptr->getVertexAttachmentShape(vertexId); - PhysxShape *shape = shapePtr ? (PhysxShape *)(shapePtr->userData) : NULL; + PhysxShape *shape = shapePtr ? (PhysxShape *)(shapePtr->userData) : nullptr; return shape; } diff --git a/panda/src/physx/physxCloth.h b/panda/src/physx/physxCloth.h index aecada8f5e..b1980a7607 100644 --- a/panda/src/physx/physxCloth.h +++ b/panda/src/physx/physxCloth.h @@ -87,7 +87,7 @@ PUBLISHED: PhysxForceMode mode=FM_force); INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; public: void update(); @@ -104,7 +104,7 @@ public: private: NxCloth *_ptr; PT(PhysxClothNode) _node; - string _name; + std::string _name; public: static TypeHandle get_class_type() { diff --git a/panda/src/physx/physxClothDesc.h b/panda/src/physx/physxClothDesc.h index 61a62e9a0f..dc40eed8aa 100644 --- a/panda/src/physx/physxClothDesc.h +++ b/panda/src/physx/physxClothDesc.h @@ -69,7 +69,7 @@ public: NxClothDesc _desc; private: - string _name; + std::string _name; }; #include "physxClothDesc.I" diff --git a/panda/src/physx/physxClothMesh.I b/panda/src/physx/physxClothMesh.I index 1b50324f23..0c9ab0d103 100644 --- a/panda/src/physx/physxClothMesh.I +++ b/panda/src/physx/physxClothMesh.I @@ -40,7 +40,7 @@ ls() const { * */ INLINE void PhysxClothMesh:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type().get_name() << " (at 0x" << this << ")\n"; diff --git a/panda/src/physx/physxClothMesh.cxx b/panda/src/physx/physxClothMesh.cxx index 7a11a450e3..493b781a0a 100644 --- a/panda/src/physx/physxClothMesh.cxx +++ b/panda/src/physx/physxClothMesh.cxx @@ -49,7 +49,7 @@ release() { unlink(); NxGetPhysicsSDK()->releaseClothMesh(*_ptr); - _ptr = NULL; + _ptr = nullptr; PhysxMeshPool::release_cloth_mesh(this); } diff --git a/panda/src/physx/physxClothMesh.h b/panda/src/physx/physxClothMesh.h index b83a867875..7cd0a5d167 100644 --- a/panda/src/physx/physxClothMesh.h +++ b/panda/src/physx/physxClothMesh.h @@ -31,7 +31,7 @@ PUBLISHED: void release(); INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; public: INLINE PhysxClothMesh(); diff --git a/panda/src/physx/physxClothMeshDesc.I b/panda/src/physx/physxClothMeshDesc.I index 973883686b..2cf02c8152 100644 --- a/panda/src/physx/physxClothMeshDesc.I +++ b/panda/src/physx/physxClothMeshDesc.I @@ -20,12 +20,12 @@ PhysxClothMeshDesc() { _desc.flags = 0; _desc.pointStrideBytes = sizeof(NxVec3); _desc.triangleStrideBytes = 3*sizeof(NxU32); - _desc.points = NULL; - _desc.triangles = NULL; + _desc.points = nullptr; + _desc.triangles = nullptr; - _points = NULL; - _triangles = NULL; - _texcoords = NULL; + _points = nullptr; + _triangles = nullptr; + _texcoords = nullptr; } /** diff --git a/panda/src/physx/physxClothNode.I b/panda/src/physx/physxClothNode.I index 3597004f03..a06bfcc3c3 100644 --- a/panda/src/physx/physxClothNode.I +++ b/panda/src/physx/physxClothNode.I @@ -30,7 +30,7 @@ PhysxClothNode(const char *name) : GeomNode(name) { this->add_geom(_geom); _numTexcoords = 0; - _texcoords = NULL; + _texcoords = nullptr; } /** diff --git a/panda/src/physx/physxContactPair.cxx b/panda/src/physx/physxContactPair.cxx index 1ecd1fab6d..fdaf22889c 100644 --- a/panda/src/physx/physxContactPair.cxx +++ b/panda/src/physx/physxContactPair.cxx @@ -25,12 +25,12 @@ PhysxActor *PhysxContactPair:: get_actor_a() const { if (_pair.isDeletedActor[0]) { - physx_cat.warning() << "actor A has been deleted" << endl; - return NULL; + physx_cat.warning() << "actor A has been deleted" << std::endl; + return nullptr; } NxActor *actorPtr = _pair.actors[0]; - return (actorPtr == NULL) ? NULL : (PhysxActor *)actorPtr->userData; + return (actorPtr == nullptr) ? nullptr : (PhysxActor *)actorPtr->userData; } /** @@ -40,12 +40,12 @@ PhysxActor *PhysxContactPair:: get_actor_b() const { if (_pair.isDeletedActor[1]) { - physx_cat.warning() << "actor B has been deleted" << endl; - return NULL; + physx_cat.warning() << "actor B has been deleted" << std::endl; + return nullptr; } NxActor *actorPtr = _pair.actors[1]; - return (actorPtr == NULL) ? NULL : (PhysxActor *)actorPtr->userData; + return (actorPtr == nullptr) ? nullptr : (PhysxActor *)actorPtr->userData; } /** diff --git a/panda/src/physx/physxController.I b/panda/src/physx/physxController.I index c6b667c35e..58bd825c21 100644 --- a/panda/src/physx/physxController.I +++ b/panda/src/physx/physxController.I @@ -39,7 +39,7 @@ PhysxController() : PhysxObject() { _up_quat = NxQuat(0.0f, NxVec3(1.0f, 0.0f, 0.0f)); break; default: - physx_cat.error() << "only y-up and z-up are permitted" << endl; + physx_cat.error() << "only y-up and z-up are permitted" << std::endl; } _up_quat_inv = _up_quat; @@ -59,7 +59,7 @@ ls() const { * */ INLINE void PhysxController:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type().get_name() << " (at 0x" << this << ")"; diff --git a/panda/src/physx/physxController.cxx b/panda/src/physx/physxController.cxx index 4e83a282a4..7787c4019e 100644 --- a/panda/src/physx/physxController.cxx +++ b/panda/src/physx/physxController.cxx @@ -55,7 +55,7 @@ factory(NxControllerType controllerType) { } physx_cat.error() << "Unknown controller type.\n"; - return NULL; + return nullptr; } @@ -65,7 +65,7 @@ factory(NxControllerType controllerType) { PhysxActor *PhysxController:: get_actor() const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); return (PhysxActor *)(ptr()->getActor()->userData); } diff --git a/panda/src/physx/physxController.h b/panda/src/physx/physxController.h index f759f43fea..dc520c3913 100644 --- a/panda/src/physx/physxController.h +++ b/panda/src/physx/physxController.h @@ -54,7 +54,7 @@ PUBLISHED: void stop_jump(); INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; public: void update_controller(float dt); diff --git a/panda/src/physx/physxControllerReport.cxx b/panda/src/physx/physxControllerReport.cxx index dd6cfb225c..a9b570fcda 100644 --- a/panda/src/physx/physxControllerReport.cxx +++ b/panda/src/physx/physxControllerReport.cxx @@ -23,8 +23,8 @@ enable() { _enabled = true; - _shape_hit_cbobj = NULL; - _controller_hit_cbobj = NULL; + _shape_hit_cbobj = nullptr; + _controller_hit_cbobj = nullptr; } /** diff --git a/panda/src/physx/physxControllerShapeHit.I b/panda/src/physx/physxControllerShapeHit.I index a894ae013d..b6500ca736 100644 --- a/panda/src/physx/physxControllerShapeHit.I +++ b/panda/src/physx/physxControllerShapeHit.I @@ -30,7 +30,7 @@ get_controller() const { return (PhysxController *)(_hit.controller->getUserData()); } else { - return NULL; + return nullptr; } } @@ -44,7 +44,7 @@ get_shape() const { return (PhysxShape *)(_hit.shape->userData); } else { - return NULL; + return nullptr; } } diff --git a/panda/src/physx/physxControllersHit.I b/panda/src/physx/physxControllersHit.I index 74816e9159..e3d9aea411 100644 --- a/panda/src/physx/physxControllersHit.I +++ b/panda/src/physx/physxControllersHit.I @@ -27,7 +27,7 @@ INLINE PhysxController *PhysxControllersHit:: get_controller() const { NxController *controllerPtr = _hit.controller; - PhysxController *controller = controllerPtr ? (PhysxController *)controllerPtr : NULL; + PhysxController *controller = controllerPtr ? (PhysxController *)controllerPtr : nullptr; return controller; } @@ -39,7 +39,7 @@ INLINE PhysxController *PhysxControllersHit:: get_other() const { NxController *otherPtr = _hit.other; - PhysxController *other = otherPtr ? (PhysxController *)otherPtr : NULL; + PhysxController *other = otherPtr ? (PhysxController *)otherPtr : nullptr; return other; } diff --git a/panda/src/physx/physxConvexForceFieldShape.cxx b/panda/src/physx/physxConvexForceFieldShape.cxx index 406fabd878..bf89f9c485 100644 --- a/panda/src/physx/physxConvexForceFieldShape.cxx +++ b/panda/src/physx/physxConvexForceFieldShape.cxx @@ -38,7 +38,7 @@ link(NxForceFieldShape *shapePtr) { void PhysxConvexForceFieldShape:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxForceFieldShapeGroup *group = (PhysxForceFieldShapeGroup *)_ptr->getShapeGroup().userData; diff --git a/panda/src/physx/physxConvexMesh.I b/panda/src/physx/physxConvexMesh.I index 79d15bcb3f..c97e48ce32 100644 --- a/panda/src/physx/physxConvexMesh.I +++ b/panda/src/physx/physxConvexMesh.I @@ -40,7 +40,7 @@ ls() const { * */ INLINE void PhysxConvexMesh:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type().get_name() << " (at 0x" << this << ")\n"; diff --git a/panda/src/physx/physxConvexMesh.cxx b/panda/src/physx/physxConvexMesh.cxx index 85bc518d9e..f703533856 100644 --- a/panda/src/physx/physxConvexMesh.cxx +++ b/panda/src/physx/physxConvexMesh.cxx @@ -49,7 +49,7 @@ release() { unlink(); NxGetPhysicsSDK()->releaseConvexMesh(*_ptr); - _ptr = NULL; + _ptr = nullptr; PhysxMeshPool::release_convex_mesh(this); } diff --git a/panda/src/physx/physxConvexMesh.h b/panda/src/physx/physxConvexMesh.h index d5f4b55e67..17f8fcd9cf 100644 --- a/panda/src/physx/physxConvexMesh.h +++ b/panda/src/physx/physxConvexMesh.h @@ -32,7 +32,7 @@ PUBLISHED: void release(); INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; public: INLINE PhysxConvexMesh(); diff --git a/panda/src/physx/physxConvexMeshDesc.I b/panda/src/physx/physxConvexMeshDesc.I index fae24d3130..1611726ecb 100644 --- a/panda/src/physx/physxConvexMeshDesc.I +++ b/panda/src/physx/physxConvexMeshDesc.I @@ -19,9 +19,9 @@ PhysxConvexMeshDesc() { _desc.flags = NX_CF_COMPUTE_CONVEX; _desc.pointStrideBytes = sizeof(NxVec3); - _desc.points = NULL; + _desc.points = nullptr; - _vertices = NULL; + _vertices = nullptr; } /** diff --git a/panda/src/physx/physxConvexShape.cxx b/panda/src/physx/physxConvexShape.cxx index 58d4a6c510..73acc06b87 100644 --- a/panda/src/physx/physxConvexShape.cxx +++ b/panda/src/physx/physxConvexShape.cxx @@ -38,7 +38,7 @@ link(NxShape *shapePtr) { void PhysxConvexShape:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxActor *actor = (PhysxActor *)_ptr->getActor().userData; diff --git a/panda/src/physx/physxCylindricalJoint.cxx b/panda/src/physx/physxCylindricalJoint.cxx index 2a2fbb22d3..037668db54 100644 --- a/panda/src/physx/physxCylindricalJoint.cxx +++ b/panda/src/physx/physxCylindricalJoint.cxx @@ -38,7 +38,7 @@ link(NxJoint *jointPtr) { void PhysxCylindricalJoint:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxScene *scene = (PhysxScene *)_ptr->getScene().userData; diff --git a/panda/src/physx/physxD6Joint.cxx b/panda/src/physx/physxD6Joint.cxx index d52f1cdae1..a95abddcf5 100644 --- a/panda/src/physx/physxD6Joint.cxx +++ b/panda/src/physx/physxD6Joint.cxx @@ -38,7 +38,7 @@ link(NxJoint *jointPtr) { void PhysxD6Joint:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxScene *scene = (PhysxScene *)_ptr->getScene().userData; diff --git a/panda/src/physx/physxDebugGeomNode.cxx b/panda/src/physx/physxDebugGeomNode.cxx index a609fb2f3c..8b3bd2a1ca 100644 --- a/panda/src/physx/physxDebugGeomNode.cxx +++ b/panda/src/physx/physxDebugGeomNode.cxx @@ -31,7 +31,7 @@ update(NxScene *scenePtr) { const NxDebugRenderable *renderable = scenePtr->getDebugRenderable(); if (!renderable) { remove_all_geoms(); - physx_cat.warning() << "Could no get debug renderable." << endl; + physx_cat.warning() << "Could no get debug renderable." << std::endl; return; } diff --git a/panda/src/physx/physxDistanceJoint.cxx b/panda/src/physx/physxDistanceJoint.cxx index 648821ce66..f24baa7c87 100644 --- a/panda/src/physx/physxDistanceJoint.cxx +++ b/panda/src/physx/physxDistanceJoint.cxx @@ -38,7 +38,7 @@ link(NxJoint *jointPtr) { void PhysxDistanceJoint:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxScene *scene = (PhysxScene *)_ptr->getScene().userData; diff --git a/panda/src/physx/physxEnums.cxx b/panda/src/physx/physxEnums.cxx index 172e6013b3..87a0222bc3 100644 --- a/panda/src/physx/physxEnums.cxx +++ b/panda/src/physx/physxEnums.cxx @@ -16,8 +16,8 @@ #include "string_utils.h" #include "config_putil.h" -ostream & -operator << (ostream &out, PhysxEnums::PhysxUpAxis axis) { +std::ostream & +operator << (std::ostream &out, PhysxEnums::PhysxUpAxis axis) { switch (axis) { case PhysxEnums::X_up: @@ -33,10 +33,10 @@ operator << (ostream &out, PhysxEnums::PhysxUpAxis axis) { return out << "**invalid PhysxEnums::PhysxUpAxis value: (" << (int)axis << ")**"; } -istream & -operator >> (istream &in, PhysxEnums::PhysxUpAxis &axis) { +std::istream & +operator >> (std::istream &in, PhysxEnums::PhysxUpAxis &axis) { - string word; + std::string word; in >> word; if (cmp_nocase(word, "x") == 0) { diff --git a/panda/src/physx/physxEnums.h b/panda/src/physx/physxEnums.h index fb17ebb978..313cb677b2 100644 --- a/panda/src/physx/physxEnums.h +++ b/panda/src/physx/physxEnums.h @@ -714,7 +714,7 @@ PUBLISHED: }; -EXPCL_PANDAPHYSX ostream &operator << (ostream &out, PhysxEnums::PhysxUpAxis axis); -EXPCL_PANDAPHYSX istream &operator >> (istream &in, PhysxEnums::PhysxUpAxis &axis); +EXPCL_PANDAPHYSX std::ostream &operator << (std::ostream &out, PhysxEnums::PhysxUpAxis axis); +EXPCL_PANDAPHYSX std::istream &operator >> (std::istream &in, PhysxEnums::PhysxUpAxis &axis); #endif diff --git a/panda/src/physx/physxFileStream.cxx b/panda/src/physx/physxFileStream.cxx index 1f308ab410..a93444148b 100644 --- a/panda/src/physx/physxFileStream.cxx +++ b/panda/src/physx/physxFileStream.cxx @@ -20,7 +20,7 @@ /** * */ -PhysxFileStream::PhysxFileStream(const Filename &fn, bool load) : _fp(NULL), _vf(NULL), _in(NULL) +PhysxFileStream::PhysxFileStream(const Filename &fn, bool load) : _fp(nullptr), _vf(nullptr), _in(nullptr) { if (load) { _vf = VirtualFileSystem::get_global_ptr()->get_file(fn); diff --git a/panda/src/physx/physxFileStream.h b/panda/src/physx/physxFileStream.h index 5b7682c9e0..3e9f4752e9 100644 --- a/panda/src/physx/physxFileStream.h +++ b/panda/src/physx/physxFileStream.h @@ -51,7 +51,7 @@ private: // read PT(VirtualFile) _vf; - istream *_in; + std::istream *_in; }; #endif // PHYSXFILESTREAM_H diff --git a/panda/src/physx/physxFixedJoint.cxx b/panda/src/physx/physxFixedJoint.cxx index 49b5265923..e3257eb22c 100644 --- a/panda/src/physx/physxFixedJoint.cxx +++ b/panda/src/physx/physxFixedJoint.cxx @@ -38,7 +38,7 @@ link(NxJoint *jointPtr) { void PhysxFixedJoint:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxScene *scene = (PhysxScene *)_ptr->getScene().userData; diff --git a/panda/src/physx/physxForceField.I b/panda/src/physx/physxForceField.I index 8a1bf87034..01dbd645ef 100644 --- a/panda/src/physx/physxForceField.I +++ b/panda/src/physx/physxForceField.I @@ -40,7 +40,7 @@ ls() const { * */ INLINE void PhysxForceField:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type().get_name() << " " << _name diff --git a/panda/src/physx/physxForceField.cxx b/panda/src/physx/physxForceField.cxx index eada698729..26149e72e0 100644 --- a/panda/src/physx/physxForceField.cxx +++ b/panda/src/physx/physxForceField.cxx @@ -50,7 +50,7 @@ unlink() { group->unlink(); // Unlink self - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxScene *scene = (PhysxScene *)_ptr->getScene().userData; @@ -67,7 +67,7 @@ release() { unlink(); _ptr->getScene().releaseForceField(*_ptr); - _ptr = NULL; + _ptr = nullptr; } /** @@ -98,7 +98,7 @@ get_name() const { PhysxScene *PhysxForceField:: get_scene() const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); return (PhysxScene *)(_ptr->getScene().userData); } @@ -108,7 +108,7 @@ get_scene() const { PhysxForceFieldShapeGroup *PhysxForceField:: get_include_shape_group() const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); return (PhysxForceFieldShapeGroup *)(_ptr->getIncludeShapeGroup().userData); } @@ -128,8 +128,8 @@ get_num_shape_groups() const { PhysxForceFieldShapeGroup *PhysxForceField:: get_shape_group(unsigned int idx) const { - nassertr(_error_type == ET_ok, NULL); - nassertr_always(idx < _ptr->getNbShapeGroups(), NULL); + nassertr(_error_type == ET_ok, nullptr); + nassertr_always(idx < _ptr->getNbShapeGroups(), nullptr); NxForceFieldShapeGroup *groupPtr; NxU32 nGroups = _ptr->getNbShapeGroups(); diff --git a/panda/src/physx/physxForceField.h b/panda/src/physx/physxForceField.h index ca9f068795..e1dbb85084 100644 --- a/panda/src/physx/physxForceField.h +++ b/panda/src/physx/physxForceField.h @@ -53,7 +53,7 @@ PUBLISHED: void release(); INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; public: INLINE NxForceField *ptr() const { return _ptr; }; @@ -63,7 +63,7 @@ public: private: NxForceField *_ptr; - string _name; + std::string _name; public: static TypeHandle get_class_type() { diff --git a/panda/src/physx/physxForceFieldDesc.h b/panda/src/physx/physxForceFieldDesc.h index accacf961e..f7974acd19 100644 --- a/panda/src/physx/physxForceFieldDesc.h +++ b/panda/src/physx/physxForceFieldDesc.h @@ -63,7 +63,7 @@ public: NxForceFieldLinearKernelDesc _kernel; private: - string _name; + std::string _name; }; #include "physxForceFieldDesc.I" diff --git a/panda/src/physx/physxForceFieldShape.I b/panda/src/physx/physxForceFieldShape.I index 1dd06f5fe8..a58a90136f 100644 --- a/panda/src/physx/physxForceFieldShape.I +++ b/panda/src/physx/physxForceFieldShape.I @@ -32,7 +32,7 @@ ls() const { * */ INLINE void PhysxForceFieldShape:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type().get_name() << " " << _name diff --git a/panda/src/physx/physxForceFieldShape.cxx b/panda/src/physx/physxForceFieldShape.cxx index a0a2d1b931..fe5cdfb316 100644 --- a/panda/src/physx/physxForceFieldShape.cxx +++ b/panda/src/physx/physxForceFieldShape.cxx @@ -56,7 +56,7 @@ factory(NxShapeType shapeType) { } physx_cat.error() << "Unknown shape type.\n"; - return NULL; + return nullptr; } /** @@ -66,11 +66,11 @@ factory(NxShapeType shapeType) { PhysxForceField *PhysxForceFieldShape:: get_force_field() const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); NxForceField *fieldPtr = ptr()->getForceField(); - if (fieldPtr == NULL) { - return NULL; + if (fieldPtr == nullptr) { + return nullptr; } return (PhysxForceField *)(fieldPtr->userData); } @@ -81,7 +81,7 @@ get_force_field() const { PhysxForceFieldShapeGroup *PhysxForceFieldShape:: get_shape_group() const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); return (PhysxForceFieldShapeGroup *)(ptr()->getShapeGroup().userData); } diff --git a/panda/src/physx/physxForceFieldShape.h b/panda/src/physx/physxForceFieldShape.h index e9e47cf510..3e6a43fe20 100644 --- a/panda/src/physx/physxForceFieldShape.h +++ b/panda/src/physx/physxForceFieldShape.h @@ -45,7 +45,7 @@ PUBLISHED: LPoint3f get_pos() const; INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; public: static PhysxForceFieldShape *factory(NxShapeType shapeType); @@ -59,7 +59,7 @@ protected: INLINE PhysxForceFieldShape(); private: - string _name; + std::string _name; public: static TypeHandle get_class_type() { diff --git a/panda/src/physx/physxForceFieldShapeDesc.h b/panda/src/physx/physxForceFieldShapeDesc.h index 1071f9dddc..fd5ab6dc1c 100644 --- a/panda/src/physx/physxForceFieldShapeDesc.h +++ b/panda/src/physx/physxForceFieldShapeDesc.h @@ -41,7 +41,7 @@ public: virtual NxForceFieldShapeDesc *ptr() const = 0; private: - string _name; + std::string _name; protected: INLINE PhysxForceFieldShapeDesc(); diff --git a/panda/src/physx/physxForceFieldShapeGroup.I b/panda/src/physx/physxForceFieldShapeGroup.I index 324b56b396..7d65ae2d18 100644 --- a/panda/src/physx/physxForceFieldShapeGroup.I +++ b/panda/src/physx/physxForceFieldShapeGroup.I @@ -40,7 +40,7 @@ ls() const { * */ INLINE void PhysxForceFieldShapeGroup:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type().get_name() << " " << _name diff --git a/panda/src/physx/physxForceFieldShapeGroup.cxx b/panda/src/physx/physxForceFieldShapeGroup.cxx index c0bb56b93d..8819fbfd19 100644 --- a/panda/src/physx/physxForceFieldShapeGroup.cxx +++ b/panda/src/physx/physxForceFieldShapeGroup.cxx @@ -60,7 +60,7 @@ unlink() { } // Unlink self - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxScene *scene = (PhysxScene *)_ptr->getScene().userData; @@ -77,7 +77,7 @@ release() { unlink(); _ptr->getScene().releaseForceFieldShapeGroup(*_ptr); - _ptr = NULL; + _ptr = nullptr; } /** @@ -86,7 +86,7 @@ release() { PhysxScene *PhysxForceFieldShapeGroup:: get_scene() const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); return (PhysxScene *)(_ptr->getScene().userData); } @@ -97,10 +97,10 @@ get_scene() const { PhysxForceField *PhysxForceFieldShapeGroup:: get_force_field() const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); - if (_ptr->getForceField() == NULL) { - return NULL; + if (_ptr->getForceField() == nullptr) { + return nullptr; } else { return (PhysxForceField *)(_ptr->getForceField()->userData); @@ -157,14 +157,14 @@ get_num_shapes() const { PhysxForceFieldShape *PhysxForceFieldShapeGroup:: create_shape(PhysxForceFieldShapeDesc &desc) { - nassertr(_error_type == ET_ok, NULL); - nassertr(desc.is_valid(),NULL); + nassertr(_error_type == ET_ok, nullptr); + nassertr(desc.is_valid(),nullptr); PhysxForceFieldShape *shape = PhysxForceFieldShape::factory(desc.ptr()->getType()); - nassertr(shape, NULL); + nassertr(shape, nullptr); NxForceFieldShape *shapePtr = _ptr->createShape(*desc.ptr()); - nassertr(shapePtr, NULL); + nassertr(shapePtr, nullptr); shape->link(shapePtr); @@ -177,8 +177,8 @@ create_shape(PhysxForceFieldShapeDesc &desc) { PhysxForceFieldShape *PhysxForceFieldShapeGroup:: get_shape(unsigned int idx) const { - nassertr(_error_type == ET_ok, NULL); - nassertr_always(idx < _ptr->getNbShapes(), NULL); + nassertr(_error_type == ET_ok, nullptr); + nassertr_always(idx < _ptr->getNbShapes(), nullptr); NxForceFieldShape *shapePtr; NxU32 nShapes = _ptr->getNbShapes(); diff --git a/panda/src/physx/physxForceFieldShapeGroup.h b/panda/src/physx/physxForceFieldShapeGroup.h index b03e34cfe9..c23b6de828 100644 --- a/panda/src/physx/physxForceFieldShapeGroup.h +++ b/panda/src/physx/physxForceFieldShapeGroup.h @@ -54,7 +54,7 @@ PUBLISHED: void release(); INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; public: INLINE NxForceFieldShapeGroup *ptr() const { return _ptr; }; @@ -66,7 +66,7 @@ public: private: NxForceFieldShapeGroup *_ptr; - string _name; + std::string _name; public: static TypeHandle get_class_type() { diff --git a/panda/src/physx/physxForceFieldShapeGroupDesc.h b/panda/src/physx/physxForceFieldShapeGroupDesc.h index 1f4a9a3206..fab6c8d0f5 100644 --- a/panda/src/physx/physxForceFieldShapeGroupDesc.h +++ b/panda/src/physx/physxForceFieldShapeGroupDesc.h @@ -45,7 +45,7 @@ public: NxForceFieldShapeGroupDesc _desc; private: - string _name; + std::string _name; }; #include "physxForceFieldShapeGroupDesc.I" diff --git a/panda/src/physx/physxGroupsMask.cxx b/panda/src/physx/physxGroupsMask.cxx index e16497350e..6591ab2583 100644 --- a/panda/src/physx/physxGroupsMask.cxx +++ b/panda/src/physx/physxGroupsMask.cxx @@ -13,6 +13,8 @@ #include "physxGroupsMask.h" +using std::string; + /** * Returns a PhysxGroupsMask whose bits are all on. */ @@ -120,7 +122,7 @@ get_bit(unsigned int idx) const { * Writes the PhysxGroupsMask out as a list of ones and zeros. */ void PhysxGroupsMask:: -output(ostream &out) const { +output(std::ostream &out) const { string name0; string name1; diff --git a/panda/src/physx/physxGroupsMask.h b/panda/src/physx/physxGroupsMask.h index 2383a2675d..bd1bfb129b 100644 --- a/panda/src/physx/physxGroupsMask.h +++ b/panda/src/physx/physxGroupsMask.h @@ -32,7 +32,7 @@ PUBLISHED: void clear_bit(unsigned int idx); bool get_bit(unsigned int idx) const; - void output(ostream &out) const; + void output(std::ostream &out) const; static PhysxGroupsMask all_on(); static PhysxGroupsMask all_off(); @@ -54,7 +54,7 @@ public: NxGroupsMask _mask; }; -INLINE ostream &operator << (ostream &out, const PhysxGroupsMask &mask) { +INLINE std::ostream &operator << (std::ostream &out, const PhysxGroupsMask &mask) { mask.output(out); return out; } diff --git a/panda/src/physx/physxHeightField.I b/panda/src/physx/physxHeightField.I index e06fb3425e..1f71266a8f 100644 --- a/panda/src/physx/physxHeightField.I +++ b/panda/src/physx/physxHeightField.I @@ -40,7 +40,7 @@ ls() const { * */ INLINE void PhysxHeightField:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type().get_name() << " (at 0x" << this << ")\n"; diff --git a/panda/src/physx/physxHeightField.cxx b/panda/src/physx/physxHeightField.cxx index b4885a1b26..4234eaf9e6 100644 --- a/panda/src/physx/physxHeightField.cxx +++ b/panda/src/physx/physxHeightField.cxx @@ -46,7 +46,7 @@ release() { unlink(); NxGetPhysicsSDK()->releaseHeightField(*_ptr); - _ptr = NULL; + _ptr = nullptr; } /** diff --git a/panda/src/physx/physxHeightField.h b/panda/src/physx/physxHeightField.h index 4449e09022..3741533d1b 100644 --- a/panda/src/physx/physxHeightField.h +++ b/panda/src/physx/physxHeightField.h @@ -49,7 +49,7 @@ PUBLISHED: float get_height(float x, float y) const; INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; public: INLINE PhysxHeightField(); diff --git a/panda/src/physx/physxHeightFieldDesc.I b/panda/src/physx/physxHeightFieldDesc.I index e6870dd4cb..daf9ebc58c 100644 --- a/panda/src/physx/physxHeightFieldDesc.I +++ b/panda/src/physx/physxHeightFieldDesc.I @@ -17,7 +17,7 @@ INLINE PhysxHeightFieldDesc:: PhysxHeightFieldDesc() { - _samples = NULL; + _samples = nullptr; _desc.setToDefault(); } @@ -76,7 +76,7 @@ unset_size() { if (_samples) { _desc.nbRows = (NxU32) 0; _desc.nbColumns = (NxU32) 0; - _desc.samples = NULL; + _desc.samples = nullptr; delete[] _samples; } } diff --git a/panda/src/physx/physxHeightFieldShape.cxx b/panda/src/physx/physxHeightFieldShape.cxx index 21d0f6f81f..87b8ef7581 100644 --- a/panda/src/physx/physxHeightFieldShape.cxx +++ b/panda/src/physx/physxHeightFieldShape.cxx @@ -38,7 +38,7 @@ link(NxShape *shapePtr) { void PhysxHeightFieldShape:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxActor *actor = (PhysxActor *)_ptr->getActor().userData; diff --git a/panda/src/physx/physxJoint.I b/panda/src/physx/physxJoint.I index 1acb52d01d..663f2b3253 100644 --- a/panda/src/physx/physxJoint.I +++ b/panda/src/physx/physxJoint.I @@ -32,7 +32,7 @@ ls() const { * */ INLINE void PhysxJoint:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type().get_name() << " " << _name diff --git a/panda/src/physx/physxJoint.cxx b/panda/src/physx/physxJoint.cxx index 0217d43849..0af47ee6e0 100644 --- a/panda/src/physx/physxJoint.cxx +++ b/panda/src/physx/physxJoint.cxx @@ -80,7 +80,7 @@ factory(NxJointType shapeType) { } physx_cat.error() << "Unknown joint type.\n"; - return NULL; + return nullptr; } /** @@ -112,8 +112,8 @@ get_name() const { PhysxActor *PhysxJoint:: get_actor(unsigned int idx) const { - nassertr_always(idx < 2, NULL); - nassertr(_error_type == ET_ok, NULL); + nassertr_always(idx < 2, nullptr); + nassertr(_error_type == ET_ok, nullptr); NxActor *actorPtr[2]; ptr()->getActors(&actorPtr[0], &actorPtr[1]); @@ -126,7 +126,7 @@ get_actor(unsigned int idx) const { PhysxScene *PhysxJoint:: get_scene() const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); return (PhysxScene *)(ptr()->getScene().userData); } diff --git a/panda/src/physx/physxJoint.h b/panda/src/physx/physxJoint.h index 25b623c2bc..adb536e2fb 100644 --- a/panda/src/physx/physxJoint.h +++ b/panda/src/physx/physxJoint.h @@ -55,7 +55,7 @@ PUBLISHED: bool get_use_acceleration_spring() const; INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; public: static PhysxJoint *factory(NxJointType shapeType); @@ -69,7 +69,7 @@ protected: INLINE PhysxJoint(); private: - string _name; + std::string _name; public: static TypeHandle get_class_type() { diff --git a/panda/src/physx/physxJointDesc.cxx b/panda/src/physx/physxJointDesc.cxx index fec3e3f791..dc0eeb1196 100644 --- a/panda/src/physx/physxJointDesc.cxx +++ b/panda/src/physx/physxJointDesc.cxx @@ -208,11 +208,11 @@ get_joint_flag(const PhysxJointFlag flag) const { PhysxActor *PhysxJointDesc:: get_actor(unsigned int idx) const { - nassertr_always(idx < 2, NULL); + nassertr_always(idx < 2, nullptr); NxActor *actorPtr = ptr()->actor[idx]; - if (actorPtr == NULL) { - return NULL; + if (actorPtr == nullptr) { + return nullptr; } else { return (PhysxActor *)(actorPtr->userData); diff --git a/panda/src/physx/physxJointDesc.h b/panda/src/physx/physxJointDesc.h index 9f24e5a214..b123dd81e2 100644 --- a/panda/src/physx/physxJointDesc.h +++ b/panda/src/physx/physxJointDesc.h @@ -57,7 +57,7 @@ public: virtual NxJointDesc *ptr() const = 0; private: - string _name; + std::string _name; protected: INLINE PhysxJointDesc(); diff --git a/panda/src/physx/physxKitchen.cxx b/panda/src/physx/physxKitchen.cxx index 144e6b2cbe..8dda747eaa 100644 --- a/panda/src/physx/physxKitchen.cxx +++ b/panda/src/physx/physxKitchen.cxx @@ -151,20 +151,20 @@ cook_texcoords(const PhysxClothMeshDesc &meshDesc, const Filename &filename) { PhysxConvexMesh *PhysxKitchen:: cook_convex_mesh(const PhysxConvexMeshDesc &meshDesc) { - nassertr_always(meshDesc.is_valid(), NULL); + nassertr_always(meshDesc.is_valid(), nullptr); PhysxMemoryWriteBuffer buffer; bool status = _cooking->NxCookConvexMesh(meshDesc.get_desc(), buffer); - nassertr(status, NULL); + nassertr(status, nullptr); NxPhysicsSDK *sdk = NxGetPhysicsSDK(); - nassertr(sdk, NULL); + nassertr(sdk, nullptr); PhysxConvexMesh *mesh = new PhysxConvexMesh(); - nassertr(mesh, NULL); + nassertr(mesh, nullptr); NxConvexMesh *meshPtr = sdk->createConvexMesh(PhysxMemoryReadBuffer(buffer.data)); - nassertr(meshPtr, NULL); + nassertr(meshPtr, nullptr); mesh->link(meshPtr); @@ -177,20 +177,20 @@ cook_convex_mesh(const PhysxConvexMeshDesc &meshDesc) { PhysxTriangleMesh *PhysxKitchen:: cook_triangle_mesh(const PhysxTriangleMeshDesc &meshDesc) { - nassertr_always(meshDesc.is_valid(), NULL); + nassertr_always(meshDesc.is_valid(), nullptr); PhysxMemoryWriteBuffer buffer; bool status = _cooking->NxCookTriangleMesh(meshDesc.get_desc(), buffer); - nassertr(status, NULL); + nassertr(status, nullptr); NxPhysicsSDK *sdk = NxGetPhysicsSDK(); - nassertr(sdk, NULL); + nassertr(sdk, nullptr); PhysxTriangleMesh *mesh = new PhysxTriangleMesh(); - nassertr(mesh, NULL); + nassertr(mesh, nullptr); NxTriangleMesh *meshPtr = sdk->createTriangleMesh(PhysxMemoryReadBuffer(buffer.data)); - nassertr(meshPtr, NULL); + nassertr(meshPtr, nullptr); mesh->link(meshPtr); @@ -203,21 +203,21 @@ cook_triangle_mesh(const PhysxTriangleMeshDesc &meshDesc) { PhysxClothMesh *PhysxKitchen:: cook_cloth_mesh(const PhysxClothMeshDesc &meshDesc) { - nassertr_always(meshDesc.is_valid(), NULL); + nassertr_always(meshDesc.is_valid(), nullptr); PhysxMemoryWriteBuffer wbuffer; bool status = _cooking->NxCookClothMesh(meshDesc.get_desc(), wbuffer); - nassertr(status, NULL); + nassertr(status, nullptr); NxPhysicsSDK *sdk = NxGetPhysicsSDK(); - nassertr(sdk, NULL); + nassertr(sdk, nullptr); PhysxClothMesh *mesh = new PhysxClothMesh(); - nassertr(mesh, NULL); + nassertr(mesh, nullptr); PhysxMemoryReadBuffer rbuffer(wbuffer.data); NxClothMesh *meshPtr = sdk->createClothMesh(rbuffer); - nassertr(meshPtr, NULL); + nassertr(meshPtr, nullptr); mesh->link(meshPtr); @@ -230,21 +230,21 @@ cook_cloth_mesh(const PhysxClothMeshDesc &meshDesc) { PhysxSoftBodyMesh *PhysxKitchen:: cook_soft_body_mesh(const PhysxSoftBodyMeshDesc &meshDesc) { - nassertr_always(meshDesc.is_valid(), NULL); + nassertr_always(meshDesc.is_valid(), nullptr); PhysxMemoryWriteBuffer wbuffer; bool status = _cooking->NxCookSoftBodyMesh(meshDesc.get_desc(), wbuffer); - nassertr(status, NULL); + nassertr(status, nullptr); NxPhysicsSDK *sdk = NxGetPhysicsSDK(); - nassertr(sdk, NULL); + nassertr(sdk, nullptr); PhysxSoftBodyMesh *mesh = new PhysxSoftBodyMesh(); - nassertr(mesh, NULL); + nassertr(mesh, nullptr); PhysxMemoryReadBuffer rbuffer(wbuffer.data); NxSoftBodyMesh *meshPtr = sdk->createSoftBodyMesh(rbuffer); - nassertr(meshPtr, NULL); + nassertr(meshPtr, nullptr); mesh->link(meshPtr); diff --git a/panda/src/physx/physxLinearInterpolationValues.cxx b/panda/src/physx/physxLinearInterpolationValues.cxx index 346d30508f..45cd603c64 100644 --- a/panda/src/physx/physxLinearInterpolationValues.cxx +++ b/panda/src/physx/physxLinearInterpolationValues.cxx @@ -32,8 +32,8 @@ insert(float index, float value) { _min = _max = index; } else { - _min = min(_min, index); - _max = max(_max, index); + _min = std::min(_min, index); + _max = std::max(_max, index); } _map[index] = value; } @@ -106,11 +106,11 @@ get_value_at_index(int index) const { * */ void PhysxLinearInterpolationValues:: -output(ostream &out) const { +output(std::ostream &out) const { MapType::const_iterator it = _map.begin(); for (; it != _map.end(); ++it) { - cout << it->first << " -> " << it->second << "\n"; + std::cout << it->first << " -> " << it->second << "\n"; } } diff --git a/panda/src/physx/physxLinearInterpolationValues.h b/panda/src/physx/physxLinearInterpolationValues.h index 4770393e34..9bc5acb4d7 100644 --- a/panda/src/physx/physxLinearInterpolationValues.h +++ b/panda/src/physx/physxLinearInterpolationValues.h @@ -28,7 +28,7 @@ public: INLINE PhysxLinearInterpolationValues(); INLINE ~PhysxLinearInterpolationValues(); - void output(ostream &out) const; + void output(std::ostream &out) const; void clear(); void insert(float index, float value); @@ -45,7 +45,7 @@ private: MapType _map; }; -INLINE ostream &operator << (ostream &out, const PhysxLinearInterpolationValues &values) { +INLINE std::ostream &operator << (std::ostream &out, const PhysxLinearInterpolationValues &values) { values.output(out); return out; } diff --git a/panda/src/physx/physxManager.I b/panda/src/physx/physxManager.I index f6011a7e43..c1bc8a59c9 100644 --- a/panda/src/physx/physxManager.I +++ b/panda/src/physx/physxManager.I @@ -192,7 +192,7 @@ ls() const { * */ INLINE void PhysxManager:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { indent(out, indent_level) << "PhysxManager\n"; diff --git a/panda/src/physx/physxManager.cxx b/panda/src/physx/physxManager.cxx index 297bbbaed4..1bba65c280 100644 --- a/panda/src/physx/physxManager.cxx +++ b/panda/src/physx/physxManager.cxx @@ -15,6 +15,8 @@ #include "physxScene.h" #include "physxSceneDesc.h" +using std::endl; + PhysxManager *PhysxManager::_global_ptr; PhysxManager::PhysxOutputStream PhysxManager::_outputStream; @@ -28,7 +30,7 @@ PhysxManager() { NxSDKCreateError error; NxPhysicsSDKDesc desc = NxPhysicsSDKDesc(); - _sdk = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, &_outputStream, desc, &error); + _sdk = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, nullptr, &_outputStream, desc, &error); if (error == NXCE_NO_ERROR) { physx_cat.info() << "PhysX subsystem initialized. Number of PPUs=" @@ -37,7 +39,7 @@ PhysxManager() { else { physx_cat.error() << "Error when setting up the PhysX subsystem: " << get_sdk_error_string(error) << endl; - _sdk = NULL; + _sdk = nullptr; } nassertv_always(error == NXCE_NO_ERROR); @@ -95,12 +97,12 @@ PhysxManager:: PhysxManager *PhysxManager:: get_global_ptr() { - if (_global_ptr == (PhysxManager *)NULL) { + if (_global_ptr == nullptr) { _global_ptr = new PhysxManager; } - if (_global_ptr->_sdk == NULL) { - return NULL; + if (_global_ptr->_sdk == nullptr) { + return nullptr; } else { return _global_ptr; @@ -122,7 +124,7 @@ get_num_scenes() const { PhysxScene *PhysxManager:: create_scene(PhysxSceneDesc &sceneDesc) { - nassertr(sceneDesc.is_valid(),NULL); + nassertr(sceneDesc.is_valid(),nullptr); // _desc.timeStepMethod = NX_TIMESTEP_FIXED; _desc.maxTimestep = 1.0f // 240.0f; _desc.maxIter = 8; @@ -139,10 +141,10 @@ create_scene(PhysxSceneDesc &sceneDesc) { } PhysxScene *scene = new PhysxScene(); - nassertr(scene, NULL); + nassertr(scene, nullptr); NxScene *scenePtr = _sdk->createScene(sceneDesc._desc); - nassertr(scenePtr, NULL); + nassertr(scenePtr, nullptr); scene->link(scenePtr); @@ -155,7 +157,7 @@ create_scene(PhysxSceneDesc &sceneDesc) { PhysxScene *PhysxManager:: get_scene(unsigned int idx) const { - nassertr_always(idx < _sdk->getNbScenes(), NULL); + nassertr_always(idx < _sdk->getNbScenes(), nullptr); NxScene *scenePtr = _sdk->getScene(idx); PhysxScene *scene = (PhysxScene *)(scenePtr->userData); @@ -178,13 +180,13 @@ get_num_height_fields() { PhysxHeightField *PhysxManager:: create_height_field(PhysxHeightFieldDesc &desc) { - nassertr(desc.is_valid(),NULL); + nassertr(desc.is_valid(),nullptr); PhysxHeightField *hf = new PhysxHeightField(); - nassertr(hf, NULL); + nassertr(hf, nullptr); NxHeightField *hfPtr = _sdk->createHeightField(desc._desc); - nassertr(hfPtr, NULL); + nassertr(hfPtr, nullptr); hf->link(hfPtr); @@ -197,7 +199,7 @@ create_height_field(PhysxHeightFieldDesc &desc) { PhysxHeightField *PhysxManager:: get_height_field(unsigned int idx) { - nassertr_always(idx < _sdk->getNbHeightFields(), NULL); + nassertr_always(idx < _sdk->getNbHeightFields(), nullptr); return (PhysxHeightField *)_heightfields[idx]; } @@ -217,7 +219,7 @@ get_num_convex_meshes() { PhysxConvexMesh *PhysxManager:: get_convex_mesh(unsigned int idx) { - nassertr_always(idx < _sdk->getNbConvexMeshes(), NULL); + nassertr_always(idx < _sdk->getNbConvexMeshes(), nullptr); return (PhysxConvexMesh *)_convex_meshes[idx]; } @@ -237,7 +239,7 @@ get_num_triangle_meshes() { PhysxTriangleMesh *PhysxManager:: get_triangle_mesh(unsigned int idx) { - nassertr_always(idx < _sdk->getNbTriangleMeshes(), NULL); + nassertr_always(idx < _sdk->getNbTriangleMeshes(), nullptr); return (PhysxTriangleMesh *)_triangle_meshes[idx]; } @@ -257,7 +259,7 @@ get_num_cloth_meshes() { PhysxClothMesh *PhysxManager:: get_cloth_mesh(unsigned int idx) { - nassertr_always(idx < _sdk->getNbClothMeshes(), NULL); + nassertr_always(idx < _sdk->getNbClothMeshes(), nullptr); return (PhysxClothMesh *)_cloth_meshes[idx]; } @@ -277,7 +279,7 @@ get_num_soft_body_meshes() { PhysxSoftBodyMesh *PhysxManager:: get_soft_body_mesh(unsigned int idx) { - nassertr_always(idx < _sdk->getNbSoftBodyMeshes(), NULL); + nassertr_always(idx < _sdk->getNbSoftBodyMeshes(), nullptr); return (PhysxSoftBodyMesh *)_softbody_meshes[idx]; } @@ -297,14 +299,14 @@ get_num_ccd_skeletons() { PhysxCcdSkeleton *PhysxManager:: create_ccd_skeleton(PhysxCcdSkeletonDesc &desc) { - nassertr(desc.is_valid(), NULL); - nassertr(desc.get_desc().numVertices < 64, NULL); + nassertr(desc.is_valid(), nullptr); + nassertr(desc.get_desc().numVertices < 64, nullptr); PhysxCcdSkeleton *skel = new PhysxCcdSkeleton(); - nassertr(skel, NULL); + nassertr(skel, nullptr); NxCCDSkeleton *skelPtr = _sdk->createCCDSkeleton(desc.get_desc()); - nassertr(skelPtr, NULL); + nassertr(skelPtr, nullptr); skel->link(skelPtr); @@ -317,7 +319,7 @@ create_ccd_skeleton(PhysxCcdSkeletonDesc &desc) { PhysxCcdSkeleton *PhysxManager:: get_ccd_skeleton(unsigned int idx) { - nassertr_always(idx < _sdk->getNbCCDSkeletons(), NULL); + nassertr_always(idx < _sdk->getNbCCDSkeletons(), nullptr); return (PhysxCcdSkeleton *)_ccd_skeletons[idx]; } @@ -364,7 +366,7 @@ get_internal_version() { v = _sdk->getInternalVersion(apiRev, descRev, branchId); - stringstream version; + std::stringstream version; version << "version:" << (unsigned int)v << " apiRef:" << (unsigned int)apiRev << " descRev:" << (unsigned int)descRev diff --git a/panda/src/physx/physxManager.h b/panda/src/physx/physxManager.h index 430bebd24f..ed5f0b79d5 100644 --- a/panda/src/physx/physxManager.h +++ b/panda/src/physx/physxManager.h @@ -89,7 +89,7 @@ PUBLISHED: MAKE_SEQ(get_ccd_skeletons, get_num_ccd_skeletons, get_ccd_skeleton); INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; public: INLINE NxPhysicsSDK *get_sdk() const; diff --git a/panda/src/physx/physxMask.cxx b/panda/src/physx/physxMask.cxx index f1e31437ea..b9f3437634 100644 --- a/panda/src/physx/physxMask.cxx +++ b/panda/src/physx/physxMask.cxx @@ -70,9 +70,9 @@ get_bit(unsigned int idx) const { * Writes the PhysxMask out as a list of ones and zeros. */ void PhysxMask:: -output(ostream &out) const { +output(std::ostream &out) const { - string name; + std::string name; for (int i=0; i<32; i++) { name += (_mask & (1 << i)) ? '1' : '0'; diff --git a/panda/src/physx/physxMask.h b/panda/src/physx/physxMask.h index 5843d18939..9117d875bf 100644 --- a/panda/src/physx/physxMask.h +++ b/panda/src/physx/physxMask.h @@ -31,7 +31,7 @@ PUBLISHED: void clear_bit(unsigned int idx); bool get_bit(unsigned int idx) const; - void output(ostream &out) const; + void output(std::ostream &out) const; static PhysxMask all_on(); static PhysxMask all_off(); @@ -43,7 +43,7 @@ private: NxU32 _mask; }; -INLINE ostream &operator << (ostream &out, const PhysxMask &mask) { +INLINE std::ostream &operator << (std::ostream &out, const PhysxMask &mask) { mask.output(out); return out; } diff --git a/panda/src/physx/physxMaterial.I b/panda/src/physx/physxMaterial.I index 22500d8a35..7bc1f46db4 100644 --- a/panda/src/physx/physxMaterial.I +++ b/panda/src/physx/physxMaterial.I @@ -40,7 +40,7 @@ ls() const { * */ INLINE void PhysxMaterial:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type().get_name() << " (at 0x" << this << ")\n"; diff --git a/panda/src/physx/physxMaterial.cxx b/panda/src/physx/physxMaterial.cxx index b583bcd000..11dedcacd4 100644 --- a/panda/src/physx/physxMaterial.cxx +++ b/panda/src/physx/physxMaterial.cxx @@ -39,7 +39,7 @@ void PhysxMaterial:: unlink() { // Unlink self - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxScene *scene = (PhysxScene *)_ptr->getScene().userData; @@ -56,7 +56,7 @@ release() { unlink(); _ptr->getScene().releaseMaterial(*_ptr); - _ptr = NULL; + _ptr = nullptr; } /** @@ -65,7 +65,7 @@ release() { PhysxScene *PhysxMaterial:: get_scene() const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); return (PhysxScene *)(_ptr->getScene().userData); } diff --git a/panda/src/physx/physxMaterial.h b/panda/src/physx/physxMaterial.h index c6e6b4d2d2..efbeaae9f6 100644 --- a/panda/src/physx/physxMaterial.h +++ b/panda/src/physx/physxMaterial.h @@ -74,7 +74,7 @@ PUBLISHED: PhysxCombineMode get_restitution_combine_mode() const; INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; PUBLISHED: void release(); diff --git a/panda/src/physx/physxMemoryWriteBuffer.cxx b/panda/src/physx/physxMemoryWriteBuffer.cxx index f690b1e327..0bede7e426 100644 --- a/panda/src/physx/physxMemoryWriteBuffer.cxx +++ b/panda/src/physx/physxMemoryWriteBuffer.cxx @@ -16,7 +16,7 @@ /** * */ -PhysxMemoryWriteBuffer::PhysxMemoryWriteBuffer() : currentSize(0), maxSize(0), data(NULL) +PhysxMemoryWriteBuffer::PhysxMemoryWriteBuffer() : currentSize(0), maxSize(0), data(nullptr) { } diff --git a/panda/src/physx/physxMeshPool.cxx b/panda/src/physx/physxMeshPool.cxx index 71fb20f495..155707cccb 100644 --- a/panda/src/physx/physxMeshPool.cxx +++ b/panda/src/physx/physxMeshPool.cxx @@ -32,12 +32,12 @@ bool PhysxMeshPool:: check_filename(const Filename &fn) { if (!(VirtualFileSystem::get_global_ptr()->exists(fn))) { - physx_cat.error() << "File does not exists: " << fn << endl; + physx_cat.error() << "File does not exists: " << fn << std::endl; return false; } if (!(VirtualFileSystem::get_global_ptr()->is_regular_file(fn))) { - physx_cat.error() << "Not a regular file: " << fn << endl; + physx_cat.error() << "Not a regular file: " << fn << std::endl; return false; } @@ -50,7 +50,7 @@ check_filename(const Filename &fn) { PhysxConvexMesh *PhysxMeshPool:: load_convex_mesh(const Filename &fn) { - if (!check_filename(fn)) return NULL; + if (!check_filename(fn)) return nullptr; PhysxConvexMesh *mesh; @@ -61,13 +61,13 @@ load_convex_mesh(const Filename &fn) { PhysxFileStream stream = PhysxFileStream(fn, true); mesh = new PhysxConvexMesh(); - nassertr_always(mesh, NULL); + nassertr_always(mesh, nullptr); NxPhysicsSDK *sdk = NxGetPhysicsSDK(); - nassertr_always(sdk, NULL); + nassertr_always(sdk, nullptr); meshPtr = sdk->createConvexMesh(stream); - nassertr_always(meshPtr, NULL); + nassertr_always(meshPtr, nullptr); mesh->link(meshPtr); @@ -87,7 +87,7 @@ load_convex_mesh(const Filename &fn) { PhysxTriangleMesh *PhysxMeshPool:: load_triangle_mesh(const Filename &fn) { - if (!check_filename(fn)) return NULL; + if (!check_filename(fn)) return nullptr; PhysxTriangleMesh *mesh; @@ -98,13 +98,13 @@ load_triangle_mesh(const Filename &fn) { PhysxFileStream stream = PhysxFileStream(fn, true); mesh = new PhysxTriangleMesh(); - nassertr_always(mesh, NULL); + nassertr_always(mesh, nullptr); NxPhysicsSDK *sdk = NxGetPhysicsSDK(); - nassertr_always(sdk, NULL); + nassertr_always(sdk, nullptr); meshPtr = sdk->createTriangleMesh(stream); - nassertr_always(meshPtr, NULL); + nassertr_always(meshPtr, nullptr); mesh->link(meshPtr); @@ -124,7 +124,7 @@ load_triangle_mesh(const Filename &fn) { PhysxClothMesh *PhysxMeshPool:: load_cloth_mesh(const Filename &fn) { - if (!check_filename(fn)) return NULL; + if (!check_filename(fn)) return nullptr; PhysxClothMesh *mesh; @@ -135,13 +135,13 @@ load_cloth_mesh(const Filename &fn) { PhysxFileStream stream = PhysxFileStream(fn, true); mesh = new PhysxClothMesh(); - nassertr_always(mesh, NULL); + nassertr_always(mesh, nullptr); NxPhysicsSDK *sdk = NxGetPhysicsSDK(); - nassertr_always(sdk, NULL); + nassertr_always(sdk, nullptr); meshPtr = sdk->createClothMesh(stream); - nassertr_always(meshPtr, NULL); + nassertr_always(meshPtr, nullptr); mesh->link(meshPtr); @@ -161,7 +161,7 @@ load_cloth_mesh(const Filename &fn) { PhysxSoftBodyMesh *PhysxMeshPool:: load_soft_body_mesh(const Filename &fn) { - if (!check_filename(fn)) return NULL; + if (!check_filename(fn)) return nullptr; PhysxSoftBodyMesh *mesh; @@ -172,13 +172,13 @@ load_soft_body_mesh(const Filename &fn) { PhysxFileStream stream = PhysxFileStream(fn, true); mesh = new PhysxSoftBodyMesh(); - nassertr_always(mesh, NULL); + nassertr_always(mesh, nullptr); NxPhysicsSDK *sdk = NxGetPhysicsSDK(); - nassertr_always(sdk, NULL); + nassertr_always(sdk, nullptr); meshPtr = sdk->createSoftBodyMesh(stream); - nassertr_always(meshPtr, NULL); + nassertr_always(meshPtr, nullptr); mesh->link(meshPtr); @@ -272,7 +272,7 @@ list_contents() { * */ void PhysxMeshPool:: -list_contents(ostream &out) { +list_contents(std::ostream &out) { out << "PhysX mesh pool contents:\n"; @@ -285,7 +285,7 @@ list_contents(ostream &out) { out << " " << fn.get_fullpath() << " (convex mesh, " << mesh->ptr()->getReferenceCount() - << " references)" << endl; + << " references)" << std::endl; } } diff --git a/panda/src/physx/physxMeshPool.h b/panda/src/physx/physxMeshPool.h index 30bec8141b..b66d06df7c 100644 --- a/panda/src/physx/physxMeshPool.h +++ b/panda/src/physx/physxMeshPool.h @@ -50,7 +50,7 @@ PUBLISHED: static bool release_soft_body_mesh(PhysxSoftBodyMesh *mesh); static void list_contents(); - static void list_contents(ostream &out); + static void list_contents(std::ostream &out); private: static bool check_filename(const Filename &fn); diff --git a/panda/src/physx/physxObject.I b/panda/src/physx/physxObject.I index 844aefd182..b2331f23d1 100644 --- a/panda/src/physx/physxObject.I +++ b/panda/src/physx/physxObject.I @@ -50,11 +50,11 @@ has_python_tags() const { * */ INLINE void PhysxObject:: -set_python_tag(const string &key, PyObject *value) { +set_python_tag(const std::string &key, PyObject *value) { Py_XINCREF(value); - pair result; + std::pair result; result = _python_tag_data.insert(PythonTagData::value_type(key, value)); if (!result.second) { @@ -72,7 +72,7 @@ set_python_tag(const string &key, PyObject *value) { * */ INLINE PyObject *PhysxObject:: -get_python_tag(const string &key) const { +get_python_tag(const std::string &key) const { PythonTagData::const_iterator ti; ti = _python_tag_data.find(key); @@ -91,7 +91,7 @@ get_python_tag(const string &key) const { * */ INLINE bool PhysxObject:: -has_python_tag(const string &key) const { +has_python_tag(const std::string &key) const { PythonTagData::const_iterator ti; ti = _python_tag_data.find(key); @@ -102,7 +102,7 @@ has_python_tag(const string &key) const { * */ INLINE void PhysxObject:: -clear_python_tag(const string &key) { +clear_python_tag(const std::string &key) { PythonTagData::iterator ti; ti = _python_tag_data.find(key); diff --git a/panda/src/physx/physxObject.h b/panda/src/physx/physxObject.h index 717405736c..0a40cb66fb 100644 --- a/panda/src/physx/physxObject.h +++ b/panda/src/physx/physxObject.h @@ -29,16 +29,16 @@ class EXPCL_PANDAPHYSX PhysxObject : public TypedReferenceCount { #ifdef HAVE_PYTHON PUBLISHED: - INLINE void set_python_tag(const string &key, PyObject *value); - INLINE PyObject *get_python_tag(const string &key) const; - INLINE bool has_python_tag(const string &key) const; - INLINE void clear_python_tag(const string &key); + INLINE void set_python_tag(const std::string &key, PyObject *value); + INLINE PyObject *get_python_tag(const std::string &key) const; + INLINE bool has_python_tag(const std::string &key) const; + INLINE void clear_python_tag(const std::string &key); INLINE bool has_python_tags() const; #endif // HAVE_PYTHON PUBLISHED: virtual void ls() const = 0; - virtual void ls(ostream &out, int indent_level=0) const = 0; + virtual void ls(std::ostream &out, int indent_level=0) const = 0; protected: INLINE PhysxObject(); @@ -55,7 +55,7 @@ protected: #ifdef HAVE_PYTHON private: - typedef phash_map PythonTagData; + typedef phash_map PythonTagData; PythonTagData _python_tag_data; #endif // HAVE_PYTHON diff --git a/panda/src/physx/physxObjectCollection.I b/panda/src/physx/physxObjectCollection.I index 128d031bfc..54137cec40 100644 --- a/panda/src/physx/physxObjectCollection.I +++ b/panda/src/physx/physxObjectCollection.I @@ -46,7 +46,7 @@ remove(PT(T) object) { } else { - physx_cat.warning() << "object not found in collection" << endl; + physx_cat.warning() << "object not found in collection" << std::endl; } } @@ -58,7 +58,7 @@ template INLINE T *PhysxObjectCollection:: get(unsigned int index) const { - nassertr(index < _objects.size(), NULL); + nassertr(index < _objects.size(), nullptr); return _objects[index]; } @@ -70,7 +70,7 @@ template INLINE T *PhysxObjectCollection:: operator [] (unsigned int index) const { - nassertr(index < _objects.size(), NULL); + nassertr(index < _objects.size(), nullptr); return _objects[index]; } @@ -89,7 +89,7 @@ ls() const { */ template INLINE void PhysxObjectCollection:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { for (unsigned int i=0; i < size(); i++) { get(i)->ls(out, indent_level + 2); diff --git a/panda/src/physx/physxObjectCollection.h b/panda/src/physx/physxObjectCollection.h index ace4799e57..77521de8aa 100644 --- a/panda/src/physx/physxObjectCollection.h +++ b/panda/src/physx/physxObjectCollection.h @@ -32,7 +32,7 @@ public: INLINE T *operator [] (unsigned int index) const; INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; private: pvector _objects; diff --git a/panda/src/physx/physxOverlapReport.cxx b/panda/src/physx/physxOverlapReport.cxx index dc5fafb431..4589740dc4 100644 --- a/panda/src/physx/physxOverlapReport.cxx +++ b/panda/src/physx/physxOverlapReport.cxx @@ -58,7 +58,7 @@ get_next_overlap() { } // No more items. Return empty overlap. - return NULL; + return nullptr; } /** @@ -67,6 +67,6 @@ get_next_overlap() { PhysxShape *PhysxOverlapReport:: get_overlap(unsigned int idx) { - nassertr(idx < get_num_overlaps(), NULL); + nassertr(idx < get_num_overlaps(), nullptr); return _overlaps[idx]; } diff --git a/panda/src/physx/physxPlaneShape.cxx b/panda/src/physx/physxPlaneShape.cxx index 49ce975f38..05a22a60f7 100644 --- a/panda/src/physx/physxPlaneShape.cxx +++ b/panda/src/physx/physxPlaneShape.cxx @@ -39,7 +39,7 @@ link(NxShape *shapePtr) { void PhysxPlaneShape:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxActor *actor = (PhysxActor *)_ptr->getActor().userData; diff --git a/panda/src/physx/physxPointInPlaneJoint.cxx b/panda/src/physx/physxPointInPlaneJoint.cxx index 34c4b0df42..fc05d6f8ca 100644 --- a/panda/src/physx/physxPointInPlaneJoint.cxx +++ b/panda/src/physx/physxPointInPlaneJoint.cxx @@ -38,7 +38,7 @@ link(NxJoint *jointPtr) { void PhysxPointInPlaneJoint:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxScene *scene = (PhysxScene *)_ptr->getScene().userData; diff --git a/panda/src/physx/physxPointOnLineJoint.cxx b/panda/src/physx/physxPointOnLineJoint.cxx index 1cdf84981f..5e5d4e8665 100644 --- a/panda/src/physx/physxPointOnLineJoint.cxx +++ b/panda/src/physx/physxPointOnLineJoint.cxx @@ -38,7 +38,7 @@ link(NxJoint *jointPtr) { void PhysxPointOnLineJoint:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxScene *scene = (PhysxScene *)_ptr->getScene().userData; diff --git a/panda/src/physx/physxPrismaticJoint.cxx b/panda/src/physx/physxPrismaticJoint.cxx index 9fd765c94f..94b9fd0949 100644 --- a/panda/src/physx/physxPrismaticJoint.cxx +++ b/panda/src/physx/physxPrismaticJoint.cxx @@ -38,7 +38,7 @@ link(NxJoint *jointPtr) { void PhysxPrismaticJoint:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxScene *scene = (PhysxScene *)_ptr->getScene().userData; diff --git a/panda/src/physx/physxPulleyJoint.cxx b/panda/src/physx/physxPulleyJoint.cxx index 3b98de1cef..0986774ae8 100644 --- a/panda/src/physx/physxPulleyJoint.cxx +++ b/panda/src/physx/physxPulleyJoint.cxx @@ -39,7 +39,7 @@ link(NxJoint *jointPtr) { void PhysxPulleyJoint:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxScene *scene = (PhysxScene *)_ptr->getScene().userData; diff --git a/panda/src/physx/physxRaycastHit.cxx b/panda/src/physx/physxRaycastHit.cxx index 30d983f0ea..5d2bce1737 100644 --- a/panda/src/physx/physxRaycastHit.cxx +++ b/panda/src/physx/physxRaycastHit.cxx @@ -21,7 +21,7 @@ bool PhysxRaycastHit:: is_empty() const { - return (_hit.shape == NULL); + return (_hit.shape == nullptr); } /** @@ -30,7 +30,7 @@ is_empty() const { PhysxShape *PhysxRaycastHit:: get_shape() const { - nassertr_always(_hit.shape, NULL); + nassertr_always(_hit.shape, nullptr); return (PhysxShape *)_hit.shape->userData; } diff --git a/panda/src/physx/physxRaycastReport.cxx b/panda/src/physx/physxRaycastReport.cxx index cb00d85b10..368c5a5c54 100644 --- a/panda/src/physx/physxRaycastReport.cxx +++ b/panda/src/physx/physxRaycastReport.cxx @@ -55,7 +55,7 @@ get_next_hit() { // No more items. Return an empty hit. NxRaycastHit hit; - hit.shape = NULL; + hit.shape = nullptr; return PhysxRaycastHit(hit); } @@ -69,7 +69,7 @@ get_hit(unsigned int idx) { { // Index out of bounds. Return an empty hit. NxRaycastHit hit; - hit.shape = NULL; + hit.shape = nullptr; return PhysxRaycastHit(hit); } diff --git a/panda/src/physx/physxRevoluteJoint.cxx b/panda/src/physx/physxRevoluteJoint.cxx index 5b3f9c5cde..43314ba157 100644 --- a/panda/src/physx/physxRevoluteJoint.cxx +++ b/panda/src/physx/physxRevoluteJoint.cxx @@ -41,7 +41,7 @@ link(NxJoint *jointPtr) { void PhysxRevoluteJoint:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxScene *scene = (PhysxScene *)_ptr->getScene().userData; @@ -242,7 +242,7 @@ set_limits(const PhysxJointLimitDesc &low, const PhysxJointLimitDesc &high) { PhysxMotorDesc PhysxRevoluteJoint:: get_motor() const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, PhysxMotorDesc(0)); PhysxMotorDesc value; _ptr->getMotor(value._desc); @@ -255,7 +255,7 @@ get_motor() const { PhysxSpringDesc PhysxRevoluteJoint:: get_spring() const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, PhysxSpringDesc(0)); PhysxSpringDesc value; _ptr->getSpring(value._desc); diff --git a/panda/src/physx/physxScene.I b/panda/src/physx/physxScene.I index d611cbe3db..482ebf829f 100644 --- a/panda/src/physx/physxScene.I +++ b/panda/src/physx/physxScene.I @@ -26,7 +26,7 @@ PhysxScene() : PhysxObject() { INLINE PhysxScene:: ~PhysxScene() { - _debugNode = NULL; + _debugNode = nullptr; } /** @@ -42,7 +42,7 @@ ls() const { * */ INLINE void PhysxScene:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type().get_name() << " (at 0x" << this << ")\n"; diff --git a/panda/src/physx/physxScene.cxx b/panda/src/physx/physxScene.cxx index e2623ef47a..b07a373729 100644 --- a/panda/src/physx/physxScene.cxx +++ b/panda/src/physx/physxScene.cxx @@ -157,7 +157,7 @@ unlink() { _cm->purgeControllers(); NxReleaseControllerManager(_cm); - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxManager::get_global_ptr()->_scenes.remove(this); @@ -174,7 +174,7 @@ release() { unlink(); NxPhysicsSDK *sdk = NxGetPhysicsSDK(); sdk->releaseScene(*_ptr); - _ptr = NULL; + _ptr = nullptr; } /** @@ -226,7 +226,7 @@ void PhysxScene:: fetch_results() { nassertv(_error_type == ET_ok); - nassertv(_ptr != NULL); + nassertv(_ptr != nullptr); _pcollector_fetch_results.start(); _ptr->fetchResults(NX_RIGID_BODY_FINISHED, true); @@ -354,14 +354,14 @@ get_num_actors() const { PhysxActor *PhysxScene:: create_actor(PhysxActorDesc &desc) { - nassertr(_error_type == ET_ok, NULL); - nassertr(desc.is_valid(), NULL); + nassertr(_error_type == ET_ok, nullptr); + nassertr(desc.is_valid(), nullptr); PhysxActor *actor = new PhysxActor(); - nassertr(actor, NULL); + nassertr(actor, nullptr); NxActor *actorPtr = _ptr->createActor(desc._desc); - nassertr(actorPtr, NULL); + nassertr(actorPtr, nullptr); actor->link(actorPtr); @@ -374,8 +374,8 @@ create_actor(PhysxActorDesc &desc) { PhysxActor *PhysxScene:: get_actor(unsigned int idx) const { - nassertr(_error_type == ET_ok, NULL); - nassertr_always(idx < _ptr->getNbActors(), NULL); + nassertr(_error_type == ET_ok, nullptr); + nassertr_always(idx < _ptr->getNbActors(), nullptr); NxActor *actorPtr = _ptr->getActors()[idx]; PhysxActor *actor = (PhysxActor *)(actorPtr->userData); @@ -395,7 +395,7 @@ get_actor(unsigned int idx) const { PhysxDebugGeomNode *PhysxScene:: get_debug_geom_node() { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); return _debugNode; } @@ -412,7 +412,7 @@ enable_contact_reporting(bool enabled) { _contact_report.enable(); } else { - _ptr->setUserContactReport(NULL); + _ptr->setUserContactReport(nullptr); _contact_report.disable(); } } @@ -441,7 +441,7 @@ enable_trigger_reporting(bool enabled) { _trigger_report.enable(); } else { - _ptr->setUserTriggerReport(NULL); + _ptr->setUserTriggerReport(nullptr); _trigger_report.disable(); } } @@ -510,14 +510,14 @@ get_num_materials() const { PhysxMaterial *PhysxScene:: create_material(PhysxMaterialDesc &desc) { - nassertr(_error_type == ET_ok, NULL); - nassertr(desc.is_valid(), NULL); + nassertr(_error_type == ET_ok, nullptr); + nassertr(desc.is_valid(), nullptr); PhysxMaterial *material = new PhysxMaterial(); - nassertr(material, NULL); + nassertr(material, nullptr); NxMaterial *materialPtr = _ptr->createMaterial(desc._desc); - nassertr(materialPtr, NULL); + nassertr(materialPtr, nullptr); material->link(materialPtr); @@ -531,15 +531,15 @@ create_material(PhysxMaterialDesc &desc) { PhysxMaterial *PhysxScene:: create_material() { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); PhysxMaterial *material = new PhysxMaterial(); - nassertr(material, NULL); + nassertr(material, nullptr); NxMaterialDesc desc; desc.setToDefault(); NxMaterial *materialPtr = _ptr->createMaterial(desc); - nassertr(materialPtr, NULL); + nassertr(materialPtr, nullptr); material->link(materialPtr); @@ -570,7 +570,7 @@ get_hightest_material_index() const { PhysxMaterial *PhysxScene:: get_material_from_index(unsigned int idx) const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); NxMaterial *materialPtr = _ptr->getMaterialFromIndex(idx); @@ -584,8 +584,8 @@ get_material_from_index(unsigned int idx) const { PhysxMaterial *PhysxScene:: get_material(unsigned int idx) const { - nassertr(_error_type == ET_ok, NULL); - nassertr_always(idx < _ptr->getNbMaterials(), NULL); + nassertr(_error_type == ET_ok, nullptr); + nassertr_always(idx < _ptr->getNbMaterials(), nullptr); NxU32 n = _ptr->getNbMaterials(); NxMaterial **materials = new NxMaterial *[n]; @@ -593,7 +593,7 @@ get_material(unsigned int idx) const { NxU32 iterator = 0; materialCount = _ptr->getMaterialArray(materials, n, iterator); - nassertr((materialCount == n), NULL); + nassertr((materialCount == n), nullptr); NxMaterial *materialPtr = materials[idx]; delete[] materials; @@ -618,17 +618,17 @@ get_num_controllers() const { PhysxController *PhysxScene:: create_controller(PhysxControllerDesc &desc) { - nassertr(_error_type == ET_ok, NULL); - nassertr(desc.is_valid(), NULL); + nassertr(_error_type == ET_ok, nullptr); + nassertr(desc.is_valid(), nullptr); PhysxController *controller = PhysxController::factory(desc.ptr()->getType()); - nassertr(controller, NULL); + nassertr(controller, nullptr); desc.ptr()->callback = &_controller_report; desc.ptr()->userData = controller; NxController *controllerPtr = _cm->createController(_ptr,*desc.ptr()); - nassertr(controllerPtr, NULL); + nassertr(controllerPtr, nullptr); controller->link(controllerPtr); controller->get_actor()->set_name(""); @@ -642,8 +642,8 @@ create_controller(PhysxControllerDesc &desc) { PhysxController *PhysxScene:: get_controller(unsigned int idx) const { - nassertr(_error_type == ET_ok, NULL); - nassertr_always(idx < _cm->getNbControllers(), NULL); + nassertr(_error_type == ET_ok, nullptr); + nassertr_always(idx < _cm->getNbControllers(), nullptr); NxController *controllerPtr = _cm->getController(idx); PhysxController *controller = (PhysxController *)(controllerPtr->getUserData()); @@ -668,14 +668,14 @@ get_num_joints() const { PhysxJoint *PhysxScene:: create_joint(PhysxJointDesc &desc) { - nassertr(_error_type == ET_ok, NULL); - nassertr(desc.is_valid(), NULL); + nassertr(_error_type == ET_ok, nullptr); + nassertr(desc.is_valid(), nullptr); PhysxJoint *joint = PhysxJoint::factory(desc.ptr()->getType()); - nassertr(joint, NULL); + nassertr(joint, nullptr); NxJoint *jointPtr = _ptr->createJoint(*desc.ptr()); - nassertr(jointPtr, NULL); + nassertr(jointPtr, nullptr); joint->link(jointPtr); @@ -688,8 +688,8 @@ create_joint(PhysxJointDesc &desc) { PhysxJoint *PhysxScene:: get_joint(unsigned int idx) const { - nassertr(_error_type == ET_ok, NULL); - nassertr_always(idx < _ptr->getNbJoints(), NULL); + nassertr(_error_type == ET_ok, nullptr); + nassertr_always(idx < _ptr->getNbJoints(), nullptr); NxJoint *jointPtr; NxU32 nJoints = _ptr->getNbJoints(); @@ -718,18 +718,18 @@ get_num_force_fields() const { PhysxForceField *PhysxScene:: create_force_field(PhysxForceFieldDesc &desc) { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); // Create the kernel desc.create_kernel(_ptr); - nassertr(desc.is_valid(), NULL); + nassertr(desc.is_valid(), nullptr); // Create the force field PhysxForceField *field = new PhysxForceField(); - nassertr(field, NULL); + nassertr(field, nullptr); NxForceField *fieldPtr = _ptr->createForceField(desc._desc); - nassertr(fieldPtr, NULL); + nassertr(fieldPtr, nullptr); field->link(fieldPtr); @@ -743,8 +743,8 @@ create_force_field(PhysxForceFieldDesc &desc) { PhysxForceField *PhysxScene:: get_force_field(unsigned int idx) const { - nassertr(_error_type == ET_ok, NULL); - nassertr_always(idx < _ptr->getNbForceFields(), NULL); + nassertr(_error_type == ET_ok, nullptr); + nassertr_always(idx < _ptr->getNbForceFields(), nullptr); NxForceField **fields = _ptr->getForceFields(); NxForceField *fieldPtr = fields[idx]; @@ -768,13 +768,13 @@ get_num_force_field_shape_groups() const { PhysxForceFieldShapeGroup *PhysxScene:: create_force_field_shape_group(PhysxForceFieldShapeGroupDesc &desc) { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); PhysxForceFieldShapeGroup *group = new PhysxForceFieldShapeGroup(); - nassertr(group, NULL); + nassertr(group, nullptr); NxForceFieldShapeGroup *groupPtr = _ptr->createForceFieldShapeGroup(desc._desc); - nassertr(groupPtr, NULL); + nassertr(groupPtr, nullptr); group->link(groupPtr); @@ -787,17 +787,17 @@ create_force_field_shape_group(PhysxForceFieldShapeGroupDesc &desc) { PhysxForceFieldShapeGroup *PhysxScene:: get_force_field_shape_group(unsigned int idx) const { - nassertr(_error_type == ET_ok, NULL); - nassertr_always(idx < _ptr->getNbForceFieldShapeGroups(), NULL); + nassertr(_error_type == ET_ok, nullptr); + nassertr_always(idx < _ptr->getNbForceFieldShapeGroups(), nullptr); _ptr->resetForceFieldShapeGroupsIterator(); - NxForceFieldShapeGroup *groupPtr = NULL; + NxForceFieldShapeGroup *groupPtr = nullptr; idx++; while (idx-- > 0) { groupPtr = _ptr->getNextForceFieldShapeGroup(); } - return groupPtr ? (PhysxForceFieldShapeGroup *)groupPtr->userData : NULL; + return groupPtr ? (PhysxForceFieldShapeGroup *)groupPtr->userData : nullptr; } /** @@ -816,13 +816,13 @@ get_num_cloths() const { PhysxCloth *PhysxScene:: create_cloth(PhysxClothDesc &desc) { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); PhysxCloth *cloth = new PhysxCloth(); - nassertr(cloth, NULL); + nassertr(cloth, nullptr); NxCloth *clothPtr = _ptr->createCloth(desc._desc); - nassertr(clothPtr, NULL); + nassertr(clothPtr, nullptr); cloth->link(clothPtr); @@ -835,8 +835,8 @@ create_cloth(PhysxClothDesc &desc) { PhysxCloth *PhysxScene:: get_cloth(unsigned int idx) const { - nassertr(_error_type == ET_ok, NULL); - nassertr_always(idx < _ptr->getNbCloths(), NULL); + nassertr(_error_type == ET_ok, nullptr); + nassertr_always(idx < _ptr->getNbCloths(), nullptr); NxCloth **cloths = _ptr->getCloths(); NxCloth *clothPtr = cloths[idx]; @@ -860,13 +860,13 @@ get_num_soft_bodies() const { PhysxSoftBody *PhysxScene:: create_soft_body(PhysxSoftBodyDesc &desc) { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); PhysxSoftBody *softbody = new PhysxSoftBody(); - nassertr(softbody, NULL); + nassertr(softbody, nullptr); NxSoftBody *softbodyPtr = _ptr->createSoftBody(desc._desc); - nassertr(softbodyPtr, NULL); + nassertr(softbodyPtr, nullptr); softbody->link(softbodyPtr); @@ -880,8 +880,8 @@ create_soft_body(PhysxSoftBodyDesc &desc) { PhysxSoftBody *PhysxScene:: get_soft_body(unsigned int idx) const { - nassertr(_error_type == ET_ok, NULL); - nassertr_always(idx < _ptr->getNbSoftBodies(), NULL); + nassertr(_error_type == ET_ok, nullptr); + nassertr_always(idx < _ptr->getNbSoftBodies(), nullptr); NxSoftBody **softbodies = _ptr->getSoftBodies(); NxSoftBody *softbodyPtr = softbodies[idx]; @@ -905,11 +905,11 @@ get_num_vehicles() const { PhysxVehicle *PhysxScene:: create_vehicle(PhysxVehicleDesc &desc) { - nassertr(_error_type == ET_ok, NULL); - nassertr(desc.is_valid(), NULL); + nassertr(_error_type == ET_ok, nullptr); + nassertr(desc.is_valid(), nullptr); PhysxVehicle *vehicle = new PhysxVehicle(); - nassertr(vehicle, NULL); + nassertr(vehicle, nullptr); vehicle->create(this, desc); @@ -922,8 +922,8 @@ create_vehicle(PhysxVehicleDesc &desc) { PhysxVehicle *PhysxScene:: get_vehicle(unsigned int idx) const { - nassertr(_error_type == ET_ok, NULL); - nassertr_always(idx < _vehicles.size(), NULL); + nassertr(_error_type == ET_ok, nullptr); + nassertr_always(idx < _vehicles.size(), nullptr); return _vehicles[idx]; } @@ -934,7 +934,7 @@ get_vehicle(unsigned int idx) const { PhysxSceneStats2 PhysxScene:: get_stats2() const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); return PhysxSceneStats2(_ptr->getStats2()); } @@ -949,7 +949,7 @@ raycast_any_shape(const PhysxRay &ray, nassertr(_error_type == ET_ok, false); - NxGroupsMask *groupsPtr = groups ? &(groups->_mask) : NULL; + NxGroupsMask *groupsPtr = groups ? &(groups->_mask) : nullptr; return _ptr->raycastAnyShape(ray._ray, (NxShapesType)shapesType, mask.get_mask(), ray._length, groupsPtr); @@ -969,7 +969,7 @@ raycast_closest_shape(const PhysxRay &ray, nassertr(_error_type == ET_ok, hit); - NxGroupsMask *groupsPtr = groups ? &(groups->_mask) : NULL; + NxGroupsMask *groupsPtr = groups ? &(groups->_mask) : nullptr; NxU32 hints = NX_RAYCAST_SHAPE | NX_RAYCAST_IMPACT | NX_RAYCAST_DISTANCE; if (smoothNormal == true) { @@ -1000,7 +1000,7 @@ raycast_all_shapes(const PhysxRay &ray, nassertr(_error_type == ET_ok, report); - NxGroupsMask *groupsPtr = groups ? &(groups->_mask) : NULL; + NxGroupsMask *groupsPtr = groups ? &(groups->_mask) : nullptr; NxU32 hints = NX_RAYCAST_SHAPE | NX_RAYCAST_IMPACT | NX_RAYCAST_DISTANCE; if (smoothNormal == true) { @@ -1028,7 +1028,7 @@ raycast_any_bounds(const PhysxRay &ray, nassertr(_error_type == ET_ok, false); - NxGroupsMask *groupsPtr = groups ? &(groups->_mask) : NULL; + NxGroupsMask *groupsPtr = groups ? &(groups->_mask) : nullptr; return _ptr->raycastAnyBounds(ray._ray, (NxShapesType)shapesType, mask.get_mask(), ray._length, groupsPtr); @@ -1046,7 +1046,7 @@ raycast_closest_bounds(const PhysxRay &ray, PhysxShapesType shapesType, PhysxMas nassertr(_error_type == ET_ok, hit); - NxGroupsMask *groupsPtr = groups ? &(groups->_mask) : NULL; + NxGroupsMask *groupsPtr = groups ? &(groups->_mask) : nullptr; NxU32 hints = NX_RAYCAST_SHAPE | NX_RAYCAST_IMPACT | NX_RAYCAST_DISTANCE; if (smoothNormal == true) { @@ -1078,7 +1078,7 @@ raycast_all_bounds(const PhysxRay &ray, nassertr(_error_type == ET_ok, report); - NxGroupsMask *groupsPtr = groups ? &(groups->_mask) : NULL; + NxGroupsMask *groupsPtr = groups ? &(groups->_mask) : nullptr; NxU32 hints = NX_RAYCAST_SHAPE | NX_RAYCAST_IMPACT | NX_RAYCAST_DISTANCE; if (smoothNormal == true) { @@ -1109,8 +1109,8 @@ overlap_sphere_shapes(const LPoint3f ¢er, float radius, NxSphere worldSphere(PhysxManager::point3_to_nxVec3(center), radius); - _ptr->overlapSphereShapes(worldSphere, (NxShapesType)shapesType, 0, NULL, &report, - mask.get_mask(), NULL, accurateCollision); + _ptr->overlapSphereShapes(worldSphere, (NxShapesType)shapesType, 0, nullptr, &report, + mask.get_mask(), nullptr, accurateCollision); return report; } @@ -1132,8 +1132,8 @@ overlap_capsule_shapes(const LPoint3f &p0, const LPoint3f &p1, float radius, PhysxManager::point3_to_nxVec3(p1)); NxCapsule worldCapsule(segment, radius); - _ptr->overlapCapsuleShapes(worldCapsule, (NxShapesType)shapesType, 0, NULL, &report, - mask.get_mask(), NULL, accurateCollision); + _ptr->overlapCapsuleShapes(worldCapsule, (NxShapesType)shapesType, 0, nullptr, &report, + mask.get_mask(), nullptr, accurateCollision); return report; } @@ -1541,9 +1541,9 @@ get_dominance_group_pair(unsigned int g1, unsigned int g2) { PhysxMaterial *PhysxScene:: get_wheel_shape_material() { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); - if (_wheelShapeMaterial == NULL) { + if (_wheelShapeMaterial == nullptr) { PhysxMaterialDesc materialDesc; materialDesc.set_flag(PhysxMaterialDesc::MF_disable_friction, true); _wheelShapeMaterial = create_material(materialDesc); diff --git a/panda/src/physx/physxScene.h b/panda/src/physx/physxScene.h index b26105c644..f8bf2b302b 100644 --- a/panda/src/physx/physxScene.h +++ b/panda/src/physx/physxScene.h @@ -157,32 +157,32 @@ PUBLISHED: bool raycast_any_shape(const PhysxRay &ray, PhysxShapesType shapesType=ST_all, PhysxMask mask=PhysxMask::all_on(), - PhysxGroupsMask *groups=NULL) const; + PhysxGroupsMask *groups=nullptr) const; PhysxRaycastHit raycast_closest_shape(const PhysxRay &ray, PhysxShapesType shapesType=ST_all, PhysxMask mask=PhysxMask::all_on(), - PhysxGroupsMask *groups=NULL, bool smoothNormal=true) const; + PhysxGroupsMask *groups=nullptr, bool smoothNormal=true) const; PhysxRaycastReport raycast_all_shapes(const PhysxRay &ray, PhysxShapesType shapesType=ST_all, PhysxMask mask=PhysxMask::all_on(), - PhysxGroupsMask *groups=NULL, bool smoothNormal=true) const; + PhysxGroupsMask *groups=nullptr, bool smoothNormal=true) const; bool raycast_any_bounds(const PhysxRay &ray, PhysxShapesType shapesType=ST_all, PhysxMask mask=PhysxMask::all_on(), - PhysxGroupsMask *groups=NULL) const; + PhysxGroupsMask *groups=nullptr) const; PhysxRaycastHit raycast_closest_bounds(const PhysxRay &ray, PhysxShapesType shapesType=ST_all, PhysxMask mask=PhysxMask::all_on(), - PhysxGroupsMask *groups=NULL, bool smoothNormal=true) const; + PhysxGroupsMask *groups=nullptr, bool smoothNormal=true) const; PhysxRaycastReport raycast_all_bounds(const PhysxRay &ray, PhysxShapesType shapesType=ST_all, PhysxMask mask=PhysxMask::all_on(), - PhysxGroupsMask *groups=NULL, bool smoothNormal=true) const; + PhysxGroupsMask *groups=nullptr, bool smoothNormal=true) const; // Overlap queries PhysxOverlapReport overlap_sphere_shapes(const LPoint3f ¢er, float radius, @@ -220,7 +220,7 @@ PUBLISHED: void release(); INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; public: INLINE NxScene *ptr() const { return _ptr; }; diff --git a/panda/src/physx/physxShape.I b/panda/src/physx/physxShape.I index 1aa796edab..110613ba2a 100644 --- a/panda/src/physx/physxShape.I +++ b/panda/src/physx/physxShape.I @@ -32,7 +32,7 @@ ls() const { * */ INLINE void PhysxShape:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type().get_name() << " " << _name diff --git a/panda/src/physx/physxShape.cxx b/panda/src/physx/physxShape.cxx index 926001f1be..0518f81d12 100644 --- a/panda/src/physx/physxShape.cxx +++ b/panda/src/physx/physxShape.cxx @@ -79,7 +79,7 @@ factory(NxShapeType shapeType) { } physx_cat.error() << "Unknown shape type.\n"; - return NULL; + return nullptr; } /** @@ -88,7 +88,7 @@ factory(NxShapeType shapeType) { PhysxActor *PhysxShape:: get_actor() const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); return (PhysxActor *)(ptr()->getActor().userData); } @@ -406,7 +406,7 @@ set_ccd_skeleton(PhysxCcdSkeleton *skel) { PhysxCcdSkeleton *PhysxShape:: get_ccd_skeleton() const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); return _skel; } diff --git a/panda/src/physx/physxShape.h b/panda/src/physx/physxShape.h index 660eecc211..fbfe01d988 100644 --- a/panda/src/physx/physxShape.h +++ b/panda/src/physx/physxShape.h @@ -72,7 +72,7 @@ PUBLISHED: PhysxRaycastHit raycast(const PhysxRay &worldRay, bool firstHit, bool smoothNormal) const; INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; public: static PhysxShape *factory(NxShapeType shapeType); @@ -86,7 +86,7 @@ protected: INLINE PhysxShape(); private: - string _name; + std::string _name; PT(PhysxCcdSkeleton) _skel; public: diff --git a/panda/src/physx/physxShapeDesc.h b/panda/src/physx/physxShapeDesc.h index 6ae7452a79..0ef063fe22 100644 --- a/panda/src/physx/physxShapeDesc.h +++ b/panda/src/physx/physxShapeDesc.h @@ -59,7 +59,7 @@ public: virtual NxShapeDesc *ptr() const = 0; private: - string _name; + std::string _name; protected: INLINE PhysxShapeDesc(); diff --git a/panda/src/physx/physxSoftBody.I b/panda/src/physx/physxSoftBody.I index de1a958608..cba8af0499 100644 --- a/panda/src/physx/physxSoftBody.I +++ b/panda/src/physx/physxSoftBody.I @@ -40,7 +40,7 @@ ls() const { * */ INLINE void PhysxSoftBody:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type().get_name() << " " << _name diff --git a/panda/src/physx/physxSoftBody.cxx b/panda/src/physx/physxSoftBody.cxx index 268a229502..1e5ed73685 100644 --- a/panda/src/physx/physxSoftBody.cxx +++ b/panda/src/physx/physxSoftBody.cxx @@ -45,13 +45,13 @@ void PhysxSoftBody:: unlink() { // Unlink self - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxScene *scene = (PhysxScene *)_ptr->getScene().userData; scene->_softbodies.remove(this); - _node = NULL; + _node = nullptr; } /** @@ -64,7 +64,7 @@ release() { unlink(); _ptr->getScene().releaseSoftBody(*_ptr); - _ptr = NULL; + _ptr = nullptr; } /** @@ -94,7 +94,7 @@ update() { PhysxScene *PhysxSoftBody:: get_scene() const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); return (PhysxScene *)_ptr->getScene().userData; } @@ -104,7 +104,7 @@ get_scene() const { PhysxSoftBodyNode *PhysxSoftBody:: get_soft_body_node() const { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); return _node; } @@ -114,7 +114,7 @@ get_soft_body_node() const { PhysxSoftBodyNode *PhysxSoftBody:: create_soft_body_node(const char *name) { - nassertr(_error_type == ET_ok, NULL); + nassertr(_error_type == ET_ok, nullptr); _node = new PhysxSoftBodyNode(name); _node->allocate(this); diff --git a/panda/src/physx/physxSoftBody.h b/panda/src/physx/physxSoftBody.h index 58020ed4a8..45416148c3 100644 --- a/panda/src/physx/physxSoftBody.h +++ b/panda/src/physx/physxSoftBody.h @@ -168,7 +168,7 @@ virtual void setForceFieldMaterial (NxForceFieldMaterial)=0 */ INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; public: void update(); @@ -185,7 +185,7 @@ public: private: NxSoftBody *_ptr; PT(PhysxSoftBodyNode) _node; - string _name; + std::string _name; public: static TypeHandle get_class_type() { diff --git a/panda/src/physx/physxSoftBodyDesc.h b/panda/src/physx/physxSoftBodyDesc.h index 550649a67f..10db3cabae 100644 --- a/panda/src/physx/physxSoftBodyDesc.h +++ b/panda/src/physx/physxSoftBodyDesc.h @@ -73,7 +73,7 @@ public: NxSoftBodyDesc _desc; private: - string _name; + std::string _name; }; #include "physxSoftBodyDesc.I" diff --git a/panda/src/physx/physxSoftBodyMesh.I b/panda/src/physx/physxSoftBodyMesh.I index fd2e3bfe26..314089dda6 100644 --- a/panda/src/physx/physxSoftBodyMesh.I +++ b/panda/src/physx/physxSoftBodyMesh.I @@ -40,7 +40,7 @@ ls() const { * */ INLINE void PhysxSoftBodyMesh:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type().get_name() << " (at 0x" << this << ")\n"; diff --git a/panda/src/physx/physxSoftBodyMesh.cxx b/panda/src/physx/physxSoftBodyMesh.cxx index 4cb0c9cc26..2f69f3d173 100644 --- a/panda/src/physx/physxSoftBodyMesh.cxx +++ b/panda/src/physx/physxSoftBodyMesh.cxx @@ -49,7 +49,7 @@ release() { unlink(); NxGetPhysicsSDK()->releaseSoftBodyMesh(*_ptr); - _ptr = NULL; + _ptr = nullptr; PhysxMeshPool::release_soft_body_mesh(this); } diff --git a/panda/src/physx/physxSoftBodyMesh.h b/panda/src/physx/physxSoftBodyMesh.h index ad6615b39e..1284582285 100644 --- a/panda/src/physx/physxSoftBodyMesh.h +++ b/panda/src/physx/physxSoftBodyMesh.h @@ -31,7 +31,7 @@ PUBLISHED: void release(); INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; public: INLINE PhysxSoftBodyMesh(); diff --git a/panda/src/physx/physxSoftBodyMeshDesc.I b/panda/src/physx/physxSoftBodyMeshDesc.I index 0cf5663cd7..0125b456ec 100644 --- a/panda/src/physx/physxSoftBodyMeshDesc.I +++ b/panda/src/physx/physxSoftBodyMeshDesc.I @@ -20,11 +20,11 @@ PhysxSoftBodyMeshDesc() { _desc.flags = 0; _desc.vertexStrideBytes = sizeof(NxVec3); _desc.tetrahedronStrideBytes = 4*sizeof(NxU32); - _desc.vertices = NULL; - _desc.tetrahedra = NULL; + _desc.vertices = nullptr; + _desc.tetrahedra = nullptr; - _vertices = NULL; - _tetrahedra = NULL; + _vertices = nullptr; + _tetrahedra = nullptr; } /** diff --git a/panda/src/physx/physxSphereForceFieldShape.cxx b/panda/src/physx/physxSphereForceFieldShape.cxx index 4f140de456..bb04de907a 100644 --- a/panda/src/physx/physxSphereForceFieldShape.cxx +++ b/panda/src/physx/physxSphereForceFieldShape.cxx @@ -38,7 +38,7 @@ link(NxForceFieldShape *shapePtr) { void PhysxSphereForceFieldShape:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxForceFieldShapeGroup *group = (PhysxForceFieldShapeGroup *)_ptr->getShapeGroup().userData; diff --git a/panda/src/physx/physxSphereShape.cxx b/panda/src/physx/physxSphereShape.cxx index 60d7f15425..a67a3b2062 100644 --- a/panda/src/physx/physxSphereShape.cxx +++ b/panda/src/physx/physxSphereShape.cxx @@ -38,7 +38,7 @@ link(NxShape *shapePtr) { void PhysxSphereShape:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxActor *actor = (PhysxActor *)_ptr->getActor().userData; diff --git a/panda/src/physx/physxSphericalJoint.cxx b/panda/src/physx/physxSphericalJoint.cxx index f1e8606ffa..3dabd9bfe4 100644 --- a/panda/src/physx/physxSphericalJoint.cxx +++ b/panda/src/physx/physxSphericalJoint.cxx @@ -38,7 +38,7 @@ link(NxJoint *jointPtr) { void PhysxSphericalJoint:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxScene *scene = (PhysxScene *)_ptr->getScene().userData; diff --git a/panda/src/physx/physxTriangleMesh.I b/panda/src/physx/physxTriangleMesh.I index 3b983f3893..d4e6a6e994 100644 --- a/panda/src/physx/physxTriangleMesh.I +++ b/panda/src/physx/physxTriangleMesh.I @@ -40,7 +40,7 @@ ls() const { * */ INLINE void PhysxTriangleMesh:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type().get_name() << " (at 0x" << this << ")\n"; diff --git a/panda/src/physx/physxTriangleMesh.cxx b/panda/src/physx/physxTriangleMesh.cxx index 80971a3f2e..2b3d81280c 100644 --- a/panda/src/physx/physxTriangleMesh.cxx +++ b/panda/src/physx/physxTriangleMesh.cxx @@ -49,7 +49,7 @@ release() { unlink(); NxGetPhysicsSDK()->releaseTriangleMesh(*_ptr); - _ptr = NULL; + _ptr = nullptr; PhysxMeshPool::release_triangle_mesh(this); } diff --git a/panda/src/physx/physxTriangleMesh.h b/panda/src/physx/physxTriangleMesh.h index bf2ef86301..691e012a3f 100644 --- a/panda/src/physx/physxTriangleMesh.h +++ b/panda/src/physx/physxTriangleMesh.h @@ -31,7 +31,7 @@ PUBLISHED: void release(); INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; public: INLINE PhysxTriangleMesh(); diff --git a/panda/src/physx/physxTriangleMeshDesc.I b/panda/src/physx/physxTriangleMeshDesc.I index 4acd6b09f9..e337b35d18 100644 --- a/panda/src/physx/physxTriangleMeshDesc.I +++ b/panda/src/physx/physxTriangleMeshDesc.I @@ -21,13 +21,13 @@ PhysxTriangleMeshDesc() { _desc.pointStrideBytes = sizeof(NxVec3); _desc.triangleStrideBytes = 3*sizeof(NxU32); _desc.materialIndexStride = sizeof(NxMaterialIndex); - _desc.points = NULL; - _desc.triangles = NULL; - _desc.materialIndices = NULL; + _desc.points = nullptr; + _desc.triangles = nullptr; + _desc.materialIndices = nullptr; - _vertices = NULL; - _triangles = NULL; - _materials = NULL; + _vertices = nullptr; + _triangles = nullptr; + _materials = nullptr; } /** diff --git a/panda/src/physx/physxTriangleMeshShape.cxx b/panda/src/physx/physxTriangleMeshShape.cxx index 954d0cf321..eaa57db4fc 100644 --- a/panda/src/physx/physxTriangleMeshShape.cxx +++ b/panda/src/physx/physxTriangleMeshShape.cxx @@ -38,7 +38,7 @@ link(NxShape *shapePtr) { void PhysxTriangleMeshShape:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxActor *actor = (PhysxActor *)_ptr->getActor().userData; diff --git a/panda/src/physx/physxUtilLib.I b/panda/src/physx/physxUtilLib.I index ff04f2a2c2..dcdcb328ae 100644 --- a/panda/src/physx/physxUtilLib.I +++ b/panda/src/physx/physxUtilLib.I @@ -26,5 +26,5 @@ PhysxUtilLib() { INLINE PhysxUtilLib:: ~PhysxUtilLib() { - _ptr = NULL; + _ptr = nullptr; } diff --git a/panda/src/physx/physxVehicle.I b/panda/src/physx/physxVehicle.I index 3be65f3a92..ed095f7211 100644 --- a/panda/src/physx/physxVehicle.I +++ b/panda/src/physx/physxVehicle.I @@ -40,7 +40,7 @@ ls() const { * */ INLINE void PhysxVehicle:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type().get_name() << " (at 0x" << this << ")\n"; diff --git a/panda/src/physx/physxVehicle.h b/panda/src/physx/physxVehicle.h index 78b358e667..15c3cb6bfa 100644 --- a/panda/src/physx/physxVehicle.h +++ b/panda/src/physx/physxVehicle.h @@ -41,7 +41,7 @@ PUBLISHED: //MAKE_SEQ(get_wheels, get_num_wheels, get_wheel); INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; private: diff --git a/panda/src/physx/physxWheel.I b/panda/src/physx/physxWheel.I index 71b43426fd..1aef97f663 100644 --- a/panda/src/physx/physxWheel.I +++ b/panda/src/physx/physxWheel.I @@ -40,7 +40,7 @@ ls() const { * */ INLINE void PhysxWheel:: -ls(ostream &out, int indent_level) const { +ls(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type().get_name() << " (at 0x" << this << ")\n"; diff --git a/panda/src/physx/physxWheel.h b/panda/src/physx/physxWheel.h index 84aa5a3acd..457962995c 100644 --- a/panda/src/physx/physxWheel.h +++ b/panda/src/physx/physxWheel.h @@ -40,7 +40,7 @@ PUBLISHED: //NodePath get_node_path() const; INLINE void ls() const; - INLINE void ls(ostream &out, int indent_level=0) const; + INLINE void ls(std::ostream &out, int indent_level=0) const; private: PT(PhysxWheelShape) _wheelShape; diff --git a/panda/src/physx/physxWheelShape.cxx b/panda/src/physx/physxWheelShape.cxx index de34bf760c..69a3e5d02a 100644 --- a/panda/src/physx/physxWheelShape.cxx +++ b/panda/src/physx/physxWheelShape.cxx @@ -39,7 +39,7 @@ link(NxShape *shapePtr) { void PhysxWheelShape:: unlink() { - _ptr->userData = NULL; + _ptr->userData = nullptr; _error_type = ET_released; PhysxActor *actor = (PhysxActor *)_ptr->getActor().userData; diff --git a/panda/src/pipeline/conditionVar.I b/panda/src/pipeline/conditionVar.I index d797ab2390..196e4283d0 100644 --- a/panda/src/pipeline/conditionVar.I +++ b/panda/src/pipeline/conditionVar.I @@ -27,44 +27,6 @@ ConditionVar(Mutex &mutex) : { } -/** - * - */ -INLINE ConditionVar:: -~ConditionVar() { -} - -/** - * Do not attempt to copy condition variables. - */ -INLINE ConditionVar:: -ConditionVar(const ConditionVar ©) : -#ifdef DEBUG_THREADS - ConditionVarDebug(copy.get_mutex()) -#else - ConditionVarDirect(copy.get_mutex()) -#endif // DEBUG_THREADS -{ - nassertv(false); -} - -/** - * Do not attempt to copy condition variables. - */ -INLINE void ConditionVar:: -operator = (const ConditionVar ©) { - nassertv(false); -} - -/** - * The notify_all() method is specifically *not* provided by ConditionVar. - * Use ConditionVarFull if you need to call this method. - */ -INLINE void ConditionVar:: -notify_all() { - nassertv(false); -} - /** * Returns the mutex associated with this condition variable. */ diff --git a/panda/src/pipeline/conditionVar.h b/panda/src/pipeline/conditionVar.h index 3c94e03a34..fe90e22063 100644 --- a/panda/src/pipeline/conditionVar.h +++ b/panda/src/pipeline/conditionVar.h @@ -43,20 +43,19 @@ class EXPCL_PANDA_PIPELINE ConditionVar : public ConditionVarDirect { PUBLISHED: INLINE explicit ConditionVar(Mutex &mutex); - INLINE ~ConditionVar(); -private: - INLINE ConditionVar(const ConditionVar ©); - INLINE void operator = (const ConditionVar ©); + ConditionVar(const ConditionVar ©) = delete; + ~ConditionVar() = default; - // These methods are inherited from the base class. INLINE void wait(); - // INLINE void notify(); + ConditionVar &operator = (const ConditionVar ©) = delete; + + // These methods are inherited from the base class. + //INLINE void wait(); + //INLINE void notify(); -private: // The notify_all() method is specifically *not* provided by ConditionVar. // Use ConditionVarFull if you need to call this method. - INLINE void notify_all(); + void notify_all() = delete; -PUBLISHED: INLINE Mutex &get_mutex() const; }; diff --git a/panda/src/pipeline/conditionVarDebug.I b/panda/src/pipeline/conditionVarDebug.I index 6b16125a0e..f7804b22b2 100644 --- a/panda/src/pipeline/conditionVarDebug.I +++ b/panda/src/pipeline/conditionVarDebug.I @@ -11,25 +11,6 @@ * @date 2006-02-13 */ -/** - * Do not attempt to copy condition variables. - */ -INLINE ConditionVarDebug:: -ConditionVarDebug(const ConditionVarDebug ©) : - _mutex(copy._mutex), - _impl(*_mutex._global_lock) -{ - nassertv(false); -} - -/** - * Do not attempt to copy condition variables. - */ -INLINE void ConditionVarDebug:: -operator = (const ConditionVarDebug ©) { - nassertv(false); -} - /** * Returns the mutex associated with this condition variable. */ diff --git a/panda/src/pipeline/conditionVarDebug.cxx b/panda/src/pipeline/conditionVarDebug.cxx index d8c838196e..bbf9ce0d22 100644 --- a/panda/src/pipeline/conditionVarDebug.cxx +++ b/panda/src/pipeline/conditionVarDebug.cxx @@ -17,6 +17,9 @@ #ifdef DEBUG_THREADS +using std::ostream; +using std::ostringstream; + /** * You must pass in a Mutex to the condition variable constructor. This mutex * may be shared by other condition variables, if desired. It is the caller's @@ -57,7 +60,7 @@ ConditionVarDebug:: */ void ConditionVarDebug:: wait() { - _mutex._global_lock->acquire(); + _mutex._global_lock->lock(); Thread *current_thread = Thread::get_current_thread(); @@ -66,7 +69,7 @@ wait() { ostr << *current_thread << " attempted to wait on " << *this << " without holding " << _mutex; nassert_raise(ostr.str()); - _mutex._global_lock->release(); + _mutex._global_lock->unlock(); return; } @@ -75,25 +78,25 @@ wait() { << *current_thread << " waiting on " << *this << "\n"; } - nassertd(current_thread->_waiting_on_cvar == NULL && - current_thread->_waiting_on_cvar_full == NULL) { + nassertd(current_thread->_waiting_on_cvar == nullptr && + current_thread->_waiting_on_cvar_full == nullptr) { } current_thread->_waiting_on_cvar = this; - _mutex.do_release(); + _mutex.do_unlock(); _impl.wait(); // temporarily releases _global_lock - _mutex.do_acquire(current_thread); + _mutex.do_lock(current_thread); nassertd(current_thread->_waiting_on_cvar == this) { } - current_thread->_waiting_on_cvar = NULL; + current_thread->_waiting_on_cvar = nullptr; if (thread_cat.is_spam()) { thread_cat.spam() << *current_thread << " awake on " << *this << "\n"; } - _mutex._global_lock->release(); + _mutex._global_lock->unlock(); } /** @@ -106,7 +109,7 @@ wait() { */ void ConditionVarDebug:: wait(double timeout) { - _mutex._global_lock->acquire(); + _mutex._global_lock->lock(); Thread *current_thread = Thread::get_current_thread(); @@ -115,7 +118,7 @@ wait(double timeout) { ostr << *current_thread << " attempted to wait on " << *this << " without holding " << _mutex; nassert_raise(ostr.str()); - _mutex._global_lock->release(); + _mutex._global_lock->unlock(); return; } @@ -125,25 +128,25 @@ wait(double timeout) { << ", with timeout " << timeout << "\n"; } - nassertd(current_thread->_waiting_on_cvar == NULL && - current_thread->_waiting_on_cvar_full == NULL) { + nassertd(current_thread->_waiting_on_cvar == nullptr && + current_thread->_waiting_on_cvar_full == nullptr) { } current_thread->_waiting_on_cvar = this; - _mutex.do_release(); + _mutex.do_unlock(); _impl.wait(timeout); // temporarily releases _global_lock - _mutex.do_acquire(current_thread); + _mutex.do_lock(current_thread); nassertd(current_thread->_waiting_on_cvar == this) { } - current_thread->_waiting_on_cvar = NULL; + current_thread->_waiting_on_cvar = nullptr; if (thread_cat.is_spam()) { thread_cat.spam() << *current_thread << " awake on " << *this << "\n"; } - _mutex._global_lock->release(); + _mutex._global_lock->unlock(); } /** @@ -160,7 +163,7 @@ wait(double timeout) { */ void ConditionVarDebug:: notify() { - _mutex._global_lock->acquire(); + _mutex._global_lock->lock(); Thread *current_thread = Thread::get_current_thread(); @@ -169,7 +172,7 @@ notify() { ostr << *current_thread << " attempted to notify " << *this << " without holding " << _mutex; nassert_raise(ostr.str()); - _mutex._global_lock->release(); + _mutex._global_lock->unlock(); return; } @@ -179,7 +182,7 @@ notify() { } _impl.notify(); - _mutex._global_lock->release(); + _mutex._global_lock->unlock(); } /** diff --git a/panda/src/pipeline/conditionVarDebug.h b/panda/src/pipeline/conditionVarDebug.h index 7cbacbaf0d..85da3fde2e 100644 --- a/panda/src/pipeline/conditionVarDebug.h +++ b/panda/src/pipeline/conditionVarDebug.h @@ -32,10 +32,10 @@ class EXPCL_PANDA_PIPELINE ConditionVarDebug { public: explicit ConditionVarDebug(MutexDebug &mutex); + ConditionVarDebug(const ConditionVarDebug ©) = delete; virtual ~ConditionVarDebug(); -private: - INLINE ConditionVarDebug(const ConditionVarDebug ©); - INLINE void operator = (const ConditionVarDebug ©); + + ConditionVarDebug &operator = (const ConditionVarDebug ©) = delete; PUBLISHED: INLINE MutexDebug &get_mutex() const; @@ -43,15 +43,15 @@ PUBLISHED: BLOCKING void wait(); BLOCKING void wait(double timeout); void notify(); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: MutexDebug &_mutex; ConditionVarImpl _impl; }; -INLINE ostream & -operator << (ostream &out, const ConditionVarDebug &cv) { +INLINE std::ostream & +operator << (std::ostream &out, const ConditionVarDebug &cv) { cv.output(out); return out; } diff --git a/panda/src/pipeline/conditionVarDirect.I b/panda/src/pipeline/conditionVarDirect.I index 6b9d0351bf..bf8e42aea5 100644 --- a/panda/src/pipeline/conditionVarDirect.I +++ b/panda/src/pipeline/conditionVarDirect.I @@ -24,32 +24,6 @@ ConditionVarDirect(MutexDirect &mutex) : { } -/** - * - */ -INLINE ConditionVarDirect:: -~ConditionVarDirect() { -} - -/** - * Do not attempt to copy condition variables. - */ -INLINE ConditionVarDirect:: -ConditionVarDirect(const ConditionVarDirect ©) : - _mutex(copy._mutex), - _impl(_mutex._impl) -{ - nassertv(false); -} - -/** - * Do not attempt to copy condition variables. - */ -INLINE void ConditionVarDirect:: -operator = (const ConditionVarDirect ©) { - nassertv(false); -} - /** * Returns the mutex associated with this condition variable. */ diff --git a/panda/src/pipeline/conditionVarDirect.cxx b/panda/src/pipeline/conditionVarDirect.cxx index b3f18f1c0c..c9337e8d9c 100644 --- a/panda/src/pipeline/conditionVarDirect.cxx +++ b/panda/src/pipeline/conditionVarDirect.cxx @@ -20,7 +20,7 @@ * ConditionVarDirect. */ void ConditionVarDirect:: -output(ostream &out) const { +output(std::ostream &out) const { out << "ConditionVar " << (void *)this << " on " << _mutex; } diff --git a/panda/src/pipeline/conditionVarDirect.h b/panda/src/pipeline/conditionVarDirect.h index 116f22b899..2a8c9197cb 100644 --- a/panda/src/pipeline/conditionVarDirect.h +++ b/panda/src/pipeline/conditionVarDirect.h @@ -32,10 +32,10 @@ class EXPCL_PANDA_PIPELINE ConditionVarDirect { public: INLINE explicit ConditionVarDirect(MutexDirect &mutex); - INLINE ~ConditionVarDirect(); -private: - INLINE ConditionVarDirect(const ConditionVarDirect ©); - INLINE void operator = (const ConditionVarDirect ©); + ConditionVarDirect(const ConditionVarDirect ©) = delete; + ~ConditionVarDirect() = default; + + ConditionVarDirect &operator = (const ConditionVarDirect ©) = delete; PUBLISHED: INLINE MutexDirect &get_mutex() const; @@ -43,15 +43,15 @@ PUBLISHED: BLOCKING INLINE void wait(); BLOCKING INLINE void wait(double timeout); INLINE void notify(); - void output(ostream &out) const; + void output(std::ostream &out) const; private: MutexDirect &_mutex; ConditionVarImpl _impl; }; -INLINE ostream & -operator << (ostream &out, const ConditionVarDirect &cv) { +INLINE std::ostream & +operator << (std::ostream &out, const ConditionVarDirect &cv) { cv.output(out); return out; } diff --git a/panda/src/pipeline/conditionVarFull.I b/panda/src/pipeline/conditionVarFull.I index 21b93b5ec6..b796e7aed2 100644 --- a/panda/src/pipeline/conditionVarFull.I +++ b/panda/src/pipeline/conditionVarFull.I @@ -27,35 +27,6 @@ ConditionVarFull(Mutex &mutex) : { } -/** - * - */ -INLINE ConditionVarFull:: -~ConditionVarFull() { -} - -/** - * Do not attempt to copy condition variables. - */ -INLINE ConditionVarFull:: -ConditionVarFull(const ConditionVarFull ©) : -#ifdef DEBUG_THREADS - ConditionVarFullDebug(copy.get_mutex()) -#else - ConditionVarFullDirect(copy.get_mutex()) -#endif // DEBUG_THREADS -{ - nassertv(false); -} - -/** - * Do not attempt to copy condition variables. - */ -INLINE void ConditionVarFull:: -operator = (const ConditionVarFull ©) { - nassertv(false); -} - /** * Returns the mutex associated with this condition variable. */ diff --git a/panda/src/pipeline/conditionVarFull.h b/panda/src/pipeline/conditionVarFull.h index 5f8b7ea731..37a9af1e11 100644 --- a/panda/src/pipeline/conditionVarFull.h +++ b/panda/src/pipeline/conditionVarFull.h @@ -46,12 +46,11 @@ class EXPCL_PANDA_PIPELINE ConditionVarFull : public ConditionVarFullDirect { PUBLISHED: INLINE explicit ConditionVarFull(Mutex &mutex); - INLINE ~ConditionVarFull(); -private: - INLINE ConditionVarFull(const ConditionVarFull ©); - INLINE void operator = (const ConditionVarFull ©); + ConditionVarFull(const ConditionVarFull ©) = delete; + ~ConditionVarFull() = default; + + ConditionVarFull &operator = (const ConditionVarFull ©) = delete; -PUBLISHED: INLINE Mutex &get_mutex() const; }; diff --git a/panda/src/pipeline/conditionVarFullDebug.I b/panda/src/pipeline/conditionVarFullDebug.I index bbf60f603d..5a09f03a3d 100644 --- a/panda/src/pipeline/conditionVarFullDebug.I +++ b/panda/src/pipeline/conditionVarFullDebug.I @@ -11,25 +11,6 @@ * @date 2006-08-28 */ -/** - * Do not attempt to copy condition variables. - */ -INLINE ConditionVarFullDebug:: -ConditionVarFullDebug(const ConditionVarFullDebug ©) : - _mutex(copy._mutex), - _impl(*_mutex._global_lock) -{ - nassertv(false); -} - -/** - * Do not attempt to copy condition variables. - */ -INLINE void ConditionVarFullDebug:: -operator = (const ConditionVarFullDebug ©) { - nassertv(false); -} - /** * Returns the mutex associated with this condition variable. */ diff --git a/panda/src/pipeline/conditionVarFullDebug.cxx b/panda/src/pipeline/conditionVarFullDebug.cxx index 4c76b513d0..746991e79c 100644 --- a/panda/src/pipeline/conditionVarFullDebug.cxx +++ b/panda/src/pipeline/conditionVarFullDebug.cxx @@ -17,6 +17,9 @@ #ifdef DEBUG_THREADS +using std::ostream; +using std::ostringstream; + /** * You must pass in a Mutex to the condition variable constructor. This mutex * may be shared by other condition variables, if desired. It is the caller's @@ -57,7 +60,7 @@ ConditionVarFullDebug:: */ void ConditionVarFullDebug:: wait() { - _mutex._global_lock->acquire(); + _mutex._global_lock->lock(); Thread *current_thread = Thread::get_current_thread(); @@ -66,7 +69,7 @@ wait() { ostr << *current_thread << " attempted to wait on " << *this << " without holding " << _mutex; nassert_raise(ostr.str()); - _mutex._global_lock->release(); + _mutex._global_lock->unlock(); return; } @@ -75,25 +78,25 @@ wait() { << *current_thread << " waiting on " << *this << "\n"; } - nassertd(current_thread->_waiting_on_cvar == NULL && - current_thread->_waiting_on_cvar_full == NULL) { + nassertd(current_thread->_waiting_on_cvar == nullptr && + current_thread->_waiting_on_cvar_full == nullptr) { } current_thread->_waiting_on_cvar_full = this; - _mutex.do_release(); + _mutex.do_unlock(); _impl.wait(); // temporarily releases _global_lock - _mutex.do_acquire(current_thread); + _mutex.do_lock(current_thread); nassertd(current_thread->_waiting_on_cvar_full == this) { } - current_thread->_waiting_on_cvar_full = NULL; + current_thread->_waiting_on_cvar_full = nullptr; if (thread_cat.is_spam()) { thread_cat.spam() << *current_thread << " awake on " << *this << "\n"; } - _mutex._global_lock->release(); + _mutex._global_lock->unlock(); } /** @@ -106,7 +109,7 @@ wait() { */ void ConditionVarFullDebug:: wait(double timeout) { - _mutex._global_lock->acquire(); + _mutex._global_lock->lock(); Thread *current_thread = Thread::get_current_thread(); @@ -115,7 +118,7 @@ wait(double timeout) { ostr << *current_thread << " attempted to wait on " << *this << " without holding " << _mutex; nassert_raise(ostr.str()); - _mutex._global_lock->release(); + _mutex._global_lock->unlock(); return; } @@ -125,25 +128,25 @@ wait(double timeout) { << ", with timeout " << timeout << "\n"; } - nassertd(current_thread->_waiting_on_cvar == NULL && - current_thread->_waiting_on_cvar_full == NULL) { + nassertd(current_thread->_waiting_on_cvar == nullptr && + current_thread->_waiting_on_cvar_full == nullptr) { } current_thread->_waiting_on_cvar_full = this; - _mutex.do_release(); + _mutex.do_unlock(); _impl.wait(timeout); // temporarily releases _global_lock - _mutex.do_acquire(current_thread); + _mutex.do_lock(current_thread); nassertd(current_thread->_waiting_on_cvar_full == this) { } - current_thread->_waiting_on_cvar_full = NULL; + current_thread->_waiting_on_cvar_full = nullptr; if (thread_cat.is_spam()) { thread_cat.spam() << *current_thread << " awake on " << *this << "\n"; } - _mutex._global_lock->release(); + _mutex._global_lock->unlock(); } /** @@ -160,7 +163,7 @@ wait(double timeout) { */ void ConditionVarFullDebug:: notify() { - _mutex._global_lock->acquire(); + _mutex._global_lock->lock(); Thread *current_thread = Thread::get_current_thread(); @@ -169,7 +172,7 @@ notify() { ostr << *current_thread << " attempted to notify " << *this << " without holding " << _mutex; nassert_raise(ostr.str()); - _mutex._global_lock->release(); + _mutex._global_lock->unlock(); return; } @@ -179,7 +182,7 @@ notify() { } _impl.notify(); - _mutex._global_lock->release(); + _mutex._global_lock->unlock(); } /** @@ -193,7 +196,7 @@ notify() { */ void ConditionVarFullDebug:: notify_all() { - _mutex._global_lock->acquire(); + _mutex._global_lock->lock(); Thread *current_thread = Thread::get_current_thread(); @@ -202,7 +205,7 @@ notify_all() { ostr << *current_thread << " attempted to notify " << *this << " without holding " << _mutex; nassert_raise(ostr.str()); - _mutex._global_lock->release(); + _mutex._global_lock->unlock(); return; } @@ -212,7 +215,7 @@ notify_all() { } _impl.notify_all(); - _mutex._global_lock->release(); + _mutex._global_lock->unlock(); } /** diff --git a/panda/src/pipeline/conditionVarFullDebug.h b/panda/src/pipeline/conditionVarFullDebug.h index 02c5957f72..cefb27cad7 100644 --- a/panda/src/pipeline/conditionVarFullDebug.h +++ b/panda/src/pipeline/conditionVarFullDebug.h @@ -32,10 +32,10 @@ class EXPCL_PANDA_PIPELINE ConditionVarFullDebug { public: explicit ConditionVarFullDebug(MutexDebug &mutex); + ConditionVarFullDebug(const ConditionVarFullDebug ©) = delete; virtual ~ConditionVarFullDebug(); -private: - INLINE ConditionVarFullDebug(const ConditionVarFullDebug ©); - INLINE void operator = (const ConditionVarFullDebug ©); + + ConditionVarFullDebug &operator = (const ConditionVarFullDebug ©) = delete; PUBLISHED: INLINE MutexDebug &get_mutex() const; @@ -44,15 +44,15 @@ PUBLISHED: BLOCKING void wait(double timeout); void notify(); void notify_all(); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: MutexDebug &_mutex; ConditionVarFullImpl _impl; }; -INLINE ostream & -operator << (ostream &out, const ConditionVarFullDebug &cv) { +INLINE std::ostream & +operator << (std::ostream &out, const ConditionVarFullDebug &cv) { cv.output(out); return out; } diff --git a/panda/src/pipeline/conditionVarFullDirect.I b/panda/src/pipeline/conditionVarFullDirect.I index fa0da2b3c6..207cb01538 100644 --- a/panda/src/pipeline/conditionVarFullDirect.I +++ b/panda/src/pipeline/conditionVarFullDirect.I @@ -24,32 +24,6 @@ ConditionVarFullDirect(MutexDirect &mutex) : { } -/** - * - */ -INLINE ConditionVarFullDirect:: -~ConditionVarFullDirect() { -} - -/** - * Do not attempt to copy condition variables. - */ -INLINE ConditionVarFullDirect:: -ConditionVarFullDirect(const ConditionVarFullDirect ©) : - _mutex(copy._mutex), - _impl(_mutex._impl) -{ - nassertv(false); -} - -/** - * Do not attempt to copy condition variables. - */ -INLINE void ConditionVarFullDirect:: -operator = (const ConditionVarFullDirect ©) { - nassertv(false); -} - /** * Returns the mutex associated with this condition variable. */ diff --git a/panda/src/pipeline/conditionVarFullDirect.cxx b/panda/src/pipeline/conditionVarFullDirect.cxx index 10c30d57c9..04f9c647ed 100644 --- a/panda/src/pipeline/conditionVarFullDirect.cxx +++ b/panda/src/pipeline/conditionVarFullDirect.cxx @@ -20,7 +20,7 @@ * in ConditionVarFullDirect. */ void ConditionVarFullDirect:: -output(ostream &out) const { +output(std::ostream &out) const { out << "ConditionVarFull " << (void *)this << " on " << _mutex; } diff --git a/panda/src/pipeline/conditionVarFullDirect.h b/panda/src/pipeline/conditionVarFullDirect.h index 45cd0ac3f4..729185501b 100644 --- a/panda/src/pipeline/conditionVarFullDirect.h +++ b/panda/src/pipeline/conditionVarFullDirect.h @@ -32,10 +32,10 @@ class EXPCL_PANDA_PIPELINE ConditionVarFullDirect { public: INLINE explicit ConditionVarFullDirect(MutexDirect &mutex); - INLINE ~ConditionVarFullDirect(); -private: - INLINE ConditionVarFullDirect(const ConditionVarFullDirect ©); - INLINE void operator = (const ConditionVarFullDirect ©); + ConditionVarFullDirect(const ConditionVarFullDirect ©) = delete; + ~ConditionVarFullDirect() = default; + + ConditionVarFullDirect &operator = (const ConditionVarFullDirect ©) = delete; PUBLISHED: INLINE MutexDirect &get_mutex() const; @@ -44,15 +44,15 @@ PUBLISHED: BLOCKING INLINE void wait(double timeout); INLINE void notify(); INLINE void notify_all(); - void output(ostream &out) const; + void output(std::ostream &out) const; private: MutexDirect &_mutex; ConditionVarFullImpl _impl; }; -INLINE ostream & -operator << (ostream &out, const ConditionVarFullDirect &cv) { +INLINE std::ostream & +operator << (std::ostream &out, const ConditionVarFullDirect &cv) { cv.output(out); return out; } diff --git a/panda/src/pipeline/conditionVarFullWin32Impl.I b/panda/src/pipeline/conditionVarFullWin32Impl.I index 361e81ac93..386a9d5784 100644 --- a/panda/src/pipeline/conditionVarFullWin32Impl.I +++ b/panda/src/pipeline/conditionVarFullWin32Impl.I @@ -19,8 +19,8 @@ ConditionVarFullWin32Impl(MutexWin32Impl &mutex) { _external_mutex = &mutex._lock; // Create an auto-reset event and a manual-reset event. - _event_signal = CreateEvent(NULL, false, false, NULL); - _event_broadcast = CreateEvent(NULL, true, false, NULL); + _event_signal = CreateEvent(nullptr, false, false, nullptr); + _event_broadcast = CreateEvent(nullptr, true, false, nullptr); _waiters_count = 0; } diff --git a/panda/src/pipeline/conditionVarPosixImpl.I b/panda/src/pipeline/conditionVarPosixImpl.I index e51c0e8447..0b3e533717 100644 --- a/panda/src/pipeline/conditionVarPosixImpl.I +++ b/panda/src/pipeline/conditionVarPosixImpl.I @@ -19,7 +19,7 @@ ConditionVarPosixImpl(MutexPosixImpl &mutex) : _mutex(mutex) { TAU_PROFILE("ConditionVarPosixImpl::ConditionVarPosixImpl()", " ", TAU_USER); - int result = pthread_cond_init(&_cvar, NULL); + int result = pthread_cond_init(&_cvar, nullptr); nassertv(result == 0); } diff --git a/panda/src/pipeline/conditionVarPosixImpl.cxx b/panda/src/pipeline/conditionVarPosixImpl.cxx index 6613dd53b4..e2e527c369 100644 --- a/panda/src/pipeline/conditionVarPosixImpl.cxx +++ b/panda/src/pipeline/conditionVarPosixImpl.cxx @@ -26,7 +26,7 @@ wait(double timeout) { // TAU_PROFILE("ConditionVarPosixImpl::wait()", " ", TAU_USER); struct timeval now; - gettimeofday(&now, NULL); + gettimeofday(&now, nullptr); // Convert from timeval to timespec struct timespec ts; diff --git a/panda/src/pipeline/conditionVarSimpleImpl.cxx b/panda/src/pipeline/conditionVarSimpleImpl.cxx index 9c60c98ff0..761798d227 100644 --- a/panda/src/pipeline/conditionVarSimpleImpl.cxx +++ b/panda/src/pipeline/conditionVarSimpleImpl.cxx @@ -23,14 +23,14 @@ */ void ConditionVarSimpleImpl:: wait() { - _mutex.release_quietly(); + _mutex.unlock_quietly(); ThreadSimpleManager *manager = ThreadSimpleManager::get_global_ptr(); ThreadSimpleImpl *thread = manager->get_current_thread(); manager->enqueue_block(thread, this); manager->next_context(); - _mutex.acquire(); + _mutex.lock(); } /** @@ -38,7 +38,7 @@ wait() { */ void ConditionVarSimpleImpl:: wait(double timeout) { - _mutex.release_quietly(); + _mutex.unlock_quietly(); // TODO. For now this will release every frame, since we don't have an // interface yet on ThreadSimpleManager to do a timed wait. Maybe that's @@ -49,7 +49,7 @@ wait(double timeout) { manager->enqueue_ready(thread, true); manager->next_context(); - _mutex.acquire(); + _mutex.lock(); } /** diff --git a/panda/src/pipeline/conditionVarWin32Impl.I b/panda/src/pipeline/conditionVarWin32Impl.I index 263a7d37a4..5994c638d5 100644 --- a/panda/src/pipeline/conditionVarWin32Impl.I +++ b/panda/src/pipeline/conditionVarWin32Impl.I @@ -19,7 +19,7 @@ ConditionVarWin32Impl(MutexWin32Impl &mutex) { _external_mutex = &mutex._lock; // Create an auto-reset event. - _event_signal = CreateEvent(NULL, false, false, NULL); + _event_signal = CreateEvent(nullptr, false, false, nullptr); } /** diff --git a/panda/src/pipeline/config_pipeline.cxx b/panda/src/pipeline/config_pipeline.cxx index 8f82307c86..60f077688f 100644 --- a/panda/src/pipeline/config_pipeline.cxx +++ b/panda/src/pipeline/config_pipeline.cxx @@ -12,6 +12,7 @@ */ #include "config_pipeline.h" +#include "cycleData.h" #include "mainThread.h" #include "externalThread.h" #include "genericThread.h" @@ -70,6 +71,7 @@ init_libpipeline() { } initialized = true; + CycleData::init_type(); MainThread::init_type(); ExternalThread::init_type(); GenericThread::init_type(); diff --git a/panda/src/pipeline/cycleData.cxx b/panda/src/pipeline/cycleData.cxx index 7570aabbf8..346a6e8042 100644 --- a/panda/src/pipeline/cycleData.cxx +++ b/panda/src/pipeline/cycleData.cxx @@ -13,6 +13,9 @@ #include "cycleData.h" +#ifdef DO_PIPELINING +TypeHandle CycleData::_type_handle; +#endif /** * @@ -79,6 +82,6 @@ get_parent_type() const { * This is useful mainly for debugging. */ void CycleData:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_parent_type() << "::CData"; } diff --git a/panda/src/pipeline/cycleData.h b/panda/src/pipeline/cycleData.h index 72ba074088..de90bdf226 100644 --- a/panda/src/pipeline/cycleData.h +++ b/panda/src/pipeline/cycleData.h @@ -49,9 +49,9 @@ class EXPCL_PANDA_PIPELINE CycleData #endif // DO_PIPELINING { public: - INLINE CycleData() DEFAULT_CTOR; - INLINE CycleData(CycleData &&from) DEFAULT_CTOR; - INLINE CycleData(const CycleData ©) DEFAULT_CTOR; + INLINE CycleData() = default; + INLINE CycleData(CycleData &&from) = default; + INLINE CycleData(const CycleData ©) = default; virtual ~CycleData(); virtual CycleData *make_copy() const=0; @@ -64,11 +64,27 @@ public: void *extra_data); virtual TypeHandle get_parent_type() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; + +#ifdef DO_PIPELINING +public: + static TypeHandle get_class_type() { + return _type_handle; + } + + static void init_type() { + NodeReferenceCount::init_type(); + register_type(_type_handle, "CycleData", + NodeReferenceCount::get_class_type()); + } + +private: + static TypeHandle _type_handle; +#endif }; -INLINE ostream & -operator << (ostream &out, const CycleData &cd) { +INLINE std::ostream & +operator << (std::ostream &out, const CycleData &cd) { cd.output(out); return out; } diff --git a/panda/src/pipeline/cycleDataLockedReader.I b/panda/src/pipeline/cycleDataLockedReader.I index 0ac88ebb67..a622b9a2c0 100644 --- a/panda/src/pipeline/cycleDataLockedReader.I +++ b/panda/src/pipeline/cycleDataLockedReader.I @@ -28,7 +28,7 @@ CycleDataLockedReader(const PipelineCycler &cycler, _current_thread(current_thread) { _pointer = _cycler->read(_current_thread); - nassertv(_pointer != (const CycleDataType *)NULL); + nassertv(_pointer != nullptr); } /** @@ -41,7 +41,7 @@ CycleDataLockedReader(const CycleDataLockedReader ©) : _current_thread(copy._current_thread), _pointer(copy._pointer) { - nassertv(_pointer != (const CycleDataType *)NULL); + nassertv(_pointer != nullptr); _cycler->increment_read(_pointer); } @@ -51,28 +51,27 @@ CycleDataLockedReader(const CycleDataLockedReader ©) : template INLINE void CycleDataLockedReader:: operator = (const CycleDataLockedReader ©) { - nassertv(_pointer == (CycleDataType *)NULL); + nassertv(_pointer == nullptr); nassertv(_current_thread == copy._current_thread); _cycler = copy._cycler; _pointer = copy._pointer; - nassertv(_pointer != (const CycleDataType *)NULL); + nassertv(_pointer != nullptr); _cycler->increment_read(_pointer); } -#ifdef USE_MOVE_SEMANTICS /** * */ template INLINE CycleDataLockedReader:: -CycleDataLockedReader(CycleDataLockedReader &&from) NOEXCEPT : +CycleDataLockedReader(CycleDataLockedReader &&from) noexcept : _cycler(from._cycler), _current_thread(from._current_thread), _pointer(from._pointer) { - from._pointer = NULL; + from._pointer = nullptr; } /** @@ -80,16 +79,15 @@ CycleDataLockedReader(CycleDataLockedReader &&from) NOEXCEPT : */ template INLINE void CycleDataLockedReader:: -operator = (CycleDataLockedReader &&from) NOEXCEPT { - nassertv(_pointer == (CycleDataType *)NULL); +operator = (CycleDataLockedReader &&from) noexcept { + nassertv(_pointer == nullptr); nassertv(_current_thread == from._current_thread); _cycler = from._cycler; _pointer = from._pointer; - from._pointer = NULL; + from._pointer = nullptr; } -#endif // USE_MOVE_SEMANTICS /** * @@ -97,7 +95,7 @@ operator = (CycleDataLockedReader &&from) NOEXCEPT { template INLINE CycleDataLockedReader:: ~CycleDataLockedReader() { - if (_pointer != NULL) { + if (_pointer != nullptr) { _cycler->release_read(_pointer); } } @@ -108,7 +106,7 @@ INLINE CycleDataLockedReader:: template INLINE const CycleDataType *CycleDataLockedReader:: operator -> () const { - nassertr(_pointer != (const CycleDataType *)NULL, _cycler->cheat()); + nassertr(_pointer != nullptr, _cycler->cheat()); return _pointer; } @@ -119,7 +117,7 @@ operator -> () const { template INLINE CycleDataLockedReader:: operator const CycleDataType * () const { - nassertr(_pointer != (const CycleDataType *)NULL, _cycler->cheat()); + nassertr(_pointer != nullptr, _cycler->cheat()); return _pointer; } @@ -133,8 +131,8 @@ template INLINE const CycleDataType *CycleDataLockedReader:: take_pointer() { const CycleDataType *pointer = _pointer; - _pointer = (CycleDataType *)NULL; - nassertr(pointer != (const CycleDataType *)NULL, _cycler->cheat()); + _pointer = nullptr; + nassertr(pointer != nullptr, _cycler->cheat()); return pointer; } diff --git a/panda/src/pipeline/cycleDataLockedReader.h b/panda/src/pipeline/cycleDataLockedReader.h index f66143fab4..62c1a72b1a 100644 --- a/panda/src/pipeline/cycleDataLockedReader.h +++ b/panda/src/pipeline/cycleDataLockedReader.h @@ -45,12 +45,10 @@ public: INLINE CycleDataLockedReader(const PipelineCycler &cycler, Thread *current_thread = Thread::get_current_thread()); INLINE CycleDataLockedReader(const CycleDataLockedReader ©); - INLINE void operator = (const CycleDataLockedReader ©); + INLINE CycleDataLockedReader(CycleDataLockedReader &&from) noexcept; -#if defined(USE_MOVE_SEMANTICS) && defined(DO_PIPELINING) - INLINE CycleDataLockedReader(CycleDataLockedReader &&from) NOEXCEPT; - INLINE void operator = (CycleDataLockedReader &&from) NOEXCEPT; -#endif + INLINE void operator = (const CycleDataLockedReader ©); + INLINE void operator = (CycleDataLockedReader &&from) noexcept; INLINE ~CycleDataLockedReader(); diff --git a/panda/src/pipeline/cycleDataLockedStageReader.I b/panda/src/pipeline/cycleDataLockedStageReader.I index 9f2c74d23a..22b8785c82 100644 --- a/panda/src/pipeline/cycleDataLockedStageReader.I +++ b/panda/src/pipeline/cycleDataLockedStageReader.I @@ -29,7 +29,7 @@ CycleDataLockedStageReader(const PipelineCycler &cycler, _stage(stage) { _pointer = _cycler->read_stage(_stage, _current_thread); - nassertv(_pointer != (const CycleDataType *)NULL); + nassertv(_pointer != nullptr); } /** @@ -43,7 +43,7 @@ CycleDataLockedStageReader(const CycleDataLockedStageReader © _pointer(copy._pointer), _stage(copy._stage) { - nassertv(_pointer != (const CycleDataType *)NULL); + nassertv(_pointer != nullptr); _cycler->increment_read(_pointer); } @@ -53,30 +53,29 @@ CycleDataLockedStageReader(const CycleDataLockedStageReader © template INLINE void CycleDataLockedStageReader:: operator = (const CycleDataLockedStageReader ©) { - nassertv(_pointer == (CycleDataType *)NULL); + nassertv(_pointer == nullptr); nassertv(_current_thread == copy._current_thread); _cycler = copy._cycler; _pointer = copy._pointer; _stage = copy._stage; - nassertv(_pointer != (const CycleDataType *)NULL); + nassertv(_pointer != nullptr); _cycler->increment_read(_pointer); } -#ifdef USE_MOVE_SEMANTICS /** * */ template INLINE CycleDataLockedStageReader:: -CycleDataLockedStageReader(CycleDataLockedStageReader &&from) NOEXCEPT : +CycleDataLockedStageReader(CycleDataLockedStageReader &&from) noexcept : _cycler(from._cycler), _current_thread(from._current_thread), _pointer(from._pointer), _stage(from._stage) { - from._pointer = NULL; + from._pointer = nullptr; } /** @@ -84,17 +83,16 @@ CycleDataLockedStageReader(CycleDataLockedStageReader &&from) NOE */ template INLINE void CycleDataLockedStageReader:: -operator = (CycleDataLockedStageReader &&from) NOEXCEPT { - nassertv(_pointer == (CycleDataType *)NULL); +operator = (CycleDataLockedStageReader &&from) noexcept { + nassertv(_pointer == nullptr); nassertv(_current_thread == from._current_thread); _cycler = from._cycler; _pointer = from._pointer; _stage = from._stage; - from._pointer = NULL; + from._pointer = nullptr; } -#endif // USE_MOVE_SEMANTICS /** * @@ -102,7 +100,7 @@ operator = (CycleDataLockedStageReader &&from) NOEXCEPT { template INLINE CycleDataLockedStageReader:: ~CycleDataLockedStageReader() { - if (_pointer != NULL) { + if (_pointer != nullptr) { _cycler->release_read_stage(_stage, _pointer); } } @@ -113,7 +111,7 @@ INLINE CycleDataLockedStageReader:: template INLINE const CycleDataType *CycleDataLockedStageReader:: operator -> () const { - nassertr(_pointer != (const CycleDataType *)NULL, _cycler->cheat()); + nassertr(_pointer != nullptr, _cycler->cheat()); return _pointer; } @@ -124,7 +122,7 @@ operator -> () const { template INLINE CycleDataLockedStageReader:: operator const CycleDataType * () const { - nassertr(_pointer != (const CycleDataType *)NULL, _cycler->cheat()); + nassertr(_pointer != nullptr, _cycler->cheat()); return _pointer; } @@ -138,8 +136,8 @@ template INLINE const CycleDataType *CycleDataLockedStageReader:: take_pointer() { const CycleDataType *pointer = _pointer; - _pointer = (CycleDataType *)NULL; - nassertr(pointer != (const CycleDataType *)NULL, _cycler->cheat()); + _pointer = nullptr; + nassertr(pointer != nullptr, _cycler->cheat()); return pointer; } diff --git a/panda/src/pipeline/cycleDataLockedStageReader.h b/panda/src/pipeline/cycleDataLockedStageReader.h index 6837a6edf4..4220a2ce0f 100644 --- a/panda/src/pipeline/cycleDataLockedStageReader.h +++ b/panda/src/pipeline/cycleDataLockedStageReader.h @@ -32,12 +32,10 @@ public: INLINE CycleDataLockedStageReader(const PipelineCycler &cycler, int stage, Thread *current_thread = Thread::get_current_thread()); INLINE CycleDataLockedStageReader(const CycleDataLockedStageReader ©); - INLINE void operator = (const CycleDataLockedStageReader ©); + INLINE CycleDataLockedStageReader(CycleDataLockedStageReader &&from) noexcept; -#if defined(USE_MOVE_SEMANTICS) && defined(DO_PIPELINING) - INLINE CycleDataLockedStageReader(CycleDataLockedStageReader &&from) NOEXCEPT; - INLINE void operator = (CycleDataLockedStageReader &&from) NOEXCEPT; -#endif + INLINE void operator = (const CycleDataLockedStageReader ©); + INLINE void operator = (CycleDataLockedStageReader &&from) noexcept; INLINE ~CycleDataLockedStageReader(); diff --git a/panda/src/pipeline/cycleDataStageWriter.I b/panda/src/pipeline/cycleDataStageWriter.I index 3e6d464768..a4c1851dde 100644 --- a/panda/src/pipeline/cycleDataStageWriter.I +++ b/panda/src/pipeline/cycleDataStageWriter.I @@ -29,7 +29,7 @@ CycleDataStageWriter(PipelineCycler &cycler, int stage, _stage(stage) { _pointer = _cycler->write_stage(_stage, _current_thread); - nassertv(_pointer != (CycleDataType *)NULL); + nassertv(_pointer != nullptr); } /** @@ -44,7 +44,7 @@ CycleDataStageWriter(PipelineCycler &cycler, int stage, _stage(stage) { _pointer = _cycler->write_stage_upstream(_stage, force_to_0, _current_thread); - nassertv(_pointer != (CycleDataType *)NULL); + nassertv(_pointer != nullptr); } /** @@ -58,7 +58,7 @@ CycleDataStageWriter(const CycleDataStageWriter ©) : _pointer(copy._pointer), _stage(copy._stage) { - nassertv(_pointer != (CycleDataType *)NULL); + nassertv(_pointer != nullptr); _cycler->increment_write(_pointer); } @@ -68,14 +68,14 @@ CycleDataStageWriter(const CycleDataStageWriter ©) : template INLINE void CycleDataStageWriter:: operator = (const CycleDataStageWriter ©) { - nassertv(_pointer == (CycleDataType *)NULL); + nassertv(_pointer == nullptr); nassertv(_current_thread == copy._current_thread); _cycler = copy._cycler; _pointer = copy._pointer; _stage = copy._stage; - nassertv(_pointer != (CycleDataType *)NULL); + nassertv(_pointer != nullptr); _cycler->increment_write(_pointer); } @@ -114,19 +114,18 @@ CycleDataStageWriter(PipelineCycler &cycler, int stage, force_to_0, _current_thread); } -#ifdef USE_MOVE_SEMANTICS /** * */ template INLINE CycleDataStageWriter:: -CycleDataStageWriter(CycleDataStageWriter &&from) NOEXCEPT : +CycleDataStageWriter(CycleDataStageWriter &&from) noexcept : _cycler(from._cycler), _current_thread(from._current_thread), _pointer(from._pointer), _stage(from._stage) { - from._pointer = NULL; + from._pointer = nullptr; } /** @@ -134,17 +133,16 @@ CycleDataStageWriter(CycleDataStageWriter &&from) NOEXCEPT : */ template INLINE void CycleDataStageWriter:: -operator = (CycleDataStageWriter &&from) NOEXCEPT { - nassertv(_pointer == (CycleDataType *)NULL); +operator = (CycleDataStageWriter &&from) noexcept { + nassertv(_pointer == nullptr); nassertv(_current_thread == from._current_thread); _cycler = from._cycler; _pointer = from._pointer; _stage = from._stage; - from._pointer = NULL; + from._pointer = nullptr; } -#endif // USE_MOVE_SEMANTICS /** * @@ -152,7 +150,7 @@ operator = (CycleDataStageWriter &&from) NOEXCEPT { template INLINE CycleDataStageWriter:: ~CycleDataStageWriter() { - if (_pointer != (CycleDataType *)NULL) { + if (_pointer != nullptr) { _cycler->release_write_stage(_stage, _pointer); } } @@ -163,7 +161,7 @@ INLINE CycleDataStageWriter:: template INLINE CycleDataType *CycleDataStageWriter:: operator -> () { - nassertr(_pointer != (CycleDataType *)NULL, _cycler->cheat()); + nassertr(_pointer != nullptr, _cycler->cheat()); return _pointer; } @@ -173,7 +171,7 @@ operator -> () { template INLINE const CycleDataType *CycleDataStageWriter:: operator -> () const { - nassertr(_pointer != (CycleDataType *)NULL, _cycler->cheat()); + nassertr(_pointer != nullptr, _cycler->cheat()); return _pointer; } @@ -184,7 +182,7 @@ operator -> () const { template INLINE CycleDataStageWriter:: operator CycleDataType * () { - nassertr(_pointer != (CycleDataType *)NULL, _cycler->cheat()); + nassertr(_pointer != nullptr, _cycler->cheat()); return _pointer; } diff --git a/panda/src/pipeline/cycleDataStageWriter.h b/panda/src/pipeline/cycleDataStageWriter.h index d154adb6d8..0357d1863d 100644 --- a/panda/src/pipeline/cycleDataStageWriter.h +++ b/panda/src/pipeline/cycleDataStageWriter.h @@ -39,7 +39,7 @@ public: bool force_to_0, Thread *current_thread = Thread::get_current_thread()); INLINE CycleDataStageWriter(const CycleDataStageWriter ©); - INLINE void operator = (const CycleDataStageWriter ©); + INLINE CycleDataStageWriter(CycleDataStageWriter &&from) noexcept; INLINE CycleDataStageWriter(PipelineCycler &cycler, int stage, CycleDataLockedStageReader &take_from); @@ -47,13 +47,11 @@ public: CycleDataLockedStageReader &take_from, bool force_to_0); -#if defined(USE_MOVE_SEMANTICS) && defined(DO_PIPELINING) - INLINE CycleDataStageWriter(CycleDataStageWriter &&from) NOEXCEPT; - INLINE void operator = (CycleDataStageWriter &&from) NOEXCEPT; -#endif - INLINE ~CycleDataStageWriter(); + INLINE void operator = (const CycleDataStageWriter ©); + INLINE void operator = (CycleDataStageWriter &&from) noexcept; + INLINE CycleDataType *operator -> (); INLINE const CycleDataType *operator -> () const; diff --git a/panda/src/pipeline/cycleDataWriter.I b/panda/src/pipeline/cycleDataWriter.I index 3706468612..584c3ea129 100644 --- a/panda/src/pipeline/cycleDataWriter.I +++ b/panda/src/pipeline/cycleDataWriter.I @@ -27,7 +27,7 @@ CycleDataWriter(PipelineCycler &cycler, Thread *current_thread) : _current_thread(current_thread) { _pointer = _cycler->write(_current_thread); - nassertv(_pointer != (CycleDataType *)NULL); + nassertv(_pointer != nullptr); } /** @@ -45,7 +45,7 @@ CycleDataWriter(PipelineCycler &cycler, bool force_to_0, _current_thread(current_thread) { _pointer = _cycler->write_upstream(force_to_0, _current_thread); - nassertv(_pointer != (CycleDataType *)NULL); + nassertv(_pointer != nullptr); } /** @@ -64,7 +64,7 @@ CycleDataWriter(PipelineCycler &cycler, CycleDataType *locked_cda _current_thread(current_thread) { _pointer = locked_cdata; - nassertv(_pointer != (CycleDataType *)NULL); + nassertv(_pointer != nullptr); } /** @@ -77,7 +77,7 @@ CycleDataWriter(const CycleDataWriter ©) : _current_thread(copy._current_thread), _pointer(copy._pointer) { - nassertv(_pointer != (CycleDataType *)NULL); + nassertv(_pointer != nullptr); _cycler->increment_write(_pointer); } @@ -87,13 +87,13 @@ CycleDataWriter(const CycleDataWriter ©) : template INLINE void CycleDataWriter:: operator = (const CycleDataWriter ©) { - nassertv(_pointer == (CycleDataType *)NULL); + nassertv(_pointer == nullptr); nassertv(_current_thread == copy._current_thread); _cycler = copy._cycler; _pointer = copy._pointer; - nassertv(_pointer != (CycleDataType *)NULL); + nassertv(_pointer != nullptr); _cycler->increment_write(_pointer); } @@ -130,18 +130,17 @@ CycleDataWriter(PipelineCycler &cycler, force_to_0, _current_thread); } -#ifdef USE_MOVE_SEMANTICS /** * */ template INLINE CycleDataWriter:: -CycleDataWriter(CycleDataWriter &&from) NOEXCEPT : +CycleDataWriter(CycleDataWriter &&from) noexcept : _cycler(from._cycler), _current_thread(from._current_thread), _pointer(from._pointer) { - from._pointer = NULL; + from._pointer = nullptr; } /** @@ -149,16 +148,15 @@ CycleDataWriter(CycleDataWriter &&from) NOEXCEPT : */ template INLINE void CycleDataWriter:: -operator = (CycleDataWriter &&from) NOEXCEPT { - nassertv(_pointer == (CycleDataType *)NULL); +operator = (CycleDataWriter &&from) noexcept { + nassertv(_pointer == nullptr); nassertv(_current_thread == from._current_thread); _cycler = from._cycler; _pointer = from._pointer; - from._pointer = NULL; + from._pointer = nullptr; } -#endif // USE_MOVE_SEMANTICS /** * @@ -166,7 +164,7 @@ operator = (CycleDataWriter &&from) NOEXCEPT { template INLINE CycleDataWriter:: ~CycleDataWriter() { - if (_pointer != (CycleDataType *)NULL) { + if (_pointer != nullptr) { _cycler->release_write(_pointer); } } @@ -177,7 +175,7 @@ INLINE CycleDataWriter:: template INLINE CycleDataType *CycleDataWriter:: operator -> () { - nassertr(_pointer != (CycleDataType *)NULL, _cycler->cheat()); + nassertr(_pointer != nullptr, _cycler->cheat()); return _pointer; } @@ -187,7 +185,7 @@ operator -> () { template INLINE const CycleDataType *CycleDataWriter:: operator -> () const { - nassertr(_pointer != (CycleDataType *)NULL, _cycler->cheat()); + nassertr(_pointer != nullptr, _cycler->cheat()); return _pointer; } @@ -198,7 +196,7 @@ operator -> () const { template INLINE CycleDataWriter:: operator CycleDataType * () { - nassertr(_pointer != (CycleDataType *)NULL, _cycler->cheat()); + nassertr(_pointer != nullptr, _cycler->cheat()); return _pointer; } diff --git a/panda/src/pipeline/cycleDataWriter.h b/panda/src/pipeline/cycleDataWriter.h index e2a4da7831..616ddae28e 100644 --- a/panda/src/pipeline/cycleDataWriter.h +++ b/panda/src/pipeline/cycleDataWriter.h @@ -44,15 +44,13 @@ public: CycleDataType *locked_cdata, Thread *current_thread = Thread::get_current_thread()); INLINE CycleDataWriter(const CycleDataWriter ©); - INLINE void operator = (const CycleDataWriter ©); + INLINE CycleDataWriter(CycleDataWriter &&from) noexcept; INLINE CycleDataWriter(PipelineCycler &cycler, CycleDataLockedReader &take_from); INLINE CycleDataWriter(PipelineCycler &cycler, CycleDataLockedReader &take_from, bool force_to_0); -#if defined(USE_MOVE_SEMANTICS) && defined(DO_PIPELINING) - INLINE CycleDataWriter(CycleDataWriter &&from) NOEXCEPT; - INLINE void operator = (CycleDataWriter &&from) NOEXCEPT; -#endif + INLINE void operator = (CycleDataWriter &&from) noexcept; + INLINE void operator = (const CycleDataWriter ©); INLINE ~CycleDataWriter(); diff --git a/panda/src/pipeline/cyclerHolder.I b/panda/src/pipeline/cyclerHolder.I index d9d2782373..f30ca75751 100644 --- a/panda/src/pipeline/cyclerHolder.I +++ b/panda/src/pipeline/cyclerHolder.I @@ -31,19 +31,3 @@ INLINE CyclerHolder:: _cycler->release(); #endif } - -/** - * Do not attempt to copy CyclerHolders. - */ -INLINE CyclerHolder:: -CyclerHolder(const CyclerHolder ©) { - nassertv(false); -} - -/** - * Do not attempt to copy CyclerHolders. - */ -INLINE void CyclerHolder:: -operator = (const CyclerHolder ©) { - nassertv(false); -} diff --git a/panda/src/pipeline/cyclerHolder.h b/panda/src/pipeline/cyclerHolder.h index fa5b81a30f..f1888345be 100644 --- a/panda/src/pipeline/cyclerHolder.h +++ b/panda/src/pipeline/cyclerHolder.h @@ -25,10 +25,10 @@ class EXPCL_PANDA_PIPELINE CyclerHolder { public: INLINE CyclerHolder(PipelineCyclerBase &cycler); + CyclerHolder(const CyclerHolder ©) = delete; INLINE ~CyclerHolder(); -private: - INLINE CyclerHolder(const CyclerHolder ©); - INLINE void operator = (const CyclerHolder ©); + + CyclerHolder &operator = (const CyclerHolder ©) = delete; private: #ifdef DO_PIPELINING diff --git a/panda/src/pipeline/externalThread.cxx b/panda/src/pipeline/externalThread.cxx index 411c4f2062..d77fc194ea 100644 --- a/panda/src/pipeline/externalThread.cxx +++ b/panda/src/pipeline/externalThread.cxx @@ -31,7 +31,7 @@ ExternalThread() : Thread("External", "External") { * external thread that is bound via Thread::bind_thread(). */ ExternalThread:: -ExternalThread(const string &name, const string &sync_name) : +ExternalThread(const std::string &name, const std::string &sync_name) : Thread(name, sync_name) { _started = true; diff --git a/panda/src/pipeline/externalThread.h b/panda/src/pipeline/externalThread.h index aaff62ac18..0b6add95b1 100644 --- a/panda/src/pipeline/externalThread.h +++ b/panda/src/pipeline/externalThread.h @@ -24,7 +24,7 @@ class EXPCL_PANDA_PIPELINE ExternalThread : public Thread { private: ExternalThread(); - ExternalThread(const string &name, const string &sync_name); + ExternalThread(const std::string &name, const std::string &sync_name); virtual void thread_main(); PUBLISHED: diff --git a/panda/src/pipeline/genericThread.cxx b/panda/src/pipeline/genericThread.cxx index eb1941a5e3..64eb0b4814 100644 --- a/panda/src/pipeline/genericThread.cxx +++ b/panda/src/pipeline/genericThread.cxx @@ -20,18 +20,18 @@ TypeHandle GenericThread::_type_handle; * */ GenericThread:: -GenericThread(const string &name, const string &sync_name) : +GenericThread(const std::string &name, const std::string &sync_name) : Thread(name, sync_name) { - _function = NULL; - _user_data = NULL; + _function = nullptr; + _user_data = nullptr; } /** * */ GenericThread:: -GenericThread(const string &name, const string &sync_name, GenericThread::ThreadFunc *function, void *user_data) : +GenericThread(const std::string &name, const std::string &sync_name, GenericThread::ThreadFunc *function, void *user_data) : Thread(name, sync_name), _function(function), _user_data(user_data) @@ -43,6 +43,6 @@ GenericThread(const string &name, const string &sync_name, GenericThread::Thread */ void GenericThread:: thread_main() { - nassertv(_function != NULL); + nassertv(_function != nullptr); (*_function)(_user_data); } diff --git a/panda/src/pipeline/genericThread.h b/panda/src/pipeline/genericThread.h index 3e07e6a7e1..6e6a6ade6a 100644 --- a/panda/src/pipeline/genericThread.h +++ b/panda/src/pipeline/genericThread.h @@ -25,8 +25,8 @@ class EXPCL_PANDA_PIPELINE GenericThread : public Thread { public: typedef void ThreadFunc(void *user_data); - GenericThread(const string &name, const string &sync_name); - GenericThread(const string &name, const string &sync_name, ThreadFunc *function, void *user_data); + GenericThread(const std::string &name, const std::string &sync_name); + GenericThread(const std::string &name, const std::string &sync_name, ThreadFunc *function, void *user_data); INLINE void set_function(ThreadFunc *function); INLINE ThreadFunc *get_function() const; diff --git a/panda/src/pipeline/lightMutex.I b/panda/src/pipeline/lightMutex.I index a7bb09ed17..b76b743e34 100644 --- a/panda/src/pipeline/lightMutex.I +++ b/panda/src/pipeline/lightMutex.I @@ -16,7 +16,7 @@ */ INLINE LightMutex:: #ifdef DEBUG_THREADS -LightMutex() : MutexDebug(string(), false, true) +LightMutex() : MutexDebug(std::string(), false, true) #else LightMutex() #endif // DEBUG_THREADS @@ -28,7 +28,7 @@ LightMutex() */ INLINE LightMutex:: #ifdef DEBUG_THREADS -LightMutex(const char *name) : MutexDebug(string(name), false, true) +LightMutex(const char *name) : MutexDebug(std::string(name), false, true) #else LightMutex(const char *) #endif // DEBUG_THREADS @@ -40,37 +40,9 @@ LightMutex(const char *) */ INLINE LightMutex:: #ifdef DEBUG_THREADS -LightMutex(const string &name) : MutexDebug(name, false, true) +LightMutex(const std::string &name) : MutexDebug(name, false, true) #else -LightMutex(const string &) +LightMutex(const std::string &) #endif // DEBUG_THREADS { } - -/** - * - */ -INLINE LightMutex:: -~LightMutex() { -} - -/** - * Do not attempt to copy lightMutexes. - */ -INLINE LightMutex:: -#ifdef DEBUG_THREADS -LightMutex(const LightMutex ©) : MutexDebug(string(), false, true) -#else - LightMutex(const LightMutex ©) -#endif // DEBUG_THREADS -{ - nassertv(false); -} - -/** - * Do not attempt to copy lightMutexes. - */ -INLINE void LightMutex:: -operator = (const LightMutex ©) { - nassertv(false); -} diff --git a/panda/src/pipeline/lightMutex.h b/panda/src/pipeline/lightMutex.h index 77ad4b26ae..4d8ae9a785 100644 --- a/panda/src/pipeline/lightMutex.h +++ b/panda/src/pipeline/lightMutex.h @@ -44,11 +44,11 @@ PUBLISHED: public: INLINE explicit LightMutex(const char *name); PUBLISHED: - INLINE explicit LightMutex(const string &name); - INLINE ~LightMutex(); -private: - INLINE LightMutex(const LightMutex ©); - INLINE void operator = (const LightMutex ©); + INLINE explicit LightMutex(const std::string &name); + LightMutex(const LightMutex ©) = delete; + ~LightMutex() = default; + + LightMutex &operator = (const LightMutex ©) = delete; }; #include "lightMutex.I" diff --git a/panda/src/pipeline/lightMutexDirect.I b/panda/src/pipeline/lightMutexDirect.I index 052ba9a8bf..a43921ecfb 100644 --- a/panda/src/pipeline/lightMutexDirect.I +++ b/panda/src/pipeline/lightMutexDirect.I @@ -12,33 +12,33 @@ */ /** - * - */ -INLINE LightMutexDirect:: -LightMutexDirect() { -} - -/** - * - */ -INLINE LightMutexDirect:: -~LightMutexDirect() { -} - -/** - * Do not attempt to copy lightMutexes. - */ -INLINE LightMutexDirect:: -LightMutexDirect(const LightMutexDirect ©) { - nassertv(false); -} - -/** - * Do not attempt to copy lightMutexes. + * Alias for acquire() to match C++11 semantics. + * @see acquire() */ INLINE void LightMutexDirect:: -operator = (const LightMutexDirect ©) { - nassertv(false); +lock() { + TAU_PROFILE("void LightMutexDirect::acquire()", " ", TAU_USER); + _impl.lock(); +} + +/** + * Alias for try_acquire() to match C++11 semantics. + * @see try_acquire() + */ +INLINE bool LightMutexDirect:: +try_lock() { + TAU_PROFILE("void LightMutexDirect::try_acquire()", " ", TAU_USER); + return _impl.try_lock(); +} + +/** + * Alias for release() to match C++11 semantics. + * @see release() + */ +INLINE void LightMutexDirect:: +unlock() { + TAU_PROFILE("void LightMutexDirect::unlock()", " ", TAU_USER); + _impl.unlock(); } /** @@ -55,7 +55,7 @@ operator = (const LightMutexDirect ©) { INLINE void LightMutexDirect:: acquire() const { TAU_PROFILE("void LightMutexDirect::acquire()", " ", TAU_USER); - ((LightMutexDirect *)this)->_impl.acquire(); + _impl.lock(); } /** @@ -68,7 +68,7 @@ acquire() const { INLINE void LightMutexDirect:: release() const { TAU_PROFILE("void LightMutexDirect::release()", " ", TAU_USER); - ((LightMutexDirect *)this)->_impl.release(); + _impl.unlock(); } /** @@ -86,7 +86,7 @@ debug_is_locked() const { * The lightMutex name is only defined when compiling in DEBUG_THREADS mode. */ INLINE void LightMutexDirect:: -set_name(const string &) { +set_name(const std::string &) { } /** @@ -107,7 +107,7 @@ has_name() const { /** * The lightMutex name is only defined when compiling in DEBUG_THREADS mode. */ -INLINE string LightMutexDirect:: +INLINE std::string LightMutexDirect:: get_name() const { - return string(); + return std::string(); } diff --git a/panda/src/pipeline/lightMutexDirect.cxx b/panda/src/pipeline/lightMutexDirect.cxx index ed5d1a30ff..522d361032 100644 --- a/panda/src/pipeline/lightMutexDirect.cxx +++ b/panda/src/pipeline/lightMutexDirect.cxx @@ -20,7 +20,7 @@ * LightMutexDirect. */ void LightMutexDirect:: -output(ostream &out) const { +output(std::ostream &out) const { out << "LightMutex " << (void *)this; } diff --git a/panda/src/pipeline/lightMutexDirect.h b/panda/src/pipeline/lightMutexDirect.h index e2085f6d29..e72bd808fe 100644 --- a/panda/src/pipeline/lightMutexDirect.h +++ b/panda/src/pipeline/lightMutexDirect.h @@ -30,23 +30,28 @@ class Thread; */ class EXPCL_PANDA_PIPELINE LightMutexDirect { protected: - INLINE LightMutexDirect(); - INLINE ~LightMutexDirect(); -private: - INLINE LightMutexDirect(const LightMutexDirect ©); - INLINE void operator = (const LightMutexDirect ©); + LightMutexDirect() = default; + LightMutexDirect(const LightMutexDirect ©) = delete; + ~LightMutexDirect() = default; + + void operator = (const LightMutexDirect ©) = delete; + +public: + INLINE void lock(); + INLINE bool try_lock(); + INLINE void unlock(); PUBLISHED: BLOCKING INLINE void acquire() const; INLINE void release() const; INLINE bool debug_is_locked() const; - INLINE void set_name(const string &name); + INLINE void set_name(const std::string &name); INLINE void clear_name(); INLINE bool has_name() const; - INLINE string get_name() const; + INLINE std::string get_name() const; - void output(ostream &out) const; + void output(std::ostream &out) const; private: #ifdef DO_PSTATS @@ -54,14 +59,14 @@ private: // even in the SIMPLE_THREADS case. We have to do this since any PStatTimer // call may trigger a context switch, and any low-level context switch // requires all containing mutexes to be true mutexes. - MutexTrueImpl _impl; + mutable MutexTrueImpl _impl; #else - MutexImpl _impl; + mutable MutexImpl _impl; #endif // DO_PSTATS }; -INLINE ostream & -operator << (ostream &out, const LightMutexDirect &m) { +INLINE std::ostream & +operator << (std::ostream &out, const LightMutexDirect &m) { m.output(out); return out; } diff --git a/panda/src/pipeline/lightMutexHolder.I b/panda/src/pipeline/lightMutexHolder.I index 392a234b29..6793c533ca 100644 --- a/panda/src/pipeline/lightMutexHolder.I +++ b/panda/src/pipeline/lightMutexHolder.I @@ -33,7 +33,7 @@ LightMutexHolder(const LightMutex &mutex) { INLINE LightMutexHolder:: LightMutexHolder(LightMutex *&mutex) { #if defined(HAVE_THREADS) || defined(DEBUG_THREADS) - if (mutex == (LightMutex *)NULL) { + if (mutex == nullptr) { mutex = new LightMutex; } _mutex = mutex; @@ -50,19 +50,3 @@ INLINE LightMutexHolder:: _mutex->release(); #endif } - -/** - * Do not attempt to copy LightMutexHolders. - */ -INLINE LightMutexHolder:: -LightMutexHolder(const LightMutexHolder ©) { - nassertv(false); -} - -/** - * Do not attempt to copy LightMutexHolders. - */ -INLINE void LightMutexHolder:: -operator = (const LightMutexHolder ©) { - nassertv(false); -} diff --git a/panda/src/pipeline/lightMutexHolder.h b/panda/src/pipeline/lightMutexHolder.h index 778ac69722..fde6a4ba9a 100644 --- a/panda/src/pipeline/lightMutexHolder.h +++ b/panda/src/pipeline/lightMutexHolder.h @@ -26,10 +26,10 @@ class EXPCL_PANDA_PIPELINE LightMutexHolder { public: INLINE LightMutexHolder(const LightMutex &mutex); INLINE LightMutexHolder(LightMutex *&mutex); + LightMutexHolder(const LightMutexHolder ©) = delete; INLINE ~LightMutexHolder(); -private: - INLINE LightMutexHolder(const LightMutexHolder ©); - INLINE void operator = (const LightMutexHolder ©); + + LightMutexHolder &operator = (const LightMutexHolder ©) = delete; private: #if defined(HAVE_THREADS) || defined(DEBUG_THREADS) diff --git a/panda/src/pipeline/lightReMutex.I b/panda/src/pipeline/lightReMutex.I index e1993f5dee..bc27a5a711 100644 --- a/panda/src/pipeline/lightReMutex.I +++ b/panda/src/pipeline/lightReMutex.I @@ -16,7 +16,7 @@ */ INLINE LightReMutex:: #ifdef DEBUG_THREADS -LightReMutex() : MutexDebug(string(), true, true) +LightReMutex() : MutexDebug(std::string(), true, true) #else LightReMutex() #endif // DEBUG_THREADS @@ -28,7 +28,7 @@ LightReMutex() */ INLINE LightReMutex:: #ifdef DEBUG_THREADS -LightReMutex(const char *name) : MutexDebug(string(name), true, true) +LightReMutex(const char *name) : MutexDebug(std::string(name), true, true) #else LightReMutex(const char *) #endif // DEBUG_THREADS @@ -40,24 +40,9 @@ LightReMutex(const char *) */ INLINE LightReMutex:: #ifdef DEBUG_THREADS -LightReMutex(const string &name) : MutexDebug(name, true, true) +LightReMutex(const std::string &name) : MutexDebug(name, true, true) #else -LightReMutex(const string &) +LightReMutex(const std::string &) #endif // DEBUG_THREADS { } - -/** - * - */ -INLINE LightReMutex:: -~LightReMutex() { -} - -/** - * Do not attempt to copy mutexes. - */ -INLINE void LightReMutex:: -operator = (const LightReMutex ©) { - nassertv(false); -} diff --git a/panda/src/pipeline/lightReMutex.h b/panda/src/pipeline/lightReMutex.h index 6959c4ab17..b219d7d10c 100644 --- a/panda/src/pipeline/lightReMutex.h +++ b/panda/src/pipeline/lightReMutex.h @@ -35,11 +35,11 @@ PUBLISHED: public: INLINE explicit LightReMutex(const char *name); PUBLISHED: - INLINE explicit LightReMutex(const string &name); - INLINE ~LightReMutex(); -private: - INLINE LightReMutex(const LightReMutex ©); - INLINE void operator = (const LightReMutex ©); + INLINE explicit LightReMutex(const std::string &name); + LightReMutex(const LightReMutex ©) = delete; + ~LightReMutex() = default; + + LightReMutex &operator = (const LightReMutex ©) = delete; }; #include "lightReMutex.I" diff --git a/panda/src/pipeline/lightReMutexDirect.I b/panda/src/pipeline/lightReMutexDirect.I index be78a3919e..08bb0daa67 100644 --- a/panda/src/pipeline/lightReMutexDirect.I +++ b/panda/src/pipeline/lightReMutexDirect.I @@ -21,36 +21,39 @@ LightReMutexDirect() #endif { #ifndef HAVE_REMUTEXIMPL - _locking_thread = NULL; + _locking_thread = nullptr; _lock_count = 0; #endif } /** - * - */ -INLINE LightReMutexDirect:: -~LightReMutexDirect() { -} - -/** - * Do not attempt to copy lightReMutexes. - */ -INLINE LightReMutexDirect:: -LightReMutexDirect(const LightReMutexDirect ©) -#ifndef HAVE_REMUTEXIMPL - : _cvar_impl(_lock_impl) -#endif -{ - nassertv(false); -} - -/** - * Do not attempt to copy lightReMutexes. + * Alias for acquire() to match C++11 semantics. + * @see acquire() */ INLINE void LightReMutexDirect:: -operator = (const LightReMutexDirect ©) { - nassertv(false); +lock() { + TAU_PROFILE("void LightReMutexDirect::acquire()", " ", TAU_USER); + _impl.lock(); +} + +/** + * Alias for try_acquire() to match C++11 semantics. + * @see try_acquire() + */ +INLINE bool LightReMutexDirect:: +try_lock() { + TAU_PROFILE("void LightReMutexDirect::try_acquire()", " ", TAU_USER); + return _impl.try_lock(); +} + +/** + * Alias for release() to match C++11 semantics. + * @see release() + */ +INLINE void LightReMutexDirect:: +unlock() { + TAU_PROFILE("void LightReMutexDirect::unlock()", " ", TAU_USER); + _impl.unlock(); } /** @@ -67,7 +70,11 @@ operator = (const LightReMutexDirect ©) { INLINE void LightReMutexDirect:: acquire() const { TAU_PROFILE("void LightReMutexDirect::acquire()", " ", TAU_USER); - ((LightReMutexDirect *)this)->_impl.acquire(); +#ifdef HAVE_REMUTEXTRUEIMPL + _impl.lock(); +#else + _impl.do_lock(Thread::get_current_thread()); +#endif } /** @@ -77,10 +84,10 @@ acquire() const { INLINE void LightReMutexDirect:: acquire(Thread *current_thread) const { TAU_PROFILE("void LightReMutexDirect::acquire(Thread *)", " ", TAU_USER); -#ifdef HAVE_REMUTEXIMPL - ((LightReMutexDirect *)this)->_impl.acquire(); +#ifdef HAVE_REMUTEXTRUEIMPL + _impl.lock(); #else - ((LightReMutexDirect *)this)->_impl.do_lock(current_thread); + _impl.do_lock(current_thread); #endif // HAVE_REMUTEXIMPL } @@ -97,10 +104,10 @@ acquire(Thread *current_thread) const { INLINE void LightReMutexDirect:: elevate_lock() const { TAU_PROFILE("void LightReMutexDirect::elevate_lock()", " ", TAU_USER); -#ifdef HAVE_REMUTEXIMPL - ((LightReMutexDirect *)this)->_impl.acquire(); +#ifdef HAVE_REMUTEXTRUEIMPL + _impl.lock(); #else - ((LightReMutexDirect *)this)->_impl.do_elevate_lock(); + _impl.do_elevate_lock(); #endif // HAVE_REMUTEXIMPL } @@ -114,7 +121,11 @@ elevate_lock() const { INLINE void LightReMutexDirect:: release() const { TAU_PROFILE("void LightReMutexDirect::release()", " ", TAU_USER); - ((LightReMutexDirect *)this)->_impl.release(); +#ifdef HAVE_REMUTEXTRUEIMPL + _impl.unlock(); +#else + _impl.do_unlock(Thread::get_current_thread()); +#endif } /** @@ -132,7 +143,7 @@ debug_is_locked() const { * The mutex name is only defined when compiling in DEBUG_THREADS mode. */ INLINE void LightReMutexDirect:: -set_name(const string &) { +set_name(const std::string &) { } /** @@ -153,7 +164,7 @@ has_name() const { /** * The mutex name is only defined when compiling in DEBUG_THREADS mode. */ -INLINE string LightReMutexDirect:: +INLINE std::string LightReMutexDirect:: get_name() const { - return string(); + return std::string(); } diff --git a/panda/src/pipeline/lightReMutexDirect.cxx b/panda/src/pipeline/lightReMutexDirect.cxx index fdfcc71cd2..9166f87867 100644 --- a/panda/src/pipeline/lightReMutexDirect.cxx +++ b/panda/src/pipeline/lightReMutexDirect.cxx @@ -21,7 +21,7 @@ * LightReMutexDirect. */ void LightReMutexDirect:: -output(ostream &out) const { +output(std::ostream &out) const { out << "LightReMutex " << (void *)this; } diff --git a/panda/src/pipeline/lightReMutexDirect.h b/panda/src/pipeline/lightReMutexDirect.h index 9daeff46a2..56371cc443 100644 --- a/panda/src/pipeline/lightReMutexDirect.h +++ b/panda/src/pipeline/lightReMutexDirect.h @@ -30,10 +30,15 @@ class Thread; class EXPCL_PANDA_PIPELINE LightReMutexDirect { protected: INLINE LightReMutexDirect(); - INLINE ~LightReMutexDirect(); -private: - INLINE LightReMutexDirect(const LightReMutexDirect ©); - INLINE void operator = (const LightReMutexDirect ©); + LightReMutexDirect(const LightReMutexDirect ©) = delete; + ~LightReMutexDirect() = default; + + void operator = (const LightReMutexDirect ©) = delete; + +public: + INLINE void lock(); + INLINE bool try_lock(); + INLINE void unlock(); PUBLISHED: BLOCKING INLINE void acquire() const; @@ -43,26 +48,26 @@ PUBLISHED: INLINE bool debug_is_locked() const; - INLINE void set_name(const string &name); + INLINE void set_name(const std::string &name); INLINE void clear_name(); INLINE bool has_name() const; - INLINE string get_name() const; + INLINE std::string get_name() const; - void output(ostream &out) const; + void output(std::ostream &out) const; private: -#if defined(HAVE_REMUTEXIMPL) && !defined(DO_PSTATS) - ReMutexImpl _impl; +#ifdef HAVE_REMUTEXTRUEIMPL + mutable ReMutexImpl _impl; #else // If we don't have a reentrant mutex, use the one we hand-rolled in // ReMutexDirect. - ReMutexDirect _impl; + mutable ReMutexDirect _impl; #endif // HAVE_REMUTEXIMPL }; -INLINE ostream & -operator << (ostream &out, const LightReMutexDirect &m) { +INLINE std::ostream & +operator << (std::ostream &out, const LightReMutexDirect &m) { m.output(out); return out; } diff --git a/panda/src/pipeline/lightReMutexHolder.I b/panda/src/pipeline/lightReMutexHolder.I index 96141251d7..8c0f82d98a 100644 --- a/panda/src/pipeline/lightReMutexHolder.I +++ b/panda/src/pipeline/lightReMutexHolder.I @@ -45,7 +45,7 @@ LightReMutexHolder(const LightReMutex &mutex, Thread *current_thread) { INLINE LightReMutexHolder:: LightReMutexHolder(LightReMutex *&mutex) { #if defined(HAVE_THREADS) || defined(DEBUG_THREADS) - if (mutex == (LightReMutex *)NULL) { + if (mutex == nullptr) { mutex = new LightReMutex; } _mutex = mutex; @@ -62,19 +62,3 @@ INLINE LightReMutexHolder:: _mutex->release(); #endif } - -/** - * Do not attempt to copy LightReMutexHolders. - */ -INLINE LightReMutexHolder:: -LightReMutexHolder(const LightReMutexHolder ©) { - nassertv(false); -} - -/** - * Do not attempt to copy LightReMutexHolders. - */ -INLINE void LightReMutexHolder:: -operator = (const LightReMutexHolder ©) { - nassertv(false); -} diff --git a/panda/src/pipeline/lightReMutexHolder.h b/panda/src/pipeline/lightReMutexHolder.h index 462b22180b..019206fbac 100644 --- a/panda/src/pipeline/lightReMutexHolder.h +++ b/panda/src/pipeline/lightReMutexHolder.h @@ -27,10 +27,10 @@ public: INLINE LightReMutexHolder(const LightReMutex &mutex); INLINE LightReMutexHolder(const LightReMutex &mutex, Thread *current_thread); INLINE LightReMutexHolder(LightReMutex *&mutex); + LightReMutexHolder(const LightReMutexHolder ©) = delete; INLINE ~LightReMutexHolder(); -private: - INLINE LightReMutexHolder(const LightReMutexHolder ©); - INLINE void operator = (const LightReMutexHolder ©); + + LightReMutexHolder &operator = (const LightReMutexHolder ©) = delete; private: #if defined(HAVE_THREADS) || defined(DEBUG_THREADS) diff --git a/panda/src/pipeline/mutexDebug.I b/panda/src/pipeline/mutexDebug.I index 6a487bde8f..ae3ce74967 100644 --- a/panda/src/pipeline/mutexDebug.I +++ b/panda/src/pipeline/mutexDebug.I @@ -12,19 +12,40 @@ */ /** - * Do not attempt to copy mutexes. + * Alias for acquire() to match C++11 semantics. + * @see acquire() */ -INLINE MutexDebug:: -MutexDebug(const MutexDebug ©) : _cvar_impl(*get_global_lock()) { - nassertv(false); +INLINE void MutexDebug:: +lock() { + TAU_PROFILE("void MutexDebug::acquire()", " ", TAU_USER); + _global_lock->lock(); + ((MutexDebug *)this)->do_lock(Thread::get_current_thread()); + _global_lock->unlock(); } /** - * Do not attempt to copy mutexes. + * Alias for try_acquire() to match C++11 semantics. + * @see try_acquire() + */ +INLINE bool MutexDebug:: +try_lock() { + TAU_PROFILE("void MutexDebug::try_lock()", " ", TAU_USER); + _global_lock->lock(); + bool acquired = ((MutexDebug *)this)->do_try_lock(Thread::get_current_thread()); + _global_lock->unlock(); + return acquired; +} + +/** + * Alias for release() to match C++11 semantics. + * @see release() */ INLINE void MutexDebug:: -operator = (const MutexDebug ©) { - nassertv(false); +unlock() { + TAU_PROFILE("void MutexDebug::unlock()", " ", TAU_USER); + _global_lock->lock(); + ((MutexDebug *)this)->do_unlock(); + _global_lock->unlock(); } /** @@ -41,9 +62,9 @@ INLINE void MutexDebug:: acquire(Thread *current_thread) const { TAU_PROFILE("void MutexDebug::acquire(Thread *)", " ", TAU_USER); nassertv(current_thread == Thread::get_current_thread()); - _global_lock->acquire(); - ((MutexDebug *)this)->do_acquire(current_thread); - _global_lock->release(); + _global_lock->lock(); + ((MutexDebug *)this)->do_lock(current_thread); + _global_lock->unlock(); } /** @@ -52,11 +73,11 @@ acquire(Thread *current_thread) const { */ INLINE bool MutexDebug:: try_acquire(Thread *current_thread) const { - TAU_PROFILE("void MutexDebug::acquire(Thread *)", " ", TAU_USER); + TAU_PROFILE("void MutexDebug::try_acquire(Thread *)", " ", TAU_USER); nassertr(current_thread == Thread::get_current_thread(), false); - _global_lock->acquire(); - bool acquired = ((MutexDebug *)this)->do_try_acquire(current_thread); - _global_lock->release(); + _global_lock->lock(); + bool acquired = ((MutexDebug *)this)->do_try_lock(current_thread); + _global_lock->unlock(); return acquired; } @@ -93,9 +114,9 @@ elevate_lock() const { INLINE void MutexDebug:: release() const { TAU_PROFILE("void MutexDebug::release()", " ", TAU_USER); - _global_lock->acquire(); - ((MutexDebug *)this)->do_release(); - _global_lock->release(); + _global_lock->lock(); + ((MutexDebug *)this)->do_unlock(); + _global_lock->unlock(); } /** @@ -107,9 +128,9 @@ release() const { INLINE bool MutexDebug:: debug_is_locked() const { TAU_PROFILE("bool MutexDebug::debug_is_locked()", " ", TAU_USER); - _global_lock->acquire(); + _global_lock->lock(); bool is_locked = do_debug_is_locked(); - _global_lock->release(); + _global_lock->unlock(); return is_locked; } @@ -121,7 +142,7 @@ debug_is_locked() const { */ INLINE MutexTrueImpl *MutexDebug:: get_global_lock() { - if (_global_lock == (MutexTrueImpl *)NULL) { + if (_global_lock == nullptr) { _global_lock = new MutexTrueImpl; } return _global_lock; diff --git a/panda/src/pipeline/mutexDebug.cxx b/panda/src/pipeline/mutexDebug.cxx index d22a923694..d1e0194e6f 100644 --- a/panda/src/pipeline/mutexDebug.cxx +++ b/panda/src/pipeline/mutexDebug.cxx @@ -17,6 +17,9 @@ #ifdef DEBUG_THREADS +using std::ostream; +using std::ostringstream; + int MutexDebug::_pstats_count = 0; MutexTrueImpl *MutexDebug::_global_lock; @@ -24,13 +27,13 @@ MutexTrueImpl *MutexDebug::_global_lock; * */ MutexDebug:: -MutexDebug(const string &name, bool allow_recursion, bool lightweight) : +MutexDebug(const std::string &name, bool allow_recursion, bool lightweight) : Namable(name), _allow_recursion(allow_recursion), _lightweight(lightweight), - _locking_thread(NULL), + _locking_thread(nullptr), _lock_count(0), - _deleted_name(NULL), + _deleted_name(nullptr), _cvar_impl(*get_global_lock()) { #ifndef SIMPLE_THREADS @@ -45,7 +48,7 @@ MutexDebug(const string &name, bool allow_recursion, bool lightweight) : */ MutexDebug:: ~MutexDebug() { - nassertv(_locking_thread == NULL && _lock_count == 0); + nassertv(_locking_thread == nullptr && _lock_count == 0); // If the config variable says to, allocate (and leak) a string name for the // mutex, so we can report which mutex it is that has destructed after the @@ -53,7 +56,7 @@ MutexDebug:: if (name_deleted_mutexes) { ostringstream strm; strm << *this; - string name = strm.str(); + std::string name = strm.str(); _deleted_name = strdup((char *)name.c_str()); } @@ -84,12 +87,12 @@ output(ostream &out) const { */ void MutexDebug:: output_with_holder(ostream &out) const { - _global_lock->acquire(); + _global_lock->lock(); output(out); - if (_locking_thread != (Thread *)NULL) { + if (_locking_thread != nullptr) { out << " (held by " << *_locking_thread << ")\n"; } - _global_lock->release(); + _global_lock->unlock(); } /** @@ -99,9 +102,9 @@ output_with_holder(ostream &out) const { */ void MutexDebug:: increment_pstats() { - _global_lock->acquire(); + _global_lock->lock(); ++_pstats_count; - _global_lock->release(); + _global_lock->unlock(); } /** @@ -110,22 +113,22 @@ increment_pstats() { */ void MutexDebug:: decrement_pstats() { - _global_lock->acquire(); + _global_lock->lock(); --_pstats_count; - _global_lock->release(); + _global_lock->unlock(); } /** * The private implementation of acquire() assumes that _lock_impl is held. */ void MutexDebug:: -do_acquire(Thread *current_thread) { +do_lock(Thread *current_thread) { // If this assertion is triggered, you tried to lock a recently-destructed // mutex. nassertd(_lock_count != -100) { pipeline_cat.error() << "Destructed mutex: " << (void *)this << "\n"; - if (name_deleted_mutexes && _deleted_name != NULL) { + if (name_deleted_mutexes && _deleted_name != nullptr) { pipeline_cat.error() << _deleted_name << "\n"; } else { @@ -135,7 +138,7 @@ do_acquire(Thread *current_thread) { return; } - if (_locking_thread == (Thread *)NULL) { + if (_locking_thread == nullptr) { // The mutex is not already locked by anyone. Lock it. _locking_thread = current_thread; ++_lock_count; @@ -178,7 +181,7 @@ do_acquire(Thread *current_thread) { // Check for deadlock. MutexDebug *next_mutex = this; - while (next_mutex != NULL) { + while (next_mutex != nullptr) { if (next_mutex->_locking_thread == current_thread) { // Whoops, the thread is blocked on me! Deadlock! report_deadlock(current_thread); @@ -186,7 +189,7 @@ do_acquire(Thread *current_thread) { return; } Thread *next_thread = next_mutex->_locking_thread; - if (next_thread == NULL) { + if (next_thread == nullptr) { // Looks like this mutex isn't actually locked, which means the last // thread isn't really blocked--it just hasn't woken up yet to // discover that. In any case, no deadlock. @@ -209,7 +212,7 @@ do_acquire(Thread *current_thread) { << *_locking_thread << ")\n"; } - while (_locking_thread != (Thread *)NULL) { + while (_locking_thread != nullptr) { thread_cat.debug() << *current_thread << " still blocking on " << *this << " (held by " << *_locking_thread << ")\n"; @@ -221,7 +224,7 @@ do_acquire(Thread *current_thread) { << *current_thread << " acquired " << *this << "\n"; } - current_thread->_blocked_on_mutex = NULL; + current_thread->_blocked_on_mutex = nullptr; _locking_thread = current_thread; ++_lock_count; @@ -235,13 +238,13 @@ do_acquire(Thread *current_thread) { * held. */ bool MutexDebug:: -do_try_acquire(Thread *current_thread) { +do_try_lock(Thread *current_thread) { // If this assertion is triggered, you tried to lock a recently-destructed // mutex. nassertd(_lock_count != -100) { pipeline_cat.error() << "Destructed mutex: " << (void *)this << "\n"; - if (name_deleted_mutexes && _deleted_name != NULL) { + if (name_deleted_mutexes && _deleted_name != nullptr) { pipeline_cat.error() << _deleted_name << "\n"; } else { @@ -252,7 +255,7 @@ do_try_acquire(Thread *current_thread) { } bool acquired = true; - if (_locking_thread == (Thread *)NULL) { + if (_locking_thread == nullptr) { // The mutex is not already locked by anyone. Lock it. _locking_thread = current_thread; ++_lock_count; @@ -301,13 +304,13 @@ do_try_acquire(Thread *current_thread) { * The private implementation of acquire() assumes that _lock_impl is held. */ void MutexDebug:: -do_release() { +do_unlock() { // If this assertion is triggered, you tried to release a recently- // destructed mutex. nassertd(_lock_count != -100) { pipeline_cat.error() << "Destructed mutex: " << (void *)this << "\n"; - if (name_deleted_mutexes && _deleted_name != NULL) { + if (name_deleted_mutexes && _deleted_name != nullptr) { pipeline_cat.error() << _deleted_name << "\n"; } else { @@ -350,7 +353,7 @@ do_release() { --_lock_count; if (_lock_count == 0) { // That was the last lock held by this thread. Release the lock. - _locking_thread = (Thread *)NULL; + _locking_thread = nullptr; if (_lightweight) { if (!_missed_threads.empty()) { @@ -415,7 +418,7 @@ report_deadlock(Thread *current_thread) { MutexDebug *next_mutex = this; Thread *next_thread = next_mutex->_locking_thread; next_mutex = next_thread->_blocked_on_mutex; - while (next_mutex != NULL) { + while (next_mutex != nullptr) { thread_cat.error() << *next_thread << " is blocked waiting on " << *next_mutex << " which is held by " diff --git a/panda/src/pipeline/mutexDebug.h b/panda/src/pipeline/mutexDebug.h index 24b8b6500f..094f2eafc6 100644 --- a/panda/src/pipeline/mutexDebug.h +++ b/panda/src/pipeline/mutexDebug.h @@ -29,11 +29,16 @@ */ class EXPCL_PANDA_PIPELINE MutexDebug : public Namable { protected: - MutexDebug(const string &name, bool allow_recursion, bool lightweight); + MutexDebug(const std::string &name, bool allow_recursion, bool lightweight); + MutexDebug(const MutexDebug ©) = delete; virtual ~MutexDebug(); -private: - INLINE MutexDebug(const MutexDebug ©); - INLINE void operator = (const MutexDebug ©); + + void operator = (const MutexDebug ©) = delete; + +public: + INLINE void lock(); + INLINE bool try_lock(); + INLINE void unlock(); PUBLISHED: BLOCKING INLINE void acquire(Thread *current_thread = Thread::get_current_thread()) const; @@ -42,8 +47,8 @@ PUBLISHED: INLINE void release() const; INLINE bool debug_is_locked() const; - virtual void output(ostream &out) const; - void output_with_holder(ostream &out) const; + virtual void output(std::ostream &out) const; + void output_with_holder(std::ostream &out) const; typedef void VoidFunc(); @@ -52,9 +57,9 @@ public: static void decrement_pstats(); private: - void do_acquire(Thread *current_thread); - bool do_try_acquire(Thread *current_thread); - void do_release(); + void do_lock(Thread *current_thread); + bool do_try_lock(Thread *current_thread); + void do_unlock(); bool do_debug_is_locked() const; void report_deadlock(Thread *current_thread); @@ -81,8 +86,8 @@ private: friend class ConditionVarFullDebug; }; -INLINE ostream & -operator << (ostream &out, const MutexDebug &m) { +INLINE std::ostream & +operator << (std::ostream &out, const MutexDebug &m) { m.output(out); return out; } diff --git a/panda/src/pipeline/mutexDirect.I b/panda/src/pipeline/mutexDirect.I index 0fb8c8b954..71a26543a7 100644 --- a/panda/src/pipeline/mutexDirect.I +++ b/panda/src/pipeline/mutexDirect.I @@ -12,33 +12,33 @@ */ /** - * - */ -INLINE MutexDirect:: -MutexDirect() { -} - -/** - * - */ -INLINE MutexDirect:: -~MutexDirect() { -} - -/** - * Do not attempt to copy mutexes. - */ -INLINE MutexDirect:: -MutexDirect(const MutexDirect ©) { - nassertv(false); -} - -/** - * Do not attempt to copy mutexes. + * Alias for acquire() to match C++11 semantics. + * @see acquire() */ INLINE void MutexDirect:: -operator = (const MutexDirect ©) { - nassertv(false); +lock() { + TAU_PROFILE("void MutexDirect::acquire()", " ", TAU_USER); + _impl.lock(); +} + +/** + * Alias for try_acquire() to match C++11 semantics. + * @see try_acquire() + */ +INLINE bool MutexDirect:: +try_lock() { + TAU_PROFILE("void MutexDirect::try_acquire()", " ", TAU_USER); + return _impl.try_lock(); +} + +/** + * Alias for release() to match C++11 semantics. + * @see release() + */ +INLINE void MutexDirect:: +unlock() { + TAU_PROFILE("void MutexDirect::unlock()", " ", TAU_USER); + _impl.unlock(); } /** @@ -54,7 +54,7 @@ operator = (const MutexDirect ©) { INLINE void MutexDirect:: acquire() const { TAU_PROFILE("void MutexDirect::acquire()", " ", TAU_USER); - ((MutexDirect *)this)->_impl.acquire(); + _impl.lock(); } /** @@ -64,7 +64,7 @@ acquire() const { INLINE bool MutexDirect:: try_acquire() const { TAU_PROFILE("void MutexDirect::acquire(bool)", " ", TAU_USER); - return ((MutexDirect *)this)->_impl.try_acquire(); + return _impl.try_lock(); } /** @@ -77,7 +77,7 @@ try_acquire() const { INLINE void MutexDirect:: release() const { TAU_PROFILE("void MutexDirect::release()", " ", TAU_USER); - ((MutexDirect *)this)->_impl.release(); + _impl.unlock(); } /** @@ -95,7 +95,7 @@ debug_is_locked() const { * The mutex name is only defined when compiling in DEBUG_THREADS mode. */ INLINE void MutexDirect:: -set_name(const string &) { +set_name(const std::string &) { } /** @@ -116,7 +116,7 @@ has_name() const { /** * The mutex name is only defined when compiling in DEBUG_THREADS mode. */ -INLINE string MutexDirect:: +INLINE std::string MutexDirect:: get_name() const { - return string(); + return std::string(); } diff --git a/panda/src/pipeline/mutexDirect.cxx b/panda/src/pipeline/mutexDirect.cxx index 5f74c67c93..29c0beb9b4 100644 --- a/panda/src/pipeline/mutexDirect.cxx +++ b/panda/src/pipeline/mutexDirect.cxx @@ -20,7 +20,7 @@ * MutexDirect. */ void MutexDirect:: -output(ostream &out) const { +output(std::ostream &out) const { out << "Mutex " << (void *)this; } diff --git a/panda/src/pipeline/mutexDirect.h b/panda/src/pipeline/mutexDirect.h index 494c067a12..068f5fc5c4 100644 --- a/panda/src/pipeline/mutexDirect.h +++ b/panda/src/pipeline/mutexDirect.h @@ -29,11 +29,16 @@ class Thread; */ class EXPCL_PANDA_PIPELINE MutexDirect { protected: - INLINE MutexDirect(); - INLINE ~MutexDirect(); -private: - INLINE MutexDirect(const MutexDirect ©); - INLINE void operator = (const MutexDirect ©); + MutexDirect() = default; + MutexDirect(const MutexDirect ©) = delete; + ~MutexDirect() = default; + + void operator = (const MutexDirect ©) = delete; + +public: + INLINE void lock(); + INLINE bool try_lock(); + INLINE void unlock(); PUBLISHED: BLOCKING INLINE void acquire() const; @@ -41,22 +46,22 @@ PUBLISHED: INLINE void release() const; INLINE bool debug_is_locked() const; - INLINE void set_name(const string &name); + INLINE void set_name(const std::string &name); INLINE void clear_name(); INLINE bool has_name() const; - INLINE string get_name() const; + INLINE std::string get_name() const; - void output(ostream &out) const; + void output(std::ostream &out) const; private: - MutexTrueImpl _impl; + mutable MutexTrueImpl _impl; friend class ConditionVarDirect; friend class ConditionVarFullDirect; }; -INLINE ostream & -operator << (ostream &out, const MutexDirect &m) { +INLINE std::ostream & +operator << (std::ostream &out, const MutexDirect &m) { m.output(out); return out; } diff --git a/panda/src/pipeline/mutexHolder.I b/panda/src/pipeline/mutexHolder.I index 9b1b99d6b6..f70220f338 100644 --- a/panda/src/pipeline/mutexHolder.I +++ b/panda/src/pipeline/mutexHolder.I @@ -47,7 +47,7 @@ MutexHolder(const Mutex &mutex, Thread *current_thread) { INLINE MutexHolder:: MutexHolder(Mutex *&mutex) { #if defined(HAVE_THREADS) || defined(DEBUG_THREADS) - if (mutex == (Mutex *)NULL) { + if (mutex == nullptr) { mutex = new Mutex; } _mutex = mutex; @@ -64,19 +64,3 @@ INLINE MutexHolder:: _mutex->release(); #endif } - -/** - * Do not attempt to copy MutexHolders. - */ -INLINE MutexHolder:: -MutexHolder(const MutexHolder ©) { - nassertv(false); -} - -/** - * Do not attempt to copy MutexHolders. - */ -INLINE void MutexHolder:: -operator = (const MutexHolder ©) { - nassertv(false); -} diff --git a/panda/src/pipeline/mutexHolder.h b/panda/src/pipeline/mutexHolder.h index 26f1af5d9d..ccd7b321a8 100644 --- a/panda/src/pipeline/mutexHolder.h +++ b/panda/src/pipeline/mutexHolder.h @@ -27,10 +27,10 @@ public: INLINE MutexHolder(const Mutex &mutex); INLINE MutexHolder(const Mutex &mutex, Thread *current_thread); INLINE MutexHolder(Mutex *&mutex); + MutexHolder(const MutexHolder ©) = delete; INLINE ~MutexHolder(); -private: - INLINE MutexHolder(const MutexHolder ©); - INLINE void operator = (const MutexHolder ©); + + MutexHolder &operator = (const MutexHolder ©) = delete; private: // If HAVE_THREADS is defined, the Mutex class implements an actual mutex diff --git a/panda/src/pipeline/mutexSimpleImpl.I b/panda/src/pipeline/mutexSimpleImpl.I index 82b3f5fa51..61123f83f6 100644 --- a/panda/src/pipeline/mutexSimpleImpl.I +++ b/panda/src/pipeline/mutexSimpleImpl.I @@ -11,27 +11,13 @@ * @date 2007-06-19 */ -/** - * - */ -INLINE MutexSimpleImpl:: -MutexSimpleImpl() { -} - -/** - * - */ -INLINE MutexSimpleImpl:: -~MutexSimpleImpl() { -} - /** * */ INLINE void MutexSimpleImpl:: -acquire() { - if (!try_acquire()) { - do_acquire(); +lock() { + if (!try_lock()) { + do_lock(); } } @@ -39,7 +25,7 @@ acquire() { * */ INLINE bool MutexSimpleImpl:: -try_acquire() { +try_lock() { if ((_flags & F_lock_count) != 0) { return false; } @@ -52,12 +38,12 @@ try_acquire() { * waiters on the mutex. */ INLINE void MutexSimpleImpl:: -release() { +unlock() { nassertv((_flags & F_lock_count) != 0); _flags &= ~F_lock_count; if (_flags & F_has_waiters) { - do_release(); + do_unlock(); } } @@ -65,11 +51,11 @@ release() { * Releases the mutex, without allowing a context switch to occur. */ INLINE void MutexSimpleImpl:: -release_quietly() { +unlock_quietly() { nassertv((_flags & F_lock_count) != 0); _flags &= ~F_lock_count; if (_flags & F_has_waiters) { - do_release_quietly(); + do_unlock_quietly(); } } diff --git a/panda/src/pipeline/mutexSimpleImpl.cxx b/panda/src/pipeline/mutexSimpleImpl.cxx index 0908104ae7..624a1989eb 100644 --- a/panda/src/pipeline/mutexSimpleImpl.cxx +++ b/panda/src/pipeline/mutexSimpleImpl.cxx @@ -23,7 +23,7 @@ * */ void MutexSimpleImpl:: -do_acquire() { +do_lock() { // By the time we get here, we already know that someone else is holding the // lock: (_flags & F_lock_count) != 0. ThreadSimpleManager *manager = ThreadSimpleManager::get_global_ptr(); @@ -41,7 +41,7 @@ do_acquire() { * */ void MutexSimpleImpl:: -do_release() { +do_unlock() { // By the time we get here, we already know that someone else is blocked on // this mutex: (_flags & F_waiters) != 0. ThreadSimpleManager *manager = ThreadSimpleManager::get_global_ptr(); @@ -58,7 +58,7 @@ do_release() { * */ void MutexSimpleImpl:: -do_release_quietly() { +do_unlock_quietly() { ThreadSimpleManager *manager = ThreadSimpleManager::get_global_ptr(); manager->unblock_one(this); } diff --git a/panda/src/pipeline/mutexSimpleImpl.h b/panda/src/pipeline/mutexSimpleImpl.h index 60b5bc56b1..3c194a08f1 100644 --- a/panda/src/pipeline/mutexSimpleImpl.h +++ b/panda/src/pipeline/mutexSimpleImpl.h @@ -36,18 +36,17 @@ */ class EXPCL_PANDA_PIPELINE MutexSimpleImpl : public BlockerSimple { public: - INLINE MutexSimpleImpl(); - INLINE ~MutexSimpleImpl(); + constexpr MutexSimpleImpl() = default; - INLINE void acquire(); - INLINE bool try_acquire(); - INLINE void release(); - INLINE void release_quietly(); + INLINE void lock(); + INLINE bool try_lock(); + INLINE void unlock(); + INLINE void unlock_quietly(); private: - void do_acquire(); - void do_release(); - void do_release_quietly(); + void do_lock(); + void do_unlock(); + void do_unlock_quietly(); friend class ThreadSimpleManager; }; diff --git a/panda/src/pipeline/pipeline.I b/panda/src/pipeline/pipeline.I index 9d3512ae6c..2116a030e6 100644 --- a/panda/src/pipeline/pipeline.I +++ b/panda/src/pipeline/pipeline.I @@ -16,7 +16,7 @@ */ INLINE Pipeline *Pipeline:: get_render_pipeline() { - if (_render_pipeline == (Pipeline *)NULL) { + if (_render_pipeline == nullptr) { make_render_pipeline(); } return _render_pipeline; @@ -27,7 +27,7 @@ get_render_pipeline() { */ INLINE void Pipeline:: set_min_stages(int min_stages) { - set_num_stages(max(min_stages, get_num_stages())); + set_num_stages(std::max(min_stages, get_num_stages())); } /** diff --git a/panda/src/pipeline/pipeline.cxx b/panda/src/pipeline/pipeline.cxx index e6fd1b6cee..a3633226bc 100644 --- a/panda/src/pipeline/pipeline.cxx +++ b/panda/src/pipeline/pipeline.cxx @@ -16,13 +16,13 @@ #include "configVariableInt.h" #include "config_pipeline.h" -Pipeline *Pipeline::_render_pipeline = (Pipeline *)NULL; +Pipeline *Pipeline::_render_pipeline = nullptr; /** * */ Pipeline:: -Pipeline(const string &name, int num_stages) : +Pipeline(const std::string &name, int num_stages) : Namable(name), #ifdef THREADED_PIPELINE _num_stages(num_stages), @@ -94,7 +94,7 @@ cycle() { pvector< PT(CycleData) > saved_cdatas; { ReMutexHolder cycle_holder(_cycle_lock); - int prev_seq, next_seq; + unsigned int prev_seq, next_seq; PipelineCyclerLinks prev_dirty; { // We can't hold the lock protecting the linked lists during the cycling @@ -134,7 +134,7 @@ cycle() { while (link != &prev_dirty) { PipelineCyclerTrueImpl *cycler = (PipelineCyclerTrueImpl *)link; - if (!cycler->_lock.try_acquire()) { + if (!cycler->_lock.try_lock()) { // No big deal, just move on to the next one for now, and we'll // come back around to it. It's important not to block here in // order to prevent one cycler from deadlocking another. @@ -144,7 +144,7 @@ cycle() { } else { // Well, we are the last cycler left, so we might as well wait. // This is necessary to trigger the deadlock detection code. - cycler->_lock.acquire(); + cycler->_lock.lock(); } } @@ -162,7 +162,7 @@ cycle() { #ifdef DEBUG_THREADS inc_cycler_type(_dirty_cycler_types, cycler->get_parent_type(), -1); #endif - cycler->_lock.release(); + cycler->_lock.unlock(); break; } } @@ -174,7 +174,7 @@ cycle() { while (link != &prev_dirty) { PipelineCyclerTrueImpl *cycler = (PipelineCyclerTrueImpl *)link; - if (!cycler->_lock.try_acquire()) { + if (!cycler->_lock.try_lock()) { // No big deal, just move on to the next one for now, and we'll // come back around to it. It's important not to block here in // order to prevent one cycler from deadlocking another. @@ -184,7 +184,7 @@ cycle() { } else { // Well, we are the last cycler left, so we might as well wait. // This is necessary to trigger the deadlock detection code. - cycler->_lock.acquire(); + cycler->_lock.lock(); } } @@ -206,7 +206,7 @@ cycle() { inc_cycler_type(_dirty_cycler_types, cycler->get_parent_type(), -1); #endif } - cycler->_lock.release(); + cycler->_lock.unlock(); break; } } @@ -218,7 +218,7 @@ cycle() { while (link != &prev_dirty) { PipelineCyclerTrueImpl *cycler = (PipelineCyclerTrueImpl *)link; - if (!cycler->_lock.try_acquire()) { + if (!cycler->_lock.try_lock()) { // No big deal, just move on to the next one for now, and we'll // come back around to it. It's important not to block here in // order to prevent one cycler from deadlocking another. @@ -228,7 +228,7 @@ cycle() { } else { // Well, we are the last cycler left, so we might as well wait. // This is necessary to trigger the deadlock detection code. - cycler->_lock.acquire(); + cycler->_lock.lock(); } } @@ -250,7 +250,7 @@ cycle() { inc_cycler_type(_dirty_cycler_types, cycler->get_parent_type(), -1); #endif } - cycler->_lock.release(); + cycler->_lock.unlock(); break; } } @@ -293,11 +293,11 @@ set_num_stages(int num_stages) { PipelineCyclerLinks *links; for (links = _clean._next; links != &_clean; links = links->_next) { PipelineCyclerTrueImpl *cycler = (PipelineCyclerTrueImpl *)links; - cycler->_lock.acquire(); + cycler->_lock.lock(); } for (links = _dirty._next; links != &_dirty; links = links->_next) { PipelineCyclerTrueImpl *cycler = (PipelineCyclerTrueImpl *)links; - cycler->_lock.acquire(); + cycler->_lock.lock(); } _num_stages = num_stages; @@ -315,12 +315,12 @@ set_num_stages(int num_stages) { int count = 0; for (links = _clean._next; links != &_clean; links = links->_next) { PipelineCyclerTrueImpl *cycler = (PipelineCyclerTrueImpl *)links; - cycler->_lock.release(); + cycler->_lock.unlock(); ++count; } for (links = _dirty._next; links != &_dirty; links = links->_next) { PipelineCyclerTrueImpl *cycler = (PipelineCyclerTrueImpl *)links; - cycler->_lock.release(); + cycler->_lock.unlock(); ++count; } nassertv(count == _num_cyclers); @@ -402,7 +402,7 @@ remove_cycler(PipelineCyclerTrueImpl *cycler) { // during cycle only if it's 0 (clean) or _next_cycle_seq (scheduled for the // next cycle, so not owned by the current one). while (cycler->_dirty != 0 && cycler->_dirty != _next_cycle_seq) { - if (_cycle_lock.try_acquire()) { + if (_cycle_lock.try_lock()) { // OK, great, we got the lock, so it finished cycling already. nassertv(!_cycling); @@ -417,16 +417,16 @@ remove_cycler(PipelineCyclerTrueImpl *cycler) { inc_cycler_type(_dirty_cycler_types, cycler->get_parent_type(), -1); #endif - _cycle_lock.release(); + _cycle_lock.unlock(); return; } else { // It's possibly currently being cycled. We will wait for the cycler // to be done with it, so that we can safely remove it. - _lock.release(); - cycler->_lock.release(); + _lock.unlock(); + cycler->_lock.unlock(); Thread::force_yield(); - cycler->_lock.acquire(); - _lock.acquire(); + cycler->_lock.lock(); + _lock.lock(); } } @@ -500,7 +500,7 @@ make_render_pipeline() { "pipeline stages than your application requires will incur " "additional runtime overhead.")); - nassertv(_render_pipeline == (Pipeline *)NULL); + nassertv(_render_pipeline == nullptr); _render_pipeline = new Pipeline("render", pipeline_stages); } diff --git a/panda/src/pipeline/pipeline.h b/panda/src/pipeline/pipeline.h index 1dbba9429f..c06bb2ffef 100644 --- a/panda/src/pipeline/pipeline.h +++ b/panda/src/pipeline/pipeline.h @@ -37,7 +37,7 @@ struct PipelineCyclerTrueImpl; */ class EXPCL_PANDA_PIPELINE Pipeline : public Namable { public: - Pipeline(const string &name, int num_stages); + Pipeline(const std::string &name, int num_stages); ~Pipeline(); INLINE static Pipeline *get_render_pipeline(); diff --git a/panda/src/pipeline/pipelineCycler.I b/panda/src/pipeline/pipelineCycler.I index 06c6c1e5dc..2cd818a747 100644 --- a/panda/src/pipeline/pipelineCycler.I +++ b/panda/src/pipeline/pipelineCycler.I @@ -31,7 +31,7 @@ PipelineCycler(Pipeline *pipeline) : template INLINE PipelineCycler:: PipelineCycler(CycleDataType &&initial_data, Pipeline *pipeline) : - PipelineCyclerBase(new CycleDataType(move(initial_data)), pipeline) + PipelineCyclerBase(new CycleDataType(std::move(initial_data)), pipeline) { } @@ -198,7 +198,7 @@ PipelineCycler(Pipeline *pipeline) : template INLINE PipelineCycler:: PipelineCycler(CycleDataType &&initial_data, Pipeline *pipeline) : - _typed_data(move(initial_data)), + _typed_data(std::move(initial_data)), PipelineCyclerBase(&_typed_data, pipeline) { } diff --git a/panda/src/pipeline/pipelineCyclerDummyImpl.I b/panda/src/pipeline/pipelineCyclerDummyImpl.I index 997bdc9a09..2d0a9a8f04 100644 --- a/panda/src/pipeline/pipelineCyclerDummyImpl.I +++ b/panda/src/pipeline/pipelineCyclerDummyImpl.I @@ -22,7 +22,7 @@ PipelineCyclerDummyImpl(CycleData *initial_data, Pipeline *pipeline) : _write_count(0), _locked(false) { - if (_pipeline == (Pipeline *)NULL) { + if (_pipeline == nullptr) { _pipeline = Pipeline::get_render_pipeline(); } } @@ -259,7 +259,7 @@ get_num_stages() { INLINE const CycleData *PipelineCyclerDummyImpl:: read_stage_unlocked(int pipeline_stage) const { TAU_PROFILE("const CycleData *PipelineCyclerDummyImpl::read_stage_unlocked(int)", " ", TAU_USER); - nassertr(pipeline_stage == 0, NULL); + nassertr(pipeline_stage == 0, nullptr); return _data; } @@ -276,7 +276,7 @@ read_stage(int pipeline_stage, Thread *) const { TAU_PROFILE("const CycleData *PipelineCyclerDummyImpl::read_stage(int, Thread *)", " ", TAU_USER); // This function isn't truly const, but it doesn't change the data in any // meaningful way, so we pretend it is. - nassertr(pipeline_stage == 0, NULL); + nassertr(pipeline_stage == 0, nullptr); ((PipelineCyclerDummyImpl *)this)->_read_count++; // It's not an error to grab a read pointer while someone else holds a read @@ -307,7 +307,7 @@ release_read_stage(int pipeline_stage, const CycleData *pointer) const { INLINE CycleData *PipelineCyclerDummyImpl:: write_stage(int pipeline_stage, Thread *) { TAU_PROFILE("CycleData *PipelineCyclerDummyImpl::write_stage(int)", " ", TAU_USER); - nassertr(pipeline_stage == 0, (CycleData *)NULL); + nassertr(pipeline_stage == 0, nullptr); _write_count++; return _data; } @@ -321,7 +321,7 @@ write_stage(int pipeline_stage, Thread *) { INLINE CycleData *PipelineCyclerDummyImpl:: write_stage_upstream(int pipeline_stage, bool, Thread *) { TAU_PROFILE("CycleData *PipelineCyclerDummyImpl::write_stage_upstream(int)", " ", TAU_USER); - nassertr(pipeline_stage == 0, (CycleData *)NULL); + nassertr(pipeline_stage == 0, nullptr); _write_count++; return _data; } @@ -334,7 +334,7 @@ write_stage_upstream(int pipeline_stage, bool, Thread *) { INLINE CycleData *PipelineCyclerDummyImpl:: elevate_read_stage(int pipeline_stage, const CycleData *pointer, Thread *current_thread) { TAU_PROFILE("CycleData *PipelineCyclerDummyImpl::elevate_read_stage(int, CycleData *)", " ", TAU_USER); - nassertr(pipeline_stage == 0, NULL); + nassertr(pipeline_stage == 0, nullptr); release_read(pointer); return write(current_thread); } @@ -348,7 +348,7 @@ INLINE CycleData *PipelineCyclerDummyImpl:: elevate_read_stage_upstream(int pipeline_stage, const CycleData *pointer, bool, Thread *current_thread) { TAU_PROFILE("CycleData *PipelineCyclerDummyImpl::elevate_read_stage(int, CycleData *)", " ", TAU_USER); - nassertr(pipeline_stage == 0, NULL); + nassertr(pipeline_stage == 0, nullptr); release_read(pointer); return write(current_thread); } diff --git a/panda/src/pipeline/pipelineCyclerDummyImpl.h b/panda/src/pipeline/pipelineCyclerDummyImpl.h index 00e0df9387..588bb09d0c 100644 --- a/panda/src/pipeline/pipelineCyclerDummyImpl.h +++ b/panda/src/pipeline/pipelineCyclerDummyImpl.h @@ -38,12 +38,12 @@ */ struct EXPCL_PANDA_PIPELINE PipelineCyclerDummyImpl { public: - INLINE PipelineCyclerDummyImpl(CycleData *initial_data, Pipeline *pipeline = NULL); + INLINE PipelineCyclerDummyImpl(CycleData *initial_data, Pipeline *pipeline = nullptr); INLINE PipelineCyclerDummyImpl(const PipelineCyclerDummyImpl ©); INLINE void operator = (const PipelineCyclerDummyImpl ©); INLINE ~PipelineCyclerDummyImpl(); - INLINE void acquire(Thread *current_thread = NULL); + INLINE void acquire(Thread *current_thread = nullptr); INLINE void release(); INLINE const CycleData *read_unlocked(Thread *current_thread) const; diff --git a/panda/src/pipeline/pipelineCyclerLinks.I b/panda/src/pipeline/pipelineCyclerLinks.I index 7b52a935a5..bc002e8cd6 100644 --- a/panda/src/pipeline/pipelineCyclerLinks.I +++ b/panda/src/pipeline/pipelineCyclerLinks.I @@ -18,8 +18,8 @@ INLINE PipelineCyclerLinks:: PipelineCyclerLinks() { #ifndef NDEBUG - _next = NULL; - _prev = NULL; + _next = nullptr; + _prev = nullptr; #endif } #endif // THREADED_PIPELINE @@ -30,7 +30,7 @@ PipelineCyclerLinks() { */ INLINE PipelineCyclerLinks:: ~PipelineCyclerLinks() { - nassertv(_next == NULL && _prev == NULL); + nassertv(_next == nullptr && _prev == nullptr); } #endif // THREADED_PIPELINE @@ -40,7 +40,7 @@ INLINE PipelineCyclerLinks:: */ INLINE void PipelineCyclerLinks:: make_head() { - nassertv(_next == NULL && _prev == NULL); + nassertv(_next == nullptr && _prev == nullptr); _next = this; _prev = this; } @@ -55,8 +55,8 @@ INLINE void PipelineCyclerLinks:: clear_head() { nassertv(_next == this && _prev == this); #ifndef NDEBUG - _next = NULL; - _prev = NULL; + _next = nullptr; + _prev = nullptr; #endif } #endif // THREADED_PIPELINE @@ -71,8 +71,8 @@ remove_from_list() { _prev->_next = _next; _next->_prev = _prev; #ifndef NDEBUG - _next = NULL; - _prev = NULL; + _next = nullptr; + _prev = nullptr; #endif } #endif // THREADED_PIPELINE @@ -85,8 +85,8 @@ remove_from_list() { INLINE void PipelineCyclerLinks:: insert_before(PipelineCyclerLinks *node) { nassertv(node->_prev->_next == node && node->_next->_prev == node); - nassertv(_prev == (PipelineCyclerLinks *)NULL && - _next == (PipelineCyclerLinks *)NULL); + nassertv(_prev == nullptr && + _next == nullptr); _prev = node->_prev; _next = node; _prev->_next = this; diff --git a/panda/src/pipeline/pipelineCyclerTrivialImpl.I b/panda/src/pipeline/pipelineCyclerTrivialImpl.I index 5cc1eecf39..316cadae30 100644 --- a/panda/src/pipeline/pipelineCyclerTrivialImpl.I +++ b/panda/src/pipeline/pipelineCyclerTrivialImpl.I @@ -30,35 +30,6 @@ PipelineCyclerTrivialImpl(CycleData *initial_data, Pipeline *) { #endif // SIMPLE_STRUCT_POINTERS } -/** - * - */ -INLINE PipelineCyclerTrivialImpl:: -PipelineCyclerTrivialImpl(const PipelineCyclerTrivialImpl &) { - // The copy constructor for the PipelineCyclerTrivialImpl case doesn't work. - // Don't try to use it. The PipelineCycler template class is ifdeffed - // appropriately to call the normal constructor instead. - nassertv(false); -} - -/** - * - */ -INLINE void PipelineCyclerTrivialImpl:: -operator = (const PipelineCyclerTrivialImpl &) { - // The copy assignment operator for the PipelineCyclerTrivialImpl case - // doesn't work. Don't try to use it. The PipelineCycler template class is - // ifdeffed appropriately not to call this method. - nassertv(false); -} - -/** - * - */ -INLINE PipelineCyclerTrivialImpl:: -~PipelineCyclerTrivialImpl() { -} - /** * Grabs an overall lock on the cycler. Release it with a call to release(). * This lock should be held while walking the list of stages. diff --git a/panda/src/pipeline/pipelineCyclerTrivialImpl.h b/panda/src/pipeline/pipelineCyclerTrivialImpl.h index ea0593ba24..75b2b6fffb 100644 --- a/panda/src/pipeline/pipelineCyclerTrivialImpl.h +++ b/panda/src/pipeline/pipelineCyclerTrivialImpl.h @@ -40,14 +40,13 @@ class Pipeline; */ struct EXPCL_PANDA_PIPELINE PipelineCyclerTrivialImpl { public: - INLINE PipelineCyclerTrivialImpl(CycleData *initial_data, Pipeline *pipeline = NULL); -private: - INLINE PipelineCyclerTrivialImpl(const PipelineCyclerTrivialImpl ©); - INLINE void operator = (const PipelineCyclerTrivialImpl ©); -public: - INLINE ~PipelineCyclerTrivialImpl(); + INLINE PipelineCyclerTrivialImpl(CycleData *initial_data, Pipeline *pipeline = nullptr); + PipelineCyclerTrivialImpl(const PipelineCyclerTrivialImpl ©) = delete; + ~PipelineCyclerTrivialImpl() = default; - INLINE void acquire(Thread *current_thread = NULL); + PipelineCyclerTrivialImpl &operator = (const PipelineCyclerTrivialImpl ©) = delete; + + INLINE void acquire(Thread *current_thread = nullptr); INLINE void release(); INLINE const CycleData *read_unlocked(Thread *current_thread) const; diff --git a/panda/src/pipeline/pipelineCyclerTrueImpl.I b/panda/src/pipeline/pipelineCyclerTrueImpl.I index fa6a97499b..4d6591b9b7 100644 --- a/panda/src/pipeline/pipelineCyclerTrueImpl.I +++ b/panda/src/pipeline/pipelineCyclerTrueImpl.I @@ -54,7 +54,7 @@ read_unlocked(Thread *current_thread) const { TAU_PROFILE("const CycleData *PipelineCyclerTrueImpl::read_unlocked(Thread *)", " ", TAU_USER); int pipeline_stage = current_thread->get_pipeline_stage(); #ifdef _DEBUG - nassertr(pipeline_stage >= 0 && pipeline_stage < _num_stages, NULL); + nassertr(pipeline_stage >= 0 && pipeline_stage < _num_stages, nullptr); #endif return _data[pipeline_stage]._cdata; } @@ -72,7 +72,7 @@ read(Thread *current_thread) const { TAU_PROFILE("const CycleData *PipelineCyclerTrueImpl::read(Thread *)", " ", TAU_USER); int pipeline_stage = current_thread->get_pipeline_stage(); #ifdef _DEBUG - nassertr(pipeline_stage >= 0 && pipeline_stage < _num_stages, NULL); + nassertr(pipeline_stage >= 0 && pipeline_stage < _num_stages, nullptr); #endif _lock.acquire(current_thread); return _data[pipeline_stage]._cdata; @@ -161,8 +161,8 @@ elevate_read(const CycleData *pointer, Thread *current_thread) { TAU_PROFILE("CycleData *PipelineCyclerTrueImpl::elevate_read(const CycleData *)", " ", TAU_USER); #ifdef _DEBUG int pipeline_stage = current_thread->get_pipeline_stage(); - nassertr(pipeline_stage >= 0 && pipeline_stage < _num_stages, NULL); - nassertr(_data[pipeline_stage]._cdata == pointer, NULL); + nassertr(pipeline_stage >= 0 && pipeline_stage < _num_stages, nullptr); + nassertr(_data[pipeline_stage]._cdata == pointer, nullptr); #endif CycleData *new_pointer = write(current_thread); _lock.release(); @@ -179,8 +179,8 @@ elevate_read_upstream(const CycleData *pointer, bool force_to_0, Thread *current TAU_PROFILE("CycleData *PipelineCyclerTrueImpl::elevate_read_upstream(const CycleData *, bool)", " ", TAU_USER); #ifdef _DEBUG int pipeline_stage = current_thread->get_pipeline_stage(); - nassertr(pipeline_stage >= 0 && pipeline_stage < _num_stages, NULL); - nassertr(_data[pipeline_stage]._cdata == pointer, NULL); + nassertr(pipeline_stage >= 0 && pipeline_stage < _num_stages, nullptr); + nassertr(_data[pipeline_stage]._cdata == pointer, nullptr); #endif CycleData *new_pointer = write_upstream(force_to_0, current_thread); _lock.release(); @@ -230,7 +230,7 @@ INLINE const CycleData *PipelineCyclerTrueImpl:: read_stage_unlocked(int pipeline_stage) const { TAU_PROFILE("const CycleData *PipelineCyclerTrueImpl::read_stage_unlocked(int)", " ", TAU_USER); #ifdef _DEBUG - nassertr(pipeline_stage >= 0 && pipeline_stage < _num_stages, NULL); + nassertr(pipeline_stage >= 0 && pipeline_stage < _num_stages, nullptr); #elif defined(__has_builtin) && __has_builtin(__builtin_assume) __builtin_assume(pipeline_stage >= 0); #endif @@ -249,7 +249,7 @@ INLINE const CycleData *PipelineCyclerTrueImpl:: read_stage(int pipeline_stage, Thread *current_thread) const { TAU_PROFILE("const CycleData *PipelineCyclerTrueImpl::read_stage(int, Thread *)", " ", TAU_USER); #ifdef _DEBUG - nassertr(pipeline_stage >= 0 && pipeline_stage < _num_stages, NULL); + nassertr(pipeline_stage >= 0 && pipeline_stage < _num_stages, nullptr); #elif defined(__has_builtin) && __has_builtin(__builtin_assume) __builtin_assume(pipeline_stage >= 0); #endif @@ -280,8 +280,8 @@ elevate_read_stage(int pipeline_stage, const CycleData *pointer, Thread *current_thread) { TAU_PROFILE("CycleData *PipelineCyclerTrueImpl::elevate_read_stage(int, const CycleData *)", " ", TAU_USER); #ifdef _DEBUG - nassertr(pipeline_stage >= 0 && pipeline_stage < _num_stages, NULL); - nassertr(_data[pipeline_stage]._cdata == pointer, NULL); + nassertr(pipeline_stage >= 0 && pipeline_stage < _num_stages, nullptr); + nassertr(_data[pipeline_stage]._cdata == pointer, nullptr); #elif defined(__has_builtin) && __has_builtin(__builtin_assume) __builtin_assume(pipeline_stage >= 0); #endif @@ -300,8 +300,8 @@ elevate_read_stage_upstream(int pipeline_stage, const CycleData *pointer, bool force_to_0, Thread *current_thread) { TAU_PROFILE("CycleData *PipelineCyclerTrueImpl::elevate_read_stage(int, const CycleData *)", " ", TAU_USER); #ifdef _DEBUG - nassertr(pipeline_stage >= 0 && pipeline_stage < _num_stages, NULL); - nassertr(_data[pipeline_stage]._cdata == pointer, NULL); + nassertr(pipeline_stage >= 0 && pipeline_stage < _num_stages, nullptr); + nassertr(_data[pipeline_stage]._cdata == pointer, nullptr); #elif defined(__has_builtin) && __has_builtin(__builtin_assume) __builtin_assume(pipeline_stage >= 0); #endif @@ -347,7 +347,7 @@ INLINE CycleData *PipelineCyclerTrueImpl:: cheat() const { TAU_PROFILE("CycleData *PipelineCyclerTrueImpl::cheat()", " ", TAU_USER); int pipeline_stage = Thread::get_current_pipeline_stage(); - nassertr(pipeline_stage >= 0 && pipeline_stage < _num_stages, NULL); + nassertr(pipeline_stage >= 0 && pipeline_stage < _num_stages, nullptr); return _data[pipeline_stage]._cdata; } diff --git a/panda/src/pipeline/pipelineCyclerTrueImpl.cxx b/panda/src/pipeline/pipelineCyclerTrueImpl.cxx index f943a030f8..714e61c0e4 100644 --- a/panda/src/pipeline/pipelineCyclerTrueImpl.cxx +++ b/panda/src/pipeline/pipelineCyclerTrueImpl.cxx @@ -27,7 +27,7 @@ PipelineCyclerTrueImpl(CycleData *initial_data, Pipeline *pipeline) : _dirty(0), _lock(this) { - if (_pipeline == (Pipeline *)NULL) { + if (_pipeline == nullptr) { _pipeline = Pipeline::get_render_pipeline(); } @@ -64,7 +64,7 @@ PipelineCyclerTrueImpl(const PipelineCyclerTrueImpl ©) : for (int i = 0; i < _num_stages; ++i) { PT(CycleData) &new_pt = pointers[copy._data[i]._cdata]; - if (new_pt == NULL) { + if (new_pt == nullptr) { new_pt = copy._data[i]._cdata->make_copy(); } _data[i]._cdata = new_pt.p(); @@ -90,7 +90,7 @@ operator = (const PipelineCyclerTrueImpl ©) { for (int i = 0; i < _num_stages; ++i) { PT(CycleData) &new_pt = pointers[copy._data[i]._cdata]; - if (new_pt == NULL) { + if (new_pt == nullptr) { new_pt = copy._data[i]._cdata->make_copy(); } _data[i]._cdata = new_pt.p(); @@ -111,7 +111,7 @@ PipelineCyclerTrueImpl:: _pipeline->remove_cycler(this); delete[] _data; - _data = NULL; + _data = nullptr; _num_stages = 0; } @@ -128,7 +128,7 @@ write_stage(int pipeline_stage, Thread *current_thread) { #ifndef NDEBUG nassertd(pipeline_stage >= 0 && pipeline_stage < _num_stages) { _lock.release(); - return NULL; + return nullptr; } #endif // NDEBUG @@ -176,7 +176,7 @@ write_stage_upstream(int pipeline_stage, bool force_to_0, Thread *current_thread #ifndef NDEBUG nassertd(pipeline_stage >= 0 && pipeline_stage < _num_stages) { _lock.release(); - return NULL; + return nullptr; } #endif // NDEBUG @@ -209,7 +209,7 @@ write_stage_upstream(int pipeline_stage, bool force_to_0, Thread *current_thread k = pipeline_stage - 1; while (k >= 0 && (_data[k]._cdata == old_data || force_to_0)) { - nassertr(_data[k]._writes_outstanding == 0, NULL); + nassertr(_data[k]._writes_outstanding == 0, nullptr); _data[k]._cdata = new_data.p(); --k; } @@ -228,7 +228,7 @@ write_stage_upstream(int pipeline_stage, bool force_to_0, Thread *current_thread // There are no external pointers, so no need to copy-on-write, but the // current pointer doesn't go all the way back. Make it do so. while (k >= 0) { - nassertr(_data[k]._writes_outstanding == 0, NULL); + nassertr(_data[k]._writes_outstanding == 0, nullptr); _data[k]._cdata = old_data; --k; } @@ -324,7 +324,7 @@ set_num_stages(int num_stages) { * */ void PipelineCyclerTrueImpl::CyclerMutex:: -output(ostream &out) const { +output(std::ostream &out) const { out << "CyclerMutex "; _cycler->cheat()->output(out); } diff --git a/panda/src/pipeline/pipelineCyclerTrueImpl.h b/panda/src/pipeline/pipelineCyclerTrueImpl.h index 59896c8b18..12232f70d0 100644 --- a/panda/src/pipeline/pipelineCyclerTrueImpl.h +++ b/panda/src/pipeline/pipelineCyclerTrueImpl.h @@ -44,7 +44,7 @@ struct EXPCL_PANDA_PIPELINE PipelineCyclerTrueImpl : public PipelineCyclerLinks private: PipelineCyclerTrueImpl(); public: - PipelineCyclerTrueImpl(CycleData *initial_data, Pipeline *pipeline = NULL); + PipelineCyclerTrueImpl(CycleData *initial_data, Pipeline *pipeline = nullptr); PipelineCyclerTrueImpl(const PipelineCyclerTrueImpl ©); void operator = (const PipelineCyclerTrueImpl ©); ~PipelineCyclerTrueImpl(); @@ -94,7 +94,7 @@ public: INLINE CyclerMutex(PipelineCyclerTrueImpl *cycler); #ifdef DEBUG_THREADS - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; PipelineCyclerTrueImpl *_cycler; #endif // DEBUG_THREADS }; diff --git a/panda/src/pipeline/pmutex.I b/panda/src/pipeline/pmutex.I index 1cdfd011d4..e148ce22e3 100644 --- a/panda/src/pipeline/pmutex.I +++ b/panda/src/pipeline/pmutex.I @@ -16,7 +16,7 @@ */ INLINE Mutex:: #ifdef DEBUG_THREADS -Mutex() : MutexDebug(string(), false, false) +Mutex() : MutexDebug(std::string(), false, false) #else Mutex() #endif // DEBUG_THREADS @@ -28,7 +28,7 @@ Mutex() */ INLINE Mutex:: #ifdef DEBUG_THREADS -Mutex(const char *name) : MutexDebug(string(name), false, false) +Mutex(const char *name) : MutexDebug(std::string(name), false, false) #else Mutex(const char *) #endif // DEBUG_THREADS @@ -40,37 +40,9 @@ Mutex(const char *) */ INLINE Mutex:: #ifdef DEBUG_THREADS -Mutex(const string &name) : MutexDebug(name, false, false) +Mutex(const std::string &name) : MutexDebug(name, false, false) #else -Mutex(const string &) +Mutex(const std::string &) #endif // DEBUG_THREADS { } - -/** - * - */ -INLINE Mutex:: -~Mutex() { -} - -/** - * Do not attempt to copy mutexes. - */ -INLINE Mutex:: -#ifdef DEBUG_THREADS -Mutex(const Mutex ©) : MutexDebug(string(), false, false) -#else - Mutex(const Mutex ©) -#endif // DEBUG_THREADS -{ - nassertv(false); -} - -/** - * Do not attempt to copy mutexes. - */ -INLINE void Mutex:: -operator = (const Mutex ©) { - nassertv(false); -} diff --git a/panda/src/pipeline/pmutex.h b/panda/src/pipeline/pmutex.h index c5d471ae0c..2a47b7dbac 100644 --- a/panda/src/pipeline/pmutex.h +++ b/panda/src/pipeline/pmutex.h @@ -43,11 +43,11 @@ PUBLISHED: public: INLINE Mutex(const char *name); PUBLISHED: - INLINE explicit Mutex(const string &name); - INLINE ~Mutex(); -private: - INLINE Mutex(const Mutex ©); - INLINE void operator = (const Mutex ©); + INLINE explicit Mutex(const std::string &name); + Mutex(const Mutex ©) = delete; + ~Mutex() = default; + + void operator = (const Mutex ©) = delete; public: // This is a global mutex set aside for the purpose of protecting Notify diff --git a/panda/src/pipeline/psemaphore.I b/panda/src/pipeline/psemaphore.I index 1111e01857..0d1fe57bdf 100644 --- a/panda/src/pipeline/psemaphore.I +++ b/panda/src/pipeline/psemaphore.I @@ -23,31 +23,6 @@ Semaphore(int initial_count) : nassertv(_count >= 0); } -/** - * - */ -INLINE Semaphore:: -~Semaphore() { -} - -/** - * Do not attempt to copy semaphores. - */ -INLINE Semaphore:: -Semaphore(const Semaphore ©) : - _cvar(_lock) -{ - nassertv(false); -} - -/** - * Do not attempt to copy semaphores. - */ -INLINE void Semaphore:: -operator = (const Semaphore ©) { - nassertv(false); -} - /** * Decrements the internal count. If the count was already at zero, blocks * until the count is nonzero, then decrements it. diff --git a/panda/src/pipeline/psemaphore.cxx b/panda/src/pipeline/psemaphore.cxx index 1142930e3a..9a1e453819 100644 --- a/panda/src/pipeline/psemaphore.cxx +++ b/panda/src/pipeline/psemaphore.cxx @@ -17,7 +17,7 @@ * */ void Semaphore:: -output(ostream &out) const { +output(std::ostream &out) const { MutexHolder holder(_lock); out << "Semaphore, count = " << _count; } diff --git a/panda/src/pipeline/psemaphore.h b/panda/src/pipeline/psemaphore.h index 6fd9162cc2..306992b5d9 100644 --- a/panda/src/pipeline/psemaphore.h +++ b/panda/src/pipeline/psemaphore.h @@ -30,10 +30,10 @@ class EXPCL_PANDA_PIPELINE Semaphore { PUBLISHED: INLINE explicit Semaphore(int initial_count = 1); - INLINE ~Semaphore(); -private: - INLINE Semaphore(const Semaphore ©); - INLINE void operator = (const Semaphore ©); + Semaphore(const Semaphore ©) = delete; + ~Semaphore() = default; + + Semaphore &operator = (const Semaphore ©) = delete; PUBLISHED: BLOCKING INLINE void acquire(); @@ -41,7 +41,7 @@ PUBLISHED: INLINE int release(); INLINE int get_count() const; - void output(ostream &out) const; + void output(std::ostream &out) const; private: Mutex _lock; @@ -49,8 +49,8 @@ private: int _count; }; -INLINE ostream & -operator << (ostream &out, const Semaphore &sem) { +INLINE std::ostream & +operator << (std::ostream &out, const Semaphore &sem) { sem.output(out); return out; } diff --git a/panda/src/pipeline/pythonThread.cxx b/panda/src/pipeline/pythonThread.cxx index 28bef610b5..ab41070fb8 100644 --- a/panda/src/pipeline/pythonThread.cxx +++ b/panda/src/pipeline/pythonThread.cxx @@ -24,13 +24,13 @@ TypeHandle PythonThread::_type_handle; */ PythonThread:: PythonThread(PyObject *function, PyObject *args, - const string &name, const string &sync_name) : + const std::string &name, const std::string &sync_name) : Thread(name, sync_name) { _function = function; Py_INCREF(_function); - _args = NULL; - _result = NULL; + _args = nullptr; + _result = nullptr; if (!PyCallable_Check(_function)) { nassert_raise("Invalid function passed to PythonThread constructor"); @@ -78,7 +78,7 @@ PyObject *PythonThread:: join() { Thread::join(); - if (_result == NULL) { + if (_result == nullptr) { // No result; return None. Py_INCREF(Py_None); return Py_None; @@ -107,11 +107,11 @@ set_args(PyObject *args) { // None means no arguments; create an empty tuple. _args = PyTuple_New(0); } else { - _args = NULL; + _args = nullptr; if (PySequence_Check(args)) { _args = PySequence_Tuple(args); } - if (_args == NULL) { + if (_args == nullptr) { Dtool_Raise_TypeError("PythonThread args must be a tuple"); } } @@ -130,13 +130,13 @@ call_python_func(PyObject *function, PyObject *args) { // Create a new Python thread state data structure, so Python can properly // lock itself. - PyObject *result = NULL; + PyObject *result = nullptr; if (current_thread == get_main_thread()) { // In the main thread, just call the function. - result = PyObject_Call(function, args, NULL); + result = PyObject_Call(function, args, nullptr); - if (result == (PyObject *)NULL) { + if (result == nullptr) { if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_SystemExit)) { // If we caught SystemExit, let it pass by without bothering to print // a callback. @@ -161,7 +161,7 @@ call_python_func(PyObject *function, PyObject *args) { #ifndef HAVE_THREADS // Shouldn't be possible to come here without having some kind of // threading support enabled. - nassertr(false, NULL); + nassertr(false, nullptr); #else #ifdef SIMPLE_THREADS @@ -193,8 +193,8 @@ call_python_func(PyObject *function, PyObject *args) { PyThreadState_Swap(new_thread_state); // Call the user's function. - result = PyObject_Call(function, args, NULL); - if (result == (PyObject *)NULL && PyErr_Occurred()) { + result = PyObject_Call(function, args, nullptr); + if (result == nullptr && PyErr_Occurred()) { // We got an exception. Move the exception from the current thread into // the main thread, so it can be handled there. PyObject *exc, *val, *tb; @@ -237,8 +237,8 @@ call_python_func(PyObject *function, PyObject *args) { gstate = PyGILState_Ensure(); // Call the user's function. - result = PyObject_Call(function, args, NULL); - if (result == (PyObject *)NULL && PyErr_Occurred()) { + result = PyObject_Call(function, args, nullptr); + if (result == nullptr && PyErr_Occurred()) { // We got an exception. Move the exception from the current thread into // the main thread, so it can be handled there. PyObject *exc, *val, *tb; diff --git a/panda/src/pipeline/pythonThread.h b/panda/src/pipeline/pythonThread.h index 66b7e45aa4..eb57351149 100644 --- a/panda/src/pipeline/pythonThread.h +++ b/panda/src/pipeline/pythonThread.h @@ -27,7 +27,7 @@ class PythonThread : public Thread { PUBLISHED: explicit PythonThread(PyObject *function, PyObject *args, - const string &name, const string &sync_name); + const std::string &name, const std::string &sync_name); virtual ~PythonThread(); BLOCKING PyObject *join(); diff --git a/panda/src/pipeline/reMutex.I b/panda/src/pipeline/reMutex.I index e67f378c35..af2ea3d59c 100644 --- a/panda/src/pipeline/reMutex.I +++ b/panda/src/pipeline/reMutex.I @@ -16,7 +16,7 @@ */ INLINE ReMutex:: #ifdef DEBUG_THREADS -ReMutex() : MutexDebug(string(), true, false) +ReMutex() : MutexDebug(std::string(), true, false) #else ReMutex() #endif // DEBUG_THREADS @@ -28,7 +28,7 @@ ReMutex() */ INLINE ReMutex:: #ifdef DEBUG_THREADS -ReMutex(const char *name) : MutexDebug(string(name), true, false) +ReMutex(const char *name) : MutexDebug(std::string(name), true, false) #else ReMutex(const char *) #endif // DEBUG_THREADS @@ -40,24 +40,9 @@ ReMutex(const char *) */ INLINE ReMutex:: #ifdef DEBUG_THREADS -ReMutex(const string &name) : MutexDebug(name, true, false) +ReMutex(const std::string &name) : MutexDebug(name, true, false) #else -ReMutex(const string &) +ReMutex(const std::string &) #endif // DEBUG_THREADS { } - -/** - * - */ -INLINE ReMutex:: -~ReMutex() { -} - -/** - * Do not attempt to copy mutexes. - */ -INLINE void ReMutex:: -operator = (const ReMutex ©) { - nassertv(false); -} diff --git a/panda/src/pipeline/reMutex.h b/panda/src/pipeline/reMutex.h index fd6a710b55..bdf9031304 100644 --- a/panda/src/pipeline/reMutex.h +++ b/panda/src/pipeline/reMutex.h @@ -37,11 +37,11 @@ PUBLISHED: public: INLINE explicit ReMutex(const char *name); PUBLISHED: - INLINE explicit ReMutex(const string &name); - INLINE ~ReMutex(); -private: - INLINE ReMutex(const ReMutex ©); - INLINE void operator = (const ReMutex ©); + INLINE explicit ReMutex(const std::string &name); + ReMutex(const ReMutex ©) = delete; + ~ReMutex() = default; + + void operator = (const ReMutex ©) = delete; }; #include "reMutex.I" diff --git a/panda/src/pipeline/reMutexDirect.I b/panda/src/pipeline/reMutexDirect.I index abdce3562f..0785473e7c 100644 --- a/panda/src/pipeline/reMutexDirect.I +++ b/panda/src/pipeline/reMutexDirect.I @@ -21,36 +21,39 @@ ReMutexDirect() #endif { #ifndef HAVE_REMUTEXTRUEIMPL - _locking_thread = NULL; + _locking_thread = nullptr; _lock_count = 0; #endif } /** - * - */ -INLINE ReMutexDirect:: -~ReMutexDirect() { -} - -/** - * Do not attempt to copy reMutexes. - */ -INLINE ReMutexDirect:: -ReMutexDirect(const ReMutexDirect ©) -#ifndef HAVE_REMUTEXTRUEIMPL - : _cvar_impl(_lock_impl) -#endif -{ - nassertv(false); -} - -/** - * Do not attempt to copy reMutexes. + * Alias for acquire() to match C++11 semantics. + * @see acquire() */ INLINE void ReMutexDirect:: -operator = (const ReMutexDirect ©) { - nassertv(false); +lock() { + TAU_PROFILE("void ReMutexDirect::acquire()", " ", TAU_USER); + _impl.lock(); +} + +/** + * Alias for try_acquire() to match C++11 semantics. + * @see try_acquire() + */ +INLINE bool ReMutexDirect:: +try_lock() { + TAU_PROFILE("void ReMutexDirect::try_acquire()", " ", TAU_USER); + return _impl.try_lock(); +} + +/** + * Alias for release() to match C++11 semantics. + * @see release() + */ +INLINE void ReMutexDirect:: +unlock() { + TAU_PROFILE("void ReMutexDirect::unlock()", " ", TAU_USER); + _impl.unlock(); } /** @@ -67,9 +70,9 @@ INLINE void ReMutexDirect:: acquire() const { TAU_PROFILE("void ReMutexDirect::acquire()", " ", TAU_USER); #ifdef HAVE_REMUTEXTRUEIMPL - ((ReMutexDirect *)this)->_impl.acquire(); + _impl.lock(); #else - ((ReMutexDirect *)this)->do_acquire(); + ((ReMutexDirect *)this)->do_lock(); #endif // HAVE_REMUTEXTRUEIMPL } @@ -81,9 +84,9 @@ INLINE void ReMutexDirect:: acquire(Thread *current_thread) const { TAU_PROFILE("void ReMutexDirect::acquire(Thread *)", " ", TAU_USER); #ifdef HAVE_REMUTEXTRUEIMPL - ((ReMutexDirect *)this)->_impl.acquire(); + _impl.lock(); #else - ((ReMutexDirect *)this)->do_acquire(current_thread); + ((ReMutexDirect *)this)->do_lock(current_thread); #endif // HAVE_REMUTEXTRUEIMPL } @@ -95,9 +98,9 @@ INLINE bool ReMutexDirect:: try_acquire() const { TAU_PROFILE("void ReMutexDirect::acquire(bool)", " ", TAU_USER); #ifdef HAVE_REMUTEXTRUEIMPL - return ((ReMutexDirect *)this)->_impl.try_acquire(); + return _impl.try_lock(); #else - return ((ReMutexDirect *)this)->do_try_acquire(); + return ((ReMutexDirect *)this)->do_try_lock(); #endif // HAVE_REMUTEXTRUEIMPL } @@ -109,9 +112,9 @@ INLINE bool ReMutexDirect:: try_acquire(Thread *current_thread) const { TAU_PROFILE("void ReMutexDirect::acquire(bool)", " ", TAU_USER); #ifdef HAVE_REMUTEXTRUEIMPL - return ((ReMutexDirect *)this)->_impl.try_acquire(); + return _impl.try_lock(); #else - return ((ReMutexDirect *)this)->do_try_acquire(current_thread); + return ((ReMutexDirect *)this)->do_try_lock(current_thread); #endif // HAVE_REMUTEXTRUEIMPL } @@ -129,7 +132,7 @@ INLINE void ReMutexDirect:: elevate_lock() const { TAU_PROFILE("void ReMutexDirect::elevate_lock()", " ", TAU_USER); #ifdef HAVE_REMUTEXTRUEIMPL - ((ReMutexDirect *)this)->_impl.acquire(); + _impl.lock(); #else ((ReMutexDirect *)this)->do_elevate_lock(); #endif // HAVE_REMUTEXTRUEIMPL @@ -146,9 +149,9 @@ INLINE void ReMutexDirect:: release() const { TAU_PROFILE("void ReMutexDirect::release()", " ", TAU_USER); #ifdef HAVE_REMUTEXTRUEIMPL - ((ReMutexDirect *)this)->_impl.release(); + _impl.unlock(); #else - ((ReMutexDirect *)this)->do_release(); + ((ReMutexDirect *)this)->do_unlock(); #endif // HAVE_REMUTEXTRUEIMPL } @@ -167,7 +170,7 @@ debug_is_locked() const { * The mutex name is only defined when compiling in DEBUG_THREADS mode. */ INLINE void ReMutexDirect:: -set_name(const string &) { +set_name(const std::string &) { } /** @@ -188,9 +191,9 @@ has_name() const { /** * The mutex name is only defined when compiling in DEBUG_THREADS mode. */ -INLINE string ReMutexDirect:: +INLINE std::string ReMutexDirect:: get_name() const { - return string(); + return std::string(); } #ifndef HAVE_REMUTEXTRUEIMPL @@ -201,8 +204,8 @@ get_name() const { * mutex). */ INLINE void ReMutexDirect:: -do_acquire() { - do_acquire(Thread::get_current_thread()); +do_lock() { + do_lock(Thread::get_current_thread()); } #endif @@ -214,7 +217,7 @@ do_acquire() { * mutex). */ INLINE bool ReMutexDirect:: -do_try_acquire() { - return do_try_acquire(Thread::get_current_thread()); +do_try_lock() { + return do_try_lock(Thread::get_current_thread()); } #endif diff --git a/panda/src/pipeline/reMutexDirect.cxx b/panda/src/pipeline/reMutexDirect.cxx index 33ff64c4cc..7bfdcb8f8d 100644 --- a/panda/src/pipeline/reMutexDirect.cxx +++ b/panda/src/pipeline/reMutexDirect.cxx @@ -21,7 +21,7 @@ * ReMutexDirect. */ void ReMutexDirect:: -output(ostream &out) const { +output(std::ostream &out) const { out << "ReMutex " << (void *)this; } @@ -33,10 +33,10 @@ output(ostream &out) const { * mutex). */ void ReMutexDirect:: -do_acquire(Thread *current_thread) { - _lock_impl.acquire(); +do_lock(Thread *current_thread) { + _lock_impl.lock(); - if (_locking_thread == (Thread *)NULL) { + if (_locking_thread == nullptr) { // The mutex is not already locked by anyone. Lock it. _locking_thread = current_thread; ++_lock_count; @@ -52,7 +52,7 @@ do_acquire(Thread *current_thread) { } else { // The mutex is locked by some other thread. Go to sleep on the condition // variable until it's unlocked. - while (_locking_thread != (Thread *)NULL) { + while (_locking_thread != nullptr) { _cvar_impl.wait(); } @@ -61,7 +61,7 @@ do_acquire(Thread *current_thread) { nassertd(_lock_count == 1) { } } - _lock_impl.release(); + _lock_impl.unlock(); } #endif // !HAVE_REMUTEXTRUEIMPL @@ -73,11 +73,11 @@ do_acquire(Thread *current_thread) { * mutex). */ bool ReMutexDirect:: -do_try_acquire(Thread *current_thread) { +do_try_lock(Thread *current_thread) { bool acquired = true; - _lock_impl.acquire(); + _lock_impl.lock(); - if (_locking_thread == (Thread *)NULL) { + if (_locking_thread == nullptr) { // The mutex is not already locked by anyone. Lock it. _locking_thread = current_thread; ++_lock_count; @@ -94,7 +94,7 @@ do_try_acquire(Thread *current_thread) { // The mutex is locked by some other thread. Return false. acquired = false; } - _lock_impl.release(); + _lock_impl.unlock(); return acquired; } @@ -109,16 +109,16 @@ do_try_acquire(Thread *current_thread) { */ void ReMutexDirect:: do_elevate_lock() { - _lock_impl.acquire(); + _lock_impl.lock(); #ifdef _DEBUG nassertd(_locking_thread == Thread::get_current_thread()) { - _lock_impl.release(); + _lock_impl.unlock(); return; } #elif !defined(NDEBUG) - nassertd(_locking_thread != (Thread *)NULL) { - _lock_impl.release(); + nassertd(_locking_thread != nullptr) { + _lock_impl.unlock(); return; } #endif // NDEBUG @@ -129,7 +129,7 @@ do_elevate_lock() { nassertd(_lock_count > 0) { } - _lock_impl.release(); + _lock_impl.unlock(); } #endif // !HAVE_REMUTEXTRUEIMPL @@ -141,16 +141,16 @@ do_elevate_lock() { * mutex). */ void ReMutexDirect:: -do_release() { - _lock_impl.acquire(); +do_unlock() { + _lock_impl.lock(); #ifdef _DEBUG if (_locking_thread != Thread::get_current_thread()) { - ostringstream ostr; + std::ostringstream ostr; ostr << *_locking_thread << " attempted to release " << *this << " which it does not own"; nassert_raise(ostr.str()); - _lock_impl.release(); + _lock_impl.unlock(); return; } #endif // _DEBUG @@ -161,10 +161,10 @@ do_release() { --_lock_count; if (_lock_count == 0) { // That was the last lock held by this thread. Release the lock. - _locking_thread = (Thread *)NULL; + _locking_thread = nullptr; _cvar_impl.notify(); } - _lock_impl.release(); + _lock_impl.unlock(); } #endif // !HAVE_REMUTEXTRUEIMPL diff --git a/panda/src/pipeline/reMutexDirect.h b/panda/src/pipeline/reMutexDirect.h index ce86e774f0..b6f5215319 100644 --- a/panda/src/pipeline/reMutexDirect.h +++ b/panda/src/pipeline/reMutexDirect.h @@ -30,10 +30,15 @@ class Thread; class EXPCL_PANDA_PIPELINE ReMutexDirect { protected: INLINE ReMutexDirect(); - INLINE ~ReMutexDirect(); -private: - INLINE ReMutexDirect(const ReMutexDirect ©); - INLINE void operator = (const ReMutexDirect ©); + ReMutexDirect(const ReMutexDirect ©) = delete; + ~ReMutexDirect() = default; + + void operator = (const ReMutexDirect ©) = delete; + +public: + INLINE void lock(); + INLINE bool try_lock(); + INLINE void unlock(); PUBLISHED: BLOCKING INLINE void acquire() const; @@ -45,25 +50,25 @@ PUBLISHED: INLINE bool debug_is_locked() const; - INLINE void set_name(const string &name); + INLINE void set_name(const std::string &name); INLINE void clear_name(); INLINE bool has_name() const; - INLINE string get_name() const; + INLINE std::string get_name() const; - void output(ostream &out) const; + void output(std::ostream &out) const; private: #ifdef HAVE_REMUTEXTRUEIMPL - ReMutexImpl _impl; + mutable ReMutexImpl _impl; #else // If we don't have a reentrant mutex, we have to hand-roll one. - INLINE void do_acquire(); - void do_acquire(Thread *current_thread); - INLINE bool do_try_acquire(); - bool do_try_acquire(Thread *current_thread); + INLINE void do_lock(); + void do_lock(Thread *current_thread); + INLINE bool do_try_lock(); + bool do_try_lock(Thread *current_thread); void do_elevate_lock(); - void do_release(); + void do_unlock(); Thread *_locking_thread; int _lock_count; @@ -75,8 +80,8 @@ private: friend class LightReMutexDirect; }; -INLINE ostream & -operator << (ostream &out, const ReMutexDirect &m) { +INLINE std::ostream & +operator << (std::ostream &out, const ReMutexDirect &m) { m.output(out); return out; } diff --git a/panda/src/pipeline/reMutexHolder.I b/panda/src/pipeline/reMutexHolder.I index 25a0032b4e..1c05196c7e 100644 --- a/panda/src/pipeline/reMutexHolder.I +++ b/panda/src/pipeline/reMutexHolder.I @@ -44,7 +44,7 @@ ReMutexHolder(const ReMutex &mutex, Thread *current_thread) { INLINE ReMutexHolder:: ReMutexHolder(ReMutex *&mutex) { #if defined(HAVE_THREADS) || defined(DEBUG_THREADS) - if (mutex == (ReMutex *)NULL) { + if (mutex == nullptr) { mutex = new ReMutex; } _mutex = mutex; @@ -61,19 +61,3 @@ INLINE ReMutexHolder:: _mutex->release(); #endif } - -/** - * Do not attempt to copy ReMutexHolders. - */ -INLINE ReMutexHolder:: -ReMutexHolder(const ReMutexHolder ©) { - nassertv(false); -} - -/** - * Do not attempt to copy ReMutexHolders. - */ -INLINE void ReMutexHolder:: -operator = (const ReMutexHolder ©) { - nassertv(false); -} diff --git a/panda/src/pipeline/reMutexHolder.h b/panda/src/pipeline/reMutexHolder.h index f0830803fb..3411f7e3f8 100644 --- a/panda/src/pipeline/reMutexHolder.h +++ b/panda/src/pipeline/reMutexHolder.h @@ -27,10 +27,10 @@ public: INLINE ReMutexHolder(const ReMutex &mutex); INLINE ReMutexHolder(const ReMutex &mutex, Thread *current_thread); INLINE ReMutexHolder(ReMutex *&mutex); + ReMutexHolder(const ReMutexHolder ©) = delete; INLINE ~ReMutexHolder(); -private: - INLINE ReMutexHolder(const ReMutexHolder ©); - INLINE void operator = (const ReMutexHolder ©); + + ReMutexHolder &operator = (const ReMutexHolder ©) = delete; private: #if defined(HAVE_THREADS) || defined(DEBUG_THREADS) diff --git a/panda/src/pipeline/test_atomic.cxx b/panda/src/pipeline/test_atomic.cxx index ae371114e4..66ab6c5a14 100644 --- a/panda/src/pipeline/test_atomic.cxx +++ b/panda/src/pipeline/test_atomic.cxx @@ -35,7 +35,7 @@ AtomicAdjust::Integer _num_net_count_incremented = 0; class MyThread : public Thread { public: - MyThread(const string &name) : Thread(name, name) + MyThread(const std::string &name) : Thread(name, name) { } @@ -73,7 +73,7 @@ main(int argc, char *argv[]) { for (int i = 1; i < number_of_threads; ++i) { char name = 'a' + i; - PT(MyThread) thread = new MyThread(string(1, name)); + PT(MyThread) thread = new MyThread(std::string(1, name)); threads.push_back(thread); thread->start(TP_normal, true); } diff --git a/panda/src/pipeline/test_concurrency.cxx b/panda/src/pipeline/test_concurrency.cxx index 9d092d08c8..6f59a025b1 100644 --- a/panda/src/pipeline/test_concurrency.cxx +++ b/panda/src/pipeline/test_concurrency.cxx @@ -50,7 +50,7 @@ volatile MemBlock memblock[number_of_threads]; class MyThread : public Thread { public: - MyThread(const string &name, int index) : + MyThread(const std::string &name, int index) : Thread(name, name), _index(index) { @@ -101,7 +101,7 @@ main(int argc, char *argv[]) { for (int i = 1; i < number_of_threads; ++i) { char name = 'a' + i; Thread::sleep(delay_between_threads); - PT(MyThread) thread = new MyThread(string(1, name), i); + PT(MyThread) thread = new MyThread(std::string(1, name), i); threads.push_back(thread); thread->start(TP_normal, true); } diff --git a/panda/src/pipeline/test_delete.cxx b/panda/src/pipeline/test_delete.cxx index f49606a6f1..3ea431f77b 100644 --- a/panda/src/pipeline/test_delete.cxx +++ b/panda/src/pipeline/test_delete.cxx @@ -80,7 +80,7 @@ TypeHandle Doober::_type_handle; class MyThread : public Thread { public: - MyThread(const string &name) : Thread(name, name) + MyThread(const std::string &name) : Thread(name, name) { } @@ -106,7 +106,7 @@ public: doobers.push_back(new Doober(++counter)); } int num_del = (int)random_f(max_doobers_per_chunk); - num_del = min(num_del, (int)doobers.size()); + num_del = std::min(num_del, (int)doobers.size()); for (int j = 0; j < num_del; ++j) { assert(!doobers.empty()); @@ -137,7 +137,7 @@ main(int argc, char *argv[]) { for (int i = 1; i < number_of_threads; ++i) { char name = 'a' + i; - PT(MyThread) thread = new MyThread(string(1, name)); + PT(MyThread) thread = new MyThread(std::string(1, name)); threads.push_back(thread); thread->start(TP_normal, true); } diff --git a/panda/src/pipeline/test_diners.cxx b/panda/src/pipeline/test_diners.cxx index 0a8f01e484..a5ff82e446 100644 --- a/panda/src/pipeline/test_diners.cxx +++ b/panda/src/pipeline/test_diners.cxx @@ -24,6 +24,8 @@ #include "trueClock.h" #include "pstrtod.h" +using std::cerr; + #ifdef WIN32_VC // Under Windows, the rand() function seems to return a sequence per-thread, // so we use this trick to set each thread to a different seed. @@ -42,7 +44,7 @@ static double random_f(double max) return max * (double)i / (double)RAND_MAX; } -#define PRINTMSG(x) { MutexHolder l(Mutex::_notify_mutex); x << flush; } +#define PRINTMSG(x) { MutexHolder l(Mutex::_notify_mutex); x << std::flush; } // n philosophers sharing n chopsticks. Philosophers are poor folk and can't // afford luxuries like 2 chopsticks per person. @@ -50,7 +52,7 @@ static double random_f(double max) class ChopstickMutex : public Mutex { public: - void output(ostream &out) const { + void output(std::ostream &out) const { out << "chopstick " << _n; } int _n; @@ -121,7 +123,7 @@ public: _id = id; } - virtual void output(ostream &out) const { + virtual void output(std::ostream &out) const { out << "philosopher " << _id; } }; diff --git a/panda/src/pipeline/test_mutex.cxx b/panda/src/pipeline/test_mutex.cxx index 39f5e8a24c..a0a4dd49c6 100644 --- a/panda/src/pipeline/test_mutex.cxx +++ b/panda/src/pipeline/test_mutex.cxx @@ -22,7 +22,7 @@ static const double thread_duration = 5.0; class MyThread : public Thread { public: - MyThread(const string &name, MutexImpl &m1, double period) : + MyThread(const std::string &name, MutexImpl &m1, double period) : Thread(name, name), _m1(m1), _period(period) { @@ -33,9 +33,9 @@ public: double start = clock->get_short_time(); double end = start + thread_duration; while (clock->get_short_time() < end) { - _m1.acquire(); + _m1.lock(); Thread::sleep(_period); - _m1.release(); + _m1.unlock(); } } @@ -47,14 +47,14 @@ int main(int argc, char *argv[]) { MutexImpl _m1; - _m1.acquire(); - _m1.release(); + _m1.lock(); + _m1.unlock(); - cerr << "Making threads.\n"; + std::cerr << "Making threads.\n"; MyThread *a = new MyThread("a", _m1, 1.0); MyThread *b = new MyThread("b", _m1, 0.9); - cerr << "Starting threads.\n"; + std::cerr << "Starting threads.\n"; a->start(TP_normal, true); b->start(TP_normal, true); diff --git a/panda/src/pipeline/test_setjmp.cxx b/panda/src/pipeline/test_setjmp.cxx index 3ce1bcf075..4803ff3fee 100644 --- a/panda/src/pipeline/test_setjmp.cxx +++ b/panda/src/pipeline/test_setjmp.cxx @@ -15,6 +15,8 @@ #include +using std::cerr; + int main(int argc, char *argv[]) { diff --git a/panda/src/pipeline/test_threaddata.cxx b/panda/src/pipeline/test_threaddata.cxx index ebf6698216..b3d919a827 100644 --- a/panda/src/pipeline/test_threaddata.cxx +++ b/panda/src/pipeline/test_threaddata.cxx @@ -17,12 +17,14 @@ #include "mutexHolder.h" #include "pointerTo.h" -Mutex *cout_mutex = (Mutex *)NULL; +using std::cout; + +Mutex *cout_mutex = nullptr; // Test forking a thread with some private data. class ThreadWithData : public Thread { public: - ThreadWithData(const string &name, int parameter); + ThreadWithData(const std::string &name, int parameter); virtual void thread_main(); @@ -32,7 +34,7 @@ private: ThreadWithData:: -ThreadWithData(const string &name, int parameter) : +ThreadWithData(const std::string &name, int parameter) : Thread(name, name), _parameter(parameter) { @@ -48,7 +50,7 @@ thread_main() { MutexHolder holder(cout_mutex); cout << "Running thread " << get_name() << " with parameter " << _parameter - << ", i = " << i << "\n" << flush; + << ", i = " << i << "\n" << std::flush; Thread *thread = get_current_thread(); nassertv(thread == this); } @@ -60,7 +62,7 @@ int main() { cout << "main beginning.\n"; for (int i = 0; i < 10; i++) { - string name = string("thread_") + (char)(i + 'a'); + std::string name = std::string("thread_") + (char)(i + 'a'); PT(Thread) thread = new ThreadWithData(name, i); if (!thread->start(TP_low, true)) { MutexHolder holder(cout_mutex); diff --git a/panda/src/pipeline/thread.I b/panda/src/pipeline/thread.I index 10d7b6e44f..dc7001fd06 100644 --- a/panda/src/pipeline/thread.I +++ b/panda/src/pipeline/thread.I @@ -11,29 +11,13 @@ * @date 2002-08-08 */ -/** - * Do not attempt to copy threads. - */ -INLINE Thread:: -Thread(const Thread ©) : _impl(this) { - nassertv(false); -} - -/** - * Do not attempt to copy threads. - */ -INLINE void Thread:: -operator = (const Thread ©) { - nassertv(false); -} - /** * Returns the sync name of the thread. This name collects threads into "sync * groups", which are expected to run synchronously. This is mainly used for * the benefit of PStats; threads with the same sync name can be ticked all at * once via the thread_tick() call. */ -INLINE const string &Thread:: +INLINE const std::string &Thread:: get_sync_name() const { return _sync_name; } @@ -62,7 +46,7 @@ get_python_index() const { * Returns a string that is guaranteed to be unique to this thread, across all * processes on the machine, during at least the lifetime of this process. */ -INLINE string Thread:: +INLINE std::string Thread:: get_unique_id() const { return _impl.get_unique_id(); } @@ -91,7 +75,7 @@ get_pipeline_stage() const { */ INLINE void Thread:: set_min_pipeline_stage(int min_pipeline_stage) { - set_pipeline_stage(max(_pipeline_stage, min_pipeline_stage)); + set_pipeline_stage(std::max(_pipeline_stage, min_pipeline_stage)); } /** @@ -100,7 +84,7 @@ set_min_pipeline_stage(int min_pipeline_stage) { */ INLINE Thread *Thread:: get_main_thread() { - if (_main_thread == (Thread *)NULL) { + if (_main_thread == nullptr) { init_main_thread(); } return _main_thread; @@ -114,7 +98,7 @@ get_main_thread() { */ INLINE Thread *Thread:: get_external_thread() { - if (_external_thread == (Thread *)NULL) { + if (_external_thread == nullptr) { init_external_thread(); } return _external_thread; @@ -137,7 +121,7 @@ get_current_thread() { return get_main_thread(); #else // HAVE_THREADS Thread *thread = ThreadImpl::get_current_thread(); - if (thread == (Thread *)NULL) { + if (thread == nullptr) { return Thread::get_external_thread(); } return thread; @@ -339,8 +323,8 @@ get_pstats_callback() const { return _pstats_callback; } -INLINE ostream & -operator << (ostream &out, const Thread &thread) { +INLINE std::ostream & +operator << (std::ostream &out, const Thread &thread) { thread.output(out); return out; } diff --git a/panda/src/pipeline/thread.cxx b/panda/src/pipeline/thread.cxx index 6a0f0278fc..351e316033 100644 --- a/panda/src/pipeline/thread.cxx +++ b/panda/src/pipeline/thread.cxx @@ -36,7 +36,7 @@ TypeHandle Thread::_type_handle; * given the same sync_name, for the benefit of PStats. */ Thread:: -Thread(const string &name, const string &sync_name) : +Thread(const std::string &name, const std::string &sync_name) : Namable(name), _sync_name(sync_name), _impl(this) @@ -44,15 +44,15 @@ Thread(const string &name, const string &sync_name) : _started = false; _pstats_index = -1; _python_index = -1; - _pstats_callback = NULL; + _pstats_callback = nullptr; _pipeline_stage = 0; _joinable = false; - _current_task = NULL; + _current_task = nullptr; #ifdef DEBUG_THREADS - _blocked_on_mutex = NULL; - _waiting_on_cvar = NULL; - _waiting_on_cvar_full = NULL; + _blocked_on_mutex = nullptr; + _waiting_on_cvar = nullptr; + _waiting_on_cvar_full = nullptr; #endif } @@ -62,9 +62,9 @@ Thread(const string &name, const string &sync_name) : Thread:: ~Thread() { #ifdef DEBUG_THREADS - nassertv(_blocked_on_mutex == NULL && - _waiting_on_cvar == NULL && - _waiting_on_cvar_full == NULL); + nassertv(_blocked_on_mutex == nullptr && + _waiting_on_cvar == nullptr && + _waiting_on_cvar_full == nullptr); #endif } @@ -87,7 +87,7 @@ Thread:: * case the same pointer will be returned each time). */ PT(Thread) Thread:: -bind_thread(const string &name, const string &sync_name) { +bind_thread(const std::string &name, const std::string &sync_name) { Thread *current_thread = get_current_thread(); if (current_thread != get_external_thread()) { // This thread already has an associated thread. @@ -129,7 +129,7 @@ set_pipeline_stage(int pipeline_stage) { * */ void Thread:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type() << " " << get_name(); } @@ -139,13 +139,13 @@ output(ostream &out) const { * DEBUG_THREADS mode. */ void Thread:: -output_blocker(ostream &out) const { +output_blocker(std::ostream &out) const { #ifdef DEBUG_THREADS - if (_blocked_on_mutex != (MutexDebug *)NULL) { + if (_blocked_on_mutex != nullptr) { _blocked_on_mutex->output_with_holder(out); - } else if (_waiting_on_cvar != (ConditionVarDebug *)NULL) { + } else if (_waiting_on_cvar != nullptr) { out << *_waiting_on_cvar; - } else if (_waiting_on_cvar_full != (ConditionVarFullDebug *)NULL) { + } else if (_waiting_on_cvar_full != nullptr) { out << *_waiting_on_cvar_full; } #endif // DEBUG_THREADS @@ -155,7 +155,7 @@ output_blocker(ostream &out) const { * */ void Thread:: -write_status(ostream &out) { +write_status(std::ostream &out) { #if defined(HAVE_THREADS) && defined(SIMPLE_THREADS) ThreadImpl::write_status(out); #endif @@ -210,7 +210,7 @@ init_main_thread() { // here attempts to protect against that. static int count = 0; ++count; - if (count == 1 && _main_thread == (Thread *)NULL) { + if (count == 1 && _main_thread == nullptr) { _main_thread = new MainThread; _main_thread->ref(); } @@ -221,7 +221,7 @@ init_main_thread() { */ void Thread:: init_external_thread() { - if (_external_thread == (Thread *)NULL) { + if (_external_thread == nullptr) { _external_thread = new ExternalThread; _external_thread->ref(); } diff --git a/panda/src/pipeline/thread.h b/panda/src/pipeline/thread.h index 730deb5872..69b878725a 100644 --- a/panda/src/pipeline/thread.h +++ b/panda/src/pipeline/thread.h @@ -45,26 +45,25 @@ class AsyncTask; */ class EXPCL_PANDA_PIPELINE Thread : public TypedReferenceCount, public Namable { protected: - Thread(const string &name, const string &sync_name); + Thread(const std::string &name, const std::string &sync_name); + Thread(const Thread ©) = delete; PUBLISHED: virtual ~Thread(); -private: - INLINE Thread(const Thread ©); - INLINE void operator = (const Thread ©); - protected: + Thread &operator = (const Thread ©) = delete; + virtual void thread_main()=0; PUBLISHED: - static PT(Thread) bind_thread(const string &name, const string &sync_name); + static PT(Thread) bind_thread(const std::string &name, const std::string &sync_name); - INLINE const string &get_sync_name() const; + INLINE const std::string &get_sync_name() const; INLINE int get_pstats_index() const; INLINE int get_python_index() const; - INLINE string get_unique_id() const; + INLINE std::string get_unique_id() const; INLINE int get_pipeline_stage() const; void set_pipeline_stage(int pipeline_stage); @@ -82,9 +81,9 @@ PUBLISHED: BLOCKING INLINE static void force_yield(); BLOCKING INLINE static void consider_yield(); - virtual void output(ostream &out) const; - void output_blocker(ostream &out) const; - static void write_status(ostream &out); + virtual void output(std::ostream &out) const; + void output_blocker(std::ostream &out) const; + static void write_status(std::ostream &out); INLINE bool is_started() const; INLINE bool is_joinable() const; @@ -144,7 +143,7 @@ protected: bool _started; private: - string _sync_name; + std::string _sync_name; ThreadImpl _impl; int _pstats_index; int _pipeline_stage; @@ -195,7 +194,7 @@ private: friend class AsyncTask; }; -INLINE ostream &operator << (ostream &out, const Thread &thread); +INLINE std::ostream &operator << (std::ostream &out, const Thread &thread); #include "thread.I" diff --git a/panda/src/pipeline/threadDummyImpl.I b/panda/src/pipeline/threadDummyImpl.I index 930f53fe4b..0bd2f7747a 100644 --- a/panda/src/pipeline/threadDummyImpl.I +++ b/panda/src/pipeline/threadDummyImpl.I @@ -107,7 +107,7 @@ sleep(double seconds) { struct timespec rqtp; rqtp.tv_sec = time_t(seconds); rqtp.tv_nsec = long((seconds - (double)rqtp.tv_sec) * 1000000000.0); - nanosleep(&rqtp, NULL); + nanosleep(&rqtp, nullptr); #endif // WIN32 } diff --git a/panda/src/pipeline/threadDummyImpl.cxx b/panda/src/pipeline/threadDummyImpl.cxx index 419744a4b5..2d30630d98 100644 --- a/panda/src/pipeline/threadDummyImpl.cxx +++ b/panda/src/pipeline/threadDummyImpl.cxx @@ -28,10 +28,10 @@ /** * */ -string ThreadDummyImpl:: +std::string ThreadDummyImpl:: get_unique_id() const { // In a single-threaded application, this is just the unique process ID. - ostringstream strm; + std::ostringstream strm; #ifdef WIN32 strm << GetCurrentProcessId(); #else diff --git a/panda/src/pipeline/threadDummyImpl.h b/panda/src/pipeline/threadDummyImpl.h index 1b2c46cd46..7721ca2d6c 100644 --- a/panda/src/pipeline/threadDummyImpl.h +++ b/panda/src/pipeline/threadDummyImpl.h @@ -45,7 +45,7 @@ public: INLINE void join(); INLINE void preempt(); - string get_unique_id() const; + std::string get_unique_id() const; INLINE static void prepare_for_exit(); diff --git a/panda/src/pipeline/threadPosixImpl.I b/panda/src/pipeline/threadPosixImpl.I index 62b6026061..22a8c90118 100644 --- a/panda/src/pipeline/threadPosixImpl.I +++ b/panda/src/pipeline/threadPosixImpl.I @@ -101,7 +101,7 @@ sleep(double seconds) { struct timespec rqtp; rqtp.tv_sec = time_t(seconds); rqtp.tv_nsec = long((seconds - (double)rqtp.tv_sec) * 1000000000.0); - nanosleep(&rqtp, NULL); + nanosleep(&rqtp, nullptr); } /** diff --git a/panda/src/pipeline/threadPosixImpl.cxx b/panda/src/pipeline/threadPosixImpl.cxx index 5104c67926..0d88c5ebe8 100644 --- a/panda/src/pipeline/threadPosixImpl.cxx +++ b/panda/src/pipeline/threadPosixImpl.cxx @@ -41,14 +41,14 @@ ThreadPosixImpl:: << "Deleting thread " << _parent_obj->get_name() << "\n"; } - _mutex.acquire(); + _mutex.lock(); if (!_detached) { pthread_detach(_thread); _detached = true; } - _mutex.release(); + _mutex.unlock(); } /** @@ -65,13 +65,13 @@ setup_main_thread() { */ bool ThreadPosixImpl:: start(ThreadPriority priority, bool joinable) { - _mutex.acquire(); + _mutex.lock(); if (thread_cat->is_debug()) { thread_cat.debug() << "Starting " << *_parent_obj << "\n"; } nassertd(_status == S_new) { - _mutex.release(); + _mutex.unlock(); return false; } @@ -148,12 +148,12 @@ start(ThreadPriority priority, bool joinable) { // Oops, we couldn't start the thread. Be sure to decrement the reference // count we incremented above, and return false to indicate failure. unref_delete(_parent_obj); - _mutex.release(); + _mutex.unlock(); return false; } // Thread was successfully started. - _mutex.release(); + _mutex.unlock(); return true; } @@ -163,23 +163,23 @@ start(ThreadPriority priority, bool joinable) { */ void ThreadPosixImpl:: join() { - _mutex.acquire(); + _mutex.lock(); if (!_detached) { - _mutex.release(); + _mutex.unlock(); void *return_val; pthread_join(_thread, &return_val); _detached = true; return; } - _mutex.release(); + _mutex.unlock(); } /** * */ -string ThreadPosixImpl:: +std::string ThreadPosixImpl:: get_unique_id() const { - ostringstream strm; + std::ostringstream strm; strm << getpid() << "." << _thread; return strm.str(); @@ -193,7 +193,7 @@ get_unique_id() const { bool ThreadPosixImpl:: attach_java_vm() { JNIEnv *env; - string thread_name = _parent_obj->get_name(); + std::string thread_name = _parent_obj->get_name(); JavaVMAttachArgs args; args.version = JNI_VERSION_1_2; args.name = thread_name.c_str(); @@ -243,17 +243,17 @@ root_func(void *data) { ThreadPosixImpl *self = (ThreadPosixImpl *)data; int result = pthread_setspecific(_pt_ptr_index, self->_parent_obj); - nassertr(result == 0, NULL); + nassertr(result == 0, nullptr); { - self->_mutex.acquire(); + self->_mutex.lock(); nassertd(self->_status == S_start_called) { - self->_mutex.release(); - return NULL; + self->_mutex.unlock(); + return nullptr; } self->_status = S_running; - self->_mutex.release(); + self->_mutex.unlock(); } #ifdef ANDROID @@ -270,13 +270,13 @@ root_func(void *data) { } { - self->_mutex.acquire(); + self->_mutex.lock(); nassertd(self->_status == S_running) { - self->_mutex.release(); - return NULL; + self->_mutex.unlock(); + return nullptr; } self->_status = S_finished; - self->_mutex.release(); + self->_mutex.unlock(); } #ifdef ANDROID @@ -293,7 +293,7 @@ root_func(void *data) { unref_delete(self->_parent_obj); } - return NULL; + return nullptr; } /** @@ -304,7 +304,7 @@ void ThreadPosixImpl:: init_pt_ptr_index() { nassertv(!_got_pt_ptr_index); - int result = pthread_key_create(&_pt_ptr_index, NULL); + int result = pthread_key_create(&_pt_ptr_index, nullptr); if (result != 0) { thread_cat->error() << "Unable to associate Thread pointers with threads.\n"; diff --git a/panda/src/pipeline/threadPosixImpl.h b/panda/src/pipeline/threadPosixImpl.h index ee279c98dd..cdfd5eab8a 100644 --- a/panda/src/pipeline/threadPosixImpl.h +++ b/panda/src/pipeline/threadPosixImpl.h @@ -44,7 +44,7 @@ public: void join(); INLINE void preempt(); - string get_unique_id() const; + std::string get_unique_id() const; INLINE static void prepare_for_exit(); diff --git a/panda/src/pipeline/threadPriority.cxx b/panda/src/pipeline/threadPriority.cxx index 0402273099..3d9c55fe21 100644 --- a/panda/src/pipeline/threadPriority.cxx +++ b/panda/src/pipeline/threadPriority.cxx @@ -15,6 +15,10 @@ #include "pnotify.h" // nassertr #include "pipeline.h" +using std::istream; +using std::ostream; +using std::string; + ostream & operator << (ostream &out, ThreadPriority pri) { switch (pri) { diff --git a/panda/src/pipeline/threadPriority.h b/panda/src/pipeline/threadPriority.h index 104b0dac3b..8d1379e98a 100644 --- a/panda/src/pipeline/threadPriority.h +++ b/panda/src/pipeline/threadPriority.h @@ -27,10 +27,10 @@ enum ThreadPriority { }; END_PUBLISH -EXPCL_PANDA_PIPELINE ostream & -operator << (ostream &out, ThreadPriority pri); -EXPCL_PANDA_PIPELINE istream & -operator >> (istream &in, ThreadPriority &pri); +EXPCL_PANDA_PIPELINE std::ostream & +operator << (std::ostream &out, ThreadPriority pri); +EXPCL_PANDA_PIPELINE std::istream & +operator >> (std::istream &in, ThreadPriority &pri); #endif diff --git a/panda/src/pipeline/threadSimpleImpl.I b/panda/src/pipeline/threadSimpleImpl.I index 41b31b2b14..001f3037d4 100644 --- a/panda/src/pipeline/threadSimpleImpl.I +++ b/panda/src/pipeline/threadSimpleImpl.I @@ -130,7 +130,7 @@ get_wake_time() const { * Writes a list of threads running and threads blocked. */ void ThreadSimpleImpl:: -write_status(ostream &out) { +write_status(std::ostream &out) { ThreadSimpleManager *manager = ThreadSimpleManager::get_global_ptr(); manager->write_status(out); } diff --git a/panda/src/pipeline/threadSimpleImpl.cxx b/panda/src/pipeline/threadSimpleImpl.cxx index b4c90cd54e..a631421503 100644 --- a/panda/src/pipeline/threadSimpleImpl.cxx +++ b/panda/src/pipeline/threadSimpleImpl.cxx @@ -43,7 +43,7 @@ ThreadSimpleImpl(Thread *parent_obj) : _wake_time = 0.0; _context = alloc_thread_context(); - _stack = NULL; + _stack = nullptr; _stack_size = 0; // Save this pointer for convenience. @@ -70,7 +70,7 @@ ThreadSimpleImpl:: free_thread_context(_context); - if (_stack != (void *)NULL) { + if (_stack != nullptr) { memory_hook->mmap_free(_stack, _stack_size); } _manager->remove_thread(this); @@ -107,7 +107,7 @@ start(ThreadPriority priority, bool joinable) { nassertr(_status == TS_new, false); - nassertr(_stack == NULL, false); + nassertr(_stack == nullptr, false); _stack_size = memory_hook->round_up_to_page_size((size_t)thread_stack_size); if (needs_stack_prealloc) { _stack = (unsigned char *)memory_hook->mmap_alloc(_stack_size, true); @@ -141,7 +141,7 @@ start(ThreadPriority priority, bool joinable) { #ifdef HAVE_PYTHON // Query the current Python thread state. - _python_state = PyThreadState_Swap(NULL); + _python_state = PyThreadState_Swap(nullptr); PyThreadState_Swap(_python_state); #endif // HAVE_PYTHON @@ -178,9 +178,9 @@ preempt() { /** * */ -string ThreadSimpleImpl:: +std::string ThreadSimpleImpl:: get_unique_id() const { - ostringstream strm; + std::ostringstream strm; #ifdef WIN32 strm << GetCurrentProcessId(); #else diff --git a/panda/src/pipeline/threadSimpleImpl.h b/panda/src/pipeline/threadSimpleImpl.h index aa2e4e7ab7..c552dd1357 100644 --- a/panda/src/pipeline/threadSimpleImpl.h +++ b/panda/src/pipeline/threadSimpleImpl.h @@ -54,7 +54,7 @@ public: void join(); void preempt(); - string get_unique_id() const; + std::string get_unique_id() const; static void prepare_for_exit(); @@ -75,7 +75,7 @@ public: INLINE double get_wake_time() const; - INLINE static void write_status(ostream &out); + INLINE static void write_status(std::ostream &out); private: static void st_begin_thread(void *data); diff --git a/panda/src/pipeline/threadSimpleManager.cxx b/panda/src/pipeline/threadSimpleManager.cxx index 4c7640b885..4d9890dfd4 100644 --- a/panda/src/pipeline/threadSimpleManager.cxx +++ b/panda/src/pipeline/threadSimpleManager.cxx @@ -71,9 +71,9 @@ ThreadSimpleManager() : { _tick_scale = 1000000.0; _total_ticks = 0; - _current_thread = NULL; + _current_thread = nullptr; _clock = TrueClock::get_global_ptr(); - _waiting_for_exit = NULL; + _waiting_for_exit = nullptr; // Install these global pointers so very low-level code (code defined before // the pipeline directory) can yield when necessary. @@ -235,12 +235,12 @@ next_context() { #ifdef HAVE_PYTHON // Save the current Python thread state. - _current_thread->_python_state = PyThreadState_Swap(NULL); + _current_thread->_python_state = PyThreadState_Swap(nullptr); #endif // HAVE_PYTHON #ifdef DO_PSTATS Thread::PStatsCallback *pstats_callback = _current_thread->_parent_obj->get_pstats_callback(); - if (pstats_callback != NULL) { + if (pstats_callback != nullptr) { pstats_callback->deactivate_hook(_current_thread->_parent_obj); } #endif // DO_PSTATS @@ -250,7 +250,7 @@ next_context() { // current thread. #ifdef DO_PSTATS - if (pstats_callback != NULL) { + if (pstats_callback != nullptr) { pstats_callback->activate_hook(_current_thread->_parent_obj); } #endif // DO_PSTATS @@ -281,7 +281,7 @@ prepare_for_exit() { << "prepare_for_exit\n"; } - nassertv(_waiting_for_exit == NULL); + nassertv(_waiting_for_exit == nullptr); _waiting_for_exit = _current_thread; // At this point, any non-joinable threads on any of the queues are @@ -321,7 +321,7 @@ prepare_for_exit() { */ void ThreadSimpleManager:: set_current_thread(ThreadSimpleImpl *current_thread) { - nassertv(_current_thread == (ThreadSimpleImpl *)NULL); + nassertv(_current_thread == nullptr); _current_thread = current_thread; } @@ -369,7 +369,7 @@ system_sleep(double seconds) { struct timeval tv; tv.tv_sec = time_t(seconds); tv.tv_usec = long((seconds - (double)tv.tv_sec) * 1000000.0 + 0.5); - select(0, NULL, NULL, NULL, &tv); + select(0, nullptr, nullptr, nullptr, &tv); #endif // WIN32 } @@ -377,7 +377,7 @@ system_sleep(double seconds) { * Writes a list of threads running and threads blocked. */ void ThreadSimpleManager:: -write_status(ostream &out) const { +write_status(std::ostream &out) const { out << "Currently running: " << *_current_thread->_parent_obj << "\n"; out << "Ready:"; @@ -498,7 +498,7 @@ choose_next_context(struct ThreadContext *from_context) { double now = get_current_time(); do_timeslice_accounting(_current_thread, now); - _current_thread = NULL; + _current_thread = nullptr; if (!_sleeping.empty() || !_volunteers.empty()) { if (_ready.empty() && _next_ready.empty()) { @@ -578,12 +578,12 @@ choose_next_context(struct ThreadContext *from_context) { } else { // No threads are ready! - if (_waiting_for_exit != NULL) { + if (_waiting_for_exit != nullptr) { // This is a shutdown situation. In this case, we quietly abandoned // the remaining blocked threads, if any, and switch back to the // main thread to finish shutting down. _ready.push_back(_waiting_for_exit); - _waiting_for_exit = NULL; + _waiting_for_exit = nullptr; break; } @@ -663,7 +663,7 @@ do_timeslice_accounting(ThreadSimpleImpl *thread, double now) { // Clamp the elapsed time at 0. (If it's less than 0, the clock is running // backwards, ick.) - elapsed = max(elapsed, 0.0); + elapsed = std::max(elapsed, 0.0); unsigned int ticks = (unsigned int)(elapsed * _tick_scale + 0.5); thread->_run_ticks += ticks; diff --git a/panda/src/pipeline/threadSimpleManager.h b/panda/src/pipeline/threadSimpleManager.h index 364b59be8f..668c1451fe 100644 --- a/panda/src/pipeline/threadSimpleManager.h +++ b/panda/src/pipeline/threadSimpleManager.h @@ -78,7 +78,7 @@ public: double get_current_time() const; INLINE static ThreadSimpleManager *get_global_ptr(); - void write_status(ostream &out) const; + void write_status(std::ostream &out) const; private: static void init_pointers(); diff --git a/panda/src/pipeline/threadWin32Impl.cxx b/panda/src/pipeline/threadWin32Impl.cxx index 006a98441e..4671787918 100644 --- a/panda/src/pipeline/threadWin32Impl.cxx +++ b/panda/src/pipeline/threadWin32Impl.cxx @@ -49,13 +49,13 @@ setup_main_thread() { */ bool ThreadWin32Impl:: start(ThreadPriority priority, bool joinable) { - _mutex.acquire(); + _mutex.lock(); if (thread_cat->is_debug()) { thread_cat.debug() << "Starting " << *_parent_obj << "\n"; } nassertd(_status == S_new && _thread == 0) { - _mutex.release(); + _mutex.unlock(); return false; } @@ -70,13 +70,13 @@ start(ThreadPriority priority, bool joinable) { // eventually decrement it when it terminates. _parent_obj->ref(); _thread = - CreateThread(NULL, 0, &root_func, (void *)this, 0, &_thread_id); + CreateThread(nullptr, 0, &root_func, (void *)this, 0, &_thread_id); if (_thread_id == 0) { // Oops, we couldn't start the thread. Be sure to decrement the reference // count we incremented above, and return false to indicate failure. unref_delete(_parent_obj); - _mutex.release(); + _mutex.unlock(); return false; } @@ -100,7 +100,7 @@ start(ThreadPriority priority, bool joinable) { break; } - _mutex.release(); + _mutex.unlock(); return true; } @@ -110,24 +110,24 @@ start(ThreadPriority priority, bool joinable) { */ void ThreadWin32Impl:: join() { - _mutex.acquire(); + _mutex.lock(); nassertd(_joinable && _status != S_new) { - _mutex.release(); + _mutex.unlock(); return; } while (_status != S_finished) { _cv.wait(); } - _mutex.release(); + _mutex.unlock(); } /** * */ -string ThreadWin32Impl:: +std::string ThreadWin32Impl:: get_unique_id() const { - ostringstream strm; + std::ostringstream strm; strm << GetCurrentProcessId() << "." << _thread_id; return strm.str(); @@ -147,14 +147,14 @@ root_func(LPVOID data) { nassertr(result, 1); { - self->_mutex.acquire(); + self->_mutex.lock(); nassertd(self->_status == S_start_called) { - self->_mutex.release(); + self->_mutex.unlock(); return 1; } self->_status = S_running; self->_cv.notify(); - self->_mutex.release(); + self->_mutex.unlock(); } self->_parent_obj->thread_main(); @@ -166,14 +166,14 @@ root_func(LPVOID data) { } { - self->_mutex.acquire(); + self->_mutex.lock(); nassertd(self->_status == S_running) { - self->_mutex.release(); + self->_mutex.unlock(); return 1; } self->_status = S_finished; self->_cv.notify(); - self->_mutex.release(); + self->_mutex.unlock(); } // Now drop the parent object reference that we grabbed in start(). This diff --git a/panda/src/pipeline/threadWin32Impl.h b/panda/src/pipeline/threadWin32Impl.h index 665e1be43c..69163230c9 100644 --- a/panda/src/pipeline/threadWin32Impl.h +++ b/panda/src/pipeline/threadWin32Impl.h @@ -39,7 +39,7 @@ public: void join(); INLINE void preempt(); - string get_unique_id() const; + std::string get_unique_id() const; INLINE static void prepare_for_exit(); diff --git a/panda/src/pnmimage/config_pnmimage.h b/panda/src/pnmimage/config_pnmimage.h index 9ff40dd5a0..f5f6c029bb 100644 --- a/panda/src/pnmimage/config_pnmimage.h +++ b/panda/src/pnmimage/config_pnmimage.h @@ -21,11 +21,11 @@ NotifyCategoryDecl(pnmimage, EXPCL_PANDA_PNMIMAGE, EXPTP_PANDA_PNMIMAGE); -extern ConfigVariableBool pfm_force_littleendian; -extern ConfigVariableBool pfm_reverse_dimensions; -extern ConfigVariableBool pfm_resize_gaussian; -extern ConfigVariableBool pfm_resize_quick; -extern ConfigVariableDouble pfm_resize_radius; +extern EXPCL_PANDA_PNMIMAGE ConfigVariableBool pfm_force_littleendian; +extern EXPCL_PANDA_PNMIMAGE ConfigVariableBool pfm_reverse_dimensions; +extern EXPCL_PANDA_PNMIMAGE ConfigVariableBool pfm_resize_gaussian; +extern EXPCL_PANDA_PNMIMAGE ConfigVariableBool pfm_resize_quick; +extern EXPCL_PANDA_PNMIMAGE ConfigVariableDouble pfm_resize_radius; extern EXPCL_PANDA_PNMIMAGE void init_libpnmimage(); diff --git a/panda/src/pnmimage/convert_srgb.I b/panda/src/pnmimage/convert_srgb.I index f49cc38203..27d6bbf802 100644 --- a/panda/src/pnmimage/convert_srgb.I +++ b/panda/src/pnmimage/convert_srgb.I @@ -44,8 +44,8 @@ INLINE unsigned char decode_sRGB_uchar(unsigned char val) { */ INLINE unsigned char decode_sRGB_uchar(float val) { return (val <= 0.04045f) - ? (unsigned char)(max(0.f, val) * (255.f / 12.92f) + 0.5f) - : (unsigned char)(cpow((min(val, 1.f) + 0.055f) * (1.f / 1.055f), 2.4f) * 255.f + 0.5f); + ? (unsigned char)(std::max(0.f, val) * (255.f / 12.92f) + 0.5f) + : (unsigned char)(cpow((std::min(val, 1.f) + 0.055f) * (1.f / 1.055f), 2.4f) * 255.f + 0.5f); } /** @@ -99,8 +99,8 @@ encode_sRGB_uchar(float val) { return encode_sRGB_uchar_sse2(val); #else return (val < 0.0031308f) - ? (unsigned char) (max(0.f, val) * 3294.6f + 0.5f) - : (unsigned char) (269.025f * cpow(min(val, 1.f), 0.41666f) - 13.525f); + ? (unsigned char) (std::max(0.f, val) * 3294.6f + 0.5f) + : (unsigned char) (269.025f * cpow(std::min(val, 1.f), 0.41666f) - 13.525f); #endif } diff --git a/panda/src/pnmimage/pfmFile.I b/panda/src/pnmimage/pfmFile.I index b8f63272f0..0ba12061ee 100644 --- a/panda/src/pnmimage/pfmFile.I +++ b/panda/src/pnmimage/pfmFile.I @@ -587,12 +587,12 @@ setup_sub_image(const PfmFile ©, int &xto, int &yto, yto = 0; } - x_size = min(x_size, copy.get_x_size() - xfrom); - y_size = min(y_size, copy.get_y_size() - yfrom); + x_size = std::min(x_size, copy.get_x_size() - xfrom); + y_size = std::min(y_size, copy.get_y_size() - yfrom); xmin = xto; ymin = yto; - xmax = min(xmin + x_size, get_x_size()); - ymax = min(ymin + y_size, get_y_size()); + xmax = std::min(xmin + x_size, get_x_size()); + ymax = std::min(ymin + y_size, get_y_size()); } diff --git a/panda/src/pnmimage/pfmFile.cxx b/panda/src/pnmimage/pfmFile.cxx index d0424fcafe..57b9671d1a 100644 --- a/panda/src/pnmimage/pfmFile.cxx +++ b/panda/src/pnmimage/pfmFile.cxx @@ -24,6 +24,11 @@ #include "string_utils.h" #include "look_at.h" +using std::istream; +using std::max; +using std::min; +using std::ostream; + /** * */ @@ -118,7 +123,7 @@ read(const Filename &fullpath) { Filename filename = Filename::binary_filename(fullpath); PT(VirtualFile) file = vfs->get_file(filename); - if (file == (VirtualFile *)NULL) { + if (file == nullptr) { // No such file. pnmimage_cat.error() << "Could not find " << fullpath << "\n"; @@ -147,7 +152,7 @@ read(const Filename &fullpath) { bool PfmFile:: read(istream &in, const Filename &fullpath) { PNMReader *reader = make_reader(&in, false, fullpath); - if (reader == (PNMReader *)NULL) { + if (reader == nullptr) { clear(); return false; } @@ -163,7 +168,7 @@ bool PfmFile:: read(PNMReader *reader) { clear(); - if (reader == NULL) { + if (reader == nullptr) { return false; } @@ -230,7 +235,7 @@ write(ostream &out, const Filename &fullpath) { } PNMWriter *writer = make_writer(&out, false, fullpath); - if (writer == (PNMWriter *)NULL) { + if (writer == nullptr) { return false; } @@ -244,7 +249,7 @@ write(ostream &out, const Filename &fullpath) { */ bool PfmFile:: write(PNMWriter *writer) { - if (writer == NULL) { + if (writer == nullptr) { return false; } @@ -1721,35 +1726,32 @@ compute_planar_bounds(const LPoint2f ¢er, PN_float32 point_dist, PN_float32 // Now determine the minmax. PN_float32 min_x, min_y, min_z, max_x, max_y, max_z; - bool got_point = false; if (points_only) { - LPoint3f points[4] = { + const LPoint3f points[4] = { p0 * rinv, p1 * rinv, p2 * rinv, p3 * rinv, }; - for (int i = 0; i < 4; ++i) { - const LPoint3f &point = points[i]; - if (!got_point) { - min_x = point[0]; - min_y = point[1]; - min_z = point[2]; - max_x = point[0]; - max_y = point[1]; - max_z = point[2]; - got_point = true; - } else { - min_x = min(min_x, point[0]); - min_y = min(min_y, point[1]); - min_z = min(min_z, point[2]); - max_x = max(max_x, point[0]); - max_y = max(max_y, point[1]); - max_z = max(max_z, point[2]); - } - } + const LPoint3f &point = points[0]; + min_x = point[0]; + min_y = point[1]; + min_z = point[2]; + max_x = point[0]; + max_y = point[1]; + max_z = point[2]; + for (int i = 1; i < 4; ++i) { + const LPoint3f &point = points[i]; + min_x = min(min_x, point[0]); + min_y = min(min_y, point[1]); + min_z = min(min_z, point[2]); + max_x = max(max_x, point[0]); + max_y = max(max_y, point[1]); + max_z = max(max_z, point[2]); + } } else { + bool got_point = false; for (int yi = 0; yi < _y_size; ++yi) { for (int xi = 0; xi < _x_size; ++xi) { if (!has_point(xi, yi)) { @@ -1775,6 +1777,14 @@ compute_planar_bounds(const LPoint2f ¢er, PN_float32 point_dist, PN_float32 } } } + if (!got_point) { + min_x = 0.0f; + min_y = 0.0f; + min_z = 0.0f; + max_x = 0.0f; + max_y = 0.0f; + max_z = 0.0f; + } } PT(BoundingHexahedron) bounds; @@ -1816,7 +1826,7 @@ compute_planar_bounds(const LPoint2f ¢er, PN_float32 point_dist, PN_float32 break; default: - nassertr(false, NULL); + nassertr(false, nullptr); } // Rotate the bounding volume back into the original space of the screen. diff --git a/panda/src/pnmimage/pfmFile.h b/panda/src/pnmimage/pfmFile.h index 74eda76bce..cb8dd3b309 100644 --- a/panda/src/pnmimage/pfmFile.h +++ b/panda/src/pnmimage/pfmFile.h @@ -38,10 +38,10 @@ PUBLISHED: void clear(int x_size, int y_size, int num_channels); BLOCKING bool read(const Filename &fullpath); - BLOCKING bool read(istream &in, const Filename &fullpath = Filename()); + BLOCKING bool read(std::istream &in, const Filename &fullpath = Filename()); BLOCKING bool read(PNMReader *reader); BLOCKING bool write(const Filename &fullpath); - BLOCKING bool write(ostream &out, const Filename &fullpath = Filename()); + BLOCKING bool write(std::ostream &out, const Filename &fullpath = Filename()); BLOCKING bool write(PNMWriter *writer); BLOCKING bool load(const PNMImage &pnmimage); @@ -168,7 +168,7 @@ PUBLISHED: INLINE void apply_exponent(float c0_exponent, float c1_exponent, float c2_exponent); void apply_exponent(float c0_exponent, float c1_exponent, float c2_exponent, float c3_exponent); - void output(ostream &out) const; + void output(std::ostream &out) const; #ifdef HAVE_PYTHON EXTENSION(PyObject *get_points() const); diff --git a/panda/src/pnmimage/pfmFile_ext.cxx b/panda/src/pnmimage/pfmFile_ext.cxx index 4e041e986f..fb31f7ead5 100644 --- a/panda/src/pnmimage/pfmFile_ext.cxx +++ b/panda/src/pnmimage/pfmFile_ext.cxx @@ -93,7 +93,7 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const { int channels = _this->get_num_channels(); int num_pixels = _this->get_x_size() * _this->get_y_size(); - if (self != NULL) { + if (self != nullptr) { Py_INCREF(self); } view->obj = self; @@ -101,20 +101,20 @@ __getbuffer__(PyObject *self, Py_buffer *view, int flags) const { view->len = 4 * table.size(); view->readonly = 1; view->itemsize = 4; - view->format = NULL; + view->format = nullptr; if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) { view->format = (char *) "f"; } view->ndim = 2; - view->shape = NULL; + view->shape = nullptr; if ((flags & PyBUF_ND) == PyBUF_ND) { // If you're leaking and you know it, clap your hands! view->shape = new Py_ssize_t[2]; view->shape[0] = num_pixels; view->shape[1] = channels; } - view->strides = NULL; - view->suboffsets = NULL; + view->strides = nullptr; + view->suboffsets = nullptr; return 0; #else diff --git a/panda/src/pnmimage/pnm-image-filter.cxx b/panda/src/pnmimage/pnm-image-filter.cxx index 63398ad3c1..6ca6a145d6 100644 --- a/panda/src/pnmimage/pnm-image-filter.cxx +++ b/panda/src/pnmimage/pnm-image-filter.cxx @@ -37,6 +37,9 @@ #include "pnmImage.h" #include "pfmFile.h" +using std::max; +using std::min; + // WorkType is an abstraction that allows the filtering process to be // recompiled to use either floating-point or integer arithmetic. On SGI // machines, there doesn't seem to be much of a performance difference-- if diff --git a/panda/src/pnmimage/pnmBrush.cxx b/panda/src/pnmimage/pnmBrush.cxx index 64dffab3cb..94d1799fe7 100644 --- a/panda/src/pnmimage/pnmBrush.cxx +++ b/panda/src/pnmimage/pnmBrush.cxx @@ -16,6 +16,9 @@ #include "config_pnmimage.h" #include "cmath.h" +using std::max; +using std::min; + // A PNMTransparentBrush doesn't draw or fill anything. class EXPCL_PANDA_PNMIMAGE PNMTransparentBrush : public PNMBrush { public: diff --git a/panda/src/pnmimage/pnmFileType.cxx b/panda/src/pnmimage/pnmFileType.cxx index 762d86fee4..c400db9d53 100644 --- a/panda/src/pnmimage/pnmFileType.cxx +++ b/panda/src/pnmimage/pnmFileType.cxx @@ -18,6 +18,8 @@ #include "bamReader.h" #include "bamWriter.h" +using std::string; + bool PNMFileType::_did_init_pnm = false; TypeHandle PNMFileType::_type_handle; @@ -91,8 +93,8 @@ matches_magic_number(const string &) const { * returns NULL. */ PNMReader *PNMFileType:: -make_reader(istream *, bool, const string &) { - return NULL; +make_reader(std::istream *, bool, const string &) { + return nullptr; } /** @@ -101,8 +103,8 @@ make_reader(istream *, bool, const string &) { * NULL. */ PNMWriter *PNMFileType:: -make_writer(ostream *, bool) { - return NULL; +make_writer(std::ostream *, bool) { + return nullptr; } /** diff --git a/panda/src/pnmimage/pnmFileType.h b/panda/src/pnmimage/pnmFileType.h index 48e4a533fb..fbde4717a2 100644 --- a/panda/src/pnmimage/pnmFileType.h +++ b/panda/src/pnmimage/pnmFileType.h @@ -37,12 +37,12 @@ public: virtual ~PNMFileType(); PUBLISHED: - virtual string get_name() const=0; + virtual std::string get_name() const=0; virtual int get_num_extensions() const; - virtual string get_extension(int n) const; + virtual std::string get_extension(int n) const; MAKE_SEQ(get_extensions, get_num_extensions, get_extension); - virtual string get_suggested_extension() const; + virtual std::string get_suggested_extension() const; MAKE_PROPERTY(name, get_name); MAKE_SEQ_PROPERTY(extensions, get_num_extensions, get_extension); @@ -50,11 +50,11 @@ PUBLISHED: public: virtual bool has_magic_number() const; - virtual bool matches_magic_number(const string &magic_number) const; + virtual bool matches_magic_number(const std::string &magic_number) const; - virtual PNMReader *make_reader(istream *file, bool owns_file = true, - const string &magic_number = string()); - virtual PNMWriter *make_writer(ostream *file, bool owns_file = true); + virtual PNMReader *make_reader(std::istream *file, bool owns_file = true, + const std::string &magic_number = std::string()); + virtual PNMWriter *make_writer(std::ostream *file, bool owns_file = true); protected: static void init_pnm(); diff --git a/panda/src/pnmimage/pnmFileTypeRegistry.cxx b/panda/src/pnmimage/pnmFileTypeRegistry.cxx index 96e24ef1bb..d290f52bdc 100644 --- a/panda/src/pnmimage/pnmFileTypeRegistry.cxx +++ b/panda/src/pnmimage/pnmFileTypeRegistry.cxx @@ -21,6 +21,8 @@ #include +using std::string; + PNMFileTypeRegistry *PNMFileTypeRegistry::_global_ptr; /** @@ -132,7 +134,7 @@ get_num_types() const { */ PNMFileType *PNMFileTypeRegistry:: get_type(int n) const { - nassertr(n >= 0 && n < (int)_types.size(), NULL); + nassertr(n >= 0 && n < (int)_types.size(), nullptr); return _types[n]; } @@ -190,7 +192,7 @@ get_type_from_extension(const string &filename) const { if (ei == _extensions.end() || (*ei).second.empty()) { // Nothing matches that string. - return NULL; + return nullptr; } } @@ -219,7 +221,7 @@ get_type_from_magic_number(const string &magic_number) const { } } - return NULL; + return nullptr; } /** @@ -235,7 +237,7 @@ get_type_by_handle(TypeHandle handle) const { return (*hi).second; } - return (PNMFileType *)NULL; + return nullptr; } /** @@ -243,7 +245,7 @@ get_type_by_handle(TypeHandle handle) const { * one per line. */ void PNMFileTypeRegistry:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { if (_types.empty()) { indent(out, indent_level) << "(No image types are known).\n"; } else { @@ -252,7 +254,7 @@ write(ostream &out, int indent_level) const { PNMFileType *type = (*ti); string name = type->get_name(); indent(out, indent_level) << name; - indent(out, max(30 - (int)name.length(), 0)) << " "; + indent(out, std::max(30 - (int)name.length(), 0)) << " "; int num_extensions = type->get_num_extensions(); if (num_extensions == 1) { @@ -273,7 +275,7 @@ write(ostream &out, int indent_level) const { */ PNMFileTypeRegistry *PNMFileTypeRegistry:: get_global_ptr() { - if (_global_ptr == (PNMFileTypeRegistry *)NULL) { + if (_global_ptr == nullptr) { _global_ptr = new PNMFileTypeRegistry; } return _global_ptr; diff --git a/panda/src/pnmimage/pnmFileTypeRegistry.h b/panda/src/pnmimage/pnmFileTypeRegistry.h index 9c8702a961..ae4c6a7688 100644 --- a/panda/src/pnmimage/pnmFileTypeRegistry.h +++ b/panda/src/pnmimage/pnmFileTypeRegistry.h @@ -41,11 +41,11 @@ PUBLISHED: MAKE_SEQ(get_types, get_num_types, get_type); MAKE_SEQ_PROPERTY(types, get_num_types, get_type); - PNMFileType *get_type_from_extension(const string &filename) const; - PNMFileType *get_type_from_magic_number(const string &magic_number) const; + PNMFileType *get_type_from_extension(const std::string &filename) const; + PNMFileType *get_type_from_magic_number(const std::string &magic_number) const; PNMFileType *get_type_by_handle(TypeHandle handle) const; - void write(ostream &out, int indent_level = 0) const; + void write(std::ostream &out, int indent_level = 0) const; static PNMFileTypeRegistry *get_global_ptr(); @@ -55,7 +55,7 @@ private: typedef pvector Types; Types _types; - typedef pmap Extensions; + typedef pmap Extensions; Extensions _extensions; typedef pmap Handles; diff --git a/panda/src/pnmimage/pnmImage.I b/panda/src/pnmimage/pnmImage.I index d4a7026483..fe589d3f9b 100644 --- a/panda/src/pnmimage/pnmImage.I +++ b/panda/src/pnmimage/pnmImage.I @@ -16,8 +16,8 @@ */ INLINE PNMImage:: PNMImage() { - _array = NULL; - _alpha = NULL; + _array = nullptr; + _alpha = nullptr; clear(); } @@ -28,8 +28,8 @@ PNMImage() { INLINE PNMImage:: PNMImage(int x_size, int y_size, int num_channels, xelval maxval, PNMFileType *type, ColorSpace color_space) { - _array = NULL; - _alpha = NULL; + _array = nullptr; + _alpha = nullptr; clear(x_size, y_size, num_channels, maxval, type, color_space); } @@ -41,8 +41,8 @@ INLINE PNMImage:: PNMImage(const PNMImage ©) { // We don't need to invoke PNMImageHeader's copy constructor, because we'll // just call copy_from(). - _array = NULL; - _alpha = NULL; + _array = nullptr; + _alpha = nullptr; copy_from(copy); } @@ -68,7 +68,7 @@ INLINE PNMImage:: */ INLINE xelval PNMImage:: clamp_val(int input_value) const { - return (xelval)min(max(0, input_value), (int)get_maxval()); + return (xelval)std::min(std::max(0, input_value), (int)get_maxval()); } /** @@ -80,7 +80,7 @@ to_val(float input_value) const { switch (_xel_encoding) { case XE_generic: case XE_generic_alpha: - return (int)(min(1.0f, max(0.0f, input_value)) * get_maxval() + 0.5f); + return (int)(std::min(1.0f, std::max(0.0f, input_value)) * get_maxval() + 0.5f); case XE_generic_sRGB: case XE_generic_sRGB_alpha: @@ -97,7 +97,7 @@ to_val(float input_value) const { case XE_scRGB: case XE_scRGB_alpha: - return min(max(0, (int)((8192 * input_value) + 4096.5f)), 65535); + return std::min(std::max(0, (int)((8192 * input_value) + 4096.5f)), 65535); default: return 0; @@ -251,7 +251,7 @@ get_color_space() const { */ INLINE bool PNMImage:: is_valid() const { - return (_array != NULL); + return (_array != nullptr); } /** @@ -403,7 +403,7 @@ get_gray_val(int x, int y) const { */ INLINE xelval PNMImage:: get_alpha_val(int x, int y) const { - nassertr(_alpha != NULL && x >= 0 && x < _x_size && y >= 0 && y < _y_size, 0); + nassertr(_alpha != nullptr && x >= 0 && x < _x_size && y >= 0 && y < _y_size, 0); return alpha_row(y)[x]; } @@ -468,7 +468,7 @@ set_gray_val(int x, int y, xelval gray) { */ INLINE void PNMImage:: set_alpha_val(int x, int y, xelval a) { - nassertv(_alpha != NULL && x >= 0 && x < _x_size && y >= 0 && y < _y_size); + nassertv(_alpha != nullptr && x >= 0 && x < _x_size && y >= 0 && y < _y_size); alpha_row(y)[x] = a; } @@ -559,9 +559,9 @@ set_xel(int x, int y, const LRGBColorf &value) { case XE_scRGB_alpha: { LRGBColorf scaled = value * 8192.f + 4096.5f; - col.r = min(max(0, (int)scaled[0]), 65535); - col.g = min(max(0, (int)scaled[1]), 65535); - col.b = min(max(0, (int)scaled[2]), 65535); + col.r = std::min(std::max(0, (int)scaled[0]), 65535); + col.g = std::min(std::max(0, (int)scaled[1]), 65535); + col.b = std::min(std::max(0, (int)scaled[2]), 65535); } break; } @@ -721,19 +721,19 @@ set_xel_a(int x, int y, const LColorf &value) { case XE_scRGB: { LColorf scaled = value * 8192.0f + 4096.5f; - col.r = min(max(0, (int)scaled[0]), 65535); - col.g = min(max(0, (int)scaled[1]), 65535); - col.b = min(max(0, (int)scaled[2]), 65535); + col.r = std::min(std::max(0, (int)scaled[0]), 65535); + col.g = std::min(std::max(0, (int)scaled[1]), 65535); + col.b = std::min(std::max(0, (int)scaled[2]), 65535); } break; case XE_scRGB_alpha: { LColorf scaled = value * 8192.0f + 4096.5f; - col.r = min(max(0, (int)scaled[0]), 65535); - col.g = min(max(0, (int)scaled[1]), 65535); - col.b = min(max(0, (int)scaled[2]), 65535); - alpha_row(y)[x] = min(max(0, (int)(value[3] * 65535 + 0.5f)), 65535); + col.r = std::min(std::max(0, (int)scaled[0]), 65535); + col.g = std::min(std::max(0, (int)scaled[1]), 65535); + col.b = std::min(std::max(0, (int)scaled[2]), 65535); + alpha_row(y)[x] = std::min(std::max(0, (int)(value[3] * 65535 + 0.5f)), 65535); } break; } @@ -1120,7 +1120,7 @@ get_alpha_array() const { INLINE xel *PNMImage:: take_array() { xel *array = _array; - _array = NULL; + _array = nullptr; return array; } @@ -1133,7 +1133,7 @@ take_array() { INLINE xelval *PNMImage:: take_alpha_array() { xelval *alpha = _alpha; - _alpha = NULL; + _alpha = nullptr; return alpha; } @@ -1159,7 +1159,7 @@ allocate_alpha() { */ INLINE xel *PNMImage:: row(int y) const { - nassertr(y >= 0 && y < _y_size, NULL); + nassertr(y >= 0 && y < _y_size, nullptr); return _array + y * _x_size; } @@ -1169,7 +1169,7 @@ row(int y) const { */ INLINE xelval *PNMImage:: alpha_row(int y) const { - nassertr(_alpha != NULL && y >= 0 && y < _y_size, NULL); + nassertr(_alpha != nullptr && y >= 0 && y < _y_size, nullptr); return _alpha + y * _x_size; } @@ -1210,14 +1210,14 @@ setup_sub_image(const PNMImage ©, int &xto, int &yto, yto = 0; } - x_size = min(x_size, copy.get_x_size() - xfrom); - y_size = min(y_size, copy.get_y_size() - yfrom); + x_size = std::min(x_size, copy.get_x_size() - xfrom); + y_size = std::min(y_size, copy.get_y_size() - yfrom); xmin = xto; ymin = yto; - xmax = min(xmin + x_size, get_x_size()); - ymax = min(ymin + y_size, get_y_size()); + xmax = std::min(xmin + x_size, get_x_size()); + ymax = std::min(ymin + y_size, get_y_size()); } /** diff --git a/panda/src/pnmimage/pnmImage.cxx b/panda/src/pnmimage/pnmImage.cxx index 3e3829ac52..9c6c3a68d9 100644 --- a/panda/src/pnmimage/pnmImage.cxx +++ b/panda/src/pnmimage/pnmImage.cxx @@ -21,13 +21,16 @@ #include "stackedPerlinNoise2.h" #include +using std::max; +using std::min; + /** * */ PNMImage:: PNMImage(const Filename &filename, PNMFileType *type) { - _array = NULL; - _alpha = NULL; + _array = nullptr; + _alpha = nullptr; _has_read_size = false; bool result = read(filename, type); @@ -43,13 +46,13 @@ PNMImage(const Filename &filename, PNMFileType *type) { */ void PNMImage:: clear() { - if (_array != (xel *)NULL) { + if (_array != nullptr) { PANDA_FREE_ARRAY(_array); - _array = (xel *)NULL; + _array = nullptr; } - if (_alpha != (xelval *)NULL) { + if (_alpha != nullptr) { PANDA_FREE_ARRAY(_alpha); - _alpha = (xelval *)NULL; + _alpha = nullptr; } _x_size = 0; _y_size = 0; @@ -58,7 +61,7 @@ clear() { _inv_maxval = 1.0 / 255.0; _color_space = CS_linear; _comment.clear(); - _type = (PNMFileType *)NULL; + _type = nullptr; _has_read_size = false; _xel_encoding = XE_generic; } @@ -226,10 +229,10 @@ take_from(PNMImage &orig) { if (has_alpha()) { _alpha = orig._alpha; - orig._alpha = NULL; + orig._alpha = nullptr; } _array = orig._array; - orig._array = NULL; + orig._array = nullptr; orig.clear(); } @@ -274,7 +277,7 @@ alpha_fill_val(xelval alpha) { bool PNMImage:: read(const Filename &filename, PNMFileType *type, bool report_unknown_type) { PNMReader *reader = make_reader(filename, type, report_unknown_type); - if (reader == (PNMReader *)NULL) { + if (reader == nullptr) { clear(); return false; } @@ -295,11 +298,11 @@ read(const Filename &filename, PNMFileType *type, bool report_unknown_type) { * Returns true if successful, false on error. */ bool PNMImage:: -read(istream &data, const string &filename, PNMFileType *type, +read(std::istream &data, const std::string &filename, PNMFileType *type, bool report_unknown_type) { PNMReader *reader = PNMImageHeader::make_reader - (&data, false, filename, string(), type, report_unknown_type); - if (reader == (PNMReader *)NULL) { + (&data, false, filename, std::string(), type, report_unknown_type); + if (reader == nullptr) { clear(); return false; } @@ -322,7 +325,7 @@ read(PNMReader *reader) { clear(); - if (reader == NULL) { + if (reader == nullptr) { return false; } @@ -385,7 +388,7 @@ write(const Filename &filename, PNMFileType *type) const { } PNMWriter *writer = PNMImageHeader::make_writer(filename, type); - if (writer == (PNMWriter *)NULL) { + if (writer == nullptr) { return false; } @@ -402,14 +405,14 @@ write(const Filename &filename, PNMFileType *type) const { * write. */ bool PNMImage:: -write(ostream &data, const string &filename, PNMFileType *type) const { +write(std::ostream &data, const std::string &filename, PNMFileType *type) const { if (!is_valid()) { return false; } PNMWriter *writer = PNMImageHeader::make_writer (&data, false, filename, type); - if (writer == (PNMWriter *)NULL) { + if (writer == nullptr) { return false; } @@ -425,7 +428,7 @@ write(ostream &data, const string &filename, PNMFileType *type) const { */ bool PNMImage:: write(PNMWriter *writer) const { - if (writer == NULL) { + if (writer == nullptr) { return false; } @@ -497,9 +500,9 @@ set_color_type(PNMImage::ColorType color_type) { if (has_alpha() && !has_alpha(color_type)) { // Discard the alpha channel - if (_alpha != NULL) { + if (_alpha != nullptr) { PANDA_FREE_ARRAY(_alpha); - _alpha = NULL; + _alpha = nullptr; } } else if (!has_alpha() && has_alpha(color_type)) { @@ -535,7 +538,7 @@ set_color_space(ColorSpace color_space) { return; } - if (_array != NULL) { + if (_array != nullptr) { size_t array_size = _x_size * _y_size; // Note: only convert RGB, since alpha channel is always linear. @@ -680,7 +683,7 @@ unpremultiply_alpha() { */ void PNMImage:: reverse_rows() { - if (_array != NULL) { + if (_array != nullptr) { xel *new_array = (xel *)PANDA_MALLOC_ARRAY(_x_size * _y_size * sizeof(xel)); for (int y = 0; y < _y_size; y++) { int new_y = _y_size - 1 - y; @@ -690,7 +693,7 @@ reverse_rows() { _array = new_array; } - if (_alpha != NULL) { + if (_alpha != nullptr) { xelval *new_alpha = (xelval *)PANDA_MALLOC_ARRAY(_x_size * _y_size * sizeof(xelval)); for (int y = 0; y < _y_size; y++) { int new_y = _y_size - 1 - y; @@ -712,7 +715,7 @@ void PNMImage:: flip(bool flip_x, bool flip_y, bool transpose) { if (transpose) { // Transposed case. X becomes Y, Y becomes X. - if (_array != NULL) { + if (_array != nullptr) { xel *new_array = (xel *)PANDA_MALLOC_ARRAY(_x_size * _y_size * sizeof(xel)); for (int xi = 0; xi < _x_size; ++xi) { xel *row = new_array + xi * _y_size; @@ -727,7 +730,7 @@ flip(bool flip_x, bool flip_y, bool transpose) { _array = new_array; } - if (_alpha != NULL) { + if (_alpha != nullptr) { xelval *new_alpha = (xelval *)PANDA_MALLOC_ARRAY(_x_size * _y_size * sizeof(xelval)); for (int xi = 0; xi < _x_size; ++xi) { xelval *row = new_alpha + xi * _y_size; @@ -749,7 +752,7 @@ flip(bool flip_x, bool flip_y, bool transpose) { } else { // Non-transposed. X is X, Y is Y. - if (_array != NULL) { + if (_array != nullptr) { xel *new_array = (xel *)PANDA_MALLOC_ARRAY(_x_size * _y_size * sizeof(xel)); for (int yi = 0; yi < _y_size; ++yi) { xel *row = new_array + yi * _x_size; @@ -765,7 +768,7 @@ flip(bool flip_x, bool flip_y, bool transpose) { _array = new_array; } - if (_alpha != NULL) { + if (_alpha != nullptr) { xelval *new_alpha = (xelval *)PANDA_MALLOC_ARRAY(_x_size * _y_size * sizeof(xelval)); for (int yi = 0; yi < _y_size; ++yi) { xelval *row = new_alpha + yi * _x_size; @@ -984,7 +987,7 @@ set_pixel(int x, int y, const PixelSpec &pixel) { xel p; PPM_ASSIGN(p, pixel._red, pixel._green, pixel._blue); set_xel_val(x, y, p); - if (_alpha != NULL) { + if (_alpha != nullptr) { set_alpha_val(x, y, pixel._alpha); } } @@ -1016,9 +1019,9 @@ blend(int x, int y, float r, float g, float b, float alpha) { } else { // Blend the color with the previous color. LRGBColorf prev_rgb = get_xel(x, y); - r = r + (1.0f - alpha) * (get_red(x, y) - r); - g = g + (1.0f - alpha) * (get_green(x, y) - g); - b = b + (1.0f - alpha) * (get_blue(x, y) - b); + r = r + (1.0f - alpha) * (prev_rgb[0] - r); + g = g + (1.0f - alpha) * (prev_rgb[1] - g); + b = b + (1.0f - alpha) * (prev_rgb[2] - b); alpha = prev_alpha + alpha * (1.0f - prev_alpha); if (has_alpha()) { @@ -1039,7 +1042,7 @@ blend(int x, int y, float r, float g, float b, float alpha) { */ void PNMImage:: set_array(xel *array) { - if (_array != (xel *)NULL) { + if (_array != nullptr) { PANDA_FREE_ARRAY(_array); } _array = array; @@ -1055,7 +1058,7 @@ set_array(xel *array) { */ void PNMImage:: set_alpha_array(xelval *alpha) { - if (_alpha != (xelval *)NULL) { + if (_alpha != nullptr) { PANDA_FREE_ARRAY(_alpha); } _alpha = alpha; @@ -1596,7 +1599,7 @@ threshold(const PNMImage &select_image, int channel, float threshold, void PNMImage:: fill_distance_inside(const PNMImage &mask, float threshold, int radius, bool shrink_from_border) { nassertv(radius <= PNM_MAXMAXVAL); - PNMImage dist(mask.get_x_size(), mask.get_y_size(), 1, radius, NULL, CS_linear); + PNMImage dist(mask.get_x_size(), mask.get_y_size(), 1, radius, nullptr, CS_linear); dist.fill_val(radius); xelval threshold_val = mask.to_val(threshold); @@ -1640,7 +1643,7 @@ fill_distance_inside(const PNMImage &mask, float threshold, int radius, bool shr void PNMImage:: fill_distance_outside(const PNMImage &mask, float threshold, int radius) { nassertv(radius <= PNM_MAXMAXVAL); - PNMImage dist(mask.get_x_size(), mask.get_y_size(), 1, radius, NULL, CS_linear); + PNMImage dist(mask.get_x_size(), mask.get_y_size(), 1, radius, nullptr, CS_linear); dist.fill_val(radius); xelval threshold_val = mask.to_val(threshold); @@ -1918,7 +1921,7 @@ make_histogram(PNMImage::Histogram &histogram) { pixels.push_back(PixelSpecCount((*hi).first, (*hi).second)); } } - ::sort(pixels.begin(), pixels.end()); + std::sort(pixels.begin(), pixels.end()); histogram.swap(pixels, hist_map); } @@ -2252,20 +2255,20 @@ operator ~ () const { PNMImage target (*this); size_t array_size = _x_size * _y_size; - if (_array != NULL && _alpha != NULL) { + if (_array != nullptr && _alpha != nullptr) { for (size_t i = 0; i < array_size; ++i) { target._array[i].r = _maxval - _array[i].r; target._array[i].g = _maxval - _array[i].g; target._array[i].b = _maxval - _array[i].b; target._alpha[i] = _maxval - _alpha[i]; } - } else if (_array != NULL) { + } else if (_array != nullptr) { for (size_t i = 0; i < array_size; ++i) { target._array[i].r = _maxval - _array[i].r; target._array[i].g = _maxval - _array[i].g; target._array[i].b = _maxval - _array[i].b; } - } else if (_alpha != NULL) { + } else if (_alpha != nullptr) { for (size_t i = 0; i < array_size; ++i) { target._alpha[i] = _maxval - _alpha[i]; } @@ -2288,7 +2291,7 @@ operator += (const PNMImage &other) { size_t array_size = _x_size * _y_size; // Simple case: add vals directly. - if (_alpha != NULL && other._alpha != NULL) { + if (_alpha != nullptr && other._alpha != nullptr) { for (size_t i = 0; i < array_size; ++i) { _array[i].r = clamp_val((int)_array[i].r + (int)other._array[i].r); _array[i].g = clamp_val((int)_array[i].g + (int)other._array[i].g); @@ -2329,7 +2332,7 @@ operator += (const LColorf &other) { int add_b = (int)(other.get_z() * get_maxval() + 0.5); int add_a = (int)(other.get_w() * get_maxval() + 0.5); - if (_alpha != NULL) { + if (_alpha != nullptr) { for (size_t i = 0; i < array_size; ++i) { _array[i].r = clamp_val((int)_array[i].r + add_r); _array[i].g = clamp_val((int)_array[i].g + add_g); @@ -2370,7 +2373,7 @@ operator -= (const PNMImage &other) { size_t array_size = _x_size * _y_size; // Simple case: subtract vals directly. - if (_alpha != NULL && other._alpha != NULL) { + if (_alpha != nullptr && other._alpha != nullptr) { for (size_t i = 0; i < array_size; ++i) { _array[i].r = clamp_val((int)_array[i].r - (int)other._array[i].r); _array[i].g = clamp_val((int)_array[i].g - (int)other._array[i].g); @@ -2433,7 +2436,7 @@ operator *= (float multiplier) { if (get_color_space() == CS_linear) { size_t array_size = _x_size * _y_size; - if (_alpha != NULL) { + if (_alpha != nullptr) { for (size_t i = 0; i < array_size; ++i) { _array[i].r = clamp_val((int)(_array[i].r * multiplier + 0.5f)); _array[i].g = clamp_val((int)(_array[i].g * multiplier + 0.5f)); @@ -2470,7 +2473,7 @@ operator *= (const LColorf &other) { if (get_color_space() == CS_linear) { size_t array_size = _x_size * _y_size; - if (_alpha != NULL) { + if (_alpha != nullptr) { for (size_t i = 0; i < array_size; ++i) { _array[i].r = clamp_val((int)(_array[i].r * other[0] + 0.5f)); _array[i].g = clamp_val((int)(_array[i].g * other[1] + 0.5f)); diff --git a/panda/src/pnmimage/pnmImage.h b/panda/src/pnmimage/pnmImage.h index 2f7b653185..494acb8029 100644 --- a/panda/src/pnmimage/pnmImage.h +++ b/panda/src/pnmimage/pnmImage.h @@ -58,9 +58,9 @@ class PNMFileType; class EXPCL_PANDA_PNMIMAGE PNMImage : public PNMImageHeader { PUBLISHED: INLINE PNMImage(); - explicit PNMImage(const Filename &filename, PNMFileType *type = NULL); + explicit PNMImage(const Filename &filename, PNMFileType *type = nullptr); INLINE explicit PNMImage(int x_size, int y_size, int num_channels = 3, - xelval maxval = 255, PNMFileType *type = NULL, + xelval maxval = 255, PNMFileType *type = nullptr, ColorSpace color_space = CS_linear); INLINE PNMImage(const PNMImage ©); INLINE void operator = (const PNMImage ©); @@ -75,7 +75,7 @@ PUBLISHED: void clear(); void clear(int x_size, int y_size, int num_channels = 3, - xelval maxval = 255, PNMFileType *type = NULL, + xelval maxval = 255, PNMFileType *type = nullptr, ColorSpace color_space = CS_linear); void copy_from(const PNMImage ©); @@ -100,16 +100,16 @@ PUBLISHED: INLINE int get_read_y_size() const; INLINE ColorSpace get_color_space() const; - BLOCKING bool read(const Filename &filename, PNMFileType *type = NULL, + BLOCKING bool read(const Filename &filename, PNMFileType *type = nullptr, bool report_unknown_type = true); - BLOCKING bool read(istream &data, const string &filename = string(), - PNMFileType *type = NULL, + BLOCKING bool read(std::istream &data, const std::string &filename = std::string(), + PNMFileType *type = nullptr, bool report_unknown_type = true); BLOCKING bool read(PNMReader *reader); - BLOCKING bool write(const Filename &filename, PNMFileType *type = NULL) const; - BLOCKING bool write(ostream &data, const string &filename = string(), - PNMFileType *type = NULL) const; + BLOCKING bool write(const Filename &filename, PNMFileType *type = nullptr) const; + BLOCKING bool write(std::ostream &data, const std::string &filename = std::string(), + PNMFileType *type = nullptr) const; BLOCKING bool write(PNMWriter *writer) const; INLINE bool is_valid() const; diff --git a/panda/src/pnmimage/pnmImageHeader.I b/panda/src/pnmimage/pnmImageHeader.I index fc62587986..0e4adbaf11 100644 --- a/panda/src/pnmimage/pnmImageHeader.I +++ b/panda/src/pnmimage/pnmImageHeader.I @@ -21,7 +21,7 @@ PNMImageHeader() { _num_channels = 0; _maxval = 255; _color_space = CS_unspecified; - _type = (PNMFileType *)NULL; + _type = nullptr; } /** @@ -166,7 +166,7 @@ get_size() const { /** * Gets the user comment from the file. */ -INLINE string PNMImageHeader:: +INLINE std::string PNMImageHeader:: get_comment() const { return _comment; } @@ -175,7 +175,7 @@ get_comment() const { * Writes a user comment string to the image (header). */ INLINE void PNMImageHeader:: -set_comment(const string& comment) { +set_comment(const std::string& comment) { _comment = comment; } @@ -184,7 +184,7 @@ set_comment(const string& comment) { */ INLINE bool PNMImageHeader:: has_type() const { - return _type != (PNMFileType *)NULL; + return _type != nullptr; } /** diff --git a/panda/src/pnmimage/pnmImageHeader.cxx b/panda/src/pnmimage/pnmImageHeader.cxx index a0098b58f7..c7a6129bd7 100644 --- a/panda/src/pnmimage/pnmImageHeader.cxx +++ b/panda/src/pnmimage/pnmImageHeader.cxx @@ -20,6 +20,10 @@ #include "virtualFileSystem.h" #include "zStream.h" +using std::istream; +using std::ostream; +using std::string; + /** * Opens up the image file and tries to read its header information to * determine its size, number of channels, etc. If successful, updates the @@ -29,7 +33,7 @@ bool PNMImageHeader:: read_header(const Filename &filename, PNMFileType *type, bool report_unknown_type) { PNMReader *reader = make_reader(filename, type, report_unknown_type); - if (reader != (PNMReader *)NULL) { + if (reader != nullptr) { (*this) = (*reader); delete reader; return true; @@ -55,7 +59,7 @@ read_header(istream &data, const string &filename, PNMFileType *type, bool report_unknown_type) { PNMReader *reader = PNMImageHeader::make_reader (&data, false, filename, string(), type, report_unknown_type); - if (reader != (PNMReader *)NULL) { + if (reader != nullptr) { (*this) = (*reader); delete reader; return true; @@ -80,11 +84,11 @@ make_reader(const Filename &filename, PNMFileType *type, << "Reading image from " << filename << "\n"; } bool owns_file = false; - istream *file = (istream *)NULL; + istream *file = nullptr; if (filename == "-") { owns_file = false; - file = &cin; + file = &std::cin; if (pnmimage_cat.is_debug()) { pnmimage_cat.debug() @@ -96,12 +100,12 @@ make_reader(const Filename &filename, PNMFileType *type, file = vfs->open_read_file(filename, true); } - if (file == (istream *)NULL) { + if (file == nullptr) { if (pnmimage_cat.is_debug()) { pnmimage_cat.debug() << "Unable to open file.\n"; } - return NULL; + return nullptr; } return make_reader(file, owns_file, filename, string(), type, @@ -135,7 +139,7 @@ PNMReader *PNMImageHeader:: make_reader(istream *file, bool owns_file, const Filename &filename, string magic_number, PNMFileType *type, bool report_unknown_type) const { - if (type == (PNMFileType *)NULL) { + if (type == nullptr) { if (!read_magic_number(file, magic_number, 2)) { // No magic number. No image. if (pnmimage_cat.is_debug()) { @@ -151,14 +155,14 @@ make_reader(istream *file, bool owns_file, const Filename &filename, // since vfs->close_read_file() just deletes the file pointer anyway. vfs->close_read_file(file); } - return NULL; + return nullptr; } type = PNMFileTypeRegistry::get_global_ptr()-> get_type_from_magic_number(magic_number); if (pnmimage_cat.is_debug()) { - if (type != (PNMFileType *)NULL) { + if (type != nullptr) { pnmimage_cat.debug() << "By magic number, image file appears to be type " << type->get_name() << ".\n"; @@ -169,13 +173,13 @@ make_reader(istream *file, bool owns_file, const Filename &filename, } } - if (type == (PNMFileType *)NULL && !filename.empty()) { + if (type == nullptr && !filename.empty()) { // We still don't know the type; attempt to guess it from the filename // extension. type = PNMFileTypeRegistry::get_global_ptr()->get_type_from_extension(filename); if (pnmimage_cat.is_debug()) { - if (type != (PNMFileType *)NULL) { + if (type != nullptr) { pnmimage_cat.debug() << "From its extension, image file is probably type " << type->get_name() << ".\n"; @@ -187,17 +191,17 @@ make_reader(istream *file, bool owns_file, const Filename &filename, } } - if (type == (PNMFileType *)NULL) { + if (type == nullptr) { // No? How about the default type associated with this image header. type = _type; - if (pnmimage_cat.is_debug() && type != (PNMFileType *)NULL) { + if (pnmimage_cat.is_debug() && type != nullptr) { pnmimage_cat.debug() << "Assuming image file type is " << type->get_name() << ".\n"; } } - if (type == (PNMFileType *)NULL) { + if (type == nullptr) { // We can't figure out what type the file is; give up. if (report_unknown_type && pnmimage_cat.is_error()) { pnmimage_cat.error() @@ -215,18 +219,18 @@ make_reader(istream *file, bool owns_file, const Filename &filename, // since vfs->close_read_file() just deletes the file pointer anyway. vfs->close_read_file(file); } - return NULL; + return nullptr; } PNMReader *reader = type->make_reader(file, owns_file, magic_number); - if (reader == NULL && owns_file) { + if (reader == nullptr && owns_file) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->close_read_file(file); } if (!reader->is_valid()) { delete reader; - reader = NULL; + reader = nullptr; } return reader; @@ -247,11 +251,11 @@ make_writer(const Filename &filename, PNMFileType *type) const { << "Writing image to " << filename << "\n"; } bool owns_file = false; - ostream *file = (ostream *)NULL; + ostream *file = nullptr; if (filename == "-") { owns_file = false; - file = &cout; + file = &std::cout; if (pnmimage_cat.is_debug()) { pnmimage_cat.debug() @@ -262,17 +266,17 @@ make_writer(const Filename &filename, PNMFileType *type) const { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); Filename actual_name = Filename::binary_filename(filename); file = vfs->open_write_file(actual_name, true, true); - if (file != NULL) { + if (file != nullptr) { owns_file = true; } } - if (file == (ostream *)NULL) { + if (file == nullptr) { if (pnmimage_cat.is_debug()) { pnmimage_cat.debug() << "Unable to write to file.\n"; } - return NULL; + return nullptr; } return make_writer(file, owns_file, filename, type); @@ -299,13 +303,13 @@ make_writer(const Filename &filename, PNMFileType *type) const { PNMWriter *PNMImageHeader:: make_writer(ostream *file, bool owns_file, const Filename &filename, PNMFileType *type) const { - if (type == (PNMFileType *)NULL && !filename.empty()) { + if (type == nullptr && !filename.empty()) { // We don't know the type; attempt to guess it from the filename // extension. type = PNMFileTypeRegistry::get_global_ptr()->get_type_from_extension(filename); if (pnmimage_cat.is_debug()) { - if (type != (PNMFileType *)NULL) { + if (type != nullptr) { pnmimage_cat.debug() << "From its extension, image file is intended to be type " << type->get_name() << ".\n"; @@ -316,17 +320,17 @@ make_writer(ostream *file, bool owns_file, const Filename &filename, } } - if (type == (PNMFileType *)NULL) { + if (type == nullptr) { // No? How about the default type associated with this image header. type = _type; - if (pnmimage_cat.is_debug() && type != (PNMFileType *)NULL) { + if (pnmimage_cat.is_debug() && type != nullptr) { pnmimage_cat.debug() << "Assuming image file type is " << type->get_name() << ".\n"; } } - if (type == (PNMFileType *)NULL) { + if (type == nullptr) { // We can't figure out what type the file is; give up. if (pnmimage_cat.is_debug()) { pnmimage_cat.debug() @@ -335,17 +339,17 @@ make_writer(ostream *file, bool owns_file, const Filename &filename, if (owns_file) { delete file; } - return NULL; + return nullptr; } PNMWriter *writer = type->make_writer(file, owns_file); - if (writer == NULL && owns_file) { + if (writer == nullptr && owns_file) { delete file; } - if (writer != NULL && !writer->is_valid()) { + if (writer != nullptr && !writer->is_valid()) { delete writer; - writer = NULL; + writer = nullptr; } return writer; diff --git a/panda/src/pnmimage/pnmImageHeader.h b/panda/src/pnmimage/pnmImageHeader.h index 1132bed14f..162dd21784 100644 --- a/panda/src/pnmimage/pnmImageHeader.h +++ b/panda/src/pnmimage/pnmImageHeader.h @@ -75,8 +75,8 @@ PUBLISHED: INLINE LVecBase2i get_size() const; MAKE_PROPERTY(size, get_size); - INLINE string get_comment() const; - INLINE void set_comment(const string &comment); + INLINE std::string get_comment() const; + INLINE void set_comment(const std::string &comment); MAKE_PROPERTY(comment, get_comment, set_comment); INLINE bool has_type() const; @@ -84,30 +84,30 @@ PUBLISHED: INLINE void set_type(PNMFileType *type); MAKE_PROPERTY2(type, has_type, get_type); - BLOCKING bool read_header(const Filename &filename, PNMFileType *type = NULL, + BLOCKING bool read_header(const Filename &filename, PNMFileType *type = nullptr, bool report_unknown_type = true); - BLOCKING bool read_header(istream &data, const string &filename = string(), - PNMFileType *type = NULL, bool report_unknown_type = true); + BLOCKING bool read_header(std::istream &data, const std::string &filename = std::string(), + PNMFileType *type = nullptr, bool report_unknown_type = true); PNMReader *make_reader(const Filename &filename, - PNMFileType *type = NULL, + PNMFileType *type = nullptr, bool report_unknown_type = true) const; - PNMReader *make_reader(istream *file, bool owns_file = true, + PNMReader *make_reader(std::istream *file, bool owns_file = true, const Filename &filename = Filename(), - string magic_number = string(), - PNMFileType *type = NULL, + std::string magic_number = std::string(), + PNMFileType *type = nullptr, bool report_unknown_type = true) const; PNMWriter *make_writer(const Filename &filename, - PNMFileType *type = NULL) const; - PNMWriter *make_writer(ostream *file, bool owns_file = true, + PNMFileType *type = nullptr) const; + PNMWriter *make_writer(std::ostream *file, bool owns_file = true, const Filename &filename = Filename(), - PNMFileType *type = NULL) const; + PNMFileType *type = nullptr) const; - static bool read_magic_number(istream *file, string &magic_number, + static bool read_magic_number(std::istream *file, std::string &magic_number, int num_bytes); - void output(ostream &out) const; + void output(std::ostream &out) const; // Contains a single pixel specification used in compute_histogram() and // make_histogram(). Note that pixels are stored by integer value, not by @@ -141,7 +141,7 @@ PUBLISHED: INLINE xelval operator [](int n) const; INLINE static int size(); - void output(ostream &out) const; + void output(std::ostream &out) const; public: xelval _red, _green, _blue, _alpha; @@ -173,7 +173,7 @@ PUBLISHED: INLINE int get_count(const PixelSpec &pixel) const; MAKE_SEQ(get_pixels, get_num_pixels, get_pixel); - void write(ostream &out) const; + void write(std::ostream &out) const; public: INLINE void swap(PixelCount &pixels, HistMap &hist_map); @@ -194,16 +194,16 @@ protected: int _num_channels; xelval _maxval; ColorSpace _color_space; - string _comment; + std::string _comment; PNMFileType *_type; }; -INLINE ostream &operator << (ostream &out, const PNMImageHeader &header) { +INLINE std::ostream &operator << (std::ostream &out, const PNMImageHeader &header) { header.output(out); return out; } -INLINE ostream &operator << (ostream &out, const PNMImageHeader::PixelSpec &pixel) { +INLINE std::ostream &operator << (std::ostream &out, const PNMImageHeader::PixelSpec &pixel) { pixel.output(out); return out; } diff --git a/panda/src/pnmimage/pnmReader.I b/panda/src/pnmimage/pnmReader.I index 3e1f5d8fff..b066a2d7c3 100644 --- a/panda/src/pnmimage/pnmReader.I +++ b/panda/src/pnmimage/pnmReader.I @@ -15,7 +15,7 @@ * */ INLINE PNMReader:: -PNMReader(PNMFileType *type, istream *file, bool owns_file) : +PNMReader(PNMFileType *type, std::istream *file, bool owns_file) : _type(type), _owns_file(owns_file), _file(file), diff --git a/panda/src/pnmimage/pnmReader.cxx b/panda/src/pnmimage/pnmReader.cxx index 9f6c3bc2c9..938648e0a1 100644 --- a/panda/src/pnmimage/pnmReader.cxx +++ b/panda/src/pnmimage/pnmReader.cxx @@ -29,7 +29,7 @@ PNMReader:: // vfs->close_read_file() just deletes the file pointer anyway. vfs->close_read_file(_file); } - _file = (istream *)NULL; + _file = nullptr; } /** @@ -249,7 +249,7 @@ get_reduction_shift(int orig_size, int new_size) { return 0; } - int reduction = max(orig_size / new_size, 1); + int reduction = std::max(orig_size / new_size, 1); int shift = 0; diff --git a/panda/src/pnmimage/pnmReader.h b/panda/src/pnmimage/pnmReader.h index 833c531f29..14355ec43c 100644 --- a/panda/src/pnmimage/pnmReader.h +++ b/panda/src/pnmimage/pnmReader.h @@ -26,7 +26,7 @@ class PfmFile; */ class EXPCL_PANDA_PNMIMAGE PNMReader : public PNMImageHeader { protected: - INLINE PNMReader(PNMFileType *type, istream *file, bool owns_file); + INLINE PNMReader(PNMFileType *type, std::istream *file, bool owns_file); public: virtual ~PNMReader(); @@ -51,7 +51,7 @@ private: protected: PNMFileType *_type; bool _owns_file; - istream *_file; + std::istream *_file; bool _is_valid; int _read_x_size, _read_y_size; diff --git a/panda/src/pnmimage/pnmWriter.I b/panda/src/pnmimage/pnmWriter.I index f9686a5c44..fbc64f6b5f 100644 --- a/panda/src/pnmimage/pnmWriter.I +++ b/panda/src/pnmimage/pnmWriter.I @@ -15,7 +15,7 @@ * */ INLINE PNMWriter:: -PNMWriter(PNMFileType *type, ostream *file, bool owns_file) : +PNMWriter(PNMFileType *type, std::ostream *file, bool owns_file) : _type(type), _owns_file(owns_file), _file(file), diff --git a/panda/src/pnmimage/pnmWriter.cxx b/panda/src/pnmimage/pnmWriter.cxx index 0115f261aa..936608e69e 100644 --- a/panda/src/pnmimage/pnmWriter.cxx +++ b/panda/src/pnmimage/pnmWriter.cxx @@ -22,7 +22,7 @@ PNMWriter:: if (_owns_file) { delete _file; } - _file = (ostream *)NULL; + _file = nullptr; } /** diff --git a/panda/src/pnmimage/pnmWriter.h b/panda/src/pnmimage/pnmWriter.h index 062b89602f..1da578124e 100644 --- a/panda/src/pnmimage/pnmWriter.h +++ b/panda/src/pnmimage/pnmWriter.h @@ -26,7 +26,7 @@ class PfmFile; */ class EXPCL_PANDA_PNMIMAGE PNMWriter : public PNMImageHeader { protected: - INLINE PNMWriter(PNMFileType *type, ostream *file, bool owns_file); + INLINE PNMWriter(PNMFileType *type, std::ostream *file, bool owns_file); public: @@ -62,7 +62,7 @@ public: protected: PNMFileType *_type; bool _owns_file; - ostream *_file; + std::ostream *_file; bool _is_valid; }; diff --git a/panda/src/pnmimage/pnmbitio.cxx b/panda/src/pnmimage/pnmbitio.cxx index ec44d05d44..fbd9bff5d4 100644 --- a/panda/src/pnmimage/pnmbitio.cxx +++ b/panda/src/pnmimage/pnmbitio.cxx @@ -15,6 +15,10 @@ #include "pnmbitio.h" #include + +using std::istream; +using std::ostream; + struct bitstream { istream *inf; @@ -48,7 +52,7 @@ struct bitstream EXPCL_PANDA_PNMIMAGE struct bitstream * pm_bitinit(istream *f, const char *mode) { - struct bitstream *ans = (struct bitstream *)0; + struct bitstream *ans = nullptr; if(!f || !mode || !*mode) return ans; @@ -68,7 +72,7 @@ pm_bitinit(istream *f, const char *mode) EXPCL_PANDA_PNMIMAGE struct bitstream * pm_bitinit(ostream *f, const char *mode) { - struct bitstream *ans = (struct bitstream *)0; + struct bitstream *ans = nullptr; if(!f || !mode || !*mode) return ans; diff --git a/panda/src/pnmimage/pnmbitio.h b/panda/src/pnmimage/pnmbitio.h index 4213d221b8..464b48617c 100644 --- a/panda/src/pnmimage/pnmbitio.h +++ b/panda/src/pnmimage/pnmbitio.h @@ -30,8 +30,8 @@ typedef struct bitstream *BITSTREAM; * Returns 0 on error. */ -extern EXPCL_PANDA_PNMIMAGE BITSTREAM pm_bitinit(istream *f, const char *mode); -extern EXPCL_PANDA_PNMIMAGE BITSTREAM pm_bitinit(ostream *f, const char *mode); +extern EXPCL_PANDA_PNMIMAGE BITSTREAM pm_bitinit(std::istream *f, const char *mode); +extern EXPCL_PANDA_PNMIMAGE BITSTREAM pm_bitinit(std::ostream *f, const char *mode); /* * pm_bitfini() - deallocate the given BITSTREAM. diff --git a/panda/src/pnmimage/pnmimage_base.cxx b/panda/src/pnmimage/pnmimage_base.cxx index 075b45dcd2..0fb9bedfc6 100644 --- a/panda/src/pnmimage/pnmimage_base.cxx +++ b/panda/src/pnmimage/pnmimage_base.cxx @@ -19,6 +19,9 @@ #include #include // for sprintf() +using std::istream; +using std::ostream; + /** * Outputs the given printf-style message to the user and returns. diff --git a/panda/src/pnmimage/pnmimage_base.h b/panda/src/pnmimage/pnmimage_base.h index e9c36416cc..ca1f356c48 100644 --- a/panda/src/pnmimage/pnmimage_base.h +++ b/panda/src/pnmimage/pnmimage_base.h @@ -40,7 +40,7 @@ typedef unsigned char gray; struct pixel { PUBLISHED: - pixel() { } + pixel() = default; pixel(gray fill) : r(fill), g(fill), b(fill) { } pixel(gray r, gray g, gray b) : r(r), g(g), b(b) { } @@ -61,7 +61,7 @@ PUBLISHED: #ifdef HAVE_PYTHON static int size() { return 3; } - void output(ostream &out) { + void output(std::ostream &out) { out << "pixel(r=" << r << ", g=" << g << ", b=" << b << ")"; } #endif @@ -105,14 +105,14 @@ EXPCL_PANDA_PNMIMAGE int pm_bitstomaxval(int bits); EXPCL_PANDA_PNMIMAGE char *pm_allocrow(int cols, int size); EXPCL_PANDA_PNMIMAGE void pm_freerow(char *itrow); -EXPCL_PANDA_PNMIMAGE int pm_readbigshort(istream *in, short *sP); -EXPCL_PANDA_PNMIMAGE int pm_writebigshort(ostream *out, short s); -EXPCL_PANDA_PNMIMAGE int pm_readbiglong(istream *in, long *lP); -EXPCL_PANDA_PNMIMAGE int pm_writebiglong(ostream *out, long l); -EXPCL_PANDA_PNMIMAGE int pm_readlittleshort(istream *in, short *sP); -EXPCL_PANDA_PNMIMAGE int pm_writelittleshort(ostream *out, short s); -EXPCL_PANDA_PNMIMAGE int pm_readlittlelong(istream *in, long *lP); -EXPCL_PANDA_PNMIMAGE int pm_writelittlelong(ostream *out, long l); +EXPCL_PANDA_PNMIMAGE int pm_readbigshort(std::istream *in, short *sP); +EXPCL_PANDA_PNMIMAGE int pm_writebigshort(std::ostream *out, short s); +EXPCL_PANDA_PNMIMAGE int pm_readbiglong(std::istream *in, long *lP); +EXPCL_PANDA_PNMIMAGE int pm_writebiglong(std::ostream *out, long l); +EXPCL_PANDA_PNMIMAGE int pm_readlittleshort(std::istream *in, short *sP); +EXPCL_PANDA_PNMIMAGE int pm_writelittleshort(std::ostream *out, short s); +EXPCL_PANDA_PNMIMAGE int pm_readlittlelong(std::istream *in, long *lP); +EXPCL_PANDA_PNMIMAGE int pm_writelittlelong(std::ostream *out, long l); // These ratios are used to compute the brightness of a colored pixel; they diff --git a/panda/src/pnmimage/ppmcmap.cxx b/panda/src/pnmimage/ppmcmap.cxx index c061bfbde5..48de568d68 100644 --- a/panda/src/pnmimage/ppmcmap.cxx +++ b/panda/src/pnmimage/ppmcmap.cxx @@ -31,8 +31,8 @@ ppm_computecolorhist(pixel** pixels, colorhist_vector chv; cht = ppm_computecolorhash( pixels, cols, rows, maxcolors, colorsP ); - if ( cht == (colorhash_table) 0 ) - return (colorhist_vector) 0; + if ( cht == nullptr ) + return nullptr; chv = ppm_colorhashtocolorhist( cht, maxcolors ); ppm_freecolorhash( cht ); return chv; @@ -95,20 +95,20 @@ ppm_computecolorhash(pixel** pixels, for ( col = 0, pP = pixels[row]; col < cols; ++col, ++pP ) { hash = ppm_hashpixel( *pP ); - for ( chl = cht[hash]; chl != (colorhist_list) 0; chl = chl->next ) + for ( chl = cht[hash]; chl != nullptr; chl = chl->next ) if ( PPM_EQUAL( chl->ch.color, *pP ) ) break; - if ( chl != (colorhist_list) 0 ) + if ( chl != nullptr ) ++(chl->ch.value); else { if ( ++(*colorsP) > maxcolors ) { ppm_freecolorhash( cht ); - return (colorhash_table) 0; + return nullptr; } chl = (colorhist_list) malloc( sizeof(struct colorhist_list_item) ); - if ( chl == 0 ) + if ( chl == nullptr ) pm_error( "out of memory computing hash table" ); chl->ch.color = *pP; chl->ch.value = 1; @@ -127,11 +127,11 @@ ppm_alloccolorhash( ) int i; cht = (colorhash_table) malloc( HASH_SIZE * sizeof(colorhist_list) ); - if ( cht == 0 ) + if ( cht == nullptr ) pm_error( "out of memory allocating hash table" ); for ( i = 0; i < HASH_SIZE; ++i ) - cht[i] = (colorhist_list) 0; + cht[i] = nullptr; return cht; } @@ -145,7 +145,7 @@ ppm_addtocolorhash(colorhash_table cht, colorhist_list chl; chl = (colorhist_list) malloc( sizeof(struct colorhist_list_item) ); - if ( chl == 0 ) + if ( chl == nullptr ) return -1; hash = ppm_hashpixel( *colorP ); chl->ch.color = *colorP; @@ -166,13 +166,13 @@ ppm_colorhashtocolorhist(colorhash_table cht, /* Now collate the hash table into a simple colorhist array. */ chv = (colorhist_vector) malloc( maxcolors * sizeof(struct colorhist_item) ); /* (Leave room for expansion by caller.) */ - if ( chv == (colorhist_vector) 0 ) + if ( chv == nullptr ) pm_error( "out of memory generating histogram" ); /* Loop through the hash table. */ j = 0; for ( i = 0; i < HASH_SIZE; ++i ) - for ( chl = cht[i]; chl != (colorhist_list) 0; chl = chl->next ) + for ( chl = cht[i]; chl != nullptr; chl = chl->next ) { /* Add the new entry. */ chv[j] = chl->ch; @@ -198,13 +198,13 @@ ppm_colorhisttocolorhash(colorhist_vector chv, { color = chv[i].color; hash = ppm_hashpixel( color ); - for ( chl = cht[hash]; chl != (colorhist_list) 0; chl = chl->next ) + for ( chl = cht[hash]; chl != nullptr; chl = chl->next ) if ( PPM_EQUAL( chl->ch.color, color ) ) pm_error( "same color found twice - %d %d %d", PPM_GETR(color), PPM_GETG(color), PPM_GETB(color) ); chl = (colorhist_list) malloc( sizeof(struct colorhist_list_item) ); - if ( chl == (colorhist_list) 0 ) + if ( chl == nullptr ) pm_error( "out of memory" ); chl->ch.color = color; chl->ch.value = i; @@ -223,7 +223,7 @@ ppm_lookupcolor(colorhash_table cht, colorhist_list chl; hash = ppm_hashpixel( *colorP ); - for ( chl = cht[hash]; chl != (colorhist_list) 0; chl = chl->next ) + for ( chl = cht[hash]; chl != nullptr; chl = chl->next ) if ( PPM_EQUAL( chl->ch.color, *colorP ) ) return chl->ch.value; @@ -243,7 +243,7 @@ ppm_freecolorhash(colorhash_table cht) colorhist_list chl, chlnext; for ( i = 0; i < HASH_SIZE; ++i ) - for ( chl = cht[i]; chl != (colorhist_list) 0; chl = chlnext ) + for ( chl = cht[i]; chl != nullptr; chl = chlnext ) { chlnext = chl->next; free( (char*) chl ); diff --git a/panda/src/pnmimage/ppmcmap.h b/panda/src/pnmimage/ppmcmap.h index f8b9966818..5466de04e7 100644 --- a/panda/src/pnmimage/ppmcmap.h +++ b/panda/src/pnmimage/ppmcmap.h @@ -26,7 +26,7 @@ struct colorhist_list_item EXPCL_PANDA_PNMIMAGE colorhist_vector ppm_computecolorhist( pixel** pixels, int cols, int rows, int maxcolors, int* colorsP ); /* Returns a colorhist *colorsP long (with space allocated for maxcolors. */ -void ppm_addtocolorhist ( colorhist_vector chv, int* colorsP, int maxcolors, pixel* colorP, int value, int position ); +EXPCL_PANDA_PNMIMAGE void ppm_addtocolorhist ( colorhist_vector chv, int* colorsP, int maxcolors, pixel* colorP, int value, int position ); EXPCL_PANDA_PNMIMAGE void ppm_freecolorhist( colorhist_vector chv ); @@ -35,19 +35,19 @@ EXPCL_PANDA_PNMIMAGE void ppm_freecolorhist( colorhist_vector chv ); typedef colorhist_list* colorhash_table; -colorhash_table ppm_computecolorhash ( pixel** pixels, int cols, int rows, int maxcolors, int* colorsP ); +EXPCL_PANDA_PNMIMAGE colorhash_table ppm_computecolorhash ( pixel** pixels, int cols, int rows, int maxcolors, int* colorsP ); EXPCL_PANDA_PNMIMAGE int ppm_lookupcolor( colorhash_table cht, pixel* colorP ); -colorhist_vector ppm_colorhashtocolorhist ( colorhash_table cht, int maxcolors ); +EXPCL_PANDA_PNMIMAGE colorhist_vector ppm_colorhashtocolorhist ( colorhash_table cht, int maxcolors ); EXPCL_PANDA_PNMIMAGE colorhash_table ppm_colorhisttocolorhash( colorhist_vector chv, int colors ); -int ppm_addtocolorhash ( colorhash_table cht, pixel* colorP, int value ); +EXPCL_PANDA_PNMIMAGE int ppm_addtocolorhash ( colorhash_table cht, pixel* colorP, int value ); /* Returns -1 on failure. */ -colorhash_table ppm_alloccolorhash ( void ); +EXPCL_PANDA_PNMIMAGE colorhash_table ppm_alloccolorhash ( void ); -void ppm_freecolorhash( colorhash_table cht ); +EXPCL_PANDA_PNMIMAGE void ppm_freecolorhash( colorhash_table cht ); #endif diff --git a/panda/src/pnmimagetypes/config_pnmimagetypes.cxx b/panda/src/pnmimagetypes/config_pnmimagetypes.cxx index b115aa5213..551c351c43 100644 --- a/panda/src/pnmimagetypes/config_pnmimagetypes.cxx +++ b/panda/src/pnmimagetypes/config_pnmimagetypes.cxx @@ -36,6 +36,10 @@ #error Buildsystem error: BUILDING_PANDA_PNMIMAGETYPES not defined #endif +using std::istream; +using std::ostream; +using std::string; + Configure(config_pnmimagetypes); NotifyCategoryDefName(pnmimage_sgi, "sgi", pnmimage_cat); NotifyCategoryDefName(pnmimage_tga, "tga", pnmimage_cat); @@ -269,6 +273,7 @@ init_libpnmimagetypes() { // And register with the PandaSystem. PandaSystem *ps = PandaSystem::get_global_ptr(); + (void)ps; // Suppress unused variable warning #ifdef HAVE_JPEG ps->add_system("libjpeg"); diff --git a/panda/src/pnmimagetypes/config_pnmimagetypes.h b/panda/src/pnmimagetypes/config_pnmimagetypes.h index 95ed9224a5..75fb491143 100644 --- a/panda/src/pnmimagetypes/config_pnmimagetypes.h +++ b/panda/src/pnmimagetypes/config_pnmimagetypes.h @@ -46,8 +46,8 @@ enum SGIStorageType { SST_verbatim = STORAGE_VERBATIM, }; -EXPCL_PANDA_PNMIMAGETYPES ostream &operator << (ostream &out, SGIStorageType sst); -EXPCL_PANDA_PNMIMAGETYPES istream &operator >> (istream &in, SGIStorageType &sst); +EXPCL_PANDA_PNMIMAGETYPES std::ostream &operator << (std::ostream &out, SGIStorageType sst); +EXPCL_PANDA_PNMIMAGETYPES std::istream &operator >> (std::istream &in, SGIStorageType &sst); extern ConfigVariableEnum sgi_storage_type; extern ConfigVariableString sgi_imagename; @@ -68,8 +68,8 @@ enum IMGHeaderType { IHT_long, }; -EXPCL_PANDA_PNMIMAGETYPES ostream &operator << (ostream &out, IMGHeaderType iht); -EXPCL_PANDA_PNMIMAGETYPES istream &operator >> (istream &in, IMGHeaderType &iht); +EXPCL_PANDA_PNMIMAGETYPES std::ostream &operator << (std::ostream &out, IMGHeaderType iht); +EXPCL_PANDA_PNMIMAGETYPES std::istream &operator >> (std::istream &in, IMGHeaderType &iht); extern ConfigVariableEnum img_header_type; extern ConfigVariableInt img_size; diff --git a/panda/src/pnmimagetypes/pnmFileTypeBMP.cxx b/panda/src/pnmimagetypes/pnmFileTypeBMP.cxx index 9ff4240ecf..688275edf7 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeBMP.cxx +++ b/panda/src/pnmimagetypes/pnmFileTypeBMP.cxx @@ -20,6 +20,8 @@ #include "pnmFileTypeRegistry.h" #include "bamReader.h" +using std::string; + static const char * const extensions_bmp[] = { "bmp" }; @@ -96,7 +98,7 @@ matches_magic_number(const string &magic_number) const { * returns NULL. */ PNMReader *PNMFileTypeBMP:: -make_reader(istream *file, bool owns_file, const string &magic_number) { +make_reader(std::istream *file, bool owns_file, const string &magic_number) { init_pnm(); return new Reader(this, file, owns_file, magic_number); } @@ -107,7 +109,7 @@ make_reader(istream *file, bool owns_file, const string &magic_number) { * NULL. */ PNMWriter *PNMFileTypeBMP:: -make_writer(ostream *file, bool owns_file) { +make_writer(std::ostream *file, bool owns_file) { init_pnm(); return new Writer(this, file, owns_file); } diff --git a/panda/src/pnmimagetypes/pnmFileTypeBMP.h b/panda/src/pnmimagetypes/pnmFileTypeBMP.h index 731fc06477..6cd3e8e32f 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeBMP.h +++ b/panda/src/pnmimagetypes/pnmFileTypeBMP.h @@ -29,23 +29,23 @@ class EXPCL_PANDA_PNMIMAGETYPES PNMFileTypeBMP : public PNMFileType { public: PNMFileTypeBMP(); - virtual string get_name() const; + virtual std::string get_name() const; virtual int get_num_extensions() const; - virtual string get_extension(int n) const; - virtual string get_suggested_extension() const; + virtual std::string get_extension(int n) const; + virtual std::string get_suggested_extension() const; virtual bool has_magic_number() const; - virtual bool matches_magic_number(const string &magic_number) const; + virtual bool matches_magic_number(const std::string &magic_number) const; - virtual PNMReader *make_reader(istream *file, bool owns_file = true, - const string &magic_number = string()); - virtual PNMWriter *make_writer(ostream *file, bool owns_file = true); + virtual PNMReader *make_reader(std::istream *file, bool owns_file = true, + const std::string &magic_number = std::string()); + virtual PNMWriter *make_writer(std::ostream *file, bool owns_file = true); public: class Reader : public PNMReader { public: - Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number); + Reader(PNMFileType *type, std::istream *file, bool owns_file, std::string magic_number); virtual int read_data(xel *array, xelval *alpha); @@ -65,7 +65,7 @@ public: class Writer : public PNMWriter { public: - Writer(PNMFileType *type, ostream *file, bool owns_file); + Writer(PNMFileType *type, std::ostream *file, bool owns_file); virtual int write_data(xel *array, xelval *alpha); virtual bool supports_grayscale() const; diff --git a/panda/src/pnmimagetypes/pnmFileTypeBMPReader.cxx b/panda/src/pnmimagetypes/pnmFileTypeBMPReader.cxx index 5d33812216..7b2fc6e18c 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeBMPReader.cxx +++ b/panda/src/pnmimagetypes/pnmFileTypeBMPReader.cxx @@ -19,6 +19,9 @@ #include "bmp.h" #include "pnmbitio.h" +using std::istream; +using std::string; + // Much code in this file is borrowed from Netpbm, specifically bmptoppm.c. /* * bmptoppm.c - Converts from a Microsoft Windows or OS/2 .BMP file to a @@ -332,13 +335,13 @@ BMPreadrow( pixval *G, pixval *B) { - BITSTREAM b = NULL; + BITSTREAM b = nullptr; unsigned nbyte = 0; int rc; unsigned x; if (indexed) { - if ((b = pm_bitinit(fp, "r")) == (BITSTREAM) 0) + if ((b = pm_bitinit(fp, "r")) == nullptr) { return -1; } diff --git a/panda/src/pnmimagetypes/pnmFileTypeBMPWriter.cxx b/panda/src/pnmimagetypes/pnmFileTypeBMPWriter.cxx index 879682a297..2c592afa9d 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeBMPWriter.cxx +++ b/panda/src/pnmimagetypes/pnmFileTypeBMPWriter.cxx @@ -45,6 +45,8 @@ #define MAXCOLORS 256 +using std::ostream; + /* * Utilities */ @@ -276,7 +278,7 @@ BMPwriterow( unsigned x; if (indexed) { - if ((b = pm_bitinit(fp, "w")) == (BITSTREAM) 0) + if ((b = pm_bitinit(fp, "w")) == nullptr) { return -1; } @@ -580,7 +582,7 @@ write_data(xel *array, xelval *) { // Quietly generate a 24-bit image. BMPEncode24(_file, classv, _x_size, _y_size, pixels, _maxval); - } else if (chv == (colorhist_vector) 0) { + } else if (chv == nullptr) { if (bmp_bpp != 0) { // Even though we asked for fewer bits, we have to settle for 24-bit. pnmimage_bmp_cat.info() diff --git a/panda/src/pnmimagetypes/pnmFileTypeEXR.cxx b/panda/src/pnmimagetypes/pnmFileTypeEXR.cxx index 6f27c5e09a..83d7cf5bb4 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeEXR.cxx +++ b/panda/src/pnmimagetypes/pnmFileTypeEXR.cxx @@ -30,6 +30,10 @@ #define IMATH_NAMESPACE Imath #endif +using std::istream; +using std::ostream; +using std::string; + TypeHandle PNMFileTypeEXR::_type_handle; static const char * const extensions_exr[] = { @@ -216,8 +220,8 @@ Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number) : // grayscale/alpha images correctly, but also incorrectly detects // luminance/chroma images as grayscale only. However, these kind // of images are a pain to handle anyway, so maybe that's OK. - const char *possible_channel_names[] = { "R", "G", "B", "Y", "A", NULL }; - for (const char **pni = possible_channel_names; *pni != NULL; ++pni) { + const char *possible_channel_names[] = { "R", "G", "B", "Y", "A", nullptr }; + for (const char **pni = possible_channel_names; *pni != nullptr; ++pni) { std::string name = *pni; IMF::ChannelList::ConstIterator ci = channels.find(name.c_str()); if (ci != channels.end()) { @@ -376,7 +380,7 @@ write_pfm(const PfmFile &pfm) { const char *channel_names_2[] = { "G", "A" }; const char *channel_names_3[] = { "R", "G", "B" }; const char *channel_names_4[] = { "R", "G", "B", "A" }; - const char **channel_names = NULL; + const char **channel_names = nullptr; switch (pfm.get_num_channels()) { case 1: diff --git a/panda/src/pnmimagetypes/pnmFileTypeEXR.h b/panda/src/pnmimagetypes/pnmFileTypeEXR.h index 3a0827a74e..75a2b000e9 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeEXR.h +++ b/panda/src/pnmimagetypes/pnmFileTypeEXR.h @@ -40,23 +40,23 @@ class EXPCL_PANDA_PNMIMAGETYPES PNMFileTypeEXR : public PNMFileType { public: PNMFileTypeEXR(); - virtual string get_name() const; + virtual std::string get_name() const; virtual int get_num_extensions() const; - virtual string get_extension(int n) const; - virtual string get_suggested_extension() const; + virtual std::string get_extension(int n) const; + virtual std::string get_suggested_extension() const; virtual bool has_magic_number() const; - virtual bool matches_magic_number(const string &magic_number) const; + virtual bool matches_magic_number(const std::string &magic_number) const; - virtual PNMReader *make_reader(istream *file, bool owns_file = true, - const string &magic_number = string()); - virtual PNMWriter *make_writer(ostream *file, bool owns_file = true); + virtual PNMReader *make_reader(std::istream *file, bool owns_file = true, + const std::string &magic_number = std::string()); + virtual PNMWriter *make_writer(std::ostream *file, bool owns_file = true); public: class Reader : public PNMReader { public: - Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number); + Reader(PNMFileType *type, std::istream *file, bool owns_file, std::string magic_number); virtual ~Reader(); virtual bool is_floating_point(); @@ -69,12 +69,11 @@ public: typedef std::vector ChannelNames; ChannelNames _channel_names; - IMF::PixelType _best_pixel_type; }; class Writer : public PNMWriter { public: - Writer(PNMFileType *type, ostream *file, bool owns_file); + Writer(PNMFileType *type, std::ostream *file, bool owns_file); virtual bool supports_floating_point(); virtual bool supports_integer(); diff --git a/panda/src/pnmimagetypes/pnmFileTypeIMG.cxx b/panda/src/pnmimagetypes/pnmFileTypeIMG.cxx index 477f921bd2..3e20f41a87 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeIMG.cxx +++ b/panda/src/pnmimagetypes/pnmFileTypeIMG.cxx @@ -25,6 +25,10 @@ // than this, it must be bogus. #define INSANE_SIZE 20000 +using std::istream; +using std::ostream; +using std::string; + static const char * const extensions_img[] = { "img" }; diff --git a/panda/src/pnmimagetypes/pnmFileTypeIMG.h b/panda/src/pnmimagetypes/pnmFileTypeIMG.h index 084caf4152..2c406dfa68 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeIMG.h +++ b/panda/src/pnmimagetypes/pnmFileTypeIMG.h @@ -29,20 +29,20 @@ class EXPCL_PANDA_PNMIMAGETYPES PNMFileTypeIMG : public PNMFileType { public: PNMFileTypeIMG(); - virtual string get_name() const; + virtual std::string get_name() const; virtual int get_num_extensions() const; - virtual string get_extension(int n) const; - virtual string get_suggested_extension() const; + virtual std::string get_extension(int n) const; + virtual std::string get_suggested_extension() const; - virtual PNMReader *make_reader(istream *file, bool owns_file = true, - const string &magic_number = string()); - virtual PNMWriter *make_writer(ostream *file, bool owns_file = true); + virtual PNMReader *make_reader(std::istream *file, bool owns_file = true, + const std::string &magic_number = std::string()); + virtual PNMWriter *make_writer(std::ostream *file, bool owns_file = true); public: class Reader : public PNMReader { public: - Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number); + Reader(PNMFileType *type, std::istream *file, bool owns_file, std::string magic_number); virtual bool supports_read_row() const; virtual bool read_row(xel *array, xelval *alpha, int x_size, int y_size); @@ -50,7 +50,7 @@ public: class Writer : public PNMWriter { public: - Writer(PNMFileType *type, ostream *file, bool owns_file); + Writer(PNMFileType *type, std::ostream *file, bool owns_file); virtual bool supports_write_row() const; virtual bool write_header(); diff --git a/panda/src/pnmimagetypes/pnmFileTypeJPG.cxx b/panda/src/pnmimagetypes/pnmFileTypeJPG.cxx index 555fe29074..d7793be7fe 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeJPG.cxx +++ b/panda/src/pnmimagetypes/pnmFileTypeJPG.cxx @@ -20,6 +20,8 @@ #include "pnmFileTypeRegistry.h" #include "bamReader.h" +using std::string; + static const char *const extensions_jpg[] = { "jpg", "jpeg" }; @@ -97,7 +99,7 @@ matches_magic_number(const string &magic_number) const { * returns NULL. */ PNMReader *PNMFileTypeJPG:: -make_reader(istream *file, bool owns_file, const string &magic_number) { +make_reader(std::istream *file, bool owns_file, const string &magic_number) { init_pnm(); return new Reader(this, file, owns_file, magic_number); } @@ -108,7 +110,7 @@ make_reader(istream *file, bool owns_file, const string &magic_number) { * NULL. */ PNMWriter *PNMFileTypeJPG:: -make_writer(ostream *file, bool owns_file) { +make_writer(std::ostream *file, bool owns_file) { init_pnm(); return new Writer(this, file, owns_file); } diff --git a/panda/src/pnmimagetypes/pnmFileTypeJPG.h b/panda/src/pnmimagetypes/pnmFileTypeJPG.h index b82534189a..f851c6d226 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeJPG.h +++ b/panda/src/pnmimagetypes/pnmFileTypeJPG.h @@ -59,23 +59,23 @@ class EXPCL_PANDA_PNMIMAGETYPES PNMFileTypeJPG : public PNMFileType { public: PNMFileTypeJPG(); - virtual string get_name() const; + virtual std::string get_name() const; virtual int get_num_extensions() const; - virtual string get_extension(int n) const; - virtual string get_suggested_extension() const; + virtual std::string get_extension(int n) const; + virtual std::string get_suggested_extension() const; virtual bool has_magic_number() const; - virtual bool matches_magic_number(const string &magic_number) const; + virtual bool matches_magic_number(const std::string &magic_number) const; - virtual PNMReader *make_reader(istream *file, bool owns_file = true, - const string &magic_number = string()); - virtual PNMWriter *make_writer(ostream *file, bool owns_file = true); + virtual PNMReader *make_reader(std::istream *file, bool owns_file = true, + const std::string &magic_number = std::string()); + virtual PNMWriter *make_writer(std::ostream *file, bool owns_file = true); public: class Reader : public PNMReader { public: - Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number); + Reader(PNMFileType *type, std::istream *file, bool owns_file, std::string magic_number); ~Reader(); virtual void prepare_read(); @@ -89,24 +89,12 @@ public: }; typedef struct my_error_mgr *_my_error_ptr; struct my_error_mgr _jerr; - unsigned long pos; - - unsigned long offBits; - - unsigned short cBitCount; - int indexed; - int classv; - - pixval R[256]; /* reds */ - pixval G[256]; /* greens */ - pixval B[256]; /* blues */ - bool _is_valid; }; class Writer : public PNMWriter { public: - Writer(PNMFileType *type, ostream *file, bool owns_file); + Writer(PNMFileType *type, std::ostream *file, bool owns_file); virtual int write_data(xel *array, xelval *alpha); }; diff --git a/panda/src/pnmimagetypes/pnmFileTypeJPGReader.cxx b/panda/src/pnmimagetypes/pnmFileTypeJPGReader.cxx index 333bac61eb..2789583e7f 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeJPGReader.cxx +++ b/panda/src/pnmimagetypes/pnmFileTypeJPGReader.cxx @@ -49,7 +49,7 @@ extern "C" { typedef struct { struct jpeg_source_mgr pub; /* public fields */ - istream * infile; /* source stream */ + std::istream * infile; /* source stream */ JOCTET * buffer; /* start of buffer */ boolean start_of_file; /* have we gotten any data yet? */ } my_source_mgr; @@ -205,7 +205,7 @@ term_source (j_decompress_ptr cinfo) */ GLOBAL(void) -jpeg_istream_src (j_decompress_ptr cinfo, istream * infile) +jpeg_istream_src (j_decompress_ptr cinfo, std::istream * infile) { my_src_ptr src; @@ -216,7 +216,7 @@ jpeg_istream_src (j_decompress_ptr cinfo, istream * infile) * This makes it unsafe to use this manager and a different source * manager serially with the same JPEG object. Caveat programmer. */ - if (cinfo->src == NULL) { /* first time for this JPEG object? */ + if (cinfo->src == nullptr) { /* first time for this JPEG object? */ cinfo->src = (struct jpeg_source_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_source_mgr)); @@ -234,7 +234,7 @@ jpeg_istream_src (j_decompress_ptr cinfo, istream * infile) src->pub.term_source = term_source; src->infile = infile; src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */ - src->pub.next_input_byte = NULL; /* until buffer loaded */ + src->pub.next_input_byte = nullptr; /* until buffer loaded */ } @@ -245,11 +245,11 @@ jpeg_istream_src (j_decompress_ptr cinfo, istream * infile) * */ PNMFileTypeJPG::Reader:: -Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number) : +Reader(PNMFileType *type, std::istream *file, bool owns_file, std::string magic_number) : PNMReader(type, file, owns_file) { // Hope we can putback() more than one character. - for (string::reverse_iterator mi = magic_number.rbegin(); + for (std::string::reverse_iterator mi = magic_number.rbegin(); mi != magic_number.rend(); ++mi) { _file->putback(*mi); @@ -308,7 +308,7 @@ prepare_read() { // Attempt to get the scale close to our target scale. int x_reduction = _cinfo.image_width / _read_x_size; int y_reduction = _cinfo.image_height / _read_y_size; - _cinfo.scale_denom = max(min(x_reduction, y_reduction), 1); + _cinfo.scale_denom = std::max(std::min(x_reduction, y_reduction), 1); } /* Step 7: Start decompressor */ @@ -413,7 +413,7 @@ read_data(xel *array, xelval *) { */ if (_jerr.pub.num_warnings) { pnmimage_jpg_cat.warning() - << "Jpeg data may be corrupt" << endl; + << "Jpeg data may be corrupt" << std::endl; } return _y_size; diff --git a/panda/src/pnmimagetypes/pnmFileTypeJPGWriter.cxx b/panda/src/pnmimagetypes/pnmFileTypeJPGWriter.cxx index 5e0f52f5a6..6f0285a841 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeJPGWriter.cxx +++ b/panda/src/pnmimagetypes/pnmFileTypeJPGWriter.cxx @@ -53,7 +53,7 @@ extern "C" { typedef struct { struct jpeg_destination_mgr pub; /* public fields */ - ostream * outfile; /* target stream */ + std::ostream * outfile; /* target stream */ JOCTET * buffer; /* start of buffer */ } my_destination_mgr; @@ -156,7 +156,7 @@ term_destination (j_compress_ptr cinfo) */ GLOBAL(void) -jpeg_ostream_dest (j_compress_ptr cinfo, ostream * outfile) +jpeg_ostream_dest (j_compress_ptr cinfo, std::ostream * outfile) { my_dest_ptr dest; @@ -166,7 +166,7 @@ jpeg_ostream_dest (j_compress_ptr cinfo, ostream * outfile) * manager serially with the same JPEG object, because their private object * sizes may be different. Caveat programmer. */ - if (cinfo->dest == NULL) { /* first time for this JPEG object? */ + if (cinfo->dest == nullptr) { /* first time for this JPEG object? */ cinfo->dest = (struct jpeg_destination_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_destination_mgr)); @@ -187,7 +187,7 @@ jpeg_ostream_dest (j_compress_ptr cinfo, ostream * outfile) * */ PNMFileTypeJPG::Writer:: -Writer(PNMFileType *type, ostream *file, bool owns_file) : +Writer(PNMFileType *type, std::ostream *file, bool owns_file) : PNMWriter(type, file, owns_file) { } diff --git a/panda/src/pnmimagetypes/pnmFileTypePNG.cxx b/panda/src/pnmimagetypes/pnmFileTypePNG.cxx index bf4ab4ac31..799f4d1dce 100644 --- a/panda/src/pnmimagetypes/pnmFileTypePNG.cxx +++ b/panda/src/pnmimagetypes/pnmFileTypePNG.cxx @@ -21,6 +21,10 @@ #include "bamReader.h" #include "thread.h" +using std::istream; +using std::ostream; +using std::string; + static const char * const extensions_png[] = { "png" }; @@ -162,19 +166,19 @@ PNMFileTypePNG::Reader:: Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number) : PNMReader(type, file, owns_file) { - _png = NULL; - _info = NULL; + _png = nullptr; + _info = nullptr; _is_valid = false; - _png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, + _png = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, png_error, png_warning); - if (_png == NULL) { + if (_png == nullptr) { return; } _info = png_create_info_struct(_png); - if (_info == NULL) { - png_destroy_read_struct(&_png, NULL, NULL); + if (_info == nullptr) { + png_destroy_read_struct(&_png, nullptr, nullptr); return; } @@ -201,7 +205,7 @@ Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number) : double gamma; png_get_IHDR(_png, _info, &width, &height, - &bit_depth, &color_type, NULL, NULL, NULL); + &bit_depth, &color_type, nullptr, nullptr, nullptr); // Look for an sRGB chunk. if (png_get_sRGB(_png, _info, &srgb_intent) == PNG_INFO_sRGB) { @@ -403,7 +407,7 @@ read_data(xel *array, xelval *alpha_data) { PANDA_FREE_ARRAY(rows); - png_read_end(_png, NULL); + png_read_end(_png, nullptr); return _y_size; } @@ -414,7 +418,7 @@ read_data(xel *array, xelval *alpha_data) { void PNMFileTypePNG::Reader:: free_png() { if (_is_valid) { - png_destroy_read_struct(&_png, &_info, NULL); + png_destroy_read_struct(&_png, &_info, nullptr); _is_valid = false; } } @@ -456,7 +460,7 @@ png_error(png_structp png_ptr, png_const_charp error_msg) { // The PNG library insists we should not return, so instead of returning, we // will do a longjmp out of the png code. Reader *self = (Reader *)png_get_io_ptr(png_ptr); - if (self == (Reader *)NULL) { + if (self == nullptr) { // Oops, we haven't got a self pointer yet. Return anyway and hope we'll // be ok. pnmimage_png_cat.error() @@ -474,19 +478,19 @@ PNMFileTypePNG::Writer:: Writer(PNMFileType *type, ostream *file, bool owns_file) : PNMWriter(type, file, owns_file) { - _png = NULL; - _info = NULL; + _png = nullptr; + _info = nullptr; _is_valid = false; - _png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, + _png = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, png_error, png_warning); - if (_png == NULL) { + if (_png == nullptr) { return; } _info = png_create_info_struct(_png); - if (_info == NULL) { - png_destroy_write_struct(&_png, NULL); + if (_info == nullptr) { + png_destroy_write_struct(&_png, nullptr); return; } @@ -610,7 +614,7 @@ write_data(xel *array, xelval *alpha_data) { if (has_alpha()) { pnmimage_png_cat.debug() << "palette contains " << num_alpha << " transparent entries.\n"; - png_set_tRNS(_png, _info, png_trans, num_alpha, NULL); + png_set_tRNS(_png, _info, png_trans, num_alpha, nullptr); } } else { pnmimage_png_cat.debug() @@ -828,7 +832,7 @@ write_data(xel *array, xelval *alpha_data) { } PANDA_FREE_ARRAY(row); - png_write_end(_png, NULL); + png_write_end(_png, nullptr); return _y_size; } @@ -918,7 +922,7 @@ png_error(png_structp png_ptr, png_const_charp error_msg) { // The PNG library insists we should not return, so instead of returning, we // will do a longjmp out of the png code. Writer *self = (Writer *)png_get_io_ptr(png_ptr); - if (self == (Writer *)NULL) { + if (self == nullptr) { // Oops, we haven't got a self pointer yet. Return anyway and hope we'll // be ok. pnmimage_png_cat.error() diff --git a/panda/src/pnmimagetypes/pnmFileTypePNG.h b/panda/src/pnmimagetypes/pnmFileTypePNG.h index 79b9fb1f73..3c1df88cbc 100644 --- a/panda/src/pnmimagetypes/pnmFileTypePNG.h +++ b/panda/src/pnmimagetypes/pnmFileTypePNG.h @@ -32,23 +32,23 @@ class EXPCL_PANDA_PNMIMAGETYPES PNMFileTypePNG : public PNMFileType { public: PNMFileTypePNG(); - virtual string get_name() const; + virtual std::string get_name() const; virtual int get_num_extensions() const; - virtual string get_extension(int n) const; - virtual string get_suggested_extension() const; + virtual std::string get_extension(int n) const; + virtual std::string get_suggested_extension() const; virtual bool has_magic_number() const; - virtual bool matches_magic_number(const string &magic_number) const; + virtual bool matches_magic_number(const std::string &magic_number) const; - virtual PNMReader *make_reader(istream *file, bool owns_file = true, - const string &magic_number = string()); - virtual PNMWriter *make_writer(ostream *file, bool owns_file = true); + virtual PNMReader *make_reader(std::istream *file, bool owns_file = true, + const std::string &magic_number = std::string()); + virtual PNMWriter *make_writer(std::ostream *file, bool owns_file = true); public: class Reader : public PNMReader { public: - Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number); + Reader(PNMFileType *type, std::istream *file, bool owns_file, std::string magic_number); virtual ~Reader(); virtual int read_data(xel *array, xelval *alpha_data); @@ -72,7 +72,7 @@ public: class Writer : public PNMWriter { public: - Writer(PNMFileType *type, ostream *file, bool owns_file); + Writer(PNMFileType *type, std::ostream *file, bool owns_file); virtual ~Writer(); virtual int write_data(xel *array, xelval *alpha); diff --git a/panda/src/pnmimagetypes/pnmFileTypePNM.cxx b/panda/src/pnmimagetypes/pnmFileTypePNM.cxx index efbee9e646..cdc1e62f93 100644 --- a/panda/src/pnmimagetypes/pnmFileTypePNM.cxx +++ b/panda/src/pnmimagetypes/pnmFileTypePNM.cxx @@ -20,6 +20,10 @@ #include "pnmFileTypeRegistry.h" #include "bamReader.h" +using std::istream; +using std::ostream; +using std::string; + static const char * const extensions_PNM[] = { "pbm", "pgm", "ppm", "pnm" }; @@ -127,21 +131,21 @@ pm_allocarray(int const cols, int const rows, int const size ) { char * rowheap; rowIndex = (char **)PANDA_MALLOC_ARRAY((rows + 1) * sizeof(char *)); - if ( rowIndex == NULL ) + if ( rowIndex == nullptr ) pm_error("out of memory allocating row index (%u rows) for an array", rows); rowheap = (char *)PANDA_MALLOC_ARRAY( rows * cols * size ); - if ( rowheap == NULL ) { + if ( rowheap == nullptr ) { /* We couldn't get the whole heap in one block, so try fragmented format. */ int row; - rowIndex[rows] = NULL; /* Declare it fragmented format */ + rowIndex[rows] = nullptr; /* Declare it fragmented format */ for (row = 0; row < rows; ++row) { rowIndex[row] = pm_allocrow(cols, size); - if (rowIndex[row] == NULL) + if (rowIndex[row] == nullptr) pm_error("out of memory allocating Row %u " "(%u columns, %u bytes per tuple) " "of an array", row, cols, size); @@ -163,7 +167,7 @@ pm_freearray(char ** const rowIndex, void * const rowheap = rowIndex[rows]; - if (rowheap != NULL) { + if (rowheap != nullptr) { PANDA_FREE_ARRAY(rowheap); } else { int row; diff --git a/panda/src/pnmimagetypes/pnmFileTypePNM.h b/panda/src/pnmimagetypes/pnmFileTypePNM.h index 1f5bc4cc7d..1c65c19109 100644 --- a/panda/src/pnmimagetypes/pnmFileTypePNM.h +++ b/panda/src/pnmimagetypes/pnmFileTypePNM.h @@ -29,23 +29,23 @@ class EXPCL_PANDA_PNMIMAGETYPES PNMFileTypePNM : public PNMFileType { public: PNMFileTypePNM(); - virtual string get_name() const; + virtual std::string get_name() const; virtual int get_num_extensions() const; - virtual string get_extension(int n) const; - virtual string get_suggested_extension() const; + virtual std::string get_extension(int n) const; + virtual std::string get_suggested_extension() const; virtual bool has_magic_number() const; - virtual bool matches_magic_number(const string &magic_number) const; + virtual bool matches_magic_number(const std::string &magic_number) const; - virtual PNMReader *make_reader(istream *file, bool owns_file = true, - const string &magic_number = string()); - virtual PNMWriter *make_writer(ostream *file, bool owns_file = true); + virtual PNMReader *make_reader(std::istream *file, bool owns_file = true, + const std::string &magic_number = std::string()); + virtual PNMWriter *make_writer(std::ostream *file, bool owns_file = true); public: class Reader : public PNMReader { public: - Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number); + Reader(PNMFileType *type, std::istream *file, bool owns_file, std::string magic_number); virtual bool supports_read_row() const; virtual bool read_row(xel *array, xelval *alpha, int x_size, int y_size); @@ -56,7 +56,7 @@ public: class Writer : public PNMWriter { public: - Writer(PNMFileType *type, ostream *file, bool owns_file); + Writer(PNMFileType *type, std::ostream *file, bool owns_file); virtual bool supports_write_row() const; virtual bool write_header(); diff --git a/panda/src/pnmimagetypes/pnmFileTypePfm.cxx b/panda/src/pnmimagetypes/pnmFileTypePfm.cxx index 71652689ec..89324f3c61 100644 --- a/panda/src/pnmimagetypes/pnmFileTypePfm.cxx +++ b/panda/src/pnmimagetypes/pnmFileTypePfm.cxx @@ -18,6 +18,10 @@ #include "pnmFileTypeRegistry.h" #include "bamReader.h" +using std::istream; +using std::ostream; +using std::string; + TypeHandle PNMFileTypePfm::_type_handle; /** diff --git a/panda/src/pnmimagetypes/pnmFileTypePfm.h b/panda/src/pnmimagetypes/pnmFileTypePfm.h index cbc7bb4512..ab18685084 100644 --- a/panda/src/pnmimagetypes/pnmFileTypePfm.h +++ b/panda/src/pnmimagetypes/pnmFileTypePfm.h @@ -25,27 +25,27 @@ * For reading and writing PFM files using the basic PNMImage interface, as if * they were basic RGB files. */ -class EXPCL_PANDA_PNMIMAGE PNMFileTypePfm : public PNMFileType { +class EXPCL_PANDA_PNMIMAGETYPES PNMFileTypePfm : public PNMFileType { public: PNMFileTypePfm(); - virtual string get_name() const; + virtual std::string get_name() const; virtual int get_num_extensions() const; - virtual string get_extension(int n) const; - virtual string get_suggested_extension() const; + virtual std::string get_extension(int n) const; + virtual std::string get_suggested_extension() const; virtual bool has_magic_number() const; - virtual bool matches_magic_number(const string &magic_number) const; + virtual bool matches_magic_number(const std::string &magic_number) const; - virtual PNMReader *make_reader(istream *file, bool owns_file = true, - const string &magic_number = string()); - virtual PNMWriter *make_writer(ostream *file, bool owns_file = true); + virtual PNMReader *make_reader(std::istream *file, bool owns_file = true, + const std::string &magic_number = std::string()); + virtual PNMWriter *make_writer(std::ostream *file, bool owns_file = true); public: class Reader : public PNMReader { public: - Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number); + Reader(PNMFileType *type, std::istream *file, bool owns_file, std::string magic_number); virtual bool is_floating_point(); virtual bool read_pfm(PfmFile &pfm); @@ -56,7 +56,7 @@ public: class Writer : public PNMWriter { public: - Writer(PNMFileType *type, ostream *file, bool owns_file); + Writer(PNMFileType *type, std::ostream *file, bool owns_file); virtual bool supports_floating_point(); virtual bool supports_integer(); diff --git a/panda/src/pnmimagetypes/pnmFileTypeSGI.cxx b/panda/src/pnmimagetypes/pnmFileTypeSGI.cxx index e35880daa3..e2a99eb378 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeSGI.cxx +++ b/panda/src/pnmimagetypes/pnmFileTypeSGI.cxx @@ -21,6 +21,8 @@ #include "pnmFileTypeRegistry.h" #include "bamReader.h" +using std::string; + static const char * const extensions_sgi[] = { "rgb", "rgba", "sgi" }; @@ -100,7 +102,7 @@ matches_magic_number(const string &magic_number) const { * returns NULL. */ PNMReader *PNMFileTypeSGI:: -make_reader(istream *file, bool owns_file, const string &magic_number) { +make_reader(std::istream *file, bool owns_file, const string &magic_number) { init_pnm(); return new Reader(this, file, owns_file, magic_number); } @@ -111,7 +113,7 @@ make_reader(istream *file, bool owns_file, const string &magic_number) { * NULL. */ PNMWriter *PNMFileTypeSGI:: -make_writer(ostream *file, bool owns_file) { +make_writer(std::ostream *file, bool owns_file) { init_pnm(); return new Writer(this, file, owns_file); } diff --git a/panda/src/pnmimagetypes/pnmFileTypeSGI.h b/panda/src/pnmimagetypes/pnmFileTypeSGI.h index 300ccfd777..ff026a3740 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeSGI.h +++ b/panda/src/pnmimagetypes/pnmFileTypeSGI.h @@ -29,23 +29,23 @@ class EXPCL_PANDA_PNMIMAGETYPES PNMFileTypeSGI : public PNMFileType { public: PNMFileTypeSGI(); - virtual string get_name() const; + virtual std::string get_name() const; virtual int get_num_extensions() const; - virtual string get_extension(int n) const; - virtual string get_suggested_extension() const; + virtual std::string get_extension(int n) const; + virtual std::string get_suggested_extension() const; virtual bool has_magic_number() const; - virtual bool matches_magic_number(const string &magic_number) const; + virtual bool matches_magic_number(const std::string &magic_number) const; - virtual PNMReader *make_reader(istream *file, bool owns_file = true, - const string &magic_number = string()); - virtual PNMWriter *make_writer(ostream *file, bool owns_file = true); + virtual PNMReader *make_reader(std::istream *file, bool owns_file = true, + const std::string &magic_number = std::string()); + virtual PNMWriter *make_writer(std::ostream *file, bool owns_file = true); public: class Reader : public PNMReader { public: - Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number); + Reader(PNMFileType *type, std::istream *file, bool owns_file, std::string magic_number); virtual ~Reader(); virtual bool supports_read_row() const; @@ -65,7 +65,7 @@ public: class Writer : public PNMWriter { public: - Writer(PNMFileType *type, ostream *file, bool owns_file); + Writer(PNMFileType *type, std::ostream *file, bool owns_file); virtual ~Writer(); virtual bool supports_write_row() const; @@ -90,7 +90,7 @@ public: void write_rgb_header(const char *imagename); void write_table(); - void write_channels(ScanLine channel[], void (*put)(ostream *, short)); + void write_channels(ScanLine channel[], void (*put)(std::ostream *, short)); void build_scanline(ScanLine output[], xel *row_data, xelval *alpha_data); ScanElem *compress(ScanElem *temp, ScanLine &output); int rle_compress(ScanElem *inbuf, int size); diff --git a/panda/src/pnmimagetypes/pnmFileTypeSGIReader.cxx b/panda/src/pnmimagetypes/pnmFileTypeSGIReader.cxx index 597dc9296a..fafb625fac 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeSGIReader.cxx +++ b/panda/src/pnmimagetypes/pnmFileTypeSGIReader.cxx @@ -23,6 +23,9 @@ #include "pnotify.h" +using std::istream; +using std::string; + // Much code in this file is borrowed from Netpbm, specifically sgitopnm.c. /* sgitopnm.c - read an SGI image and and produce a portable anymap @@ -86,7 +89,7 @@ Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number) : PNMReader(type, file, owns_file) { eof_err = false; - table = NULL; + table = nullptr; if (!read_magic_number(_file, magic_number, 4)) { // No magic number. No image. @@ -121,7 +124,7 @@ Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number) : _x_size = head.xsize; _y_size = head.ysize; - _num_channels = min((int)head.zsize, 4); + _num_channels = std::min((int)head.zsize, 4); bpc = head.bpc; current_row = _y_size - 1; @@ -146,7 +149,7 @@ Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number) : */ PNMFileTypeSGI::Reader:: ~Reader() { - if (table != NULL) { + if (table != nullptr) { free(table); } } @@ -333,7 +336,7 @@ read_channel(istream *ifp, TabEntry *table, ScanElem *channel_data, long table_start, int channel, int row) { - ScanElem *temp = NULL; + ScanElem *temp = nullptr; int sgi_index, i; long offset, length; @@ -486,10 +489,10 @@ xmalloc(int bytes) { void *mem; if( bytes == 0 ) - return NULL; + return nullptr; mem = malloc(bytes); - if( mem == NULL ) + if( mem == nullptr ) pm_error("out of memory allocating %d bytes", bytes); return mem; } diff --git a/panda/src/pnmimagetypes/pnmFileTypeSGIWriter.cxx b/panda/src/pnmimagetypes/pnmFileTypeSGIWriter.cxx index f63431bba1..f5b143e867 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeSGIWriter.cxx +++ b/panda/src/pnmimagetypes/pnmFileTypeSGIWriter.cxx @@ -49,6 +49,8 @@ #define MAXVAL_BYTE 255 #define MAXVAL_WORD 65535 +using std::ostream; + inline void put_byte(ostream *out_file, unsigned char b) { out_file->put(b); @@ -88,7 +90,7 @@ Writer(PNMFileType *type, ostream *file, bool owns_file) : */ PNMFileTypeSGI::Writer:: ~Writer() { - if (table!=NULL) { + if (table!=nullptr) { // Rewrite the table with the correct values in it. _file->seekp(table_start); write_table(); @@ -119,7 +121,7 @@ supports_write_row() const { */ bool PNMFileTypeSGI::Writer:: write_header() { - table = NULL; + table = nullptr; switch (_num_channels) { case 1: @@ -155,7 +157,7 @@ write_header() { write_rgb_header(sgi_imagename.c_str()); - if (table!=NULL) { + if (table!=nullptr) { table_start = _file->tellp(); // The first time we write the table, it has zeroes. We'll correct this diff --git a/panda/src/pnmimagetypes/pnmFileTypeSoftImage.cxx b/panda/src/pnmimagetypes/pnmFileTypeSoftImage.cxx index e2d12c3e33..d67a22fa53 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeSoftImage.cxx +++ b/panda/src/pnmimagetypes/pnmFileTypeSoftImage.cxx @@ -20,6 +20,10 @@ #include "pnmFileTypeRegistry.h" #include "bamReader.h" +using std::istream; +using std::ostream; +using std::string; + static const float imageVersionNumber = 3.0; static const int imageCommentLength = 80; static const char imageComment[imageCommentLength+1] = @@ -322,7 +326,7 @@ Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number) : read_float(_file); // Skip comment - _file->seekg(imageCommentLength, ios::cur); + _file->seekg(imageCommentLength, std::ios::cur); char pict_id[4]; _file->read(pict_id, 4); diff --git a/panda/src/pnmimagetypes/pnmFileTypeSoftImage.h b/panda/src/pnmimagetypes/pnmFileTypeSoftImage.h index 9fffbbd42d..c6e6860621 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeSoftImage.h +++ b/panda/src/pnmimagetypes/pnmFileTypeSoftImage.h @@ -29,23 +29,23 @@ class EXPCL_PANDA_PNMIMAGETYPES PNMFileTypeSoftImage : public PNMFileType { public: PNMFileTypeSoftImage(); - virtual string get_name() const; + virtual std::string get_name() const; virtual int get_num_extensions() const; - virtual string get_extension(int n) const; - virtual string get_suggested_extension() const; + virtual std::string get_extension(int n) const; + virtual std::string get_suggested_extension() const; virtual bool has_magic_number() const; - virtual bool matches_magic_number(const string &magic_number) const; + virtual bool matches_magic_number(const std::string &magic_number) const; - virtual PNMReader *make_reader(istream *file, bool owns_file = true, - const string &magic_number = string()); - virtual PNMWriter *make_writer(ostream *file, bool owns_file = true); + virtual PNMReader *make_reader(std::istream *file, bool owns_file = true, + const std::string &magic_number = std::string()); + virtual PNMWriter *make_writer(std::ostream *file, bool owns_file = true); public: class Reader : public PNMReader { public: - Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number); + Reader(PNMFileType *type, std::istream *file, bool owns_file, std::string magic_number); virtual bool supports_read_row() const; virtual bool read_row(xel *array, xelval *alpha, int x_size, int y_size); @@ -57,7 +57,7 @@ public: class Writer : public PNMWriter { public: - Writer(PNMFileType *type, ostream *file, bool owns_file); + Writer(PNMFileType *type, std::ostream *file, bool owns_file); virtual bool supports_write_row() const; virtual bool write_header(); diff --git a/panda/src/pnmimagetypes/pnmFileTypeStbImage.cxx b/panda/src/pnmimagetypes/pnmFileTypeStbImage.cxx index e17e0e9df8..96610157a4 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeStbImage.cxx +++ b/panda/src/pnmimagetypes/pnmFileTypeStbImage.cxx @@ -60,6 +60,10 @@ #include "stb_image.h" +using std::ios; +using std::istream; +using std::string; + static const char *const stb_extensions[] = { // Expose the extensions that we don't already expose through other loaders. #if !defined(HAVE_JPEG) && !defined(ANDROID) @@ -91,7 +95,7 @@ static const int num_stb_extensions = sizeof(stb_extensions) / sizeof(const char // Callbacks to allow stb_image to read from VFS. static int cb_read(void *user, char *data, int size) { istream *in = (istream *)user; - nassertr(in != NULL, 0); + nassertr(in != nullptr, 0); in->read(data, size); @@ -105,7 +109,7 @@ static int cb_read(void *user, char *data, int size) { static void cb_skip(void *user, int n) { istream *in = (istream *)user; - nassertv(in != NULL); + nassertv(in != nullptr); in->seekg(n, ios::cur); @@ -118,7 +122,7 @@ static void cb_skip(void *user, int n) { static int cb_eof(void *user) { istream *in = (istream *)user; - nassertr(in != NULL, 1); + nassertr(in != nullptr, 1); return in->eof(); } @@ -300,7 +304,7 @@ read_pfm(PfmFile &pfm) { } else { // We need to reinitialize the context. _file->seekg(0, ios::beg); - if (_file->tellg() != (streampos)0) { + if (_file->tellg() != (std::streampos)0) { pnmimage_cat.error() << "Could not reposition file pointer to the beginning.\n"; return false; @@ -358,7 +362,7 @@ read_pfm(PfmFile &pfm) { return false; } token += 3; - width = (int) strtol(token, NULL, 10); + width = (int) strtol(token, nullptr, 10); // Read data pfm.clear(width, height, 3); @@ -380,7 +384,7 @@ main_decode_loop: } } else { // Read RLE-encoded data - scanline = NULL; + scanline = nullptr; for (j = 0; j < height; ++j) { c1 = stbi__get8(&_context); @@ -482,7 +486,7 @@ read_data(xel *array, xelval *alpha) { } else { // We need to reinitialize the context. _file->seekg(0, ios::beg); - if (_file->tellg() != (streampos)0) { + if (_file->tellg() != (std::streampos)0) { pnmimage_cat.error() << "Could not reposition file pointer to the beginning.\n"; return false; diff --git a/panda/src/pnmimagetypes/pnmFileTypeStbImage.h b/panda/src/pnmimagetypes/pnmFileTypeStbImage.h index 08cf62e247..ce7d2d55ea 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeStbImage.h +++ b/panda/src/pnmimagetypes/pnmFileTypeStbImage.h @@ -31,16 +31,16 @@ class EXPCL_PANDA_PNMIMAGETYPES PNMFileTypeStbImage : public PNMFileType { public: PNMFileTypeStbImage(); - virtual string get_name() const; + virtual std::string get_name() const; virtual int get_num_extensions() const; - virtual string get_extension(int n) const; + virtual std::string get_extension(int n) const; virtual bool has_magic_number() const; - virtual bool matches_magic_number(const string &magic_number) const; + virtual bool matches_magic_number(const std::string &magic_number) const; - virtual PNMReader *make_reader(istream *file, bool owns_file = true, - const string &magic_number = string()); + virtual PNMReader *make_reader(std::istream *file, bool owns_file = true, + const std::string &magic_number = std::string()); public: static void register_with_read_factory(); diff --git a/panda/src/pnmimagetypes/pnmFileTypeTGA.cxx b/panda/src/pnmimagetypes/pnmFileTypeTGA.cxx index 75e90d630d..a50ae370ae 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeTGA.cxx +++ b/panda/src/pnmimagetypes/pnmFileTypeTGA.cxx @@ -52,6 +52,10 @@ #include +using std::istream; +using std::ostream; +using std::string; + static const char * const extensions_tga[] = { "tga" }; @@ -176,8 +180,8 @@ Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number) : tga_head = new ImageHeader; RLE_count = 0; RLE_flag = 0; - ColorMap = NULL; - AlphaMap = NULL; + ColorMap = nullptr; + AlphaMap = nullptr; Red = 0; Grn = 0; @@ -283,7 +287,7 @@ Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number) : temp1 = tga_head->Index_lo + tga_head->Index_hi * 256; temp2 = tga_head->Length_lo + tga_head->Length_hi * 256; int num_colors = temp1 + temp2 + 1; - nassertv(ColorMap == NULL && AlphaMap == NULL); + nassertv(ColorMap == nullptr && AlphaMap == nullptr); ColorMap = (pixel *)PANDA_MALLOC_ARRAY(num_colors * sizeof(pixel)); AlphaMap = (gray *)PANDA_MALLOC_ARRAY(num_colors * sizeof(gray)); for ( unsigned int i = temp1; i < ( temp1 + temp2 ); ++i ) @@ -311,10 +315,10 @@ Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number) : PNMFileTypeTGA::Reader:: ~Reader() { delete tga_head; - if (ColorMap != NULL) { + if (ColorMap != nullptr) { PANDA_FREE_ARRAY(ColorMap); } - if (AlphaMap != NULL) { + if (AlphaMap != nullptr) { PANDA_FREE_ARRAY(AlphaMap); } } @@ -363,9 +367,9 @@ Writer(PNMFileType *type, ostream *file, bool owns_file) : PNMWriter(type, file, owns_file) { tgaHeader = new ImageHeader; - chv = (colorhist_vector)0; - cht = (colorhash_table)0; - runlength = (int*)0; + chv = nullptr; + cht = nullptr; + runlength = nullptr; } /** @@ -375,13 +379,13 @@ PNMFileTypeTGA::Writer:: ~Writer() { delete tgaHeader; - if (chv != (colorhist_vector)0) { + if (chv != nullptr) { ppm_freecolorhist(chv); } - if (cht != (colorhash_table)0) { + if (cht != nullptr) { ppm_freecolorhash(cht); } - if (runlength != (int *)0) { + if (runlength != nullptr) { pm_freerow((char *)runlength); } } @@ -432,7 +436,7 @@ write_data(xel *array, xelval *) { pnmimage_tga_cat.info() << "computing colormap...\n"; chv = ppm_computecolorhist(&array, cols * rows, 1, TGA_MAXCOLORS, &ncolors ); - if ( chv == (colorhist_vector) 0 ) { + if ( chv == nullptr ) { pnmimage_tga_cat.info() << "too many colors, writing RGB.\n"; } else { @@ -498,7 +502,7 @@ write_data(xel *array, xelval *) { tgaHeader->OrgBit = 0; /* Write out the Targa header. */ - writetga( tgaHeader, (char*) 0 ); + writetga( tgaHeader, nullptr ); if ( tgaHeader->ImgType == TGA_Map || tgaHeader->ImgType == TGA_RLEMap ) { @@ -717,8 +721,8 @@ get_pixel( istream *ifp, pixel *dest, int Size, gray *alpha_p) { Red = getbyte( ifp ); if ( Size == 32 ) Alpha = getbyte( ifp ); - else - Alpha = 0; + else + Alpha = 0; l = 0; break; diff --git a/panda/src/pnmimagetypes/pnmFileTypeTGA.h b/panda/src/pnmimagetypes/pnmFileTypeTGA.h index 911ebb7c20..c50a09ed47 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeTGA.h +++ b/panda/src/pnmimagetypes/pnmFileTypeTGA.h @@ -34,30 +34,30 @@ class EXPCL_PANDA_PNMIMAGETYPES PNMFileTypeTGA : public PNMFileType { public: PNMFileTypeTGA(); - virtual string get_name() const; + virtual std::string get_name() const; virtual int get_num_extensions() const; - virtual string get_extension(int n) const; - virtual string get_suggested_extension() const; + virtual std::string get_extension(int n) const; + virtual std::string get_suggested_extension() const; - virtual PNMReader *make_reader(istream *file, bool owns_file = true, - const string &magic_number = string()); - virtual PNMWriter *make_writer(ostream *file, bool owns_file = true); + virtual PNMReader *make_reader(std::istream *file, bool owns_file = true, + const std::string &magic_number = std::string()); + virtual PNMWriter *make_writer(std::ostream *file, bool owns_file = true); public: class Reader : public PNMReader { public: - Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number); + Reader(PNMFileType *type, std::istream *file, bool owns_file, std::string magic_number); virtual ~Reader(); virtual int read_data(xel *array, xelval *alpha); private: - void readtga ( istream* ifp, struct ImageHeader* tgaP, const string &magic_number ); - void get_map_entry ( istream* ifp, pixel* Value, int Size, + void readtga ( std::istream* ifp, struct ImageHeader* tgaP, const std::string &magic_number ); + void get_map_entry ( std::istream* ifp, pixel* Value, int Size, gray* Alpha); - void get_pixel ( istream* ifp, pixel* dest, int Size, gray* alpha_p); - unsigned char getbyte ( istream* ifp ); + void get_pixel ( std::istream* ifp, pixel* dest, int Size, gray* alpha_p); + unsigned char getbyte ( std::istream* ifp ); int rows, cols, rlencoded, mapped; struct ImageHeader *tga_head; @@ -72,7 +72,7 @@ public: class Writer : public PNMWriter { public: - Writer(PNMFileType *type, ostream *file, bool owns_file); + Writer(PNMFileType *type, std::ostream *file, bool owns_file); virtual ~Writer(); virtual int write_data(xel *array, xelval *alpha); diff --git a/panda/src/pnmimagetypes/pnmFileTypeTIFF.cxx b/panda/src/pnmimagetypes/pnmFileTypeTIFF.cxx index d4870c22d3..3c4634055d 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeTIFF.cxx +++ b/panda/src/pnmimagetypes/pnmFileTypeTIFF.cxx @@ -28,6 +28,11 @@ #define int32 tiff_int32 #define uint32 tiff_uint32 +using std::ios; +using std::istream; +using std::ostream; +using std::string; + extern "C" { #include #include @@ -338,7 +343,7 @@ Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number) : iostream_dont_close, istream_size, iostream_map, iostream_unmap); - if ( tif == NULL ) { + if ( tif == nullptr ) { _is_valid = false; } } @@ -374,7 +379,7 @@ Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number) : if (_is_valid) { unsigned short num_extra_samples; - unsigned short *extra_samples = NULL; + unsigned short *extra_samples = nullptr; if (!TIFFGetField(tif, TIFFTAG_EXTRASAMPLES, &num_extra_samples, &extra_samples)) { @@ -547,7 +552,7 @@ Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number) : */ PNMFileTypeTIFF::Reader:: ~Reader() { - if (tif != (struct tiff *)NULL) { + if (tif != nullptr) { TIFFClose(tif); } } @@ -898,7 +903,7 @@ write_pfm(const PfmFile &pfm) { (TIFFSeekProc)ostream_seek, iostream_dont_close, ostream_size, iostream_map, iostream_unmap); - if (tif == NULL) { + if (tif == nullptr) { return false; } @@ -958,7 +963,7 @@ write_pfm(const PfmFile &pfm) { */ int PNMFileTypeTIFF::Writer:: write_data(xel *array, xelval *alpha) { - colorhist_vector chv = (colorhist_vector) 0; + colorhist_vector chv = nullptr; colorhash_table cht; unsigned short red[TIFF_COLORMAP_MAXCOLORS], @@ -986,7 +991,7 @@ write_data(xel *array, xelval *alpha) { // the number of colors we can read. chv = ppm_computecolorhist( (pixel **)&array, _x_size * _y_size, 1, 256, &colors ); - if ( chv == (colorhist_vector) 0 ) { + if ( chv == nullptr ) { pnmimage_tiff_cat.debug() << colors << " colors found; too many for a palette.\n" << "Writing a 24-bit RGB file.\n"; @@ -1011,12 +1016,12 @@ write_data(xel *array, xelval *alpha) { case CT_two_channel: // We don't yet support two-channel output for TIFF's. case CT_four_channel: - chv = (colorhist_vector) 0; + chv = nullptr; grayscale = false; break; case CT_grayscale: - chv = (colorhist_vector) 0; + chv = nullptr; grayscale = true; break; @@ -1031,7 +1036,7 @@ write_data(xel *array, xelval *alpha) { (TIFFSeekProc)ostream_seek, iostream_dont_close, ostream_size, iostream_map, iostream_unmap); - if ( tif == NULL ) { + if ( tif == nullptr ) { return 0; } @@ -1039,20 +1044,20 @@ write_data(xel *array, xelval *alpha) { switch ( get_color_type() ) { case CT_color: case CT_four_channel: - if ( chv == (colorhist_vector) 0 ) { + if ( chv == nullptr ) { samplesperpixel = _num_channels; bitspersample = 8; photometric = PHOTOMETRIC_RGB; bytesperrow = _x_size * samplesperpixel; } else if ( grayscale ) { samplesperpixel = 1; - bitspersample = min(8, pm_maxvaltobits(_maxval)); + bitspersample = std::min(8, pm_maxvaltobits(_maxval)); photometric = PHOTOMETRIC_MINISBLACK; i = 8 / bitspersample; bytesperrow = ( _x_size + i - 1 ) / i; } else { samplesperpixel = 1; - bitspersample = min(8, pm_maxvaltobits(_maxval)); + bitspersample = std::min(8, pm_maxvaltobits(_maxval)); photometric = PHOTOMETRIC_PALETTE; bytesperrow = _x_size; } @@ -1072,7 +1077,7 @@ write_data(xel *array, xelval *alpha) { } buf = (unsigned char*) malloc( bytesperrow ); - if ( buf == (unsigned char*) 0 ) { + if ( buf == nullptr ) { pnmimage_tiff_cat.error() << "Can't allocate memory for row buffer\n"; return 0; @@ -1100,8 +1105,8 @@ write_data(xel *array, xelval *alpha) { } TIFFSetField( tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG ); - if ( chv == (colorhist_vector) 0 ) { - cht = (colorhash_table) 0; + if ( chv == nullptr ) { + cht = nullptr; } else { /* Make TIFF colormap. */ for ( i = 0; i < colors; ++i ) { @@ -1122,7 +1127,7 @@ write_data(xel *array, xelval *alpha) { xelval *alpha_data = alpha + row*_x_size; if ( !is_grayscale() && ! grayscale ) { - if ( cht == (colorhash_table) 0 ) { + if ( cht == nullptr ) { tP = buf; for ( col = 0; col < _x_size; ++col ) { *tP++ = (unsigned char)(255 * PPM_GETR(row_data[col]) / _maxval); diff --git a/panda/src/pnmimagetypes/pnmFileTypeTIFF.h b/panda/src/pnmimagetypes/pnmFileTypeTIFF.h index 21466b2cd9..c61e4f53f1 100644 --- a/panda/src/pnmimagetypes/pnmFileTypeTIFF.h +++ b/panda/src/pnmimagetypes/pnmFileTypeTIFF.h @@ -34,23 +34,23 @@ class EXPCL_PANDA_PNMIMAGETYPES PNMFileTypeTIFF : public PNMFileType { public: PNMFileTypeTIFF(); - virtual string get_name() const; + virtual std::string get_name() const; virtual int get_num_extensions() const; - virtual string get_extension(int n) const; - virtual string get_suggested_extension() const; + virtual std::string get_extension(int n) const; + virtual std::string get_suggested_extension() const; virtual bool has_magic_number() const; - virtual bool matches_magic_number(const string &magic_number) const; + virtual bool matches_magic_number(const std::string &magic_number) const; - virtual PNMReader *make_reader(istream *file, bool owns_file = true, - const string &magic_number = string()); - virtual PNMWriter *make_writer(ostream *file, bool owns_file = true); + virtual PNMReader *make_reader(std::istream *file, bool owns_file = true, + const std::string &magic_number = std::string()); + virtual PNMWriter *make_writer(std::ostream *file, bool owns_file = true); public: class Reader : public PNMReader { public: - Reader(PNMFileType *type, istream *file, bool owns_file, string magic_number); + Reader(PNMFileType *type, std::istream *file, bool owns_file, std::string magic_number); virtual ~Reader(); virtual bool is_floating_point(); @@ -77,7 +77,7 @@ public: class Writer : public PNMWriter { public: - Writer(PNMFileType *type, ostream *file, bool owns_file); + Writer(PNMFileType *type, std::ostream *file, bool owns_file); virtual bool supports_floating_point(); virtual bool supports_integer(); diff --git a/panda/src/pnmtext/freetypeFace.cxx b/panda/src/pnmtext/freetypeFace.cxx index 0366e3c49a..6dee837486 100644 --- a/panda/src/pnmtext/freetypeFace.cxx +++ b/panda/src/pnmtext/freetypeFace.cxx @@ -28,7 +28,7 @@ TypeHandle FreetypeFace::_type_handle; */ FreetypeFace:: FreetypeFace() : _lock("FreetypeFace::_lock") { - _face = NULL; + _face = nullptr; _char_size = 0; _dpi = 0; _pixel_width = 0; @@ -44,7 +44,7 @@ FreetypeFace() : _lock("FreetypeFace::_lock") { */ FreetypeFace:: ~FreetypeFace() { - if (_face != NULL){ + if (_face != nullptr){ FT_Done_Face(_face); } } @@ -101,7 +101,7 @@ void FreetypeFace:: set_face(FT_Face face) { MutexHolder holder(_lock); - if (_face != NULL){ + if (_face != nullptr){ FT_Done_Face(_face); } _face = face; @@ -111,7 +111,7 @@ set_face(FT_Face face) { _pixel_height = 0; _name = _face->family_name; - if (_face->style_name != NULL) { + if (_face->style_name != nullptr) { _name += " "; _name += _face->style_name; } @@ -129,7 +129,7 @@ set_face(FT_Face face) { pnmtext_cat.debug() << "default charmap is " << (void *)_face->charmap << "\n"; } - if (_face->charmap == NULL) { + if (_face->charmap == nullptr) { // If for some reason FreeType didn't set us up a charmap, then set it up // ourselves. if (_face->num_charmaps == 0) { diff --git a/panda/src/pnmtext/freetypeFace.h b/panda/src/pnmtext/freetypeFace.h index 2070e5ca66..e8c0774eee 100644 --- a/panda/src/pnmtext/freetypeFace.h +++ b/panda/src/pnmtext/freetypeFace.h @@ -46,9 +46,9 @@ private: private: // This is provided as a permanent storage for the raw font data, if needed. - string _font_data; + std::string _font_data; - string _name; + std::string _name; FT_Face _face; int _char_size; int _dpi; diff --git a/panda/src/pnmtext/freetypeFont.I b/panda/src/pnmtext/freetypeFont.I index 897100998b..dc0f4ae60b 100644 --- a/panda/src/pnmtext/freetypeFont.I +++ b/panda/src/pnmtext/freetypeFont.I @@ -207,7 +207,7 @@ get_winding_order() const { */ INLINE FT_Face FreetypeFont:: acquire_face() const { - nassertr(_face != NULL, NULL); + nassertr(_face != nullptr, nullptr); return _face->acquire_face(_char_size, _dpi, _pixel_width, _pixel_height); } @@ -217,7 +217,7 @@ acquire_face() const { */ INLINE void FreetypeFont:: release_face(FT_Face face) const { - nassertv(_face != NULL); + nassertv(_face != nullptr); _face->release_face(face); } diff --git a/panda/src/pnmtext/freetypeFont.cxx b/panda/src/pnmtext/freetypeFont.cxx index 379a139426..f922943b7f 100644 --- a/panda/src/pnmtext/freetypeFont.cxx +++ b/panda/src/pnmtext/freetypeFont.cxx @@ -25,6 +25,10 @@ #undef interface // I don't know where this symbol is defined, but it interferes with FreeType. #include FT_OUTLINE_H +using std::istream; +using std::ostream; +using std::string; + // This constant determines how big a particular point size font appears to // be. By convention, 10 points is 1 unit (e.g. 1 foot) high. const PN_stdfloat FreetypeFont::_points_per_unit = 10.0f; @@ -37,7 +41,7 @@ const PN_stdfloat FreetypeFont::_points_per_inch = 72.0f; */ FreetypeFont:: FreetypeFont() { - _face = NULL; + _face = nullptr; _point_size = text_point_size; _requested_pixels_per_unit = text_pixels_per_unit; @@ -183,7 +187,7 @@ load_font(const char *font_data, int data_length, int face_index) { */ void FreetypeFont:: unload_font() { - _face = NULL; + _face = nullptr; } /** @@ -297,7 +301,7 @@ copy_bitmap_to_pnmimage(const FT_Bitmap &bitmap, PNMImage &image) { */ bool FreetypeFont:: reset_scale() { - if (_face == NULL) { + if (_face == nullptr) { return false; } @@ -461,7 +465,7 @@ render_distance_field(PNMImage &image, int outline, int min_x, int min_y) { } } else { - dist_sq = min((p - begin).length_squared(), (p - end).length_squared()); + dist_sq = std::min((p - begin).length_squared(), (p - end).length_squared()); if (begin[1] <= p[1]) { if (end[1] > p[1]) { if ((v[0] * (p[1] - begin[1]) > v[1] * (p[0] - begin[0]))) { @@ -503,7 +507,7 @@ render_distance_field(PNMImage &image, int outline, int min_x, int min_y) { } } - min_dist_sq = min(min_dist_sq, dist_sq); + min_dist_sq = std::min(min_dist_sq, dist_sq); } } // Determine the sign based on whether we're inside the contour. diff --git a/panda/src/pnmtext/freetypeFont.h b/panda/src/pnmtext/freetypeFont.h index a33059f3d7..dc89b09218 100644 --- a/panda/src/pnmtext/freetypeFont.h +++ b/panda/src/pnmtext/freetypeFont.h @@ -85,7 +85,7 @@ PUBLISHED: MAKE_PROPERTY(winding_order, get_winding_order, set_winding_order); public: - static WindingOrder string_winding_order(const string &string); + static WindingOrder string_winding_order(const std::string &string); protected: INLINE FT_Face acquire_face() const; @@ -163,8 +163,8 @@ protected: #include "freetypeFont.I" -EXPCL_PANDA_PNMTEXT ostream &operator << (ostream &out, FreetypeFont::WindingOrder wo); -EXPCL_PANDA_PNMTEXT istream &operator >> (istream &in, FreetypeFont::WindingOrder &wo); +EXPCL_PANDA_PNMTEXT std::ostream &operator << (std::ostream &out, FreetypeFont::WindingOrder wo); +EXPCL_PANDA_PNMTEXT std::istream &operator >> (std::istream &in, FreetypeFont::WindingOrder &wo); #endif // HAVE_FREETYPE diff --git a/panda/src/pnmtext/pnmTextGlyph.cxx b/panda/src/pnmtext/pnmTextGlyph.cxx index 833febd98c..d52e415c02 100644 --- a/panda/src/pnmtext/pnmTextGlyph.cxx +++ b/panda/src/pnmtext/pnmTextGlyph.cxx @@ -14,6 +14,9 @@ #include "pnmTextGlyph.h" #include "indent.h" +using std::max; +using std::min; + /** * */ diff --git a/panda/src/pnmtext/pnmTextMaker.I b/panda/src/pnmtext/pnmTextMaker.I index c8cce09b52..96eb380976 100644 --- a/panda/src/pnmtext/pnmTextMaker.I +++ b/panda/src/pnmtext/pnmTextMaker.I @@ -122,7 +122,7 @@ get_distance_field_radius() const { * position; the return value is the total width in pixels. */ INLINE int PNMTextMaker:: -generate_into(const string &text, PNMImage &dest_image, int x, int y) { +generate_into(const std::string &text, PNMImage &dest_image, int x, int y) { TextEncoder encoder; encoder.set_text(text); return generate_into(encoder.get_wtext(), dest_image, x, y); @@ -132,7 +132,7 @@ generate_into(const string &text, PNMImage &dest_image, int x, int y) { * Returns the width in pixels of the indicated line of text. */ INLINE int PNMTextMaker:: -calc_width(const string &text) { +calc_width(const std::string &text) { TextEncoder encoder; encoder.set_text(text); return calc_width(encoder.get_wtext()); diff --git a/panda/src/pnmtext/pnmTextMaker.cxx b/panda/src/pnmtext/pnmTextMaker.cxx index 1c11dac21c..8a22fff510 100644 --- a/panda/src/pnmtext/pnmTextMaker.cxx +++ b/panda/src/pnmtext/pnmTextMaker.cxx @@ -18,6 +18,8 @@ #include FT_OUTLINE_H +using std::wstring; + /** * The constructor expects the name of some font file that FreeType can read, * along with face_index, indicating which font within the file to load @@ -171,7 +173,7 @@ make_glyph(int glyph_index) { FT_Face face = acquire_face(); if (!load_glyph(face, glyph_index)) { release_face(face); - return (PNMTextGlyph *)NULL; + return nullptr; } FT_GlyphSlot slot = face->glyph; diff --git a/panda/src/pnmtext/pnmTextMaker.h b/panda/src/pnmtext/pnmTextMaker.h index 4ae8f04069..213298f81c 100644 --- a/panda/src/pnmtext/pnmTextMaker.h +++ b/panda/src/pnmtext/pnmTextMaker.h @@ -63,12 +63,12 @@ PUBLISHED: INLINE void set_distance_field_radius(int radius); INLINE int get_distance_field_radius() const; - INLINE int generate_into(const string &text, + INLINE int generate_into(const std::string &text, PNMImage &dest_image, int x, int y); - int generate_into(const wstring &text, + int generate_into(const std::wstring &text, PNMImage &dest_image, int x, int y); - INLINE int calc_width(const string &text); - int calc_width(const wstring &text); + INLINE int calc_width(const std::string &text); + int calc_width(const std::wstring &text); PNMTextGlyph *get_glyph(int character); diff --git a/panda/src/pstatclient/pStatClient.I b/panda/src/pstatclient/pStatClient.I index 8ce9381978..452c165901 100644 --- a/panda/src/pstatclient/pStatClient.I +++ b/panda/src/pstatclient/pStatClient.I @@ -25,7 +25,7 @@ get_num_collectors() const { */ INLINE PStatCollectorDef *PStatClient:: get_collector_def(int index) const { - nassertr(index >= 0 && index < _num_collectors, NULL); + nassertr(index >= 0 && index < _num_collectors, nullptr); return get_collector_ptr(index)->get_def(this, index); } @@ -42,32 +42,29 @@ get_num_threads() const { /** * Returns the name of the indicated thread. */ -INLINE string PStatClient:: +INLINE std::string PStatClient:: get_thread_name(int index) const { - nassertr(index >= 0 && index < AtomicAdjust::get(_num_threads), string()); + nassertr(index >= 0 && index < AtomicAdjust::get(_num_threads), std::string()); return get_thread_ptr(index)->_name; } /** * Returns the sync_name of the indicated thread. */ -INLINE string PStatClient:: +INLINE std::string PStatClient:: get_thread_sync_name(int index) const { - nassertr(index >= 0 && index < AtomicAdjust::get(_num_threads), string()); + nassertr(index >= 0 && index < AtomicAdjust::get(_num_threads), std::string()); return get_thread_ptr(index)->_sync_name; } /** * Returns the Panda Thread object associated with the indicated PStatThread. */ -INLINE Thread *PStatClient:: +INLINE PT(Thread) PStatClient:: get_thread_object(int index) const { - nassertr(index >= 0 && index < AtomicAdjust::get(_num_threads), NULL); + nassertr(index >= 0 && index < AtomicAdjust::get(_num_threads), nullptr); InternalThread *thread = get_thread_ptr(index); - if (thread->_thread.was_deleted()) { - return NULL; - } - return thread->_thread; + return thread->_thread.lock(); } /** @@ -75,7 +72,7 @@ get_thread_object(int index) const { * true if successful, false on failure. */ INLINE bool PStatClient:: -connect(const string &hostname, int port) { +connect(const std::string &hostname, int port) { return get_global_pstats()->client_connect(hostname, port); } @@ -112,7 +109,7 @@ resume_after_pause() { */ INLINE bool PStatClient:: has_impl() const { - return (_impl != (PStatClientImpl *)NULL); + return (_impl != nullptr); } /** @@ -122,7 +119,7 @@ has_impl() const { INLINE PStatClientImpl *PStatClient:: get_impl() { ReMutexHolder holder(_lock); - if (_impl == (PStatClientImpl *)NULL) { + if (_impl == nullptr) { make_impl(); } return _impl; @@ -135,7 +132,7 @@ get_impl() { INLINE const PStatClientImpl *PStatClient:: get_impl() const { ReMutexHolder holder(_lock); - if (_impl == (PStatClientImpl *)NULL) { + if (_impl == nullptr) { make_impl(); } return _impl; @@ -164,8 +161,8 @@ get_thread_ptr(int thread_index) const { * */ INLINE PStatClient::Collector:: -Collector(int parent_index, const string &name) : - _def(NULL), +Collector(int parent_index, const std::string &name) : + _def(nullptr), _parent_index(parent_index), _name(name) { @@ -182,7 +179,7 @@ get_parent_index() const { /** * */ -INLINE const string &PStatClient::Collector:: +INLINE const std::string &PStatClient::Collector:: get_name() const { return _name; } @@ -194,7 +191,7 @@ get_name() const { */ INLINE bool PStatClient::Collector:: is_active() const { - return _def != (PStatCollectorDef *)NULL && _def->_is_active; + return _def != nullptr && _def->_is_active; } /** @@ -203,7 +200,7 @@ is_active() const { */ INLINE PStatCollectorDef *PStatClient::Collector:: get_def(const PStatClient *client, int this_index) const { - if (_def == (PStatCollectorDef *)NULL) { + if (_def == nullptr) { ((Collector *)this)->make_def(client, this_index); } diff --git a/panda/src/pstatclient/pStatClient.cxx b/panda/src/pstatclient/pStatClient.cxx index a735ea080e..c69e1ea032 100644 --- a/panda/src/pstatclient/pStatClient.cxx +++ b/panda/src/pstatclient/pStatClient.cxx @@ -27,6 +27,8 @@ #include "clockObject.h" #include "neverFreeMemory.h" +using std::string; + PStatCollector PStatClient::_heap_total_size_pcollector("System memory:Heap"); PStatCollector PStatClient::_heap_overhead_size_pcollector("System memory:Heap:Overhead"); PStatCollector PStatClient::_heap_single_size_pcollector("System memory:Heap:Single"); @@ -44,7 +46,7 @@ PStatCollector PStatClient::_clock_wait_pcollector("Wait:Clock Wait:Sleep"); PStatCollector PStatClient::_clock_busy_wait_pcollector("Wait:Clock Wait:Spin"); PStatCollector PStatClient::_thread_block_pcollector("Wait:Thread block"); -PStatClient *PStatClient::_global_pstats = NULL; +PStatClient *PStatClient::_global_pstats = nullptr; // This class is used to report memory usage per TypeHandle. We create one of @@ -73,13 +75,13 @@ PerThreadData() { PStatClient:: PStatClient() : _lock("PStatClient::_lock"), - _impl(NULL) + _impl(nullptr) { - _collectors = NULL; + _collectors = nullptr; _collectors_size = 0; _num_collectors = 0; - _threads = NULL; + _threads = nullptr; _threads_size = 0; _num_threads = 0; @@ -334,7 +336,7 @@ main_tick() { // Not used. break; } - ostringstream strm; + std::ostringstream strm; strm << "System memory:" << category << ":" << type; col = PStatCollector(strm.str()); } @@ -457,7 +459,7 @@ client_disconnect() { if (has_impl()) { _impl->client_disconnect(); delete _impl; - _impl = NULL; + _impl = nullptr; } ThreadPointer *threads = (ThreadPointer *)_threads; @@ -508,7 +510,7 @@ client_resume_after_pause() { */ PStatClient *PStatClient:: get_global_pstats() { - if (_global_pstats == (PStatClient *)NULL) { + if (_global_pstats == nullptr) { _global_pstats = new PStatClient; ClockObject::_start_clock_wait = start_clock_wait; @@ -1129,7 +1131,7 @@ deactivate_hook(Thread *thread) { // We shouldn't use a mutex here, because this code is only called during // the SIMPLE_THREADS case, so a mutex isn't necessary; and because we are // called during a context switch, so a mutex might be dangerous. - if (_impl == NULL) { + if (_impl == nullptr) { return; } int thread_index = thread->get_pstats_index(); @@ -1154,7 +1156,7 @@ activate_hook(Thread *thread) { // We shouldn't use a mutex here, because this code is only called during // the SIMPLE_THREADS case, so a mutex isn't necessary; and because we are // called during a context switch, so a mutex might be dangerous. - if (_impl == NULL) { + if (_impl == nullptr) { return; } @@ -1173,7 +1175,7 @@ activate_hook(Thread *thread) { void PStatClient::Collector:: make_def(const PStatClient *client, int this_index) { ReMutexHolder holder(client->_lock); - if (_def == (PStatCollectorDef *)NULL) { + if (_def == nullptr) { _def = new PStatCollectorDef(this_index, _name); if (_parent_index != this_index) { const PStatCollectorDef *parent_def = @@ -1205,7 +1207,7 @@ InternalThread(Thread *thread) : */ PStatClient::InternalThread:: InternalThread(const string &name, const string &sync_name) : - _thread(NULL), + _thread(nullptr), _name(name), _sync_name(sync_name), _is_active(false), diff --git a/panda/src/pstatclient/pStatClient.h b/panda/src/pstatclient/pStatClient.h index 2d285c6f8a..bdcdb4eb20 100644 --- a/panda/src/pstatclient/pStatClient.h +++ b/panda/src/pstatclient/pStatClient.h @@ -56,8 +56,8 @@ public: ~PStatClient(); PUBLISHED: - void set_client_name(const string &name); - string get_client_name() const; + void set_client_name(const std::string &name); + std::string get_client_name() const; void set_max_rate(double rate); double get_max_rate() const; @@ -65,15 +65,15 @@ PUBLISHED: PStatCollector get_collector(int index) const; MAKE_SEQ(get_collectors, get_num_collectors, get_collector); INLINE PStatCollectorDef *get_collector_def(int index) const; - string get_collector_name(int index) const; - string get_collector_fullname(int index) const; + std::string get_collector_name(int index) const; + std::string get_collector_fullname(int index) const; INLINE int get_num_threads() const; PStatThread get_thread(int index) const; MAKE_SEQ(get_threads, get_num_threads, get_thread); - INLINE string get_thread_name(int index) const; - INLINE string get_thread_sync_name(int index) const; - INLINE Thread *get_thread_object(int index) const; + INLINE std::string get_thread_name(int index) const; + INLINE std::string get_thread_sync_name(int index) const; + INLINE PT(Thread) get_thread_object(int index) const; PStatThread get_main_thread() const; PStatThread get_current_thread() const; @@ -88,18 +88,18 @@ PUBLISHED: MAKE_PROPERTY(current_thread, get_current_thread); MAKE_PROPERTY(real_time, get_real_time); - INLINE static bool connect(const string &hostname = string(), int port = -1); + INLINE static bool connect(const std::string &hostname = std::string(), int port = -1); INLINE static void disconnect(); INLINE static bool is_connected(); INLINE static void resume_after_pause(); static void main_tick(); - static void thread_tick(const string &sync_name); + static void thread_tick(const std::string &sync_name); void client_main_tick(); - void client_thread_tick(const string &sync_name); - bool client_connect(string hostname, int port); + void client_thread_tick(const std::string &sync_name); + bool client_connect(std::string hostname, int port); void client_disconnect(); bool client_is_connected() const; @@ -113,12 +113,12 @@ private: INLINE const PStatClientImpl *get_impl() const; void make_impl() const; - PStatCollector make_collector_with_relname(int parent_index, string relname); - PStatCollector make_collector_with_name(int parent_index, const string &name); + PStatCollector make_collector_with_relname(int parent_index, std::string relname); + PStatCollector make_collector_with_name(int parent_index, const std::string &name); PStatThread do_get_current_thread() const; PStatThread make_thread(Thread *thread); PStatThread do_make_thread(Thread *thread); - PStatThread make_gpu_thread(const string &name); + PStatThread make_gpu_thread(const std::string &name); bool is_active(int collector_index, int thread_index) const; bool is_started(int collector_index, int thread_index) const; @@ -152,8 +152,8 @@ private: // This mutex protects everything in this class. ReMutex _lock; - typedef pmap ThingsByName; - typedef pmap MultiThingsByName; + typedef pmap ThingsByName; + typedef pmap MultiThingsByName; MultiThingsByName _threads_by_name, _threads_by_sync_name; // This is for the data that is per-collector, per-thread. A vector of @@ -169,11 +169,11 @@ private: // This is where the meat of the Collector data is stored. (All the stuff // in PStatCollector and PStatCollectorDef is just fluff.) - class Collector { + class EXPCL_PANDA_PSTATCLIENT Collector { public: - INLINE Collector(int parent_index, const string &name); + INLINE Collector(int parent_index, const std::string &name); INLINE int get_parent_index() const; - INLINE const string &get_name() const; + INLINE const std::string &get_name() const; INLINE bool is_active() const; INLINE PStatCollectorDef *get_def(const PStatClient *client, int this_index) const; @@ -187,7 +187,7 @@ private: // This data is used to create the PStatCollectorDef when it is needed. int _parent_index; - string _name; + std::string _name; public: // Relations to other collectors. @@ -205,11 +205,11 @@ private: class InternalThread { public: InternalThread(Thread *thread); - InternalThread(const string &name, const string &sync_name = "Main"); + InternalThread(const std::string &name, const std::string &sync_name = "Main"); WPT(Thread) _thread; - string _name; - string _sync_name; + std::string _name; + std::string _sync_name; PStatFrameData _frame_data; bool _is_active; int _frame_number; @@ -266,13 +266,13 @@ public: ~PStatClient() { } PUBLISHED: - INLINE static bool connect(const string & = string(), int = -1) { return false; } + INLINE static bool connect(const std::string & = std::string(), int = -1) { return false; } INLINE static void disconnect() { } INLINE static bool is_connected() { return false; } INLINE static void resume_after_pause() { } INLINE static void main_tick() { } - INLINE static void thread_tick(const string &) { } + INLINE static void thread_tick(const std::string &) { } }; #endif // DO_PSTATS diff --git a/panda/src/pstatclient/pStatClientControlMessage.h b/panda/src/pstatclient/pStatClientControlMessage.h index b815f3f558..97e7dede98 100644 --- a/panda/src/pstatclient/pStatClientControlMessage.h +++ b/panda/src/pstatclient/pStatClientControlMessage.h @@ -45,8 +45,8 @@ public: Type _type; // Used for T_hello - string _client_hostname; - string _client_progname; + std::string _client_hostname; + std::string _client_progname; int _major_version; int _minor_version; @@ -55,7 +55,7 @@ public: // Used for T_define_threads int _first_thread_index; - pvector _names; + pvector _names; }; diff --git a/panda/src/pstatclient/pStatClientImpl.I b/panda/src/pstatclient/pStatClientImpl.I index 95f6f13740..8e38b9a486 100644 --- a/panda/src/pstatclient/pStatClientImpl.I +++ b/panda/src/pstatclient/pStatClientImpl.I @@ -16,14 +16,14 @@ * will presumably be written in the title bar or something. */ INLINE void PStatClientImpl:: -set_client_name(const string &name) { +set_client_name(const std::string &name) { _client_name = name; } /** * Retrieves the name of the client as set. */ -INLINE string PStatClientImpl:: +INLINE std::string PStatClientImpl:: get_client_name() const { return _client_name; } diff --git a/panda/src/pstatclient/pStatClientImpl.cxx b/panda/src/pstatclient/pStatClientImpl.cxx index d126c6c753..d607a53bd9 100644 --- a/panda/src/pstatclient/pStatClientImpl.cxx +++ b/panda/src/pstatclient/pStatClientImpl.cxx @@ -85,7 +85,7 @@ PStatClientImpl:: * Called only by PStatClient::client_connect(). */ bool PStatClientImpl:: -client_connect(string hostname, int port) { +client_connect(std::string hostname, int port) { nassertr(!_is_connected, true); if (hostname.empty()) { @@ -372,7 +372,7 @@ transmit_control_data() { /** * Returns the current machine's hostname. */ -string PStatClientImpl:: +std::string PStatClientImpl:: get_hostname() { if (_hostname.empty()) { char temp_buff[1024]; diff --git a/panda/src/pstatclient/pStatClientImpl.h b/panda/src/pstatclient/pStatClientImpl.h index 88327defb5..598a2e63e7 100644 --- a/panda/src/pstatclient/pStatClientImpl.h +++ b/panda/src/pstatclient/pStatClientImpl.h @@ -51,15 +51,15 @@ public: PStatClientImpl(PStatClient *client); ~PStatClientImpl(); - INLINE void set_client_name(const string &name); - INLINE string get_client_name() const; + INLINE void set_client_name(const std::string &name); + INLINE std::string get_client_name() const; INLINE void set_max_rate(double rate); INLINE double get_max_rate() const; INLINE double get_real_time() const; INLINE void client_main_tick(); - bool client_connect(string hostname, int port); + bool client_connect(std::string hostname, int port); void client_disconnect(); INLINE bool client_is_connected() const; @@ -79,7 +79,7 @@ private: double _last_frame; // Networking stuff - string get_hostname(); + std::string get_hostname(); void send_hello(); void report_new_collectors(); void report_new_threads(); @@ -103,8 +103,8 @@ private: int _collectors_reported; int _threads_reported; - string _hostname; - string _client_name; + std::string _hostname; + std::string _client_name; double _max_rate; double _tcp_count_factor; diff --git a/panda/src/pstatclient/pStatCollector.I b/panda/src/pstatclient/pStatCollector.I index f103bbbae0..710d803e3e 100644 --- a/panda/src/pstatclient/pStatCollector.I +++ b/panda/src/pstatclient/pStatCollector.I @@ -25,20 +25,6 @@ PStatCollector(PStatClient *client, int index) : { } -/** - * Creates an invalid PStatCollector. Any attempt to use this collector will - * crash messily. - * - * You can reassign it to a different, valid one later. - */ -INLINE PStatCollector:: -PStatCollector() : - _client(NULL), - _index(0), - _level(0.0f) -{ -} - /** * Creates a new PStatCollector, ready to start accumulating data. The name * of the collector uniquely identifies it among the other collectors; if two @@ -54,10 +40,10 @@ PStatCollector() : * register the collector with; otherwise, the global client is used. */ INLINE PStatCollector:: -PStatCollector(const string &name, PStatClient *client) : +PStatCollector(const std::string &name, PStatClient *client) : _level(0.0f) { - if (client == (PStatClient *)NULL) { + if (client == nullptr) { client = PStatClient::get_global_pstats(); } (*this) = client->make_collector_with_relname(0, name); @@ -80,10 +66,10 @@ PStatCollector(const string &name, PStatClient *client) : * collector on the same client as its parent. */ INLINE PStatCollector:: -PStatCollector(const PStatCollector &parent, const string &name) : +PStatCollector(const PStatCollector &parent, const std::string &name) : _level(0.0f) { - nassertv(parent._client != (PStatClient *)NULL); + nassertv(parent._client != nullptr); (*this) = parent._client->make_collector_with_relname(parent._index, name); } @@ -115,38 +101,38 @@ operator = (const PStatCollector ©) { */ INLINE bool PStatCollector:: is_valid() const { - return (_client != (PStatClient *)NULL); + return (_client != nullptr); } /** * Returns the local name of this collector. This is the rightmost part of * the fullname, after the rightmost colon. */ -INLINE string PStatCollector:: +INLINE std::string PStatCollector:: get_name() const { - if (_client != (PStatClient *)NULL) { + if (_client != nullptr) { return _client->get_collector_name(_index); } - return string(); + return std::string(); } /** * Returns the full name of this collector. This includes the names of all * the collector's parents, concatenated together with colons. */ -INLINE string PStatCollector:: +INLINE std::string PStatCollector:: get_fullname() const { - if (_client != (PStatClient *)NULL) { + if (_client != nullptr) { return _client->get_collector_fullname(_index); } - return string(); + return std::string(); } /** * */ INLINE void PStatCollector:: -output(ostream &out) const { +output(std::ostream &out) const { out << "PStatCollector(\"" << get_fullname() << "\")"; } @@ -384,7 +370,7 @@ is_started(const PStatThread &thread) { */ INLINE void PStatCollector:: start(const PStatThread &thread) { - nassertv(_client != NULL); + nassertv(_client != nullptr); _client->start(_index, thread._index); } @@ -494,11 +480,11 @@ PStatCollector() * defined, meaning all these functions should compile to nothing. */ INLINE PStatCollector:: -PStatCollector(const string &, PStatClient *client) { +PStatCollector(const std::string &, PStatClient *client) { // We need this bogus comparison just to prevent the SGI compiler from // dumping core. It's perfectly meaningless. #ifdef mips - if (client == (PStatClient *)NULL) { + if (client == nullptr) { return; } #endif @@ -509,11 +495,11 @@ PStatCollector(const string &, PStatClient *client) { * defined, meaning all these functions should compile to nothing. */ INLINE PStatCollector:: -PStatCollector(const PStatCollector &parent, const string &) { +PStatCollector(const PStatCollector &parent, const std::string &) { // We need this bogus comparison just to prevent the SGI compiler from // dumping core. It's perfectly meaningless. #ifdef mips - if (&parent == (const PStatCollector *)NULL) { + if (&parent == nullptr) { return; } #endif diff --git a/panda/src/pstatclient/pStatCollector.h b/panda/src/pstatclient/pStatCollector.h index 6c265f5e0c..aeb74f7cdb 100644 --- a/panda/src/pstatclient/pStatCollector.h +++ b/panda/src/pstatclient/pStatCollector.h @@ -47,21 +47,21 @@ private: INLINE PStatCollector(PStatClient *client, int index); public: - INLINE PStatCollector(); + PStatCollector() = default; PUBLISHED: - INLINE explicit PStatCollector(const string &name, - PStatClient *client = NULL); + INLINE explicit PStatCollector(const std::string &name, + PStatClient *client = nullptr); INLINE explicit PStatCollector(const PStatCollector &parent, - const string &name); + const std::string &name); INLINE PStatCollector(const PStatCollector ©); INLINE void operator = (const PStatCollector ©); INLINE bool is_valid() const; - INLINE string get_name() const; - INLINE string get_fullname() const; - INLINE void output(ostream &out) const; + INLINE std::string get_name() const; + INLINE std::string get_fullname() const; + INLINE void output(std::ostream &out) const; INLINE bool is_active(); INLINE bool is_started(); @@ -99,9 +99,9 @@ PUBLISHED: INLINE int get_index() const; private: - PStatClient *_client; - int _index; - double _level; + PStatClient *_client = nullptr; + int _index = 0; + double _level = 0.0; friend class PStatClient; @@ -110,10 +110,10 @@ public: INLINE PStatCollector(); PUBLISHED: - INLINE PStatCollector(const string &name, - PStatClient *client = NULL); + INLINE PStatCollector(const std::string &name, + PStatClient *client = nullptr); INLINE PStatCollector(const PStatCollector &parent, - const string &name); + const std::string &name); INLINE bool is_active() { return false; } INLINE bool is_started() { return false; } @@ -148,7 +148,7 @@ PUBLISHED: #include "pStatCollector.I" -inline ostream &operator << (ostream &out, const PStatCollector &pcol) { +inline std::ostream &operator << (std::ostream &out, const PStatCollector &pcol) { #ifdef DO_PSTATS pcol.output(out); #endif // DO_PSTATS diff --git a/panda/src/pstatclient/pStatCollectorDef.cxx b/panda/src/pstatclient/pStatCollectorDef.cxx index 13070343e0..bdd0035bba 100644 --- a/panda/src/pstatclient/pStatCollectorDef.cxx +++ b/panda/src/pstatclient/pStatCollectorDef.cxx @@ -38,7 +38,7 @@ PStatCollectorDef() { * */ PStatCollectorDef:: -PStatCollectorDef(int index, const string &name) : +PStatCollectorDef(int index, const std::string &name) : _index(index), _name(name) { diff --git a/panda/src/pstatclient/pStatCollectorDef.h b/panda/src/pstatclient/pStatCollectorDef.h index 79996677f2..443f72a088 100644 --- a/panda/src/pstatclient/pStatCollectorDef.h +++ b/panda/src/pstatclient/pStatCollectorDef.h @@ -29,7 +29,7 @@ class PStatClientVersion; class EXPCL_PANDA_PSTATCLIENT PStatCollectorDef { public: PStatCollectorDef(); - PStatCollectorDef(int index, const string &name); + PStatCollectorDef(int index, const std::string &name); void set_parent(const PStatCollectorDef &parent); void write_datagram(Datagram &destination) const; @@ -40,11 +40,11 @@ public: }; int _index; - string _name; + std::string _name; int _parent_index; ColorDef _suggested_color; int _sort; - string _level_units; + std::string _level_units; double _suggested_scale; double _factor; bool _is_active; diff --git a/panda/src/pstatclient/pStatFrameData.cxx b/panda/src/pstatclient/pStatFrameData.cxx index f15f6bc61e..9c58f8d29d 100644 --- a/panda/src/pstatclient/pStatFrameData.cxx +++ b/panda/src/pstatclient/pStatFrameData.cxx @@ -25,7 +25,7 @@ */ void PStatFrameData:: sort_time() { - stable_sort(_time_data.begin(), _time_data.end()); + std::stable_sort(_time_data.begin(), _time_data.end()); } /** diff --git a/panda/src/pstatclient/pStatProperties.cxx b/panda/src/pstatclient/pStatProperties.cxx index 01411f3f74..cce31e693f 100644 --- a/panda/src/pstatclient/pStatProperties.cxx +++ b/panda/src/pstatclient/pStatProperties.cxx @@ -23,6 +23,8 @@ #include +using std::string; + static const int current_pstat_major_version = 3; static const int current_pstat_minor_version = 0; // Initialized at 2.0 on 51801, when version numbers were first added. @@ -146,7 +148,7 @@ static TimeCollectorProperties time_properties[] = { { 1, "Draw:Set State", { 0.2, 0.6, 0.8 } }, { 1, "Draw:Wait occlusion", { 1.0, 0.5, 0.0 } }, { 1, "Draw:Bind FBO", { 0.0, 0.8, 0.8 } }, - { 0, NULL } + { 0, nullptr } }; static LevelCollectorProperties level_properties[] = { @@ -218,7 +220,7 @@ static LevelCollectorProperties level_properties[] = { { 1, "Collision Volumes", { 1.0, 0.8, 0.5 }, "", 500 }, { 1, "Collision Tests", { 0.5, 0.8, 1.0 }, "", 100 }, { 1, "Command latency", { 0.8, 0.2, 0.0 }, "ms", 10, 1.0 / 1000.0 }, - { 0, NULL } + { 0, nullptr } }; @@ -231,7 +233,7 @@ initialize_collector_def_from_table(const string &fullname, PStatCollectorDef *d int i; for (i = 0; - time_properties[i].name != (const char *)NULL; + time_properties[i].name != nullptr; i++) { const TimeCollectorProperties &tp = time_properties[i]; if (fullname == tp.name) { @@ -248,7 +250,7 @@ initialize_collector_def_from_table(const string &fullname, PStatCollectorDef *d } for (i = 0; - level_properties[i].name != (const char *)NULL; + level_properties[i].name != nullptr; i++) { const LevelCollectorProperties &lp = level_properties[i]; if (fullname == lp.name) { @@ -260,7 +262,7 @@ initialize_collector_def_from_table(const string &fullname, PStatCollectorDef *d if (lp.suggested_scale != 0.0) { def->_suggested_scale = lp.suggested_scale; } - if (lp.units != (const char *)NULL) { + if (lp.units != nullptr) { def->_level_units = lp.units; } if (lp.inv_factor != 0.0) { diff --git a/panda/src/pstatclient/pStatServerControlMessage.h b/panda/src/pstatclient/pStatServerControlMessage.h index 332a850530..ffcf19e836 100644 --- a/panda/src/pstatclient/pStatServerControlMessage.h +++ b/panda/src/pstatclient/pStatServerControlMessage.h @@ -39,8 +39,8 @@ public: Type _type; // Used for T_hello - string _server_hostname; - string _server_progname; + std::string _server_hostname; + std::string _server_progname; int _udp_port; }; diff --git a/panda/src/pstatclient/pStatThread.I b/panda/src/pstatclient/pStatThread.I index 4fd43c5669..fb68d4d3f9 100644 --- a/panda/src/pstatclient/pStatThread.I +++ b/panda/src/pstatclient/pStatThread.I @@ -37,7 +37,7 @@ PStatThread(PStatClient *client, int index) : INLINE PStatThread:: PStatThread(Thread *thread, PStatClient *client) { #ifdef DO_PSTATS - if (client == (PStatClient *)NULL) { + if (client == nullptr) { client = PStatClient::get_global_pstats(); } @@ -51,7 +51,7 @@ PStatThread(Thread *thread, PStatClient *client) { (*this) = client->make_thread(thread); } #else - _client = (PStatClient *)NULL; + _client = nullptr; _index = 0; #endif } diff --git a/panda/src/pstatclient/pStatThread.h b/panda/src/pstatclient/pStatThread.h index 0ad8567c7a..74defa2a15 100644 --- a/panda/src/pstatclient/pStatThread.h +++ b/panda/src/pstatclient/pStatThread.h @@ -31,7 +31,7 @@ public: PUBLISHED: INLINE PStatThread(PStatClient *client, int index); - INLINE PStatThread(Thread *thread, PStatClient *client = NULL); + INLINE PStatThread(Thread *thread, PStatClient *client = nullptr); INLINE PStatThread(const PStatThread ©); INLINE void operator = (const PStatThread ©); diff --git a/panda/src/pstatclient/pStatTimer.h b/panda/src/pstatclient/pStatTimer.h index b7a32f27e2..4cfca5a7d2 100644 --- a/panda/src/pstatclient/pStatTimer.h +++ b/panda/src/pstatclient/pStatTimer.h @@ -27,7 +27,7 @@ class Thread; * and when the PStatTimer variable goes out of scope (for instance, at the * end of the function), it will automatically stop the Collector. */ -class EXPCL_PANDA_PSTATCLIENT PStatTimer { +class PStatTimer { public: #ifdef DO_PSTATS INLINE PStatTimer(PStatCollector &collector); diff --git a/panda/src/pstatclient/test_client.cxx b/panda/src/pstatclient/test_client.cxx index 35a79a8cbd..8151b808d2 100644 --- a/panda/src/pstatclient/test_client.cxx +++ b/panda/src/pstatclient/test_client.cxx @@ -45,13 +45,13 @@ SampleData dataset_zero[] = { { "Cull", 5, 6, false }, { "App", 0, 5, false }, { "Texture memory", 8000000, 100000, true }, - { NULL }, + { nullptr }, }; SampleData dataset_one[] = { { "Draw", 10, 12, false }, { "Squeak", 25, 30, false }, - { NULL }, + { nullptr }, }; SampleData dataset_two[] = { @@ -63,7 +63,7 @@ SampleData dataset_two[] = { { "Animation:donald", 5, 6, false }, { "Animation:goofy", 5, 6, false }, { "Animation:pluto", 5, 6, false }, - { NULL }, + { nullptr }, }; #define NUM_DATASETS 3 @@ -85,7 +85,7 @@ public: int main(int argc, char *argv[]) { - string hostname = "localhost"; + std::string hostname = "localhost"; int port = pstats_port; if (argc > 1) { @@ -113,7 +113,7 @@ main(int argc, char *argv[]) { exit(1); } - srand(time(NULL)); + srand(time(nullptr)); int ds_index; if (argc > 3) { @@ -132,7 +132,7 @@ main(int argc, char *argv[]) { pvector _collectors; int i = 0; - while (ds[i].category != (const char *)NULL) { + while (ds[i].category != nullptr) { _collectors.push_back(PStatCollector(ds[i].category)); if (ds[i].is_level) { _collectors[i].set_level(ds[i].min_ms); diff --git a/panda/src/putil/animInterface.I b/panda/src/putil/animInterface.I index c25e748cbb..3d09f34a00 100644 --- a/panda/src/putil/animInterface.I +++ b/panda/src/putil/animInterface.I @@ -266,8 +266,8 @@ get_frac() const { return get_full_fframe() - (double)get_full_frame(0); } -INLINE ostream & -operator << (ostream &out, const AnimInterface &ai) { +INLINE std::ostream & +operator << (std::ostream &out, const AnimInterface &ai) { ai.output(out); return out; } diff --git a/panda/src/putil/animInterface.cxx b/panda/src/putil/animInterface.cxx index 4727b4f907..304e4f95af 100644 --- a/panda/src/putil/animInterface.cxx +++ b/panda/src/putil/animInterface.cxx @@ -18,6 +18,9 @@ #include "datagram.h" #include "datagramIterator.h" +using std::max; +using std::min; + TypeHandle AnimInterface::_type_handle; /** @@ -61,7 +64,7 @@ get_num_frames() const { * */ void AnimInterface:: -output(ostream &out) const { +output(std::ostream &out) const { CDReader cdata(_cycler); cdata->output(out); } @@ -375,7 +378,7 @@ is_playing() const { * */ void AnimInterface::CData:: -output(ostream &out) const { +output(std::ostream &out) const { switch (_play_mode) { case PM_pose: out << "pose, frame " << get_full_fframe(); diff --git a/panda/src/putil/animInterface.h b/panda/src/putil/animInterface.h index 1c3b0ec6e5..80f2a3da9d 100644 --- a/panda/src/putil/animInterface.h +++ b/panda/src/putil/animInterface.h @@ -60,7 +60,7 @@ PUBLISHED: INLINE double get_full_fframe() const; INLINE bool is_playing() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; PUBLISHED: MAKE_PROPERTY(play_rate, get_play_rate, set_play_rate); @@ -113,7 +113,7 @@ private: double get_full_fframe() const; bool is_playing() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; void internal_set_rate(double frame_rate, double play_rate); double get_f() const; @@ -153,7 +153,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const AnimInterface &ai); +INLINE std::ostream &operator << (std::ostream &out, const AnimInterface &ai); #include "animInterface.I" diff --git a/panda/src/putil/autoTextureScale.cxx b/panda/src/putil/autoTextureScale.cxx index ea17b6f08b..f9c27128ce 100644 --- a/panda/src/putil/autoTextureScale.cxx +++ b/panda/src/putil/autoTextureScale.cxx @@ -15,6 +15,10 @@ #include "string_utils.h" #include "config_putil.h" +using std::istream; +using std::ostream; +using std::string; + ostream & operator << (ostream &out, AutoTextureScale ats) { switch (ats) { diff --git a/panda/src/putil/autoTextureScale.h b/panda/src/putil/autoTextureScale.h index b51295881f..3c1e8b5fbe 100644 --- a/panda/src/putil/autoTextureScale.h +++ b/panda/src/putil/autoTextureScale.h @@ -26,7 +26,7 @@ enum AutoTextureScale { }; END_PUBLISH -EXPCL_PANDA_PUTIL ostream &operator << (ostream &out, AutoTextureScale ats); -EXPCL_PANDA_PUTIL istream &operator >> (istream &in, AutoTextureScale &ats); +EXPCL_PANDA_PUTIL std::ostream &operator << (std::ostream &out, AutoTextureScale ats); +EXPCL_PANDA_PUTIL std::istream &operator >> (std::istream &in, AutoTextureScale &ats); #endif diff --git a/panda/src/putil/bam.h b/panda/src/putil/bam.h index 2755f0f25d..ad7d000fd2 100644 --- a/panda/src/putil/bam.h +++ b/panda/src/putil/bam.h @@ -22,7 +22,7 @@ // The magic number for a BAM file. It includes a carriage return and newline // character to help detect files damaged due to faulty ASCIIBinary // conversion. -static const string _bam_header = string("pbj\0\n\r", 6); +static const std::string _bam_header = std::string("pbj\0\n\r", 6); static const unsigned short _bam_major_ver = 6; // Bumped to major version 2 on 2000-07-06 due to major changes in Character. diff --git a/panda/src/putil/bamCache.I b/panda/src/putil/bamCache.I index 0d359ad29b..38a9e45540 100644 --- a/panda/src/putil/bamCache.I +++ b/panda/src/putil/bamCache.I @@ -221,7 +221,7 @@ get_read_only() const { */ INLINE BamCache *BamCache:: get_global_ptr() { - if (_global_ptr == (BamCache *)NULL) { + if (_global_ptr == nullptr) { make_global(); } return _global_ptr; @@ -232,7 +232,7 @@ get_global_ptr() { */ INLINE void BamCache:: consider_flush_global_index() { - if (_global_ptr != (BamCache *)NULL) { + if (_global_ptr != nullptr) { _global_ptr->consider_flush_index(); } } @@ -242,7 +242,7 @@ consider_flush_global_index() { */ INLINE void BamCache:: flush_global_index() { - if (_global_ptr != (BamCache *)NULL) { + if (_global_ptr != nullptr) { _global_ptr->flush_index(); } } @@ -254,6 +254,6 @@ flush_global_index() { INLINE void BamCache:: mark_index_stale() { if (_index_stale_since == 0) { - _index_stale_since = time(NULL); + _index_stale_since = time(nullptr); } } diff --git a/panda/src/putil/bamCache.cxx b/panda/src/putil/bamCache.cxx index 94c31665c6..4dbcf06966 100644 --- a/panda/src/putil/bamCache.cxx +++ b/panda/src/putil/bamCache.cxx @@ -27,7 +27,12 @@ #include "configVariableFilename.h" #include "virtualFileSystem.h" -BamCache *BamCache::_global_ptr = NULL; +using std::istream; +using std::ostream; +using std::ostringstream; +using std::string; + +BamCache *BamCache::_global_ptr = nullptr; /** * @@ -101,7 +106,7 @@ BamCache:: ~BamCache() { flush_index(); delete _index; - _index = NULL; + _index = nullptr; } /** @@ -165,7 +170,7 @@ lookup(const Filename &source_filename, const string &cache_extension) { if (rel_pathname.is_local()) { // If the source pathname is already within the cache directory, don't // cache it further. - return NULL; + return nullptr; } Filename cache_filename = hash_filename(source_pathname.get_fullpath()); @@ -199,7 +204,7 @@ store(BamCacheRecord *record) { nassertr(rel_pathname.is_local(), false); #endif // NDEBUG - record->_recorded_time = time(NULL); + record->_recorded_time = time(nullptr); Filename cache_pathname = Filename::binary_filename(record->_cache_pathname); @@ -311,7 +316,7 @@ emergency_read_only() { void BamCache:: consider_flush_index() { #if defined(HAVE_THREADS) || defined(DEBUG_THREADS) - if (!_lock.try_acquire()) { + if (!_lock.try_lock()) { // If we can't grab the lock, no big deal. We don't want to hold up // the frame waiting for a cache operation. We can try again later. return; @@ -319,14 +324,14 @@ consider_flush_index() { #endif if (_index_stale_since != 0) { - int elapsed = (int)time(NULL) - (int)_index_stale_since; + int elapsed = (int)time(nullptr) - (int)_index_stale_since; if (elapsed > _flush_time) { flush_index(); } } #if defined(HAVE_THREADS) || defined(DEBUG_THREADS) - _lock.release(); + _lock.unlock(); #endif } @@ -404,7 +409,7 @@ read_index() { while (true) { BamCacheIndex *new_index = do_read_index(_index_pathname); - if (new_index != (BamCacheIndex *)NULL) { + if (new_index != nullptr) { merge_index(new_index); return; } @@ -514,7 +519,7 @@ merge_index(BamCacheIndex *new_index) { if (cache_pathname.exists()) { PT(BamCacheRecord) record = do_read_record(cache_pathname, false); - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { _index->_records.insert(_index->_records.end(), BamCacheIndex::Records::value_type(record->get_source_pathname(), record)); } } @@ -558,7 +563,7 @@ rebuild_index() { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); PT(VirtualFileList) contents = vfs->scan_directory(_root); - if (contents == NULL) { + if (contents == nullptr) { util_cat.error() << "Unable to read directory " << _root << ", caching disabled.\n"; set_active(false); @@ -577,7 +582,7 @@ rebuild_index() { Filename pathname(_root, filename); PT(BamCacheRecord) record = do_read_record(pathname, false); - if (record == (BamCacheRecord *)NULL) { + if (record == nullptr) { // Well, it was invalid, so blow it away. if (util_cat.is_debug()) { util_cat.debug() @@ -599,7 +604,7 @@ rebuild_index() { } _index->process_new_records(); - _index_stale_since = time(NULL); + _index_stale_since = time(nullptr); check_cache_size(); flush_index(); } @@ -642,7 +647,7 @@ check_cache_size() { if (_index->_cache_size / 1024 > _max_kbytes) { while (_index->_cache_size / 1024 > _max_kbytes) { PT(BamCacheRecord) record = _index->evict_old_file(); - if (record == NULL) { + if (record == nullptr) { // Never mind; the cache is empty. break; } @@ -666,53 +671,53 @@ check_cache_size() { BamCacheIndex *BamCache:: do_read_index(const Filename &index_pathname) { if (index_pathname.empty()) { - return NULL; + return nullptr; } DatagramInputFile din; if (!din.open(index_pathname)) { util_cat.debug() << "Could not read index file: " << index_pathname << "\n"; - return NULL; + return nullptr; } string head; if (!din.read_header(head, _bam_header.size())) { util_cat.debug() << index_pathname << " is not an index file.\n"; - return NULL; + return nullptr; } if (head != _bam_header) { util_cat.debug() << index_pathname << " is not an index file.\n"; - return NULL; + return nullptr; } BamReader reader(&din); if (!reader.init()) { - return NULL; + return nullptr; } TypedWritable *object = reader.read_object(); - if (object == (TypedWritable *)NULL) { + if (object == nullptr) { util_cat.error() << "Cache index " << index_pathname << " is empty.\n"; - return NULL; + return nullptr; } else if (!object->is_of_type(BamCacheIndex::get_class_type())) { util_cat.error() << "Cache index " << index_pathname << " contains a " << object->get_type() << ", not a BamCacheIndex.\n"; - return NULL; + return nullptr; } BamCacheIndex *index = DCAST(BamCacheIndex, object); if (!reader.resolve()) { util_cat.error() << "Unable to fully resolve cache index file.\n"; - return NULL; + return nullptr; } return index; @@ -767,7 +772,7 @@ find_and_read_record(const Filename &source_pathname, while (true) { PT(BamCacheRecord) record = read_record(source_pathname, cache_filename, pass); - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { add_to_index(record); return record; } @@ -809,7 +814,7 @@ read_record(const Filename &source_pathname, } PT(BamCacheRecord) record = do_read_record(cache_pathname, true); - if (record == (BamCacheRecord *)NULL) { + if (record == nullptr) { // Well, it was invalid, so blow it away, and make a new one. if (util_cat.is_debug()) { util_cat.debug() @@ -832,7 +837,7 @@ read_record(const Filename &source_pathname, << record->get_source_pathname() << ", not " << source_pathname << "\n"; } - return NULL; + return nullptr; } if (!record->has_data()) { @@ -855,7 +860,7 @@ do_read_record(const Filename &cache_pathname, bool read_data) { util_cat.debug() << "Could not read cache file: " << cache_pathname << "\n"; } - return NULL; + return nullptr; } string head; @@ -864,7 +869,7 @@ do_read_record(const Filename &cache_pathname, bool read_data) { util_cat.debug() << cache_pathname << " is not a cache file.\n"; } - return NULL; + return nullptr; } if (head != _bam_header) { @@ -872,21 +877,21 @@ do_read_record(const Filename &cache_pathname, bool read_data) { util_cat.debug() << cache_pathname << " is not a cache file.\n"; } - return NULL; + return nullptr; } BamReader reader(&din); if (!reader.init()) { - return NULL; + return nullptr; } TypedWritable *object = reader.read_object(); - if (object == (TypedWritable *)NULL) { + if (object == nullptr) { if (util_cat.is_debug()) { util_cat.debug() << cache_pathname << " is empty.\n"; } - return NULL; + return nullptr; } else if (!object->is_of_type(BamCacheRecord::get_class_type())) { if (util_cat.is_debug()) { @@ -894,7 +899,7 @@ do_read_record(const Filename &cache_pathname, bool read_data) { << "Cache file " << cache_pathname << " contains a " << object->get_type() << ", not a BamCacheRecord.\n"; } - return NULL; + return nullptr; } PT(BamCacheRecord) record = DCAST(BamCacheRecord, object); @@ -903,7 +908,7 @@ do_read_record(const Filename &cache_pathname, bool read_data) { util_cat.debug() << "Unable to fully resolve cache record in " << cache_pathname << "\n"; } - return NULL; + return nullptr; } // From this point below, we have validated that the selected filename is @@ -937,7 +942,7 @@ do_read_record(const Filename &cache_pathname, bool read_data) { record->_record_size = vfile->get_file_size(&in); // And the last access time is now, duh. - record->_record_access_time = time(NULL); + record->_record_access_time = time(nullptr); return record; } @@ -966,7 +971,7 @@ hash_filename(const string &filename) { } ostringstream strm; - strm << hex << setw(8) << setfill('0') << hash; + strm << std::hex << std::setw(8) << std::setfill('0') << hash; return strm.str(); #endif // HAVE_OPENSSL diff --git a/panda/src/putil/bamCache.h b/panda/src/putil/bamCache.h index 9b533ce5c5..28b2335ff6 100644 --- a/panda/src/putil/bamCache.h +++ b/panda/src/putil/bamCache.h @@ -72,13 +72,13 @@ PUBLISHED: INLINE bool get_read_only() const; PT(BamCacheRecord) lookup(const Filename &source_filename, - const string &cache_extension); + const std::string &cache_extension); bool store(BamCacheRecord *record); void consider_flush_index(); void flush_index(); - void list_index(ostream &out, int indent_level = 0) const; + void list_index(std::ostream &out, int indent_level = 0) const; INLINE static BamCache *get_global_ptr(); INLINE static void consider_flush_global_index(); @@ -100,7 +100,7 @@ PUBLISHED: private: void read_index(); bool read_index_pathname(Filename &index_pathname, - string &index_ref_contents) const; + std::string &index_ref_contents) const; void merge_index(BamCacheIndex *new_index); void rebuild_index(); INLINE void mark_index_stale(); @@ -123,7 +123,7 @@ private: static PT(BamCacheRecord) do_read_record(const Filename &cache_pathname, bool read_data); - static string hash_filename(const string &filename); + static std::string hash_filename(const std::string &filename); static void make_global(); bool _active; @@ -141,7 +141,7 @@ private: time_t _index_stale_since; Filename _index_pathname; - string _index_ref_contents; + std::string _index_ref_contents; ReMutex _lock; }; diff --git a/panda/src/putil/bamCacheIndex.cxx b/panda/src/putil/bamCacheIndex.cxx index 31c62ec3a5..4455d5362d 100644 --- a/panda/src/putil/bamCacheIndex.cxx +++ b/panda/src/putil/bamCacheIndex.cxx @@ -37,7 +37,7 @@ BamCacheIndex:: * */ void BamCacheIndex:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "BamCacheIndex, " << _records.size() << " records:\n"; @@ -45,13 +45,13 @@ write(ostream &out, int indent_level) const { for (ri = _records.begin(); ri != _records.end(); ++ri) { BamCacheRecord *record = (*ri).second; indent(out, indent_level + 2) - << setw(10) << record->_record_size << " " + << std::setw(10) << record->_record_size << " " << record->get_cache_filename() << " " << record->get_source_pathname() << "\n"; } out << "\n"; indent(out, indent_level) - << setw(12) << _cache_size << " bytes total\n"; + << std::setw(12) << _cache_size << " bytes total\n"; } /** @@ -94,8 +94,8 @@ release_records() { Records::const_iterator ri; for (ri = _records.begin(); ri != _records.end(); ++ri) { BamCacheRecord *record = (*ri).second; - record->_next = NULL; - record->_prev = NULL; + record->_next = nullptr; + record->_prev = nullptr; } _next = this; _prev = this; @@ -110,13 +110,13 @@ PT(BamCacheRecord) BamCacheIndex:: evict_old_file() { if (_next == this) { // Nothing in the cache. - return NULL; + return nullptr; } // The first record in the linked list is the least-recently-used one. PT(BamCacheRecord) record = (BamCacheRecord *)_next; bool removed = remove_record(record->get_source_pathname()); - nassertr(removed, NULL); + nassertr(removed, nullptr); return record; } @@ -129,7 +129,7 @@ evict_old_file() { */ bool BamCacheIndex:: add_record(BamCacheRecord *record) { - pair result = + std::pair result = _records.insert(Records::value_type(record->get_source_pathname(), record)); if (!result.second) { // We already had a record for this filename; it gets replaced. @@ -249,7 +249,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { int num_records = scan.get_uint32(); _record_vector.reserve(num_records); for (int i = 0; i < num_records; ++i) { - _record_vector.push_back(NULL); + _record_vector.push_back(nullptr); manager->read_pointer(scan); } } diff --git a/panda/src/putil/bamCacheIndex.h b/panda/src/putil/bamCacheIndex.h index f7e8c2b7a5..d6f403bbf0 100644 --- a/panda/src/putil/bamCacheIndex.h +++ b/panda/src/putil/bamCacheIndex.h @@ -36,7 +36,7 @@ private: ~BamCacheIndex(); public: - void write(ostream &out, int indent_level = 0) const; + void write(std::ostream &out, int indent_level = 0) const; private: void process_new_records(); @@ -50,7 +50,7 @@ private: typedef pmap Records; Records _records; - streamsize _cache_size; + std::streamsize _cache_size; // This structure is a temporary container. It is only filled in while // reading from a bam file. diff --git a/panda/src/putil/bamCacheRecord.I b/panda/src/putil/bamCacheRecord.I index 6693b1c694..e5288c03ac 100644 --- a/panda/src/putil/bamCacheRecord.I +++ b/panda/src/putil/bamCacheRecord.I @@ -95,7 +95,7 @@ get_dependent_pathname(int n) const { */ INLINE bool BamCacheRecord:: has_data() const { - return (_ptr != (TypedWritable *)NULL); + return (_ptr != nullptr); } /** @@ -104,12 +104,12 @@ has_data() const { */ INLINE void BamCacheRecord:: clear_data() { - if (_ref_ptr != NULL) { + if (_ref_ptr != nullptr) { unref_delete(_ref_ptr); } - _ptr = NULL; - _ref_ptr = NULL; + _ptr = nullptr; + _ref_ptr = nullptr; } /** @@ -135,7 +135,7 @@ extract_data(TypedWritable *&ptr, ReferenceCount *&ref_ptr) { ptr = _ptr; ref_ptr = _ref_ptr; clear_data(); - return (ptr != (TypedWritable *)NULL); + return (ptr != nullptr); } /** @@ -155,7 +155,7 @@ set_data(TypedWritable *ptr, ReferenceCount *ref_ptr) { clear_data(); _ptr = ptr; _ref_ptr = ref_ptr; - if (_ref_ptr != NULL) { + if (_ref_ptr != nullptr) { _ref_ptr->ref(); } } @@ -186,7 +186,7 @@ set_data(TypedWritableReferenceCount *ptr) { INLINE void BamCacheRecord:: set_data(TypedWritable *ptr, int dummy) { nassertv(dummy == 0); - set_data(ptr, (ReferenceCount *)NULL); + set_data(ptr, nullptr); } /** diff --git a/panda/src/putil/bamCacheRecord.cxx b/panda/src/putil/bamCacheRecord.cxx index 8fabae7326..65a3c650f1 100644 --- a/panda/src/putil/bamCacheRecord.cxx +++ b/panda/src/putil/bamCacheRecord.cxx @@ -29,8 +29,8 @@ BamCacheRecord() : _recorded_time(0), _record_size(0), _source_timestamp(0), - _ptr(NULL), - _ref_ptr(NULL), + _ptr(nullptr), + _ref_ptr(nullptr), _record_access_time(0) { } @@ -46,8 +46,8 @@ BamCacheRecord(const Filename &source_pathname, _recorded_time(0), _record_size(0), _source_timestamp(0), - _ptr(NULL), - _ref_ptr(NULL), + _ptr(nullptr), + _ref_ptr(nullptr), _record_access_time(0) { } @@ -62,8 +62,8 @@ BamCacheRecord(const BamCacheRecord ©) : _recorded_time(copy._recorded_time), _record_size(copy._record_size), _source_timestamp(copy._source_timestamp), - _ptr(NULL), - _ref_ptr(NULL), + _ptr(nullptr), + _ref_ptr(nullptr), _record_access_time(copy._record_access_time) { } @@ -93,7 +93,7 @@ dependents_unchanged() const { for (fi = _files.begin(); fi != _files.end(); ++fi) { const DependentFile &dfile = (*fi); PT(VirtualFile) file = vfs->get_file(dfile._pathname); - if (file == (VirtualFile *)NULL) { + if (file == nullptr) { // No such file. if (dfile._timestamp != 0) { if (util_cat.is_debug()) { @@ -153,7 +153,7 @@ add_dependent_file(const Filename &pathname) { dfile._pathname.make_absolute(); PT(VirtualFile) file = vfs->get_file(dfile._pathname); - if (file == (VirtualFile *)NULL) { + if (file == nullptr) { // No such file. dfile._timestamp = 0; dfile._size = 0; @@ -190,7 +190,7 @@ add_dependent_file(const VirtualFile *file) { * */ void BamCacheRecord:: -output(ostream &out) const { +output(std::ostream &out) const { out << "BamCacheRecord " << get_source_pathname(); } @@ -198,7 +198,7 @@ output(ostream &out) const { * */ void BamCacheRecord:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "BamCacheRecord " << get_source_pathname() << "\n"; indent(out, indent_level) @@ -212,7 +212,7 @@ write(ostream &out, int indent_level) const { for (fi = _files.begin(); fi != _files.end(); ++fi) { const DependentFile &dfile = (*fi); indent(out, indent_level + 2) - << setw(10) << dfile._size << " " + << std::setw(10) << dfile._size << " " << format_timestamp(dfile._timestamp) << " " << dfile._pathname << "\n"; } @@ -221,7 +221,7 @@ write(ostream &out, int indent_level) const { /** * Returns a timestamp value formatted nicely for output. */ -string BamCacheRecord:: +std::string BamCacheRecord:: format_timestamp(time_t timestamp) { static const size_t buffer_size = 512; char buffer[buffer_size]; @@ -231,7 +231,7 @@ format_timestamp(time_t timestamp) { return " (no date) "; } - time_t now = time(NULL); + time_t now = time(nullptr); struct tm atm; #ifdef _WIN32 localtime_s(&atm, ×tamp); diff --git a/panda/src/putil/bamCacheRecord.h b/panda/src/putil/bamCacheRecord.h index 77bccf2fbf..39b3728dfa 100644 --- a/panda/src/putil/bamCacheRecord.h +++ b/panda/src/putil/bamCacheRecord.h @@ -76,8 +76,8 @@ PUBLISHED: MAKE_PROPERTY2(data, has_data, get_data, set_data, clear_data); - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; private: // This class is used to sort BamCacheRecords by access time. @@ -86,19 +86,19 @@ private: INLINE bool operator () (const BamCacheRecord *a, const BamCacheRecord *b) const; }; - static string format_timestamp(time_t timestamp); + static std::string format_timestamp(time_t timestamp); Filename _source_pathname; Filename _cache_filename; time_t _recorded_time; - streamsize _record_size; // this is accurate only in the index file. + std::streamsize _record_size; // this is accurate only in the index file. time_t _source_timestamp; // Not record to the cache file. class DependentFile { public: Filename _pathname; time_t _timestamp; - streamsize _size; + std::streamsize _size; }; typedef pvector DependentFiles; @@ -145,7 +145,7 @@ private: friend class BamCacheRecord::SortByAccessTime; }; -INLINE ostream &operator << (ostream &out, const BamCacheRecord &record) { +INLINE std::ostream &operator << (std::ostream &out, const BamCacheRecord &record) { record.output(out); return out; } diff --git a/panda/src/putil/bamEnums.cxx b/panda/src/putil/bamEnums.cxx index ed1b18ac58..88d21cecf8 100644 --- a/panda/src/putil/bamEnums.cxx +++ b/panda/src/putil/bamEnums.cxx @@ -15,6 +15,10 @@ #include "string_utils.h" #include "config_putil.h" +using std::istream; +using std::ostream; +using std::string; + ostream & operator << (ostream &out, BamEnums::BamEndian be) { switch (be) { diff --git a/panda/src/putil/bamEnums.h b/panda/src/putil/bamEnums.h index c2cef20db8..1f5b481c9a 100644 --- a/panda/src/putil/bamEnums.h +++ b/panda/src/putil/bamEnums.h @@ -66,12 +66,12 @@ PUBLISHED: }; }; -EXPCL_PANDA_PUTIL ostream &operator << (ostream &out, BamEnums::BamEndian be); -EXPCL_PANDA_PUTIL istream &operator >> (istream &in, BamEnums::BamEndian &be); +EXPCL_PANDA_PUTIL std::ostream &operator << (std::ostream &out, BamEnums::BamEndian be); +EXPCL_PANDA_PUTIL std::istream &operator >> (std::istream &in, BamEnums::BamEndian &be); -EXPCL_PANDA_PUTIL ostream &operator << (ostream &out, BamEnums::BamObjectCode boc); +EXPCL_PANDA_PUTIL std::ostream &operator << (std::ostream &out, BamEnums::BamObjectCode boc); -EXPCL_PANDA_PUTIL ostream &operator << (ostream &out, BamEnums::BamTextureMode btm); -EXPCL_PANDA_PUTIL istream &operator >> (istream &in, BamEnums::BamTextureMode &btm); +EXPCL_PANDA_PUTIL std::ostream &operator << (std::ostream &out, BamEnums::BamTextureMode btm); +EXPCL_PANDA_PUTIL std::istream &operator >> (std::istream &in, BamEnums::BamTextureMode &btm); #endif diff --git a/panda/src/putil/bamReader.I b/panda/src/putil/bamReader.I index ece2676956..b0da184554 100644 --- a/panda/src/putil/bamReader.I +++ b/panda/src/putil/bamReader.I @@ -34,7 +34,7 @@ get_source() { */ INLINE const Filename &BamReader:: get_filename() const { - if (_source != (DatagramGenerator *)NULL) { + if (_source != nullptr) { return _source->get_filename(); } static const Filename empty_filename; @@ -64,7 +64,7 @@ set_loader_options(const LoaderOptions &options) { */ INLINE bool BamReader:: is_eof() const { - nassertr(_source != NULL, true); + nassertr(_source != nullptr, true); return _source->is_eof(); } @@ -131,7 +131,7 @@ get_current_minor_ver() const { */ INLINE const FileReference *BamReader:: get_file() { - nassertr(_source != NULL, NULL); + nassertr(_source != nullptr, nullptr); return _source->get_file(); } @@ -141,7 +141,7 @@ get_file() { */ INLINE VirtualFile *BamReader:: get_vfile() { - nassertr(_source != NULL, NULL); + nassertr(_source != nullptr, nullptr); return _source->get_vfile(); } @@ -153,9 +153,9 @@ get_vfile() { * pointing to the first byte following the datagram returned after a call to * get_datagram(). */ -INLINE streampos BamReader:: +INLINE std::streampos BamReader:: get_file_pos() { - nassertr(_source != NULL, 0); + nassertr(_source != nullptr, 0); return _source->get_file_pos(); } @@ -175,7 +175,7 @@ register_factory(TypeHandle handle, WritableFactory::CreateFunc *func, void *use */ INLINE WritableFactory *BamReader:: get_factory() { - if (_factory == (WritableFactory *)NULL) { + if (_factory == nullptr) { create_factory(); } return _factory; @@ -195,7 +195,7 @@ create_factory() { */ INLINE bool BamReader:: get_datagram(Datagram &datagram) { - nassertr(_source != NULL, false); + nassertr(_source != nullptr, false); if (_source->is_error()) { return false; } @@ -221,10 +221,10 @@ AuxData() { INLINE BamReader::CreatedObj:: CreatedObj() : _created(false), - _ptr(NULL), - _ref_ptr(NULL), - _change_this(NULL), - _change_this_ref(NULL) + _ptr(nullptr), + _ref_ptr(nullptr), + _change_this(nullptr), + _change_this_ref(nullptr) { } @@ -233,7 +233,7 @@ CreatedObj() : */ INLINE BamReader::CreatedObj:: ~CreatedObj() { - set_ptr(NULL, NULL); + set_ptr(nullptr, nullptr); } /** @@ -249,7 +249,7 @@ INLINE BamReader::CreatedObj:: INLINE void BamReader::CreatedObj:: set_ptr(TypedWritable *ptr, ReferenceCount *ref_ptr) { if (_ptr != ptr) { - if (_ref_ptr != NULL) { + if (_ref_ptr != nullptr) { nassertv(_ref_ptr != ref_ptr); unref_delete(_ref_ptr); } @@ -257,7 +257,7 @@ set_ptr(TypedWritable *ptr, ReferenceCount *ref_ptr) { _ptr = ptr; _ref_ptr = ref_ptr; - if (_ref_ptr != NULL) { + if (_ref_ptr != nullptr) { _ref_ptr->ref(); } } else { diff --git a/panda/src/putil/bamReader.cxx b/panda/src/putil/bamReader.cxx index eab309c9d6..db360ae249 100644 --- a/panda/src/putil/bamReader.cxx +++ b/panda/src/putil/bamReader.cxx @@ -20,11 +20,13 @@ #include "config_putil.h" #include "pipelineCyclerBase.h" +using std::string; + TypeHandle BamReaderAuxData::_type_handle; -WritableFactory *BamReader::_factory = (WritableFactory*)0L; -BamReader *const BamReader::Null = (BamReader*)0L; -WritableFactory *const BamReader::NullFactory = (WritableFactory*)0L; +WritableFactory *BamReader::_factory = nullptr; +BamReader *const BamReader::Null = nullptr; +WritableFactory *const BamReader::NullFactory = nullptr; BamReader::NewTypes BamReader::_new_types; @@ -43,7 +45,7 @@ BamReader(DatagramGenerator *source) _num_extra_objects = 0; _nesting_level = 0; _now_creating = _created_objs.end(); - _reading_cycler = (PipelineCyclerBase *)NULL; + _reading_cycler = nullptr; _pta_id = -1; _long_object_id = false; _long_pta_id = false; @@ -66,7 +68,7 @@ BamReader:: void BamReader:: set_source(DatagramGenerator *source) { _source = source; - if (_needs_init && _source != NULL) { + if (_needs_init && _source != nullptr) { bool success = init(); nassertv(success); } @@ -81,7 +83,7 @@ set_source(DatagramGenerator *source) { */ bool BamReader:: init() { - nassertr(_source != NULL, false); + nassertr(_source != nullptr, false); nassertr(_needs_init, false); _needs_init = false; Datagram header; @@ -163,7 +165,7 @@ init() { */ void BamReader:: set_aux_data(TypedWritable *obj, const string &name, BamReader::AuxData *data) { - if (data == (void *)NULL) { + if (data == nullptr) { AuxDataTable::iterator ti = _aux_data.find(obj); if (ti != _aux_data.end()) { AuxDataNames &names = (*ti).second; @@ -194,7 +196,7 @@ get_aux_data(TypedWritable *obj, const string &name) const { } } - return NULL; + return nullptr; } @@ -224,7 +226,7 @@ read_object() { ReferenceCount *ref_ptr; if (!read_object(ptr, ref_ptr)) { - return NULL; + return nullptr; } return ptr; @@ -241,8 +243,8 @@ read_object() { */ bool BamReader:: read_object(TypedWritable *&ptr, ReferenceCount *&ref_ptr) { - ptr = NULL; - ref_ptr = NULL; + ptr = nullptr; + ref_ptr = nullptr; nassertr(_num_extra_objects == 0, false); int start_level = _nesting_level; @@ -290,13 +292,13 @@ read_object(TypedWritable *&ptr, ReferenceCount *&ref_ptr) { ref_ptr = created_obj._ref_ptr; if (bam_cat.is_spam()) { - if (ptr != (TypedWritable *)NULL) { + if (ptr != nullptr) { bam_cat.spam() << "Returning object of type " << ptr->get_type() << "\n"; } } - if (created_obj._change_this != NULL || - created_obj._change_this_ref != NULL) { + if (created_obj._change_this != nullptr || + created_obj._change_this_ref != nullptr) { bam_cat.warning() << "Returning pointer to " << ptr->get_type() << " that might change.\n"; @@ -360,10 +362,10 @@ resolve() { any_completed_this_pass = true; // Does the pointer need to change? - if (created_obj._change_this_ref != NULL) { + if (created_obj._change_this_ref != nullptr) { // Reference-counting variant. TypedWritableReferenceCount *object_ref_ptr = (TypedWritableReferenceCount *)object_ptr; - nassertr(created_obj._ref_ptr == NULL || created_obj._ref_ptr == object_ref_ptr, false); + nassertr(created_obj._ref_ptr == nullptr || created_obj._ref_ptr == object_ref_ptr, false); PT(TypedWritableReferenceCount) new_ptr = created_obj._change_this_ref(object_ref_ptr, this); if (new_ptr != object_ref_ptr) { // Also update the reverse @@ -381,10 +383,10 @@ resolve() { _finalize_list.erase(object_ptr); } created_obj.set_ptr(new_ptr, new_ptr); - created_obj._change_this = NULL; - created_obj._change_this_ref = NULL; + created_obj._change_this = nullptr; + created_obj._change_this_ref = nullptr; - } else if (created_obj._change_this != NULL) { + } else if (created_obj._change_this != nullptr) { // Non-reference-counting variant. TypedWritable *new_ptr = created_obj._change_this(object_ptr, this); if (new_ptr != object_ptr) { @@ -403,8 +405,8 @@ resolve() { _finalize_list.erase(object_ptr); } created_obj.set_ptr(new_ptr, new_ptr->as_reference_count()); - created_obj._change_this = NULL; - created_obj._change_this_ref = NULL; + created_obj._change_this = nullptr; + created_obj._change_this_ref = nullptr; } } else { @@ -615,7 +617,7 @@ read_pointer(DatagramIterator &scan) { int object_id = read_object_id(scan); PointerReference &pref = _object_pointers[requestor_id]; - if (_reading_cycler == (PipelineCyclerBase *)NULL) { + if (_reading_cycler == nullptr) { // This is not being read within a read_cdata() call. pref._objects.push_back(object_id); } else { @@ -781,15 +783,15 @@ set_aux_tag(const string &tag, BamReaderAuxData *value) { */ BamReaderAuxData *BamReader:: get_aux_tag(const string &tag) const { - nassertr(_now_creating != _created_objs.end(), NULL); + nassertr(_now_creating != _created_objs.end(), nullptr); int requestor_id = (*_now_creating).first; ObjectPointers::const_iterator opi = _object_pointers.find(requestor_id); - nassertr(opi != _object_pointers.end(), NULL); + nassertr(opi != _object_pointers.end(), nullptr); const PointerReference &pref = (*opi).second; AuxTags::const_iterator ati = pref._aux_tags.find(tag); - nassertr(ati != pref._aux_tags.end(), NULL); + nassertr(ati != pref._aux_tags.end(), nullptr); return (*ati).second; } @@ -804,7 +806,7 @@ get_aux_tag(const string &tag) const { */ void BamReader:: register_finalize(TypedWritable *whom) { - nassertv(whom != (TypedWritable *)NULL); + nassertv(whom != nullptr); if (bam_cat.is_spam()) { bam_cat.spam() @@ -837,7 +839,7 @@ register_change_this(ChangeThisFunc func, TypedWritable *object) { #ifndef NDEBUG // Sanity check the pointer--it should always be the same pointer after we // set it the first time. - if (created_obj._ptr == (TypedWritable *)NULL) { + if (created_obj._ptr == nullptr) { created_obj.set_ptr(object, object->as_reference_count()); } else { // We've previously assigned this pointer, and we should have assigned it @@ -847,7 +849,7 @@ register_change_this(ChangeThisFunc func, TypedWritable *object) { #endif // NDEBUG created_obj._change_this = func; - created_obj._change_this_ref = NULL; + created_obj._change_this_ref = nullptr; } /** @@ -872,7 +874,7 @@ register_change_this(ChangeThisRefFunc func, TypedWritableReferenceCount *object #ifndef NDEBUG // Sanity check the pointer--it should always be the same pointer after we // set it the first time. - if (created_obj._ptr == (TypedWritable *)NULL) { + if (created_obj._ptr == nullptr) { created_obj.set_ptr(object, object); } else { // We've previously assigned this pointer, and we should have assigned it @@ -882,7 +884,7 @@ register_change_this(ChangeThisRefFunc func, TypedWritableReferenceCount *object } #endif // NDEBUG - created_obj._change_this = NULL; + created_obj._change_this = nullptr; created_obj._change_this_ref = func; } @@ -893,7 +895,7 @@ register_change_this(ChangeThisRefFunc func, TypedWritableReferenceCount *object */ void BamReader:: finalize_now(TypedWritable *whom) { - if (whom == (TypedWritable *)NULL) { + if (whom == nullptr) { return; } @@ -927,7 +929,7 @@ finalize_now(TypedWritable *whom) { */ void *BamReader:: get_pta(DatagramIterator &scan) { - nassertr(_pta_id == -1, (void *)NULL); + nassertr(_pta_id == -1, nullptr); int id = read_pta_id(scan); if (id == 0) { @@ -935,7 +937,7 @@ get_pta(DatagramIterator &scan) { // able to differentiate this case from that of a previously-read pointer, // but that's OK because the next data in the Bam file is the length of // the array, which will be zero--indicating an empty or NULL array. - return (void *)NULL; + return nullptr; } PTAMap::iterator pi = _pta_map.find(id); @@ -943,7 +945,7 @@ get_pta(DatagramIterator &scan) { // This is the first time we've encountered this particular ID, meaning we // need to read the data now and register it. _pta_id = id; - return (void *)NULL; + return nullptr; } return (*pi).second; @@ -1111,7 +1113,7 @@ p_read_object() { default: bam_cat.error() - << "Encountered invalid BamObjectCode 0x" << hex << (int)boc << dec << ".\n"; + << "Encountered invalid BamObjectCode 0x" << std::hex << (int)boc << std::dec << ".\n"; return 0; } @@ -1155,7 +1157,7 @@ p_read_object() { _created_objs.insert(CreatedObjs::value_type(object_id, new_created_obj)).first; CreatedObj &created_obj = (*oi).second; - if (created_obj._ptr != NULL) { + if (created_obj._ptr != nullptr) { // This object had already existed; thus, we are just receiving an // update for it. @@ -1200,15 +1202,15 @@ p_read_object() { _now_creating = was_creating; // And now we can store the new object pointer in the map. - nassertr(created_obj._ptr == object || created_obj._ptr == NULL, object_id); - if (object == NULL) { - created_obj.set_ptr(NULL, NULL); + nassertr(created_obj._ptr == object || created_obj._ptr == nullptr, object_id); + if (object == nullptr) { + created_obj.set_ptr(nullptr, nullptr); } else { created_obj.set_ptr(object, object->as_reference_count()); } created_obj._created = true; - if (created_obj._change_this_ref != NULL) { + if (created_obj._change_this_ref != nullptr) { // If the pointer is scheduled to change after complete_pointers(), // but we have no entry in _object_pointers for this object (and hence // no plan to call complete_pointers()), then just change the pointer @@ -1218,8 +1220,8 @@ p_read_object() { PT(TypedWritableReferenceCount) object_ref = (*created_obj._change_this_ref)((TypedWritableReferenceCount *)object, this); TypedWritable *new_ptr = object_ref; created_obj.set_ptr(object_ref, object_ref); - created_obj._change_this = NULL; - created_obj._change_this_ref = NULL; + created_obj._change_this = nullptr; + created_obj._change_this_ref = nullptr; // Remove the pointer from the finalize list (the new pointer // presumably doesn't require finalizing). @@ -1229,14 +1231,14 @@ p_read_object() { object = new_ptr; } - } else if (created_obj._change_this != NULL) { + } else if (created_obj._change_this != nullptr) { // Non-reference-counting variant. ObjectPointers::const_iterator ri = _object_pointers.find(object_id); if (ri == _object_pointers.end()) { TypedWritable *new_ptr = (*created_obj._change_this)(object, this); created_obj.set_ptr(new_ptr, new_ptr->as_reference_count()); - created_obj._change_this = NULL; - created_obj._change_this_ref = NULL; + created_obj._change_this = nullptr; + created_obj._change_this_ref = nullptr; if (new_ptr != object) { _finalize_list.erase(object); @@ -1248,10 +1250,10 @@ p_read_object() { _created_objs_by_pointer[created_obj._ptr].push_back(object_id); // Just some sanity checks - if (object == (TypedWritable *)NULL) { + if (object == nullptr) { if (bam_cat.is_debug()) { bam_cat.debug() - << "Unable to create an object of type " << type << endl; + << "Unable to create an object of type " << type << std::endl; } } else if (object->get_type() != type) { @@ -1263,7 +1265,7 @@ p_read_object() { bam_cat.warning() << "Attempted to create a " << type.get_name() \ << " but a " << object->get_type() \ - << " was created instead." << endl; + << " was created instead." << std::endl; } } else { @@ -1272,7 +1274,7 @@ p_read_object() { bam_cat.warning() << "Attempted to create a " << type.get_name() \ << " but a " << object->get_type() \ - << " was created instead." << endl; + << " was created instead." << std::endl; } } else { @@ -1355,7 +1357,7 @@ resolve_object_pointers(TypedWritable *object, int child_id = (*pi); if (child_id == 0) { // A NULL pointer is a NULL pointer. - references.push_back((TypedWritable *)NULL); + references.push_back(nullptr); continue; } @@ -1374,7 +1376,7 @@ resolve_object_pointers(TypedWritable *object, break; } - if (child_obj._change_this != NULL || child_obj._change_this_ref != NULL) { + if (child_obj._change_this != nullptr || child_obj._change_this_ref != nullptr) { // It's been created, but the pointer might still change. is_complete = false; break; @@ -1447,7 +1449,7 @@ resolve_cycler_pointers(PipelineCyclerBase *cycler, if (child_id == 0) { // A NULL pointer is a NULL pointer. - references.push_back((TypedWritable *)NULL); + references.push_back(nullptr); continue; } @@ -1460,7 +1462,7 @@ resolve_cycler_pointers(PipelineCyclerBase *cycler, } const CreatedObj &child_obj = (*oi).second; - if (child_obj._change_this != NULL || child_obj._change_this_ref != NULL) { + if (child_obj._change_this != nullptr || child_obj._change_this_ref != nullptr) { // It's been created, but the pointer might still change. is_complete = false; break; @@ -1513,7 +1515,7 @@ finalize() { Finalize::iterator fi = _finalize_list.begin(); while (fi != _finalize_list.end()) { TypedWritable *object = (*fi); - nassertv(object != (TypedWritable *)NULL); + nassertv(object != nullptr); _finalize_list.erase(fi); if (bam_cat.is_spam()) { bam_cat.spam() @@ -1527,14 +1529,14 @@ finalize() { // Now clear the aux data of all objects, except the NULL object. if (!_aux_data.empty()) { - AuxDataTable::iterator ti = _aux_data.find((TypedWritable *)NULL); + AuxDataTable::iterator ti = _aux_data.find(nullptr); if (ti != _aux_data.end()) { if (_aux_data.size() > 1) { // Move the NULL data to the new table; remove the rest. AuxDataTable new_aux_data; AuxDataTable::iterator nti = - new_aux_data.insert(AuxDataTable::value_type((TypedWritable *)NULL, AuxDataNames())).first; + new_aux_data.insert(AuxDataTable::value_type(nullptr, AuxDataNames())).first; (*nti).second.swap((*ti).second); _aux_data.swap(new_aux_data); } @@ -1544,10 +1546,3 @@ finalize() { } } } - -/** - * - */ -BamReader::AuxData:: -~AuxData() { -} diff --git a/panda/src/putil/bamReader.h b/panda/src/putil/bamReader.h index bf88ced2af..69c901f0fa 100644 --- a/panda/src/putil/bamReader.h +++ b/panda/src/putil/bamReader.h @@ -42,7 +42,7 @@ #define READ_PTA(Manager, source, Read_func, array) \ { \ void *t; \ - if ((t = Manager->get_pta(source)) == (void*)NULL) \ + if ((t = Manager->get_pta(source)) == nullptr) \ { \ array = Read_func(Manager, source); \ Manager->register_pta(array.get_void_ptr()); \ @@ -58,7 +58,7 @@ * object's read pass. To use this, subclass BamReaderAuxData and add * whatever additional data you require. */ -class EXPCL_PANDA_PGRAPH BamReaderAuxData : public TypedReferenceCount { +class EXPCL_PANDA_PUTIL BamReaderAuxData : public TypedReferenceCount { public: INLINE BamReaderAuxData(); @@ -115,7 +115,7 @@ public: PUBLISHED: // The primary interface for a caller. - explicit BamReader(DatagramGenerator *source = NULL); + explicit BamReader(DatagramGenerator *source = nullptr); ~BamReader(); void set_source(DatagramGenerator *source); @@ -124,8 +124,8 @@ PUBLISHED: bool init(); class AuxData; - void set_aux_data(TypedWritable *obj, const string &name, AuxData *data); - AuxData *get_aux_data(TypedWritable *obj, const string &name) const; + void set_aux_data(TypedWritable *obj, const std::string &name, AuxData *data); + AuxData *get_aux_data(TypedWritable *obj, const std::string &name) const; INLINE const Filename &get_filename() const; @@ -172,11 +172,11 @@ public: void read_cdata(DatagramIterator &scan, PipelineCyclerBase &cycler, void *extra_data); - void set_int_tag(const string &tag, int value); - int get_int_tag(const string &tag) const; + void set_int_tag(const std::string &tag, int value); + int get_int_tag(const std::string &tag) const; - void set_aux_tag(const string &tag, BamReaderAuxData *value); - BamReaderAuxData *get_aux_tag(const string &tag) const; + void set_aux_tag(const std::string &tag, BamReaderAuxData *value); + BamReaderAuxData *get_aux_tag(const std::string &tag) const; void register_finalize(TypedWritable *whom); @@ -194,11 +194,11 @@ public: INLINE const FileReference *get_file(); INLINE VirtualFile *get_vfile(); - INLINE streampos get_file_pos(); + INLINE std::streampos get_file_pos(); public: INLINE static void register_factory(TypeHandle type, WritableFactory::CreateFunc *func, - void *user_data = NULL); + void *user_data = nullptr); INLINE static WritableFactory *get_factory(); PUBLISHED: @@ -228,7 +228,7 @@ public: class AuxData : public ReferenceCount { public: INLINE AuxData(); - virtual ~AuxData(); + virtual ~AuxData() = default; }; private: @@ -282,8 +282,8 @@ private: // which read_pointer() was called, so that we may call the appropriate // complete_pointers() later. typedef phash_map CyclerPointers; - typedef pmap IntTags; - typedef pmap AuxTags; + typedef pmap IntTags; + typedef pmap AuxTags; class PointerReference { public: vector_int _objects; @@ -328,7 +328,7 @@ private: static NewTypes _new_types; // This is used in support of set_aux_data() and get_aux_data(). - typedef pmap AuxDataNames; + typedef pmap AuxDataNames; typedef phash_map AuxDataTable; AuxDataTable _aux_data; diff --git a/panda/src/putil/bamReader_ext.cxx b/panda/src/putil/bamReader_ext.cxx index 444688a654..a224a36037 100644 --- a/panda/src/putil/bamReader_ext.cxx +++ b/panda/src/putil/bamReader_ext.cxx @@ -28,7 +28,7 @@ extern Dtool_PyTypedObject Dtool_TypedWritable; */ static TypedWritable *factory_callback(const FactoryParams ¶ms){ PyObject *func = (PyObject *)params.get_user_data(); - nassertr(func != NULL, NULL); + nassertr(func != nullptr, nullptr); #if defined(HAVE_THREADS) && !defined(SIMPLE_THREADS) // Use PyGILState to protect this asynchronous call. @@ -51,7 +51,7 @@ static TypedWritable *factory_callback(const FactoryParams ¶ms){ Py_DECREF(py_scan); Py_DECREF(py_manager); - if (result == (PyObject *)NULL) { + if (result == nullptr) { util_cat.error() << "Exception occurred in Python factory function\n"; @@ -59,7 +59,7 @@ static TypedWritable *factory_callback(const FactoryParams ¶ms){ util_cat.error() << "Python factory function returned None\n"; Py_DECREF(result); - result = NULL; + result = nullptr; } #if defined(HAVE_THREADS) && !defined(SIMPLE_THREADS) @@ -67,15 +67,15 @@ static TypedWritable *factory_callback(const FactoryParams ¶ms){ #endif // Unwrap the returned TypedWritable object. - if (result == (PyObject *)NULL) { - return (TypedWritable *)NULL; + if (result == nullptr) { + return nullptr; } else { - void *object = NULL; + void *object = nullptr; Dtool_Call_ExtractThisPointer(result, Dtool_TypedWritable, &object); TypedWritable *ptr = (TypedWritable *)object; ReferenceCount *ref_count = ptr->as_reference_count(); - if (ref_count != NULL) { + if (ref_count != nullptr) { // If the Python pointer is the last reference to it, make sure that the // object isn't destroyed. We do this by calling unref(), which // decreases the reference count without destroying the object. @@ -109,7 +109,7 @@ get_file_version() const { */ void Extension:: register_factory(TypeHandle handle, PyObject *func) { - nassertv(func != NULL); + nassertv(func != nullptr); if (!PyCallable_Check(func)) { Dtool_Raise_TypeError("second argument to register_factory must be callable"); diff --git a/panda/src/putil/bamWriter.I b/panda/src/putil/bamWriter.I index b2fa51d146..ad8b119edf 100644 --- a/panda/src/putil/bamWriter.I +++ b/panda/src/putil/bamWriter.I @@ -27,7 +27,7 @@ get_target() { */ INLINE const Filename &BamWriter:: get_filename() const { - if (_target != (DatagramSink *)NULL) { + if (_target != nullptr) { return _target->get_filename(); } static const Filename empty_filename; diff --git a/panda/src/putil/bamWriter.cxx b/panda/src/putil/bamWriter.cxx index ac3ac6b8ad..d8aa3e0b30 100644 --- a/panda/src/putil/bamWriter.cxx +++ b/panda/src/putil/bamWriter.cxx @@ -107,12 +107,12 @@ BamWriter:: */ void BamWriter:: set_target(DatagramSink *target) { - if (_target != NULL) { + if (_target != nullptr) { _target->flush(); } _target = target; - if (_needs_init && _target != NULL) { + if (_needs_init && _target != nullptr) { init(); } } @@ -126,7 +126,7 @@ set_target(DatagramSink *target) { */ bool BamWriter:: init() { - nassertr(_target != NULL, false); + nassertr(_target != nullptr, false); nassertr(_needs_init, false); _needs_init = false; @@ -183,7 +183,7 @@ init() { */ bool BamWriter:: write_object(const TypedWritable *object) { - nassertr(_target != NULL, false); + nassertr(_target != nullptr, false); // Increment the _writing_seq, so we can check for newly stale objects // during this operation. @@ -246,7 +246,7 @@ has_object(const TypedWritable *object) const { */ void BamWriter:: flush() { - nassertv(_target != NULL); + nassertv(_target != nullptr); _target->flush(); } @@ -298,7 +298,7 @@ void BamWriter:: write_pointer(Datagram &packet, const TypedWritable *object) { // If the pointer is NULL, we always simply write a zero for an object ID // and leave it at that. - if (object == (const TypedWritable *)NULL) { + if (object == nullptr) { write_object_id(packet, 0); } else { @@ -436,7 +436,7 @@ write_cdata(Datagram &packet, const PipelineCyclerBase &cycler, */ bool BamWriter:: register_pta(Datagram &packet, const void *ptr) { - if (ptr == (const void *)NULL) { + if (ptr == nullptr) { // A zero for the PTA ID indicates a NULL pointer. This is a special // case. write_pta_id(packet, 0); @@ -649,7 +649,7 @@ enqueue_object(const TypedWritable *object) { */ bool BamWriter:: flush_queue() { - nassertr(_target != NULL, false); + nassertr(_target != nullptr, false); // Each object we write may append more to the queue. while (!_object_queue.empty()) { const TypedWritable *object = _object_queue.front(); diff --git a/panda/src/putil/bamWriter.h b/panda/src/putil/bamWriter.h index bcd4a76ce6..b8c53aac38 100644 --- a/panda/src/putil/bamWriter.h +++ b/panda/src/putil/bamWriter.h @@ -62,7 +62,7 @@ */ class EXPCL_PANDA_PUTIL BamWriter : public BamEnums { PUBLISHED: - explicit BamWriter(DatagramSink *target = NULL); + explicit BamWriter(DatagramSink *target = nullptr); ~BamWriter(); void set_target(DatagramSink *target); diff --git a/panda/src/putil/bitArray.I b/panda/src/putil/bitArray.I index f746a9ba77..605cf40a57 100644 --- a/panda/src/putil/bitArray.I +++ b/panda/src/putil/bitArray.I @@ -78,44 +78,6 @@ range(int low_bit, int size) { return result; } -/** - * Returns true if there is a maximum number of bits that may be stored in - * this structure, false otherwise. If this returns true, the number may be - * queried in get_max_num_bits(). - * - * This method always returns false. The BitArray has no maximum number of - * bits. This method is defined so generic programming algorithms can use - * BitMask or BitArray interchangeably. - */ -CONSTEXPR bool BitArray:: -has_max_num_bits() { - return false; -} - -/** - * If get_max_num_bits() returned true, this method may be called to return - * the maximum number of bits that may be stored in this structure. It is an - * error to call this if get_max_num_bits() return false. - * - * It is always an error to call this method. The BitArray has no maximum - * number of bits. This method is defined so generic programming algorithms - * can use BitMask or BitArray interchangeably. - */ -CONSTEXPR int BitArray:: -get_max_num_bits() { - return INT_MAX; -} - -/** - * Returns the number of bits stored per word internally. This is of interest - * only in that it limits the maximum number of bits that may be queried or - * set at once by extract() and store(). - */ -CONSTEXPR int BitArray:: -get_num_bits_per_word() { - return num_bits_per_word; -} - /** * Returns the current number of possibly different bits in this array. There * are actually an infinite number of bits, but every bit higher than this bit diff --git a/panda/src/putil/bitArray.cxx b/panda/src/putil/bitArray.cxx index f91c16d573..2ba077e0c1 100644 --- a/panda/src/putil/bitArray.cxx +++ b/panda/src/putil/bitArray.cxx @@ -16,6 +16,10 @@ #include "datagram.h" #include "datagramIterator.h" +using std::max; +using std::min; +using std::ostream; + TypeHandle BitArray::_type_handle; /** @@ -83,7 +87,7 @@ is_all_on() const { */ bool BitArray:: has_any_of(int low_bit, int size) const { - if ((low_bit + size - 1) / num_bits_per_word >= get_num_words()) { + if ((size_t)(low_bit + size) > get_num_bits()) { // This range touches the highest bits. if (_highest_bits) { return true; @@ -93,7 +97,7 @@ has_any_of(int low_bit, int size) const { int w = low_bit / num_bits_per_word; int b = low_bit % num_bits_per_word; - if (w >= get_num_words()) { + if (w >= (int)get_num_words()) { // This range is entirely among the highest bits. return (_highest_bits != 0); } @@ -122,7 +126,7 @@ has_any_of(int low_bit, int size) const { size -= num_bits_per_word; ++w; - if (w >= get_num_words()) { + if (w >= (int)get_num_words()) { // Now we're up to the highest bits. return (_highest_bits != 0); } @@ -136,7 +140,7 @@ has_any_of(int low_bit, int size) const { */ bool BitArray:: has_all_of(int low_bit, int size) const { - if ((low_bit + size - 1) / num_bits_per_word >= get_num_words()) { + if ((size_t)(low_bit + size) > get_num_bits()) { // This range touches the highest bits. if (!_highest_bits) { return false; @@ -146,7 +150,7 @@ has_all_of(int low_bit, int size) const { int w = low_bit / num_bits_per_word; int b = low_bit % num_bits_per_word; - if (w >= get_num_words()) { + if (w >= (int)get_num_words()) { // This range is entirely among the highest bits. return (_highest_bits != 0); } @@ -175,7 +179,7 @@ has_all_of(int low_bit, int size) const { size -= num_bits_per_word; ++w; - if (w >= get_num_words()) { + if (w >= (int)get_num_words()) { // Now we're up to the highest bits. return (_highest_bits != 0); } @@ -192,7 +196,7 @@ set_range(int low_bit, int size) { int w = low_bit / num_bits_per_word; int b = low_bit % num_bits_per_word; - if (w >= get_num_words() && _highest_bits) { + if (w >= (int)get_num_words() && _highest_bits) { // All the highest bits are already on. return; } @@ -225,7 +229,7 @@ set_range(int low_bit, int size) { size -= num_bits_per_word; ++w; - if (w >= get_num_words() && _highest_bits) { + if (w >= (int)get_num_words() && _highest_bits) { // All the highest bits are already on. normalize(); return; @@ -242,7 +246,7 @@ clear_range(int low_bit, int size) { int w = low_bit / num_bits_per_word; int b = low_bit % num_bits_per_word; - if (w >= get_num_words() && !_highest_bits) { + if (w >= (int)get_num_words() && !_highest_bits) { // All the highest bits are already off. return; } @@ -275,7 +279,7 @@ clear_range(int low_bit, int size) { size -= num_bits_per_word; ++w; - if (w >= get_num_words() && !_highest_bits) { + if (w >= (int)get_num_words() && !_highest_bits) { // All the highest bits are already off. normalize(); return; diff --git a/panda/src/putil/bitArray.h b/panda/src/putil/bitArray.h index 72ef1f656d..0338747295 100644 --- a/panda/src/putil/bitArray.h +++ b/panda/src/putil/bitArray.h @@ -54,10 +54,10 @@ PUBLISHED: INLINE static BitArray bit(int index); INLINE static BitArray range(int low_bit, int size); - CONSTEXPR static bool has_max_num_bits(); - CONSTEXPR static int get_max_num_bits(); + constexpr static bool has_max_num_bits() { return false; } + constexpr static int get_max_num_bits() { return INT_MAX; } - CONSTEXPR static int get_num_bits_per_word(); + constexpr static int get_num_bits_per_word() { return num_bits_per_word; } INLINE size_t get_num_bits() const; INLINE bool get_bit(int index) const; INLINE void set_bit(int index); @@ -91,10 +91,10 @@ PUBLISHED: bool has_bits_in_common(const BitArray &other) const; INLINE void clear(); - void output(ostream &out) const; - void output_binary(ostream &out, int spaces_every = 4) const; - void output_hex(ostream &out, int spaces_every = 4) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void output_binary(std::ostream &out, int spaces_every = 4) const; + void output_hex(std::ostream &out, int spaces_every = 4) const; + void write(std::ostream &out, int indent_level = 0) const; INLINE bool operator == (const BitArray &other) const; INLINE bool operator != (const BitArray &other) const; @@ -156,8 +156,8 @@ private: #include "bitArray.I" -INLINE ostream & -operator << (ostream &out, const BitArray &array) { +INLINE std::ostream & +operator << (std::ostream &out, const BitArray &array) { array.output(out); return out; } diff --git a/panda/src/putil/bitMask.I b/panda/src/putil/bitMask.I index 0411d06042..6bff1e70d4 100644 --- a/panda/src/putil/bitMask.I +++ b/panda/src/putil/bitMask.I @@ -18,17 +18,7 @@ TypeHandle BitMask::_type_handle; * */ template -INLINE BitMask:: -BitMask() : - _word(0) -{ -} - -/** - * - */ -template -INLINE BitMask:: +constexpr BitMask:: BitMask(WordType init_value) : _word(init_value) { @@ -101,41 +91,12 @@ range(int low_bit, int size) { return result; } -/** - * Returns true if there is a maximum number of bits that may be stored in - * this structure, false otherwise. If this returns true, the number may be - * queried in get_max_num_bits(). - * - * This method always returns true. This method is defined so generic - * programming algorithms can use BitMask or BitArray interchangeably. - */ -template -CONSTEXPR bool BitMask:: -has_max_num_bits() { - return true; -} - -/** - * If get_max_num_bits() returned true, this method may be called to return - * the maximum number of bits that may be stored in this structure. It is an - * error to call this if get_max_num_bits() return false. - * - * It is never an error to call this method. This returns the same thing as - * get_num_bits(). This method is defined so generic programming algorithms - * can use BitMask or BitArray interchangeably. - */ -template -CONSTEXPR int BitMask:: -get_max_num_bits() { - return num_bits; -} - /** * Returns the number of bits available to set in the bitmask. */ template -CONSTEXPR int BitMask:: -get_num_bits() { +constexpr int BitMask:: +get_num_bits() const { return num_bits; } @@ -199,7 +160,7 @@ is_zero() const { template INLINE bool BitMask:: is_all_on() const { - return (~_word == 0); + return _word == (WordType)~0; } /** @@ -207,7 +168,7 @@ is_all_on() const { * BitMask, shifted to the least-significant position. */ template -INLINE TYPENAME BitMask::WordType BitMask:: +INLINE typename BitMask::WordType BitMask:: extract(int low_bit, int size) const { return (_word >> low_bit) & BitMask::lower_on(size)._word; @@ -281,7 +242,7 @@ set_range_to(bool value, int low_bit, int size) { * Returns the entire BitMask as a single word. */ template -INLINE TYPENAME BitMask::WordType BitMask:: +INLINE typename BitMask::WordType BitMask:: get_word() const { return _word; } @@ -441,7 +402,7 @@ clear() { */ template void BitMask:: -output(ostream &out) const { +output(std::ostream &out) const { if (num_bits >= 40) { output_hex(out); } else { @@ -454,7 +415,7 @@ output(ostream &out) const { */ template void BitMask:: -output_binary(ostream &out, int spaces_every) const { +output_binary(std::ostream &out, int spaces_every) const { for (int i = num_bits - 1; i >= 0; i--) { if (spaces_every != 0 && ((i % spaces_every) == spaces_every - 1)) { out << ' '; @@ -469,7 +430,7 @@ output_binary(ostream &out, int spaces_every) const { */ template void BitMask:: -output_hex(ostream &out, int spaces_every) const { +output_hex(std::ostream &out, int spaces_every) const { int num_digits = (num_bits + 3) / 4; for (int i = num_digits - 1; i >= 0; i--) { @@ -491,7 +452,7 @@ output_hex(ostream &out, int spaces_every) const { */ template void BitMask:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << *this << "\n"; } @@ -685,7 +646,7 @@ generate_hash(ChecksumHashGenerator &hashgen) const { */ template void BitMask:: -init_type(const string &name) { +init_type(const std::string &name) { register_type(_type_handle, name); } diff --git a/panda/src/putil/bitMask.cxx b/panda/src/putil/bitMask.cxx index 8e51315eb2..cd200ab565 100644 --- a/panda/src/putil/bitMask.cxx +++ b/panda/src/putil/bitMask.cxx @@ -16,3 +16,11 @@ template class BitMask; template class BitMask; template class BitMask; + +#if !defined(CPPPARSER) && !defined(__APPLE__) +#include + +static_assert(std::is_literal_type::value, "BitMask16 is not a literal type"); +static_assert(std::is_literal_type::value, "BitMask32 is not a literal type"); +static_assert(std::is_literal_type::value, "BitMask64 is not a literal type"); +#endif diff --git a/panda/src/putil/bitMask.h b/panda/src/putil/bitMask.h index 5333562025..cb11fe10bf 100644 --- a/panda/src/putil/bitMask.h +++ b/panda/src/putil/bitMask.h @@ -36,8 +36,8 @@ public: PUBLISHED: enum { num_bits = nbits }; - INLINE BitMask(); - INLINE BitMask(WordType init_value); + constexpr BitMask() = default; + constexpr BitMask(WordType init_value); INLINE static BitMask all_on(); INLINE static BitMask all_off(); @@ -45,10 +45,10 @@ PUBLISHED: INLINE static BitMask bit(int index); INLINE static BitMask range(int low_bit, int size); - CONSTEXPR static bool has_max_num_bits(); - CONSTEXPR static int get_max_num_bits(); + constexpr static bool has_max_num_bits() { return true; } + constexpr static int get_max_num_bits() { return num_bits; } - CONSTEXPR static int get_num_bits(); + constexpr int get_num_bits() const; INLINE bool get_bit(int index) const; INLINE void set_bit(int index); INLINE void clear_bit(int index); @@ -78,10 +78,10 @@ PUBLISHED: INLINE bool has_bits_in_common(const BitMask &other) const; INLINE void clear(); - void output(ostream &out) const; - void output_binary(ostream &out, int spaces_every = 4) const; - void output_hex(ostream &out, int spaces_every = 4) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void output_binary(std::ostream &out, int spaces_every = 4) const; + void output_hex(std::ostream &out, int spaces_every = 4) const; + void write(std::ostream &out, int indent_level = 0) const; INLINE bool operator == (const BitMask &other) const; INLINE bool operator != (const BitMask &other) const; @@ -131,13 +131,13 @@ public: INLINE void generate_hash(ChecksumHashGenerator &hashgen) const; private: - WordType _word; + WordType _word = 0u; public: static TypeHandle get_class_type() { return _type_handle; } - static void init_type(const string &name); + static void init_type(const std::string &name); private: static TypeHandle _type_handle; @@ -146,7 +146,7 @@ private: #include "bitMask.I" template -INLINE ostream &operator << (ostream &out, const BitMask &bitmask) { +INLINE std::ostream &operator << (std::ostream &out, const BitMask &bitmask) { bitmask.output(out); return out; } diff --git a/panda/src/putil/buttonHandle.I b/panda/src/putil/buttonHandle.I index 2353b01689..c45145dd40 100644 --- a/panda/src/putil/buttonHandle.I +++ b/panda/src/putil/buttonHandle.I @@ -15,7 +15,7 @@ * Constructs a ButtonHandle with the corresponding index number, which may * have been returned by an earlier call to ButtonHandle::get_index(). */ -CONSTEXPR ButtonHandle:: +constexpr ButtonHandle:: ButtonHandle(int index) : _index(index) { } @@ -124,7 +124,7 @@ matches(const ButtonHandle &other) const { * opaque classes. This is provided for the convenience of non-C++ scripting * languages to build a hashtable of ButtonHandles. */ -CONSTEXPR int ButtonHandle:: +constexpr int ButtonHandle:: get_index() const { return _index; } @@ -133,7 +133,7 @@ get_index() const { * */ INLINE void ButtonHandle:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_name(); } diff --git a/panda/src/putil/buttonHandle.cxx b/panda/src/putil/buttonHandle.cxx index 5495b7ce18..831a3daddd 100644 --- a/panda/src/putil/buttonHandle.cxx +++ b/panda/src/putil/buttonHandle.cxx @@ -27,14 +27,14 @@ TypeHandle ButtonHandle::_type_handle; * ButtonRegistry::register_button(). */ ButtonHandle:: -ButtonHandle(const string &name) { +ButtonHandle(const std::string &name) { _index = ButtonRegistry::ptr()->get_button(name)._index; } /** * Returns the name of the button. */ -string ButtonHandle:: +std::string ButtonHandle:: get_name() const { if ((*this) == ButtonHandle::none()) { return "none"; diff --git a/panda/src/putil/buttonHandle.h b/panda/src/putil/buttonHandle.h index 429108249f..ad43ad2a86 100644 --- a/panda/src/putil/buttonHandle.h +++ b/panda/src/putil/buttonHandle.h @@ -23,15 +23,15 @@ * keyboard buttons and mouse buttons (but see KeyboardButton and * MouseButton). */ -class EXPCL_PANDA_PUTIL ButtonHandle FINAL { +class EXPCL_PANDA_PUTIL ButtonHandle final { PUBLISHED: // The default constructor must do nothing, because we can't guarantee // ordering of static initializers. If the constructor tried to initialize // its value, it might happen after the value had already been set // previously by another static initializer! - INLINE ButtonHandle() DEFAULT_CTOR; - CONSTEXPR ButtonHandle(int index); - ButtonHandle(const string &name); + INLINE ButtonHandle() = default; + constexpr ButtonHandle(int index); + ButtonHandle(const std::string &name); PUBLISHED: INLINE bool operator == (const ButtonHandle &other) const; @@ -43,7 +43,7 @@ PUBLISHED: INLINE int compare_to(const ButtonHandle &other) const; INLINE size_t get_hash() const; - string get_name() const; + std::string get_name() const; INLINE bool has_ascii_equivalent() const; INLINE char get_ascii_equivalent() const; @@ -51,8 +51,8 @@ PUBLISHED: INLINE bool matches(const ButtonHandle &other) const; - CONSTEXPR int get_index() const; - INLINE void output(ostream &out) const; + constexpr int get_index() const; + INLINE void output(std::ostream &out) const; INLINE static ButtonHandle none(); INLINE operator bool () const; @@ -83,7 +83,7 @@ friend class ButtonRegistry; // It's handy to be able to output a ButtonHandle directly, and see the button // name. -INLINE ostream &operator << (ostream &out, ButtonHandle button) { +INLINE std::ostream &operator << (std::ostream &out, ButtonHandle button) { button.output(out); return out; } diff --git a/panda/src/putil/buttonMap.I b/panda/src/putil/buttonMap.I index bd7e6e4012..49cb2f9931 100644 --- a/panda/src/putil/buttonMap.I +++ b/panda/src/putil/buttonMap.I @@ -40,7 +40,7 @@ get_mapped_button(size_t i) const { * Returns the label associated with the nth mapped button, meaning the button * that the nth raw button is mapped to. */ -INLINE const string &ButtonMap:: +INLINE const std::string &ButtonMap:: get_mapped_button_label(size_t i) const { return _buttons[i]->_label; } @@ -67,7 +67,7 @@ get_mapped_button(ButtonHandle raw) const { * given raw button. */ INLINE ButtonHandle ButtonMap:: -get_mapped_button(const string &raw_name) const { +get_mapped_button(const std::string &raw_name) const { ButtonHandle raw_button = ButtonRegistry::ptr()->find_button(raw_name); if (raw_button == ButtonHandle::none()) { return ButtonHandle::none(); @@ -84,12 +84,12 @@ get_mapped_button(const string &raw_name) const { * Note that this is not the same as get_mapped_button().get_name(), which * returns the name of the Panda event associated with the button. */ -INLINE const string &ButtonMap:: +INLINE const std::string &ButtonMap:: get_mapped_button_label(ButtonHandle raw) const { pmap::const_iterator it; it = _button_map.find(raw.get_index()); if (it == _button_map.end()) { - static const string empty = ""; + static const std::string empty = ""; return empty; } else { return it->second._label; @@ -104,11 +104,11 @@ get_mapped_button_label(ButtonHandle raw) const { * Note that this is not the same as get_mapped_button().get_name(), which * returns the name of the Panda event associated with the button. */ -INLINE const string &ButtonMap:: -get_mapped_button_label(const string &raw_name) const { +INLINE const std::string &ButtonMap:: +get_mapped_button_label(const std::string &raw_name) const { ButtonHandle raw_button = ButtonRegistry::ptr()->find_button(raw_name); if (raw_button == ButtonHandle::none()) { - static const string empty = ""; + static const std::string empty = ""; return empty; } else { return get_mapped_button_label(raw_button); diff --git a/panda/src/putil/buttonMap.cxx b/panda/src/putil/buttonMap.cxx index 7fcc0fa516..2e74d929ce 100644 --- a/panda/src/putil/buttonMap.cxx +++ b/panda/src/putil/buttonMap.cxx @@ -20,7 +20,7 @@ TypeHandle ButtonMap::_type_handle; * Registers a new button mapping. */ void ButtonMap:: -map_button(ButtonHandle raw_button, ButtonHandle button, const string &label) { +map_button(ButtonHandle raw_button, ButtonHandle button, const std::string &label) { int index = raw_button.get_index(); if (_button_map.find(index) != _button_map.end()) { // A button with this index was already mapped. @@ -39,7 +39,7 @@ map_button(ButtonHandle raw_button, ButtonHandle button, const string &label) { * */ void ButtonMap:: -output(ostream &out) const { +output(std::ostream &out) const { out << "ButtonMap (" << get_num_buttons() << " buttons)"; } @@ -47,7 +47,7 @@ output(ostream &out) const { * */ void ButtonMap:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "ButtonMap, " << get_num_buttons() << " buttons:\n"; diff --git a/panda/src/putil/buttonMap.h b/panda/src/putil/buttonMap.h index 1c375ad128..fca64c1146 100644 --- a/panda/src/putil/buttonMap.h +++ b/panda/src/putil/buttonMap.h @@ -32,24 +32,24 @@ PUBLISHED: INLINE size_t get_num_buttons() const; INLINE ButtonHandle get_raw_button(size_t i) const; INLINE ButtonHandle get_mapped_button(size_t i) const; - INLINE const string &get_mapped_button_label(size_t i) const; + INLINE const std::string &get_mapped_button_label(size_t i) const; INLINE ButtonHandle get_mapped_button(ButtonHandle raw) const; - INLINE ButtonHandle get_mapped_button(const string &raw_name) const; - INLINE const string &get_mapped_button_label(ButtonHandle raw) const; - INLINE const string &get_mapped_button_label(const string &raw_name) const; + INLINE ButtonHandle get_mapped_button(const std::string &raw_name) const; + INLINE const std::string &get_mapped_button_label(ButtonHandle raw) const; + INLINE const std::string &get_mapped_button_label(const std::string &raw_name) const; - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; public: - void map_button(ButtonHandle raw_button, ButtonHandle button, const string &label = ""); + void map_button(ButtonHandle raw_button, ButtonHandle button, const std::string &label = ""); private: struct ButtonNode { ButtonHandle _raw; ButtonHandle _mapped; - string _label; + std::string _label; }; pmap _button_map; diff --git a/panda/src/putil/buttonRegistry.I b/panda/src/putil/buttonRegistry.I index b531b444f5..74fe89471c 100644 --- a/panda/src/putil/buttonRegistry.I +++ b/panda/src/putil/buttonRegistry.I @@ -17,7 +17,7 @@ * */ INLINE ButtonRegistry::RegistryNode:: -RegistryNode(ButtonHandle handle, ButtonHandle alias, const string &name) : +RegistryNode(ButtonHandle handle, ButtonHandle alias, const std::string &name) : _handle(handle), _alias(alias), _name(name) { } @@ -27,7 +27,7 @@ RegistryNode(ButtonHandle handle, ButtonHandle alias, const string &name) : */ INLINE ButtonRegistry *ButtonRegistry:: ptr() { - if (_global_pointer == (ButtonRegistry *)NULL) { + if (_global_pointer == nullptr) { init_global_pointer(); } return _global_pointer; @@ -36,10 +36,10 @@ ptr() { /** * Returns the name of the indicated button. */ -INLINE string ButtonRegistry:: +INLINE std::string ButtonRegistry:: get_name(ButtonHandle button) const { RegistryNode *rnode = look_up(button); - nassertr(rnode != (RegistryNode *)NULL, ""); + nassertr(rnode != nullptr, ""); return rnode->_name; } @@ -50,6 +50,6 @@ get_name(ButtonHandle button) const { INLINE ButtonHandle ButtonRegistry:: get_alias(ButtonHandle button) const { RegistryNode *rnode = look_up(button); - nassertr(rnode != (RegistryNode *)NULL, ButtonHandle::none()); + nassertr(rnode != nullptr, ButtonHandle::none()); return rnode->_alias; } diff --git a/panda/src/putil/buttonRegistry.cxx b/panda/src/putil/buttonRegistry.cxx index 594a5864fd..1800d9e88a 100644 --- a/panda/src/putil/buttonRegistry.cxx +++ b/panda/src/putil/buttonRegistry.cxx @@ -21,7 +21,7 @@ // and we must use the arrow syntax to force initialization of the util_cat // category. -ButtonRegistry *ButtonRegistry::_global_pointer = NULL; +ButtonRegistry *ButtonRegistry::_global_pointer = nullptr; /** @@ -41,7 +41,7 @@ ButtonRegistry *ButtonRegistry::_global_pointer = NULL; * right. */ bool ButtonRegistry:: -register_button(ButtonHandle &button_handle, const string &name, +register_button(ButtonHandle &button_handle, const std::string &name, ButtonHandle alias, char ascii_equivalent) { NameRegistry::iterator ri; ri = _name_registry.find(name); @@ -52,7 +52,7 @@ register_button(ButtonHandle &button_handle, const string &name, int index = -1; if (ascii_equivalent != '\0') { - if (_handle_registry[ascii_equivalent] == (RegistryNode *)NULL) { + if (_handle_registry[ascii_equivalent] == nullptr) { index = ascii_equivalent; } else { util_cat->error() @@ -73,7 +73,7 @@ register_button(ButtonHandle &button_handle, const string &name, if (index == -1) { // It's not an ASCII equivalent; make up a new number. index = _handle_registry.size(); - _handle_registry.push_back(NULL); + _handle_registry.push_back(nullptr); } ButtonHandle new_handle; @@ -109,7 +109,7 @@ register_button(ButtonHandle &button_handle, const string &name, * is no such ButtonHandle, registers a new one and returns it. */ ButtonHandle ButtonRegistry:: -get_button(const string &name) { +get_button(const std::string &name) { NameRegistry::const_iterator ri; ri = _name_registry.find(name); @@ -127,7 +127,7 @@ get_button(const string &name) { * is no such ButtonHandle, returns ButtonHandle::none(). */ ButtonHandle ButtonRegistry:: -find_button(const string &name) { +find_button(const std::string &name) { NameRegistry::const_iterator ri; ri = _name_registry.find(name); @@ -145,7 +145,7 @@ find_button(const string &name) { */ ButtonHandle ButtonRegistry:: find_ascii_button(char ascii_equivalent) const { - if (_handle_registry[ascii_equivalent] == (RegistryNode *)NULL) { + if (_handle_registry[ascii_equivalent] == nullptr) { return ButtonHandle::none(); } return _handle_registry[ascii_equivalent]->_handle; @@ -155,10 +155,10 @@ find_ascii_button(char ascii_equivalent) const { * */ void ButtonRegistry:: -write(ostream &out) const { +write(std::ostream &out) const { out << "ASCII equivalents:\n"; for (int i = 1; i < 128; i++) { - if (_handle_registry[i] != (RegistryNode *)NULL) { + if (_handle_registry[i] != nullptr) { char hex[12]; sprintf(hex, "%02x", (unsigned int)i); nassertv(strlen(hex) < 12); @@ -192,7 +192,7 @@ ButtonRegistry() { _handle_registry.reserve(128); int i; for (i = 0; i < 128; i++) { - _handle_registry.push_back(NULL); + _handle_registry.push_back(nullptr); } } @@ -210,14 +210,14 @@ init_global_pointer() { */ ButtonRegistry::RegistryNode *ButtonRegistry:: look_up(ButtonHandle handle) const { - nassertr(handle._index != 0, NULL); + nassertr(handle._index != 0, nullptr); if (handle._index < 0 || handle._index >= (int)_handle_registry.size()) { util_cat->fatal() << "Invalid ButtonHandle index " << handle._index << "! Is memory corrupt?\n"; - return (RegistryNode *)NULL; + return nullptr; } return _handle_registry[handle._index]; diff --git a/panda/src/putil/buttonRegistry.h b/panda/src/putil/buttonRegistry.h index c57efbf089..19a315ae90 100644 --- a/panda/src/putil/buttonRegistry.h +++ b/panda/src/putil/buttonRegistry.h @@ -31,30 +31,30 @@ protected: class EXPCL_PANDA_PUTIL RegistryNode { public: INLINE RegistryNode(ButtonHandle handle, ButtonHandle alias, - const string &name); + const std::string &name); ButtonHandle _handle; ButtonHandle _alias; - string _name; + std::string _name; }; public: - bool register_button(ButtonHandle &button_handle, const string &name, + bool register_button(ButtonHandle &button_handle, const std::string &name, ButtonHandle alias = ButtonHandle::none(), char ascii_equivalent = '\0'); PUBLISHED: - ButtonHandle get_button(const string &name); - ButtonHandle find_button(const string &name); + ButtonHandle get_button(const std::string &name); + ButtonHandle find_button(const std::string &name); ButtonHandle find_ascii_button(char ascii_equivalent) const; - void write(ostream &out) const; + void write(std::ostream &out) const; // ptr() returns the pointer to the global ButtonRegistry object. INLINE static ButtonRegistry *ptr(); public: - INLINE string get_name(ButtonHandle button) const; + INLINE std::string get_name(ButtonHandle button) const; INLINE ButtonHandle get_alias(ButtonHandle button) const; private: @@ -69,7 +69,7 @@ private: typedef pvector HandleRegistry; HandleRegistry _handle_registry; - typedef pmap NameRegistry; + typedef pmap NameRegistry; NameRegistry _name_registry; static ButtonRegistry *_global_pointer; diff --git a/panda/src/putil/cachedTypedWritableReferenceCount.I b/panda/src/putil/cachedTypedWritableReferenceCount.I index 1d60f9a614..dae8502d4b 100644 --- a/panda/src/putil/cachedTypedWritableReferenceCount.I +++ b/panda/src/putil/cachedTypedWritableReferenceCount.I @@ -49,8 +49,6 @@ CachedTypedWritableReferenceCount(const CachedTypedWritableReferenceCount ©) */ INLINE void CachedTypedWritableReferenceCount:: operator = (const CachedTypedWritableReferenceCount ©) { - nassertv(this != NULL); - // If this assertion fails, our own pointer was recently deleted. Possibly // you used a real pointer instead of a PointerTo at some point, and the // object was deleted when the PointerTo went out of scope. Maybe you tried @@ -71,8 +69,6 @@ operator = (const CachedTypedWritableReferenceCount ©) { */ INLINE CachedTypedWritableReferenceCount:: ~CachedTypedWritableReferenceCount() { - nassertv(this != NULL); - // If this assertion fails, we're trying to delete an object that was just // deleted. Possibly you used a real pointer instead of a PointerTo at some // point, and the object was deleted when the PointerTo went out of scope. diff --git a/panda/src/putil/cachedTypedWritableReferenceCount.cxx b/panda/src/putil/cachedTypedWritableReferenceCount.cxx index 53e4fa355a..d7ee3ed74d 100644 --- a/panda/src/putil/cachedTypedWritableReferenceCount.cxx +++ b/panda/src/putil/cachedTypedWritableReferenceCount.cxx @@ -21,8 +21,6 @@ TypeHandle CachedTypedWritableReferenceCount::_type_handle; */ bool CachedTypedWritableReferenceCount:: do_test_ref_count_integrity() const { - nassertr(this != NULL, false); - // If this assertion fails, we're trying to delete an object that was just // deleted. Possibly you used a real pointer instead of a PointerTo at some // point, and the object was deleted when the PointerTo went out of scope. diff --git a/panda/src/putil/callbackData.cxx b/panda/src/putil/callbackData.cxx index de7eac9678..1a3f15672b 100644 --- a/panda/src/putil/callbackData.cxx +++ b/panda/src/putil/callbackData.cxx @@ -20,7 +20,7 @@ TypeHandle CallbackData::_type_handle; * */ void CallbackData:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type(); } diff --git a/panda/src/putil/callbackData.h b/panda/src/putil/callbackData.h index 8380788e13..b1b084bdf9 100644 --- a/panda/src/putil/callbackData.h +++ b/panda/src/putil/callbackData.h @@ -31,7 +31,7 @@ protected: INLINE CallbackData(); PUBLISHED: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; virtual void upcall(); @@ -53,7 +53,7 @@ private: static TypeHandle _type_handle; }; -inline ostream &operator << (ostream &out, const CallbackData &cbd) { +inline std::ostream &operator << (std::ostream &out, const CallbackData &cbd) { cbd.output(out); return out; } diff --git a/panda/src/putil/callbackObject.cxx b/panda/src/putil/callbackObject.cxx index 9f1ce360ac..579b0299b7 100644 --- a/panda/src/putil/callbackObject.cxx +++ b/panda/src/putil/callbackObject.cxx @@ -20,7 +20,7 @@ TypeHandle CallbackObject::_type_handle; * */ void CallbackObject:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type(); } diff --git a/panda/src/putil/callbackObject.h b/panda/src/putil/callbackObject.h index 320fb9c0ef..0702c704f5 100644 --- a/panda/src/putil/callbackObject.h +++ b/panda/src/putil/callbackObject.h @@ -32,7 +32,7 @@ public: ALLOC_DELETED_CHAIN(CallbackObject); PUBLISHED: - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; EXTENSION(static PT(CallbackObject) make(PyObject *function)); @@ -57,7 +57,7 @@ private: static TypeHandle _type_handle; }; -inline ostream &operator << (ostream &out, const CallbackObject &cbo) { +inline std::ostream &operator << (std::ostream &out, const CallbackObject &cbo) { cbo.output(out); return out; } diff --git a/panda/src/putil/callbackObject_ext.I b/panda/src/putil/callbackObject_ext.I index 12edcf6b23..536ba2ac97 100644 --- a/panda/src/putil/callbackObject_ext.I +++ b/panda/src/putil/callbackObject_ext.I @@ -20,7 +20,7 @@ INLINE PT(CallbackObject) Extension:: make(PyObject *function) { if (function != Py_None && !PyCallable_Check(function)) { PyErr_SetString(PyExc_TypeError, "expected callable or None"); - return NULL; + return nullptr; } else { return new PythonCallbackObject(function); } diff --git a/panda/src/putil/clockObject.I b/panda/src/putil/clockObject.I index f8a0bbc02b..b2cb2975d1 100644 --- a/panda/src/putil/clockObject.I +++ b/panda/src/putil/clockObject.I @@ -110,7 +110,7 @@ INLINE double ClockObject:: get_dt(Thread *current_thread) const { CDReader cdata(_cycler, current_thread); if (_max_dt > 0.0) { - return min(_max_dt, cdata->_dt); + return std::min(_max_dt, cdata->_dt); } return cdata->_dt; } diff --git a/panda/src/putil/clockObject.cxx b/panda/src/putil/clockObject.cxx index 341a11374a..0eb72647e4 100644 --- a/panda/src/putil/clockObject.cxx +++ b/panda/src/putil/clockObject.cxx @@ -17,6 +17,10 @@ #include "string_utils.h" #include "thread.h" +using std::istream; +using std::ostream; +using std::string; + void (*ClockObject::_start_clock_wait)() = ClockObject::dummy_clock_wait; void (*ClockObject::_start_clock_busy_wait)() = ClockObject::dummy_clock_wait; void (*ClockObject::_stop_clock_wait)() = ClockObject::dummy_clock_wait; @@ -351,7 +355,7 @@ tick(Thread *current_thread) { // In case someone munged the clock last frame and sent us backward in // time, clamp the previous time to the current time to make sure we don't // report anything strange (or wait interminably). - old_time = min(old_time, _actual_frame_time); + old_time = std::min(old_time, _actual_frame_time); ++cdata->_frame_count; @@ -375,7 +379,7 @@ tick(Thread *current_thread) { double wait_until_time = old_time + 1.0 / _user_frame_rate; wait_until(wait_until_time); cdata->_dt = _actual_frame_time - old_time; - cdata->_reported_frame_time = max(_actual_frame_time, wait_until_time); + cdata->_reported_frame_time = std::max(_actual_frame_time, wait_until_time); } break; diff --git a/panda/src/putil/clockObject.h b/panda/src/putil/clockObject.h index bcea511f29..4e06ec2554 100644 --- a/panda/src/putil/clockObject.h +++ b/panda/src/putil/clockObject.h @@ -188,10 +188,10 @@ private: static TypeHandle _type_handle; }; -EXPCL_PANDA_PUTIL ostream & -operator << (ostream &out, ClockObject::Mode mode); -EXPCL_PANDA_PUTIL istream & -operator >> (istream &in, ClockObject::Mode &mode); +EXPCL_PANDA_PUTIL std::ostream & +operator << (std::ostream &out, ClockObject::Mode mode); +EXPCL_PANDA_PUTIL std::istream & +operator >> (std::istream &in, ClockObject::Mode &mode); #include "clockObject.I" diff --git a/panda/src/putil/colorSpace.cxx b/panda/src/putil/colorSpace.cxx index 075eb438a1..3a244a68eb 100644 --- a/panda/src/putil/colorSpace.cxx +++ b/panda/src/putil/colorSpace.cxx @@ -21,6 +21,11 @@ #include +using std::istream; +using std::ostream; +using std::ostringstream; +using std::string; + ColorSpace parse_color_space_string(const string &str) { if (cmp_nocase_uh(str, "linear") == 0 || diff --git a/panda/src/putil/colorSpace.h b/panda/src/putil/colorSpace.h index 97d70ad49f..9c9d237cc6 100644 --- a/panda/src/putil/colorSpace.h +++ b/panda/src/putil/colorSpace.h @@ -42,12 +42,12 @@ enum ColorSpace { CS_scRGB, }; -EXPCL_PANDA_PUTIL ColorSpace parse_color_space_string(const string &str); -EXPCL_PANDA_PUTIL string format_color_space(ColorSpace cs); +EXPCL_PANDA_PUTIL ColorSpace parse_color_space_string(const std::string &str); +EXPCL_PANDA_PUTIL std::string format_color_space(ColorSpace cs); END_PUBLISH -EXPCL_PANDA_PUTIL ostream &operator << (ostream &out, ColorSpace cs); -EXPCL_PANDA_PUTIL istream &operator >> (istream &in, ColorSpace &cs); +EXPCL_PANDA_PUTIL std::ostream &operator << (std::ostream &out, ColorSpace cs); +EXPCL_PANDA_PUTIL std::istream &operator >> (std::istream &in, ColorSpace &cs); #endif diff --git a/panda/src/putil/config_putil.cxx b/panda/src/putil/config_putil.cxx index 5461b73f3f..c3083f306f 100644 --- a/panda/src/putil/config_putil.cxx +++ b/panda/src/putil/config_putil.cxx @@ -103,8 +103,8 @@ ConfigureFn(config_putil) { ConfigVariableSearchPath & get_model_path() { - static ConfigVariableSearchPath *model_path = NULL; - if (model_path == NULL) { + static ConfigVariableSearchPath *model_path = nullptr; + if (model_path == nullptr) { model_path = new ConfigVariableSearchPath ("model-path", PRC_DESC("The default directories to search for all models and general " @@ -116,8 +116,8 @@ get_model_path() { ConfigVariableSearchPath & get_plugin_path() { - static ConfigVariableSearchPath *plugin_path = NULL; - if (plugin_path == NULL) { + static ConfigVariableSearchPath *plugin_path = nullptr; + if (plugin_path == nullptr) { plugin_path = new ConfigVariableSearchPath ("plugin-path", "", PRC_DESC("The directories to search for plugin shared libraries.")); diff --git a/panda/src/putil/copyOnWriteObject.I b/panda/src/putil/copyOnWriteObject.I index 304e7214c5..bcf326d87c 100644 --- a/panda/src/putil/copyOnWriteObject.I +++ b/panda/src/putil/copyOnWriteObject.I @@ -32,7 +32,7 @@ CopyOnWriteObject() #endif #ifdef COW_THREADED _lock_status = LS_unlocked; - _locking_thread = NULL; + _locking_thread = nullptr; #endif // COW_THREADED } @@ -52,7 +52,7 @@ CopyOnWriteObject(const CopyOnWriteObject ©) : #endif #ifdef COW_THREADED _lock_status = LS_unlocked; - _locking_thread = NULL; + _locking_thread = nullptr; #endif // COW_THREADED } @@ -130,9 +130,9 @@ void CopyOnWriteObj:: init_type() { #if defined(HAVE_RTTI) && !defined(__EDG__) // If we have RTTI, we can determine the name of the base type. - string base_name = typeid(Base).name(); + std::string base_name = typeid(Base).name(); #else - string base_name = "unknown"; + std::string base_name = "unknown"; #endif TypeHandle base_type = register_dynamic_type(base_name); @@ -190,9 +190,9 @@ void CopyOnWriteObj1:: init_type() { #if defined(HAVE_RTTI) && !defined(__EDG__) // If we have RTTI, we can determine the name of the base type. - string base_name = typeid(Base).name(); + std::string base_name = typeid(Base).name(); #else - string base_name = "unknown"; + std::string base_name = "unknown"; #endif TypeHandle base_type = register_dynamic_type(base_name); diff --git a/panda/src/putil/copyOnWriteObject.cxx b/panda/src/putil/copyOnWriteObject.cxx index 172f354319..e039f12450 100644 --- a/panda/src/putil/copyOnWriteObject.cxx +++ b/panda/src/putil/copyOnWriteObject.cxx @@ -30,7 +30,7 @@ unref() const { bool is_zero = CachedTypedWritableReferenceCount::unref(); if (get_ref_count() == get_cache_ref_count()) { ((CopyOnWriteObject *)this)->_lock_status = LS_unlocked; - ((CopyOnWriteObject *)this)->_locking_thread = NULL; + ((CopyOnWriteObject *)this)->_locking_thread = nullptr; ((CopyOnWriteObject *)this)->_lock_cvar.notify(); } return is_zero; @@ -48,7 +48,7 @@ cache_ref_only() const { CachedTypedWritableReferenceCount::cache_ref_only(); if (get_ref_count() == get_cache_ref_count()) { ((CopyOnWriteObject *)this)->_lock_status = LS_unlocked; - ((CopyOnWriteObject *)this)->_locking_thread = NULL; + ((CopyOnWriteObject *)this)->_locking_thread = nullptr; ((CopyOnWriteObject *)this)->_lock_cvar.notify(); } } diff --git a/panda/src/putil/copyOnWritePointer.I b/panda/src/putil/copyOnWritePointer.I index 9e996355fa..2f5f79b281 100644 --- a/panda/src/putil/copyOnWritePointer.I +++ b/panda/src/putil/copyOnWritePointer.I @@ -18,7 +18,7 @@ INLINE CopyOnWritePointer:: CopyOnWritePointer(CopyOnWriteObject *object) : _cow_object(object) { - if (_cow_object != (CopyOnWriteObject *)NULL) { + if (_cow_object != nullptr) { _cow_object->cache_ref(); } } @@ -30,7 +30,7 @@ INLINE CopyOnWritePointer:: CopyOnWritePointer(const CopyOnWritePointer ©) : _cow_object(copy._cow_object) { - if (_cow_object != (CopyOnWriteObject *)NULL) { + if (_cow_object != nullptr) { _cow_object->cache_ref(); } } @@ -49,11 +49,11 @@ operator = (const CopyOnWritePointer ©) { INLINE void CopyOnWritePointer:: operator = (CopyOnWriteObject *object) { if (_cow_object != object) { - if (_cow_object != (CopyOnWriteObject *)NULL) { + if (_cow_object != nullptr) { cache_unref_delete(_cow_object); } _cow_object = object; - if (_cow_object != (CopyOnWriteObject *)NULL) { + if (_cow_object != nullptr) { _cow_object->cache_ref(); } } @@ -64,50 +64,49 @@ operator = (CopyOnWriteObject *object) { */ INLINE CopyOnWritePointer:: ~CopyOnWritePointer() { - if (_cow_object != (CopyOnWriteObject *)NULL) { + if (_cow_object != nullptr) { cache_unref_delete(_cow_object); } } -#ifdef USE_MOVE_SEMANTICS /** * */ INLINE CopyOnWritePointer:: -CopyOnWritePointer(CopyOnWritePointer &&from) NOEXCEPT : +CopyOnWritePointer(CopyOnWritePointer &&from) noexcept : _cow_object(from._cow_object) { // Steal the other's reference count. - from._cow_object = (CopyOnWriteObject *)NULL; + from._cow_object = nullptr; } /** * */ INLINE CopyOnWritePointer:: -CopyOnWritePointer(PointerTo &&from) NOEXCEPT : +CopyOnWritePointer(PointerTo &&from) noexcept : _cow_object(from.p()) { // Steal the other's reference count, but because it is a regular pointer, // we do need to include the cache reference count. - if (_cow_object != (CopyOnWriteObject *)NULL) { + if (_cow_object != nullptr) { _cow_object->cache_ref_only(); } - from.cheat() = NULL; + from.cheat() = nullptr; } /** * */ INLINE void CopyOnWritePointer:: -operator = (CopyOnWritePointer &&from) NOEXCEPT { +operator = (CopyOnWritePointer &&from) noexcept { // Protect against self-move-assignment. if (from._cow_object != _cow_object) { CopyOnWriteObject *old_object = _cow_object; _cow_object = from._cow_object; - from._cow_object = NULL; + from._cow_object = nullptr; - if (old_object != (CopyOnWriteObject *)NULL) { + if (old_object != nullptr) { cache_unref_delete(old_object); } } @@ -117,7 +116,7 @@ operator = (CopyOnWritePointer &&from) NOEXCEPT { * */ INLINE void CopyOnWritePointer:: -operator = (PointerTo &&from) NOEXCEPT { +operator = (PointerTo &&from) noexcept { if (from.p() != _cow_object) { CopyOnWriteObject *old_object = _cow_object; @@ -125,14 +124,13 @@ operator = (PointerTo &&from) NOEXCEPT { // we do need to include the cache reference count. _cow_object = from.p(); _cow_object->cache_ref_only(); - from.cheat() = NULL; + from.cheat() = nullptr; - if (old_object != (CopyOnWriteObject *)NULL) { + if (old_object != nullptr) { cache_unref_delete(old_object); } } } -#endif // USE_MOVE_SEMANTICS /** * @@ -183,8 +181,8 @@ get_read_pointer(Thread *current_thread) const { */ INLINE CopyOnWriteObject *CopyOnWritePointer:: get_write_pointer() { - if (_cow_object == (CopyOnWriteObject *)NULL) { - return NULL; + if (_cow_object == nullptr) { + return nullptr; } if (_cow_object->get_cache_ref_count() > 1) { PT(CopyOnWriteObject) new_object = _cow_object->make_cow_copy(); @@ -212,7 +210,7 @@ get_unsafe_pointer() { */ bool CopyOnWritePointer:: is_null() const { - return (_cow_object == (CopyOnWriteObject *)NULL); + return (_cow_object == nullptr); } /** @@ -220,10 +218,10 @@ is_null() const { */ void CopyOnWritePointer:: clear() { - if (_cow_object != (CopyOnWriteObject *)NULL) { + if (_cow_object != nullptr) { cache_unref_delete(_cow_object); } - _cow_object = NULL; + _cow_object = nullptr; } /** @@ -232,7 +230,7 @@ clear() { */ INLINE bool CopyOnWritePointer:: test_ref_count_integrity() const { - nassertr(_cow_object != (CopyOnWriteObject *)NULL, false); + nassertr(_cow_object != nullptr, false); return _cow_object->test_ref_count_integrity(); } @@ -242,7 +240,7 @@ test_ref_count_integrity() const { */ INLINE bool CopyOnWritePointer:: test_ref_count_nonzero() const { - nassertr(_cow_object != (CopyOnWriteObject *)NULL, false); + nassertr(_cow_object != nullptr, false); return _cow_object->test_ref_count_nonzero(); } @@ -290,14 +288,13 @@ operator = (To *object) { } #endif // CPPPARSER -#ifdef USE_MOVE_SEMANTICS #ifndef CPPPARSER /** * */ template INLINE CopyOnWritePointerTo:: -CopyOnWritePointerTo(CopyOnWritePointerTo &&from) NOEXCEPT : +CopyOnWritePointerTo(CopyOnWritePointerTo &&from) noexcept : CopyOnWritePointer((CopyOnWritePointer &&)from) { } @@ -309,14 +306,14 @@ CopyOnWritePointerTo(CopyOnWritePointerTo &&from) NOEXCEPT : */ template INLINE CopyOnWritePointerTo:: -CopyOnWritePointerTo(PointerTo &&from) NOEXCEPT { +CopyOnWritePointerTo(PointerTo &&from) noexcept { // Steal the other's reference count, but because it is a regular pointer, // we do need to include the cache reference count. _cow_object = from.p(); - if (_cow_object != (CopyOnWriteObject *)NULL) { + if (_cow_object != nullptr) { _cow_object->cache_ref_only(); } - from.cheat() = NULL; + from.cheat() = nullptr; } #endif // CPPPARSER @@ -326,7 +323,7 @@ CopyOnWritePointerTo(PointerTo &&from) NOEXCEPT { */ template INLINE void CopyOnWritePointerTo:: -operator = (CopyOnWritePointerTo &&from) NOEXCEPT { +operator = (CopyOnWritePointerTo &&from) noexcept { CopyOnWritePointer::operator = ((CopyOnWritePointer &&)from); } #endif // CPPPARSER @@ -337,7 +334,7 @@ operator = (CopyOnWritePointerTo &&from) NOEXCEPT { */ template INLINE void CopyOnWritePointerTo:: -operator = (PointerTo &&from) NOEXCEPT { +operator = (PointerTo &&from) noexcept { if (from.p() != _cow_object) { CopyOnWriteObject *old_object = _cow_object; @@ -345,15 +342,14 @@ operator = (PointerTo &&from) NOEXCEPT { // we do need to include the cache reference count. _cow_object = from.p(); _cow_object->cache_ref_only(); - from.cheat() = NULL; + from.cheat() = nullptr; - if (old_object != (CopyOnWriteObject *)NULL) { + if (old_object != nullptr) { cache_unref_delete(old_object); } } } #endif // CPPPARSER -#endif // USE_MOVE_SEMANTICS #ifndef CPPPARSER #ifdef COW_THREADED @@ -361,11 +357,11 @@ operator = (PointerTo &&from) NOEXCEPT { * See CopyOnWritePointer::get_read_pointer(). */ template -INLINE CPT(TYPENAME CopyOnWritePointerTo::To) CopyOnWritePointerTo:: +INLINE CPT(typename CopyOnWritePointerTo::To) CopyOnWritePointerTo:: get_read_pointer(Thread *current_thread) const { // This is necessary because we don't currently have a way to cast between // two compatible PointerTo types without losing the reference count. - CPT(TYPENAME CopyOnWritePointerTo::To) to; + CPT(typename CopyOnWritePointerTo::To) to; CPT(CopyOnWriteObject) from = CopyOnWritePointer::get_read_pointer(current_thread); to.cheat() = (const To *)from.p(); from.cheat() = nullptr; @@ -376,7 +372,7 @@ get_read_pointer(Thread *current_thread) const { * See CopyOnWritePointer::get_read_pointer(). */ template -INLINE const TYPENAME CopyOnWritePointerTo::To *CopyOnWritePointerTo:: +INLINE const typename CopyOnWritePointerTo::To *CopyOnWritePointerTo:: get_read_pointer(Thread *current_thread) const { return (const To *)CopyOnWritePointer::get_read_pointer(current_thread); } @@ -389,11 +385,11 @@ get_read_pointer(Thread *current_thread) const { * See CopyOnWritePointer::get_write_pointer(). */ template -INLINE PT(TYPENAME CopyOnWritePointerTo::To) CopyOnWritePointerTo:: +INLINE PT(typename CopyOnWritePointerTo::To) CopyOnWritePointerTo:: get_write_pointer() { // This is necessary because we don't currently have a way to cast between // two compatible PointerTo types without losing the reference count. - PT(TYPENAME CopyOnWritePointerTo::To) to; + PT(typename CopyOnWritePointerTo::To) to; PT(CopyOnWriteObject) from = CopyOnWritePointer::get_write_pointer(); to.cheat() = (To *)from.p(); from.cheat() = nullptr; @@ -404,7 +400,7 @@ get_write_pointer() { * See CopyOnWritePointer::get_write_pointer(). */ template -INLINE TYPENAME CopyOnWritePointerTo::To *CopyOnWritePointerTo:: +INLINE typename CopyOnWritePointerTo::To *CopyOnWritePointerTo:: get_write_pointer() { return (To *)CopyOnWritePointer::get_write_pointer(); } @@ -416,7 +412,7 @@ get_write_pointer() { * See CopyOnWritePointer::get_unsafe_pointer(). */ template -INLINE TYPENAME CopyOnWritePointerTo::To *CopyOnWritePointerTo:: +INLINE typename CopyOnWritePointerTo::To *CopyOnWritePointerTo:: get_unsafe_pointer() { return (To *)(CopyOnWritePointer::get_unsafe_pointer()); } diff --git a/panda/src/putil/copyOnWritePointer.cxx b/panda/src/putil/copyOnWritePointer.cxx index 4beb105ada..35a4aa8da0 100644 --- a/panda/src/putil/copyOnWritePointer.cxx +++ b/panda/src/putil/copyOnWritePointer.cxx @@ -24,8 +24,8 @@ */ CPT(CopyOnWriteObject) CopyOnWritePointer:: get_read_pointer(Thread *current_thread) const { - if (_cow_object == (CopyOnWriteObject *)NULL) { - return NULL; + if (_cow_object == nullptr) { + return nullptr; } MutexHolder holder(_cow_object->_lock_mutex); @@ -60,13 +60,13 @@ get_read_pointer(Thread *current_thread) const { */ PT(CopyOnWriteObject) CopyOnWritePointer:: get_write_pointer() { - if (_cow_object == (CopyOnWriteObject *)NULL) { - return NULL; + if (_cow_object == nullptr) { + return nullptr; } Thread *current_thread = Thread::get_current_thread(); - _cow_object->_lock_mutex.acquire(); + _cow_object->_lock_mutex.lock(); while (_cow_object->_lock_status == CopyOnWriteObject::LS_locked_write && _cow_object->_locking_thread != current_thread) { if (util_cat.is_debug()) { @@ -79,7 +79,7 @@ get_write_pointer() { } if (_cow_object->_lock_status == CopyOnWriteObject::LS_locked_read) { - nassertr(_cow_object->get_ref_count() > _cow_object->get_cache_ref_count(), NULL); + nassertr(_cow_object->get_ref_count() > _cow_object->get_cache_ref_count(), nullptr); if (util_cat.is_debug()) { util_cat.debug() @@ -89,7 +89,7 @@ get_write_pointer() { PT(CopyOnWriteObject) new_object = _cow_object->make_cow_copy(); _cow_object->CachedTypedWritableReferenceCount::cache_unref(); - _cow_object->_lock_mutex.release(); + _cow_object->_lock_mutex.unlock(); MutexHolder holder(new_object->_lock_mutex); _cow_object = new_object; @@ -112,7 +112,7 @@ get_write_pointer() { PT(CopyOnWriteObject) new_object = _cow_object->make_cow_copy(); _cow_object->CachedTypedWritableReferenceCount::cache_unref(); - _cow_object->_lock_mutex.release(); + _cow_object->_lock_mutex.unlock(); MutexHolder holder(new_object->_lock_mutex); _cow_object = new_object; @@ -132,7 +132,7 @@ get_write_pointer() { // reference. _cow_object->_lock_status = CopyOnWriteObject::LS_locked_write; _cow_object->_locking_thread = current_thread; - _cow_object->_lock_mutex.release(); + _cow_object->_lock_mutex.unlock(); } return _cow_object; diff --git a/panda/src/putil/copyOnWritePointer.h b/panda/src/putil/copyOnWritePointer.h index 2178b6b433..24e0ffff64 100644 --- a/panda/src/putil/copyOnWritePointer.h +++ b/panda/src/putil/copyOnWritePointer.h @@ -30,18 +30,16 @@ */ class EXPCL_PANDA_PUTIL CopyOnWritePointer { public: - INLINE CopyOnWritePointer(CopyOnWriteObject *object = NULL); + INLINE CopyOnWritePointer(CopyOnWriteObject *object = nullptr); INLINE CopyOnWritePointer(const CopyOnWritePointer ©); - INLINE void operator = (const CopyOnWritePointer ©); - INLINE void operator = (CopyOnWriteObject *object); + INLINE CopyOnWritePointer(CopyOnWritePointer &&from) noexcept; + INLINE CopyOnWritePointer(PointerTo &&from) noexcept; INLINE ~CopyOnWritePointer(); -#ifdef USE_MOVE_SEMANTICS - INLINE CopyOnWritePointer(CopyOnWritePointer &&from) NOEXCEPT; - INLINE CopyOnWritePointer(PointerTo &&from) NOEXCEPT; - INLINE void operator = (CopyOnWritePointer &&from) NOEXCEPT; - INLINE void operator = (PointerTo &&from) NOEXCEPT; -#endif + INLINE void operator = (const CopyOnWritePointer ©); + INLINE void operator = (CopyOnWritePointer &&from) noexcept; + INLINE void operator = (PointerTo &&from) noexcept; + INLINE void operator = (CopyOnWriteObject *object); INLINE bool operator == (const CopyOnWritePointer &other) const; INLINE bool operator != (const CopyOnWritePointer &other) const; @@ -80,17 +78,15 @@ public: #ifndef CPPPARSER typedef T To; - INLINE CopyOnWritePointerTo(To *object = NULL); + INLINE CopyOnWritePointerTo(To *object = nullptr); INLINE CopyOnWritePointerTo(const CopyOnWritePointerTo ©); + INLINE CopyOnWritePointerTo(CopyOnWritePointerTo &&from) noexcept; + INLINE CopyOnWritePointerTo(PointerTo &&from) noexcept; + INLINE void operator = (const CopyOnWritePointerTo ©); INLINE void operator = (To *object); - -#ifdef USE_MOVE_SEMANTICS - INLINE CopyOnWritePointerTo(CopyOnWritePointerTo &&from) NOEXCEPT; - INLINE CopyOnWritePointerTo(PointerTo &&from) NOEXCEPT; - INLINE void operator = (CopyOnWritePointerTo &&from) NOEXCEPT; - INLINE void operator = (PointerTo &&from) NOEXCEPT; -#endif + INLINE void operator = (CopyOnWritePointerTo &&from) noexcept; + INLINE void operator = (PointerTo &&from) noexcept; #ifdef COW_THREADED INLINE CPT(To) get_read_pointer(Thread *current_thread = Thread::get_current_thread()) const; diff --git a/panda/src/putil/datagramBuffer.I b/panda/src/putil/datagramBuffer.I index 123642db9f..4ee99b8da0 100644 --- a/panda/src/putil/datagramBuffer.I +++ b/panda/src/putil/datagramBuffer.I @@ -26,7 +26,7 @@ DatagramBuffer() : */ INLINE DatagramBuffer:: DatagramBuffer(vector_uchar data) : - _data(move(data)), + _data(std::move(data)), _read_offset(0), _wrote_first_datagram(false), _read_first_datagram(false) { @@ -56,7 +56,7 @@ get_data() const { */ INLINE void DatagramBuffer:: set_data(vector_uchar data) { - _data = move(data); + _data = std::move(data); } /** diff --git a/panda/src/putil/datagramBuffer.cxx b/panda/src/putil/datagramBuffer.cxx index c9831a4f82..7b1acb4ba1 100644 --- a/panda/src/putil/datagramBuffer.cxx +++ b/panda/src/putil/datagramBuffer.cxx @@ -20,7 +20,7 @@ * written. */ bool DatagramBuffer:: -write_header(const string &header) { +write_header(const std::string &header) { nassertr(!_wrote_first_datagram, false); _data.insert(_data.end(), header.begin(), header.end()); @@ -78,13 +78,13 @@ flush() { * has been read. */ bool DatagramBuffer:: -read_header(string &header, size_t num_bytes) { +read_header(std::string &header, size_t num_bytes) { nassertr(!_read_first_datagram, false); if (_read_offset + num_bytes > _data.size()) { return false; } - header = string((char *)&_data[_read_offset], num_bytes); + header = std::string((char *)&_data[_read_offset], num_bytes); _read_offset += num_bytes; return true; } diff --git a/panda/src/putil/datagramBuffer.h b/panda/src/putil/datagramBuffer.h index 8962ddbb2b..7990b36e71 100644 --- a/panda/src/putil/datagramBuffer.h +++ b/panda/src/putil/datagramBuffer.h @@ -35,11 +35,11 @@ PUBLISHED: INLINE void clear(); public: - bool write_header(const string &header); + bool write_header(const std::string &header); virtual bool put_datagram(const Datagram &data) override; virtual void flush() override; - bool read_header(string &header, size_t num_bytes); + bool read_header(std::string &header, size_t num_bytes); virtual bool get_datagram(Datagram &data) override; virtual bool is_eof() override; diff --git a/panda/src/putil/datagramInputFile.I b/panda/src/putil/datagramInputFile.I index c956fef4ac..7f60129eb1 100644 --- a/panda/src/putil/datagramInputFile.I +++ b/panda/src/putil/datagramInputFile.I @@ -18,7 +18,7 @@ INLINE DatagramInputFile:: DatagramInputFile() { _error = false; _read_first_datagram = false; - _in = (istream *)NULL; + _in = nullptr; _owns_in = false; _timestamp = 0; } @@ -43,9 +43,9 @@ open(const Filename &filename) { /** * Returns the istream represented by the input file. */ -INLINE istream &DatagramInputFile:: +INLINE std::istream &DatagramInputFile:: get_stream() { - static ifstream null_stream; - nassertr(_in != NULL, null_stream); + static std::ifstream null_stream; + nassertr(_in != nullptr, null_stream); return *_in; } diff --git a/panda/src/putil/datagramInputFile.cxx b/panda/src/putil/datagramInputFile.cxx index 4fc9b47ffb..c4802ceed2 100644 --- a/panda/src/putil/datagramInputFile.cxx +++ b/panda/src/putil/datagramInputFile.cxx @@ -22,6 +22,9 @@ #include "streamReader.h" #include "thread.h" +using std::streampos; +using std::streamsize; + /** * Opens the indicated filename for reading. Returns true on success, false * on failure. @@ -38,13 +41,13 @@ open(const FileReference *file) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); _vfile = vfs->get_file(_filename); - if (_vfile == (VirtualFile *)NULL) { + if (_vfile == nullptr) { // No such file. return false; } _timestamp = _vfile->get_timestamp(); _in = _vfile->open_read_file(true); - _owns_in = (_in != (istream *)NULL); + _owns_in = (_in != nullptr); return _owns_in && !_in->fail(); } @@ -54,7 +57,7 @@ open(const FileReference *file) { * you are responsible for closing or deleting it when you are done. */ bool DatagramInputFile:: -open(istream &in, const Filename &filename) { +open(std::istream &in, const Filename &filename) { close(); _in = ∈ @@ -80,7 +83,7 @@ close() { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->close_read_file(_in); } - _in = (istream *)NULL; + _in = nullptr; _owns_in = false; _file.clear(); @@ -98,19 +101,19 @@ close() { * has been read. */ bool DatagramInputFile:: -read_header(string &header, size_t num_bytes) { +read_header(std::string &header, size_t num_bytes) { nassertr(!_read_first_datagram, false); - nassertr(_in != (istream *)NULL, false); + nassertr(_in != nullptr, false); char *buffer = (char *)alloca(num_bytes); - nassertr(buffer != (char *)NULL, false); + nassertr(buffer != nullptr, false); _in->read(buffer, num_bytes); if (_in->fail() || _in->eof()) { return false; } - header = string(buffer, num_bytes); + header = std::string(buffer, num_bytes); Thread::consider_yield(); return true; } @@ -121,7 +124,7 @@ read_header(string &header, size_t num_bytes) { */ bool DatagramInputFile:: get_datagram(Datagram &data) { - nassertr(_in != (istream *)NULL, false); + nassertr(_in != nullptr, false); _read_first_datagram = true; // First, get the size of the upcoming datagram. @@ -170,7 +173,7 @@ get_datagram(Datagram &data) { // standards. Let's take it 4MB at a time just in case the length is // corrupt, so we don't allocate potentially a few GBs of RAM only to // find a truncated file. - bytes_left = min(bytes_left, (size_t)4*1024*1024); + bytes_left = std::min(bytes_left, (size_t)4*1024*1024); PTA_uchar buffer = data.modify_array(); buffer.resize(buffer.size() + bytes_left); @@ -201,7 +204,7 @@ get_datagram(Datagram &data) { */ bool DatagramInputFile:: save_datagram(SubfileInfo &info) { - nassertr(_in != (istream *)NULL, false); + nassertr(_in != nullptr, false); _read_first_datagram = true; // First, get the size of the upcoming datagram. @@ -219,9 +222,9 @@ save_datagram(SubfileInfo &info) { // If this stream is file-based, we can just point the SubfileInfo directly // into this file. - if (_file != (FileReference *)NULL) { + if (_file != nullptr) { info = SubfileInfo(_file, _in->tellg(), num_bytes); - _in->seekg(num_bytes, ios::cur); + _in->seekg(num_bytes, std::ios::cur); return true; } @@ -245,7 +248,7 @@ save_datagram(SubfileInfo &info) { static const size_t buffer_size = 4096; char buffer[buffer_size]; - _in->read(buffer, min((streamsize)buffer_size, num_remaining)); + _in->read(buffer, std::min((streamsize)buffer_size, num_remaining)); streamsize count = _in->gcount(); while (count != 0) { out.write(buffer, count); @@ -259,7 +262,7 @@ save_datagram(SubfileInfo &info) { if (num_remaining == 0) { break; } - _in->read(buffer, min((streamsize)buffer_size, num_remaining)); + _in->read(buffer, std::min((streamsize)buffer_size, num_remaining)); count = _in->gcount(); } @@ -279,7 +282,7 @@ save_datagram(SubfileInfo &info) { */ bool DatagramInputFile:: is_eof() { - return _in != (istream *)NULL ? _in->eof() : true; + return _in != nullptr ? _in->eof() : true; } /** @@ -287,7 +290,7 @@ is_eof() { */ bool DatagramInputFile:: is_error() { - if (_in == (istream *)NULL) { + if (_in == nullptr) { return true; } @@ -343,7 +346,7 @@ get_vfile() { */ streampos DatagramInputFile:: get_file_pos() { - if (_in == (istream *)NULL) { + if (_in == nullptr) { return 0; } return _in->tellg(); diff --git a/panda/src/putil/datagramInputFile.h b/panda/src/putil/datagramInputFile.h index a8f8f67341..37fdf8bbe2 100644 --- a/panda/src/putil/datagramInputFile.h +++ b/panda/src/putil/datagramInputFile.h @@ -32,12 +32,12 @@ PUBLISHED: bool open(const FileReference *file); INLINE bool open(const Filename &filename); - bool open(istream &in, const Filename &filename = Filename()); - INLINE istream &get_stream(); + bool open(std::istream &in, const Filename &filename = Filename()); + INLINE std::istream &get_stream(); void close(); - bool read_header(string &header, size_t num_bytes); + bool read_header(std::string &header, size_t num_bytes); virtual bool get_datagram(Datagram &data); virtual bool save_datagram(SubfileInfo &info); virtual bool is_eof(); @@ -47,14 +47,14 @@ PUBLISHED: virtual time_t get_timestamp() const; virtual const FileReference *get_file(); virtual VirtualFile *get_vfile(); - virtual streampos get_file_pos(); + virtual std::streampos get_file_pos(); private: bool _read_first_datagram; bool _error; CPT(FileReference) _file; PT(VirtualFile) _vfile; - istream *_in; + std::istream *_in; bool _owns_in; Filename _filename; time_t _timestamp; diff --git a/panda/src/putil/datagramOutputFile.I b/panda/src/putil/datagramOutputFile.I index b3dbe95c9c..56060c51cf 100644 --- a/panda/src/putil/datagramOutputFile.I +++ b/panda/src/putil/datagramOutputFile.I @@ -18,7 +18,7 @@ INLINE DatagramOutputFile:: DatagramOutputFile() { _error = false; _wrote_first_datagram = false; - _out = (ostream *)NULL; + _out = nullptr; _owns_out = false; } @@ -42,9 +42,9 @@ open(const Filename &filename) { /** * Returns the ostream represented by the output file. */ -INLINE ostream &DatagramOutputFile:: +INLINE std::ostream &DatagramOutputFile:: get_stream() { - static ofstream null_stream; - nassertr(_out != NULL, null_stream); + static std::ofstream null_stream; + nassertr(_out != nullptr, null_stream); return *_out; } diff --git a/panda/src/putil/datagramOutputFile.cxx b/panda/src/putil/datagramOutputFile.cxx index cd9a1af2fc..407e1adfec 100644 --- a/panda/src/putil/datagramOutputFile.cxx +++ b/panda/src/putil/datagramOutputFile.cxx @@ -16,6 +16,10 @@ #include "zStream.h" #include +using std::min; +using std::streampos; +using std::streamsize; + /** * Opens the indicated filename for writing. Returns true if successful, * false on failure. @@ -32,12 +36,12 @@ open(const FileReference *file) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); _vfile = vfs->create_file(_filename); - if (_vfile == (VirtualFile *)NULL) { + if (_vfile == nullptr) { // No such file. return false; } _out = _vfile->open_write_file(true, true); - _owns_out = (_out != (ostream *)NULL); + _owns_out = (_out != nullptr); return _owns_out && !_out->fail(); } @@ -47,7 +51,7 @@ open(const FileReference *file) { * are responsible for closing or deleting it when you are done. */ bool DatagramOutputFile:: -open(ostream &out, const Filename &filename) { +open(std::ostream &out, const Filename &filename) { close(); _out = &out; @@ -72,7 +76,7 @@ close() { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->close_write_file(_out); } - _out = (ostream *)NULL; + _out = nullptr; _owns_out = false; _file.clear(); @@ -89,8 +93,8 @@ close() { * written. */ bool DatagramOutputFile:: -write_header(const string &header) { - nassertr(_out != (ostream *)NULL, false); +write_header(const std::string &header) { + nassertr(_out != nullptr, false); nassertr(!_wrote_first_datagram, false); _out->write(header.data(), header.size()); @@ -104,7 +108,7 @@ write_header(const string &header) { */ bool DatagramOutputFile:: put_datagram(const Datagram &data) { - nassertr(_out != (ostream *)NULL, false); + nassertr(_out != nullptr, false); _wrote_first_datagram = true; // First, write the size of the upcoming datagram. @@ -137,16 +141,16 @@ put_datagram(const Datagram &data) { */ bool DatagramOutputFile:: copy_datagram(SubfileInfo &result, const Filename &filename) { - nassertr(_out != (ostream *)NULL, false); + nassertr(_out != nullptr, false); _wrote_first_datagram = true; VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); PT(VirtualFile) vfile = vfs->get_file(filename); - if (vfile == NULL) { + if (vfile == nullptr) { return false; } - istream *in = vfile->open_read_file(true); - if (in == NULL) { + std::istream *in = vfile->open_read_file(true); + if (in == nullptr) { return false; } @@ -206,7 +210,7 @@ copy_datagram(SubfileInfo &result, const Filename &filename) { */ bool DatagramOutputFile:: copy_datagram(SubfileInfo &result, const SubfileInfo &source) { - nassertr(_out != (ostream *)NULL, false); + nassertr(_out != nullptr, false); _wrote_first_datagram = true; pifstream in; @@ -261,7 +265,7 @@ copy_datagram(SubfileInfo &result, const SubfileInfo &source) { */ bool DatagramOutputFile:: is_error() { - if (_out == (ostream *)NULL) { + if (_out == nullptr) { return true; } @@ -277,7 +281,7 @@ is_error() { */ void DatagramOutputFile:: flush() { - if (_out != (ostream *)NULL) { + if (_out != nullptr) { _out->flush(); } } @@ -311,7 +315,7 @@ get_file() { */ streampos DatagramOutputFile:: get_file_pos() { - if (_out == (ostream *)NULL) { + if (_out == nullptr) { return 0; } return _out->tellp(); diff --git a/panda/src/putil/datagramOutputFile.h b/panda/src/putil/datagramOutputFile.h index c81dcdf986..17402850b0 100644 --- a/panda/src/putil/datagramOutputFile.h +++ b/panda/src/putil/datagramOutputFile.h @@ -34,11 +34,11 @@ PUBLISHED: bool open(const FileReference *file); INLINE bool open(const Filename &filename); - bool open(ostream &out, const Filename &filename = Filename()); + bool open(std::ostream &out, const Filename &filename = Filename()); void close(); - bool write_header(const string &header); + bool write_header(const std::string &header); virtual bool put_datagram(const Datagram &data); virtual bool copy_datagram(SubfileInfo &result, const Filename &filename); virtual bool copy_datagram(SubfileInfo &result, const SubfileInfo &source); @@ -48,9 +48,9 @@ PUBLISHED: public: virtual const Filename &get_filename(); virtual const FileReference *get_file(); - virtual streampos get_file_pos(); + virtual std::streampos get_file_pos(); - INLINE ostream &get_stream(); + INLINE std::ostream &get_stream(); PUBLISHED: MAKE_PROPERTY(stream, get_stream); @@ -60,7 +60,7 @@ private: bool _error; CPT(FileReference) _file; PT(VirtualFile) _vfile; - ostream *_out; + std::ostream *_out; bool _owns_out; Filename _filename; }; diff --git a/panda/src/putil/doubleBitMask.I b/panda/src/putil/doubleBitMask.I index a6997af549..cc400a14fb 100644 --- a/panda/src/putil/doubleBitMask.I +++ b/panda/src/putil/doubleBitMask.I @@ -14,36 +14,6 @@ template TypeHandle DoubleBitMask::_type_handle; -/** - * - */ -template -INLINE DoubleBitMask:: -DoubleBitMask() { -} - -/** - * - */ -template -INLINE DoubleBitMask:: -DoubleBitMask(const DoubleBitMask ©) : - _lo(copy._lo), - _hi(copy._hi) -{ -} - -/** - * - */ -template -INLINE DoubleBitMask &DoubleBitMask:: -operator = (const DoubleBitMask ©) { - _lo = copy._lo; - _hi = copy._hi; - return *this; -} - /** * Returns a DoubleBitMask whose bits are all on. */ @@ -111,49 +81,12 @@ range(int low_bit, int size) { return result; } -/** - * - */ -template -INLINE DoubleBitMask:: -~DoubleBitMask() { -} - -/** - * Returns true if there is a maximum number of bits that may be stored in - * this structure, false otherwise. If this returns true, the number may be - * queried in get_max_num_bits(). - * - * This method always returns true. This method is defined so generic - * programming algorithms can use DoubleBitMask or BitArray interchangeably. - */ -template -CONSTEXPR bool DoubleBitMask:: -has_max_num_bits() { - return true; -} - -/** - * If get_max_num_bits() returned true, this method may be called to return - * the maximum number of bits that may be stored in this structure. It is an - * error to call this if get_max_num_bits() return false. - * - * It is never an error to call this method. This returns the same thing as - * get_num_bits(). This method is defined so generic programming algorithms - * can use DoubleBitMask or BitArray interchangeably. - */ -template -CONSTEXPR int DoubleBitMask:: -get_max_num_bits() { - return num_bits; -} - /** * Returns the number of bits available to set in the doubleBitMask. */ template -CONSTEXPR int DoubleBitMask:: -get_num_bits() { +constexpr int DoubleBitMask:: +get_num_bits() const { return num_bits; } @@ -234,7 +167,7 @@ is_all_on() const { * DoubleBitMask, shifted to the least-significant position. */ template -INLINE TYPENAME DoubleBitMask::WordType DoubleBitMask:: +INLINE typename DoubleBitMask::WordType DoubleBitMask:: extract(int low_bit, int size) const { if (low_bit >= half_bits) { return _hi.extract(low_bit - half_bits, size); @@ -281,8 +214,8 @@ has_any_of(int low_bit, int size) const { } else { int hi_portion = low_bit + size - half_bits; int lo_portion = size - hi_portion; - return (_hi.has_any_of(0, hi_portion) << lo_portion) || - _lo.has_any_of(low_bit, lo_portion); + return _hi.has_any_of(0, hi_portion) + || _lo.has_any_of(low_bit, lo_portion); } } @@ -299,8 +232,8 @@ has_all_of(int low_bit, int size) const { } else { int hi_portion = low_bit + size - half_bits; int lo_portion = size - hi_portion; - return (_hi.has_all_of(0, hi_portion) << lo_portion) && - _lo.has_all_of(low_bit, lo_portion); + return _hi.has_all_of(0, hi_portion) + && _lo.has_all_of(low_bit, lo_portion); } } @@ -509,7 +442,7 @@ clear() { */ template void DoubleBitMask:: -output(ostream &out) const { +output(std::ostream &out) const { output_hex(out); } @@ -519,7 +452,7 @@ output(ostream &out) const { */ template void DoubleBitMask:: -output_binary(ostream &out, int spaces_every) const { +output_binary(std::ostream &out, int spaces_every) const { _hi.output_binary(out); out << ' '; _lo.output_binary(out); @@ -531,7 +464,7 @@ output_binary(ostream &out, int spaces_every) const { */ template void DoubleBitMask:: -output_hex(ostream &out, int spaces_every) const { +output_hex(std::ostream &out, int spaces_every) const { _hi.output_hex(out); out << ' '; _lo.output_hex(out); @@ -543,7 +476,7 @@ output_hex(ostream &out, int spaces_every) const { */ template void DoubleBitMask:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << *this << "\n"; } @@ -730,7 +663,7 @@ generate_hash(ChecksumHashGenerator &hashgen) const { template void DoubleBitMask:: init_type() { - ostringstream str; + std::ostringstream str; str << "DoubleBitMask" << num_bits; register_type(_type_handle, str.str()); } diff --git a/panda/src/putil/doubleBitMask.cxx b/panda/src/putil/doubleBitMask.cxx index c35d11613a..ff651eea61 100644 --- a/panda/src/putil/doubleBitMask.cxx +++ b/panda/src/putil/doubleBitMask.cxx @@ -15,3 +15,10 @@ template class DoubleBitMask; template class DoubleBitMask; + +#if !defined(CPPPARSER) && !defined(__APPLE__) +#include + +static_assert(std::is_literal_type::value, "DoubleBitMaskNative is not a literal type"); +static_assert(std::is_literal_type::value, "QuadBitMaskNative is not a literal type"); +#endif diff --git a/panda/src/putil/doubleBitMask.h b/panda/src/putil/doubleBitMask.h index d229eb03a6..7ebc114f5f 100644 --- a/panda/src/putil/doubleBitMask.h +++ b/panda/src/putil/doubleBitMask.h @@ -27,7 +27,7 @@ template class DoubleBitMask { public: - typedef TYPENAME BMType::WordType WordType; + typedef typename BMType::WordType WordType; PUBLISHED: typedef BMType BitMaskType; @@ -37,9 +37,7 @@ PUBLISHED: num_bits = BMType::num_bits * 2, }; - INLINE DoubleBitMask(); - INLINE DoubleBitMask(const DoubleBitMask ©); - INLINE DoubleBitMask &operator = (const DoubleBitMask ©); + constexpr DoubleBitMask() = default; INLINE static DoubleBitMask all_on(); INLINE static DoubleBitMask all_off(); @@ -47,12 +45,10 @@ PUBLISHED: INLINE static DoubleBitMask bit(int index); INLINE static DoubleBitMask range(int low_bit, int size); - INLINE ~DoubleBitMask(); + constexpr static bool has_max_num_bits() {return true;} + constexpr static int get_max_num_bits() {return num_bits;} - CONSTEXPR static bool has_max_num_bits(); - CONSTEXPR static int get_max_num_bits(); - - CONSTEXPR static int get_num_bits(); + constexpr int get_num_bits() const; INLINE bool get_bit(int index) const; INLINE void set_bit(int index); INLINE void clear_bit(int index); @@ -80,10 +76,10 @@ PUBLISHED: INLINE bool has_bits_in_common(const DoubleBitMask &other) const; INLINE void clear(); - void output(ostream &out) const; - void output_binary(ostream &out, int spaces_every = 4) const; - void output_hex(ostream &out, int spaces_every = 4) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void output_binary(std::ostream &out, int spaces_every = 4) const; + void output_hex(std::ostream &out, int spaces_every = 4) const; + void write(std::ostream &out, int indent_level = 0) const; INLINE bool operator == (const DoubleBitMask &other) const; INLINE bool operator != (const DoubleBitMask &other) const; @@ -133,7 +129,7 @@ private: #include "doubleBitMask.I" template -INLINE ostream &operator << (ostream &out, const DoubleBitMask &doubleBitMask) { +INLINE std::ostream &operator << (std::ostream &out, const DoubleBitMask &doubleBitMask) { doubleBitMask.output(out); return out; } diff --git a/panda/src/putil/factory.I b/panda/src/putil/factory.I index 57d3fadff5..bfd170af40 100644 --- a/panda/src/putil/factory.I +++ b/panda/src/putil/factory.I @@ -34,7 +34,7 @@ make_instance(TypeHandle handle, const FactoryParams ¶ms) { */ template INLINE Type *Factory:: -make_instance(const string &type_name, const FactoryParams ¶ms) { +make_instance(const std::string &type_name, const FactoryParams ¶ms) { return (Type *)FactoryBase::make_instance(type_name, params); } @@ -60,7 +60,7 @@ make_instance_more_general(TypeHandle handle, const FactoryParams ¶ms) { */ template INLINE Type *Factory:: -make_instance_more_general(const string &type_name, +make_instance_more_general(const std::string &type_name, const FactoryParams ¶ms) { return (Type *)FactoryBase::make_instance_more_general(type_name, params); } diff --git a/panda/src/putil/factory.h b/panda/src/putil/factory.h index 4520153911..03c1fb6f37 100644 --- a/panda/src/putil/factory.h +++ b/panda/src/putil/factory.h @@ -38,7 +38,7 @@ public: INLINE Type *make_instance(TypeHandle handle, const FactoryParams ¶ms = FactoryParams()); - INLINE Type *make_instance(const string &type_name, + INLINE Type *make_instance(const std::string &type_name, const FactoryParams ¶ms = FactoryParams()); INLINE Type * @@ -46,11 +46,11 @@ public: const FactoryParams ¶ms = FactoryParams()); INLINE Type * - make_instance_more_general(const string &type_name, + make_instance_more_general(const std::string &type_name, const FactoryParams ¶ms = FactoryParams()); INLINE void register_factory(TypeHandle handle, CreateFunc *func, - void *user_data = NULL); + void *user_data = nullptr); }; #include "factory.I" diff --git a/panda/src/putil/factoryBase.I b/panda/src/putil/factoryBase.I index 3452a9758c..3d93306a4e 100644 --- a/panda/src/putil/factoryBase.I +++ b/panda/src/putil/factoryBase.I @@ -21,9 +21,9 @@ * desired type. It must be the name of some already-registered type. */ INLINE TypedObject *FactoryBase:: -make_instance(const string &type_name, const FactoryParams ¶ms) { +make_instance(const std::string &type_name, const FactoryParams ¶ms) { TypeHandle handle = TypeRegistry::ptr()->find_type(type_name); - nassertr(handle != TypeHandle::none(), NULL); + nassertr(handle != TypeHandle::none(), nullptr); return make_instance(handle, params); } @@ -39,10 +39,10 @@ make_instance(const string &type_name, const FactoryParams ¶ms) { * type. */ INLINE TypedObject *FactoryBase:: -make_instance_more_general(const string &type_name, +make_instance_more_general(const std::string &type_name, const FactoryParams ¶ms) { TypeHandle handle = TypeRegistry::ptr()->find_type(type_name); - nassertr(handle != TypeHandle::none(), NULL); + nassertr(handle != TypeHandle::none(), nullptr); return make_instance_more_general(handle, params); } diff --git a/panda/src/putil/factoryBase.cxx b/panda/src/putil/factoryBase.cxx index d34035177c..341028d068 100644 --- a/panda/src/putil/factoryBase.cxx +++ b/panda/src/putil/factoryBase.cxx @@ -15,20 +15,6 @@ #include "indent.h" #include "config_putil.h" -/** - * - */ -FactoryBase:: -FactoryBase() { -} - -/** - * - */ -FactoryBase:: -~FactoryBase() { -} - /** * Attempts to create a new instance of some class of the indicated type, or * some derivative if necessary. If an instance of the exact type cannot be @@ -37,10 +23,10 @@ FactoryBase:: */ TypedObject *FactoryBase:: make_instance(TypeHandle handle, const FactoryParams ¶ms) { - TypedObject *instance = (TypedObject *)NULL; + TypedObject *instance = nullptr; instance = make_instance_exact(handle, params); - if (instance == (TypedObject *)NULL) { + if (instance == nullptr) { // Can't create an exact instance; try for a derived type. instance = make_instance_more_specific(handle, params); } @@ -49,7 +35,7 @@ make_instance(TypeHandle handle, const FactoryParams ¶ms) { util_cat.debug() << "make_instance(" << handle << ", params) returns " << (void *)instance; - if (instance != (TypedObject *)NULL) { + if (instance != nullptr) { util_cat.debug(false) << ", of type " << instance->get_type(); } @@ -67,15 +53,15 @@ TypedObject *FactoryBase:: make_instance_more_general(TypeHandle handle, const FactoryParams ¶ms) { TypedObject *object = make_instance_exact(handle, params); - if (object == (TypedObject *)NULL) { + if (object == nullptr) { // Recursively search through the entire inheritance tree until we find // something we know about. if (handle.get_num_parent_classes() == 0) { - return NULL; + return nullptr; } int num_parents = handle.get_num_parent_classes(); - for (int i = 0; i < num_parents && object == (TypedObject *)NULL; i++) { + for (int i = 0; i < num_parents && object == nullptr; i++) { object = make_instance_more_general(handle.get_parent_class(i), params); } } @@ -84,7 +70,7 @@ make_instance_more_general(TypeHandle handle, const FactoryParams ¶ms) { util_cat.debug() << "make_instance(" << handle << ", params) returns " << (void *)object; - if (object != (TypedObject *)NULL) { + if (object != nullptr) { util_cat.debug(false) << ", of type " << object->get_type(); } @@ -134,7 +120,7 @@ find_registered_type(TypeHandle handle) { void FactoryBase:: register_factory(TypeHandle handle, BaseCreateFunc *func, void *user_data) { nassertv(handle != TypeHandle::none()); - nassertv(func != (BaseCreateFunc *)NULL); + nassertv(func != nullptr); Creator creator; creator._func = func; @@ -145,7 +131,7 @@ register_factory(TypeHandle handle, BaseCreateFunc *func, void *user_data) { /** * Returns the number of different types the Factory knows how to create. */ -int FactoryBase:: +size_t FactoryBase:: get_num_types() const { return _creators.size(); } @@ -156,8 +142,8 @@ get_num_types() const { * Normally you wouldn't need to traverse the list of the Factory's types. */ TypeHandle FactoryBase:: -get_type(int n) const { - nassertr(n >= 0 && n < get_num_types(), TypeHandle::none()); +get_type(size_t n) const { + nassertr(n < get_num_types(), TypeHandle::none()); Creators::const_iterator ci; for (ci = _creators.begin(); ci != _creators.end(); ++ci) { if (n == 0) { @@ -193,7 +179,7 @@ add_preferred(TypeHandle handle) { /** * Returns the number of types added to the preferred-type list. */ -int FactoryBase:: +size_t FactoryBase:: get_num_preferred() const { return _preferred.size(); } @@ -202,8 +188,8 @@ get_num_preferred() const { * Returns the nth type added to the preferred-type list. */ TypeHandle FactoryBase:: -get_preferred(int n) const { - nassertr(n >= 0 && n < get_num_preferred(), TypeHandle::none()); +get_preferred(size_t n) const { + nassertr(n < get_num_preferred(), TypeHandle::none()); return _preferred[n]; } @@ -212,28 +198,13 @@ get_preferred(int n) const { * output stream, one per line. */ void FactoryBase:: -write_types(ostream &out, int indent_level) const { +write_types(std::ostream &out, int indent_level) const { Creators::const_iterator ci; for (ci = _creators.begin(); ci != _creators.end(); ++ci) { indent(out, indent_level) << (*ci).first << "\n"; } } - -/** - * Don't copy Factories. - */ -FactoryBase:: -FactoryBase(const FactoryBase &) { -} - -/** - * Don't copy Factories. - */ -void FactoryBase:: -operator = (const FactoryBase &) { -} - /** * Attempts to create an instance of the exact type requested by the given * handle. Returns the new instance created, or NULL if the instance could @@ -243,11 +214,11 @@ TypedObject *FactoryBase:: make_instance_exact(TypeHandle handle, FactoryParams params) { Creators::const_iterator ci = _creators.find(handle); if (ci == _creators.end()) { - return NULL; + return nullptr; } Creator creator = (*ci).second; - nassertr(creator._func != (BaseCreateFunc *)NULL, NULL); + nassertr(creator._func != nullptr, nullptr); params._user_data = creator._user_data; return (*creator._func)(params); } @@ -262,12 +233,10 @@ make_instance_more_specific(TypeHandle handle, FactoryParams params) { // First, walk through the established preferred list. Maybe one of these // qualifies. - Preferred::const_iterator pi; - for (pi = _preferred.begin(); pi != _preferred.end(); ++pi) { - TypeHandle ptype = (*pi); + for (TypeHandle ptype : _preferred) { if (ptype.is_derived_from(handle)) { TypedObject *object = make_instance_exact(ptype, params); - if (object != (TypedObject *)NULL) { + if (object != nullptr) { return object; } } @@ -280,14 +249,14 @@ make_instance_more_specific(TypeHandle handle, FactoryParams params) { TypeHandle ctype = (*ci).first; if (ctype.is_derived_from(handle)) { Creator creator = (*ci).second; - nassertr(creator._func != (BaseCreateFunc *)NULL, NULL); + nassertr(creator._func != nullptr, nullptr); params._user_data = creator._user_data; TypedObject *object = (*creator._func)(params); - if (object != (TypedObject *)NULL) { + if (object != nullptr) { return object; } } } - return NULL; + return nullptr; } diff --git a/panda/src/putil/factoryBase.h b/panda/src/putil/factoryBase.h index 6fcfc2f54f..65617f254b 100644 --- a/panda/src/putil/factoryBase.h +++ b/panda/src/putil/factoryBase.h @@ -39,40 +39,39 @@ public: // public interface public: - FactoryBase(); - ~FactoryBase(); + FactoryBase() = default; + FactoryBase(const FactoryBase ©) = delete; + ~FactoryBase() = default; + + FactoryBase &operator = (const FactoryBase ©) = delete; TypedObject *make_instance(TypeHandle handle, const FactoryParams ¶ms); - INLINE TypedObject *make_instance(const string &type_name, + INLINE TypedObject *make_instance(const std::string &type_name, const FactoryParams ¶ms); TypedObject *make_instance_more_general(TypeHandle handle, const FactoryParams ¶ms); - INLINE TypedObject *make_instance_more_general(const string &type_name, + INLINE TypedObject *make_instance_more_general(const std::string &type_name, const FactoryParams ¶ms); TypeHandle find_registered_type(TypeHandle handle); - void register_factory(TypeHandle handle, BaseCreateFunc *func, void *user_data = NULL); + void register_factory(TypeHandle handle, BaseCreateFunc *func, void *user_data = nullptr); - int get_num_types() const; - TypeHandle get_type(int n) const; + size_t get_num_types() const; + TypeHandle get_type(size_t n) const; void clear_preferred(); void add_preferred(TypeHandle handle); - int get_num_preferred() const; - TypeHandle get_preferred(int n) const; + size_t get_num_preferred() const; + TypeHandle get_preferred(size_t n) const; - void write_types(ostream &out, int indent_level = 0) const; + void write_types(std::ostream &out, int indent_level = 0) const; private: - // These are private; we shouldn't be copy-constructing Factories. - FactoryBase(const FactoryBase ©); - void operator = (const FactoryBase ©); - // internal utility functions TypedObject *make_instance_exact(TypeHandle handle, FactoryParams params); TypedObject *make_instance_more_specific(TypeHandle handle, diff --git a/panda/src/putil/factoryParams.I b/panda/src/putil/factoryParams.I index 0c6fdd09e7..0f71e62969 100644 --- a/panda/src/putil/factoryParams.I +++ b/panda/src/putil/factoryParams.I @@ -13,47 +13,6 @@ #include "pnotify.h" -/** - * - */ -INLINE FactoryParams:: -FactoryParams() : _user_data(NULL) { -} - -/** - * - */ -INLINE FactoryParams:: -FactoryParams(const FactoryParams ©) : - _params(copy._params), - _user_data(copy._user_data) {} - -/** - * - */ -INLINE FactoryParams:: -~FactoryParams() { -} - -#ifdef USE_MOVE_SEMANTICS -/** - * - */ -INLINE FactoryParams:: -FactoryParams(FactoryParams &&from) NOEXCEPT : - _params(move(from._params)), - _user_data(from._user_data) {} - -/** - * - */ -INLINE void FactoryParams:: -operator = (FactoryParams &&from) NOEXCEPT { - _params = move(from._params); - _user_data = from._user_data; -} -#endif - /** * Returns the custom pointer that was associated with the factory function. */ @@ -72,8 +31,8 @@ template bool get_param_into(ParamType *&pointer, const FactoryParams ¶ms) { FactoryParam *param = params.get_param_of_type(ParamType::get_class_type()); - if (param == (FactoryParam *)NULL) { - pointer = NULL; + if (param == nullptr) { + pointer = nullptr; return false; } DCAST_INTO_R(pointer, param, false); diff --git a/panda/src/putil/factoryParams.cxx b/panda/src/putil/factoryParams.cxx index 6224f8b94e..362ec097c1 100644 --- a/panda/src/putil/factoryParams.cxx +++ b/panda/src/putil/factoryParams.cxx @@ -18,7 +18,7 @@ */ void FactoryParams:: add_param(FactoryParam *param) { - nassertv(param != (FactoryParam *)NULL); + nassertv(param != nullptr); _params.push_back(param); } @@ -43,7 +43,7 @@ get_num_params() const { */ FactoryParam *FactoryParams:: get_param(int n) const { - nassertr(n >= 0 && n < (int)_params.size(), NULL); + nassertr(n >= 0 && n < (int)_params.size(), nullptr); return DCAST(FactoryParam, _params[n]); } @@ -59,8 +59,8 @@ get_param_of_type(TypeHandle type) const { // First, search for the exact match. for (pi = _params.begin(); pi != _params.end(); ++pi) { FactoryParam *param; - DCAST_INTO_R(param, *pi, NULL); - nassertr(param != (FactoryParam *)NULL, NULL); + DCAST_INTO_R(param, *pi, nullptr); + nassertr(param != nullptr, nullptr); if (param->is_exact_type(type)) { return param; @@ -70,13 +70,13 @@ get_param_of_type(TypeHandle type) const { // Now, search for a derived match. for (pi = _params.begin(); pi != _params.end(); ++pi) { FactoryParam *param; - DCAST_INTO_R(param, *pi, NULL); - nassertr(param != (FactoryParam *)NULL, NULL); + DCAST_INTO_R(param, *pi, nullptr); + nassertr(param != nullptr, nullptr); if (param->is_of_type(type)) { return param; } } - return NULL; + return nullptr; } diff --git a/panda/src/putil/factoryParams.h b/panda/src/putil/factoryParams.h index 5c45a6e2ee..b76dc81e84 100644 --- a/panda/src/putil/factoryParams.h +++ b/panda/src/putil/factoryParams.h @@ -35,14 +35,12 @@ */ class EXPCL_PANDA_PUTIL FactoryParams { public: - INLINE FactoryParams(); - INLINE FactoryParams(const FactoryParams ©); - INLINE ~FactoryParams(); + FactoryParams() = default; + FactoryParams(const FactoryParams ©) = default; + FactoryParams(FactoryParams &&from) noexcept = default; + ~FactoryParams() = default; -#ifdef USE_MOVE_SEMANTICS - INLINE FactoryParams(FactoryParams &&from) NOEXCEPT; - INLINE void operator = (FactoryParams &&from) NOEXCEPT; -#endif + FactoryParams &operator = (FactoryParams &&from) noexcept = default; void add_param(FactoryParam *param); void clear(); @@ -58,7 +56,7 @@ private: typedef pvector< PT(TypedReferenceCount) > Params; Params _params; - void *_user_data; + void *_user_data = nullptr; friend class FactoryBase; }; diff --git a/panda/src/putil/globalPointerRegistry.I b/panda/src/putil/globalPointerRegistry.I index 10dc289e9b..a43f3fd98d 100644 --- a/panda/src/putil/globalPointerRegistry.I +++ b/panda/src/putil/globalPointerRegistry.I @@ -49,7 +49,7 @@ clear_pointer(TypeHandle type) { */ INLINE GlobalPointerRegistry *GlobalPointerRegistry:: get_global_ptr() { - if (_global_ptr == (GlobalPointerRegistry *)NULL) { + if (_global_ptr == nullptr) { _global_ptr = new GlobalPointerRegistry; } return _global_ptr; diff --git a/panda/src/putil/globalPointerRegistry.cxx b/panda/src/putil/globalPointerRegistry.cxx index 40e062d9c0..2f6f308baf 100644 --- a/panda/src/putil/globalPointerRegistry.cxx +++ b/panda/src/putil/globalPointerRegistry.cxx @@ -34,7 +34,7 @@ ns_get_pointer(TypeHandle type) const { Pointers::const_iterator pi; pi = _pointers.find(type); if (pi == _pointers.end()) { - return (void *)NULL; + return nullptr; } return (*pi).second; @@ -51,13 +51,13 @@ ns_store_pointer(TypeHandle type, void *ptr) { util_cat->error() << "GlobalPointerRegistry::store_pointer() called on empty TypeHandle\n"; } - if (ptr == (void *)NULL) { + if (ptr == nullptr) { util_cat->error() << "Invalid attempt to store a NULL pointer for " << type << "\n"; clear_pointer(type); return; } - pair result = + std::pair result = _pointers.insert(Pointers::value_type(type, ptr)); if (!result.second) { diff --git a/panda/src/putil/iterator_types.h b/panda/src/putil/iterator_types.h index 2f2966cde7..ec90638237 100644 --- a/panda/src/putil/iterator_types.h +++ b/panda/src/putil/iterator_types.h @@ -24,9 +24,9 @@ template class first_of_pair_iterator : public pair_iterator { public: - typedef TYPENAME pair_iterator::value_type::first_type value_type; + typedef typename pair_iterator::value_type::first_type value_type; - first_of_pair_iterator() DEFAULT_CTOR; + first_of_pair_iterator() = default; first_of_pair_iterator(const pair_iterator &init) : pair_iterator(init) { } value_type operator *() { @@ -42,9 +42,9 @@ public: template class second_of_pair_iterator : public pair_iterator { public: - typedef TYPENAME pair_iterator::value_type::second_type value_type; + typedef typename pair_iterator::value_type::second_type value_type; - second_of_pair_iterator() DEFAULT_CTOR; + second_of_pair_iterator() = default; second_of_pair_iterator(const pair_iterator &init) : pair_iterator(init) { } value_type operator *() { @@ -61,7 +61,7 @@ class typecast_iterator : public base_iterator { public: typedef new_type value_type; - typecast_iterator() DEFAULT_CTOR; + typecast_iterator() = default; typecast_iterator(const base_iterator &init) : base_iterator(init) { } value_type operator *() { diff --git a/panda/src/putil/keyboardButton.cxx b/panda/src/putil/keyboardButton.cxx index e6d7162d50..3ab8e38265 100644 --- a/panda/src/putil/keyboardButton.cxx +++ b/panda/src/putil/keyboardButton.cxx @@ -155,7 +155,7 @@ init_keyboard_buttons() { for (int i = 32; i < 127; i++) { if (isgraph(i)) { ButtonHandle key; - ButtonRegistry::ptr()->register_button(key, string(1, (char)i), + ButtonRegistry::ptr()->register_button(key, std::string(1, (char)i), ButtonHandle::none(), i); } } diff --git a/panda/src/putil/linkedListNode.I b/panda/src/putil/linkedListNode.I index e722108702..a61aaa854c 100644 --- a/panda/src/putil/linkedListNode.I +++ b/panda/src/putil/linkedListNode.I @@ -17,8 +17,8 @@ INLINE LinkedListNode:: LinkedListNode() { #ifndef NDEBUG - _next = NULL; - _prev = NULL; + _next = nullptr; + _prev = nullptr; #endif } @@ -33,12 +33,48 @@ LinkedListNode(bool) { _prev = this; } +/** + * This move constructor replaces the other link with this one. + */ +INLINE LinkedListNode:: +LinkedListNode(LinkedListNode &&from) noexcept { + if (from._prev != nullptr) { + nassertv(from._prev->_next == &from); + from._prev->_next = this; + } + _prev = from._prev; + if (from._next != nullptr) { + nassertv(from._next->_prev == &from); + from._next->_prev = this; + } + _next = from._next; + from._next = nullptr; + from._prev = nullptr; +} + /** * */ INLINE LinkedListNode:: ~LinkedListNode() { - nassertv((_next == NULL && _prev == NULL) || (_next == this && _prev == this)); + nassertv((_next == nullptr && _prev == nullptr) || (_next == this && _prev == this)); +} + +/** + * Replaces the given other node with this node. + */ +INLINE LinkedListNode &LinkedListNode:: +operator = (LinkedListNode &&from) { + nassertr((_next == nullptr && _prev == nullptr) || (_next == this && _prev == this), *this); + nassertr(from._prev != nullptr && from._next != nullptr, *this); + nassertr(from._prev->_next == &from && from._next->_prev == &from, *this); + from._prev->_next = this; + from._next->_prev = this; + _prev = from._prev; + _next = from._next; + from._next = nullptr; + from._prev = nullptr; + return *this; } /** @@ -48,7 +84,7 @@ INLINE LinkedListNode:: */ INLINE bool LinkedListNode:: is_on_list() const { - return (_next != NULL); + return (_next != nullptr); } /** @@ -56,13 +92,13 @@ is_on_list() const { */ INLINE void LinkedListNode:: remove_from_list() { - nassertv(_prev != NULL && _next != NULL); + nassertv(_prev != nullptr && _next != nullptr); nassertv(_prev->_next == this && _next->_prev == this); _prev->_next = _next; _next->_prev = _prev; #ifndef NDEBUG - _next = NULL; - _prev = NULL; + _next = nullptr; + _prev = nullptr; #endif } @@ -72,9 +108,9 @@ remove_from_list() { */ INLINE void LinkedListNode:: insert_before(LinkedListNode *node) { - nassertv(node->_prev != NULL && node->_prev->_next == node && node->_next->_prev == node); - nassertv(_prev == (LinkedListNode *)NULL && - _next == (LinkedListNode *)NULL); + nassertv(node->_prev != nullptr && node->_prev->_next == node && node->_next->_prev == node); + nassertv(_prev == nullptr && + _next == nullptr); _prev = node->_prev; _next = node; _prev->_next = this; @@ -87,9 +123,9 @@ insert_before(LinkedListNode *node) { */ INLINE void LinkedListNode:: insert_after(LinkedListNode *node) { - nassertv(node->_prev != NULL && node->_prev->_next == node && node->_next->_prev == node); - nassertv(_prev == (LinkedListNode *)NULL && - _next == (LinkedListNode *)NULL); + nassertv(node->_prev != nullptr && node->_prev->_next == node && node->_next->_prev == node); + nassertv(_prev == nullptr && + _next == nullptr); _next = node->_next; _prev = node; _next->_prev = this; diff --git a/panda/src/putil/linkedListNode.h b/panda/src/putil/linkedListNode.h index 9dedbe9e4d..5f8e6f1909 100644 --- a/panda/src/putil/linkedListNode.h +++ b/panda/src/putil/linkedListNode.h @@ -32,8 +32,11 @@ class EXPCL_PANDA_PUTIL LinkedListNode { protected: INLINE LinkedListNode(); INLINE LinkedListNode(bool); + INLINE LinkedListNode(LinkedListNode &&from) noexcept; INLINE ~LinkedListNode(); + INLINE LinkedListNode &operator = (LinkedListNode &&from); + INLINE bool is_on_list() const; INLINE void remove_from_list(); INLINE void insert_before(LinkedListNode *node); diff --git a/panda/src/putil/load_prc_file.cxx b/panda/src/putil/load_prc_file.cxx index 5663c49038..f40296b403 100644 --- a/panda/src/putil/load_prc_file.cxx +++ b/panda/src/putil/load_prc_file.cxx @@ -43,11 +43,11 @@ load_prc_file(const Filename &filename) { vfs->resolve_filename(path, cp_mgr->get_search_path()) || vfs->resolve_filename(path, get_model_path()); - istream *file = vfs->open_read_file(path, true); - if (file == (istream *)NULL) { + std::istream *file = vfs->open_read_file(path, true); + if (file == nullptr) { util_cat.error() << "Unable to open " << path << "\n"; - return NULL; + return nullptr; } util_cat.info() @@ -64,7 +64,7 @@ load_prc_file(const Filename &filename) { util_cat.info() << "Unable to read " << path << "\n"; cp_mgr->delete_explicit_page(page); - return NULL; + return nullptr; } } @@ -78,8 +78,8 @@ load_prc_file(const Filename &filename) { * loaded prc files is listed. */ EXPCL_PANDA_PUTIL ConfigPage * -load_prc_file_data(const string &name, const string &data) { - istringstream strm(data); +load_prc_file_data(const std::string &name, const std::string &data) { + std::istringstream strm(data); ConfigPageManager *cp_mgr = ConfigPageManager::get_global_ptr(); @@ -94,7 +94,7 @@ load_prc_file_data(const string &name, const string &data) { util_cat.info() << "Unable to read explicit prc data " << name << "\n"; cp_mgr->delete_explicit_page(page); - return NULL; + return nullptr; } } @@ -121,7 +121,7 @@ unload_prc_file(ConfigPage *page) { */ void hash_prc_variables(HashVal &hash) { - ostringstream strm; + std::ostringstream strm; ConfigVariableManager *cv_mgr = ConfigVariableManager::get_global_ptr(); cv_mgr->write_prc_variables(strm); hash.hash_string(strm.str()); diff --git a/panda/src/putil/load_prc_file.h b/panda/src/putil/load_prc_file.h index b1711bcd6d..cf29e6c8a3 100644 --- a/panda/src/putil/load_prc_file.h +++ b/panda/src/putil/load_prc_file.h @@ -47,7 +47,7 @@ load_prc_file(const Filename &filename); * loaded prc files is listed. */ EXPCL_PANDA_PUTIL ConfigPage * -load_prc_file_data(const string &name, const string &data); +load_prc_file_data(const std::string &name, const std::string &data); /** * Unloads (and deletes) a ConfigPage that represents a prc file that was diff --git a/panda/src/putil/loaderOptions.I b/panda/src/putil/loaderOptions.I index b15780c847..6e407e7840 100644 --- a/panda/src/putil/loaderOptions.I +++ b/panda/src/putil/loaderOptions.I @@ -14,7 +14,7 @@ /** * */ -INLINE LoaderOptions:: +constexpr LoaderOptions:: LoaderOptions(int flags, int texture_flags) : _flags(flags), _texture_flags(texture_flags), @@ -23,29 +23,6 @@ LoaderOptions(int flags, int texture_flags) : { } -/** - * - */ -INLINE LoaderOptions:: -LoaderOptions(const LoaderOptions ©) : - _flags(copy._flags), - _texture_flags(copy._texture_flags), - _texture_num_views(copy._texture_num_views), - _auto_texture_scale(copy._auto_texture_scale) -{ -} - -/** - * - */ -INLINE void LoaderOptions:: -operator = (const LoaderOptions ©) { - _flags = copy._flags; - _texture_flags = copy._texture_flags; - _texture_num_views = copy._texture_num_views; - _auto_texture_scale = copy._auto_texture_scale; -} - /** * */ diff --git a/panda/src/putil/loaderOptions.cxx b/panda/src/putil/loaderOptions.cxx index 7f57d77fef..508e22f23c 100644 --- a/panda/src/putil/loaderOptions.cxx +++ b/panda/src/putil/loaderOptions.cxx @@ -15,6 +15,8 @@ #include "config_putil.h" #include "indent.h" +using std::string; + /** * */ @@ -29,13 +31,13 @@ LoaderOptions(int flags) : static ConfigVariableBool *preload_textures; static ConfigVariableBool *preload_simple_textures; static ConfigVariableBool *compressed_textures; - if (preload_textures == NULL) { + if (preload_textures == nullptr) { preload_textures = new ConfigVariableBool("preload-textures", true); } - if (preload_simple_textures == NULL) { + if (preload_simple_textures == nullptr) { preload_simple_textures = new ConfigVariableBool("preload-simple-textures", false); } - if (compressed_textures == NULL) { + if (compressed_textures == nullptr) { compressed_textures = new ConfigVariableBool("compressed-textures", false); } @@ -54,7 +56,7 @@ LoaderOptions(int flags) : * */ void LoaderOptions:: -output(ostream &out) const { +output(std::ostream &out) const { out << "LoaderOptions("; string sep = ""; @@ -100,7 +102,7 @@ output(ostream &out) const { * Used to implement output(). */ void LoaderOptions:: -write_flag(ostream &out, string &sep, +write_flag(std::ostream &out, string &sep, const string &flag_name, int flag) const { if ((_flags & flag) == flag) { out << sep << flag_name; @@ -112,7 +114,7 @@ write_flag(ostream &out, string &sep, * Used to implement output(). */ void LoaderOptions:: -write_texture_flag(ostream &out, string &sep, +write_texture_flag(std::ostream &out, string &sep, const string &flag_name, int flag) const { if ((_texture_flags & flag) == flag) { out << sep << flag_name; diff --git a/panda/src/putil/loaderOptions.h b/panda/src/putil/loaderOptions.h index 50c73f983e..c07fe798d8 100644 --- a/panda/src/putil/loaderOptions.h +++ b/panda/src/putil/loaderOptions.h @@ -49,9 +49,7 @@ PUBLISHED: }; LoaderOptions(int flags = LF_search | LF_report_errors); - INLINE LoaderOptions(int flags, int texture_flags); - INLINE LoaderOptions(const LoaderOptions ©); - INLINE void operator = (const LoaderOptions ©); + constexpr LoaderOptions(int flags, int texture_flags); INLINE void set_flags(int flags); INLINE int get_flags() const; @@ -70,20 +68,20 @@ PUBLISHED: MAKE_PROPERTY(auto_texture_scale, get_auto_texture_scale, set_auto_texture_scale); - void output(ostream &out) const; + void output(std::ostream &out) const; private: - void write_flag(ostream &out, string &sep, - const string &flag_name, int flag) const; - void write_texture_flag(ostream &out, string &sep, - const string &flag_name, int flag) const; + void write_flag(std::ostream &out, std::string &sep, + const std::string &flag_name, int flag) const; + void write_texture_flag(std::ostream &out, std::string &sep, + const std::string &flag_name, int flag) const; int _flags; int _texture_flags; int _texture_num_views; AutoTextureScale _auto_texture_scale; }; -INLINE ostream &operator << (ostream &out, const LoaderOptions &opts) { +INLINE std::ostream &operator << (std::ostream &out, const LoaderOptions &opts) { opts.output(out); return out; } diff --git a/panda/src/putil/modifierButtons.cxx b/panda/src/putil/modifierButtons.cxx index a0c4a79146..00a75fcdd9 100644 --- a/panda/src/putil/modifierButtons.cxx +++ b/panda/src/putil/modifierButtons.cxx @@ -302,9 +302,9 @@ is_down(ButtonHandle button) const { * Returns a string which can be used to prefix any button name or event name * with the unique set of modifier buttons currently being held. */ -string ModifierButtons:: +std::string ModifierButtons:: get_prefix() const { - string prefix; + std::string prefix; for (int i = 0; i < (int)_button_list.size(); i++) { if ((_state & ((BitmaskType)1 << i)) != 0) { prefix += _button_list[i].get_name(); @@ -319,7 +319,7 @@ get_prefix() const { * Writes a one-line summary of the buttons known to be down. */ void ModifierButtons:: -output(ostream &out) const { +output(std::ostream &out) const { out << "["; for (int i = 0; i < (int)_button_list.size(); i++) { if ((_state & ((BitmaskType)1 << i)) != 0) { @@ -334,7 +334,7 @@ output(ostream &out) const { * and which ones are known to be down. */ void ModifierButtons:: -write(ostream &out) const { +write(std::ostream &out) const { out << "ModifierButtons:\n"; for (int i = 0; i < (int)_button_list.size(); i++) { out << " " << _button_list[i]; diff --git a/panda/src/putil/modifierButtons.h b/panda/src/putil/modifierButtons.h index c95791b2a0..d879512514 100644 --- a/panda/src/putil/modifierButtons.h +++ b/panda/src/putil/modifierButtons.h @@ -61,10 +61,10 @@ PUBLISHED: INLINE bool is_down(int index) const; INLINE bool is_any_down() const; - string get_prefix() const; + std::string get_prefix() const; - void output(ostream &out) const; - void write(ostream &out) const; + void output(std::ostream &out) const; + void write(std::ostream &out) const; private: void modify_button_list(); @@ -74,7 +74,7 @@ private: BitmaskType _state; }; -INLINE ostream &operator << (ostream &out, const ModifierButtons &mb) { +INLINE std::ostream &operator << (std::ostream &out, const ModifierButtons &mb) { mb.output(out); return out; } diff --git a/panda/src/putil/mouseData.I b/panda/src/putil/mouseData.I index bdcf750af6..c0ab6997ef 100644 --- a/panda/src/putil/mouseData.I +++ b/panda/src/putil/mouseData.I @@ -67,7 +67,7 @@ get_in_window() const { } -INLINE ostream &operator << (ostream &out, const MouseData &md) { +INLINE std::ostream &operator << (std::ostream &out, const MouseData &md) { md.output(out); return out; } diff --git a/panda/src/putil/mouseData.cxx b/panda/src/putil/mouseData.cxx index 8149672c9b..de83bd1505 100644 --- a/panda/src/putil/mouseData.cxx +++ b/panda/src/putil/mouseData.cxx @@ -17,7 +17,7 @@ * */ void MouseData:: -output(ostream &out) const { +output(std::ostream &out) const { if (!_in_window) { out << "MouseData: Not in window"; } else { diff --git a/panda/src/putil/mouseData.h b/panda/src/putil/mouseData.h index 4fe2c81b4f..0d2a294568 100644 --- a/panda/src/putil/mouseData.h +++ b/panda/src/putil/mouseData.h @@ -32,7 +32,7 @@ PUBLISHED: INLINE double get_y() const; INLINE bool get_in_window() const; - void output(ostream &out) const; + void output(std::ostream &out) const; MAKE_PROPERTY(x, get_x); MAKE_PROPERTY(y, get_y); @@ -44,7 +44,7 @@ public: double _ypos; }; -INLINE ostream &operator << (ostream &out, const MouseData &md); +INLINE std::ostream &operator << (std::ostream &out, const MouseData &md); #include "mouseData.I" diff --git a/panda/src/putil/nameUniquifier.I b/panda/src/putil/nameUniquifier.I index 4ccfa1e0b0..760dad2dfc 100644 --- a/panda/src/putil/nameUniquifier.I +++ b/panda/src/putil/nameUniquifier.I @@ -24,8 +24,8 @@ * If the name is nonempty, the new name is the original name, followed by the * NameUniquifier's "separator" string, followed by a number. */ -INLINE string NameUniquifier:: -add_name(const string &name) { +INLINE std::string NameUniquifier:: +add_name(const std::string &name) { return add_name_body(name, name); } @@ -42,7 +42,7 @@ add_name(const string &name) { * If the prefix is nonempty, the new name is the prefix, followed by the * NameUniquifier's "separator" string, followed by a number. */ -INLINE string NameUniquifier:: -add_name(const string &name, const string &prefix) { +INLINE std::string NameUniquifier:: +add_name(const std::string &name, const std::string &prefix) { return add_name_body(name, prefix); } diff --git a/panda/src/putil/nameUniquifier.cxx b/panda/src/putil/nameUniquifier.cxx index 0629a58ac9..e6ab3f6917 100644 --- a/panda/src/putil/nameUniquifier.cxx +++ b/panda/src/putil/nameUniquifier.cxx @@ -17,6 +17,8 @@ #include +using std::string; + /** * Creates a new NameUniquifier. diff --git a/panda/src/putil/nameUniquifier.h b/panda/src/putil/nameUniquifier.h index 7b629771d2..1d3c3e2560 100644 --- a/panda/src/putil/nameUniquifier.h +++ b/panda/src/putil/nameUniquifier.h @@ -27,20 +27,20 @@ */ class EXPCL_PANDA_PUTIL NameUniquifier { public: - NameUniquifier(const string &separator = string(), - const string &empty = string()); + NameUniquifier(const std::string &separator = std::string(), + const std::string &empty = std::string()); ~NameUniquifier(); - INLINE string add_name(const string &name); - INLINE string add_name(const string &name, const string &prefix); + INLINE std::string add_name(const std::string &name); + INLINE std::string add_name(const std::string &name, const std::string &prefix); private: - string add_name_body(const string &name, const string &prefix); + std::string add_name_body(const std::string &name, const std::string &prefix); - typedef pset Names; + typedef pset Names; Names _names; - string _separator; - string _empty; + std::string _separator; + std::string _empty; int _counter; }; diff --git a/panda/src/putil/nodeCachedReferenceCount.I b/panda/src/putil/nodeCachedReferenceCount.I index c06016d523..92abe19ce3 100644 --- a/panda/src/putil/nodeCachedReferenceCount.I +++ b/panda/src/putil/nodeCachedReferenceCount.I @@ -49,8 +49,6 @@ NodeCachedReferenceCount(const NodeCachedReferenceCount ©) : CachedTypedWrit */ INLINE void NodeCachedReferenceCount:: operator = (const NodeCachedReferenceCount ©) { - nassertv(this != NULL); - // If this assertion fails, our own pointer was recently deleted. Possibly // you used a real pointer instead of a PointerTo at some point, and the // object was deleted when the PointerTo went out of scope. Maybe you tried @@ -71,8 +69,6 @@ operator = (const NodeCachedReferenceCount ©) { */ INLINE NodeCachedReferenceCount:: ~NodeCachedReferenceCount() { - nassertv(this != NULL); - // If this assertion fails, we're trying to delete an object that was just // deleted. Possibly you used a real pointer instead of a PointerTo at some // point, and the object was deleted when the PointerTo went out of scope. diff --git a/panda/src/putil/nodeCachedReferenceCount.cxx b/panda/src/putil/nodeCachedReferenceCount.cxx index 62249dcd42..f53ff22b96 100644 --- a/panda/src/putil/nodeCachedReferenceCount.cxx +++ b/panda/src/putil/nodeCachedReferenceCount.cxx @@ -21,8 +21,6 @@ TypeHandle NodeCachedReferenceCount::_type_handle; */ bool NodeCachedReferenceCount:: do_test_ref_count_integrity() const { - nassertr(this != NULL, false); - // If this assertion fails, we're trying to delete an object that was just // deleted. Possibly you used a real pointer instead of a PointerTo at some // point, and the object was deleted when the PointerTo went out of scope. diff --git a/panda/src/putil/paramValue.I b/panda/src/putil/paramValue.I index f446b88dad..0f44d4d54e 100644 --- a/panda/src/putil/paramValue.I +++ b/panda/src/putil/paramValue.I @@ -43,7 +43,7 @@ ParamTypedRefCount(const TypedReferenceCount *value) : */ INLINE TypeHandle ParamTypedRefCount:: get_value_type() const { - if (_value == NULL) { + if (_value == nullptr) { return TypeHandle::none(); } else { return _value->get_type(); @@ -116,7 +116,7 @@ get_value() const { */ template INLINE void ParamValue:: -output(ostream &out) const { +output(std::ostream &out) const { out << _value; } diff --git a/panda/src/putil/paramValue.cxx b/panda/src/putil/paramValue.cxx index 6937a27faa..5ffcf2807c 100644 --- a/panda/src/putil/paramValue.cxx +++ b/panda/src/putil/paramValue.cxx @@ -56,8 +56,8 @@ ParamTypedRefCount:: * */ void ParamTypedRefCount:: -output(ostream &out) const { - if (_value == (TypedReferenceCount *)NULL) { +output(std::ostream &out) const { + if (_value == nullptr) { out << "(empty)"; } else { diff --git a/panda/src/putil/paramValue.h b/panda/src/putil/paramValue.h index b17b2c9c37..ea3b8fcae5 100644 --- a/panda/src/putil/paramValue.h +++ b/panda/src/putil/paramValue.h @@ -35,7 +35,7 @@ public: PUBLISHED: virtual ~ParamValueBase(); INLINE virtual TypeHandle get_value_type() const; - virtual void output(ostream &out) const=0; + virtual void output(std::ostream &out) const=0; public: virtual TypeHandle get_type() const { @@ -69,7 +69,7 @@ PUBLISHED: MAKE_PROPERTY(value, get_value); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; private: PT(TypedReferenceCount) _value; @@ -114,7 +114,7 @@ PUBLISHED: MAKE_PROPERTY(value, get_value, set_value); - INLINE virtual void output(ostream &out) const; + INLINE virtual void output(std::ostream &out) const; private: Type _value; @@ -131,7 +131,7 @@ public: static TypeHandle get_class_type() { return _type_handle; } - static void init_type(const string &type_name = "UndefinedParamValue") { + static void init_type(const std::string &type_name = "UndefinedParamValue") { ParamValueBase::init_type(); _type_handle = register_dynamic_type (type_name, ParamValueBase::get_class_type()); @@ -172,8 +172,8 @@ EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_PUTIL, EXPTP_PANDA_PUTIL, ParamValue); EXPORT_TEMPLATE_CLASS(EXPCL_PANDA_PUTIL, EXPTP_PANDA_PUTIL, ParamValue); -typedef ParamValue ParamString; -typedef ParamValue ParamWstring; +typedef ParamValue ParamString; +typedef ParamValue ParamWstring; typedef ParamValue ParamVecBase2d; typedef ParamValue ParamVecBase2f; diff --git a/panda/src/putil/pythonCallbackObject.cxx b/panda/src/putil/pythonCallbackObject.cxx index b1917c6e0e..e8ef005c2e 100644 --- a/panda/src/putil/pythonCallbackObject.cxx +++ b/panda/src/putil/pythonCallbackObject.cxx @@ -111,7 +111,7 @@ do_callback(CallbackData *cbdata) { */ void PythonCallbackObject:: do_python_callback(CallbackData *cbdata) { - nassertv(cbdata != NULL); + nassertv(cbdata != nullptr); // Wrap the cbdata up in a Python object, then put it in a tuple, for the // argument list. @@ -124,7 +124,7 @@ do_python_callback(CallbackData *cbdata) { PyObject *result = PythonThread::call_python_func(_function, args); Py_DECREF(args); - if (result == (PyObject *)NULL) { + if (result == nullptr) { if (PyErr_Occurred() != PyExc_SystemExit) { util_cat.error() << "Exception occurred in " << *this << "\n"; diff --git a/panda/src/putil/simpleHashMap.I b/panda/src/putil/simpleHashMap.I index 26728f1e01..2ac26a54f0 100644 --- a/panda/src/putil/simpleHashMap.I +++ b/panda/src/putil/simpleHashMap.I @@ -15,7 +15,7 @@ * */ template -CONSTEXPR SimpleHashMap:: +constexpr SimpleHashMap:: SimpleHashMap(const Compare &comp) : _table(nullptr), _deleted_chain(nullptr), @@ -55,12 +55,12 @@ SimpleHashMap(const SimpleHashMap ©) : */ template INLINE SimpleHashMap:: -SimpleHashMap(SimpleHashMap &&from) NOEXCEPT : +SimpleHashMap(SimpleHashMap &&from) noexcept : _table(from._table), _deleted_chain(from._deleted_chain), _table_size(from._table_size), _num_entries(from._num_entries), - _comp(move(from._comp)) + _comp(std::move(from._comp)) { from._table = nullptr; from._deleted_chain = nullptr; @@ -109,13 +109,13 @@ operator = (const SimpleHashMap ©) { */ template INLINE SimpleHashMap &SimpleHashMap:: -operator = (SimpleHashMap &&from) NOEXCEPT { +operator = (SimpleHashMap &&from) noexcept { if (this != &from) { _table = from._table; _deleted_chain = from._deleted_chain; _table_size = from._table_size; _num_entries = from._num_entries; - _comp = move(from._comp); + _comp = std::move(from._comp); from._table = nullptr; from._deleted_chain = nullptr; @@ -275,7 +275,7 @@ remove(const Key &key) { // Swap it with the last one, so that we don't get any gaps in the table // of entries. - _table[index] = move(_table[last]); + _table[index] = std::move(_table[last]); index_array[(size_t)other_slot] = index; } @@ -360,7 +360,7 @@ operator [] (const Key &key) { * Returns the total number of entries in the table. Same as get_num_entries. */ template -CONSTEXPR size_t SimpleHashMap:: +constexpr size_t SimpleHashMap:: size() const { return _num_entries; } @@ -422,7 +422,7 @@ template INLINE void SimpleHashMap:: set_data(size_t n, Value &&data) { nassertv(n < _num_entries); - _table[n].set_data(move(data)); + _table[n].set_data(std::move(data)); } /** @@ -460,7 +460,7 @@ is_empty() const { */ template void SimpleHashMap:: -output(ostream &out) const { +output(std::ostream &out) const { out << "SimpleHashMap (" << _num_entries << " entries): ["; const int *index_array = get_index_array(); size_t num_slots = _table_size * sparsity; @@ -487,7 +487,7 @@ output(ostream &out) const { */ template void SimpleHashMap:: -write(ostream &out) const { +write(std::ostream &out) const { output(out); out << "\n"; for (size_t i = 0; i < _num_entries; ++i) { @@ -731,7 +731,7 @@ resize_table(size_t new_size) { // have to reorder these, fortunately. Hopefully, a smart compiler will // optimize this to a memcpy. for (size_t i = 0; i < _num_entries; ++i) { - new(&_table[i]) TableEntry(move(old_table[i])); + new(&_table[i]) TableEntry(std::move(old_table[i])); old_table[i].~TableEntry(); } diff --git a/panda/src/putil/simpleHashMap.h b/panda/src/putil/simpleHashMap.h index 68f6352a88..bae858006d 100644 --- a/panda/src/putil/simpleHashMap.h +++ b/panda/src/putil/simpleHashMap.h @@ -40,7 +40,7 @@ public: _data = data; } ALWAYS_INLINE void set_data(Value &&data) { - _data = move(data); + _data = std::move(data); } private: @@ -52,16 +52,16 @@ private: * values. This allows effectively using SimpleHashMap as a set. */ template -class SimpleKeyValuePair { +class SimpleKeyValuePair { public: - INLINE SimpleKeyValuePair(const Key &key, nullptr_t data) : + INLINE SimpleKeyValuePair(const Key &key, std::nullptr_t data) : _key(key) {} Key _key; - ALWAYS_INLINE_CONSTEXPR static nullptr_t get_data() { return nullptr; } - ALWAYS_INLINE_CONSTEXPR static nullptr_t modify_data() { return nullptr; } - ALWAYS_INLINE static void set_data(nullptr_t) {} + ALWAYS_INLINE constexpr static std::nullptr_t get_data() { return nullptr; } + ALWAYS_INLINE constexpr static std::nullptr_t modify_data() { return nullptr; } + ALWAYS_INLINE static void set_data(std::nullptr_t) {} }; /** @@ -77,7 +77,7 @@ public: * * It can also be used as a set, by using nullptr_t as Value typename. */ -template > > +template > > class SimpleHashMap { // Per-entry overhead is determined by sizeof(int) * sparsity. Should be a // power of two. @@ -85,13 +85,13 @@ class SimpleHashMap { public: #ifndef CPPPARSER - CONSTEXPR SimpleHashMap(const Compare &comp = Compare()); + constexpr SimpleHashMap(const Compare &comp = Compare()); INLINE SimpleHashMap(const SimpleHashMap ©); - INLINE SimpleHashMap(SimpleHashMap &&from) NOEXCEPT; + INLINE SimpleHashMap(SimpleHashMap &&from) noexcept; INLINE ~SimpleHashMap(); INLINE SimpleHashMap &operator = (const SimpleHashMap ©); - INLINE SimpleHashMap &operator = (SimpleHashMap &&from) NOEXCEPT; + INLINE SimpleHashMap &operator = (SimpleHashMap &&from) noexcept; INLINE void swap(SimpleHashMap &other); @@ -101,7 +101,7 @@ public: void clear(); INLINE Value &operator [] (const Key &key); - CONSTEXPR size_t size() const; + constexpr size_t size() const; INLINE const Key &get_key(size_t n) const; INLINE const Value &get_data(size_t n) const; @@ -113,8 +113,8 @@ public: INLINE size_t get_num_entries() const; INLINE bool is_empty() const; - void output(ostream &out) const; - void write(ostream &out) const; + void output(std::ostream &out) const; + void write(std::ostream &out) const; bool validate() const; INLINE bool consider_shrink_table(); @@ -145,7 +145,7 @@ public: }; template -inline ostream &operator << (ostream &out, const SimpleHashMap &shm) { +inline std::ostream &operator << (std::ostream &out, const SimpleHashMap &shm) { shm.output(out); return out; } diff --git a/panda/src/putil/sparseArray.cxx b/panda/src/putil/sparseArray.cxx index 37940d1d10..6373e53039 100644 --- a/panda/src/putil/sparseArray.cxx +++ b/panda/src/putil/sparseArray.cxx @@ -214,7 +214,7 @@ has_bits_in_common(const SparseArray &other) const { * */ void SparseArray:: -output(ostream &out) const { +output(std::ostream &out) const { out << "[ "; if (_inverse) { out << "all except: "; @@ -442,7 +442,7 @@ do_remove_range(int begin, int end) { si = _subranges.begin() + _subranges.size() - 1; if ((*si)._end >= begin) { // The new range shortens the last element of the array on the right. - end = min(end, (*si)._begin); + end = std::min(end, (*si)._begin); (*si)._end = end; // It might also shorten it on the left; fall through. } else { @@ -465,7 +465,7 @@ do_remove_range(int begin, int end) { if ((*si2)._end >= begin) { // The new range shortens an element within the array on the right // (but does not intersect the next element). - end = min(end, (*si2)._begin); + end = std::min(end, (*si2)._begin); (*si2)._end = end; // It might also shorten it on the left; fall through. si = si2; @@ -499,7 +499,7 @@ do_remove_range(int begin, int end) { si = si2; } - (*si)._end = min((*si)._end, begin); + (*si)._end = std::min((*si)._end, begin); } /** diff --git a/panda/src/putil/sparseArray.h b/panda/src/putil/sparseArray.h index a372fc240e..de6a508d29 100644 --- a/panda/src/putil/sparseArray.h +++ b/panda/src/putil/sparseArray.h @@ -80,7 +80,7 @@ PUBLISHED: bool has_bits_in_common(const SparseArray &other) const; INLINE void clear(); - void output(ostream &out) const; + void output(std::ostream &out) const; INLINE bool operator == (const SparseArray &other) const; INLINE bool operator != (const SparseArray &other) const; @@ -158,8 +158,8 @@ private: #include "sparseArray.I" -INLINE ostream & -operator << (ostream &out, const SparseArray &array) { +INLINE std::ostream & +operator << (std::ostream &out, const SparseArray &array) { array.output(out); return out; } diff --git a/panda/src/putil/test_bam.cxx b/panda/src/putil/test_bam.cxx index deef264ce1..bf6d862434 100644 --- a/panda/src/putil/test_bam.cxx +++ b/panda/src/putil/test_bam.cxx @@ -17,6 +17,8 @@ #include "test_bam.h" +using std::endl; + TypeHandle Person::_type_handle; TypeHandle Parent::_type_handle; @@ -79,9 +81,9 @@ complete_pointers(TypedWritable **p_list, BamReader *manager) void Person:: print_relationships(){ nout << "My name is " << _name << endl; - if (_bro != NULL) + if (_bro != nullptr) nout << "My brother is " << _bro->name() << endl; - if (_sis != NULL) + if (_sis != nullptr) nout << "My sister is " << _sis->name() << endl; } @@ -137,9 +139,9 @@ setDaughter(Child* daughter) void Parent:: print_relationships(){ Person::print_relationships(); - if (_son != NULL) + if (_son != nullptr) nout << "My son is " << _son->name() << endl; - if (_daughter != NULL) + if (_daughter != nullptr) nout << "My daughter is " << _daughter->name() << endl; } @@ -197,8 +199,8 @@ setMother(Parent* mom) void Child:: print_relationships(){ Person::print_relationships(); - if (_dad != NULL) + if (_dad != nullptr) nout << "My dad is " << _dad->name() << endl; - if (_mom != NULL) + if (_mom != nullptr) nout << "My mom is " << _mom->name() << endl; } diff --git a/panda/src/putil/test_bam.h b/panda/src/putil/test_bam.h index 557b9ba6b4..1570f1541a 100644 --- a/panda/src/putil/test_bam.h +++ b/panda/src/putil/test_bam.h @@ -45,16 +45,16 @@ public: bool isMale() {return myGender == MALE;} void print_relationships(); - string name() {return _name;} + std::string name() {return _name;} private: Person *_bro, *_sis; sex myGender; - string _name; + std::string _name; public: Person() {} - Person(const string &name, const sex Gender) : - _name(name), myGender(Gender), _bro((Person*)NULL), _sis((Person*)NULL) { + Person(const std::string &name, const sex Gender) : + _name(name), myGender(Gender), _bro(nullptr), _sis(nullptr) { } virtual ~Person() { @@ -100,7 +100,7 @@ private: public: Parent() {} - Parent(const string &name, const sex Gender) : Person(name, Gender) { + Parent(const std::string &name, const sex Gender) : Person(name, Gender) { } virtual ~Parent() { @@ -146,7 +146,7 @@ private: public: Child() {} - Child(const string &name, const sex Gender) : Person(name, Gender) { + Child(const std::string &name, const sex Gender) : Person(name, Gender) { } virtual ~Child() { diff --git a/panda/src/putil/test_bamRead.cxx b/panda/src/putil/test_bamRead.cxx index d49f49434b..50949f63eb 100644 --- a/panda/src/putil/test_bamRead.cxx +++ b/panda/src/putil/test_bamRead.cxx @@ -20,7 +20,7 @@ int main(int argc, char* argv[]) { - string test_file = "bamTest.out"; + std::string test_file = "bamTest.out"; DatagramInputFile stream; bool success = stream.open(test_file); nassertr(success, 1); @@ -37,11 +37,11 @@ int main(int argc, char* argv[]) manager.resolve(); dad->print_relationships(); - nout << endl; + nout << std::endl; mom->print_relationships(); - nout << endl; + nout << std::endl; bro->print_relationships(); - nout << endl; + nout << std::endl; sis->print_relationships(); return 0; diff --git a/panda/src/putil/test_bamWrite.cxx b/panda/src/putil/test_bamWrite.cxx index 59d56930ec..9469b8a6a3 100644 --- a/panda/src/putil/test_bamWrite.cxx +++ b/panda/src/putil/test_bamWrite.cxx @@ -19,7 +19,7 @@ int main(int argc, char* argv[]) { - string test_file("bamTest.out"); + std::string test_file("bamTest.out"); DatagramOutputFile stream; bool success = stream.open(test_file); nassertr(success, 1); diff --git a/panda/src/putil/test_glob.cxx b/panda/src/putil/test_glob.cxx index 32ba0d1927..cc5141dcdd 100644 --- a/panda/src/putil/test_glob.cxx +++ b/panda/src/putil/test_glob.cxx @@ -16,7 +16,7 @@ int main(int argc, char *argv[]) { if (argc != 2 && argc != 3) { - cerr + std::cerr << "test_glob \"pattern\" [from-directory]\n\n" << "Attempts to match the pattern against each of the files in the\n" << "indicated directory if specified, or the current directory\n" @@ -36,10 +36,10 @@ main(int argc, char *argv[]) { vector_string results; int num_matched = pattern.match_files(results, from_directory); - cerr << num_matched << " results:\n"; + std::cerr << num_matched << " results:\n"; vector_string::const_iterator si; for (si = results.begin(); si != results.end(); ++si) { - cerr << " " << *si << "\n"; + std::cerr << " " << *si << "\n"; } return (0); diff --git a/panda/src/putil/test_uniqueIdAllocator.cxx b/panda/src/putil/test_uniqueIdAllocator.cxx index be39a01450..73c3c6b498 100644 --- a/panda/src/putil/test_uniqueIdAllocator.cxx +++ b/panda/src/putil/test_uniqueIdAllocator.cxx @@ -4,7 +4,9 @@ #include #include #include -using namespace std; + +using std::cout; +using std::endl; #include "uniqueIdAllocator.h" diff --git a/panda/src/putil/typedWritable.I b/panda/src/putil/typedWritable.I index 21f86f03a4..5940fd9de3 100644 --- a/panda/src/putil/typedWritable.I +++ b/panda/src/putil/typedWritable.I @@ -15,14 +15,14 @@ * */ INLINE TypedWritable:: -TypedWritable() : _bam_writers(NULL) { +TypedWritable() : _bam_writers(nullptr) { } /** * */ INLINE TypedWritable:: -TypedWritable(const TypedWritable &) : _bam_writers(NULL) { +TypedWritable(const TypedWritable &) : _bam_writers(nullptr) { } /** diff --git a/panda/src/putil/typedWritable.cxx b/panda/src/putil/typedWritable.cxx index 7cc9d93cbd..8ca4081c63 100644 --- a/panda/src/putil/typedWritable.cxx +++ b/panda/src/putil/typedWritable.cxx @@ -19,7 +19,7 @@ #include "bam.h" TypeHandle TypedWritable::_type_handle; -TypedWritable* const TypedWritable::Null = (TypedWritable*)0L; +TypedWritable* const TypedWritable::Null = nullptr; /** * @@ -30,15 +30,15 @@ TypedWritable:: BamWriterLink *link; do { link = (BamWriterLink *)AtomicAdjust::get_ptr(_bam_writers); - if (link == (BamWriterLink *)NULL) { + if (link == nullptr) { // List is unlocked and empty - no writers to remove. return; } link = (BamWriterLink *)(((uintptr_t)link) & ~(uintptr_t)0x1); } while (link != AtomicAdjust:: - compare_and_exchange_ptr(_bam_writers, (void *)link, (void *)NULL)); + compare_and_exchange_ptr(_bam_writers, (void *)link, nullptr)); - while (link != (BamWriterLink *)NULL) { + while (link != nullptr) { BamWriterLink *next_link = link->_next; link->_writer->object_destructs(this); delete link; @@ -119,7 +119,7 @@ finalize(BamReader *) { */ ReferenceCount *TypedWritable:: as_reference_count() { - return NULL; + return nullptr; } /** @@ -190,11 +190,11 @@ bool TypedWritable:: decode_raw_from_bam_stream(TypedWritable *&ptr, ReferenceCount *&ref_ptr, vector_uchar data, BamReader *reader) { - DatagramBuffer buffer(move(data)); + DatagramBuffer buffer(std::move(data)); - if (reader == NULL) { + if (reader == nullptr) { // Create a local reader. - string head; + std::string head; if (!buffer.read_header(head, _bam_header.size())) { return false; } @@ -216,7 +216,7 @@ decode_raw_from_bam_stream(TypedWritable *&ptr, ReferenceCount *&ref_ptr, return false; } - if (ref_ptr == NULL) { + if (ref_ptr == nullptr) { // Can't support non-reference-counted objects. return false; } @@ -229,25 +229,25 @@ decode_raw_from_bam_stream(TypedWritable *&ptr, ReferenceCount *&ref_ptr, // Use the existing reader. reader->set_source(&buffer); if (!reader->read_object(ptr, ref_ptr)) { - reader->set_source(NULL); + reader->set_source(nullptr); return false; } if (!reader->resolve()) { - reader->set_source(NULL); + reader->set_source(nullptr); return false; } - if (ref_ptr == NULL) { + if (ref_ptr == nullptr) { // Can't support non-reference-counted objects. - reader->set_source(NULL); + reader->set_source(nullptr); return false; } // This BamReader isn't going away, but we have to balance the unref() // below. ref_ptr->ref(); - reader->set_source(NULL); + reader->set_source(nullptr); } @@ -265,7 +265,7 @@ decode_raw_from_bam_stream(TypedWritable *&ptr, ReferenceCount *&ref_ptr, */ void TypedWritable:: add_bam_writer(BamWriter *writer) { - nassertv(writer != (BamWriter *)NULL); + nassertv(writer != nullptr); BamWriterLink *begin; BamWriterLink *new_link = new BamWriterLink; @@ -289,7 +289,7 @@ add_bam_writer(BamWriter *writer) { */ void TypedWritable:: remove_bam_writer(BamWriter *writer) { - nassertv(writer != (BamWriter *)NULL); + nassertv(writer != nullptr); BamWriterLink *begin; @@ -298,7 +298,7 @@ remove_bam_writer(BamWriter *writer) { do { begin = (BamWriterLink *)AtomicAdjust::get_ptr(_bam_writers); begin = (BamWriterLink *)(((uintptr_t)begin) & ~(uintptr_t)0x1); - if (begin == NULL) { + if (begin == nullptr) { // The list is empty, nothing to remove. return; } @@ -307,21 +307,21 @@ remove_bam_writer(BamWriter *writer) { (void *)((uintptr_t)begin | (uintptr_t)0x1))); // Find the writer in the list. - BamWriterLink *prev_link = (BamWriterLink *)NULL; + BamWriterLink *prev_link = nullptr; BamWriterLink *link = begin; - while (link != NULL && link->_writer != writer) { + while (link != nullptr && link->_writer != writer) { prev_link = link; link = link->_next; } - if (link == (BamWriterLink *)NULL) { + if (link == nullptr) { // Not found. Just unlock and leave. _bam_writers = (void *)begin; return; } - if (prev_link == (BamWriterLink *)NULL) { + if (prev_link == nullptr) { // It's the first link. Replace and unlock in one atomic op. _bam_writers = (void *)link->_next; } else { diff --git a/panda/src/putil/typedWritable.h b/panda/src/putil/typedWritable.h index b13a1991fb..2dbdc3d967 100644 --- a/panda/src/putil/typedWritable.h +++ b/panda/src/putil/typedWritable.h @@ -64,11 +64,11 @@ PUBLISHED: EXTENSION(PyObject *__reduce_persist__(PyObject *self, PyObject *pickler) const); INLINE vector_uchar encode_to_bam_stream() const; - bool encode_to_bam_stream(vector_uchar &data, BamWriter *writer = NULL) const; + bool encode_to_bam_stream(vector_uchar &data, BamWriter *writer = nullptr) const; static bool decode_raw_from_bam_stream(TypedWritable *&ptr, ReferenceCount *&ref_ptr, vector_uchar data, - BamReader *reader = NULL); + BamReader *reader = nullptr); private: void add_bam_writer(BamWriter *writer); diff --git a/panda/src/putil/typedWritableReferenceCount.cxx b/panda/src/putil/typedWritableReferenceCount.cxx index ba4e2c49e4..3ca6d27550 100644 --- a/panda/src/putil/typedWritableReferenceCount.cxx +++ b/panda/src/putil/typedWritableReferenceCount.cxx @@ -41,7 +41,7 @@ decode_from_bam_stream(vector_uchar data, BamReader *reader) { TypedWritable *object; ReferenceCount *ref_ptr; - if (TypedWritable::decode_raw_from_bam_stream(object, ref_ptr, move(data), reader)) { + if (TypedWritable::decode_raw_from_bam_stream(object, ref_ptr, std::move(data), reader)) { return DCAST(TypedWritableReferenceCount, object); } else { return nullptr; diff --git a/panda/src/putil/typedWritable_ext.cxx b/panda/src/putil/typedWritable_ext.cxx index efaaac63fb..3db4b086c3 100644 --- a/panda/src/putil/typedWritable_ext.cxx +++ b/panda/src/putil/typedWritable_ext.cxx @@ -30,7 +30,7 @@ extern Dtool_PyTypedObject Dtool_BamWriter; */ PyObject *Extension:: __reduce__(PyObject *self) const { - return __reduce_persist__(self, NULL); + return __reduce_persist__(self, nullptr); } /** @@ -51,19 +51,19 @@ __reduce_persist__(PyObject *self, PyObject *pickler) const { // Check that we have a decode_from_bam_stream python method. If not, we // can't use this interface. PyObject *method = PyObject_GetAttrString(self, "decode_from_bam_stream"); - if (method == NULL) { - ostringstream stream; + if (method == nullptr) { + std::ostringstream stream; stream << "Cannot pickle objects of type " << _this->get_type() << "\n"; - string message = stream.str(); + std::string message = stream.str(); PyErr_SetString(PyExc_TypeError, message.c_str()); - return NULL; + return nullptr; } Py_DECREF(method); - BamWriter *writer = NULL; - if (pickler != NULL) { + BamWriter *writer = nullptr; + if (pickler != nullptr) { PyObject *py_writer = PyObject_GetAttrString(pickler, "bamWriter"); - if (py_writer == NULL) { + if (py_writer == nullptr) { // It's OK if there's no bamWriter. PyErr_Clear(); } else { @@ -75,39 +75,39 @@ __reduce_persist__(PyObject *self, PyObject *pickler) const { // First, streamify the object, if possible. vector_uchar bam_stream; if (!_this->encode_to_bam_stream(bam_stream, writer)) { - ostringstream stream; + std::ostringstream stream; stream << "Could not bamify object of type " << _this->get_type() << "\n"; - string message = stream.str(); + std::string message = stream.str(); PyErr_SetString(PyExc_TypeError, message.c_str()); - return NULL; + return nullptr; } // Start by getting this class object. PyObject *this_class = PyObject_Type(self); - if (this_class == NULL) { - return NULL; + if (this_class == nullptr) { + return nullptr; } PyObject *func; - if (writer != NULL) { + if (writer != nullptr) { // The modified pickle support: call the "persistent" version of this // function, which receives the unpickler itself as an additional // parameter. func = find_global_decode(this_class, "py_decode_TypedWritable_from_bam_stream_persist"); - if (func == NULL) { + if (func == nullptr) { PyErr_SetString(PyExc_TypeError, "Couldn't find py_decode_TypedWritable_from_bam_stream_persist()"); Py_DECREF(this_class); - return NULL; + return nullptr; } } else { // The traditional pickle support: call the non-persistent version of this // function. func = find_global_decode(this_class, "py_decode_TypedWritable_from_bam_stream"); - if (func == NULL) { + if (func == nullptr) { PyErr_SetString(PyExc_TypeError, "Couldn't find py_decode_TypedWritable_from_bam_stream()"); Py_DECREF(this_class); - return NULL; + return nullptr; } } @@ -135,15 +135,15 @@ PyObject *Extension:: find_global_decode(PyObject *this_class, const char *func_name) { // Get the module in which BamWriter is defined. PyObject *module_name = PyObject_GetAttrString((PyObject *)&Dtool_BamWriter, "__module__"); - if (module_name != NULL) { + if (module_name != nullptr) { // borrowed reference PyObject *sys_modules = PyImport_GetModuleDict(); - if (sys_modules != NULL) { + if (sys_modules != nullptr) { // borrowed reference PyObject *module = PyDict_GetItem(sys_modules, module_name); - if (module != NULL) { + if (module != nullptr) { PyObject *func = PyObject_GetAttrString(module, (char *)func_name); - if (func != NULL) { + if (func != nullptr) { Py_DECREF(module_name); return func; } @@ -153,15 +153,15 @@ find_global_decode(PyObject *this_class, const char *func_name) { } PyObject *bases = PyObject_GetAttrString(this_class, "__bases__"); - if (bases != NULL) { + if (bases != nullptr) { if (PySequence_Check(bases)) { Py_ssize_t size = PySequence_Size(bases); for (Py_ssize_t i = 0; i < size; ++i) { PyObject *base = PySequence_GetItem(bases, i); - if (base != NULL) { + if (base != nullptr) { PyObject *func = find_global_decode(base, func_name); Py_DECREF(base); - if (func != NULL) { + if (func != nullptr) { Py_DECREF(bases); return func; } @@ -171,7 +171,7 @@ find_global_decode(PyObject *this_class, const char *func_name) { Py_DECREF(bases); } - return NULL; + return nullptr; } /** @@ -197,10 +197,10 @@ py_decode_TypedWritable_from_bam_stream(PyObject *this_class, const vector_uchar PyObject * py_decode_TypedWritable_from_bam_stream_persist(PyObject *pickler, PyObject *this_class, const vector_uchar &data) { - PyObject *py_reader = NULL; - if (pickler != NULL) { + PyObject *py_reader = nullptr; + if (pickler != nullptr) { py_reader = PyObject_GetAttrString(pickler, "bamReader"); - if (py_reader == NULL) { + if (py_reader == nullptr) { // It's OK if there's no bamReader. PyErr_Clear(); } @@ -242,7 +242,7 @@ py_decode_TypedWritable_from_bam_stream_persist(PyObject *pickler, PyObject *thi if (result == Py_None) { Py_DECREF(result); PyErr_SetString(PyExc_ValueError, "Could not unpack bam stream"); - return NULL; + return nullptr; } return result; diff --git a/panda/src/putil/uniqueIdAllocator.cxx b/panda/src/putil/uniqueIdAllocator.cxx index 0b3307a2af..6c4edd9795 100644 --- a/panda/src/putil/uniqueIdAllocator.cxx +++ b/panda/src/putil/uniqueIdAllocator.cxx @@ -17,6 +17,8 @@ #include "uniqueIdAllocator.h" +using std::endl; + NotifyCategoryDecl(uniqueIdAllocator, EXPCL_PANDA_PUTIL, EXPTP_PANDA_PUTIL); NotifyCategoryDef(uniqueIdAllocator, ""); @@ -212,7 +214,7 @@ fraction_used() const { * ...intended for debugging only. */ void UniqueIdAllocator:: -output(ostream &out) const { +output(std::ostream &out) const { out << "UniqueIdAllocator(" << _min << ", " << _max << "), " << _free << " id's remaining of " << _size; } @@ -221,7 +223,7 @@ output(ostream &out) const { * ...intended for debugging only. */ void UniqueIdAllocator:: -write(ostream &out) const { +write(std::ostream &out) const { out << "_min: " << _min << "; _max: " << _max << ";\n_next_free: " << int32_t(_next_free) << "; _last_free: " << int32_t(_last_free) diff --git a/panda/src/putil/uniqueIdAllocator.h b/panda/src/putil/uniqueIdAllocator.h index 54da7c6463..50db80b0b0 100644 --- a/panda/src/putil/uniqueIdAllocator.h +++ b/panda/src/putil/uniqueIdAllocator.h @@ -46,8 +46,8 @@ PUBLISHED: void free(uint32_t index); PN_stdfloat fraction_used() const; - void output(ostream &out) const; - void write(ostream &out) const; + void output(std::ostream &out) const; + void write(std::ostream &out) const; public: static const uint32_t IndexEnd; diff --git a/panda/src/putil/updateSeq.I b/panda/src/putil/updateSeq.I index 99703059d4..bc620002a0 100644 --- a/panda/src/putil/updateSeq.I +++ b/panda/src/putil/updateSeq.I @@ -14,41 +14,17 @@ /** * Creates an UpdateSeq in the given state. */ -CONSTEXPR UpdateSeq:: +constexpr UpdateSeq:: UpdateSeq(unsigned int seq) : _seq(seq) { } /** * Creates an UpdateSeq in the 'initial' state. */ -CONSTEXPR UpdateSeq:: +constexpr UpdateSeq:: UpdateSeq() : _seq((unsigned int)SC_initial) { } -/** - * Returns an UpdateSeq in the 'initial' state. - */ -CONSTEXPR UpdateSeq UpdateSeq:: -initial() { - return UpdateSeq((unsigned int)SC_initial); -} - -/** - * Returns an UpdateSeq in the 'old' state. - */ -CONSTEXPR UpdateSeq UpdateSeq:: -old() { - return UpdateSeq((unsigned int)SC_old); -} - -/** - * Returns an UpdateSeq in the 'fresh' state. - */ -CONSTEXPR UpdateSeq UpdateSeq:: -fresh() { - return UpdateSeq((unsigned int)SC_fresh); -} - /** * */ @@ -59,8 +35,8 @@ UpdateSeq(const UpdateSeq ©) : _seq(AtomicAdjust::get(copy._seq)) { /** * */ -CONSTEXPR UpdateSeq:: -UpdateSeq(const UpdateSeq &&from) NOEXCEPT : _seq(from._seq) { +constexpr UpdateSeq:: +UpdateSeq(const UpdateSeq &&from) noexcept : _seq(from._seq) { } /** @@ -111,7 +87,7 @@ is_fresh() const { INLINE bool UpdateSeq:: is_special() const { // This relies on the assumption that (~0 + 1) == 0. - return ((AtomicAdjust::get(_seq) + 1) <= 2); + return (((unsigned int)AtomicAdjust::get(_seq) + 1u) <= 2u); } /** @@ -243,7 +219,7 @@ get_seq() const { * */ INLINE void UpdateSeq:: -output(ostream &out) const { +output(std::ostream &out) const { AtomicAdjust::Integer seq = AtomicAdjust::get(_seq); switch (seq) { case (AtomicAdjust::Integer)SC_initial: @@ -295,7 +271,7 @@ priv_le(AtomicAdjust::Integer a, AtomicAdjust::Integer b) { return (a == b) || priv_lt(a, b); } -INLINE ostream &operator << (ostream &out, const UpdateSeq &value) { +INLINE std::ostream &operator << (std::ostream &out, const UpdateSeq &value) { value.output(out); return out; } diff --git a/panda/src/putil/updateSeq.h b/panda/src/putil/updateSeq.h index 5ba9de908f..f4feed804a 100644 --- a/panda/src/putil/updateSeq.h +++ b/panda/src/putil/updateSeq.h @@ -36,16 +36,16 @@ */ class EXPCL_PANDA_PUTIL UpdateSeq { private: - CONSTEXPR UpdateSeq(unsigned int seq); + constexpr UpdateSeq(unsigned int seq); PUBLISHED: - CONSTEXPR UpdateSeq(); - CONSTEXPR static UpdateSeq initial(); - CONSTEXPR static UpdateSeq old(); - CONSTEXPR static UpdateSeq fresh(); + constexpr UpdateSeq(); + constexpr static UpdateSeq initial() { return UpdateSeq(SC_initial); } + constexpr static UpdateSeq old() { return UpdateSeq(SC_old); } + constexpr static UpdateSeq fresh() { return UpdateSeq(SC_fresh); } INLINE UpdateSeq(const UpdateSeq ©); - CONSTEXPR UpdateSeq(const UpdateSeq &&from) NOEXCEPT; + constexpr UpdateSeq(const UpdateSeq &&from) noexcept; INLINE UpdateSeq &operator = (const UpdateSeq ©); INLINE void clear(); @@ -68,7 +68,7 @@ PUBLISHED: INLINE AtomicAdjust::Integer get_seq() const; MAKE_PROPERTY(seq, get_seq); - INLINE void output(ostream &out) const; + INLINE void output(std::ostream &out) const; private: INLINE static bool priv_is_special(AtomicAdjust::Integer seq); @@ -76,7 +76,7 @@ private: INLINE static bool priv_le(AtomicAdjust::Integer a, AtomicAdjust::Integer b); private: - enum SpecialCases { + enum SpecialCases : unsigned int { SC_initial = 0, SC_old = 1, SC_fresh = ~(unsigned int)0, @@ -85,7 +85,7 @@ private: AtomicAdjust::Integer _seq; }; -INLINE ostream &operator << (ostream &out, const UpdateSeq &value); +INLINE std::ostream &operator << (std::ostream &out, const UpdateSeq &value); #include "updateSeq.I" diff --git a/panda/src/putil/weakKeyHashMap.I b/panda/src/putil/weakKeyHashMap.I index f894411f24..b2dc97c3f4 100644 --- a/panda/src/putil/weakKeyHashMap.I +++ b/panda/src/putil/weakKeyHashMap.I @@ -17,8 +17,8 @@ template INLINE WeakKeyHashMap:: WeakKeyHashMap() : - _table(NULL), - _deleted_chain(NULL), + _table(nullptr), + _deleted_chain(nullptr), _table_size(0), _num_entries(0) { @@ -196,8 +196,8 @@ clear() { } _deleted_chain->deallocate(_table, TypeHandle::none()); - _table = NULL; - _deleted_chain = NULL; + _table = nullptr; + _deleted_chain = nullptr; _table_size = 0; _num_entries = 0; } @@ -295,7 +295,6 @@ set_data(size_t n, const Value &data) { _table[n]._data = data; } -#ifdef USE_MOVE_SEMANTICS /** * Changes the data for the nth slot of the table. * @@ -307,9 +306,8 @@ template INLINE void WeakKeyHashMap:: set_data(size_t n, Value &&data) { nassertv(has_element(n)); - _table[n]._data = move(data); + _table[n]._data = std::move(data); } -#endif // USE_MOVE_SEMANTICS /** * Removes the nth slot from the table. @@ -337,7 +335,7 @@ remove_element(size_t n) { clear_element(i); --_num_entries; } else { - size_t wants_index = get_hash(_table[i]._key); + size_t wants_index = get_hash(_table[i]._key.get_orig()); if (wants_index != i) { // This one was a hash conflict; try to put it where it belongs. We // can't just put it in n, since maybe it belongs somewhere after n. @@ -392,7 +390,7 @@ is_empty() const { */ template void WeakKeyHashMap:: -output(ostream &out) const { +output(std::ostream &out) const { out << "WeakKeyHashMap (" << _num_entries << " entries): ["; for (size_t i = 0; i < _table_size; ++i) { if (get_exists_array()[i] == 0) { @@ -416,7 +414,7 @@ output(ostream &out) const { */ template void WeakKeyHashMap:: -write(ostream &out) const { +write(std::ostream &out) const { output(out); out << "\n"; } @@ -590,7 +588,7 @@ expand_table() { // Double the table size. size_t old_table_size = old_map._table_size; _table_size = (old_table_size << 1); - nassertv(_table == NULL); + nassertv(_table == nullptr); // We allocate enough bytes for _table_size elements of TableEntry, plus // _table_size more bytes at the end (for the exists array). @@ -611,13 +609,9 @@ expand_table() { new_index = (new_index + 1) & (_table_size - 1); } -#ifdef USE_MOVE_SEMANTICS // Use C++11 rvalue references to invoke the move constructor, which may // be more efficient. - new(&_table[new_index]) TableEntry(move(old_map._table[i])); -#else - new(&_table[new_index]) TableEntry(old_map._table[i]); -#endif + new(&_table[new_index]) TableEntry(std::move(old_map._table[i])); exists_array[new_index] = true; ++_num_entries; } diff --git a/panda/src/putil/weakKeyHashMap.h b/panda/src/putil/weakKeyHashMap.h index 3769660fbc..8e51ae700f 100644 --- a/panda/src/putil/weakKeyHashMap.h +++ b/panda/src/putil/weakKeyHashMap.h @@ -50,16 +50,14 @@ public: INLINE const Value &get_data(size_t n) const; INLINE Value &modify_data(size_t n); INLINE void set_data(size_t n, const Value &data); -#ifdef USE_MOVE_SEMANTICS INLINE void set_data(size_t n, Value &&data); -#endif void remove_element(size_t n); INLINE size_t get_num_entries() const; INLINE bool is_empty() const; - void output(ostream &out) const; - void write(ostream &out) const; + void output(std::ostream &out) const; + void write(std::ostream &out) const; bool validate() const; private: @@ -82,11 +80,10 @@ private: INLINE TableEntry(const TableEntry ©) : _key(copy._key), _data(copy._data) {} -#ifdef USE_MOVE_SEMANTICS - INLINE TableEntry(TableEntry &&from) NOEXCEPT : - _key(move(from._key)), - _data(move(from._data)) {} -#endif + INLINE TableEntry(TableEntry &&from) noexcept : + _key(std::move(from._key)), + _data(std::move(from._data)) {} + WCPT(Key) _key; Value _data; }; @@ -99,7 +96,7 @@ private: }; template -inline ostream &operator << (ostream &out, const WeakKeyHashMap &shm) { +inline std::ostream &operator << (std::ostream &out, const WeakKeyHashMap &shm) { shm.output(out); return out; } diff --git a/panda/src/putil/writableParam.h b/panda/src/putil/writableParam.h index 7bd49ebd30..bc0f600696 100644 --- a/panda/src/putil/writableParam.h +++ b/panda/src/putil/writableParam.h @@ -39,7 +39,7 @@ public: private: // The assignment operator cannot be used for this class. - WritableParam &operator = (const WritableParam &other) DELETED_ASSIGN; + WritableParam &operator = (const WritableParam &other) = delete; public: virtual TypeHandle get_type() const { diff --git a/panda/src/recorder/mouseRecorder.cxx b/panda/src/recorder/mouseRecorder.cxx index a79c7dc49b..37a5a2a440 100644 --- a/panda/src/recorder/mouseRecorder.cxx +++ b/panda/src/recorder/mouseRecorder.cxx @@ -23,7 +23,7 @@ TypeHandle MouseRecorder::_type_handle; * */ MouseRecorder:: -MouseRecorder(const string &name) : +MouseRecorder(const std::string &name) : DataNode(name) { _pixel_xy_input = define_input("pixel_xy", EventStoreVec2::get_class_type()); @@ -88,7 +88,7 @@ play_frame(DatagramIterator &scan, BamReader *manager) { * */ void MouseRecorder:: -output(ostream &out) const { +output(std::ostream &out) const { DataNode::output(out); } @@ -96,7 +96,7 @@ output(ostream &out) const { * */ void MouseRecorder:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { DataNode::write(out, indent_level); } diff --git a/panda/src/recorder/mouseRecorder.h b/panda/src/recorder/mouseRecorder.h index f43150c2b8..a30c2d428a 100644 --- a/panda/src/recorder/mouseRecorder.h +++ b/panda/src/recorder/mouseRecorder.h @@ -33,7 +33,7 @@ class BamWriter; */ class EXPCL_PANDA_RECORDER MouseRecorder : public DataNode, public RecorderBase { PUBLISHED: - explicit MouseRecorder(const string &name); + explicit MouseRecorder(const std::string &name); virtual ~MouseRecorder(); public: @@ -41,8 +41,8 @@ public: virtual void play_frame(DatagramIterator &scan, BamReader *manager); public: - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; protected: // Inherited from DataNode @@ -77,9 +77,9 @@ public: virtual void write_datagram(BamWriter *manager, Datagram &dg); virtual void write_recorder(BamWriter *manager, Datagram &dg); - INLINE virtual int get_ref_count() const FINAL { return ReferenceCount::get_ref_count(); }; - INLINE virtual void ref() const FINAL { ReferenceCount::ref(); }; - INLINE virtual bool unref() const FINAL { return ReferenceCount::unref(); }; + INLINE virtual int get_ref_count() const final { return ReferenceCount::get_ref_count(); }; + INLINE virtual void ref() const final { ReferenceCount::ref(); }; + INLINE virtual bool unref() const final { return ReferenceCount::unref(); }; protected: static TypedWritable *make_from_bam(const FactoryParams ¶ms); diff --git a/panda/src/recorder/recorderController.I b/panda/src/recorder/recorderController.I index b6312c0d82..7960a78ea1 100644 --- a/panda/src/recorder/recorderController.I +++ b/panda/src/recorder/recorderController.I @@ -46,7 +46,7 @@ get_random_seed() const { */ INLINE bool RecorderController:: is_recording() const { - return (_writer != (BamWriter *)NULL); + return (_writer != nullptr); } /** @@ -54,7 +54,7 @@ is_recording() const { */ INLINE bool RecorderController:: is_playing() const { - return (_reader != (BamReader *)NULL); + return (_reader != nullptr); } /** @@ -115,7 +115,7 @@ get_frame_offset() const { * recorder will begin receiving data. */ INLINE void RecorderController:: -add_recorder(const string &name, RecorderBase *recorder) { +add_recorder(const std::string &name, RecorderBase *recorder) { _user_table->add_recorder(name, recorder); _user_table_modified = true; @@ -137,8 +137,8 @@ add_recorder(const string &name, RecorderBase *recorder) { * via add_recorder(); see get_recorder(). */ INLINE bool RecorderController:: -has_recorder(const string &name) const { - return (_user_table->get_recorder(name) != (RecorderBase *)NULL); +has_recorder(const std::string &name) const { + return (_user_table->get_recorder(name) != nullptr); } /** @@ -151,9 +151,9 @@ has_recorder(const string &name) const { * return false, but get_recorder() will return a non-NULL value. */ INLINE RecorderBase *RecorderController:: -get_recorder(const string &name) const { +get_recorder(const std::string &name) const { RecorderBase *recorder = _user_table->get_recorder(name); - if (is_playing() && recorder == (RecorderBase *)NULL) { + if (is_playing() && recorder == nullptr) { recorder = _active_table->get_recorder(name); } return recorder; @@ -170,7 +170,7 @@ get_recorder(const string &name) const { * the data from the session file). */ INLINE bool RecorderController:: -remove_recorder(const string &name) { +remove_recorder(const std::string &name) { // If we are playing or recording, immediately remove the state flag from // the recorder. (When we are playing, the state flag will get removed // automatically at the next call to play_frame(), but we might as well be @@ -178,7 +178,7 @@ remove_recorder(const string &name) { // it now.) if (is_recording() || is_playing()) { RecorderBase *recorder = _user_table->get_recorder(name); - if (recorder != (RecorderBase *)NULL) { + if (recorder != nullptr) { recorder->_flags &= ~(RecorderBase::F_recording | RecorderBase::F_playing); } } @@ -217,7 +217,7 @@ get_frame_tie() const { */ INLINE RecorderController::RecorderFactory *RecorderController:: get_factory() { - if (_factory == (RecorderFactory *)NULL) { + if (_factory == nullptr) { create_factory(); } return _factory; diff --git a/panda/src/recorder/recorderController.cxx b/panda/src/recorder/recorderController.cxx index 364619d5ae..805ea5778a 100644 --- a/panda/src/recorder/recorderController.cxx +++ b/panda/src/recorder/recorderController.cxx @@ -20,7 +20,7 @@ #include "clockObject.h" TypeHandle RecorderController::_type_handle; -RecorderController::RecorderFactory *RecorderController::_factory = NULL; +RecorderController::RecorderFactory *RecorderController::_factory = nullptr; /** * @@ -29,13 +29,13 @@ RecorderController:: RecorderController() { _clock_offset = 0.0; _frame_offset = 0; - _writer = (BamWriter *)NULL; - _reader = (BamReader *)NULL; + _writer = nullptr; + _reader = nullptr; _frame_tie = true; _user_table = new RecorderTable; _user_table_modified = false; - _file_table = NULL; - _active_table = NULL; + _file_table = nullptr; + _active_table = nullptr; _eof = false; } @@ -113,7 +113,7 @@ begin_playback(const Filename &filename) { return false; } - string head; + std::string head; if (!_din.read_header(head, _bam_header.size()) || head != _bam_header) { recorder_cat.error() << "Unable to read " << _filename << "\n"; return false; @@ -132,7 +132,7 @@ begin_playback(const Filename &filename) { // Start out by reading the RecorderHeader. TypedWritable *object = _reader->read_object(); - if (object == (TypedWritable *)NULL || + if (object == nullptr || !object->is_of_type(RecorderHeader::get_class_type())) { recorder_cat.error() << _filename << " does not contain a recorded session.\n"; @@ -151,7 +151,7 @@ begin_playback(const Filename &filename) { // Now read the first frame. _next_frame = read_frame(); - if (_next_frame == (RecorderFrame *)NULL) { + if (_next_frame == nullptr) { recorder_cat.error() << _filename << " does not contain any frames.\n"; close(); @@ -169,16 +169,16 @@ begin_playback(const Filename &filename) { */ void RecorderController:: close() { - if (_writer != (BamWriter *)NULL) { + if (_writer != nullptr) { delete _writer; - _writer = NULL; + _writer = nullptr; // Tell all of our recorders that they're no longer recording. _user_table->clear_flags(RecorderBase::F_recording); } - if (_reader != (BamReader *)NULL) { + if (_reader != nullptr) { delete _reader; - _reader = NULL; + _reader = nullptr; // Tell all of our recorders that they're no longer playing. _active_table->clear_flags(RecorderBase::F_playing); @@ -186,14 +186,14 @@ close() { _dout.close(); _din.close(); - if (_file_table != (RecorderTable *)NULL) { + if (_file_table != nullptr) { delete _file_table; - _file_table = (RecorderTable *)NULL; + _file_table = nullptr; } - if (_active_table != (RecorderTable *)NULL) { + if (_active_table != nullptr) { delete _active_table; - _active_table = (RecorderTable *)NULL; + _active_table = nullptr; } } @@ -231,7 +231,7 @@ play_frame() { double now = global_clock->get_frame_time() - _clock_offset; int frame = global_clock->get_frame_count() - _frame_offset; - while (_next_frame != (RecorderFrame *)NULL) { + while (_next_frame != nullptr) { if (_frame_tie) { if (frame < _next_frame->_frame) { // We haven't reached the next frame yet. @@ -302,9 +302,9 @@ RecorderFrame *RecorderController:: read_frame() { TypedWritable *object = _reader->read_object(); - if (object == (TypedWritable *)NULL || + if (object == nullptr || !object->is_of_type(RecorderFrame::get_class_type())) { - return NULL; + return nullptr; } if (!_reader->resolve()) { diff --git a/panda/src/recorder/recorderController.h b/panda/src/recorder/recorderController.h index 064e882373..d3d8ccd1fd 100644 --- a/panda/src/recorder/recorderController.h +++ b/panda/src/recorder/recorderController.h @@ -52,10 +52,10 @@ PUBLISHED: INLINE double get_clock_offset() const; INLINE int get_frame_offset() const; - INLINE void add_recorder(const string &name, RecorderBase *recorder); - INLINE bool has_recorder(const string &name) const; - INLINE RecorderBase *get_recorder(const string &name) const; - INLINE bool remove_recorder(const string &name); + INLINE void add_recorder(const std::string &name, RecorderBase *recorder); + INLINE bool has_recorder(const std::string &name) const; + INLINE RecorderBase *get_recorder(const std::string &name) const; + INLINE bool remove_recorder(const std::string &name); INLINE void set_frame_tie(bool frame_tie); INLINE bool get_frame_tie() const; diff --git a/panda/src/recorder/recorderFrame.cxx b/panda/src/recorder/recorderFrame.cxx index d53e3d46dc..6b2ea3da10 100644 --- a/panda/src/recorder/recorderFrame.cxx +++ b/panda/src/recorder/recorderFrame.cxx @@ -118,7 +118,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { _timestamp = scan.get_float64(); _frame = scan.get_uint32(); _table_changed = scan.get_bool(); - _table = (RecorderTable *)NULL; + _table = nullptr; if (_table_changed) { manager->read_pointer(scan); } diff --git a/panda/src/recorder/recorderTable.I b/panda/src/recorder/recorderTable.I index 6bb2649d97..18e66bc3ee 100644 --- a/panda/src/recorder/recorderTable.I +++ b/panda/src/recorder/recorderTable.I @@ -45,8 +45,8 @@ operator = (const RecorderTable ©) { * Adds the named recorder to the set of recorders. */ INLINE void RecorderTable:: -add_recorder(const string &name, RecorderBase *recorder) { - nassertv(recorder != (RecorderBase *)NULL); +add_recorder(const std::string &name, RecorderBase *recorder) { + nassertv(recorder != nullptr); recorder->ref(); std::pair result = @@ -64,12 +64,12 @@ add_recorder(const string &name, RecorderBase *recorder) { * recorder. */ INLINE RecorderBase *RecorderTable:: -get_recorder(const string &name) const { +get_recorder(const std::string &name) const { Recorders::const_iterator ri = _recorders.find(name); if (ri != _recorders.end()) { return (*ri).second; } - return NULL; + return nullptr; } /** @@ -77,7 +77,7 @@ get_recorder(const string &name) const { * false if there was no such recorder. */ INLINE bool RecorderTable:: -remove_recorder(const string &name) { +remove_recorder(const std::string &name) { Recorders::iterator ri = _recorders.find(name); if (ri != _recorders.end()) { unref_delete(ri->second); diff --git a/panda/src/recorder/recorderTable.cxx b/panda/src/recorder/recorderTable.cxx index 6b60d82ada..4db629865f 100644 --- a/panda/src/recorder/recorderTable.cxx +++ b/panda/src/recorder/recorderTable.cxx @@ -18,6 +18,8 @@ #include "recorderController.h" #include "indent.h" +using std::string; + TypeHandle RecorderTable::_type_handle; /** @@ -140,7 +142,7 @@ clear_flags(short flags) { * */ void RecorderTable:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "RecorderTable:\n"; @@ -216,7 +218,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { RecorderBase *recorder = RecorderController::get_factory()->make_instance_more_general(type, fparams); - if (recorder == (RecorderBase *)NULL) { + if (recorder == nullptr) { recorder_cat.error() << "Unable to create Recorder of type " << type << "\n"; _error = true; diff --git a/panda/src/recorder/recorderTable.h b/panda/src/recorder/recorderTable.h index 7a5046c651..8c6d1bf412 100644 --- a/panda/src/recorder/recorderTable.h +++ b/panda/src/recorder/recorderTable.h @@ -38,21 +38,21 @@ public: void merge_from(const RecorderTable &other); - INLINE void add_recorder(const string &name, RecorderBase *recorder); - INLINE RecorderBase *get_recorder(const string &name) const; - INLINE bool remove_recorder(const string &name); + INLINE void add_recorder(const std::string &name, RecorderBase *recorder); + INLINE RecorderBase *get_recorder(const std::string &name) const; + INLINE bool remove_recorder(const std::string &name); void record_frame(BamWriter *manager, Datagram &dg); void play_frame(DatagramIterator &scan, BamReader *manager); void set_flags(short flags); void clear_flags(short flags); - void write(ostream &out, int indent_level) const; + void write(std::ostream &out, int indent_level) const; // RecorderBase itself doesn't inherit from ReferenceCount, so we can't put // a PT() around it. Instead, we manage the reference count using calls to // ref() and unref(). - typedef pmap Recorders; + typedef pmap Recorders; Recorders _recorders; bool _error; diff --git a/panda/src/recorder/socketStreamRecorder.I b/panda/src/recorder/socketStreamRecorder.I index 90c0585860..520e6f5d40 100644 --- a/panda/src/recorder/socketStreamRecorder.I +++ b/panda/src/recorder/socketStreamRecorder.I @@ -16,7 +16,7 @@ */ INLINE SocketStreamRecorder:: SocketStreamRecorder() : - _stream(NULL), + _stream(nullptr), _owns_stream(false), _closed(true) { @@ -48,7 +48,7 @@ INLINE SocketStreamRecorder:: */ bool SocketStreamRecorder:: send_datagram(const Datagram &dg) { - if (_stream != (SocketStream *)NULL) { + if (_stream != nullptr) { return _stream->send_datagram(dg); } return true; @@ -59,7 +59,7 @@ send_datagram(const Datagram &dg) { */ INLINE bool SocketStreamRecorder:: is_closed() { - if (_stream != (SocketStream *)NULL) { + if (_stream != nullptr) { return _stream->is_closed(); } return is_playing() && _closed; @@ -70,7 +70,7 @@ is_closed() { */ INLINE void SocketStreamRecorder:: close() { - if (_stream != (SocketStream *)NULL) { + if (_stream != nullptr) { _stream->close(); } _closed = true; @@ -81,7 +81,7 @@ close() { */ INLINE void SocketStreamRecorder:: set_collect_tcp(bool collect_tcp) { - if (_stream != (SocketStream *)NULL) { + if (_stream != nullptr) { _stream->set_collect_tcp(collect_tcp); } } @@ -91,7 +91,7 @@ set_collect_tcp(bool collect_tcp) { */ INLINE bool SocketStreamRecorder:: get_collect_tcp() const { - if (_stream != (SocketStream *)NULL) { + if (_stream != nullptr) { return _stream->get_collect_tcp(); } return false; @@ -102,7 +102,7 @@ get_collect_tcp() const { */ INLINE void SocketStreamRecorder:: set_collect_tcp_interval(double interval) { - if (_stream != (SocketStream *)NULL) { + if (_stream != nullptr) { _stream->set_collect_tcp_interval(interval); } } @@ -112,7 +112,7 @@ set_collect_tcp_interval(double interval) { */ INLINE double SocketStreamRecorder:: get_collect_tcp_interval() const { - if (_stream != (SocketStream *)NULL) { + if (_stream != nullptr) { return _stream->get_collect_tcp_interval(); } return 0.0; @@ -123,7 +123,7 @@ get_collect_tcp_interval() const { */ INLINE bool SocketStreamRecorder:: consider_flush() { - if (_stream != (SocketStream *)NULL) { + if (_stream != nullptr) { return _stream->consider_flush(); } return true; @@ -134,7 +134,7 @@ consider_flush() { */ INLINE bool SocketStreamRecorder:: flush() { - if (_stream != (SocketStream *)NULL) { + if (_stream != nullptr) { return _stream->flush(); } return true; diff --git a/panda/src/recorder/socketStreamRecorder.cxx b/panda/src/recorder/socketStreamRecorder.cxx index 6209239044..5ee6168d44 100644 --- a/panda/src/recorder/socketStreamRecorder.cxx +++ b/panda/src/recorder/socketStreamRecorder.cxx @@ -42,7 +42,7 @@ receive_datagram(Datagram &dg) { } else { // If we're not in playback mode, forward the request to the connection. bool got_data = false; - if (_stream != (SocketStream *)NULL) { + if (_stream != nullptr) { got_data = _stream->receive_datagram(dg); } @@ -85,7 +85,7 @@ play_frame(DatagramIterator &scan, BamReader *manager) { size_t size = scan.get_uint16(); vector_uchar packet(size); scan.extract_bytes(&packet[0], size); - _data.push_back(Datagram(move(packet))); + _data.push_back(Datagram(std::move(packet))); } } diff --git a/panda/src/recorder/socketStreamRecorder.h b/panda/src/recorder/socketStreamRecorder.h index 3b43f5ffcd..231ac19f28 100644 --- a/panda/src/recorder/socketStreamRecorder.h +++ b/panda/src/recorder/socketStreamRecorder.h @@ -74,9 +74,9 @@ public: static void register_with_read_factory(); virtual void write_recorder(BamWriter *manager, Datagram &dg); - INLINE virtual int get_ref_count() const FINAL { return ReferenceCount::get_ref_count(); }; - INLINE virtual void ref() const FINAL { ReferenceCount::ref(); }; - INLINE virtual bool unref() const FINAL { return ReferenceCount::unref(); }; + INLINE virtual int get_ref_count() const final { return ReferenceCount::get_ref_count(); }; + INLINE virtual void ref() const final { ReferenceCount::ref(); }; + INLINE virtual bool unref() const final { return ReferenceCount::unref(); }; protected: static RecorderBase *make_recorder(const FactoryParams ¶ms); diff --git a/panda/src/rocket/rocketFileInterface.cxx b/panda/src/rocket/rocketFileInterface.cxx index 99ddcd5256..5a54e31c8f 100644 --- a/panda/src/rocket/rocketFileInterface.cxx +++ b/panda/src/rocket/rocketFileInterface.cxx @@ -20,7 +20,7 @@ */ RocketFileInterface:: RocketFileInterface(VirtualFileSystem *vfs) : _vfs(vfs) { - if (_vfs == NULL) { + if (_vfs == nullptr) { _vfs = VirtualFileSystem::get_global_ptr(); } } @@ -35,25 +35,25 @@ Open(const Rocket::Core::String& path) { Filename fn = Filename::from_os_specific(path.CString()); PT(VirtualFile) file = _vfs->get_file(fn); - if (file == NULL) { + if (file == nullptr) { // failed? Try model-path as a Panda-friendly fallback. if (!_vfs->resolve_filename(fn, get_model_path())) { rocket_cat.error() << "Could not resolve " << fn << " along the model-path (currently: " << get_model_path() << ")\n"; - return (Rocket::Core::FileHandle) NULL; + return (Rocket::Core::FileHandle) nullptr; } file = _vfs->get_file(fn); - if (file == NULL) { + if (file == nullptr) { rocket_cat.error() << "Failed to get " << fn << ", found on model-path\n"; - return (Rocket::Core::FileHandle) NULL; + return (Rocket::Core::FileHandle) nullptr; } } - istream *str = file->open_read_file(true); - if (str == NULL) { + std::istream *str = file->open_read_file(true); + if (str == nullptr) { rocket_cat.error() << "Failed to open " << fn << " for reading\n"; - return (Rocket::Core::FileHandle) NULL; + return (Rocket::Core::FileHandle) nullptr; } VirtualFileHandle *handle = new VirtualFileHandle; @@ -70,7 +70,7 @@ Open(const Rocket::Core::String& path) { void RocketFileInterface:: Close(Rocket::Core::FileHandle file) { VirtualFileHandle *handle = (VirtualFileHandle*) file; - if (handle == NULL) { + if (handle == nullptr) { return; } @@ -84,7 +84,7 @@ Close(Rocket::Core::FileHandle file) { size_t RocketFileInterface:: Read(void* buffer, size_t size, Rocket::Core::FileHandle file) { VirtualFileHandle *handle = (VirtualFileHandle*) file; - if (handle == NULL) { + if (handle == nullptr) { return 0; } @@ -98,19 +98,19 @@ Read(void* buffer, size_t size, Rocket::Core::FileHandle file) { bool RocketFileInterface:: Seek(Rocket::Core::FileHandle file, long offset, int origin) { VirtualFileHandle *handle = (VirtualFileHandle*) file; - if (handle == NULL) { + if (handle == nullptr) { return false; } switch(origin) { case SEEK_SET: - handle->_stream->seekg(offset, ios::beg); + handle->_stream->seekg(offset, std::ios::beg); break; case SEEK_CUR: - handle->_stream->seekg(offset, ios::cur); + handle->_stream->seekg(offset, std::ios::cur); break; case SEEK_END: - handle->_stream->seekg(offset, ios::end); + handle->_stream->seekg(offset, std::ios::end); }; return !handle->_stream->fail(); @@ -122,7 +122,7 @@ Seek(Rocket::Core::FileHandle file, long offset, int origin) { size_t RocketFileInterface:: Tell(Rocket::Core::FileHandle file) { VirtualFileHandle *handle = (VirtualFileHandle*) file; - if (handle == NULL) { + if (handle == nullptr) { return 0; } @@ -135,7 +135,7 @@ Tell(Rocket::Core::FileHandle file) { size_t RocketFileInterface:: Length(Rocket::Core::FileHandle file) { VirtualFileHandle *handle = (VirtualFileHandle*) file; - if (handle == NULL) { + if (handle == nullptr) { return 0; } diff --git a/panda/src/rocket/rocketFileInterface.h b/panda/src/rocket/rocketFileInterface.h index 8a340136b5..5e1f4d0f8c 100644 --- a/panda/src/rocket/rocketFileInterface.h +++ b/panda/src/rocket/rocketFileInterface.h @@ -26,7 +26,7 @@ class VirtualFileSystem; */ class RocketFileInterface : public Rocket::Core::FileInterface { public: - RocketFileInterface(VirtualFileSystem *vfs = NULL); + RocketFileInterface(VirtualFileSystem *vfs = nullptr); virtual ~RocketFileInterface() {}; Rocket::Core::FileHandle Open(const Rocket::Core::String& path); @@ -41,7 +41,7 @@ public: protected: struct VirtualFileHandle { PT(VirtualFile) _file; - istream *_stream; + std::istream *_stream; }; VirtualFileSystem* _vfs; diff --git a/panda/src/rocket/rocketInputHandler.cxx b/panda/src/rocket/rocketInputHandler.cxx index fcfa6dc2cf..6b07e3a02b 100644 --- a/panda/src/rocket/rocketInputHandler.cxx +++ b/panda/src/rocket/rocketInputHandler.cxx @@ -31,7 +31,7 @@ TypeHandle RocketInputHandler::_type_handle; * */ RocketInputHandler:: -RocketInputHandler(const string &name) : +RocketInputHandler(const std::string &name) : DataNode(name), _mouse_xy(-1), _mouse_xy_changed(false), diff --git a/panda/src/rocket/rocketInputHandler.h b/panda/src/rocket/rocketInputHandler.h index e1637ba681..d0c20ff8e3 100644 --- a/panda/src/rocket/rocketInputHandler.h +++ b/panda/src/rocket/rocketInputHandler.h @@ -30,7 +30,7 @@ namespace Rocket { */ class EXPCL_ROCKET RocketInputHandler : public DataNode { PUBLISHED: - RocketInputHandler(const string &name = string()); + RocketInputHandler(const std::string &name = std::string()); virtual ~RocketInputHandler(); static int get_rocket_key(const ButtonHandle handle); diff --git a/panda/src/rocket/rocketRegion.I b/panda/src/rocket/rocketRegion.I index f9fe378ff7..1c9aab10da 100644 --- a/panda/src/rocket/rocketRegion.I +++ b/panda/src/rocket/rocketRegion.I @@ -18,7 +18,7 @@ * window. */ INLINE RocketRegion *RocketRegion:: -make(const string &context_name, GraphicsOutput *window) { +make(const std::string &context_name, GraphicsOutput *window) { return make(context_name, window, LVecBase4(0.0f, 1.0f, 0.0f, 1.0f)); } @@ -28,7 +28,7 @@ make(const string &context_name, GraphicsOutput *window) { * render to. */ INLINE RocketRegion *RocketRegion:: -make(const string &context_name, GraphicsOutput *window, +make(const std::string &context_name, GraphicsOutput *window, const LVecBase4 &dimensions) { return new RocketRegion(window, dimensions, context_name); diff --git a/panda/src/rocket/rocketRegion.cxx b/panda/src/rocket/rocketRegion.cxx index ebfcd630c2..17fdc8f55f 100644 --- a/panda/src/rocket/rocketRegion.cxx +++ b/panda/src/rocket/rocketRegion.cxx @@ -31,12 +31,12 @@ TypeHandle RocketRegion::_type_handle; */ RocketRegion:: RocketRegion(GraphicsOutput *window, const LVecBase4 &dr_dimensions, - const string &context_name) : + const std::string &context_name) : DisplayRegion(window, dr_dimensions) { // A hack I don't like. libRocket's decorator system has a bug somewhere, // and this seems to be a workaround. - if (Rocket::Core::GetRenderInterface() == NULL) { + if (Rocket::Core::GetRenderInterface() == nullptr) { Rocket::Core::SetRenderInterface(&_interface); } @@ -50,7 +50,7 @@ RocketRegion(GraphicsOutput *window, const LVecBase4 &dr_dimensions, _context = Rocket::Core::CreateContext(context_name.c_str(), dimensions, &_interface); - nassertv(_context != NULL); + nassertv(_context != nullptr); _lens = new OrthographicLens; _lens->set_film_size(dimensions.x, -dimensions.y); @@ -67,10 +67,10 @@ RocketRegion(GraphicsOutput *window, const LVecBase4 &dr_dimensions, RocketRegion:: ~RocketRegion() { if (Rocket::Core::GetRenderInterface() == &_interface) { - Rocket::Core::SetRenderInterface(NULL); + Rocket::Core::SetRenderInterface(nullptr); } - if (_context != NULL) { + if (_context != nullptr) { if (_context->GetReferenceCount() > 1) { _context->RemoveReference(); return; @@ -121,7 +121,7 @@ do_cull(CullHandler *cull_handler, SceneSetup *scene_setup, _lens->set_film_offset(dimensions.x * 0.5, dimensions.y * 0.5); } - if (_input_handler != NULL) { + if (_input_handler != nullptr) { _input_handler->update_context(_context, pl, pb); } else { _context->Update(); @@ -130,7 +130,7 @@ do_cull(CullHandler *cull_handler, SceneSetup *scene_setup, CullTraverser *trav = get_cull_traverser(); trav->set_cull_handler(cull_handler); trav->set_scene(scene_setup, gsg, get_incomplete_render()); - trav->set_view_frustum(NULL); + trav->set_view_frustum(nullptr); _interface.render(_context, trav); diff --git a/panda/src/rocket/rocketRegion.h b/panda/src/rocket/rocketRegion.h index d978ac6305..0f0eeb5603 100644 --- a/panda/src/rocket/rocketRegion.h +++ b/panda/src/rocket/rocketRegion.h @@ -28,7 +28,7 @@ class OrthographicLens; class EXPCL_ROCKET RocketRegion : public DisplayRegion { protected: RocketRegion(GraphicsOutput *window, const LVecBase4 &dimensions, - const string &context_name); + const std::string &context_name); virtual void do_cull(CullHandler *cull_handler, SceneSetup *scene_setup, GraphicsStateGuardian *gsg, Thread *current_thread); @@ -36,9 +36,9 @@ protected: PUBLISHED: virtual ~RocketRegion(); - INLINE static RocketRegion* make(const string &context_name, + INLINE static RocketRegion* make(const std::string &context_name, GraphicsOutput *window); - INLINE static RocketRegion* make(const string &context_name, + INLINE static RocketRegion* make(const std::string &context_name, GraphicsOutput *window, const LVecBase4 &dimensions); #ifndef CPPPARSER diff --git a/panda/src/rocket/rocketRegion_ext.cxx b/panda/src/rocket/rocketRegion_ext.cxx index cb79f467a1..84acb44aa0 100644 --- a/panda/src/rocket/rocketRegion_ext.cxx +++ b/panda/src/rocket/rocketRegion_ext.cxx @@ -44,7 +44,7 @@ get_context() const { (void)e; // Return NULL, which will trigger the exception in Python } - return NULL; + return nullptr; } #endif diff --git a/panda/src/rocket/rocketRenderInterface.cxx b/panda/src/rocket/rocketRenderInterface.cxx index 76e69c6e27..c5ec2eb9a7 100644 --- a/panda/src/rocket/rocketRenderInterface.cxx +++ b/panda/src/rocket/rocketRenderInterface.cxx @@ -35,7 +35,7 @@ */ void RocketRenderInterface:: render(Rocket::Core::Context* context, CullTraverser *trav) { - nassertv(context != NULL); + nassertv(context != nullptr); MutexHolder holder(_lock); _trav = trav; @@ -54,9 +54,9 @@ render(Rocket::Core::Context* context, CullTraverser *trav) { context->Render(); - _trav = NULL; - _net_transform = NULL; - _net_state = NULL; + _trav = nullptr; + _net_transform = nullptr; + _net_state = nullptr; } /** @@ -145,7 +145,7 @@ RenderGeometry(Rocket::Core::Vertex* vertices, Texture *texture = (Texture *)thandle; LVecBase2 tex_scale(1, 1); - if (texture != (Texture *)NULL) { + if (texture != nullptr) { tex_scale = texture->get_tex_scale(); } @@ -153,7 +153,7 @@ RenderGeometry(Rocket::Core::Vertex* vertices, GeomEnums::UH_stream, tex_scale); CPT(RenderState) state; - if (texture != (Texture *)NULL) { + if (texture != nullptr) { state = RenderState::make(TextureAttrib::make(texture)); } else { state = RenderState::make_empty(); @@ -176,7 +176,7 @@ CompileGeometry(Rocket::Core::Vertex* vertices, CompiledGeometry *c = new CompiledGeometry; LVecBase2 tex_scale(1, 1); - if (texture != (Texture *)NULL) { + if (texture != nullptr) { rocket_cat.debug() << "Compiling geom " << c->_geom << " with texture '" << texture->get_name() << "'\n"; @@ -240,7 +240,7 @@ LoadTexture(Rocket::Core::TextureHandle& texture_handle, Filename fn = Filename::from_os_specific(source.CString()); PT(Texture) tex = TexturePool::load_texture(fn, 0, false, options); - if (tex == NULL) { + if (tex == nullptr) { texture_handle = 0; texture_dimensions.x = 0; texture_dimensions.y = 0; @@ -322,7 +322,7 @@ GenerateTexture(Rocket::Core::TextureHandle& texture_handle, void RocketRenderInterface:: ReleaseTexture(Rocket::Core::TextureHandle texture_handle) { Texture *tex = (Texture *)texture_handle; - if (tex != (Texture *)NULL) { + if (tex != nullptr) { unref_delete(tex); } } diff --git a/panda/src/speedtree/config_speedtree.cxx b/panda/src/speedtree/config_speedtree.cxx index b386bcb59a..f820239665 100644 --- a/panda/src/speedtree/config_speedtree.cxx +++ b/panda/src/speedtree/config_speedtree.cxx @@ -300,7 +300,7 @@ public: } void Free(void *block) { - if (block != NULL) { + if (block != nullptr) { PANDA_FREE_ARRAY(block); } } diff --git a/panda/src/speedtree/loaderFileTypeSrt.cxx b/panda/src/speedtree/loaderFileTypeSrt.cxx index 6589e28c10..a0fe4e3022 100644 --- a/panda/src/speedtree/loaderFileTypeSrt.cxx +++ b/panda/src/speedtree/loaderFileTypeSrt.cxx @@ -27,7 +27,7 @@ LoaderFileTypeSrt() { /** * */ -string LoaderFileTypeSrt:: +std::string LoaderFileTypeSrt:: get_name() const { return "SpeedTree compiled tree"; } @@ -35,7 +35,7 @@ get_name() const { /** * */ -string LoaderFileTypeSrt:: +std::string LoaderFileTypeSrt:: get_extension() const { return "srt"; } @@ -57,16 +57,16 @@ load_file(const Filename &path, const LoaderOptions &, BamCacheRecord *record) const { if (!path.is_regular_file()) { // Quietly fail if the file doesn't exist. The Loader expects this. - return NULL; + return nullptr; } PT(STTree) tree = new STTree(path); if (!tree->is_valid()) { - return NULL; + return nullptr; } PT(SpeedTreeNode) st = new SpeedTreeNode(path.get_basename()); st->add_instance(tree, STTransform()); - return st.p(); + return st; } diff --git a/panda/src/speedtree/loaderFileTypeSrt.h b/panda/src/speedtree/loaderFileTypeSrt.h index 6d26eeff6b..ba40a0e5a1 100644 --- a/panda/src/speedtree/loaderFileTypeSrt.h +++ b/panda/src/speedtree/loaderFileTypeSrt.h @@ -27,8 +27,8 @@ class EXPCL_PANDASPEEDTREE LoaderFileTypeSrt : public LoaderFileType { public: LoaderFileTypeSrt(); - virtual string get_name() const; - virtual string get_extension() const; + virtual std::string get_name() const; + virtual std::string get_extension() const; virtual bool supports_compressed() const; virtual PT(PandaNode) load_file(const Filename &path, const LoaderOptions &options, diff --git a/panda/src/speedtree/loaderFileTypeStf.cxx b/panda/src/speedtree/loaderFileTypeStf.cxx index 8e1e15a2e8..9d83bddd3d 100644 --- a/panda/src/speedtree/loaderFileTypeStf.cxx +++ b/panda/src/speedtree/loaderFileTypeStf.cxx @@ -26,7 +26,7 @@ LoaderFileTypeStf() { /** * */ -string LoaderFileTypeStf:: +std::string LoaderFileTypeStf:: get_name() const { return "SpeedTree compiled tree"; } @@ -34,7 +34,7 @@ get_name() const { /** * */ -string LoaderFileTypeStf:: +std::string LoaderFileTypeStf:: get_extension() const { return "stf"; } @@ -56,11 +56,11 @@ load_file(const Filename &path, const LoaderOptions &options, BamCacheRecord *record) const { if (!path.is_regular_file()) { // Quietly fail if the file doesn't exist. The Loader expects this. - return NULL; + return nullptr; } PT(SpeedTreeNode) st = new SpeedTreeNode(path.get_basename()); st->add_from_stf(path, options); - return st.p(); + return st; } diff --git a/panda/src/speedtree/loaderFileTypeStf.h b/panda/src/speedtree/loaderFileTypeStf.h index 8ea8eae575..04bc8207e1 100644 --- a/panda/src/speedtree/loaderFileTypeStf.h +++ b/panda/src/speedtree/loaderFileTypeStf.h @@ -26,8 +26,8 @@ class EXPCL_PANDASPEEDTREE LoaderFileTypeStf : public LoaderFileType { public: LoaderFileTypeStf(); - virtual string get_name() const; - virtual string get_extension() const; + virtual std::string get_name() const; + virtual std::string get_extension() const; virtual bool supports_compressed() const; virtual PT(PandaNode) load_file(const Filename &path, const LoaderOptions &options, diff --git a/panda/src/speedtree/speedTreeNode.I b/panda/src/speedtree/speedTreeNode.I index 400a26e12b..0b1b0cd23d 100644 --- a/panda/src/speedtree/speedTreeNode.I +++ b/panda/src/speedtree/speedTreeNode.I @@ -36,7 +36,7 @@ get_num_trees() const { */ INLINE const STTree *SpeedTreeNode:: get_tree(int n) const { - nassertr(n >= 0 && n < (int)_trees.size(), NULL); + nassertr(n >= 0 && n < (int)_trees.size(), nullptr); InstanceList *instance_list = _trees[n]; return instance_list->get_tree(); } @@ -47,7 +47,9 @@ get_tree(int n) const { */ INLINE const SpeedTreeNode::InstanceList &SpeedTreeNode:: get_instance_list(int n) const { - nassertr(n >= 0 && n < (int)_trees.size(), *(InstanceList *)NULL); + // TODO: This should be nassertr instead of assert, but there's nothing we + // can really return when the assert fails. + assert(n >= 0 && n < (int)_trees.size()); InstanceList *instance_list = _trees[n]; return *instance_list; } @@ -57,7 +59,7 @@ get_instance_list(int n) const { */ INLINE STTree *SpeedTreeNode:: modify_tree(int n) { - nassertr(n >= 0 && n < (int)_trees.size(), NULL); + nassertr(n >= 0 && n < (int)_trees.size(), nullptr); InstanceList *instance_list = _trees[n]; _needs_repopulate = true; return (STTree *)instance_list->get_tree(); @@ -68,7 +70,7 @@ modify_tree(int n) { */ INLINE void SpeedTreeNode:: clear_terrain() { - set_terrain(NULL); + set_terrain(nullptr); } /** @@ -77,7 +79,7 @@ clear_terrain() { */ INLINE bool SpeedTreeNode:: has_terrain() const { - return _terrain != (STTerrain *)NULL; + return _terrain != nullptr; } /** diff --git a/panda/src/speedtree/speedTreeNode.cxx b/panda/src/speedtree/speedTreeNode.cxx index c455e848f5..48cda1204b 100644 --- a/panda/src/speedtree/speedTreeNode.cxx +++ b/panda/src/speedtree/speedTreeNode.cxx @@ -42,6 +42,10 @@ #include "dxGraphicsStateGuardian9.h" #endif +using std::istream; +using std::ostream; +using std::string; + double SpeedTreeNode::_global_time_delta = 0.0; bool SpeedTreeNode::_authorized; bool SpeedTreeNode::_done_first_init; @@ -145,15 +149,17 @@ count_total_instances() const { */ SpeedTreeNode::InstanceList &SpeedTreeNode:: add_tree(const STTree *tree) { - nassertr(is_valid(), *(InstanceList *)NULL); - nassertr(tree->is_valid(), *(InstanceList *)NULL); + // TODO: These should be nassertr instead of assert, but there's nothing we + // can really return when the assert fails. + assert(is_valid()); + assert(tree->is_valid()); InstanceList ilist(tree); Trees::iterator ti = _trees.find(&ilist); if (ti == _trees.end()) { // This is the first time that this particular tree has been added. InstanceList *instance_list = new InstanceList(tree); - pair result = _trees.insert(instance_list); + std::pair result = _trees.insert(instance_list); ti = result.first; bool inserted = result.second; nassertr(inserted, *(*ti)); @@ -245,7 +251,7 @@ get_instance_list(const STTree *tree) const { Trees::const_iterator ti = _trees.find(&ilist); if (ti == _trees.end()) { // The tree was not already present. - static InstanceList empty_list((STTree *)NULL); + static InstanceList empty_list(nullptr); return empty_list; } @@ -406,7 +412,7 @@ add_from_stf(const Filename &stf_filename, const LoaderOptions &options) { } PT(VirtualFile) file = vfs->get_file(fullpath); - if (file == (VirtualFile *)NULL) { + if (file == nullptr) { // No such file. speedtree_cat.error() << "Could not find " << stf_filename << "\n"; @@ -439,7 +445,7 @@ add_from_stf(const Filename &stf_filename, const LoaderOptions &options) { bool SpeedTreeNode:: add_from_stf(istream &in, const Filename &pathname, const LoaderOptions &options, Loader *loader) { - if (loader == NULL) { + if (loader == nullptr) { loader = Loader::get_global_ptr(); } string os_filename; @@ -468,7 +474,7 @@ add_from_stf(istream &in, const Filename &pathname, // search the model-path if necessary). PT(PandaNode) srt_root = loader->load_sync(srt_filename); - if (srt_root != NULL) { + if (srt_root != nullptr) { NodePath srt(srt_root); NodePath srt_np = srt.find("**/+SpeedTreeNode"); if (!srt_np.is_empty()) { @@ -497,7 +503,7 @@ add_from_stf(istream &in, const Filename &pathname, in >> height_min >> height_max >> slope_min >> slope_max; } - if (tree != NULL) { + if (tree != nullptr) { add_instance(tree, STTransform(pos, rad_2_deg(rotate), scale)); } } @@ -505,7 +511,7 @@ add_from_stf(istream &in, const Filename &pathname, } // Consume any whitespace at the end of the file. - in >> ws; + in >> std::ws; if (!in.eof()) { // If we didn't read all the way to end-of-file, there was an error. @@ -550,10 +556,10 @@ setup_terrain(const Filename &terrain_file) { */ void SpeedTreeNode:: set_terrain(STTerrain *terrain) { - _terrain = NULL; + _terrain = nullptr; _needs_repopulate = true; - if (terrain == (STTerrain *)NULL) { + if (terrain == nullptr) { return; } @@ -606,7 +612,7 @@ snap_to_terrain() { InstanceList *instance_list = (*ti); int num_instances = instance_list->get_num_instances(); - if (_terrain != (STTerrain *)NULL) { + if (_terrain != nullptr) { for (int i = 0; i < num_instances; ++i) { STTransform trans = instance_list->get_instance(i); LPoint3 pos = trans.get_pos(); @@ -815,7 +821,7 @@ combine_with(PandaNode *other) { // But, not if they both have a terrain set. if (has_terrain() && gother->has_terrain()) { - return NULL; + return nullptr; } else if (gother->has_terrain()) { set_terrain(gother->get_terrain()); @@ -882,7 +888,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { PStatTimer timer(_cull_speedtree_pcollector); GraphicsStateGuardian *gsg = DCAST(GraphicsStateGuardian, trav->get_gsg()); - nassertr(gsg != (GraphicsStateGuardian *)NULL, true); + nassertr(gsg != nullptr, true); if (!validate_api(gsg)) { return false; } @@ -916,7 +922,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { // to disable textures. bool show_textures = true; const TextureAttrib *ta = DCAST(TextureAttrib, state->get_attrib(TextureAttrib::get_class_slot())); - if (ta != (TextureAttrib *)NULL) { + if (ta != nullptr) { show_textures = !ta->has_all_off(); } _forest_render.EnableTexturing(show_textures); @@ -927,19 +933,19 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { // direction and color to SpeedTree. We also accumulate the ambient light // colors. LColor ambient_color(0.0f, 0.0f, 0.0f, 0.0f); - DirectionalLight *dlight = NULL; + DirectionalLight *dlight = nullptr; NodePath dlight_np; LColor diffuse_color; int diffuse_priority = 0; const LightAttrib *la = DCAST(LightAttrib, state->get_attrib(LightAttrib::get_class_slot())); - if (la != (LightAttrib *)NULL) { + if (la != nullptr) { for (int i = 0; i < la->get_num_on_lights(); ++i) { NodePath light = la->get_on_light(i); if (!light.is_empty() && light.node()->is_of_type(DirectionalLight::get_class_type())) { // A directional light. DirectionalLight *light_obj = DCAST(DirectionalLight, light.node()); - if (dlight == NULL || light_obj->get_priority() > dlight->get_priority()) { + if (dlight == nullptr || light_obj->get_priority() > dlight->get_priority()) { // Here's the most important directional light. dlight = light_obj; dlight_np = light; @@ -952,7 +958,7 @@ cull_callback(CullTraverser *trav, CullTraverserData &data) { } } - if (dlight != (DirectionalLight *)NULL) { + if (dlight != nullptr) { CPT(TransformState) transform = dlight_np.get_transform(trav->get_scene()->get_scene_root().get_parent()); LVector3 dir = dlight->get_direction() * transform->get_mat(); dir.normalize(); @@ -1019,7 +1025,7 @@ add_for_draw(CullTraverser *trav, CullTraverserData &data) { // node, so that we can make the appropriate calls into SpeedTree to // render the forest during the actual draw. CullableObject *object = - new CullableObject(NULL, data._state, + new CullableObject(nullptr, data._state, TransformState::make_identity()); object->set_draw_callback(new DrawCallback(this)); trav->get_cull_handler()->record_object(object, trav); @@ -1117,7 +1123,7 @@ write(ostream &out, int indent_level) const { void SpeedTreeNode:: write_error(ostream &out) { const char *error = SpeedTree::CCore::GetError(); - if (error != (const char *)NULL) { + if (error != nullptr) { out << error; } out << "\n"; @@ -1243,10 +1249,10 @@ repopulate() { SpeedTree::CMap::const_iterator si; si = _population_stats.m_mMaxNumInstancesPerCellPerBase.find(tree->get_tree()); if (si != _population_stats.m_mMaxNumInstancesPerCellPerBase.end()) { - max_instances = max(max_instances, (int)si->second); + max_instances = std::max(max_instances, (int)si->second); } - max_instances_by_cell = max(max_instances_by_cell, max_instances); + max_instances_by_cell = std::max(max_instances_by_cell, max_instances); } _visible_trees.Reserve(_forest_render.GetBaseTrees(), @@ -1279,7 +1285,7 @@ update_terrain_cells() { int num_cells = (int)cells.size(); for (int ci = 0; ci < num_cells; ++ci) { SpeedTree::CTerrainCell *cell = cells[ci]; - nassertv(cell != NULL && cell->GetVbo() != NULL); + nassertv(cell != nullptr && cell->GetVbo() != nullptr); int cell_yi = cell->Row(); int cell_xi = cell->Col(); // cerr << "populating cell " << cell_xi << " " << cell_yi << "\n"; @@ -1306,7 +1312,7 @@ update_terrain_cells() { bool SpeedTreeNode:: validate_api(GraphicsStateGuardian *gsg) { GraphicsPipe *pipe = gsg->get_pipe(); - nassertr(pipe != (GraphicsPipe *)NULL, true); + nassertr(pipe != nullptr, true); #if defined(SPEEDTREE_OPENGL) static const string compiled_api = "OpenGL"; @@ -1385,7 +1391,7 @@ draw_callback(CallbackData *data) { write_error(speedtree_cat.warning()); // Clear the terrain so we don't keep spamming error messages. - _terrain = NULL; + _terrain = nullptr; } } @@ -1545,7 +1551,7 @@ setup_for_render(GraphicsStateGuardian *gsg) { SpeedTree::CMap::const_iterator si; si = _population_stats.m_mMaxNumInstancesPerCellPerBase.find(tree->get_tree()); if (si != _population_stats.m_mMaxNumInstancesPerCellPerBase.end()) { - max_instances = max(max_instances, (int)si->second); + max_instances = std::max(max_instances, (int)si->second); } // Get the speedtree-textures-dir to pass for initialization. @@ -1718,9 +1724,9 @@ fillin(DatagramIterator &scan, BamReader *manager) { int num_trees = scan.get_uint32(); _trees.reserve(num_trees); for (int i = 0; i < num_trees; i++) { - InstanceList *instance_list = new InstanceList(NULL); + InstanceList *instance_list = new InstanceList(nullptr); instance_list->fillin(scan, manager); - if (instance_list->get_tree() == (STTree *)NULL) { + if (instance_list->get_tree() == nullptr) { // The tree wasn't successfully loaded. Don't keep it. delete instance_list; } else { @@ -1797,7 +1803,7 @@ fillin(DatagramIterator &scan, BamReader *manager) { Loader *loader = Loader::get_global_ptr(); PT(PandaNode) srt_root = loader->load_sync(srt_filename); - if (srt_root != NULL) { + if (srt_root != nullptr) { NodePath srt(srt_root); NodePath srt_np = srt.find("**/+SpeedTreeNode"); if (!srt_np.is_empty()) { diff --git a/panda/src/speedtree/speedTreeNode.h b/panda/src/speedtree/speedTreeNode.h index 567cb00af9..b45a3df6ee 100644 --- a/panda/src/speedtree/speedTreeNode.h +++ b/panda/src/speedtree/speedTreeNode.h @@ -71,8 +71,8 @@ PUBLISHED: INLINE int add_instance(const STTransform &transform); INLINE void remove_instance(int n); - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; public: void write_datagram(BamWriter *manager, Datagram &dg); @@ -85,7 +85,7 @@ PUBLISHED: }; PUBLISHED: - explicit SpeedTreeNode(const string &name); + explicit SpeedTreeNode(const std::string &name); virtual ~SpeedTreeNode(); INLINE bool is_valid() const; @@ -121,9 +121,9 @@ PUBLISHED: bool add_from_stf(const Filename &stf_filename, const LoaderOptions &options = LoaderOptions()); - bool add_from_stf(istream &in, const Filename &pathname, + bool add_from_stf(std::istream &in, const Filename &pathname, const LoaderOptions &options = LoaderOptions(), - Loader *loader = NULL); + Loader *loader = nullptr); bool setup_terrain(const Filename &terrain_file); void set_terrain(STTerrain *terrain); @@ -145,7 +145,7 @@ PUBLISHED: MAKE_PROPERTY(global_time_delta, get_global_time_delta, set_global_time_delta); - static bool authorize(const string &license = ""); + static bool authorize(const std::string &license = ""); public: SpeedTreeNode(const SpeedTreeNode ©); @@ -167,10 +167,10 @@ public: int pipeline_stage, Thread *current_thread) const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level) const; - static void write_error(ostream &out); + static void write_error(std::ostream &out); protected: void set_transparent_texture_mode(SpeedTree::ETextureAlphaRenderMode eMode) const; @@ -219,7 +219,7 @@ private: }; private: - string _os_shaders_dir; + std::string _os_shaders_dir; // A list of instances per each unique tree. typedef ov_set > Trees; @@ -298,7 +298,7 @@ private: friend class SpeedTreeNode::DrawCallback; }; -INLINE ostream &operator << (ostream &out, const SpeedTreeNode::InstanceList &instances) { +INLINE std::ostream &operator << (std::ostream &out, const SpeedTreeNode::InstanceList &instances) { instances.output(out); return out; } diff --git a/panda/src/speedtree/stBasicTerrain.cxx b/panda/src/speedtree/stBasicTerrain.cxx index 5ee746dcbf..1c32cfe02f 100644 --- a/panda/src/speedtree/stBasicTerrain.cxx +++ b/panda/src/speedtree/stBasicTerrain.cxx @@ -16,6 +16,10 @@ #include "pnmImage.h" #include "indent.h" +using std::istream; +using std::ostream; +using std::string; + TypeHandle STBasicTerrain::_type_handle; // VERTEX_ATTRIB_END is defined as a macro that must be evaluated within the @@ -113,7 +117,7 @@ setup_terrain(const Filename &terrain_filename) { } istream *in = vfs->open_read_file(fullpath, true); - if (in == NULL) { + if (in == nullptr) { speedtree_cat.warning() << "Couldn't open " << terrain_filename << "\n"; return false; @@ -191,7 +195,7 @@ setup_terrain(istream &in, const Filename &pathname) { } // Consume any whitespace at the end of the file. - in >> ws; + in >> std::ws; if (!in.eof()) { // If we didn't read all the way to end-of-file, there was an error. @@ -345,8 +349,8 @@ read_height_map() { v *= scalar; _height_data._data[pi] = v; ++pi; - _min_height = min(_min_height, v); - _max_height = max(_max_height, v); + _min_height = std::min(_min_height, v); + _max_height = std::max(_max_height, v); } } diff --git a/panda/src/speedtree/stBasicTerrain.h b/panda/src/speedtree/stBasicTerrain.h index a61f15a785..048c507ac7 100644 --- a/panda/src/speedtree/stBasicTerrain.h +++ b/panda/src/speedtree/stBasicTerrain.h @@ -33,7 +33,7 @@ PUBLISHED: void clear(); bool setup_terrain(const Filename &terrain_filename); - bool setup_terrain(istream &in, const Filename &pathname); + bool setup_terrain(std::istream &in, const Filename &pathname); INLINE void set_height_map(const Filename &height_map); INLINE const Filename &get_height_map() const; @@ -49,8 +49,8 @@ PUBLISHED: PN_stdfloat start_x, PN_stdfloat start_y, PN_stdfloat size_xy, int num_xy) const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; protected: bool read_height_map(); @@ -59,7 +59,7 @@ protected: INLINE PN_stdfloat interpolate(PN_stdfloat a, PN_stdfloat b, PN_stdfloat t); private: - static void read_quoted_filename(Filename &result, istream &in, + static void read_quoted_filename(Filename &result, std::istream &in, const Filename &dirname); protected: diff --git a/panda/src/speedtree/stTerrain.cxx b/panda/src/speedtree/stTerrain.cxx index 2f5f226856..9215a5dd26 100644 --- a/panda/src/speedtree/stTerrain.cxx +++ b/panda/src/speedtree/stTerrain.cxx @@ -62,7 +62,7 @@ clear() { _splat_map = ""; _splat_layers.clear(); - set_vertex_format(NULL); + set_vertex_format(nullptr); } /** @@ -149,7 +149,7 @@ fill_vertices(GeomVertexData *data, * */ void STTerrain:: -output(ostream &out) const { +output(std::ostream &out) const { Namable::output(out); } @@ -157,7 +157,7 @@ output(ostream &out) const { * */ void STTerrain:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << *this << "\n"; } @@ -169,7 +169,7 @@ write(ostream &out, int indent_level) const { const SpeedTree::SVertexAttribDesc *STTerrain:: get_st_vertex_format() const { // return SpeedTree::std_vertex_format; - nassertr(!_st_vertex_attribs.empty(), NULL); + nassertr(!_st_vertex_attribs.empty(), nullptr); return &_st_vertex_attribs[0]; } @@ -181,8 +181,8 @@ get_st_vertex_format() const { */ bool STTerrain:: set_vertex_format(const GeomVertexFormat *format) { - if (format == NULL) { - _vertex_format = NULL; + if (format == nullptr) { + _vertex_format = nullptr; _st_vertex_attribs.clear(); _is_valid = false; return true; diff --git a/panda/src/speedtree/stTerrain.h b/panda/src/speedtree/stTerrain.h index cc2bf94215..d9a2c3160a 100644 --- a/panda/src/speedtree/stTerrain.h +++ b/panda/src/speedtree/stTerrain.h @@ -68,8 +68,8 @@ PUBLISHED: PN_stdfloat start_x, PN_stdfloat start_y, PN_stdfloat size_xy, int num_xy) const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: const SpeedTree::SVertexAttribDesc *get_st_vertex_format() const; @@ -123,7 +123,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const STTerrain &terrain) { +INLINE std::ostream &operator << (std::ostream &out, const STTerrain &terrain) { terrain.output(out); return out; } diff --git a/panda/src/speedtree/stTransform.cxx b/panda/src/speedtree/stTransform.cxx index aab4be7e93..dfdb586a6c 100644 --- a/panda/src/speedtree/stTransform.cxx +++ b/panda/src/speedtree/stTransform.cxx @@ -44,7 +44,7 @@ STTransform(const TransformState *trans) { * */ void STTransform:: -output(ostream &out) const { +output(std::ostream &out) const { out << "STTransform(" << _pos << ", " << _rotate << ", " << _scale << ")"; } diff --git a/panda/src/speedtree/stTransform.h b/panda/src/speedtree/stTransform.h index 07d66a3eae..d3329b7be1 100644 --- a/panda/src/speedtree/stTransform.h +++ b/panda/src/speedtree/stTransform.h @@ -50,7 +50,7 @@ PUBLISHED: INLINE void operator *= (const STTransform &other); INLINE STTransform operator * (const STTransform &other) const; - void output(ostream &out) const; + void output(std::ostream &out) const; public: void write_datagram(BamWriter *manager, Datagram &dg); @@ -64,7 +64,7 @@ public: static STTransform _ident_mat; }; -INLINE ostream &operator << (ostream &out, const STTransform &transform) { +INLINE std::ostream &operator << (std::ostream &out, const STTransform &transform) { transform.output(out); return out; } diff --git a/panda/src/speedtree/stTree.cxx b/panda/src/speedtree/stTree.cxx index fb00fc1bea..a34b36e7a4 100644 --- a/panda/src/speedtree/stTree.cxx +++ b/panda/src/speedtree/stTree.cxx @@ -48,7 +48,7 @@ STTree(const Filename &fullpath) : } */ - string os_fullpath = _fullpath.to_os_specific(); + std::string os_fullpath = _fullpath.to_os_specific(); if (!_tree.LoadTree(os_fullpath.c_str())) { speedtree_cat.warning() << "Couldn't read: " << _fullpath << "\n"; @@ -61,20 +61,11 @@ STTree(const Filename &fullpath) : _is_valid = true; } - -/** - * An STTree copy constructor is not supported. - */ -STTree:: -STTree(const STTree ©) { - nassertv(false); -} - /** * */ void STTree:: -output(ostream &out) const { +output(std::ostream &out) const { if (!is_valid()) { out << "(invalid STTree)"; } else { diff --git a/panda/src/speedtree/stTree.h b/panda/src/speedtree/stTree.h index 55c4dacbb7..e150f70ceb 100644 --- a/panda/src/speedtree/stTree.h +++ b/panda/src/speedtree/stTree.h @@ -28,15 +28,14 @@ class SpeedTreeNode; class EXPCL_PANDASPEEDTREE STTree : public TypedReferenceCount, public Namable { PUBLISHED: STTree(const Filename &fullpath); -private: - STTree(const STTree ©); + STTree(const STTree ©) = delete; PUBLISHED: INLINE const Filename &get_fullpath() const; INLINE bool is_valid() const; - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; public: INLINE const SpeedTree::CTreeRender *get_tree() const; @@ -65,7 +64,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const STTree &tree) { +INLINE std::ostream &operator << (std::ostream &out, const STTree &tree) { tree.output(out); return out; } diff --git a/panda/src/testbed/pgrid.cxx b/panda/src/testbed/pgrid.cxx index e028e6c03c..6858165bdf 100644 --- a/panda/src/testbed/pgrid.cxx +++ b/panda/src/testbed/pgrid.cxx @@ -22,6 +22,8 @@ #define RANDFRAC (rand()/(PN_stdfloat)(RAND_MAX)) +using std::string; + class GriddedFilename { public: Filename _filename; @@ -177,7 +179,7 @@ void get_command_line_filenames(int argc, char *argv[], pvector &static_filenames, GriddedFilenames &gridded_filenames) { - for (int i = 1; i < argc && argv[i] != (char *)NULL; i++) { + for (int i = 1; i < argc && argv[i] != nullptr; i++) { const string &arg = argv[i]; size_t comma = arg.find(','); if (comma == string::npos) { @@ -226,7 +228,7 @@ load_gridded_models(WindowFramework *window, for (fi = filenames.begin(); fi != filenames.end(); ++fi) { GriddedFilename &gf = (*fi); PT(PandaNode) node = loader.load_sync(gf._filename, options); - if (node != (PandaNode *)NULL) { + if (node != nullptr) { gf._model = NodePath(node); grid_count += gf._count; } @@ -244,7 +246,7 @@ load_gridded_models(WindowFramework *window, } grid_pos_offset = -gridwidth*GRIDCELLSIZE/2.0; - wander_area_pos_offset = -max((PN_stdfloat)fabs(grid_pos_offset), MIN_WANDERAREA_DIMENSION/2.0f); + wander_area_pos_offset = -std::max((PN_stdfloat)fabs(grid_pos_offset), MIN_WANDERAREA_DIMENSION/2.0f); // Now walk through the list again, copying models into the scene graph as // we go. @@ -252,7 +254,7 @@ load_gridded_models(WindowFramework *window, PN_stdfloat xpos = grid_pos_offset; PN_stdfloat ypos = grid_pos_offset; - srand( (unsigned)time( NULL ) ); + srand( (unsigned)time( nullptr ) ); double now = ClockObject::get_global_clock()->get_frame_time(); int model_count = 0; @@ -273,7 +275,7 @@ load_gridded_models(WindowFramework *window, ++model_count; PT(PandaNode) node = loader.load_sync(gf._filename, options); NodePath model; - if (node == (PandaNode *)NULL) { + if (node == nullptr) { model = gf._model.copy_to(NodePath()); } else { model = NodePath(node); @@ -400,7 +402,7 @@ main(int argc, char **argv) { get_command_line_filenames(argc, argv, static_filenames, gridded_filenames); WindowFramework *window = framework.open_window(); - if (window != (WindowFramework *)NULL) { + if (window != nullptr) { // We've successfully opened a window. window->enable_keyboard(); diff --git a/panda/src/testbed/pview.cxx b/panda/src/testbed/pview.cxx index 6d68f099ab..73e71a358d 100644 --- a/panda/src/testbed/pview.cxx +++ b/panda/src/testbed/pview.cxx @@ -29,11 +29,8 @@ #include "asyncTask.h" #include "boundingSphere.h" -// By including checkPandaVersion.h, we guarantee that runtime attempts to run -// pview will fail if it inadvertently links with the wrong version of -// libdtool.so.dll. - -#include "checkPandaVersion.h" +using std::cerr; +using std::endl; PandaFramework framework; @@ -64,8 +61,8 @@ event_W(const Event *, void *) { // shift-W: open a new window on the same scene. // If we already have a window, use the same GSG. - GraphicsPipe *pipe = (GraphicsPipe *)NULL; - GraphicsStateGuardian *gsg = (GraphicsStateGuardian *)NULL; + GraphicsPipe *pipe = nullptr; + GraphicsStateGuardian *gsg = nullptr; if (framework.get_num_windows() > 0) { WindowFramework *old_window = framework.get_window(0); @@ -75,7 +72,7 @@ event_W(const Event *, void *) { } WindowFramework *window = framework.open_window(pipe, gsg); - if (window != (WindowFramework *)NULL) { + if (window != nullptr) { window->enable_keyboard(); window->setup_trackball(); framework.get_models().instance_to(window->get_render()); @@ -93,15 +90,15 @@ event_Enter(const Event *, void *) { // alt-enter: toggle between windowfullscreen in the same scene. // If we already have a window, use the same GSG. - GraphicsPipe *pipe = (GraphicsPipe *)NULL; - GraphicsStateGuardian *gsg = (GraphicsStateGuardian *)NULL; + GraphicsPipe *pipe = nullptr; + GraphicsStateGuardian *gsg = nullptr; WindowProperties props; for (int i = 0; i < framework.get_num_windows(); ++i) { WindowFramework *old_window = framework.get_window(i); GraphicsWindow *win = old_window->get_graphics_window(); - if (win != (GraphicsWindow *)NULL) { + if (win != nullptr) { pipe = win->get_pipe(); gsg = win->get_gsg(); props = win->get_properties(); @@ -115,7 +112,7 @@ event_Enter(const Event *, void *) { int flags = GraphicsPipe::BF_require_window; WindowFramework *window = framework.open_window(props, flags, pipe, gsg); - if (window != (WindowFramework *)NULL) { + if (window != nullptr) { window->enable_keyboard(); window->setup_trackball(); framework.get_models().instance_to(window->get_render()); @@ -131,7 +128,7 @@ event_2(const Event *event, void *) { DCAST_INTO_V(wf, param.get_ptr()); WindowFramework *split = wf->split_window(); - if (split != (WindowFramework *)NULL) { + if (split != nullptr) { split->enable_keyboard(); split->setup_trackball(); framework.get_models().instance_to(split->get_render()); @@ -243,14 +240,14 @@ report_version() { // class AdjustCameraClipPlanesTask : public AsyncTask { public: - AdjustCameraClipPlanesTask(const string &name, Camera *camera) : - AsyncTask(name), _camera(camera), _lens(camera->get_lens(0)), _sphere(NULL) + AdjustCameraClipPlanesTask(const std::string &name, Camera *camera) : + AsyncTask(name), _camera(camera), _lens(camera->get_lens(0)), _sphere(nullptr) { NodePath np = framework.get_models(); PT(BoundingVolume) volume = np.get_bounds(); // We expect at least a geometric bounding volume around the world. - nassertv(volume != (BoundingVolume *)NULL); + nassertv(volume != nullptr); nassertv(volume->is_of_type(GeometricBoundingVolume::get_class_type())); CPT(GeometricBoundingVolume) gbv = DCAST(GeometricBoundingVolume, volume); @@ -323,12 +320,12 @@ public: // Ensure the far plane is far enough back to see the entire object. PN_stdfloat ideal_far_plane = distance + radius * 1.5; - _lens->set_far(max(_lens->get_default_far(), ideal_far_plane)); + _lens->set_far(std::max(_lens->get_default_far(), ideal_far_plane)); // And that the near plane is far enough forward, but if inside // the sphere, keep above 0. - PN_stdfloat ideal_near_plane = max(min_distance * 10, distance - radius); - _lens->set_near(min(_lens->get_default_near(), ideal_near_plane)); + PN_stdfloat ideal_near_plane = std::max(min_distance * 10, distance - radius); + _lens->set_near(std::min(_lens->get_default_near(), ideal_near_plane)); return DS_cont; } @@ -354,7 +351,7 @@ main(int argc, char **argv) { Filename screenshotfn; bool delete_models = false; bool apply_lighting = false; - PointerTo pipe = NULL; + PointerTo pipe = nullptr; extern char *optarg; extern int optind; @@ -423,8 +420,8 @@ main(int argc, char **argv) { argc -= (optind - 1); argv += (optind - 1); - WindowFramework *window = framework.open_window(pipe, NULL); - if (window != (WindowFramework *)NULL) { + WindowFramework *window = framework.open_window(pipe, nullptr); + if (window != nullptr) { // We've successfully opened a window. NodePath loading_np; @@ -459,7 +456,7 @@ main(int argc, char **argv) { if (delete_models) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); - for (int i = 1; i < argc && argv[i] != (char *)NULL; i++) { + for (int i = 1; i < argc && argv[i] != nullptr; i++) { Filename model = Filename::from_os_specific(argv[i]); if (vfs->exists(model)) { nout << "Deleting " << model << "\n"; @@ -495,12 +492,12 @@ main(int argc, char **argv) { framework.get_task_mgr().add(task); framework.enable_default_keys(); - framework.define_key("shift-w", "open a new window", event_W, NULL); - framework.define_key("shift-f", "flatten hierarchy", event_F, NULL); - framework.define_key("alt-enter", "toggle between window/fullscreen", event_Enter, NULL); - framework.define_key("2", "split the window", event_2, NULL); + framework.define_key("shift-w", "open a new window", event_W, nullptr); + framework.define_key("shift-f", "flatten hierarchy", event_F, nullptr); + framework.define_key("alt-enter", "toggle between window/fullscreen", event_Enter, nullptr); + framework.define_key("2", "split the window", event_2, nullptr); if (pview_test_hack) { - framework.define_key("0", "run quick hacky test", event_0, NULL); + framework.define_key("0", "run quick hacky test", event_0, nullptr); } framework.main_loop(); framework.report_frame_rate(nout); diff --git a/panda/src/testbed/test_lod.cxx b/panda/src/testbed/test_lod.cxx index fa62edd785..00e4916ffa 100644 --- a/panda/src/testbed/test_lod.cxx +++ b/panda/src/testbed/test_lod.cxx @@ -54,7 +54,7 @@ main(int argc, char *argv[]) { framework.set_window_title("LOD Test"); WindowFramework *window = framework.open_window(); - if (window != (WindowFramework *)NULL) { + if (window != nullptr) { // We've successfully opened a window. window->enable_keyboard(); @@ -69,7 +69,7 @@ main(int argc, char *argv[]) { // Open another window too. WindowFramework *window2 = framework.open_window(); - if (window2 != (WindowFramework *)NULL) { + if (window2 != nullptr) { window2->enable_keyboard(); window2->setup_trackball(); framework.get_models().instance_to(window2->get_render()); diff --git a/panda/src/testbed/test_map.cxx b/panda/src/testbed/test_map.cxx index 2c85f2c11a..97c0176a9d 100644 --- a/panda/src/testbed/test_map.cxx +++ b/panda/src/testbed/test_map.cxx @@ -16,6 +16,10 @@ #include "memoryUsage.h" #include "clockObject.h" +using std::cerr; +using std::cout; +using std::string; + class Alpha { public: Alpha(const string &str) : _str(str) { } @@ -36,7 +40,7 @@ public: string _str; }; -ostream &operator << (ostream &out, const Alpha &alpha) { +std::ostream &operator << (std::ostream &out, const Alpha &alpha) { return out << alpha._str; } @@ -113,7 +117,7 @@ test_performance() { static const int num_cycles = 10000; static const int num_reps = 3; - vector samples; + std::vector samples; samples.reserve(sample_size); for (int s = 0; s < sample_size; s++) { string key; diff --git a/panda/src/testbed/test_texmem.cxx b/panda/src/testbed/test_texmem.cxx index 76f6adfc57..fd26a11508 100644 --- a/panda/src/testbed/test_texmem.cxx +++ b/panda/src/testbed/test_texmem.cxx @@ -49,7 +49,7 @@ event_T(const Event *, void *data) { static const int tex_x_size = 256; static const int tex_y_size = 256; - cerr << "Loading " << num_quads_side * num_quads_side << " textures at " + std::cerr << "Loading " << num_quads_side * num_quads_side << " textures at " << tex_x_size << ", " << tex_y_size << "\n"; PNMImage white_center(tex_x_size / 4, tex_y_size / 4); @@ -92,7 +92,7 @@ event_T(const Event *, void *data) { card.set_texture(tex); } } - cerr << "Done.\n"; + std::cerr << "Done.\n"; } int @@ -102,7 +102,7 @@ main(int argc, char *argv[]) { framework.set_window_title("Panda Viewer"); WindowFramework *window = framework.open_window(); - if (window != (WindowFramework *)NULL) { + if (window != nullptr) { // We've successfully opened a window. window->enable_keyboard(); diff --git a/panda/src/text/config_text.cxx b/panda/src/text/config_text.cxx index 2fff80cd0c..77dd27beba 100644 --- a/panda/src/text/config_text.cxx +++ b/panda/src/text/config_text.cxx @@ -31,6 +31,8 @@ #error Buildsystem error: BUILDING_PANDA_TEXT not defined #endif +using std::wstring; + Configure(config_text); NotifyCategoryDef(text, ""); @@ -146,14 +148,14 @@ ConfigVariableInt text_embed_graphic_key wstring get_text_soft_hyphen_output() { - static wstring *text_soft_hyphen_output = NULL; + static wstring *text_soft_hyphen_output = nullptr; static ConfigVariableString cv("text-soft-hyphen-output", "-", PRC_DESC("This is the string that is output, encoded in the default " "encoding, to represent the hyphen character that is " "introduced when the line is broken at a soft-hyphen key.")); - if (text_soft_hyphen_output == NULL) { + if (text_soft_hyphen_output == nullptr) { TextEncoder encoder; text_soft_hyphen_output = new wstring(encoder.decode_text(cv)); } @@ -169,7 +171,7 @@ ConfigVariableDouble text_hyphen_ratio wstring get_text_never_break_before() { - static wstring *text_never_break_before = NULL; + static wstring *text_never_break_before = nullptr; static ConfigVariableString cv("text-never-break-before", ",.-:?!;", PRC_DESC("This string represents a list of individual characters " @@ -177,7 +179,7 @@ get_text_never_break_before() { "following a forced break. Typically these will be " "punctuation characters.")); - if (text_never_break_before == NULL) { + if (text_never_break_before == nullptr) { TextEncoder encoder; text_never_break_before = new wstring(encoder.decode_text(cv)); } diff --git a/panda/src/text/config_text.h b/panda/src/text/config_text.h index 895072fdf6..cf58c5c811 100644 --- a/panda/src/text/config_text.h +++ b/panda/src/text/config_text.h @@ -40,14 +40,14 @@ extern ConfigVariableBool text_small_caps; extern EXPCL_PANDA_TEXT ConfigVariableDouble text_small_caps_scale; extern ConfigVariableFilename text_default_font; extern EXPCL_PANDA_TEXT ConfigVariableDouble text_tab_width; -extern ConfigVariableInt text_push_properties_key; -extern ConfigVariableInt text_pop_properties_key; +extern EXPCL_PANDA_TEXT ConfigVariableInt text_push_properties_key; +extern EXPCL_PANDA_TEXT ConfigVariableInt text_pop_properties_key; extern ConfigVariableInt text_soft_hyphen_key; extern ConfigVariableInt text_soft_break_key; extern ConfigVariableInt text_embed_graphic_key; -extern wstring get_text_soft_hyphen_output(); +extern std::wstring get_text_soft_hyphen_output(); extern ConfigVariableDouble text_hyphen_ratio; -extern wstring get_text_never_break_before(); +extern std::wstring get_text_never_break_before(); extern ConfigVariableInt text_max_never_break; extern EXPCL_PANDA_TEXT ConfigVariableDouble text_default_underscore_height; diff --git a/panda/src/text/dynamicTextFont.I b/panda/src/text/dynamicTextFont.I index 16fd832efe..eafa2b50f8 100644 --- a/panda/src/text/dynamicTextFont.I +++ b/panda/src/text/dynamicTextFont.I @@ -15,7 +15,7 @@ * Disambiguates the get_name() method between that inherited from TextFont * and that inherited from FreetypeFont. */ -INLINE const string &DynamicTextFont:: +INLINE const std::string &DynamicTextFont:: get_name() const { return TextFont::get_name(); } @@ -441,7 +441,7 @@ get_tex_format() const { } -INLINE ostream & -operator << (ostream &out, const DynamicTextFont &dtf) { +INLINE std::ostream & +operator << (std::ostream &out, const DynamicTextFont &dtf) { return out << dtf.get_name(); } diff --git a/panda/src/text/dynamicTextFont.cxx b/panda/src/text/dynamicTextFont.cxx index f02328009e..4eb4afc96a 100644 --- a/panda/src/text/dynamicTextFont.cxx +++ b/panda/src/text/dynamicTextFont.cxx @@ -162,7 +162,7 @@ get_num_pages() const { */ DynamicTextPage *DynamicTextFont:: get_page(int n) const { - nassertr(n >= 0 && n < (int)_pages.size(), (DynamicTextPage *)NULL); + nassertr(n >= 0 && n < (int)_pages.size(), nullptr); return _pages[n]; } @@ -179,7 +179,7 @@ garbage_collect() { Cache::iterator ci; for (ci = _cache.begin(); ci != _cache.end(); ++ci) { const TextGlyph *glyph = (*ci).second; - if (glyph == (TextGlyph *)NULL || glyph->get_ref_count() > 1) { + if (glyph == nullptr || glyph->get_ref_count() > 1) { // Keep this one. new_cache.insert(new_cache.end(), (*ci)); } else { @@ -226,7 +226,7 @@ clear() { * */ void DynamicTextFont:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { static const int max_glyph_name = 1024; char glyph_name[max_glyph_name]; @@ -267,7 +267,7 @@ write(ostream &out, int indent_level) const { bool DynamicTextFont:: get_glyph(int character, CPT(TextGlyph) &glyph) { if (!_is_valid) { - glyph = (TextGlyph *)NULL; + glyph = nullptr; return false; } @@ -487,7 +487,7 @@ determine_tex_format() { CPT(TextGlyph) DynamicTextFont:: make_glyph(int character, FT_Face face, int glyph_index) { if (!load_glyph(face, glyph_index, false)) { - return (TextGlyph *)NULL; + return nullptr; } FT_GlyphSlot slot = face->glyph; @@ -499,7 +499,7 @@ make_glyph(int character, FT_Face face, int glyph_index) { // is the empty bitmap, we return NULL, and use Panda's invalid glyph in // its place. We do this to guarantee that every invalid glyph is visible // as *something*. - return NULL; + return nullptr; } PN_stdfloat advance = slot->advance.x / 64.0; @@ -673,7 +673,7 @@ make_glyph(int character, FT_Face face, int glyph_index) { } DynamicTextPage *page = glyph->get_page(); - if (page != NULL) { + if (page != nullptr) { int bitmap_top = (int)floor(tex_y_orig + outline * _scale_factor + 0.5f); int bitmap_left = (int)floor(tex_x_orig - outline * _scale_factor + 0.5f); @@ -726,7 +726,7 @@ copy_bitmap_to_texture(const FT_Bitmap &bitmap, DynamicTextGlyph *glyph) { for (int yi = 0; yi < (int)bitmap.rows; yi++) { unsigned char *texture_row = glyph->get_row(yi); - nassertv(texture_row != (unsigned char *)NULL); + nassertv(texture_row != nullptr); memcpy(texture_row, buffer_row, bitmap.width); buffer_row += bitmap.pitch; } @@ -737,7 +737,7 @@ copy_bitmap_to_texture(const FT_Bitmap &bitmap, DynamicTextGlyph *glyph) { unsigned char *buffer_row = bitmap.buffer; for (int yi = 0; yi < (int)bitmap.rows; yi++) { unsigned char *texture_row = glyph->get_row(yi); - nassertv(texture_row != (unsigned char *)NULL); + nassertv(texture_row != nullptr); int bit = 0x80; unsigned char *b = buffer_row; @@ -764,7 +764,7 @@ copy_bitmap_to_texture(const FT_Bitmap &bitmap, DynamicTextGlyph *glyph) { unsigned char *buffer_row = bitmap.buffer; for (int yi = 0; yi < (int)bitmap.rows; yi++) { unsigned char *texture_row = glyph->get_row(yi); - nassertv(texture_row != (unsigned char *)NULL); + nassertv(texture_row != nullptr); for (int xi = 0; xi < (int)bitmap.width; xi++) { texture_row[xi] = (int)(buffer_row[xi] * 255) / (bitmap.num_grays - 1); } @@ -788,7 +788,7 @@ copy_pnmimage_to_texture(const PNMImage &image, DynamicTextGlyph *glyph) { nassertv(glyph->_page->get_num_components() == 1); for (int yi = 0; yi < image.get_y_size(); yi++) { unsigned char *texture_row = glyph->get_row(yi); - nassertv(texture_row != (unsigned char *)NULL); + nassertv(texture_row != nullptr); for (int xi = 0; xi < image.get_x_size(); xi++) { texture_row[xi] = image.get_gray_val(xi, yi); } @@ -853,7 +853,7 @@ blend_pnmimage_to_texture(const PNMImage &image, DynamicTextGlyph *glyph, for (int yi = 0; yi < image.get_y_size(); yi++) { unsigned char *texture_row = glyph->get_row(yi); - nassertv(texture_row != (unsigned char *)NULL); + nassertv(texture_row != nullptr); for (int xi = 0; xi < image.get_x_size(); xi++) { unsigned char *tr = texture_row + xi; PN_stdfloat t = (PN_stdfloat)image.get_gray(xi, yi); @@ -866,7 +866,7 @@ blend_pnmimage_to_texture(const PNMImage &image, DynamicTextGlyph *glyph, for (int yi = 0; yi < image.get_y_size(); yi++) { unsigned char *texture_row = glyph->get_row(yi); - nassertv(texture_row != (unsigned char *)NULL); + nassertv(texture_row != nullptr); for (int xi = 0; xi < image.get_x_size(); xi++) { unsigned char *tr = texture_row + xi * 2; PN_stdfloat t = (PN_stdfloat)image.get_gray(xi, yi); @@ -880,7 +880,7 @@ blend_pnmimage_to_texture(const PNMImage &image, DynamicTextGlyph *glyph, for (int yi = 0; yi < image.get_y_size(); yi++) { unsigned char *texture_row = glyph->get_row(yi); - nassertv(texture_row != (unsigned char *)NULL); + nassertv(texture_row != nullptr); for (int xi = 0; xi < image.get_x_size(); xi++) { unsigned char *tr = texture_row + xi * 3; PN_stdfloat t = (PN_stdfloat)image.get_gray(xi, yi); @@ -895,7 +895,7 @@ blend_pnmimage_to_texture(const PNMImage &image, DynamicTextGlyph *glyph, for (int yi = 0; yi < image.get_y_size(); yi++) { unsigned char *texture_row = glyph->get_row(yi); - nassertv(texture_row != (unsigned char *)NULL); + nassertv(texture_row != nullptr); for (int xi = 0; xi < image.get_x_size(); xi++) { unsigned char *tr = texture_row + xi * 4; PN_stdfloat t = (PN_stdfloat)image.get_gray(xi, yi); @@ -931,7 +931,7 @@ slot_glyph(int character, int x_size, int y_size, PN_stdfloat advance) { do { DynamicTextPage *page = _pages[pi]; DynamicTextGlyph *glyph = page->slot_glyph(character, x_size, y_size, _texture_margin, advance); - if (glyph != (DynamicTextGlyph *)NULL) { + if (glyph != nullptr) { // Once we found a page to hold the glyph, that becomes our new // preferred page. _preferred_page = pi; @@ -943,7 +943,7 @@ slot_glyph(int character, int x_size, int y_size, PN_stdfloat advance) { text_cat.error() << "Glyph of size " << x_size << " by " << y_size << " pixels won't fit on an empty page.\n"; - return (DynamicTextGlyph *)NULL; + return nullptr; } pi = (pi + 1) % _pages.size(); @@ -972,7 +972,7 @@ slot_glyph(int character, int x_size, int y_size, PN_stdfloat advance) { void DynamicTextFont:: render_wireframe_contours(TextGlyph *glyph) { PT(GeomVertexData) vdata = new GeomVertexData - (string(), GeomVertexFormat::get_v3(), + (std::string(), GeomVertexFormat::get_v3(), Geom::UH_static); GeomVertexWriter vertex(vdata, InternalName::get_vertex()); @@ -1003,7 +1003,7 @@ render_wireframe_contours(TextGlyph *glyph) { void DynamicTextFont:: render_polygon_contours(TextGlyph *glyph, bool face, bool extrude) { PT(GeomVertexData) vdata = new GeomVertexData - (string(), GeomVertexFormat::get_v3n3(), + (std::string(), GeomVertexFormat::get_v3n3(), Geom::UH_static); GeomVertexWriter vertex(vdata, InternalName::get_vertex()); GeomVertexWriter normal(vdata, InternalName::get_normal()); diff --git a/panda/src/text/dynamicTextFont.h b/panda/src/text/dynamicTextFont.h index 775fa6a450..d2643cffb1 100644 --- a/panda/src/text/dynamicTextFont.h +++ b/panda/src/text/dynamicTextFont.h @@ -47,7 +47,7 @@ PUBLISHED: virtual PT(TextFont) make_copy() const; - INLINE const string &get_name() const; + INLINE const std::string &get_name() const; INLINE bool set_point_size(PN_stdfloat point_size); INLINE PN_stdfloat get_point_size() const; @@ -121,7 +121,7 @@ PUBLISHED: int garbage_collect(); void clear(); - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; public: virtual bool get_glyph(int character, CPT(TextGlyph) &glyph); @@ -198,7 +198,7 @@ private: friend class TextNode; }; -INLINE ostream &operator << (ostream &out, const DynamicTextFont &dtf); +INLINE std::ostream &operator << (std::ostream &out, const DynamicTextFont &dtf); #include "dynamicTextFont.I" diff --git a/panda/src/text/dynamicTextGlyph.I b/panda/src/text/dynamicTextGlyph.I index e6406e0d0d..3f2ebebfe2 100644 --- a/panda/src/text/dynamicTextGlyph.I +++ b/panda/src/text/dynamicTextGlyph.I @@ -32,32 +32,13 @@ DynamicTextGlyph(int character, DynamicTextPage *page, int x, int y, INLINE DynamicTextGlyph:: DynamicTextGlyph(int character, PN_stdfloat advance) : TextGlyph(character, advance), - _page((DynamicTextPage *)NULL), + _page(nullptr), _x(0), _y(0), _x_size(0), _y_size(0), _margin(0) { } -/** - * Copying DynamicTextGlyph objects is not allowed. - */ -INLINE DynamicTextGlyph:: -DynamicTextGlyph(const DynamicTextGlyph &) : - TextGlyph(0) -{ - nassertv(false); -} - -/** - * Copying DynamicTextGlyph objects is not allowed. - */ -INLINE void DynamicTextGlyph:: -operator = (const DynamicTextGlyph &) { - nassertv(false); -} - - /** * Returns the DynamicTextPage that this glyph is on. */ diff --git a/panda/src/text/dynamicTextGlyph.cxx b/panda/src/text/dynamicTextGlyph.cxx index 9727b353f7..7fc2458965 100644 --- a/panda/src/text/dynamicTextGlyph.cxx +++ b/panda/src/text/dynamicTextGlyph.cxx @@ -44,8 +44,8 @@ DynamicTextGlyph:: */ unsigned char *DynamicTextGlyph:: get_row(int y) { - nassertr(y >= 0 && y < _y_size - _margin * 2, (unsigned char *)NULL); - nassertr(_page != (DynamicTextPage *)NULL, (unsigned char *)NULL); + nassertr(y >= 0 && y < _y_size - _margin * 2, nullptr); + nassertr(_page != nullptr, nullptr); // First, offset y by the glyph's start. y += _y + _margin; @@ -66,7 +66,7 @@ get_row(int y) { */ void DynamicTextGlyph:: erase(DynamicTextFont *font) { - nassertv(_page != (DynamicTextPage *)NULL); + nassertv(_page != nullptr); nassertv(_page->has_ram_image()); // The glyph covers the pixels from (_x, _y) over the rectangle (_x_size, @@ -84,7 +84,7 @@ erase(DynamicTextFont *font) { */ bool DynamicTextGlyph:: is_whitespace() const { - return (_page == (DynamicTextPage *)NULL); + return (_page == nullptr); } #endif // HAVE_FREETYPE diff --git a/panda/src/text/dynamicTextGlyph.h b/panda/src/text/dynamicTextGlyph.h index a90308977c..73ec2835a8 100644 --- a/panda/src/text/dynamicTextGlyph.h +++ b/panda/src/text/dynamicTextGlyph.h @@ -34,9 +34,9 @@ public: int x, int y, int x_size, int y_size, int margin, PN_stdfloat advance); INLINE DynamicTextGlyph(int character, PN_stdfloat advance); -private: - INLINE DynamicTextGlyph(const DynamicTextGlyph ©); - INLINE void operator = (const DynamicTextGlyph ©); + DynamicTextGlyph(const DynamicTextGlyph ©) = delete; + + DynamicTextGlyph &operator = (const DynamicTextGlyph ©) = delete; PUBLISHED: virtual ~DynamicTextGlyph(); diff --git a/panda/src/text/dynamicTextPage.cxx b/panda/src/text/dynamicTextPage.cxx index fbe1b93486..7bfe582040 100644 --- a/panda/src/text/dynamicTextPage.cxx +++ b/panda/src/text/dynamicTextPage.cxx @@ -17,7 +17,6 @@ #ifdef HAVE_FREETYPE - TypeHandle DynamicTextPage::_type_handle; /** @@ -40,7 +39,7 @@ DynamicTextPage(DynamicTextFont *font, int page_number) : setup_2d_texture(_size[0], _size[1], T_unsigned_byte, font->get_tex_format()); // Assign a name to the Texture. - ostringstream strm; + std::ostringstream strm; strm << font->get_name() << "_" << page_number; set_name(strm.str()); @@ -72,7 +71,7 @@ slot_glyph(int character, int x_size, int y_size, int margin, int x, y; if (!find_hole(x, y, x_size, y_size)) { // No room for the glyph. - return (DynamicTextGlyph *)NULL; + return nullptr; } // The glyph can be fit at (x, y). Slot it. @@ -209,13 +208,13 @@ find_hole(int &x, int &y, int x_size, int y_size) const { // Consider the spot at x, y. DynamicTextGlyph *overlap = find_overlap(x, y, x_size, y_size); - if (overlap == (DynamicTextGlyph *)NULL) { + if (overlap == nullptr) { // Hooray! return true; } next_x = overlap->_x + overlap->_x_size; - next_y = min(next_y, overlap->_y + overlap->_y_size); + next_y = std::min(next_y, overlap->_y + overlap->_y_size); nassertr(next_x > x, false); x = next_x; } @@ -245,7 +244,7 @@ find_overlap(int x, int y, int x_size, int y_size) const { } } - return (DynamicTextGlyph *)NULL; + return nullptr; } diff --git a/panda/src/text/fontPool.I b/panda/src/text/fontPool.I index c24906bdcf..c6fd4544e3 100644 --- a/panda/src/text/fontPool.I +++ b/panda/src/text/fontPool.I @@ -15,7 +15,7 @@ * Returns true if the font has ever been loaded, false otherwise. */ INLINE bool FontPool:: -has_font(const string &filename) { +has_font(const std::string &filename) { return get_ptr()->ns_has_font(filename); } @@ -26,8 +26,8 @@ has_font(const string &filename) { * with the same font name will return a valid Font pointer. */ INLINE bool FontPool:: -verify_font(const string &filename) { - return load_font(filename) != (TextFont *)NULL; +verify_font(const std::string &filename) { + return load_font(filename) != nullptr; } /** @@ -37,7 +37,7 @@ verify_font(const string &filename) { * returns NULL. */ INLINE TextFont *FontPool:: -load_font(const string &filename) { +load_font(const std::string &filename) { return get_ptr()->ns_load_font(filename); } @@ -46,7 +46,7 @@ load_font(const string &filename) { * replace any previously-loaded font in the pool that had the same filename. */ INLINE void FontPool:: -add_font(const string &filename, TextFont *font) { +add_font(const std::string &filename, TextFont *font) { get_ptr()->ns_add_font(filename, font); } @@ -57,7 +57,7 @@ add_font(const string &filename, TextFont *font) { * and fonts will never be freed. */ INLINE void FontPool:: -release_font(const string &filename) { +release_font(const std::string &filename) { get_ptr()->ns_release_font(filename); } @@ -83,7 +83,7 @@ garbage_collect() { * Lists the contents of the font pool to the indicated output stream. */ INLINE void FontPool:: -list_contents(ostream &out) { +list_contents(std::ostream &out) { get_ptr()->ns_list_contents(out); } diff --git a/panda/src/text/fontPool.cxx b/panda/src/text/fontPool.cxx index ac7d476c63..3f01243771 100644 --- a/panda/src/text/fontPool.cxx +++ b/panda/src/text/fontPool.cxx @@ -21,13 +21,15 @@ #include "loader.h" #include "lightMutexHolder.h" -FontPool *FontPool::_global_ptr = (FontPool *)NULL; +using std::string; + +FontPool *FontPool::_global_ptr = nullptr; /** * Lists the contents of the font pool to the indicated output stream. */ void FontPool:: -write(ostream &out) { +write(std::ostream &out) { get_ptr()->ns_list_contents(out); } @@ -86,7 +88,7 @@ ns_load_font(const string &str) { if (extension.empty() || extension == "egg" || extension == "bam") { Loader *model_loader = Loader::get_global_ptr(); PT(PandaNode) node = model_loader->load_sync(filename); - if (node != (PandaNode *)NULL) { + if (node != nullptr) { // It is a model. Elevate all the priorities by 1, and make a font out // of it. @@ -104,16 +106,16 @@ ns_load_font(const string &str) { } #ifdef HAVE_FREETYPE - if (font == (TextFont *)NULL || !font->is_valid()) { + if (font == nullptr || !font->is_valid()) { // If we couldn't load the font as a model, try using FreeType to load it // as a font file. font = new DynamicTextFont(filename, face_index); } #endif - if (font == (TextFont *)NULL || !font->is_valid()) { + if (font == nullptr || !font->is_valid()) { // This font was not found or could not be read. - return NULL; + return nullptr; } @@ -211,7 +213,7 @@ ns_garbage_collect() { * The nonstatic implementation of list_contents(). */ void FontPool:: -ns_list_contents(ostream &out) const { +ns_list_contents(std::ostream &out) const { LightMutexHolder holder(_lock); out << _fonts.size() << " fonts:\n"; @@ -252,7 +254,7 @@ lookup_filename(const string &str, string &index_str, VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->resolve_filename(filename, get_model_path()); - ostringstream strm; + std::ostringstream strm; strm << filename << ":" << face_index; index_str = strm.str(); } @@ -263,7 +265,7 @@ lookup_filename(const string &str, string &index_str, */ FontPool *FontPool:: get_ptr() { - if (_global_ptr == (FontPool *)NULL) { + if (_global_ptr == nullptr) { _global_ptr = new FontPool; } return _global_ptr; diff --git a/panda/src/text/fontPool.h b/panda/src/text/fontPool.h index 363e2aade7..8852a83b0c 100644 --- a/panda/src/text/fontPool.h +++ b/panda/src/text/fontPool.h @@ -33,37 +33,37 @@ PUBLISHED: // parameters may not be entirely an actual filename: they may be a filename // followed by a face index. - INLINE static bool has_font(const string &filename); - INLINE static bool verify_font(const string &filename); - BLOCKING INLINE static TextFont *load_font(const string &filename); - INLINE static void add_font(const string &filename, TextFont *font); - INLINE static void release_font(const string &filename); + INLINE static bool has_font(const std::string &filename); + INLINE static bool verify_font(const std::string &filename); + BLOCKING INLINE static TextFont *load_font(const std::string &filename); + INLINE static void add_font(const std::string &filename, TextFont *font); + INLINE static void release_font(const std::string &filename); INLINE static void release_all_fonts(); INLINE static int garbage_collect(); - INLINE static void list_contents(ostream &out); - static void write(ostream &out); + INLINE static void list_contents(std::ostream &out); + static void write(std::ostream &out); private: INLINE FontPool(); - bool ns_has_font(const string &str); - TextFont *ns_load_font(const string &str); - void ns_add_font(const string &str, TextFont *font); - void ns_release_font(const string &str); + bool ns_has_font(const std::string &str); + TextFont *ns_load_font(const std::string &str); + void ns_add_font(const std::string &str, TextFont *font); + void ns_release_font(const std::string &str); void ns_release_all_fonts(); int ns_garbage_collect(); - void ns_list_contents(ostream &out) const; + void ns_list_contents(std::ostream &out) const; - static void lookup_filename(const string &str, string &index_str, + static void lookup_filename(const std::string &str, std::string &index_str, Filename &filename, int &face_index); static FontPool *get_ptr(); static FontPool *_global_ptr; LightMutex _lock; - typedef pmap Fonts; + typedef pmap Fonts; Fonts _fonts; }; diff --git a/panda/src/text/geomTextGlyph.cxx b/panda/src/text/geomTextGlyph.cxx index 7af3d0d5e0..ecd1a2173c 100644 --- a/panda/src/text/geomTextGlyph.cxx +++ b/panda/src/text/geomTextGlyph.cxx @@ -28,7 +28,7 @@ GeomTextGlyph(const TextGlyph *glyph, const GeomVertexData *data) : { // Initially, there is only one glyph in the Geom. There might be // additional Glyphs later when we flatten the graph and call Geom::unify(). - if (glyph != (const TextGlyph *)NULL) { + if (glyph != nullptr) { _glyphs.reserve(1); _glyphs.push_back(glyph); } @@ -61,7 +61,7 @@ GeomTextGlyph:: GeomTextGlyph(const Geom ©, const TextGlyph *glyph) : Geom(copy) { - if (glyph != (const TextGlyph *)NULL) { + if (glyph != nullptr) { _glyphs.reserve(1); _glyphs.push_back(glyph); } @@ -142,13 +142,13 @@ count_geom(const Geom *other) { * */ void GeomTextGlyph:: -output(ostream &out) const { +output(std::ostream &out) const { Geom::output(out); out << ", glyphs: ["; Glyphs::const_iterator gi; for (gi = _glyphs.begin(); gi != _glyphs.end(); ++gi) { const TextGlyph *glyph = (*gi); - nassertv(glyph != (const TextGlyph *)NULL); + nassertv(glyph != nullptr); out << " " << glyph->get_character(); } out << " ]"; @@ -158,14 +158,14 @@ output(ostream &out) const { * */ void GeomTextGlyph:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { Geom::write(out, indent_level); indent(out, indent_level) << "Glyphs: ["; Glyphs::const_iterator gi; for (gi = _glyphs.begin(); gi != _glyphs.end(); ++gi) { const TextGlyph *glyph = (*gi); - nassertv(glyph != (const TextGlyph *)NULL); + nassertv(glyph != nullptr); out << " " << glyph->get_character(); } out << " ]\n"; @@ -192,8 +192,8 @@ register_with_read_factory() { */ TypedWritable* GeomTextGlyph:: make_GeomTextGlyph(const FactoryParams ¶ms) { - GeomTextGlyph *me = new GeomTextGlyph((const TextGlyph *)NULL, - (GeomVertexData *)NULL); + GeomTextGlyph *me = new GeomTextGlyph(nullptr, + nullptr); DatagramIterator scan; BamReader *manager; diff --git a/panda/src/text/geomTextGlyph.h b/panda/src/text/geomTextGlyph.h index 38d5604ee7..7e697c1405 100644 --- a/panda/src/text/geomTextGlyph.h +++ b/panda/src/text/geomTextGlyph.h @@ -38,8 +38,8 @@ public: virtual bool copy_primitives_from(const Geom *other); void count_geom(const Geom *other); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; void add_glyph(const TextGlyph *glyph); diff --git a/panda/src/text/staticTextFont.cxx b/panda/src/text/staticTextFont.cxx index 88f4186ad7..c179120a14 100644 --- a/panda/src/text/staticTextFont.cxx +++ b/panda/src/text/staticTextFont.cxx @@ -37,7 +37,7 @@ TypeHandle StaticTextFont::_type_handle; */ StaticTextFont:: StaticTextFont(PandaNode *font_def, CoordinateSystem cs) { - nassertv(font_def != (PandaNode *)NULL); + nassertv(font_def != nullptr); _font = font_def; _cs = cs; _glyphs.clear(); @@ -114,7 +114,7 @@ make_copy() const { * */ void StaticTextFont:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "StaticTextFont " << get_name() << "; " << _glyphs.size() << " characters available in font:\n"; @@ -248,7 +248,7 @@ find_character_gsets(PandaNode *root, CPT(Geom) &ch, CPT(Geom) &dot, const Geom *geom = geode->get_geom(i); bool found_points = false; - for (int j = 0; j < geom->get_num_primitives() && !found_points; j++) { + for (size_t j = 0; j < geom->get_num_primitives() && !found_points; ++j) { const GeomPrimitive *primitive = geom->get_primitive(j); if (primitive->is_of_type(GeomPoints::get_class_type())) { dot = geom; @@ -280,7 +280,7 @@ find_character_gsets(PandaNode *root, CPT(Geom) &ch, CPT(Geom) &dot, void StaticTextFont:: find_characters(PandaNode *root, const RenderState *net_state) { CPT(RenderState) next_net_state = net_state->compose(root->get_state()); - string name = root->get_name(); + std::string name = root->get_name(); bool all_digits = !name.empty(); const char *p = name.c_str(); @@ -295,10 +295,10 @@ find_characters(PandaNode *root, const RenderState *net_state) { int character = atoi(name.c_str()); CPT(Geom) ch; CPT(Geom) dot; - const RenderState *state = NULL; + const RenderState *state = nullptr; find_character_gsets(root, ch, dot, state, next_net_state); PN_stdfloat width = 0.0; - if (dot != (Geom *)NULL) { + if (dot != nullptr) { // Get the first vertex from the "dot" geoset. This will be the origin // of the next character. GeomVertexReader reader(dot->get_vertex_data(), InternalName::get_vertex()); @@ -313,9 +313,9 @@ find_characters(PandaNode *root, const RenderState *net_state) { CPT(Geom) ch; CPT(Geom) dot; - const RenderState *state = NULL; + const RenderState *state = nullptr; find_character_gsets(root, ch, dot, state, next_net_state); - if (dot != (Geom *)NULL) { + if (dot != nullptr) { // Get the first vertex from the "dot" geoset. This will be the design // size indicator. GeomVertexReader reader(dot->get_vertex_data(), InternalName::get_vertex()); diff --git a/panda/src/text/staticTextFont.h b/panda/src/text/staticTextFont.h index 95f8430975..0c36bf4c5e 100644 --- a/panda/src/text/staticTextFont.h +++ b/panda/src/text/staticTextFont.h @@ -41,7 +41,7 @@ PUBLISHED: virtual PT(TextFont) make_copy() const; - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; public: virtual bool get_glyph(int character, CPT(TextGlyph) &glyph); @@ -55,7 +55,6 @@ private: typedef pmap Glyphs; Glyphs _glyphs; - PN_stdfloat _font_height; PT(PandaNode) _font; CoordinateSystem _cs; diff --git a/panda/src/text/textAssembler.I b/panda/src/text/textAssembler.I index 5132f78859..d72d3d99bf 100644 --- a/panda/src/text/textAssembler.I +++ b/panda/src/text/textAssembler.I @@ -296,7 +296,7 @@ get_ypos(int r, int) const { */ INLINE PN_stdfloat TextAssembler:: calc_width(const TextCharacter &tch) { - if (tch._graphic != (TextGraphic *)NULL) { + if (tch._graphic != nullptr) { return calc_width(tch._graphic, tch._cprops->_properties); } else { return calc_width(tch._character, tch._cprops->_properties); @@ -310,7 +310,7 @@ INLINE TextAssembler::TextCharacter:: TextCharacter(wchar_t character, TextAssembler::ComputedProperties *cprops) : _character(character), - _graphic(NULL), + _graphic(nullptr), _cprops(cprops) { } @@ -319,7 +319,7 @@ TextCharacter(wchar_t character, * */ INLINE TextAssembler::TextCharacter:: -TextCharacter(const TextGraphic *graphic, const wstring &graphic_wname, +TextCharacter(const TextGraphic *graphic, const std::wstring &graphic_wname, TextAssembler::ComputedProperties *cprops) : _character(0), _graphic(graphic), @@ -395,7 +395,7 @@ operator = (const TextAssembler::TextRow ©) { */ INLINE TextAssembler::ComputedProperties:: ComputedProperties(const TextProperties &orig_properties) : - _based_on(NULL), + _based_on(nullptr), _depth(0), _properties(orig_properties) { @@ -405,7 +405,7 @@ ComputedProperties(const TextProperties &orig_properties) : * */ INLINE TextAssembler::ComputedProperties:: -ComputedProperties(ComputedProperties *based_on, const wstring &wname, +ComputedProperties(ComputedProperties *based_on, const std::wstring &wname, TextEncoder *encoder) : _based_on(based_on), _depth(_based_on->_depth + 1), @@ -417,10 +417,10 @@ ComputedProperties(ComputedProperties *based_on, const wstring &wname, // Now we have to encode the wstring into a string, for lookup in the // TextPropertiesManager. - string name = encoder->encode_wtext(wname); + std::string name = encoder->encode_wtext(wname); const TextProperties *named_props = manager->get_properties_ptr(name); - if (named_props != (TextProperties *)NULL) { + if (named_props != nullptr) { _properties.add_properties(*named_props); } else { text_cat.warning() diff --git a/panda/src/text/textAssembler.cxx b/panda/src/text/textAssembler.cxx index 49c507dafd..bb3a789504 100644 --- a/panda/src/text/textAssembler.cxx +++ b/panda/src/text/textAssembler.cxx @@ -40,6 +40,11 @@ #include #endif +using std::max; +using std::min; +using std::move; +using std::wstring; + // This is the factor by which CT_small scales the character down. static const PN_stdfloat small_accent_scale = 0.6f; @@ -234,7 +239,7 @@ get_plain_wtext() const { TextString::const_iterator si; for (si = _text_string.begin(); si != _text_string.end(); ++si) { const TextCharacter &tch = (*si); - if (tch._graphic == (TextGraphic *)NULL) { + if (tch._graphic == nullptr) { wtext += tch._character; } else { wtext.push_back(0); @@ -268,7 +273,7 @@ get_wordwrapped_plain_wtext() const { TextString::const_iterator si; for (si = row._string.begin(); si != row._string.end(); ++si) { const TextCharacter &tch = (*si); - if (tch._graphic == (TextGraphic *)NULL) { + if (tch._graphic == nullptr) { wtext += tch._character; } else { wtext.push_back(0); @@ -295,7 +300,7 @@ get_wtext() const { for (si = _text_string.begin(); si != _text_string.end(); ++si) { const TextCharacter &tch = (*si); current_cprops->append_delta(wtext, tch._cprops); - if (tch._graphic == (TextGraphic *)NULL) { + if (tch._graphic == nullptr) { wtext += tch._character; } else { wtext.push_back(text_embed_graphic_key); @@ -341,7 +346,7 @@ get_wordwrapped_wtext() const { for (si = row._string.begin(); si != row._string.end(); ++si) { const TextCharacter &tch = (*si); current_cprops->append_delta(wtext, tch._cprops); - if (tch._graphic == (TextGraphic *)NULL) { + if (tch._graphic == nullptr) { wtext += tch._character; } else { wtext.push_back(text_embed_graphic_key); @@ -519,7 +524,7 @@ assemble_text() { PT(GeomNode) text_geom_node = new GeomNode("text_geom"); text_node->add_child(text_geom_node); - const TextProperties *properties = NULL; + const TextProperties *properties = nullptr; CPT(RenderState) text_state; CPT(RenderState) shadow_state; LVector2 shadow(0); @@ -622,7 +627,7 @@ calc_width(wchar_t character, const TextProperties &properties) { if (character == ' ') { // A space is a special case. TextFont *font = properties.get_font(); - nassertr(font != (TextFont *)NULL, 0.0f); + nassertr(font != nullptr, 0.0f); return font->get_space_advance() * properties.get_glyph_scale() * properties.get_text_scale(); } @@ -639,10 +644,10 @@ calc_width(wchar_t character, const TextProperties &properties) { PN_stdfloat advance = 0.0f; - if (first_glyph != (TextGlyph *)NULL) { + if (first_glyph != nullptr) { advance = first_glyph->get_advance() * advance_scale; } - if (second_glyph != (TextGlyph *)NULL) { + if (second_glyph != nullptr) { advance += second_glyph->get_advance(); } @@ -681,7 +686,7 @@ has_exact_character(wchar_t character, const TextProperties &properties) { } TextFont *font = properties.get_font(); - nassertr(font != (TextFont *)NULL, false); + nassertr(font != nullptr, false); CPT(TextGlyph) glyph; return font->get_glyph(character, glyph); @@ -740,7 +745,7 @@ is_whitespace(wchar_t character, const TextProperties &properties) { TextFont *font = properties.get_font(); - nassertr(font != (TextFont *)NULL, false); + nassertr(font != nullptr, false); CPT(TextGlyph) glyph; if (!font->get_glyph(character, glyph)) { @@ -827,14 +832,14 @@ scan_wtext(TextAssembler::TextString &output_string, // Now we have to encode the wstring into a string, for lookup in the // TextPropertiesManager. - string graphic_name = _encoder->encode_wtext(graphic_wname); + std::string graphic_name = _encoder->encode_wtext(graphic_wname); TextPropertiesManager *manager = TextPropertiesManager::get_global_ptr(); // Get the graphic image. const TextGraphic *named_graphic = manager->get_graphic_ptr(graphic_name); - if (named_graphic != (TextGraphic *)NULL) { + if (named_graphic != nullptr) { output_string.push_back(TextCharacter(named_graphic, graphic_wname, current_cprops)); } else { @@ -1107,7 +1112,7 @@ wordwrap_text() { PN_stdfloat TextAssembler:: calc_hyphen_width(const TextCharacter &tch) { TextFont *font = tch._cprops->_properties.get_font(); - nassertr(font != (TextFont *)NULL, 0.0f); + nassertr(font != nullptr, 0.0f); PN_stdfloat hyphen_width = 0.0f; wstring text_soft_hyphen_output = get_text_soft_hyphen_output(); @@ -1222,7 +1227,7 @@ generate_quads(GeomNode *geom_node, const QuadMap &quad_map) { *(idx_ptr++) = i + 3; i += 4; - glyphs.push_back(MOVE(quad._glyph)); + glyphs.push_back(move(quad._glyph)); } } else { // 16-bit index case. @@ -1278,13 +1283,13 @@ generate_quads(GeomNode *geom_node, const QuadMap &quad_map) { *(idx_ptr++) = i + 3; i += 4; - glyphs.push_back(MOVE(quad._glyph)); + glyphs.push_back(move(quad._glyph)); } } } // We can compute this value much faster than GeomPrimitive can. - tris->set_minmax(0, i - 1, NULL, NULL); + tris->set_minmax(0, i - 1, nullptr, nullptr); PT(GeomTextGlyph) geom = new GeomTextGlyph(vdata); geom->_glyphs.swap(glyphs); @@ -1412,9 +1417,9 @@ assemble_row(TextAssembler::TextRow &row, bool underscore = false; PN_stdfloat underscore_start = 0.0f; const TextProperties *underscore_properties = nullptr; - const ComputedProperties *prev_cprops = nullptr; #ifdef HAVE_HARFBUZZ + const ComputedProperties *prev_cprops = nullptr; hb_buffer_t *harfbuff = nullptr; #endif @@ -1439,7 +1444,7 @@ assemble_row(TextAssembler::TextRow &row, } TextFont *font = properties->get_font(); - nassertv(font != (TextFont *)NULL); + nassertv(font != nullptr); // We get the row's alignment property from the first character of the row if ((align == TextProperties::A_left) && @@ -1454,7 +1459,7 @@ assemble_row(TextAssembler::TextRow &row, // And the height of the row is the maximum of all the fonts used within // the row. - if (graphic != (TextGraphic *)NULL) { + if (graphic != nullptr) { LVecBase4 frame = graphic->get_frame(); line_height = max(line_height, frame[3] - frame[2]); } else { @@ -1495,7 +1500,7 @@ assemble_row(TextAssembler::TextRow &row, } else if (character == text_soft_hyphen_key) { // And so is the 'soft-hyphen' key character. - } else if (graphic != (TextGraphic *)NULL) { + } else if (graphic != nullptr) { // A special embedded graphic. GlyphPlacement placement; @@ -1574,7 +1579,7 @@ assemble_row(TextAssembler::TextRow &row, // ligatures. GlyphPlacement placement; - placement._glyph = NULL; + placement._glyph = nullptr; placement._scale = glyph_scale; placement._xpos = xpos; placement._ypos = properties->get_glyph_shift(); @@ -1588,11 +1593,11 @@ assemble_row(TextAssembler::TextRow &row, // probably require the bounding volume of the glyph, so go get that. LPoint3 min_vert, max_vert; bool found_any = false; - if (first_glyph != NULL) { + if (first_glyph != nullptr) { first_glyph->calc_tight_bounds(min_vert, max_vert, found_any, current_thread); } - if (second_glyph != NULL) { + if (second_glyph != nullptr) { second_glyph->calc_tight_bounds(min_vert, max_vert, found_any, current_thread); } @@ -1625,20 +1630,20 @@ assemble_row(TextAssembler::TextRow &row, } } - if (first_glyph != (TextGlyph *)NULL) { + if (first_glyph != nullptr) { advance = first_glyph->get_advance() * advance_scale; if (!first_glyph->is_whitespace()) { - swap(placement._glyph, first_glyph); + std::swap(placement._glyph, first_glyph); placed_glyphs.push_back(placement); } } // Check if there is a second glyph to create a hacky ligature or some // such nonsense. - if (second_glyph != (TextGlyph *)NULL) { + if (second_glyph != nullptr) { placement._xpos += advance * glyph_scale; advance += second_glyph->get_advance(); - swap(placement._glyph, second_glyph); + std::swap(placement._glyph, second_glyph); placed_glyphs.push_back(placement); } @@ -1660,14 +1665,14 @@ assemble_row(TextAssembler::TextRow &row, row_width = xpos; - if (row._eol_cprops != (ComputedProperties *)NULL) { + if (row._eol_cprops != nullptr) { // If there's an _eol_cprops, it represents the cprops of the newline // character that ended the line, which should also contribute towards the // line_height. const TextProperties *properties = &(row._eol_cprops->_properties); TextFont *font = properties->get_font(); - nassertv(font != (TextFont *)NULL); + nassertv(font != nullptr); if (line_height == 0.0f) { PN_stdfloat glyph_scale = properties->get_glyph_scale() * properties->get_text_scale(); @@ -1703,7 +1708,7 @@ shape_buffer(hb_buffer_t *buf, PlacedGlyphs &placed_glyphs, PN_stdfloat &xpos, DynamicTextFont *font = DCAST(DynamicTextFont, properties.get_font()); hb_font_t *hb_font = font->get_hb_font(); - hb_shape(hb_font, buf, NULL, 0); + hb_shape(hb_font, buf, nullptr, 0); PN_stdfloat glyph_scale = properties.get_glyph_scale() * properties.get_text_scale(); PN_stdfloat scale = glyph_scale / (font->get_pixels_per_unit() * font->get_scale_factor() * 64.0); @@ -1796,7 +1801,7 @@ draw_underscore(TextAssembler::PlacedGlyphs &placed_glyphs, // LVecBase4(0), RenderState::make_empty()); GlyphPlacement placement; - placement._glyph = MOVE(glyph); + placement._glyph = move(glyph); placement._xpos = 0; placement._ypos = 0; placement._scale = 1; @@ -1825,11 +1830,11 @@ get_character_glyphs(int character, const TextProperties *properties, int &additional_flags, PN_stdfloat &glyph_scale, PN_stdfloat &advance_scale) { TextFont *font = properties->get_font(); - nassertv_always(font != (TextFont *)NULL); + nassertv_always(font != nullptr); got_glyph = false; - glyph = NULL; - second_glyph = NULL; + glyph = nullptr; + second_glyph = nullptr; accent_type = UnicodeLatinMap::AT_none; additional_flags = 0; glyph_scale = 1.0f; @@ -1839,7 +1844,7 @@ get_character_glyphs(int character, const TextProperties *properties, // capital. const UnicodeLatinMap::Entry *map_entry = UnicodeLatinMap::look_up(character); - if (map_entry != NULL) { + if (map_entry != nullptr) { if (properties->get_small_caps() && map_entry->_toupper_character != character) { character = map_entry->_toupper_character; @@ -1849,7 +1854,7 @@ get_character_glyphs(int character, const TextProperties *properties, } got_glyph = font->get_glyph(character, glyph); - if (!got_glyph && map_entry != NULL && map_entry->_ascii_equiv != 0) { + if (!got_glyph && map_entry != nullptr && map_entry->_ascii_equiv != 0) { // If we couldn't find the Unicode glyph, try the ASCII equivalent // (without the accent marks). if (map_entry->_ascii_equiv == 'i') { @@ -1870,7 +1875,7 @@ get_character_glyphs(int character, const TextProperties *properties, // If we still couldn't find it, try the uppercase equivalent. character = map_entry->_toupper_character; map_entry = UnicodeLatinMap::look_up(character); - if (map_entry != NULL) { + if (map_entry != nullptr) { got_glyph = font->get_glyph(map_entry->_ascii_equiv, glyph); } } @@ -2067,7 +2072,7 @@ tack_on_accent(wchar_t accent_mark, TextAssembler::CheesyPosition position, const TextProperties *properties, TextAssembler::GlyphPlacement &placement) const { TextFont *font = properties->get_font(); - nassertr(font != (TextFont *)NULL, false); + nassertr(font != nullptr, false); Thread *current_thread = Thread::get_current_thread(); @@ -2319,14 +2324,14 @@ append_delta(wstring &wtext, TextAssembler::ComputedProperties *other) { if (this != other) { if (_depth > other->_depth) { // Back up a level from this properties. - nassertv(_based_on != NULL); + nassertv(_based_on != nullptr); wtext.push_back(text_pop_properties_key); _based_on->append_delta(wtext, other); } else if (other->_depth > _depth) { // Back up a level from the other properties. - nassertv(other->_based_on != NULL); + nassertv(other->_based_on != nullptr); append_delta(wtext, other->_based_on); wtext.push_back(text_push_properties_key); @@ -2335,7 +2340,7 @@ append_delta(wstring &wtext, TextAssembler::ComputedProperties *other) { } else if (_depth != 0) { // Back up a level from both properties. - nassertv(_based_on != NULL && other->_based_on != NULL); + nassertv(_based_on != nullptr && other->_based_on != nullptr); wtext.push_back(text_pop_properties_key); _based_on->append_delta(wtext, other->_based_on); @@ -2381,7 +2386,7 @@ assign_append_to(GeomCollectorMap &geom_collector_map, PT(Geom) geom = _glyph->get_geom(GeomEnums::UH_static); - int p, sp, s, e, i; + int sp, s, e, i; const GeomVertexData *vdata = geom->get_vertex_data(); CPT(RenderState) rs = _glyph->get_state()->compose(state); @@ -2398,7 +2403,7 @@ assign_append_to(GeomCollectorMap &geom_collector_map, // that we don't needlessly duplicate vertices into our output vertex data. VertexIndexMap vimap; - for (p = 0; p < geom->get_num_primitives(); p++) { + for (size_t p = 0; p < geom->get_num_primitives(); ++p) { CPT(GeomPrimitive) primitive = geom->get_primitive(p)->decompose(); // Get a new GeomPrimitive of the corresponding type. @@ -2414,7 +2419,7 @@ assign_append_to(GeomCollectorMap &geom_collector_map, int vi = primitive->get_vertex(i); // Attempt to insert number "vi" into the map. - pair added = vimap.insert(VertexIndexMap::value_type(vi, 0)); + std::pair added = vimap.insert(VertexIndexMap::value_type(vi, 0)); int new_vertex; if (added.second) { // The insert succeeded. That means this is the first time we have @@ -2453,7 +2458,7 @@ assign_quad_to(QuadMap &quad_map, const RenderState *state, quad._dimensions += LVecBase4(offset[0], -offset[1], offset[0], -offset[1]); quad._glyph = _glyph; - quad_map[state->compose(_glyph->get_state())].push_back(MOVE(quad)); + quad_map[state->compose(_glyph->get_state())].push_back(move(quad)); } } @@ -2463,7 +2468,7 @@ assign_quad_to(QuadMap &quad_map, const RenderState *state, */ void TextAssembler::GlyphPlacement:: copy_graphic_to(PandaNode *node, const RenderState *state) const { - if (_graphic_model != (PandaNode *)NULL) { + if (_graphic_model != nullptr) { // We need an intermediate node to hold the transform and state. PT(PandaNode) intermediate_node = new PandaNode(""); node->add_child(intermediate_node); @@ -2510,29 +2515,29 @@ GeomCollector(const TextAssembler::GeomCollector ©) : GeomPrimitive *TextAssembler::GeomCollector:: get_primitive(TypeHandle prim_type) { if (prim_type == GeomTriangles::get_class_type()) { - if (_triangles == (GeomPrimitive *)NULL) { + if (_triangles == nullptr) { _triangles = new GeomTriangles(Geom::UH_static); _geom->add_primitive(_triangles); } return _triangles; } else if (prim_type == GeomLines::get_class_type()) { - if (_lines == (GeomPrimitive *)NULL) { + if (_lines == nullptr) { _lines = new GeomLines(Geom::UH_static); _geom->add_primitive(_lines); } return _lines; } else if (prim_type == GeomPoints::get_class_type()) { - if (_points == (GeomPrimitive *)NULL) { + if (_points == nullptr) { _points = new GeomPoints(Geom::UH_static); _geom->add_primitive(_points); } return _points; } - nassertr(false, NULL); - return NULL; + nassertr(false, nullptr); + return nullptr; } /** diff --git a/panda/src/text/textAssembler.h b/panda/src/text/textAssembler.h index 52195f8f69..2cbede0d10 100644 --- a/panda/src/text/textAssembler.h +++ b/panda/src/text/textAssembler.h @@ -64,13 +64,13 @@ PUBLISHED: INLINE void set_properties(const TextProperties &properties); INLINE const TextProperties &get_properties() const; - bool set_wtext(const wstring &wtext); - bool set_wsubstr(const wstring &wtext, int start, int count); + bool set_wtext(const std::wstring &wtext); + bool set_wsubstr(const std::wstring &wtext, int start, int count); - wstring get_plain_wtext() const; - wstring get_wordwrapped_plain_wtext() const; - wstring get_wtext() const; - wstring get_wordwrapped_wtext() const; + std::wstring get_plain_wtext() const; + std::wstring get_wordwrapped_plain_wtext() const; + std::wstring get_wtext() const; + std::wstring get_wordwrapped_wtext() const; bool calc_r_c(int &r, int &c, int n) const; INLINE int calc_r(int n) const; @@ -116,12 +116,12 @@ private: public: INLINE ComputedProperties(const TextProperties &orig_properties); INLINE ComputedProperties(ComputedProperties *based_on, - const wstring &wname, TextEncoder *encoder); - void append_delta(wstring &wtext, ComputedProperties *other); + const std::wstring &wname, TextEncoder *encoder); + void append_delta(std::wstring &wtext, ComputedProperties *other); PT(ComputedProperties) _based_on; int _depth; - wstring _wname; + std::wstring _wname; TextProperties _properties; }; @@ -133,14 +133,14 @@ private: public: INLINE TextCharacter(wchar_t character, ComputedProperties *cprops); INLINE TextCharacter(const TextGraphic *graphic, - const wstring &graphic_wname, + const std::wstring &graphic_wname, ComputedProperties *cprops); INLINE TextCharacter(const TextCharacter ©); INLINE void operator = (const TextCharacter ©); wchar_t _character; const TextGraphic *_graphic; - wstring _graphic_wname; + std::wstring _graphic_wname; PT(ComputedProperties) _cprops; }; typedef pvector TextString; @@ -169,8 +169,8 @@ private: TextBlock _text_block; void scan_wtext(TextString &output_string, - wstring::const_iterator &si, - const wstring::const_iterator &send, + std::wstring::const_iterator &si, + const std::wstring::const_iterator &send, ComputedProperties *current_cprops); bool wordwrap_text(); diff --git a/panda/src/text/textFont.cxx b/panda/src/text/textFont.cxx index add86483bd..bf6e9c5397 100644 --- a/panda/src/text/textFont.cxx +++ b/panda/src/text/textFont.cxx @@ -21,6 +21,10 @@ #include "geom.h" #include +using std::istream; +using std::ostream; +using std::string; + TypeHandle TextFont::_type_handle; /** @@ -86,7 +90,7 @@ write(ostream &out, int indent_level) const { */ TextGlyph *TextFont:: get_invalid_glyph() { - if (_invalid_glyph == (TextGlyph *)NULL) { + if (_invalid_glyph == nullptr) { make_invalid_glyph(); } return _invalid_glyph; diff --git a/panda/src/text/textFont.h b/panda/src/text/textFont.h index 7cea63e391..3c51c46d0c 100644 --- a/panda/src/text/textFont.h +++ b/panda/src/text/textFont.h @@ -76,7 +76,7 @@ PUBLISHED: virtual PN_stdfloat get_kerning(int first, int second) const; - virtual void write(ostream &out, int indent_level) const; + virtual void write(std::ostream &out, int indent_level) const; public: INLINE PN_stdfloat get_total_poly_margin() const; @@ -84,7 +84,7 @@ public: virtual bool get_glyph(int character, CPT(TextGlyph) &glyph)=0; TextGlyph *get_invalid_glyph(); - static RenderMode string_render_mode(const string &string); + static RenderMode string_render_mode(const std::string &string); private: void make_invalid_glyph(); @@ -114,8 +114,8 @@ private: static TypeHandle _type_handle; }; -EXPCL_PANDA_TEXT ostream &operator << (ostream &out, TextFont::RenderMode rm); -EXPCL_PANDA_TEXT istream &operator >> (istream &in, TextFont::RenderMode &rm); +EXPCL_PANDA_TEXT std::ostream &operator << (std::ostream &out, TextFont::RenderMode rm); +EXPCL_PANDA_TEXT std::istream &operator >> (std::istream &in, TextFont::RenderMode &rm); #include "textFont.I" diff --git a/panda/src/text/textGlyph.I b/panda/src/text/textGlyph.I index 77b3b943b0..3b8b112f79 100644 --- a/panda/src/text/textGlyph.I +++ b/panda/src/text/textGlyph.I @@ -17,7 +17,7 @@ INLINE TextGlyph:: TextGlyph(int character, PN_stdfloat advance) : _character(character), - _geom((Geom *)NULL), + _geom(nullptr), _advance(advance), _has_quad(false) { @@ -35,10 +35,10 @@ TextGlyph(int character, const Geom *geom, _advance(advance), _has_quad(false) { - if (geom != NULL) { + if (geom != nullptr) { check_quad_geom(); } - if (_state == (RenderState *)NULL) { + if (_state == nullptr) { _state = RenderState::make_empty(); } } diff --git a/panda/src/text/textGlyph.cxx b/panda/src/text/textGlyph.cxx index 0d3de18db6..bb8d998175 100644 --- a/panda/src/text/textGlyph.cxx +++ b/panda/src/text/textGlyph.cxx @@ -17,6 +17,9 @@ #include "geomVertexReader.h" #include "geomVertexWriter.h" +using std::max; +using std::min; + TypeHandle TextGlyph::_type_handle; /** @@ -51,11 +54,11 @@ get_geom(Geom::UsageHint usage_hint) const { if (_has_quad) { ((TextGlyph *)this)->make_quad_geom(); if (_geom.is_null()) { - return (Geom *)NULL; + return nullptr; } } else { // Nope. - return (Geom *)NULL; + return nullptr; } } @@ -67,7 +70,7 @@ get_geom(Geom::UsageHint usage_hint) const { PT(Geom) new_geom = new GeomTextGlyph(*_geom, this); new_geom->set_usage_hint(usage_hint); const GeomVertexData *vdata = new_geom->get_vertex_data(); - nassertr(vdata != NULL, new_geom); + nassertr(vdata != nullptr, new_geom); if (vdata->get_usage_hint() != usage_hint) { new_geom->modify_vertex_data()->set_usage_hint(usage_hint); } @@ -252,7 +255,7 @@ make_quad_geom() { // rather than a single triangle strip, to avoid the bad vertex duplication // behavior with lots of two-triangle strips. PT(GeomVertexData) vdata = new GeomVertexData - (string(), GeomVertexFormat::get_v3t2(), Geom::UH_static); + (std::string(), GeomVertexFormat::get_v3t2(), Geom::UH_static); vdata->unclean_set_num_rows(4); PT(GeomTriangles) tris = new GeomTriangles(Geom::UH_static); diff --git a/panda/src/text/textNode.I b/panda/src/text/textNode.I index 41758ba28a..313685c504 100644 --- a/panda/src/text/textNode.I +++ b/panda/src/text/textNode.I @@ -19,7 +19,7 @@ INLINE PN_stdfloat TextNode:: get_line_height() const { TextFont *font = get_font(); - if (font == (TextFont *)NULL) { + if (font == nullptr) { return 0.0f; } @@ -182,7 +182,7 @@ get_card_color() const { */ INLINE void TextNode:: set_card_texture(Texture *card_texture) { - if (card_texture == (Texture *)NULL) { + if (card_texture == nullptr) { clear_card_texture(); } else { if (!has_card_texture() || _card_texture != card_texture) { @@ -200,7 +200,7 @@ INLINE void TextNode:: clear_card_texture() { if (has_card_texture()) { _flags &= ~F_has_card_texture; - _card_texture = NULL; + _card_texture = nullptr; invalidate_no_measure(); } } @@ -830,7 +830,7 @@ clear_shadow() { * "fixed". */ INLINE void TextNode:: -set_bin(const string &bin) { +set_bin(const std::string &bin) { TextProperties::set_bin(bin); invalidate_no_measure(); } @@ -935,7 +935,7 @@ clear_glyph_shift() { * Changes the text that is displayed under the TextNode. */ INLINE void TextNode:: -set_text(const string &text) { +set_text(const std::string &text) { TextEncoder::set_text(text); invalidate_with_measure(); } @@ -947,7 +947,7 @@ set_text(const string &text) { * whichever encoding is specified by set_encoding(). */ INLINE void TextNode:: -set_text(const string &text, TextNode::Encoding encoding) { +set_text(const std::string &text, TextNode::Encoding encoding) { TextEncoder::set_text(text, encoding); invalidate_with_measure(); } @@ -965,7 +965,7 @@ clear_text() { * Appends the indicates string to the end of the stored text. */ INLINE void TextNode:: -append_text(const string &text) { +append_text(const std::string &text) { TextEncoder::append_text(text); invalidate_with_measure(); } @@ -987,7 +987,7 @@ append_unicode_char(wchar_t character) { * In earlier versions, this did not contain any embedded special characters * like \1 or \3; now it does. */ -INLINE string TextNode:: +INLINE std::string TextNode:: get_wordwrapped_text() const { return encode_wtext(get_wordwrapped_wtext()); } @@ -997,7 +997,7 @@ get_wordwrapped_text() const { * should not include the newline character. */ INLINE PN_stdfloat TextNode:: -calc_width(const string &line) const { +calc_width(const std::string &line) const { return calc_width(decode_text(line)); } @@ -1007,7 +1007,7 @@ calc_width(const string &line) const { * encoded version of the same string. */ INLINE void TextNode:: -set_wtext(const wstring &wtext) { +set_wtext(const std::wstring &wtext) { TextEncoder::set_wtext(wtext); invalidate_with_measure(); } @@ -1016,7 +1016,7 @@ set_wtext(const wstring &wtext) { * Appends the indicates string to the end of the stored wide-character text. */ INLINE void TextNode:: -append_wtext(const wstring &wtext) { +append_wtext(const std::wstring &wtext) { TextEncoder::append_wtext(wtext); invalidate_with_measure(); } @@ -1028,7 +1028,7 @@ append_wtext(const wstring &wtext) { * In earlier versions, this did not contain any embedded special characters * like \1 or \3; now it does. */ -INLINE wstring TextNode:: +INLINE std::wstring TextNode:: get_wordwrapped_wtext() const { check_measure(); return _wordwrapped_wtext; diff --git a/panda/src/text/textNode.cxx b/panda/src/text/textNode.cxx index 454c7dd7f3..92001d7b40 100644 --- a/panda/src/text/textNode.cxx +++ b/panda/src/text/textNode.cxx @@ -49,6 +49,8 @@ #include +using std::string; + TypeHandle TextNode::_type_handle; PStatCollector TextNode::_text_generate_pcollector("*:Generate Text"); @@ -174,7 +176,7 @@ TextNode:: PN_stdfloat TextNode:: calc_width(wchar_t character) const { TextFont *font = get_font(); - if (font == (TextFont *)NULL) { + if (font == nullptr) { return 0.0f; } @@ -196,7 +198,7 @@ calc_width(wchar_t character) const { bool TextNode:: has_exact_character(wchar_t character) const { TextFont *font = get_font(); - if (font == (TextFont *)NULL) { + if (font == nullptr) { return false; } @@ -215,7 +217,7 @@ has_exact_character(wchar_t character) const { bool TextNode:: has_character(wchar_t character) const { TextFont *font = get_font(); - if (font == (TextFont *)NULL) { + if (font == nullptr) { return false; } @@ -239,7 +241,7 @@ has_character(wchar_t character) const { bool TextNode:: is_whitespace(wchar_t character) const { TextFont *font = get_font(); - if (font == (TextFont *)NULL) { + if (font == nullptr) { return false; } @@ -252,10 +254,10 @@ is_whitespace(wchar_t character) const { * like \1 or \3. */ PN_stdfloat TextNode:: -calc_width(const wstring &line) const { +calc_width(const std::wstring &line) const { PN_stdfloat width = 0.0f; - wstring::const_iterator si; + std::wstring::const_iterator si; for (si = line.begin(); si != line.end(); ++si) { width += calc_width(*si); } @@ -267,12 +269,12 @@ calc_width(const wstring &line) const { * */ void TextNode:: -output(ostream &out) const { +output(std::ostream &out) const { PandaNode::output(out); check_rebuild(); int geom_count = 0; - if (_internal_geom != (PandaNode *)NULL) { + if (_internal_geom != nullptr) { geom_count = count_geoms(_internal_geom); } @@ -283,7 +285,7 @@ output(ostream &out) const { * */ void TextNode:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { PandaNode::write(out, indent_level); TextProperties::write(out, indent_level + 2); indent(out, indent_level + 2) @@ -333,7 +335,7 @@ generate() { } TextFont *font = get_font(); - if (font == (TextFont *)NULL) { + if (font == nullptr) { return root; } @@ -346,7 +348,7 @@ generate() { CPT(TransformState) transform = TransformState::make_mat(mat); root->set_transform(transform); - wstring wtext = get_wtext(); + std::wstring wtext = get_wtext(); // Assemble the text. TextAssembler assembler(this); @@ -514,7 +516,7 @@ apply_attribs_to_vertices(const AccumulatedAttribs &attribs, int attrib_types, } } if ((attrib_types & SceneGraphReducer::TT_color) != 0) { - if (attribs._color != (const RenderAttrib *)NULL) { + if (attribs._color != nullptr) { const ColorAttrib *ca = DCAST(ColorAttrib, attribs._color); if (ca->get_color_type() == ColorAttrib::T_flat) { const LColor &c = ca->get_color(); @@ -526,7 +528,7 @@ apply_attribs_to_vertices(const AccumulatedAttribs &attribs, int attrib_types, } } if ((attrib_types & SceneGraphReducer::TT_color_scale) != 0) { - if (attribs._color_scale != (const RenderAttrib *)NULL) { + if (attribs._color_scale != nullptr) { const ColorScaleAttrib *csa = DCAST(ColorScaleAttrib, attribs._color_scale); const LVecBase4 &s = csa->get_scale(); if (s != LVecBase4(1.0f, 1.0f, 1.0f, 1.0f)) { @@ -561,7 +563,7 @@ apply_attribs_to_vertices(const AccumulatedAttribs &attribs, int attrib_types, // Now propagate the attributes down to our already-generated geometry, if // we have any. if ((_flags & F_needs_rebuild) == 0 && - _internal_geom != (PandaNode *)NULL) { + _internal_geom != nullptr) { SceneGraphReducer gr; gr.apply_attribs(_internal_geom, attribs, attrib_types, transformer); } @@ -587,7 +589,7 @@ calc_tight_bounds(LPoint3 &min_point, LPoint3 &max_point, bool &found_any, check_rebuild(); - if (_internal_geom != (PandaNode *)NULL) { + if (_internal_geom != nullptr) { _internal_geom->calc_tight_bounds(min_point, max_point, found_any, next_transform, current_thread); } @@ -616,7 +618,7 @@ calc_tight_bounds(LPoint3 &min_point, LPoint3 &max_point, bool &found_any, bool TextNode:: cull_callback(CullTraverser *trav, CullTraverserData &data) { check_rebuild(); - if (_internal_geom != (PandaNode *)NULL) { + if (_internal_geom != nullptr) { // Render the text with this node. CullTraverserData next_data(data, _internal_geom); trav->traverse(next_data); @@ -682,7 +684,7 @@ r_prepare_scene(GraphicsStateGuardianBase *gsg, const RenderState *node_state, check_rebuild(); PandaNode *child = _internal_geom; - if (child != (PandaNode *)NULL) { + if (child != nullptr) { CPT(RenderState) child_state = node_state->compose(child->get_state()); child->r_prepare_scene(gsg, child_state, transformer, current_thread); } @@ -753,7 +755,7 @@ make_frame() { frame_node->add_geom(geom2, state); } - return frame_node.p(); + return frame_node; } /** @@ -793,7 +795,7 @@ make_card() { card_node->add_geom(geom); - return card_node.p(); + return card_node; } @@ -894,7 +896,7 @@ make_card_with_border() { card_node->add_geom(geom); - return card_node.p(); + return card_node; } /** diff --git a/panda/src/text/textNode.h b/panda/src/text/textNode.h index 50266cbfd7..4f37f806f4 100644 --- a/panda/src/text/textNode.h +++ b/panda/src/text/textNode.h @@ -45,8 +45,8 @@ */ class EXPCL_PANDA_TEXT TextNode : public PandaNode, public TextEncoder, public TextProperties { PUBLISHED: - explicit TextNode(const string &name); - explicit TextNode(const string &name, const TextProperties ©); + explicit TextNode(const std::string &name); + explicit TextNode(const std::string &name, const TextProperties ©); protected: TextNode(const TextNode ©); virtual PandaNode *make_copy() const; @@ -165,7 +165,7 @@ PUBLISHED: INLINE void set_shadow(const LVecBase2 &shadow_offset); INLINE void clear_shadow(); - INLINE void set_bin(const string &bin); + INLINE void set_bin(const std::string &bin); INLINE void clear_bin(); INLINE int set_draw_order(int draw_order); @@ -182,34 +182,34 @@ PUBLISHED: // These methods are inherited from TextEncoder, but we override here so we // can flag the TextNode as dirty when they have been changed. - INLINE void set_text(const string &text); - INLINE void set_text(const string &text, Encoding encoding); + INLINE void set_text(const std::string &text); + INLINE void set_text(const std::string &text, Encoding encoding); INLINE void clear_text(); - INLINE void append_text(const string &text); + INLINE void append_text(const std::string &text); INLINE void append_unicode_char(wchar_t character); // After the text has been set, you can query this to determine how it will // be wordwrapped. - INLINE string get_wordwrapped_text() const; + INLINE std::string get_wordwrapped_text() const; // These methods calculate the width of a single character or a line of text // in the current font. PN_stdfloat calc_width(wchar_t character) const; - INLINE PN_stdfloat calc_width(const string &line) const; + INLINE PN_stdfloat calc_width(const std::string &line) const; bool has_exact_character(wchar_t character) const; bool has_character(wchar_t character) const; bool is_whitespace(wchar_t character) const; // Direct support for wide-character strings. - INLINE void set_wtext(const wstring &wtext); - INLINE void append_wtext(const wstring &text); + INLINE void set_wtext(const std::wstring &wtext); + INLINE void append_wtext(const std::wstring &text); - INLINE wstring get_wordwrapped_wtext() const; - PN_stdfloat calc_width(const wstring &line) const; + INLINE std::wstring get_wordwrapped_wtext() const; + PN_stdfloat calc_width(const std::wstring &line) const; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; // The following functions return information about the text that was last // built (and is currently visible). @@ -343,7 +343,6 @@ private: int _max_rows; GeomEnums::UsageHint _usage_hint; int _flatten_flags; - bool _dynamic_merge; PN_stdfloat _frame_width; PN_stdfloat _card_border_size; PN_stdfloat _card_border_uv_portion; @@ -359,7 +358,7 @@ private: // Returned from TextAssembler: LVector2 _text_ul, _text_lr; int _num_rows; - wstring _wordwrapped_wtext; + std::wstring _wordwrapped_wtext; static PStatCollector _text_generate_pcollector; diff --git a/panda/src/text/textProperties.I b/panda/src/text/textProperties.I index e3e296c95f..09bfc78dad 100644 --- a/panda/src/text/textProperties.I +++ b/panda/src/text/textProperties.I @@ -562,7 +562,7 @@ get_shadow() const { * "fixed". */ INLINE void TextProperties:: -set_bin(const string &bin) { +set_bin(const std::string &bin) { _bin = bin; _specified |= F_has_bin; _text_state.clear(); @@ -575,7 +575,7 @@ set_bin(const string &bin) { */ INLINE void TextProperties:: clear_bin() { - _bin = string(); + _bin = std::string(); _specified &= ~F_has_bin; _text_state.clear(); _shadow_state.clear(); @@ -594,7 +594,7 @@ has_bin() const { * Returns the drawing bin set with set_bin(), or empty string if no bin has * been set. */ -INLINE const string &TextProperties:: +INLINE const std::string &TextProperties:: get_bin() const { return _bin; } diff --git a/panda/src/text/textProperties.cxx b/panda/src/text/textProperties.cxx index 341f2385a3..42e7982638 100644 --- a/panda/src/text/textProperties.cxx +++ b/panda/src/text/textProperties.cxx @@ -253,13 +253,13 @@ add_properties(const TextProperties &other) { * */ void TextProperties:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { if (!is_any_specified()) { indent(out, indent_level) << "default properties\n"; } if (has_font()) { - if (get_font() != (TextFont *)NULL) { + if (get_font() != nullptr) { indent(out, indent_level) << "with font " << _font->get_name() << "\n"; } else { @@ -408,7 +408,7 @@ get_text_state() const { state = state->add_attrib(CullBinAttrib::make(get_bin(), get_draw_order() + 2)); } - swap(_text_state, state); + std::swap(_text_state, state); return _text_state; } @@ -433,7 +433,7 @@ get_shadow_state() const { state = state->add_attrib(CullBinAttrib::make(get_bin(), get_draw_order() + 1)); } - swap(_shadow_state, state); + std::swap(_shadow_state, state); return _shadow_state; } @@ -450,7 +450,7 @@ load_default_font() { if (!text_default_font.empty()) { // First, attempt to load the user-specified filename. _default_font = FontPool::load_font(text_default_font.get_value()); - if (_default_font != (TextFont *)NULL && _default_font->is_valid()) { + if (_default_font != nullptr && _default_font->is_valid()) { return; } } @@ -466,22 +466,22 @@ load_default_font() { #else // The compiled-in Bam font requires creating a BamFile object to decode it. - string data((const char *)default_font_data, default_font_size); + std::string data((const char *)default_font_data, default_font_size); #ifdef HAVE_ZLIB // The font data is stored compressed; decompress it on-the-fly. - istringstream inz(data); + std::istringstream inz(data); IDecompressStream in(&inz, false); #else // The font data is stored uncompressed, so just load it. - istringstream in(data); + std::istringstream in(data); #endif // HAVE_ZLIB BamFile bam_file; if (bam_file.open_read(in, "default font stream")) { PT(PandaNode) node = bam_file.read_node(); - if (node != (PandaNode *)NULL) { + if (node != nullptr) { _default_font = new StaticTextFont(node); } } diff --git a/panda/src/text/textProperties.h b/panda/src/text/textProperties.h index af899f7b59..aca592e30b 100644 --- a/panda/src/text/textProperties.h +++ b/panda/src/text/textProperties.h @@ -135,10 +135,10 @@ PUBLISHED: INLINE bool has_shadow() const; INLINE LVector2 get_shadow() const; - INLINE void set_bin(const string &bin); + INLINE void set_bin(const std::string &bin); INLINE void clear_bin(); INLINE bool has_bin() const; - INLINE const string &get_bin() const; + INLINE const std::string &get_bin() const; INLINE int set_draw_order(int draw_order); INLINE void clear_draw_order(); @@ -172,7 +172,7 @@ PUBLISHED: void add_properties(const TextProperties &other); - void write(ostream &out, int indent_level = 0) const; + void write(std::ostream &out, int indent_level = 0) const; PUBLISHED: MAKE_PROPERTY2(font, has_font, get_font, set_font, clear_font); @@ -255,7 +255,7 @@ private: LColor _text_color; LColor _shadow_color; LVector2 _shadow_offset; - string _bin; + std::string _bin; int _draw_order; PN_stdfloat _tab_width; PN_stdfloat _glyph_scale; diff --git a/panda/src/text/textPropertiesManager.cxx b/panda/src/text/textPropertiesManager.cxx index 2d8c93fd32..1c589499cc 100644 --- a/panda/src/text/textPropertiesManager.cxx +++ b/panda/src/text/textPropertiesManager.cxx @@ -14,7 +14,9 @@ #include "textPropertiesManager.h" #include "indent.h" -TextPropertiesManager *TextPropertiesManager::_global_ptr = (TextPropertiesManager *)NULL; +using std::string; + +TextPropertiesManager *TextPropertiesManager::_global_ptr = nullptr; /** * The constructor is not intended to be called directly; there is only one @@ -179,7 +181,7 @@ clear_graphic(const string &name) { * */ void TextPropertiesManager:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { Properties::const_iterator pi; for (pi = _properties.begin(); pi != _properties.end(); ++pi) { indent(out, indent_level) @@ -193,7 +195,7 @@ write(ostream &out, int indent_level) const { */ TextPropertiesManager *TextPropertiesManager:: get_global_ptr() { - if (_global_ptr == (TextPropertiesManager *)NULL) { + if (_global_ptr == nullptr) { _global_ptr = new TextPropertiesManager; } return _global_ptr; @@ -210,7 +212,7 @@ get_properties_ptr(const string &name) { if (pi != _properties.end()) { return &(*pi).second; } - return NULL; + return nullptr; } /** @@ -224,5 +226,5 @@ get_graphic_ptr(const string &name) { if (pi != _graphics.end()) { return &(*pi).second; } - return NULL; + return nullptr; } diff --git a/panda/src/text/textPropertiesManager.h b/panda/src/text/textPropertiesManager.h index 2c4f6b3c84..bae0c86e78 100644 --- a/panda/src/text/textPropertiesManager.h +++ b/panda/src/text/textPropertiesManager.h @@ -47,30 +47,30 @@ protected: ~TextPropertiesManager(); PUBLISHED: - void set_properties(const string &name, const TextProperties &properties); - TextProperties get_properties(const string &name); - bool has_properties(const string &name) const; - void clear_properties(const string &name); + void set_properties(const std::string &name, const TextProperties &properties); + TextProperties get_properties(const std::string &name); + bool has_properties(const std::string &name) const; + void clear_properties(const std::string &name); - void set_graphic(const string &name, const TextGraphic &graphic); - void set_graphic(const string &name, const NodePath &model); - TextGraphic get_graphic(const string &name); - bool has_graphic(const string &name) const; - void clear_graphic(const string &name); + void set_graphic(const std::string &name, const TextGraphic &graphic); + void set_graphic(const std::string &name, const NodePath &model); + TextGraphic get_graphic(const std::string &name); + bool has_graphic(const std::string &name) const; + void clear_graphic(const std::string &name); - void write(ostream &out, int indent_level = 0) const; + void write(std::ostream &out, int indent_level = 0) const; static TextPropertiesManager *get_global_ptr(); public: - const TextProperties *get_properties_ptr(const string &name); - const TextGraphic *get_graphic_ptr(const string &name); + const TextProperties *get_properties_ptr(const std::string &name); + const TextGraphic *get_graphic_ptr(const std::string &name); private: - typedef pmap Properties; + typedef pmap Properties; Properties _properties; - typedef pmap Graphics; + typedef pmap Graphics; Graphics _graphics; static TextPropertiesManager *_global_ptr; diff --git a/panda/src/tform/buttonThrower.I b/panda/src/tform/buttonThrower.I index 22832bc933..2e0fc4c57f 100644 --- a/panda/src/tform/buttonThrower.I +++ b/panda/src/tform/buttonThrower.I @@ -24,7 +24,7 @@ * See also set_keystroke_event(). */ INLINE void ButtonThrower:: -set_button_down_event(const string &button_down_event) { +set_button_down_event(const std::string &button_down_event) { _button_down_event = button_down_event; } @@ -32,7 +32,7 @@ set_button_down_event(const string &button_down_event) { * Returns the button_down_event that has been set on this ButtonThrower. See * set_button_down_event(). */ -INLINE const string &ButtonThrower:: +INLINE const std::string &ButtonThrower:: get_button_down_event() const { return _button_down_event; } @@ -42,7 +42,7 @@ get_button_down_event() const { * button is released. See set_button_down_event(). */ INLINE void ButtonThrower:: -set_button_up_event(const string &button_up_event) { +set_button_up_event(const std::string &button_up_event) { _button_up_event = button_up_event; } @@ -50,7 +50,7 @@ set_button_up_event(const string &button_up_event) { * Returns the button_up_event that has been set on this ButtonThrower. See * set_button_up_event(). */ -INLINE const string &ButtonThrower:: +INLINE const std::string &ButtonThrower:: get_button_up_event() const { return _button_up_event; } @@ -68,7 +68,7 @@ get_button_up_event() const { * See also set_keystroke_event(). */ INLINE void ButtonThrower:: -set_button_repeat_event(const string &button_repeat_event) { +set_button_repeat_event(const std::string &button_repeat_event) { _button_repeat_event = button_repeat_event; } @@ -76,7 +76,7 @@ set_button_repeat_event(const string &button_repeat_event) { * Returns the button_repeat_event that has been set on this ButtonThrower. * See set_button_repeat_event(). */ -INLINE const string &ButtonThrower:: +INLINE const std::string &ButtonThrower:: get_button_repeat_event() const { return _button_repeat_event; } @@ -100,7 +100,7 @@ get_button_repeat_event() const { * See also set_button_down_event(). */ INLINE void ButtonThrower:: -set_keystroke_event(const string &keystroke_event) { +set_keystroke_event(const std::string &keystroke_event) { _keystroke_event = keystroke_event; } @@ -108,7 +108,7 @@ set_keystroke_event(const string &keystroke_event) { * Returns the keystroke_event that has been set on this ButtonThrower. See * set_keystroke_event(). */ -INLINE const string &ButtonThrower:: +INLINE const std::string &ButtonThrower:: get_keystroke_event() const { return _keystroke_event; } @@ -129,7 +129,7 @@ get_keystroke_event() const { * which to end the highlight, and the current cursor position. */ INLINE void ButtonThrower:: -set_candidate_event(const string &candidate_event) { +set_candidate_event(const std::string &candidate_event) { _candidate_event = candidate_event; } @@ -137,7 +137,7 @@ set_candidate_event(const string &candidate_event) { * Returns the candidate_event that has been set on this ButtonThrower. See * set_candidate_event(). */ -INLINE const string &ButtonThrower:: +INLINE const std::string &ButtonThrower:: get_candidate_event() const { return _candidate_event; } @@ -147,7 +147,7 @@ get_candidate_event() const { * within the window. */ INLINE void ButtonThrower:: -set_move_event(const string &move_event) { +set_move_event(const std::string &move_event) { _move_event = move_event; } @@ -155,7 +155,7 @@ set_move_event(const string &move_event) { * Returns the move_event that has been set on this ButtonThrower. See * set_move_event(). */ -INLINE const string &ButtonThrower:: +INLINE const std::string &ButtonThrower:: get_move_event() const { return _move_event; } @@ -166,7 +166,7 @@ get_move_event() const { * selected keyboard layout. */ INLINE void ButtonThrower:: -set_raw_button_down_event(const string &raw_button_down_event) { +set_raw_button_down_event(const std::string &raw_button_down_event) { _raw_button_down_event = raw_button_down_event; } @@ -174,7 +174,7 @@ set_raw_button_down_event(const string &raw_button_down_event) { * Returns the raw_button_down_event that has been set on this ButtonThrower. * See set_raw_button_down_event(). */ -INLINE const string &ButtonThrower:: +INLINE const std::string &ButtonThrower:: get_raw_button_down_event() const { return _raw_button_down_event; } @@ -184,7 +184,7 @@ get_raw_button_down_event() const { * button is released. See set_raw_button_down_event(). */ INLINE void ButtonThrower:: -set_raw_button_up_event(const string &raw_button_up_event) { +set_raw_button_up_event(const std::string &raw_button_up_event) { _raw_button_up_event = raw_button_up_event; } @@ -192,7 +192,7 @@ set_raw_button_up_event(const string &raw_button_up_event) { * Returns the raw_button_up_event that has been set on this ButtonThrower. * See set_raw_button_up_event(). */ -INLINE const string &ButtonThrower:: +INLINE const std::string &ButtonThrower:: get_raw_button_up_event() const { return _raw_button_up_event; } @@ -203,7 +203,7 @@ get_raw_button_up_event() const { * generic event names like set_button_down_event) thrown by this object. */ INLINE void ButtonThrower:: -set_prefix(const string &prefix) { +set_prefix(const std::string &prefix) { _prefix = prefix; } @@ -211,7 +211,7 @@ set_prefix(const string &prefix) { * Returns the prefix that has been set on this ButtonThrower. See * set_prefix(). */ -INLINE const string &ButtonThrower:: +INLINE const std::string &ButtonThrower:: get_prefix() const { return _prefix; } diff --git a/panda/src/tform/buttonThrower.cxx b/panda/src/tform/buttonThrower.cxx index 33c7150fb1..2446c1929a 100644 --- a/panda/src/tform/buttonThrower.cxx +++ b/panda/src/tform/buttonThrower.cxx @@ -21,6 +21,8 @@ #include "indent.h" #include "dcast.h" +using std::string; + TypeHandle ButtonThrower::_type_handle; @@ -204,7 +206,7 @@ clear_throw_buttons() { * Throw all events for button events found in the data element. */ void ButtonThrower:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { DataNode::write(out, indent_level); if (_throw_buttons_active) { indent(out, indent_level) @@ -310,7 +312,7 @@ do_general_event(const ButtonEvent &button_event, const string &button_name) { break; case ButtonEvent::T_keystroke: - event->add_parameter(wstring(1, button_event._keycode)); + event->add_parameter(std::wstring(1, button_event._keycode)); break; case ButtonEvent::T_candidate: diff --git a/panda/src/tform/buttonThrower.h b/panda/src/tform/buttonThrower.h index 2c1a8a3982..7aa47c1fa9 100644 --- a/panda/src/tform/buttonThrower.h +++ b/panda/src/tform/buttonThrower.h @@ -34,25 +34,25 @@ */ class EXPCL_PANDA_TFORM ButtonThrower : public DataNode { PUBLISHED: - explicit ButtonThrower(const string &name); + explicit ButtonThrower(const std::string &name); ~ButtonThrower(); - INLINE void set_button_down_event(const string &button_down_event); - INLINE const string &get_button_down_event() const; - INLINE void set_button_up_event(const string &button_up_event); - INLINE const string &get_button_up_event() const; - INLINE void set_button_repeat_event(const string &button_repeat_event); - INLINE const string &get_button_repeat_event() const; - INLINE void set_keystroke_event(const string &keystroke_event); - INLINE const string &get_keystroke_event() const; - INLINE void set_candidate_event(const string &candidate_event); - INLINE const string &get_candidate_event() const; - INLINE void set_move_event(const string &move_event); - INLINE const string &get_move_event() const; - INLINE void set_raw_button_down_event(const string &raw_button_down_event); - INLINE const string &get_raw_button_down_event() const; - INLINE void set_raw_button_up_event(const string &raw_button_up_event); - INLINE const string &get_raw_button_up_event() const; + INLINE void set_button_down_event(const std::string &button_down_event); + INLINE const std::string &get_button_down_event() const; + INLINE void set_button_up_event(const std::string &button_up_event); + INLINE const std::string &get_button_up_event() const; + INLINE void set_button_repeat_event(const std::string &button_repeat_event); + INLINE const std::string &get_button_repeat_event() const; + INLINE void set_keystroke_event(const std::string &keystroke_event); + INLINE const std::string &get_keystroke_event() const; + INLINE void set_candidate_event(const std::string &candidate_event); + INLINE const std::string &get_candidate_event() const; + INLINE void set_move_event(const std::string &move_event); + INLINE const std::string &get_move_event() const; + INLINE void set_raw_button_down_event(const std::string &raw_button_down_event); + INLINE const std::string &get_raw_button_down_event() const; + INLINE void set_raw_button_up_event(const std::string &raw_button_up_event); + INLINE const std::string &get_raw_button_up_event() const; MAKE_PROPERTY(button_down_event, get_button_down_event, set_button_down_event); MAKE_PROPERTY(button_up_event, get_button_up_event, set_button_up_event); MAKE_PROPERTY(button_repeat_event, get_button_repeat_event, set_button_repeat_event); @@ -62,8 +62,8 @@ PUBLISHED: MAKE_PROPERTY(raw_button_down_event, get_raw_button_down_event, set_raw_button_down_event); MAKE_PROPERTY(raw_button_up_event, get_raw_button_up_event, set_raw_button_up_event); - INLINE void set_prefix(const string &prefix); - INLINE const string &get_prefix() const; + INLINE void set_prefix(const std::string &prefix); + INLINE const std::string &get_prefix() const; INLINE void set_specific_flag(bool specific_flag); INLINE bool get_specific_flag() const; MAKE_PROPERTY(prefix, get_prefix, set_prefix); @@ -94,24 +94,24 @@ PUBLISHED: void clear_throw_buttons(); public: - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; private: - void do_specific_event(const string &event_name, double time); + void do_specific_event(const std::string &event_name, double time); void do_general_event(const ButtonEvent &button_event, - const string &event_name); + const std::string &event_name); private: - string _button_down_event; - string _button_up_event; - string _button_repeat_event; - string _keystroke_event; - string _candidate_event; - string _move_event; - string _raw_button_up_event; - string _raw_button_down_event; + std::string _button_down_event; + std::string _button_up_event; + std::string _button_repeat_event; + std::string _keystroke_event; + std::string _candidate_event; + std::string _move_event; + std::string _raw_button_up_event; + std::string _raw_button_down_event; bool _specific_flag; - string _prefix; + std::string _prefix; bool _time_flag; ModifierButtons _mods; diff --git a/panda/src/tform/driveInterface.cxx b/panda/src/tform/driveInterface.cxx index f9324ce110..eb3433c557 100644 --- a/panda/src/tform/driveInterface.cxx +++ b/panda/src/tform/driveInterface.cxx @@ -25,6 +25,9 @@ #include "dataNodeTransmit.h" #include "dataGraphTraverser.h" +using std::max; +using std::min; + TypeHandle DriveInterface::_type_handle; const PN_stdfloat DriveInterface::_hpr_quantize = 0.001; @@ -95,7 +98,7 @@ operator < (const DriveInterface::KeyHeld &other) const { * */ DriveInterface:: -DriveInterface(const string &name) : +DriveInterface(const std::string &name) : MouseInterfaceNode(name) { _xy_input = define_input("xy", EventStoreVec2::get_class_type()); @@ -383,7 +386,7 @@ do_transmit_data(DataGraphTraverser *, const DataNodeTransmit &input, } // Look for keyboard events. - if (required_buttons_match && button_events != (const ButtonEventList *)NULL) { + if (required_buttons_match && button_events != nullptr) { int num_events = button_events->get_num_events(); for (int i = 0; i < num_events; i++) { diff --git a/panda/src/tform/driveInterface.h b/panda/src/tform/driveInterface.h index 89f6b069b0..516cc6be43 100644 --- a/panda/src/tform/driveInterface.h +++ b/panda/src/tform/driveInterface.h @@ -30,7 +30,7 @@ */ class EXPCL_PANDA_TFORM DriveInterface : public MouseInterfaceNode { PUBLISHED: - explicit DriveInterface(const string &name = ""); + explicit DriveInterface(const std::string &name = ""); ~DriveInterface(); INLINE void set_forward_speed(PN_stdfloat speed); diff --git a/panda/src/tform/mouseInterfaceNode.cxx b/panda/src/tform/mouseInterfaceNode.cxx index b69a17d06e..63c6c6cf87 100644 --- a/panda/src/tform/mouseInterfaceNode.cxx +++ b/panda/src/tform/mouseInterfaceNode.cxx @@ -23,7 +23,7 @@ TypeHandle MouseInterfaceNode::_type_handle; * */ MouseInterfaceNode:: -MouseInterfaceNode(const string &name) : +MouseInterfaceNode(const std::string &name) : DataNode(name) { _button_events_input = define_input("button_events", ButtonEventList::get_class_type()); @@ -117,10 +117,10 @@ watch_button(const ButtonHandle &button) { const ButtonEventList *MouseInterfaceNode:: check_button_events(const DataNodeTransmit &input, bool &required_buttons_match) { - const ButtonEventList *button_events = NULL; + const ButtonEventList *button_events = nullptr; if (input.has_data(_button_events_input)) { - DCAST_INTO_R(button_events, input.get_data(_button_events_input).get_ptr(), NULL); + DCAST_INTO_R(button_events, input.get_data(_button_events_input).get_ptr(), nullptr); button_events->update_mods(_current_button_state); } diff --git a/panda/src/tform/mouseInterfaceNode.h b/panda/src/tform/mouseInterfaceNode.h index 1555dba852..b1540e6aba 100644 --- a/panda/src/tform/mouseInterfaceNode.h +++ b/panda/src/tform/mouseInterfaceNode.h @@ -30,7 +30,7 @@ class ButtonEventList; */ class EXPCL_PANDA_TFORM MouseInterfaceNode : public DataNode { public: - explicit MouseInterfaceNode(const string &name); + explicit MouseInterfaceNode(const std::string &name); virtual ~MouseInterfaceNode(); PUBLISHED: diff --git a/panda/src/tform/mouseSubregion.cxx b/panda/src/tform/mouseSubregion.cxx index f342db85fe..89a5fcca94 100644 --- a/panda/src/tform/mouseSubregion.cxx +++ b/panda/src/tform/mouseSubregion.cxx @@ -20,7 +20,7 @@ TypeHandle MouseSubregion::_type_handle; * */ MouseSubregion:: -MouseSubregion(const string &name) : +MouseSubregion(const std::string &name) : MouseInterfaceNode(name) { _pixel_xy_input = define_input("pixel_xy", EventStoreVec2::get_class_type()); diff --git a/panda/src/tform/mouseSubregion.h b/panda/src/tform/mouseSubregion.h index f500992bcb..105dda96f9 100644 --- a/panda/src/tform/mouseSubregion.h +++ b/panda/src/tform/mouseSubregion.h @@ -32,7 +32,7 @@ */ class EXPCL_PANDA_TFORM MouseSubregion : public MouseInterfaceNode { PUBLISHED: - explicit MouseSubregion(const string &name); + explicit MouseSubregion(const std::string &name); ~MouseSubregion(); INLINE PN_stdfloat get_left() const; diff --git a/panda/src/tform/mouseWatcher.I b/panda/src/tform/mouseWatcher.I index 389861e8d9..f47c07e6e2 100644 --- a/panda/src/tform/mouseWatcher.I +++ b/panda/src/tform/mouseWatcher.I @@ -101,7 +101,7 @@ get_frame() const { */ INLINE bool MouseWatcher:: is_over_region() const { - return get_over_region() != (MouseWatcherRegion *)NULL; + return get_over_region() != nullptr; } /** @@ -109,7 +109,7 @@ is_over_region() const { */ INLINE bool MouseWatcher:: is_over_region(PN_stdfloat x, PN_stdfloat y) const { - return get_over_region(x, y) != (MouseWatcherRegion *)NULL; + return get_over_region(x, y) != nullptr; } /** @@ -117,7 +117,7 @@ is_over_region(PN_stdfloat x, PN_stdfloat y) const { */ INLINE bool MouseWatcher:: is_over_region(const LPoint2 &pos) const { - return get_over_region(pos) != (MouseWatcherRegion *)NULL; + return get_over_region(pos) != nullptr; } /** @@ -160,7 +160,7 @@ is_button_down(ButtonHandle button) const { * values. */ INLINE void MouseWatcher:: -set_button_down_pattern(const string &pattern) { +set_button_down_pattern(const std::string &pattern) { _button_down_pattern = pattern; } @@ -168,7 +168,7 @@ set_button_down_pattern(const string &pattern) { * Returns the string that indicates how event names are generated when a * button is depressed. See set_button_down_pattern(). */ -INLINE const string &MouseWatcher:: +INLINE const std::string &MouseWatcher:: get_button_down_pattern() const { return _button_down_pattern; } @@ -178,7 +178,7 @@ get_button_down_pattern() const { * when a button is released. See set_button_down_pattern(). */ INLINE void MouseWatcher:: -set_button_up_pattern(const string &pattern) { +set_button_up_pattern(const std::string &pattern) { _button_up_pattern = pattern; } @@ -186,7 +186,7 @@ set_button_up_pattern(const string &pattern) { * Returns the string that indicates how event names are generated when a * button is released. See set_button_down_pattern(). */ -INLINE const string &MouseWatcher:: +INLINE const std::string &MouseWatcher:: get_button_up_pattern() const { return _button_up_pattern; } @@ -204,7 +204,7 @@ get_button_up_pattern() const { * values. */ INLINE void MouseWatcher:: -set_button_repeat_pattern(const string &pattern) { +set_button_repeat_pattern(const std::string &pattern) { _button_repeat_pattern = pattern; } @@ -213,7 +213,7 @@ set_button_repeat_pattern(const string &pattern) { * when a button is continuously held and generates keyrepeat "down" events. * See set_button_repeat_pattern(). */ -INLINE const string &MouseWatcher:: +INLINE const std::string &MouseWatcher:: get_button_repeat_pattern() const { return _button_repeat_pattern; } @@ -225,7 +225,7 @@ get_button_repeat_pattern() const { * it might be "within" multiple nested regions. */ INLINE void MouseWatcher:: -set_enter_pattern(const string &pattern) { +set_enter_pattern(const std::string &pattern) { _enter_pattern = pattern; } @@ -235,7 +235,7 @@ set_enter_pattern(const string &pattern) { * mouse is only "entered" in the topmost region at a given time, while it * might be "within" multiple nested regions. */ -INLINE const string &MouseWatcher:: +INLINE const std::string &MouseWatcher:: get_enter_pattern() const { return _enter_pattern; } @@ -247,7 +247,7 @@ get_enter_pattern() const { * it might be "within" multiple nested regions. */ INLINE void MouseWatcher:: -set_leave_pattern(const string &pattern) { +set_leave_pattern(const std::string &pattern) { _leave_pattern = pattern; } @@ -257,7 +257,7 @@ set_leave_pattern(const string &pattern) { * mouse is only "entered" in the topmost region at a given time, while it * might be "within" multiple nested regions. */ -INLINE const string &MouseWatcher:: +INLINE const std::string &MouseWatcher:: get_leave_pattern() const { return _leave_pattern; } @@ -269,7 +269,7 @@ get_leave_pattern() const { * given time, while it might be "within" multiple nested regions. */ INLINE void MouseWatcher:: -set_within_pattern(const string &pattern) { +set_within_pattern(const std::string &pattern) { _within_pattern = pattern; } @@ -279,7 +279,7 @@ set_within_pattern(const string &pattern) { * a mouse is only "entered" in the topmost region at a given time, while it * might be "within" multiple nested regions. */ -INLINE const string &MouseWatcher:: +INLINE const std::string &MouseWatcher:: get_within_pattern() const { return _within_pattern; } @@ -291,7 +291,7 @@ get_within_pattern() const { * given time, while it might be "within" multiple nested regions. */ INLINE void MouseWatcher:: -set_without_pattern(const string &pattern) { +set_without_pattern(const std::string &pattern) { _without_pattern = pattern; } @@ -301,7 +301,7 @@ set_without_pattern(const string &pattern) { * that a mouse is only "entered" in the topmost region at a given time, while * it might be "within" multiple nested regions. */ -INLINE const string &MouseWatcher:: +INLINE const std::string &MouseWatcher:: get_without_pattern() const { return _without_pattern; } @@ -391,7 +391,7 @@ get_modifier_buttons() const { INLINE void MouseWatcher:: set_display_region(DisplayRegion *dr) { _display_region = dr; - _button_down_display_region = NULL; + _button_down_display_region = nullptr; } /** @@ -400,8 +400,8 @@ set_display_region(DisplayRegion *dr) { */ INLINE void MouseWatcher:: clear_display_region() { - _display_region = NULL; - _button_down_display_region = NULL; + _display_region = nullptr; + _button_down_display_region = nullptr; } /** @@ -421,7 +421,7 @@ get_display_region() const { */ INLINE bool MouseWatcher:: has_display_region() const { - return (_display_region != (DisplayRegion *)NULL); + return (_display_region != nullptr); } /** @@ -475,7 +475,7 @@ clear_inactivity_timeout() { * timeout counter expires. See set_inactivity_timeout(). */ INLINE void MouseWatcher:: -set_inactivity_timeout_event(const string &event) { +set_inactivity_timeout_event(const std::string &event) { _inactivity_timeout_event = event; } @@ -483,7 +483,7 @@ set_inactivity_timeout_event(const string &event) { * Returns the event string that will be generated when the inactivity timeout * counter expires. See set_inactivity_timeout(). */ -INLINE const string &MouseWatcher:: +INLINE const std::string &MouseWatcher:: get_inactivity_timeout_event() const { return _inactivity_timeout_event; } diff --git a/panda/src/tform/mouseWatcher.cxx b/panda/src/tform/mouseWatcher.cxx index 30f2c4762e..c4b5c0a6e7 100644 --- a/panda/src/tform/mouseWatcher.cxx +++ b/panda/src/tform/mouseWatcher.cxx @@ -35,6 +35,8 @@ #include +using std::string; + TypeHandle MouseWatcher::_type_handle; /** @@ -62,12 +64,12 @@ MouseWatcher(const string &name) : _has_mouse = false; _internal_suppress = 0; - _preferred_region = (MouseWatcherRegion *)NULL; - _preferred_button_down_region = (MouseWatcherRegion *)NULL; + _preferred_region = nullptr; + _preferred_button_down_region = nullptr; _button_down = false; - _eh = (EventHandler *)NULL; - _display_region = (DisplayRegion *)NULL; - _button_down_display_region = (DisplayRegion *)NULL; + _eh = nullptr; + _display_region = nullptr; + _button_down_display_region = nullptr; _frame.set(-1.0f, 1.0f, -1.0f, 1.0f); @@ -109,13 +111,13 @@ remove_region(MouseWatcherRegion *region) { remove_region_from(_current_regions, region); if (region == _preferred_region) { - if (_preferred_region != (MouseWatcherRegion *)NULL) { + if (_preferred_region != nullptr) { exit_region(_preferred_region, MouseWatcherParameter()); } - _preferred_region = (MouseWatcherRegion *)NULL; + _preferred_region = nullptr; } if (region == _preferred_button_down_region) { - _preferred_button_down_region = (MouseWatcherRegion *)NULL; + _preferred_button_down_region = nullptr; } return MouseWatcherBase::do_remove_region(region); @@ -190,13 +192,13 @@ remove_group(MouseWatcherGroup *group) { set_current_regions(only_a); if (has_region_in(both, _preferred_region)) { - if (_preferred_region != (MouseWatcherRegion *)NULL) { + if (_preferred_region != nullptr) { exit_region(_preferred_region, MouseWatcherParameter()); } - _preferred_region = (MouseWatcherRegion *)NULL; + _preferred_region = nullptr; } if (has_region_in(both, _preferred_button_down_region)) { - _preferred_button_down_region = (MouseWatcherRegion *)NULL; + _preferred_button_down_region = nullptr; } #ifndef NDEBUG @@ -268,13 +270,13 @@ replace_group(MouseWatcherGroup *old_group, MouseWatcherGroup *new_group) { any_new_current_regions = true; if (has_region_in(both, _preferred_region)) { - if (_preferred_region != (MouseWatcherRegion *)NULL) { + if (_preferred_region != nullptr) { exit_region(_preferred_region, MouseWatcherParameter()); } - _preferred_region = (MouseWatcherRegion *)NULL; + _preferred_region = nullptr; } if (has_region_in(both, _preferred_button_down_region)) { - _preferred_button_down_region = (MouseWatcherRegion *)NULL; + _preferred_button_down_region = nullptr; } } @@ -343,7 +345,7 @@ get_num_groups() const { MouseWatcherGroup *MouseWatcher:: get_group(int n) const { LightMutexHolder holder(_lock); - nassertr(n >= 0 && n < (int)_groups.size(), NULL); + nassertr(n >= 0 && n < (int)_groups.size(), nullptr); return _groups[n]; } @@ -397,7 +399,7 @@ discard_excess_trail_log() { */ PT(GeomNode) MouseWatcher:: get_trail_node() { - if (_trail_node == 0) { + if (_trail_node == nullptr) { _trail_node = new GeomNode("Mouse Trail Node"); update_trail_node(); } @@ -412,7 +414,7 @@ get_trail_node() { */ void MouseWatcher:: clear_trail_node() { - _trail_node = 0; + _trail_node = nullptr; } /** @@ -420,7 +422,7 @@ clear_trail_node() { */ void MouseWatcher:: update_trail_node() { - if (_trail_node == 0) { + if (_trail_node == nullptr) { return; } _trail_node->remove_all_geoms(); @@ -487,15 +489,17 @@ note_activity() { * */ void MouseWatcher:: -output(ostream &out) const { +output(std::ostream &out) const { LightMutexHolder holder(_lock); DataNode::output(out); - int count = _regions.size(); - Groups::const_iterator gi; - for (gi = _groups.begin(); gi != _groups.end(); ++gi) { - MouseWatcherGroup *group = (*gi); - count += group->_regions.size(); + if (!_sorted) { + ((MouseWatcher *)this)->do_sort_regions(); + } + + size_t count = _regions.size(); + for (MouseWatcherGroup *group : _groups) { + count += group->get_num_regions(); } out << " (" << count << " regions)"; @@ -505,20 +509,16 @@ output(ostream &out) const { * */ void MouseWatcher:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "MouseWatcher " << get_name() << ":\n"; MouseWatcherBase::write(out, indent_level + 2); LightMutexHolder holder(_lock); - if (!_groups.empty()) { - Groups::const_iterator gi; - for (gi = _groups.begin(); gi != _groups.end(); ++gi) { - MouseWatcherGroup *group = (*gi); - indent(out, indent_level + 2) - << "Subgroup:\n"; - group->write(out, indent_level + 4); - } + for (MouseWatcherGroup *group : _groups) { + indent(out, indent_level + 2) + << "Subgroup:\n"; + group->write(out, indent_level + 4); } } @@ -540,9 +540,12 @@ get_over_regions(MouseWatcher::Regions ®ions, const LPoint2 &pos) const { // Ensure the vector is empty before we begin. regions.clear(); - Regions::const_iterator ri; - for (ri = _regions.begin(); ri != _regions.end(); ++ri) { - MouseWatcherRegion *region = (*ri); + // Make sure there are no duplicates in the regions vector. + if (!_sorted) { + ((MouseWatcher *)this)->do_sort_regions(); + } + + for (MouseWatcherRegion *region : _regions) { const LVecBase4 &frame = region->get_frame(); if (region->get_active() && @@ -554,11 +557,10 @@ get_over_regions(MouseWatcher::Regions ®ions, const LPoint2 &pos) const { } // Also check all of our sub-groups. - Groups::const_iterator gi; - for (gi = _groups.begin(); gi != _groups.end(); ++gi) { - MouseWatcherGroup *group = (*gi); - for (ri = group->_regions.begin(); ri != group->_regions.end(); ++ri) { - MouseWatcherRegion *region = (*ri); + for (MouseWatcherGroup *group : _groups) { + group->sort_regions(); + + for (MouseWatcherRegion *region : group->_regions) { const LVecBase4 &frame = region->get_frame(); if (region->get_active() && @@ -584,7 +586,7 @@ get_over_regions(MouseWatcher::Regions ®ions, const LPoint2 &pos) const { MouseWatcherRegion *MouseWatcher:: get_preferred_region(const MouseWatcher::Regions ®ions) { if (regions.empty()) { - return (MouseWatcherRegion *)NULL; + return nullptr; } Regions::const_iterator ri; @@ -625,7 +627,7 @@ set_current_regions(MouseWatcher::Regions ®ions) { // Queue up all the new regions so we can send the within patterns all at // once, after all of the without patterns have been thrown. - vector new_regions; + std::vector new_regions; bool any_changes = false; while (new_ri != regions.end() && old_ri != _current_regions.end()) { @@ -672,7 +674,7 @@ set_current_regions(MouseWatcher::Regions ®ions) { _current_regions.swap(regions); // And don't forget to throw all of the new regions' "within" events. - vector::const_iterator ri; + std::vector::const_iterator ri; for (ri = new_regions.begin(); ri != new_regions.end(); ++ri) { MouseWatcherRegion *new_region = (*ri); within_region(new_region, param); @@ -689,15 +691,15 @@ set_current_regions(MouseWatcher::Regions ®ions) { if (_button_down && new_preferred_region != _preferred_button_down_region) { // If the button's being held down, we're only allowed to select the // preferred button down region. - new_preferred_region = (MouseWatcherRegion *)NULL; + new_preferred_region = nullptr; } if (new_preferred_region != _preferred_region) { - if (_preferred_region != (MouseWatcherRegion *)NULL) { + if (_preferred_region != nullptr) { exit_region(_preferred_region, param); } _preferred_region = new_preferred_region; - if (_preferred_region != (MouseWatcherRegion *)NULL) { + if (_preferred_region != nullptr) { enter_region(_preferred_region, param); } } @@ -729,10 +731,10 @@ clear_current_regions() { _current_regions.clear(); - if (_preferred_region != (MouseWatcherRegion *)NULL) { + if (_preferred_region != nullptr) { _preferred_region->exit_region(param); throw_event_pattern(_leave_pattern, _preferred_region, ButtonHandle::none()); - _preferred_region = (MouseWatcherRegion *)NULL; + _preferred_region = nullptr; } } } @@ -750,9 +752,7 @@ do_show_regions(const NodePath &render2d, const string &bin_name, _show_regions_bin_name = bin_name; _show_regions_draw_order = draw_order; - Groups::const_iterator gi; - for (gi = _groups.begin(); gi != _groups.end(); ++gi) { - MouseWatcherGroup *group = (*gi); + for (MouseWatcherGroup *group : _groups) { group->show_regions(render2d, bin_name, draw_order); } } @@ -770,9 +770,7 @@ do_hide_regions() { _show_regions_bin_name = string(); _show_regions_draw_order = 0; - Groups::const_iterator gi; - for (gi = _groups.begin(); gi != _groups.end(); ++gi) { - MouseWatcherGroup *group = (*gi); + for (MouseWatcherGroup *group : _groups) { group->hide_regions(); } } @@ -859,7 +857,7 @@ throw_event_pattern(const string &pattern, const MouseWatcherRegion *region, return; } #ifndef NDEBUG - if (region != (MouseWatcherRegion *)NULL) { + if (region != nullptr) { region->test_ref_count_integrity(); } #endif @@ -880,7 +878,7 @@ throw_event_pattern(const string &pattern, const MouseWatcherRegion *region, string cmd = pattern.substr(p + 1, 1); p++; if (cmd == "r") { - if (region != (MouseWatcherRegion *)NULL) { + if (region != nullptr) { event += region->get_name(); } @@ -898,7 +896,7 @@ throw_event_pattern(const string &pattern, const MouseWatcherRegion *region, if (!event.empty()) { throw_event(event, EventParameter(region), EventParameter(button_name)); - if (_eh != (EventHandler*)0L) + if (_eh != nullptr) throw_event_directly(*_eh, event, EventParameter(region), EventParameter(button_name)); } @@ -916,7 +914,7 @@ move() { param.set_modifier_buttons(_mods); param.set_mouse(_mouse); - if (_preferred_button_down_region != (MouseWatcherRegion *)NULL) { + if (_preferred_button_down_region != nullptr) { _preferred_button_down_region->move(param); } } @@ -942,7 +940,7 @@ press(ButtonHandle button, bool keyrepeat) { } _button_down = true; - if (_preferred_button_down_region != (MouseWatcherRegion *)NULL) { + if (_preferred_button_down_region != nullptr) { _preferred_button_down_region->press(param); if (keyrepeat) { throw_event_pattern(_button_repeat_pattern, @@ -956,7 +954,7 @@ press(ButtonHandle button, bool keyrepeat) { } else { // It's a keyboard button; therefore, send the event to every region that // wants keyboard buttons, regardless of the mouse position. - if (_preferred_region != (MouseWatcherRegion *)NULL) { + if (_preferred_region != nullptr) { // Our current region, the one under the mouse, always get all the // keyboard events, even if it doesn't set its keyboard flag. _preferred_region->press(param); @@ -992,7 +990,7 @@ release(ButtonHandle button) { // There is some danger of losing button-up events here. If more than one // button goes down together, we won't detect both of the button-up events // properly. - if (_preferred_button_down_region != (MouseWatcherRegion *)NULL) { + if (_preferred_button_down_region != nullptr) { param.set_outside(_preferred_button_down_region != _preferred_region); _preferred_button_down_region->release(param); throw_event_pattern(_button_up_pattern, @@ -1000,12 +998,12 @@ release(ButtonHandle button) { } _button_down = false; - _preferred_button_down_region = (MouseWatcherRegion *)NULL; + _preferred_button_down_region = nullptr; } else { // It's a keyboard button; therefore, send the event to every region that // wants keyboard buttons, regardless of the mouse position. - if (_preferred_region != (MouseWatcherRegion *)NULL) { + if (_preferred_region != nullptr) { _preferred_region->release(param); } @@ -1026,15 +1024,17 @@ keystroke(int keycode) { param.set_modifier_buttons(_mods); param.set_mouse(_mouse); + // Make sure there are no duplicates in the regions vector. + if (!_sorted) { + ((MouseWatcher *)this)->do_sort_regions(); + } + // Keystrokes go to all those regions that want keyboard events, regardless // of which is the "preferred" region (that is, without respect to the mouse // position). However, we do set the outside flag according to whether the // given region is the preferred region or not. - Regions::const_iterator ri; - for (ri = _regions.begin(); ri != _regions.end(); ++ri) { - MouseWatcherRegion *region = (*ri); - + for (MouseWatcherRegion *region : _regions) { if (region->get_keyboard()) { param.set_outside(region != _preferred_region); region->keystroke(param); @@ -1043,12 +1043,10 @@ keystroke(int keycode) { } // Also check all of our sub-groups. - Groups::const_iterator gi; - for (gi = _groups.begin(); gi != _groups.end(); ++gi) { - MouseWatcherGroup *group = (*gi); - for (ri = group->_regions.begin(); ri != group->_regions.end(); ++ri) { - MouseWatcherRegion *region = (*ri); + for (MouseWatcherGroup *group : _groups) { + group->sort_regions(); + for (MouseWatcherRegion *region : group->_regions) { if (region->get_keyboard()) { param.set_outside(region != _preferred_region); region->keystroke(param); @@ -1063,7 +1061,7 @@ keystroke(int keycode) { * IME. */ void MouseWatcher:: -candidate(const wstring &candidate_string, size_t highlight_start, +candidate(const std::wstring &candidate_string, size_t highlight_start, size_t highlight_end, size_t cursor_pos) { nassertv(_lock.debug_is_locked()); @@ -1072,13 +1070,15 @@ candidate(const wstring &candidate_string, size_t highlight_start, param.set_modifier_buttons(_mods); param.set_mouse(_mouse); + // Make sure there are no duplicates in the regions vector. + if (!_sorted) { + ((MouseWatcher *)this)->do_sort_regions(); + } + // Candidate strings go to all those regions that want keyboard events, // exactly like keystrokes, above. - Regions::const_iterator ri; - for (ri = _regions.begin(); ri != _regions.end(); ++ri) { - MouseWatcherRegion *region = (*ri); - + for (MouseWatcherRegion *region : _regions) { if (region->get_keyboard()) { param.set_outside(region != _preferred_region); region->candidate(param); @@ -1086,12 +1086,10 @@ candidate(const wstring &candidate_string, size_t highlight_start, } // Also check all of our sub-groups. - Groups::const_iterator gi; - for (gi = _groups.begin(); gi != _groups.end(); ++gi) { - MouseWatcherGroup *group = (*gi); - for (ri = group->_regions.begin(); ri != group->_regions.end(); ++ri) { - MouseWatcherRegion *region = (*ri); + for (MouseWatcherGroup *group : _groups) { + group->sort_regions(); + for (MouseWatcherRegion *region : group->_regions) { if (region->get_keyboard()) { param.set_outside(region != _preferred_region); region->candidate(param); @@ -1109,10 +1107,12 @@ void MouseWatcher:: global_keyboard_press(const MouseWatcherParameter ¶m) { nassertv(_lock.debug_is_locked()); - Regions::const_iterator ri; - for (ri = _regions.begin(); ri != _regions.end(); ++ri) { - MouseWatcherRegion *region = (*ri); + // Make sure there are no duplicates in the regions vector. + if (!_sorted) { + ((MouseWatcher *)this)->do_sort_regions(); + } + for (MouseWatcherRegion *region : _regions) { if (region != _preferred_region && region->get_keyboard()) { region->press(param); consider_keyboard_suppress(region); @@ -1120,12 +1120,10 @@ global_keyboard_press(const MouseWatcherParameter ¶m) { } // Also check all of our sub-groups. - Groups::const_iterator gi; - for (gi = _groups.begin(); gi != _groups.end(); ++gi) { - MouseWatcherGroup *group = (*gi); - for (ri = group->_regions.begin(); ri != group->_regions.end(); ++ri) { - MouseWatcherRegion *region = (*ri); + for (MouseWatcherGroup *group : _groups) { + group->sort_regions(); + for (MouseWatcherRegion *region : group->_regions) { if (region != _preferred_region && region->get_keyboard()) { region->press(param); consider_keyboard_suppress(region); @@ -1142,22 +1140,22 @@ void MouseWatcher:: global_keyboard_release(const MouseWatcherParameter ¶m) { nassertv(_lock.debug_is_locked()); - Regions::const_iterator ri; - for (ri = _regions.begin(); ri != _regions.end(); ++ri) { - MouseWatcherRegion *region = (*ri); + // Make sure there are no duplicates in the regions vector. + if (!_sorted) { + ((MouseWatcher *)this)->do_sort_regions(); + } + for (MouseWatcherRegion *region : _regions) { if (region != _preferred_region && region->get_keyboard()) { region->release(param); } } // Also check all of our sub-groups. - Groups::const_iterator gi; - for (gi = _groups.begin(); gi != _groups.end(); ++gi) { - MouseWatcherGroup *group = (*gi); - for (ri = group->_regions.begin(); ri != group->_regions.end(); ++ri) { - MouseWatcherRegion *region = (*ri); + for (MouseWatcherGroup *group : _groups) { + group->sort_regions(); + for (MouseWatcherRegion *region : group->_regions) { if (region != _preferred_region && region->get_keyboard()) { region->release(param); } @@ -1302,7 +1300,7 @@ do_transmit_data(DataGraphTraverser *trav, const DataNodeTransmit &input, move(); } - if (_display_region != (DisplayRegion *)NULL) { + if (_display_region != nullptr) { // If we've got a display region, constrain the mouse to it. if (constrain_display_region(_display_region, f, p, current_thread)) { set_mouse(f, p); @@ -1348,7 +1346,7 @@ do_transmit_data(DataGraphTraverser *trav, const DataNodeTransmit &input, // If the mouse is over a particular region, or still considered owned by a // region because of a recent button-down event, that region determines // whether we suppress events below us. - if (_preferred_region != (MouseWatcherRegion *)NULL) { + if (_preferred_region != nullptr) { _internal_suppress |= _preferred_region->get_suppress_flags(); } @@ -1547,9 +1545,9 @@ constrain_display_region(DisplayRegion *display_region, LVecBase2 &f, LVecBase2 &p, Thread *current_thread) { if (!_button_down) { - _button_down_display_region = NULL; + _button_down_display_region = nullptr; } - if (_button_down_display_region != NULL) { + if (_button_down_display_region != nullptr) { // If the button went down over this DisplayRegion, we consider the button // within the same DisplayRegion until it is released (even if it wanders // outside the borders). @@ -1574,7 +1572,7 @@ constrain_display_region(DisplayRegion *display_region, PN_stdfloat x = (f[0] + 1.0f) / 2.0f; PN_stdfloat y = (f[1] + 1.0f) / 2.0f; - if (_button_down_display_region == NULL && + if (_button_down_display_region == nullptr && (x < left || x >= right || y < bottom || y >= top)) { // The mouse is outside the display region. return false; diff --git a/panda/src/tform/mouseWatcher.h b/panda/src/tform/mouseWatcher.h index c3b4988b7f..9f21f3d09b 100644 --- a/panda/src/tform/mouseWatcher.h +++ b/panda/src/tform/mouseWatcher.h @@ -60,7 +60,7 @@ class DisplayRegion; */ class EXPCL_PANDA_TFORM MouseWatcher : public DataNode, public MouseWatcherBase { PUBLISHED: - explicit MouseWatcher(const string &name = ""); + explicit MouseWatcher(const std::string &name = ""); ~MouseWatcher(); bool remove_region(MouseWatcherRegion *region); @@ -85,26 +85,26 @@ PUBLISHED: INLINE bool is_button_down(ButtonHandle button) const; - INLINE void set_button_down_pattern(const string &pattern); - INLINE const string &get_button_down_pattern() const; + INLINE void set_button_down_pattern(const std::string &pattern); + INLINE const std::string &get_button_down_pattern() const; - INLINE void set_button_up_pattern(const string &pattern); - INLINE const string &get_button_up_pattern() const; + INLINE void set_button_up_pattern(const std::string &pattern); + INLINE const std::string &get_button_up_pattern() const; - INLINE void set_button_repeat_pattern(const string &pattern); - INLINE const string &get_button_repeat_pattern() const; + INLINE void set_button_repeat_pattern(const std::string &pattern); + INLINE const std::string &get_button_repeat_pattern() const; - INLINE void set_enter_pattern(const string &pattern); - INLINE const string &get_enter_pattern() const; + INLINE void set_enter_pattern(const std::string &pattern); + INLINE const std::string &get_enter_pattern() const; - INLINE void set_leave_pattern(const string &pattern); - INLINE const string &get_leave_pattern() const; + INLINE void set_leave_pattern(const std::string &pattern); + INLINE const std::string &get_leave_pattern() const; - INLINE void set_within_pattern(const string &pattern); - INLINE const string &get_within_pattern() const; + INLINE void set_within_pattern(const std::string &pattern); + INLINE const std::string &get_within_pattern() const; - INLINE void set_without_pattern(const string &pattern); - INLINE const string &get_without_pattern() const; + INLINE void set_without_pattern(const std::string &pattern); + INLINE const std::string &get_without_pattern() const; INLINE void set_geometry(PandaNode *node); INLINE bool has_geometry() const; @@ -134,8 +134,8 @@ PUBLISHED: INLINE double get_inactivity_timeout() const; INLINE void clear_inactivity_timeout(); - INLINE void set_inactivity_timeout_event(const string &event); - INLINE const string &get_inactivity_timeout_event() const; + INLINE void set_inactivity_timeout_event(const std::string &event); + INLINE const std::string &get_inactivity_timeout_event() const; INLINE CPT(PointerEventList) get_trail_log() const; INLINE int num_trail_recent() const; @@ -147,8 +147,8 @@ PUBLISHED: void note_activity(); public: - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; protected: void get_over_regions(Regions ®ions, const LPoint2 &pos) const; @@ -159,7 +159,7 @@ protected: #ifndef NDEBUG virtual void do_show_regions(const NodePath &render2d, - const string &bin_name, int draw_order); + const std::string &bin_name, int draw_order); virtual void do_hide_regions(); #endif // NDEBUG @@ -173,7 +173,7 @@ protected: static bool has_region_in(const Regions ®ions, MouseWatcherRegion *region); - void throw_event_pattern(const string &pattern, + void throw_event_pattern(const std::string &pattern, const MouseWatcherRegion *region, const ButtonHandle &button); @@ -181,7 +181,7 @@ protected: void press(ButtonHandle button, bool keyrepeat); void release(ButtonHandle button); void keystroke(int keycode); - void candidate(const wstring &candidate, size_t highlight_start, + void candidate(const std::wstring &candidate, size_t highlight_start, size_t highlight_end, size_t cursor_pos); void global_keyboard_press(const MouseWatcherParameter ¶m); @@ -232,13 +232,13 @@ private: bool _enter_multiple; bool _implicit_click; - string _button_down_pattern; - string _button_up_pattern; - string _button_repeat_pattern; - string _enter_pattern; - string _leave_pattern; - string _within_pattern; - string _without_pattern; + std::string _button_down_pattern; + std::string _button_up_pattern; + std::string _button_repeat_pattern; + std::string _enter_pattern; + std::string _leave_pattern; + std::string _within_pattern; + std::string _without_pattern; PT(PandaNode) _geometry; @@ -249,7 +249,7 @@ private: bool _has_inactivity_timeout; double _inactivity_timeout; - string _inactivity_timeout_event; + std::string _inactivity_timeout_event; double _last_activity; enum InactivityState { @@ -262,7 +262,7 @@ private: #ifndef NDEBUG NodePath _show_regions_render2d; - string _show_regions_bin_name; + std::string _show_regions_bin_name; int _show_regions_draw_order; #endif diff --git a/panda/src/tform/mouseWatcherBase.I b/panda/src/tform/mouseWatcherBase.I new file mode 100644 index 0000000000..e5739d1de5 --- /dev/null +++ b/panda/src/tform/mouseWatcherBase.I @@ -0,0 +1,32 @@ +/** + * PANDA 3D SOFTWARE + * Copyright (c) Carnegie Mellon University. All rights reserved. + * + * All use of this software is subject to the terms of the revised BSD + * license. You should have received a copy of this license along + * with this source code in a file named "LICENSE." + * + * @file mouseWatcherBase.I + * @author rdb + * @date 2018-06-12 + */ + +/** + * Sorts all the regions in this group into pointer order. + */ +INLINE void MouseWatcherBase:: +sort_regions() { + LightMutexHolder holder(_lock); + if (!_sorted) { + do_sort_regions(); + } +} + +/** + * Returns true if the group has already been sorted, false otherwise. + */ +INLINE bool MouseWatcherBase:: +is_sorted() const { + LightMutexHolder holder(_lock); + return _sorted; +} diff --git a/panda/src/tform/mouseWatcherBase.cxx b/panda/src/tform/mouseWatcherBase.cxx index 6d86c384f1..6137ad9b3e 100644 --- a/panda/src/tform/mouseWatcherBase.cxx +++ b/panda/src/tform/mouseWatcherBase.cxx @@ -40,34 +40,31 @@ MouseWatcherBase:: } /** - * Adds the indicated region to the set of regions in the group. It is an - * error to add the same region to the set more than once. + * Adds the indicated region to the set of regions in the group. It is no + * longer an error to call this for the same region more than once. */ void MouseWatcherBase:: -add_region(MouseWatcherRegion *region) { - PT(MouseWatcherRegion) pt = region; - +add_region(PT(MouseWatcherRegion) region) { LightMutexHolder holder(_lock); - // We will only bother to check for duplicates in the region list if we are - // building a development Panda. The overhead for doing this may be too - // high if we have many regions. -#ifdef _DEBUG - // See if the region is in the setvector already - Regions::const_iterator ri = - find(_regions.begin(), _regions.end(), pt); - nassertv(ri == _regions.end()); -#endif // _DEBUG - #ifndef NDEBUG // Also add it to the vizzes if we have them. - if (_show_regions) { - nassertv(_vizzes.size() == _regions.size()); - _vizzes.push_back(make_viz_region(pt)); + if (UNLIKELY(_show_regions)) { + // We need to check whether it is already in the set, so that we don't + // create a duplicate viz. + Regions::const_iterator ri = + std::find(_regions.begin(), _regions.end(), region); + + if (ri == _regions.end()) { + nassertv(_vizzes.size() == _regions.size()); + _vizzes.push_back(make_viz_region(region)); + } else { + return; + } } #endif // NDEBUG - _regions.push_back(pt); + _regions.push_back(std::move(region)); _sorted = false; } @@ -108,18 +105,16 @@ remove_region(MouseWatcherRegion *region) { * indeterminate. */ MouseWatcherRegion *MouseWatcherBase:: -find_region(const string &name) const { +find_region(const std::string &name) const { LightMutexHolder holder(_lock); - Regions::const_iterator ri; - for (ri = _regions.begin(); ri != _regions.end(); ++ri) { - MouseWatcherRegion *region = (*ri); + for (MouseWatcherRegion *region : _regions) { if (region->get_name() == name) { return region; } } - return (MouseWatcherRegion *)NULL; + return nullptr; } /** @@ -140,32 +135,16 @@ clear_regions() { #endif // NDEBUG } -/** - * Sorts all the regions in this group into pointer order. - */ -void MouseWatcherBase:: -sort_regions() { - LightMutexHolder holder(_lock); - do_sort_regions(); -} - -/** - * Returns true if the group has already been sorted, false otherwise. - */ -bool MouseWatcherBase:: -is_sorted() const { - LightMutexHolder holder(_lock); - - return _sorted; -} - /** * Returns the number of regions in the group. */ -int MouseWatcherBase:: +size_t MouseWatcherBase:: get_num_regions() const { LightMutexHolder holder(_lock); - + if (!_sorted) { + // Remove potential duplicates to get an accurate count. + ((MouseWatcherBase *)this)->do_sort_regions(); + } return _regions.size(); } @@ -175,19 +154,22 @@ get_num_regions() const { * removed the nth region before you called this method. */ MouseWatcherRegion *MouseWatcherBase:: -get_region(int n) const { +get_region(size_t n) const { LightMutexHolder holder(_lock); - if (n >= 0 && n < (int)_regions.size()) { + if (!_sorted) { + ((MouseWatcherBase *)this)->do_sort_regions(); + } + if (n < _regions.size()) { return _regions[n]; } - return NULL; + return nullptr; } /** * */ void MouseWatcherBase:: -output(ostream &out) const { +output(std::ostream &out) const { out << "MouseWatcherGroup (" << _regions.size() << " regions)"; } @@ -195,12 +177,10 @@ output(ostream &out) const { * */ void MouseWatcherBase:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { LightMutexHolder holder(_lock); - Regions::const_iterator ri; - for (ri = _regions.begin(); ri != _regions.end(); ++ri) { - MouseWatcherRegion *region = (*ri); + for (MouseWatcherRegion *region : _regions) { region->write(out, indent_level); } } @@ -212,7 +192,7 @@ write(ostream &out, int indent_level) const { * scene graph for the window. */ void MouseWatcherBase:: -show_regions(const NodePath &render2d, const string &bin_name, int draw_order) { +show_regions(const NodePath &render2d, const std::string &bin_name, int draw_order) { LightMutexHolder holder(_lock); do_show_regions(render2d, bin_name, draw_order); } @@ -262,7 +242,7 @@ update_regions() { void MouseWatcherBase:: do_sort_regions() { if (!_sorted) { - sort(_regions.begin(), _regions.end()); + _regions.sort_unique(); _sorted = true; } } @@ -312,7 +292,7 @@ do_remove_region(MouseWatcherRegion *region) { * already held. */ void MouseWatcherBase:: -do_show_regions(const NodePath &render2d, const string &bin_name, +do_show_regions(const NodePath &render2d, const std::string &bin_name, int draw_order) { do_hide_regions(); _show_regions = true; @@ -345,13 +325,15 @@ do_update_regions() { nassertv(_lock.debug_is_locked()); if (_show_regions) { + // Make sure we have no duplicates. + do_sort_regions(); + _show_regions_root.node()->remove_all_children(); _vizzes.clear(); _vizzes.reserve(_regions.size()); - Regions::const_iterator ri; - for (ri = _regions.begin(); ri != _regions.end(); ++ri) { - _vizzes.push_back(make_viz_region(*ri)); + for (MouseWatcherRegion *region : _regions) { + _vizzes.push_back(make_viz_region(region)); } } } @@ -366,7 +348,7 @@ do_update_regions() { */ PandaNode *MouseWatcherBase:: make_viz_region(MouseWatcherRegion *region) { - nassertr(_lock.debug_is_locked(), NULL); + nassertr(_lock.debug_is_locked(), nullptr); LineSegs ls("show_regions"); ls.set_color(_color); diff --git a/panda/src/tform/mouseWatcherBase.h b/panda/src/tform/mouseWatcherBase.h index 8836f57023..b7de361653 100644 --- a/panda/src/tform/mouseWatcherBase.h +++ b/panda/src/tform/mouseWatcherBase.h @@ -21,6 +21,7 @@ #include "pvector.h" #include "nodePath.h" #include "lightMutex.h" +#include "ordered_vector.h" /** * This represents a collection of MouseWatcherRegions that may be managed as @@ -34,27 +35,27 @@ public: virtual ~MouseWatcherBase(); PUBLISHED: - void add_region(MouseWatcherRegion *region); + void add_region(PT(MouseWatcherRegion) region); bool has_region(MouseWatcherRegion *region) const; bool remove_region(MouseWatcherRegion *region); - MouseWatcherRegion *find_region(const string &name) const; + MouseWatcherRegion *find_region(const std::string &name) const; void clear_regions(); - void sort_regions(); - bool is_sorted() const; + INLINE void sort_regions(); + INLINE bool is_sorted() const; MAKE_PROPERTY(sorted, is_sorted); - int get_num_regions() const; - MouseWatcherRegion *get_region(int n) const; + size_t get_num_regions() const; + MouseWatcherRegion *get_region(size_t n) const; MAKE_SEQ(get_regions, get_num_regions, get_region); MAKE_SEQ_PROPERTY(regions, get_num_regions, get_region); - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; #ifndef NDEBUG void show_regions(const NodePath &render2d, - const string &bin_name, int draw_order); + const std::string &bin_name, int draw_order); void set_color(const LColor &color); void hide_regions(); @@ -67,13 +68,13 @@ protected: #ifndef NDEBUG virtual void do_show_regions(const NodePath &render2d, - const string &bin_name, int draw_order); + const std::string &bin_name, int draw_order); virtual void do_hide_regions(); void do_update_regions(); #endif // NDEBUG protected: - typedef pvector< PT(MouseWatcherRegion) > Regions; + typedef ov_set< PT(MouseWatcherRegion) > Regions; Regions _regions; bool _sorted; @@ -109,4 +110,6 @@ private: friend class BlobWatcher; }; +#include "mouseWatcherBase.I" + #endif diff --git a/panda/src/tform/mouseWatcherParameter.I b/panda/src/tform/mouseWatcherParameter.I index 4983fcfda0..49d6314e91 100644 --- a/panda/src/tform/mouseWatcherParameter.I +++ b/panda/src/tform/mouseWatcherParameter.I @@ -88,7 +88,7 @@ set_keycode(int keycode) { * Sets the candidate string associated with this event, if any. */ INLINE void MouseWatcherParameter:: -set_candidate(const wstring &candidate_string, +set_candidate(const std::wstring &candidate_string, size_t highlight_start, size_t highlight_end, size_t cursor_pos) { _candidate_string = candidate_string; @@ -188,7 +188,7 @@ has_candidate() const { * Returns the candidate string associated with this event. If * has_candidate(), above, returns false, this returns the empty string. */ -INLINE const wstring &MouseWatcherParameter:: +INLINE const std::wstring &MouseWatcherParameter:: get_candidate_string() const { return _candidate_string; } @@ -197,7 +197,7 @@ get_candidate_string() const { * Returns the candidate string associated with this event. If * has_candidate(), above, returns false, this returns the empty string. */ -INLINE string MouseWatcherParameter:: +INLINE std::string MouseWatcherParameter:: get_candidate_string_encoded() const { return get_candidate_string_encoded(TextEncoder::get_default_encoding()); } @@ -206,7 +206,7 @@ get_candidate_string_encoded() const { * Returns the candidate string associated with this event. If * has_candidate(), above, returns false, this returns the empty string. */ -INLINE string MouseWatcherParameter:: +INLINE std::string MouseWatcherParameter:: get_candidate_string_encoded(TextEncoder::Encoding encoding) const { return TextEncoder::encode_wtext(_candidate_string, encoding); } @@ -274,8 +274,8 @@ is_outside() const { return (_flags & F_is_outside) != 0; } -INLINE ostream & -operator << (ostream &out, const MouseWatcherParameter &parm) { +INLINE std::ostream & +operator << (std::ostream &out, const MouseWatcherParameter &parm) { parm.output(out); return out; } diff --git a/panda/src/tform/mouseWatcherParameter.cxx b/panda/src/tform/mouseWatcherParameter.cxx index c1a697375e..9cc502694a 100644 --- a/panda/src/tform/mouseWatcherParameter.cxx +++ b/panda/src/tform/mouseWatcherParameter.cxx @@ -17,7 +17,7 @@ * */ void MouseWatcherParameter:: -output(ostream &out) const { +output(std::ostream &out) const { bool output_anything = false; if (has_button()) { diff --git a/panda/src/tform/mouseWatcherParameter.h b/panda/src/tform/mouseWatcherParameter.h index 1da5dcfc45..8ea454d4f2 100644 --- a/panda/src/tform/mouseWatcherParameter.h +++ b/panda/src/tform/mouseWatcherParameter.h @@ -35,7 +35,7 @@ public: INLINE void set_button(const ButtonHandle &button); INLINE void set_keyrepeat(bool flag); INLINE void set_keycode(int keycode); - INLINE void set_candidate(const wstring &candidate_string, + INLINE void set_candidate(const std::wstring &candidate_string, size_t highlight_start, size_t higlight_end, size_t cursor_pos); @@ -54,11 +54,11 @@ PUBLISHED: INLINE bool has_candidate() const; public: - INLINE const wstring &get_candidate_string() const; + INLINE const std::wstring &get_candidate_string() const; PUBLISHED: - INLINE string get_candidate_string_encoded() const; - INLINE string get_candidate_string_encoded(TextEncoder::Encoding encoding) const; + INLINE std::string get_candidate_string_encoded() const; + INLINE std::string get_candidate_string_encoded(TextEncoder::Encoding encoding) const; INLINE size_t get_highlight_start() const; INLINE size_t get_highlight_end() const; INLINE size_t get_cursor_pos() const; @@ -70,12 +70,12 @@ PUBLISHED: INLINE bool is_outside() const; - void output(ostream &out) const; + void output(std::ostream &out) const; public: ButtonHandle _button; int _keycode; - wstring _candidate_string; + std::wstring _candidate_string; size_t _highlight_start; size_t _highlight_end; size_t _cursor_pos; @@ -93,7 +93,7 @@ public: int _flags; }; -INLINE ostream &operator << (ostream &out, const MouseWatcherParameter &parm); +INLINE std::ostream &operator << (std::ostream &out, const MouseWatcherParameter &parm); #include "mouseWatcherParameter.I" diff --git a/panda/src/tform/mouseWatcherRegion.I b/panda/src/tform/mouseWatcherRegion.I index cdcc71d51e..50dfada487 100644 --- a/panda/src/tform/mouseWatcherRegion.I +++ b/panda/src/tform/mouseWatcherRegion.I @@ -15,7 +15,7 @@ * */ INLINE MouseWatcherRegion:: -MouseWatcherRegion(const string &name, PN_stdfloat left, PN_stdfloat right, +MouseWatcherRegion(const std::string &name, PN_stdfloat left, PN_stdfloat right, PN_stdfloat bottom, PN_stdfloat top) : Namable(name), _frame(left, right, bottom, top) @@ -28,7 +28,7 @@ MouseWatcherRegion(const string &name, PN_stdfloat left, PN_stdfloat right, * */ INLINE MouseWatcherRegion:: -MouseWatcherRegion(const string &name, const LVecBase4 &frame) : +MouseWatcherRegion(const std::string &name, const LVecBase4 &frame) : Namable(name), _frame(frame) { diff --git a/panda/src/tform/mouseWatcherRegion.cxx b/panda/src/tform/mouseWatcherRegion.cxx index b9905a4715..2b7465041c 100644 --- a/panda/src/tform/mouseWatcherRegion.cxx +++ b/panda/src/tform/mouseWatcherRegion.cxx @@ -22,7 +22,7 @@ TypeHandle MouseWatcherRegion::_type_handle; * */ void MouseWatcherRegion:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_name() << " lrbt = " << _frame; } @@ -30,7 +30,7 @@ output(ostream &out) const { * */ void MouseWatcherRegion:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_name() << " lrbt = " << _frame << ", sort = " << _sort << "\n"; diff --git a/panda/src/tform/mouseWatcherRegion.h b/panda/src/tform/mouseWatcherRegion.h index 0230c42d96..a49cfcbc6e 100644 --- a/panda/src/tform/mouseWatcherRegion.h +++ b/panda/src/tform/mouseWatcherRegion.h @@ -30,9 +30,9 @@ class MouseWatcherParameter; */ class EXPCL_PANDA_TFORM MouseWatcherRegion : public TypedWritableReferenceCount, public Namable { PUBLISHED: - INLINE explicit MouseWatcherRegion(const string &name, PN_stdfloat left, PN_stdfloat right, + INLINE explicit MouseWatcherRegion(const std::string &name, PN_stdfloat left, PN_stdfloat right, PN_stdfloat bottom, PN_stdfloat top); - INLINE explicit MouseWatcherRegion(const string &name, const LVecBase4 &frame); + INLINE explicit MouseWatcherRegion(const std::string &name, const LVecBase4 &frame); INLINE void set_frame(PN_stdfloat left, PN_stdfloat right, PN_stdfloat bottom, PN_stdfloat top); INLINE void set_frame(const LVecBase4 &frame); @@ -58,8 +58,8 @@ PUBLISHED: INLINE void set_suppress_flags(int suppress_flags); INLINE int get_suppress_flags() const; - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; public: INLINE bool operator < (const MouseWatcherRegion &other) const; @@ -108,7 +108,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const MouseWatcherRegion ®ion) { +INLINE std::ostream &operator << (std::ostream &out, const MouseWatcherRegion ®ion) { region.output(out); return out; } diff --git a/panda/src/tform/trackball.cxx b/panda/src/tform/trackball.cxx index 620b52950b..b56e1d47fe 100644 --- a/panda/src/tform/trackball.cxx +++ b/panda/src/tform/trackball.cxx @@ -34,7 +34,7 @@ TypeHandle Trackball::_type_handle; * */ Trackball:: -Trackball(const string &name) : +Trackball(const std::string &name) : MouseInterfaceNode(name) { _pixel_xy_input = define_input("pixel_xy", EventStoreVec2::get_class_type()); diff --git a/panda/src/tform/trackball.h b/panda/src/tform/trackball.h index 634e81f61a..0ef01f6b8e 100644 --- a/panda/src/tform/trackball.h +++ b/panda/src/tform/trackball.h @@ -34,7 +34,7 @@ */ class EXPCL_PANDA_TFORM Trackball : public MouseInterfaceNode { PUBLISHED: - explicit Trackball(const string &name); + explicit Trackball(const std::string &name); ~Trackball(); void reset(); diff --git a/panda/src/tform/transform2sg.cxx b/panda/src/tform/transform2sg.cxx index 6adfb944c4..61f734521f 100644 --- a/panda/src/tform/transform2sg.cxx +++ b/panda/src/tform/transform2sg.cxx @@ -23,12 +23,12 @@ TypeHandle Transform2SG::_type_handle; * */ Transform2SG:: -Transform2SG(const string &name) : +Transform2SG(const std::string &name) : DataNode(name) { _transform_input = define_input("transform", TransformState::get_class_type()); - _node = NULL; + _node = nullptr; } /** @@ -65,7 +65,7 @@ do_transmit_data(DataGraphTraverser *trav, const DataNodeTransmit &input, if (input.has_data(_transform_input)) { const TransformState *transform; DCAST_INTO_V(transform, input.get_data(_transform_input).get_ptr()); - if (_node != (PandaNode *)NULL) { + if (_node != nullptr) { _node->set_transform(transform, current_thread); } } diff --git a/panda/src/tform/transform2sg.h b/panda/src/tform/transform2sg.h index 66939aa096..a385abb428 100644 --- a/panda/src/tform/transform2sg.h +++ b/panda/src/tform/transform2sg.h @@ -27,7 +27,7 @@ */ class EXPCL_PANDA_TFORM Transform2SG : public DataNode { PUBLISHED: - explicit Transform2SG(const string &name); + explicit Transform2SG(const std::string &name); void set_node(PandaNode *node); PandaNode *get_node() const; diff --git a/panda/src/tinydisplay/clip.cxx b/panda/src/tinydisplay/clip.cxx index da20a86adc..f2c6baa4ba 100644 --- a/panda/src/tinydisplay/clip.cxx +++ b/panda/src/tinydisplay/clip.cxx @@ -11,6 +11,8 @@ #define CLIP_ZMIN (1<<4) #define CLIP_ZMAX (1<<5) +using std::min; + void gl_transform_to_viewport(GLContext *c,GLVertex *v) { PN_stdfloat winv; diff --git a/panda/src/tinydisplay/init.cxx b/panda/src/tinydisplay/init.cxx index 2e11dee3c2..40ca74c31c 100644 --- a/panda/src/tinydisplay/init.cxx +++ b/panda/src/tinydisplay/init.cxx @@ -18,7 +18,7 @@ void glInit(GLContext *c, ZBuffer *zbuffer) v->updated=1; /* lights */ - c->first_light=NULL; + c->first_light=nullptr; c->ambient_light_model=gl_V4_New(0.2, 0.2, 0.2, 1.0f); c->local_light_model=0; c->lighting_enabled=0; @@ -50,7 +50,7 @@ void glInit(GLContext *c, ZBuffer *zbuffer) c->cull_face_enabled=0; /* specular buffer */ - c->specbuf_first = NULL; + c->specbuf_first = nullptr; c->specbuf_used_counter = 0; c->specbuf_num_buffers = 0; diff --git a/panda/src/tinydisplay/specbuf.cxx b/panda/src/tinydisplay/specbuf.cxx index d0c153714e..d058459e80 100644 --- a/panda/src/tinydisplay/specbuf.cxx +++ b/panda/src/tinydisplay/specbuf.cxx @@ -30,7 +30,7 @@ specbuf_get_buffer(GLContext *c, const int shininess_i, found->last_used = c->specbuf_used_counter++; return found; } - if (oldest == NULL || c->specbuf_num_buffers < MAX_SPECULAR_BUFFERS) { + if (oldest == nullptr || c->specbuf_num_buffers < MAX_SPECULAR_BUFFERS) { /* create new buffer */ GLSpecBuf *buf = (GLSpecBuf *)gl_malloc(sizeof(GLSpecBuf)); if (!buf) gl_fatal_error("could not allocate specular buffer"); diff --git a/panda/src/tinydisplay/store_pixel.cxx b/panda/src/tinydisplay/store_pixel.cxx index 07d5e7bdf4..4ffd8dde30 100644 --- a/panda/src/tinydisplay/store_pixel.cxx +++ b/panda/src/tinydisplay/store_pixel.cxx @@ -17,7 +17,7 @@ /* Pick up all of the generated code references to store_pixel.h. */ -#define STORE_PIX_CLAMP(x) (min((x), (unsigned int)0xffff)) +#define STORE_PIX_CLAMP(x) (std::min((x), (unsigned int)0xffff)) #include "store_pixel_table.h" #include "store_pixel_code.h" diff --git a/panda/src/tinydisplay/store_pixel.h b/panda/src/tinydisplay/store_pixel.h index 8352e842a4..d6fb1540c6 100644 --- a/panda/src/tinydisplay/store_pixel.h +++ b/panda/src/tinydisplay/store_pixel.h @@ -26,8 +26,8 @@ FNAME(store_pixel) (ZBuffer *zb, PIXEL &result, int r, int g, int b, int a) { r = STORE_PIXEL_0(fr, ((unsigned int)r * OP_A(fr, r) >> 16) + ((unsigned int)fr * OP_B(fr, r) >> 16)); g = STORE_PIXEL_1(fg, ((unsigned int)g * OP_A(fg, g) >> 16) + ((unsigned int)fg * OP_B(fg, g) >> 16)); - b = STORE_PIXEL_2(fg, ((unsigned int)b * OP_A(fb, b) >> 16) + ((unsigned int)fb * OP_B(fb, b) >> 16)); - a = STORE_PIXEL_3(fg, ((unsigned int)a * OP_A(fa, a) >> 16) + ((unsigned int)fa * OP_B(fa, a) >> 16)); + b = STORE_PIXEL_2(fb, ((unsigned int)b * OP_A(fb, b) >> 16) + ((unsigned int)fb * OP_B(fb, b) >> 16)); + a = STORE_PIXEL_3(fa, ((unsigned int)a * OP_A(fa, a) >> 16) + ((unsigned int)fa * OP_B(fa, a) >> 16)); result = RGBA_TO_PIXEL(r, g, b, a); } @@ -43,8 +43,8 @@ FNAME_S(store_pixel) (ZBuffer *zb, PIXEL &result, int r, int g, int b, int a) { r = STORE_PIXEL_0(fr, ((unsigned int)r * OP_A(fr, r) >> 16) + ((unsigned int)fr * OP_B(fr, r) >> 16)); g = STORE_PIXEL_1(fg, ((unsigned int)g * OP_A(fg, g) >> 16) + ((unsigned int)fg * OP_B(fg, g) >> 16)); - b = STORE_PIXEL_2(fg, ((unsigned int)b * OP_A(fb, b) >> 16) + ((unsigned int)fb * OP_B(fb, b) >> 16)); - a = STORE_PIXEL_3(fg, ((unsigned int)a * OP_A(fa, a) >> 16) + ((unsigned int)fa * OP_B(fa, a) >> 16)); + b = STORE_PIXEL_2(fb, ((unsigned int)b * OP_A(fb, b) >> 16) + ((unsigned int)fb * OP_B(fb, b) >> 16)); + a = STORE_PIXEL_3(fa, ((unsigned int)a * OP_A(fa, a) >> 16) + ((unsigned int)fa * OP_B(fa, a) >> 16)); result = SRGBA_TO_PIXEL(r, g, b, a); } diff --git a/panda/src/tinydisplay/td_light.cxx b/panda/src/tinydisplay/td_light.cxx index c49b47e4b4..c570e5347c 100644 --- a/panda/src/tinydisplay/td_light.cxx +++ b/panda/src/tinydisplay/td_light.cxx @@ -29,7 +29,7 @@ void gl_shade_vertex(GLContext *c,GLVertex *v) B=m->emission.v[2]+m->ambient.v[2]*c->ambient_light_model.v[2]; A=clampf(m->diffuse.v[3],0,1); - for(l=c->first_light;l!=NULL;l=l->next) { + for(l=c->first_light;l!=nullptr;l=l->next) { PN_stdfloat lR,lB,lG; /* ambient */ diff --git a/panda/src/tinydisplay/tinyGraphicsBuffer.cxx b/panda/src/tinydisplay/tinyGraphicsBuffer.cxx index adeceabd01..ea8e8241a6 100644 --- a/panda/src/tinydisplay/tinyGraphicsBuffer.cxx +++ b/panda/src/tinydisplay/tinyGraphicsBuffer.cxx @@ -25,7 +25,7 @@ TypeHandle TinyGraphicsBuffer::_type_handle; */ TinyGraphicsBuffer:: TinyGraphicsBuffer(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -33,7 +33,7 @@ TinyGraphicsBuffer(GraphicsEngine *engine, GraphicsPipe *pipe, GraphicsOutput *host) : GraphicsBuffer(engine, pipe, name, fb_prop, win_prop, flags, gsg, host) { - _frame_buffer = NULL; + _frame_buffer = nullptr; } /** @@ -52,7 +52,7 @@ TinyGraphicsBuffer:: bool TinyGraphicsBuffer:: begin_frame(FrameMode mode, Thread *current_thread) { begin_frame_spam(mode); - if (_gsg == (GraphicsStateGuardian *)NULL) { + if (_gsg == nullptr) { return false; } @@ -74,7 +74,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { void TinyGraphicsBuffer:: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); - nassertv(_gsg != (GraphicsStateGuardian *)NULL); + nassertv(_gsg != nullptr); if (mode == FM_render) { // end_render_texture(); @@ -94,10 +94,10 @@ end_frame(FrameMode mode, Thread *current_thread) { */ void TinyGraphicsBuffer:: close_buffer() { - if (_gsg != (GraphicsStateGuardian *)NULL) { + if (_gsg != nullptr) { TinyGraphicsStateGuardian *tinygsg; DCAST_INTO_V(tinygsg, _gsg); - tinygsg->_current_frame_buffer = NULL; + tinygsg->_current_frame_buffer = nullptr; _gsg.clear(); } @@ -114,14 +114,14 @@ open_buffer() { TinyGraphicsStateGuardian *tinygsg; if (_gsg == 0) { // There is no old gsg. Create a new one. - tinygsg = new TinyGraphicsStateGuardian(_engine, _pipe, NULL); + tinygsg = new TinyGraphicsStateGuardian(_engine, _pipe, nullptr); _gsg = tinygsg; } else { DCAST_INTO_R(tinygsg, _gsg, false); } create_frame_buffer(); - if (_frame_buffer == NULL) { + if (_frame_buffer == nullptr) { tinydisplay_cat.error() << "Could not create frame buffer.\n"; return false; @@ -144,9 +144,9 @@ open_buffer() { */ void TinyGraphicsBuffer:: create_frame_buffer() { - if (_frame_buffer != NULL) { + if (_frame_buffer != nullptr) { ZB_close(_frame_buffer); - _frame_buffer = NULL; + _frame_buffer = nullptr; } _frame_buffer = ZB_open(get_fb_x_size(), get_fb_y_size(), ZB_MODE_RGBA, 0, 0, 0, 0); diff --git a/panda/src/tinydisplay/tinyGraphicsBuffer.h b/panda/src/tinydisplay/tinyGraphicsBuffer.h index c7f7a1e61e..79c6e8c5e5 100644 --- a/panda/src/tinydisplay/tinyGraphicsBuffer.h +++ b/panda/src/tinydisplay/tinyGraphicsBuffer.h @@ -24,7 +24,7 @@ class EXPCL_TINYDISPLAY TinyGraphicsBuffer : public GraphicsBuffer { public: TinyGraphicsBuffer(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/tinydisplay/tinyGraphicsStateGuardian.I b/panda/src/tinydisplay/tinyGraphicsStateGuardian.I index cac827cf09..efda44e790 100644 --- a/panda/src/tinydisplay/tinyGraphicsStateGuardian.I +++ b/panda/src/tinydisplay/tinyGraphicsStateGuardian.I @@ -19,11 +19,11 @@ clear_light_state() { _c->lighting_enabled = false; #ifndef NDEBUG GLLight *gl_light = _c->first_light; - while (gl_light != (GLLight *)NULL) { + while (gl_light != nullptr) { GLLight *next = gl_light->next; - gl_light->next = NULL; + gl_light->next = nullptr; gl_light = next; } #endif // NDEBUG - _c->first_light = NULL; + _c->first_light = nullptr; } diff --git a/panda/src/tinydisplay/tinyGraphicsStateGuardian.cxx b/panda/src/tinydisplay/tinyGraphicsStateGuardian.cxx index a9c6b113a2..8f49433ebd 100644 --- a/panda/src/tinydisplay/tinyGraphicsStateGuardian.cxx +++ b/panda/src/tinydisplay/tinyGraphicsStateGuardian.cxx @@ -40,6 +40,9 @@ #include "store_pixel_table.h" #include "graphicsEngine.h" +using std::max; +using std::min; + TypeHandle TinyGraphicsStateGuardian::_type_handle; PStatCollector TinyGraphicsStateGuardian::_vertices_immediate_pcollector("Vertices:Immediate mode"); @@ -64,10 +67,10 @@ TinyGraphicsStateGuardian(GraphicsEngine *engine, GraphicsPipe *pipe, TinyGraphicsStateGuardian *share_with) : GraphicsStateGuardian(CS_yup_right, engine, pipe) { - _current_frame_buffer = NULL; - _aux_frame_buffer = NULL; - _c = NULL; - _vertices = NULL; + _current_frame_buffer = nullptr; + _aux_frame_buffer = nullptr; + _c = nullptr; + _vertices = nullptr; _vertices_size = 0; } @@ -99,9 +102,9 @@ reset() { _inv_state_mask.clear_bit(LightAttrib::get_class_slot()); _inv_state_mask.clear_bit(ScissorAttrib::get_class_slot()); - if (_c != (GLContext *)NULL) { + if (_c != nullptr) { glClose(_c); - _c = NULL; + _c = nullptr; } _c = (GLContext *)gl_zalloc(sizeof(GLContext)); @@ -142,14 +145,14 @@ reset() { */ void TinyGraphicsStateGuardian:: free_pointers() { - if (_aux_frame_buffer != (ZBuffer *)NULL) { + if (_aux_frame_buffer != nullptr) { ZB_close(_aux_frame_buffer); - _aux_frame_buffer = NULL; + _aux_frame_buffer = nullptr; } - if (_vertices != (GLVertex *)NULL) { + if (_vertices != nullptr) { PANDA_FREE_ARRAY(_vertices); - _vertices = NULL; + _vertices = nullptr; } _vertices_size = 0; } @@ -163,9 +166,9 @@ void TinyGraphicsStateGuardian:: close_gsg() { GraphicsStateGuardian::close_gsg(); - if (_c != (GLContext *)NULL) { + if (_c != nullptr) { glClose(_c); - _c = NULL; + _c = nullptr; } } @@ -245,7 +248,7 @@ clear(DrawableRegion *clearable) { */ void TinyGraphicsStateGuardian:: prepare_display_region(DisplayRegionPipelineReader *dr) { - nassertv(dr != (DisplayRegionPipelineReader *)NULL); + nassertv(dr != nullptr); GraphicsStateGuardian::prepare_display_region(dr); int xmin, ymin, xsize, ysize; @@ -259,10 +262,10 @@ prepare_display_region(DisplayRegionPipelineReader *dr) { ymin = 0; xsize = int(xsize * pixel_factor); ysize = int(ysize * pixel_factor); - if (_aux_frame_buffer == (ZBuffer *)NULL) { + if (_aux_frame_buffer == nullptr) { _aux_frame_buffer = ZB_open(xsize, ysize, ZB_MODE_RGBA, 0, 0, 0, 0); } else if (_aux_frame_buffer->xsize < xsize || _aux_frame_buffer->ysize < ysize) { - ZB_resize(_aux_frame_buffer, NULL, + ZB_resize(_aux_frame_buffer, nullptr, max(_aux_frame_buffer->xsize, xsize), max(_aux_frame_buffer->ysize, ysize)); } @@ -295,12 +298,12 @@ prepare_display_region(DisplayRegionPipelineReader *dr) { */ CPT(TransformState) TinyGraphicsStateGuardian:: calc_projection_mat(const Lens *lens) { - if (lens == (Lens *)NULL) { - return NULL; + if (lens == nullptr) { + return nullptr; } if (!lens->is_linear()) { - return NULL; + return nullptr; } // The projection matrix must always be right-handed Y-up, even if our @@ -481,7 +484,7 @@ begin_draw_primitives(const GeomPipelineReader *geom_reader, if (!GraphicsStateGuardian::begin_draw_primitives(geom_reader, data_reader, force)) { return false; } - nassertr(_data_reader != (GeomVertexDataPipelineReader *)NULL, false); + nassertr(_data_reader != nullptr, false); PStatTimer timer(_draw_transform_pcollector); @@ -557,7 +560,7 @@ begin_draw_primitives(const GeomPipelineReader *geom_reader, while (_vertices_size < num_used_vertices) { _vertices_size *= 2; } - if (_vertices != (GLVertex *)NULL) { + if (_vertices != nullptr) { PANDA_FREE_ARRAY(_vertices); } _vertices = (GLVertex *)PANDA_MALLOC_ARRAY(_vertices_size * sizeof(GLVertex)); @@ -697,7 +700,6 @@ begin_draw_primitives(const GeomPipelineReader *geom_reader, // Texture coordinates. for (int si = 0; si < max_stage_index; ++si) { - LTexCoord d; (*texgen_func[si])(v->tex_coord[si], tcdata[si]); } @@ -961,7 +963,7 @@ draw_triangles(const GeomPrimitivePipelineReader *reader, bool force) { case Geom::NT_uint8: { uint8_t *index = (uint8_t *)reader->get_read_pointer(force); - if (index == NULL) { + if (index == nullptr) { return false; } for (int i = 0; i < num_vertices; i += 3) { @@ -976,7 +978,7 @@ draw_triangles(const GeomPrimitivePipelineReader *reader, bool force) { case Geom::NT_uint16: { uint16_t *index = (uint16_t *)reader->get_read_pointer(force); - if (index == NULL) { + if (index == nullptr) { return false; } for (int i = 0; i < num_vertices; i += 3) { @@ -991,7 +993,7 @@ draw_triangles(const GeomPrimitivePipelineReader *reader, bool force) { case Geom::NT_uint32: { uint32_t *index = (uint32_t *)reader->get_read_pointer(force); - if (index == NULL) { + if (index == nullptr) { return false; } for (int i = 0; i < num_vertices; i += 3) { @@ -1052,7 +1054,7 @@ draw_tristrips(const GeomPrimitivePipelineReader *reader, bool force) { case Geom::NT_uint8: { uint8_t *index = (uint8_t *)reader->get_read_pointer(force); - if (index == NULL) { + if (index == nullptr) { return false; } GLVertex *v0 = &_vertices[index[start] - _min_vertex]; @@ -1077,7 +1079,7 @@ draw_tristrips(const GeomPrimitivePipelineReader *reader, bool force) { case Geom::NT_uint16: { uint16_t *index = (uint16_t *)reader->get_read_pointer(force); - if (index == NULL) { + if (index == nullptr) { return false; } GLVertex *v0 = &_vertices[index[start] - _min_vertex]; @@ -1102,7 +1104,7 @@ draw_tristrips(const GeomPrimitivePipelineReader *reader, bool force) { case Geom::NT_uint32: { uint32_t *index = (uint32_t *)reader->get_read_pointer(force); - if (index == NULL) { + if (index == nullptr) { return false; } GLVertex *v0 = &_vertices[index[start] - _min_vertex]; @@ -1183,7 +1185,7 @@ draw_lines(const GeomPrimitivePipelineReader *reader, bool force) { case Geom::NT_uint8: { uint8_t *index = (uint8_t *)reader->get_read_pointer(force); - if (index == NULL) { + if (index == nullptr) { return false; } for (int i = 0; i < num_vertices; i += 2) { @@ -1197,7 +1199,7 @@ draw_lines(const GeomPrimitivePipelineReader *reader, bool force) { case Geom::NT_uint16: { uint16_t *index = (uint16_t *)reader->get_read_pointer(force); - if (index == NULL) { + if (index == nullptr) { return false; } for (int i = 0; i < num_vertices; i += 2) { @@ -1211,7 +1213,7 @@ draw_lines(const GeomPrimitivePipelineReader *reader, bool force) { case Geom::NT_uint32: { uint32_t *index = (uint32_t *)reader->get_read_pointer(force); - if (index == NULL) { + if (index == nullptr) { return false; } for (int i = 0; i < num_vertices; i += 2) { @@ -1260,7 +1262,7 @@ draw_points(const GeomPrimitivePipelineReader *reader, bool force) { case Geom::NT_uint8: { uint8_t *index = (uint8_t *)reader->get_read_pointer(force); - if (index == NULL) { + if (index == nullptr) { return false; } for (int i = 0; i < num_vertices; ++i) { @@ -1273,7 +1275,7 @@ draw_points(const GeomPrimitivePipelineReader *reader, bool force) { case Geom::NT_uint16: { uint16_t *index = (uint16_t *)reader->get_read_pointer(force); - if (index == NULL) { + if (index == nullptr) { return false; } for (int i = 0; i < num_vertices; ++i) { @@ -1286,7 +1288,7 @@ draw_points(const GeomPrimitivePipelineReader *reader, bool force) { case Geom::NT_uint32: { uint32_t *index = (uint32_t *)reader->get_read_pointer(force); - if (index == NULL) { + if (index == nullptr) { return false; } for (int i = 0; i < num_vertices; ++i) { @@ -1347,7 +1349,7 @@ bool TinyGraphicsStateGuardian:: framebuffer_copy_to_texture(Texture *tex, int view, int z, const DisplayRegion *dr, const RenderBuffer &rb) { - nassertr(tex != NULL && dr != NULL, false); + nassertr(tex != nullptr && dr != nullptr, false); int xo, yo, w, h; dr->get_region_pixels_i(xo, yo, w, h); @@ -1355,7 +1357,7 @@ framebuffer_copy_to_texture(Texture *tex, int view, int z, tex->setup_2d_texture(w, h, Texture::T_unsigned_byte, Texture::F_rgba); TextureContext *tc = tex->prepare_now(view, get_prepared_objects(), this); - nassertr(tc != (TextureContext *)NULL, false); + nassertr(tc != nullptr, false); TinyTextureContext *gtc = DCAST(TinyTextureContext, tc); GLTexture *gltex = >c->_gltex; @@ -1395,7 +1397,7 @@ bool TinyGraphicsStateGuardian:: framebuffer_copy_to_ram(Texture *tex, int view, int z, const DisplayRegion *dr, const RenderBuffer &rb) { - nassertr(tex != NULL && dr != NULL, false); + nassertr(tex != nullptr && dr != nullptr, false); int xo, yo, w, h; dr->get_region_pixels_i(xo, yo, w, h); @@ -1611,7 +1613,7 @@ prepare_texture(Texture *tex, int view) { tinydisplay_cat.info() << "Not loading texture " << tex->get_name() << ": " << tex->get_texture_type() << "\n"; - return NULL; + return nullptr; } // Even though the texture might be compressed now, it might have an @@ -1764,7 +1766,7 @@ do_issue_light() { // Handle the diffuse color here, since all lights have this property. GLLight *gl_light = _c->first_light; - nassertv(gl_light != NULL); + nassertv(gl_light != nullptr); const LColor &diffuse = light_obj->get_color(); gl_light->diffuse.v[0] = diffuse[0]; gl_light->diffuse.v[1] = diffuse[1]; @@ -1791,7 +1793,7 @@ do_issue_light() { */ void TinyGraphicsStateGuardian:: bind_light(PointLight *light_obj, const NodePath &light, int light_id) { - pair lookup = _plights.insert(Lights::value_type(light, GLLight())); + std::pair lookup = _plights.insert(Lights::value_type(light, GLLight())); GLLight *gl_light = &(*lookup.first).second; if (lookup.second) { // It's a brand new light. Define it. @@ -1829,7 +1831,7 @@ bind_light(PointLight *light_obj, const NodePath &light, int light_id) { gl_light->attenuation[2] = att[2]; } - nassertv(gl_light->next == NULL); + nassertv(gl_light->next == nullptr); // Add it to the linked list of active lights. gl_light->next = _c->first_light; @@ -1843,7 +1845,7 @@ bind_light(PointLight *light_obj, const NodePath &light, int light_id) { */ void TinyGraphicsStateGuardian:: bind_light(DirectionalLight *light_obj, const NodePath &light, int light_id) { - pair lookup = _dlights.insert(Lights::value_type(light, GLLight())); + std::pair lookup = _dlights.insert(Lights::value_type(light, GLLight())); GLLight *gl_light = &(*lookup.first).second; if (lookup.second) { // It's a brand new light. Define it. @@ -1888,7 +1890,7 @@ bind_light(DirectionalLight *light_obj, const NodePath &light, int light_id) { gl_light->attenuation[2] = 0.0f; } - nassertv(gl_light->next == NULL); + nassertv(gl_light->next == nullptr); // Add it to the linked list of active lights. gl_light->next = _c->first_light; @@ -1902,7 +1904,7 @@ bind_light(DirectionalLight *light_obj, const NodePath &light, int light_id) { */ void TinyGraphicsStateGuardian:: bind_light(Spotlight *light_obj, const NodePath &light, int light_id) { - pair lookup = _plights.insert(Lights::value_type(light, GLLight())); + std::pair lookup = _plights.insert(Lights::value_type(light, GLLight())); GLLight *gl_light = &(*lookup.first).second; if (lookup.second) { // It's a brand new light. Define it. @@ -1915,7 +1917,7 @@ bind_light(Spotlight *light_obj, const NodePath &light, int light_id) { gl_light->specular.v[3] = specular[3]; Lens *lens = light_obj->get_lens(); - nassertv(lens != (Lens *)NULL); + nassertv(lens != nullptr); // Position needs to specify x, y, z, and w w == 1 implies non-infinite // position @@ -1953,7 +1955,7 @@ bind_light(Spotlight *light_obj, const NodePath &light, int light_id) { gl_light->attenuation[2] = att[2]; } - nassertv(gl_light->next == NULL); + nassertv(gl_light->next == nullptr); // Add it to the linked list of active lights. gl_light->next = _c->first_light; @@ -2011,7 +2013,7 @@ do_issue_render_mode() { default: tinydisplay_cat.error() - << "Unknown render mode " << (int)target_render_mode->get_mode() << endl; + << "Unknown render mode " << (int)target_render_mode->get_mode() << std::endl; } } @@ -2044,7 +2046,7 @@ do_issue_rescale_normal() { default: tinydisplay_cat.error() - << "Unknown rescale_normal mode " << (int)mode << endl; + << "Unknown rescale_normal mode " << (int)mode << std::endl; } } @@ -2090,7 +2092,7 @@ do_issue_cull_face() { break; default: tinydisplay_cat.error() - << "invalid cull face mode " << (int)mode << endl; + << "invalid cull face mode " << (int)mode << std::endl; break; } } @@ -2105,7 +2107,7 @@ do_issue_material() { const MaterialAttrib *target_material = DCAST(MaterialAttrib, _target_rs->get_attrib_def(MaterialAttrib::get_class_slot())); const Material *material; - if (target_material == (MaterialAttrib *)NULL || + if (target_material == nullptr || target_material->is_off()) { material = ∅ } else { @@ -2149,11 +2151,11 @@ do_issue_texture() { for (int si = 0; si < num_stages; ++si) { TextureStage *stage = _target_texture->get_on_ff_stage(si); Texture *texture = _target_texture->get_on_texture(stage); - nassertv(texture != (Texture *)NULL); + nassertv(texture != nullptr); int view = get_current_tex_view_offset() + stage->get_tex_view_offset(); TextureContext *tc = texture->prepare_now(view, _prepared_objects, this); - if (tc == (TextureContext *)NULL) { + if (tc == nullptr) { // Something wrong with this texture; skip it. return; } @@ -2249,10 +2251,10 @@ do_issue_texture() { // The following special cases are handled inline, rather than relying // on the above wrap function pointers. - if (wrap_u && SamplerState::WM_border_color && wrap_v == SamplerState::WM_border_color) { + if (wrap_u == SamplerState::WM_border_color && wrap_v == SamplerState::WM_border_color) { texture_def->tex_minfilter_func = apply_wrap_border_color_minfilter; texture_def->tex_magfilter_func = apply_wrap_border_color_magfilter; - } else if (wrap_u && SamplerState::WM_clamp && wrap_v == SamplerState::WM_clamp) { + } else if (wrap_u == SamplerState::WM_clamp && wrap_v == SamplerState::WM_clamp) { texture_def->tex_minfilter_func = apply_wrap_clamp_minfilter; texture_def->tex_magfilter_func = apply_wrap_clamp_magfilter; } @@ -2524,10 +2526,10 @@ bool TinyGraphicsStateGuardian:: upload_simple_texture(TinyTextureContext *gtc) { PStatTimer timer(_load_texture_pcollector); Texture *tex = gtc->get_texture(); - nassertr(tex != (Texture *)NULL, false); + nassertr(tex != nullptr, false); const unsigned char *image_ptr = tex->get_simple_ram_image(); - if (image_ptr == (const unsigned char *)NULL) { + if (image_ptr == nullptr) { return false; } @@ -2616,7 +2618,7 @@ setup_gltex(GLTexture *gltex, int x_size, int y_size, int num_levels) { } if (gltex->total_bytecount != total_bytecount) { - if (gltex->allocated_buffer != NULL) { + if (gltex->allocated_buffer != nullptr) { TinyTextureContext::get_class_type().deallocate_array(gltex->allocated_buffer); } gltex->allocated_buffer = TinyTextureContext::get_class_type().allocate_array(total_bytecount); @@ -2627,7 +2629,7 @@ setup_gltex(GLTexture *gltex, int x_size, int y_size, int num_levels) { char *end_of_buffer = next_buffer + total_bytecount; int level = 0; - ZTextureLevel *dest = NULL; + ZTextureLevel *dest = nullptr; while (level < num_levels) { dest = &gltex->levels[level]; int bytecount = x_size * y_size * 4; @@ -2705,7 +2707,7 @@ copy_lum_image(ZTextureLevel *dest, int xsize, int ysize, TinyTextureContext *gt #endif unsigned int *dpix = (unsigned int *)dest->pixmap; - nassertv(dpix != NULL); + nassertv(dpix != nullptr); const unsigned char *spix = src; int pixel_count = xsize * ysize; while (pixel_count-- > 0) { @@ -2741,7 +2743,7 @@ copy_alpha_image(ZTextureLevel *dest, int xsize, int ysize, TinyTextureContext * #endif unsigned int *dpix = (unsigned int *)dest->pixmap; - nassertv(dpix != NULL); + nassertv(dpix != nullptr); const unsigned char *spix = src; int pixel_count = xsize * ysize; while (pixel_count-- > 0) { @@ -2777,7 +2779,7 @@ copy_one_channel_image(ZTextureLevel *dest, int xsize, int ysize, TinyTextureCon #endif unsigned int *dpix = (unsigned int *)dest->pixmap; - nassertv(dpix != NULL); + nassertv(dpix != nullptr); const unsigned char *spix = src; int pixel_count = xsize * ysize; @@ -2842,7 +2844,7 @@ copy_la_image(ZTextureLevel *dest, int xsize, int ysize, TinyTextureContext *gtc #endif unsigned int *dpix = (unsigned int *)dest->pixmap; - nassertv(dpix != NULL); + nassertv(dpix != nullptr); const unsigned char *spix = src; int pixel_count = xsize * ysize; int inc = 2 * cw; @@ -2879,7 +2881,7 @@ copy_rgb_image(ZTextureLevel *dest, int xsize, int ysize, TinyTextureContext *gt #endif unsigned int *dpix = (unsigned int *)dest->pixmap; - nassertv(dpix != NULL); + nassertv(dpix != nullptr); const unsigned char *spix = src; int pixel_count = xsize * ysize; int inc = 3 * cw; @@ -2916,7 +2918,7 @@ copy_rgba_image(ZTextureLevel *dest, int xsize, int ysize, TinyTextureContext *g #endif unsigned int *dpix = (unsigned int *)dest->pixmap; - nassertv(dpix != NULL); + nassertv(dpix != nullptr); const unsigned char *spix = src; int pixel_count = xsize * ysize; int inc = 4 * cw; diff --git a/panda/src/tinydisplay/tinyOffscreenGraphicsPipe.cxx b/panda/src/tinydisplay/tinyOffscreenGraphicsPipe.cxx index c1fbe12b67..901d874c6d 100644 --- a/panda/src/tinydisplay/tinyOffscreenGraphicsPipe.cxx +++ b/panda/src/tinydisplay/tinyOffscreenGraphicsPipe.cxx @@ -43,7 +43,7 @@ TinyOffscreenGraphicsPipe:: * choose between several possible GraphicsPipes available on a particular * platform, so the name should be meaningful and unique for a given platform. */ -string TinyOffscreenGraphicsPipe:: +std::string TinyOffscreenGraphicsPipe:: get_interface_name() const { return "TinyPanda"; } @@ -61,7 +61,7 @@ pipe_constructor() { * Creates a new window on the pipe, if possible. */ PT(GraphicsOutput) TinyOffscreenGraphicsPipe:: -make_output(const string &name, +make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -75,11 +75,11 @@ make_output(const string &name, if (retry == 0) { if (((flags&BF_require_parasite)!=0)|| ((flags&BF_require_window)!=0)) { - return NULL; + return nullptr; } return new TinyGraphicsBuffer(engine, this, name, fb_prop, win_prop, flags, gsg, host); } // Nothing else left to try. - return NULL; + return nullptr; } diff --git a/panda/src/tinydisplay/tinyOffscreenGraphicsPipe.h b/panda/src/tinydisplay/tinyOffscreenGraphicsPipe.h index 21395b1e62..94d4eb8d73 100644 --- a/panda/src/tinydisplay/tinyOffscreenGraphicsPipe.h +++ b/panda/src/tinydisplay/tinyOffscreenGraphicsPipe.h @@ -31,11 +31,11 @@ public: TinyOffscreenGraphicsPipe(); virtual ~TinyOffscreenGraphicsPipe(); - virtual string get_interface_name() const; + virtual std::string get_interface_name() const; static PT(GraphicsPipe) pipe_constructor(); protected: - virtual PT(GraphicsOutput) make_output(const string &name, + virtual PT(GraphicsOutput) make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/tinydisplay/tinyOsxGraphicsPipe.cxx b/panda/src/tinydisplay/tinyOsxGraphicsPipe.cxx index cdb1b90f1f..349fad4398 100644 --- a/panda/src/tinydisplay/tinyOsxGraphicsPipe.cxx +++ b/panda/src/tinydisplay/tinyOsxGraphicsPipe.cxx @@ -48,7 +48,7 @@ TinyOsxGraphicsPipe:: * choose between several possible GraphicsPipes available on a particular * platform, so the name should be meaningful and unique for a given platform. */ -string TinyOsxGraphicsPipe:: +std::string TinyOsxGraphicsPipe:: get_interface_name() const { return "TinyPanda"; } @@ -86,7 +86,7 @@ create_cg_image(const PNMImage &pnm_image) { bool has_alpha; bool is_grayscale; - CFStringRef color_space_name = NULL; + CFStringRef color_space_name = nullptr; switch (pnm_image.get_color_type()) { case PNMImage::CT_grayscale: color_space_name = kCGColorSpaceGenericGray; @@ -114,13 +114,13 @@ create_cg_image(const PNMImage &pnm_image) { case PNMImage::CT_invalid: // Shouldn't get here. - nassertr(false, NULL); + nassertr(false, nullptr); break; } - nassertr(color_space_name != NULL, NULL); + nassertr(color_space_name != nullptr, nullptr); CGColorSpaceRef color_space = CGColorSpaceCreateWithName(color_space_name); - nassertr(color_space != NULL, NULL); + nassertr(color_space != nullptr, nullptr); CGBitmapInfo bitmap_info = 0; #ifdef PGM_BIGGRAYS @@ -148,17 +148,17 @@ create_cg_image(const PNMImage &pnm_image) { } } } - nassertr((void *)dp == (void *)(char_array + num_bytes), NULL); + nassertr((void *)dp == (void *)(char_array + num_bytes), nullptr); CGDataProviderRef provider = - CGDataProviderCreateWithData(NULL, char_array, num_bytes, release_data); - nassertr(provider != NULL, NULL); + CGDataProviderCreateWithData(nullptr, char_array, num_bytes, release_data); + nassertr(provider != nullptr, nullptr); CGImageRef image = CGImageCreate (width, height, bits_per_component, bits_per_pixel, bytes_per_row, color_space, bitmap_info, provider, - NULL, false, kCGRenderingIntentDefault); - nassertr(image != NULL, NULL); + nullptr, false, kCGRenderingIntentDefault); + nassertr(image != nullptr, nullptr); CGColorSpaceRelease(color_space); CGDataProviderRelease(provider); @@ -181,7 +181,7 @@ release_data(void *info, const void *data, size_t size) { * only called from GraphicsEngine::make_output. */ PT(GraphicsOutput) TinyOsxGraphicsPipe:: -make_output(const string &name, +make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -192,12 +192,12 @@ make_output(const string &name, bool &precertify) { if (!_is_valid) { - return NULL; + return nullptr; } TinyGraphicsStateGuardian *tinygsg = 0; if (gsg != 0) { - DCAST_INTO_R(tinygsg, gsg, NULL); + DCAST_INTO_R(tinygsg, gsg, nullptr); } // First thing to try: a TinyOsxGraphicsWindow @@ -210,22 +210,22 @@ make_output(const string &name, ((flags&BF_rtt_cumulative)!=0)|| ((flags&BF_can_bind_color)!=0)|| ((flags&BF_can_bind_every)!=0)) { - return NULL; + return nullptr; } if ((flags & BF_fb_props_optional)==0) { if ((fb_prop.get_aux_rgba() > 0)|| (fb_prop.get_aux_hrgba() > 0)|| (fb_prop.get_aux_float() > 0)) { - return NULL; + return nullptr; } } WindowHandle *window_handle = win_prop.get_parent_window(); - if (window_handle != NULL) { + if (window_handle != nullptr) { tinydisplay_cat.info() << "Got parent_window " << *window_handle << "\n"; #ifdef SUPPORT_SUBPROCESS_WINDOW WindowHandle::OSHandle *os_handle = window_handle->get_os_handle(); - if (os_handle != NULL && + if (os_handle != nullptr && os_handle->is_of_type(NativeWindowHandle::SubprocessHandle::get_class_type())) { return new SubprocessWindow(engine, this, name, fb_prop, win_prop, flags, gsg, host); @@ -240,13 +240,13 @@ make_output(const string &name, if (retry == 1) { if (((flags&BF_require_parasite)!=0)|| ((flags&BF_require_window)!=0)) { - return NULL; + return nullptr; } return new TinyGraphicsBuffer(engine, this, name, fb_prop, win_prop, flags, gsg, host); } // Nothing else left to try. - return NULL; + return nullptr; } #endif // IS_OSX diff --git a/panda/src/tinydisplay/tinyOsxGraphicsPipe.h b/panda/src/tinydisplay/tinyOsxGraphicsPipe.h index f0781dfb5b..14cc0aded0 100644 --- a/panda/src/tinydisplay/tinyOsxGraphicsPipe.h +++ b/panda/src/tinydisplay/tinyOsxGraphicsPipe.h @@ -35,7 +35,7 @@ public: TinyOsxGraphicsPipe(); virtual ~TinyOsxGraphicsPipe(); - virtual string get_interface_name() const; + virtual std::string get_interface_name() const; static PT(GraphicsPipe) pipe_constructor(); static CGImageRef create_cg_image(const PNMImage &pnm_image); @@ -44,7 +44,7 @@ private: static void release_data(void *info, const void *data, size_t size); protected: - virtual PT(GraphicsOutput) make_output(const string &name, + virtual PT(GraphicsOutput) make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/tinydisplay/tinyOsxGraphicsWindow.h b/panda/src/tinydisplay/tinyOsxGraphicsWindow.h index 1d61868c9c..71682c9a3b 100644 --- a/panda/src/tinydisplay/tinyOsxGraphicsWindow.h +++ b/panda/src/tinydisplay/tinyOsxGraphicsWindow.h @@ -30,7 +30,7 @@ class TinyOsxGraphicsWindow : public GraphicsWindow { public: TinyOsxGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/tinydisplay/tinySDLGraphicsPipe.cxx b/panda/src/tinydisplay/tinySDLGraphicsPipe.cxx index 6189f61036..8a8ef6c54b 100644 --- a/panda/src/tinydisplay/tinySDLGraphicsPipe.cxx +++ b/panda/src/tinydisplay/tinySDLGraphicsPipe.cxx @@ -55,7 +55,7 @@ TinySDLGraphicsPipe:: * choose between several possible GraphicsPipes available on a particular * platform, so the name should be meaningful and unique for a given platform. */ -string TinySDLGraphicsPipe:: +std::string TinySDLGraphicsPipe:: get_interface_name() const { return "TinyPanda"; } @@ -73,7 +73,7 @@ pipe_constructor() { * Creates a new window on the pipe, if possible. */ PT(GraphicsOutput) TinySDLGraphicsPipe:: -make_output(const string &name, +make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -83,12 +83,12 @@ make_output(const string &name, int retry, bool &precertify) { if (!_is_valid) { - return NULL; + return nullptr; } TinyGraphicsStateGuardian *tinygsg = 0; if (gsg != 0) { - DCAST_INTO_R(tinygsg, gsg, NULL); + DCAST_INTO_R(tinygsg, gsg, nullptr); } // First thing to try: a TinySDLGraphicsWindow @@ -101,14 +101,14 @@ make_output(const string &name, ((flags&BF_rtt_cumulative)!=0)|| ((flags&BF_can_bind_color)!=0)|| ((flags&BF_can_bind_every)!=0)) { - return NULL; + return nullptr; } return new TinySDLGraphicsWindow(engine, this, name, fb_prop, win_prop, flags, gsg, host); } // Nothing else left to try. - return NULL; + return nullptr; } #endif // HAVE_SDL diff --git a/panda/src/tinydisplay/tinySDLGraphicsPipe.h b/panda/src/tinydisplay/tinySDLGraphicsPipe.h index 6897e51b6b..a3fc009647 100644 --- a/panda/src/tinydisplay/tinySDLGraphicsPipe.h +++ b/panda/src/tinydisplay/tinySDLGraphicsPipe.h @@ -32,11 +32,11 @@ public: TinySDLGraphicsPipe(); virtual ~TinySDLGraphicsPipe(); - virtual string get_interface_name() const; + virtual std::string get_interface_name() const; static PT(GraphicsPipe) pipe_constructor(); protected: - virtual PT(GraphicsOutput) make_output(const string &name, + virtual PT(GraphicsOutput) make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/tinydisplay/tinySDLGraphicsWindow.cxx b/panda/src/tinydisplay/tinySDLGraphicsWindow.cxx index 68ab836ec6..640adf3d5d 100644 --- a/panda/src/tinydisplay/tinySDLGraphicsWindow.cxx +++ b/panda/src/tinydisplay/tinySDLGraphicsWindow.cxx @@ -30,7 +30,7 @@ TypeHandle TinySDLGraphicsWindow::_type_handle; */ TinySDLGraphicsWindow:: TinySDLGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -38,8 +38,8 @@ TinySDLGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, GraphicsOutput *host) : GraphicsWindow(engine, pipe, name, fb_prop, win_prop, flags, gsg, host) { - _screen = NULL; - _frame_buffer = NULL; + _screen = nullptr; + _frame_buffer = nullptr; _pitch = 0; update_pixel_factor(); @@ -64,7 +64,7 @@ TinySDLGraphicsWindow:: bool TinySDLGraphicsWindow:: begin_frame(FrameMode mode, Thread *current_thread) { begin_frame_spam(mode); - if (_gsg == (GraphicsStateGuardian *)NULL) { + if (_gsg == nullptr) { return false; } @@ -86,7 +86,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { void TinySDLGraphicsWindow:: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); - nassertv(_gsg != (GraphicsStateGuardian *)NULL); + nassertv(_gsg != nullptr); if (mode == FM_render) { // end_render_texture(); @@ -137,7 +137,7 @@ end_flip() { SDL_CreateRGBSurfaceFrom(_frame_buffer->pbuf, _frame_buffer->xsize, _frame_buffer->ysize, 32, _frame_buffer->linesize, 0xff0000, 0x00ff00, 0x0000ff, 0xff000000); SDL_SetAlpha(temp, SDL_RLEACCEL, 0); - SDL_BlitSurface(temp, NULL, _screen, NULL); + SDL_BlitSurface(temp, nullptr, _screen, nullptr); SDL_FreeSurface(temp); } @@ -156,7 +156,7 @@ void TinySDLGraphicsWindow:: process_events() { GraphicsWindow::process_events(); - if (_screen == NULL) { + if (_screen == nullptr) { return; } @@ -203,7 +203,7 @@ process_events() { properties.set_size(evt.resize.w, evt.resize.h); system_changed_properties(properties); _screen = SDL_SetVideoMode(_properties.get_x_size(), _properties.get_y_size(), 32, _flags); - ZB_resize(_frame_buffer, NULL, _properties.get_x_size(), _properties.get_y_size()); + ZB_resize(_frame_buffer, nullptr, _properties.get_x_size(), _properties.get_y_size()); _pitch = _screen->pitch * 32 / _screen->format->BitsPerPixel; break; @@ -272,7 +272,7 @@ open_window() { TinyGraphicsStateGuardian *tinygsg; if (_gsg == 0) { // There is no old gsg. Create a new one. - tinygsg = new TinyGraphicsStateGuardian(_engine, _pipe, NULL); + tinygsg = new TinyGraphicsStateGuardian(_engine, _pipe, nullptr); _gsg = tinygsg; } else { @@ -291,14 +291,14 @@ open_window() { } _screen = SDL_SetVideoMode(_properties.get_x_size(), _properties.get_y_size(), 32, _flags); - if (_screen == NULL) { + if (_screen == nullptr) { tinydisplay_cat.error() << "Video mode set failed.\n"; return false; } create_frame_buffer(); - if (_frame_buffer == NULL) { + if (_frame_buffer == nullptr) { tinydisplay_cat.error() << "Could not create frame buffer.\n"; return false; @@ -320,9 +320,9 @@ open_window() { */ void TinySDLGraphicsWindow:: create_frame_buffer() { - if (_frame_buffer != NULL) { + if (_frame_buffer != nullptr) { ZB_close(_frame_buffer); - _frame_buffer = NULL; + _frame_buffer = nullptr; } int mode; diff --git a/panda/src/tinydisplay/tinySDLGraphicsWindow.h b/panda/src/tinydisplay/tinySDLGraphicsWindow.h index ae5793dcd4..b1be27b557 100644 --- a/panda/src/tinydisplay/tinySDLGraphicsWindow.h +++ b/panda/src/tinydisplay/tinySDLGraphicsWindow.h @@ -30,7 +30,7 @@ class EXPCL_TINYDISPLAY TinySDLGraphicsWindow : public GraphicsWindow { public: TinySDLGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/tinydisplay/tinyTextureContext.I b/panda/src/tinydisplay/tinyTextureContext.I index ca4f620db1..348c748228 100644 --- a/panda/src/tinydisplay/tinyTextureContext.I +++ b/panda/src/tinydisplay/tinyTextureContext.I @@ -19,6 +19,6 @@ TinyTextureContext(PreparedGraphicsObjects *pgo, Texture *tex, int view) : TextureContext(pgo, tex, view) { _gltex.num_levels = 0; - _gltex.allocated_buffer = NULL; + _gltex.allocated_buffer = nullptr; _gltex.total_bytecount = 0; } diff --git a/panda/src/tinydisplay/tinyTextureContext.cxx b/panda/src/tinydisplay/tinyTextureContext.cxx index 5a3ae3414d..d0207a1379 100644 --- a/panda/src/tinydisplay/tinyTextureContext.cxx +++ b/panda/src/tinydisplay/tinyTextureContext.cxx @@ -22,10 +22,10 @@ TypeHandle TinyTextureContext::_type_handle; TinyTextureContext:: ~TinyTextureContext() { GLTexture *gltex = &_gltex; - if (gltex->allocated_buffer != NULL) { + if (gltex->allocated_buffer != nullptr) { nassertv(gltex->num_levels != 0); get_class_type().deallocate_array(gltex->allocated_buffer); - gltex->allocated_buffer = NULL; + gltex->allocated_buffer = nullptr; gltex->total_bytecount = 0; gltex->num_levels = 0; } else { @@ -48,10 +48,10 @@ evict_lru() { dequeue_lru(); GLTexture *gltex = &_gltex; - if (gltex->allocated_buffer != NULL) { + if (gltex->allocated_buffer != nullptr) { nassertv(gltex->num_levels != 0); get_class_type().deallocate_array(gltex->allocated_buffer); - gltex->allocated_buffer = NULL; + gltex->allocated_buffer = nullptr; gltex->total_bytecount = 0; gltex->num_levels = 0; } else { diff --git a/panda/src/tinydisplay/tinyWinGraphicsPipe.cxx b/panda/src/tinydisplay/tinyWinGraphicsPipe.cxx index 2371d17ba8..adc51e6c9f 100644 --- a/panda/src/tinydisplay/tinyWinGraphicsPipe.cxx +++ b/panda/src/tinydisplay/tinyWinGraphicsPipe.cxx @@ -43,7 +43,7 @@ TinyWinGraphicsPipe:: * choose between several possible GraphicsPipes available on a particular * platform, so the name should be meaningful and unique for a given platform. */ -string TinyWinGraphicsPipe:: +std::string TinyWinGraphicsPipe:: get_interface_name() const { return "TinyPanda"; } @@ -62,7 +62,7 @@ pipe_constructor() { * only called from GraphicsEngine::make_output. */ PT(GraphicsOutput) TinyWinGraphicsPipe:: -make_output(const string &name, +make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -73,12 +73,12 @@ make_output(const string &name, bool &precertify) { if (!_is_valid) { - return NULL; + return nullptr; } TinyGraphicsStateGuardian *tinygsg = 0; if (gsg != 0) { - DCAST_INTO_R(tinygsg, gsg, NULL); + DCAST_INTO_R(tinygsg, gsg, nullptr); } // First thing to try: a TinyWinGraphicsWindow @@ -91,13 +91,13 @@ make_output(const string &name, ((flags&BF_rtt_cumulative)!=0)|| ((flags&BF_can_bind_color)!=0)|| ((flags&BF_can_bind_every)!=0)) { - return NULL; + return nullptr; } if ((flags & BF_fb_props_optional)==0) { if ((fb_prop.get_aux_rgba() > 0)|| (fb_prop.get_aux_hrgba() > 0)|| (fb_prop.get_aux_float() > 0)) { - return NULL; + return nullptr; } } return new TinyWinGraphicsWindow(engine, this, name, fb_prop, win_prop, @@ -108,14 +108,14 @@ make_output(const string &name, if (retry == 1) { if (((flags&BF_require_parasite)!=0)|| ((flags&BF_require_window)!=0)) { - return NULL; + return nullptr; } return new TinyGraphicsBuffer(engine, this, name, fb_prop, win_prop, flags, gsg, host); } // Nothing else left to try. - return NULL; + return nullptr; } #endif // WIN32 diff --git a/panda/src/tinydisplay/tinyWinGraphicsPipe.h b/panda/src/tinydisplay/tinyWinGraphicsPipe.h index fed6c7fa12..8626a9d675 100644 --- a/panda/src/tinydisplay/tinyWinGraphicsPipe.h +++ b/panda/src/tinydisplay/tinyWinGraphicsPipe.h @@ -30,11 +30,11 @@ public: TinyWinGraphicsPipe(); virtual ~TinyWinGraphicsPipe(); - virtual string get_interface_name() const; + virtual std::string get_interface_name() const; static PT(GraphicsPipe) pipe_constructor(); protected: - virtual PT(GraphicsOutput) make_output(const string &name, + virtual PT(GraphicsOutput) make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/tinydisplay/tinyWinGraphicsWindow.cxx b/panda/src/tinydisplay/tinyWinGraphicsWindow.cxx index afb7d1f016..ac16d45bf2 100644 --- a/panda/src/tinydisplay/tinyWinGraphicsWindow.cxx +++ b/panda/src/tinydisplay/tinyWinGraphicsWindow.cxx @@ -31,7 +31,7 @@ TypeHandle TinyWinGraphicsWindow::_type_handle; */ TinyWinGraphicsWindow:: TinyWinGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -39,7 +39,7 @@ TinyWinGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, GraphicsOutput *host) : WinGraphicsWindow(engine, pipe, name, fb_prop, win_prop, flags, gsg, host) { - _frame_buffer = NULL; + _frame_buffer = nullptr; _hdc = (HDC)0; update_pixel_factor(); } @@ -60,7 +60,7 @@ TinyWinGraphicsWindow:: bool TinyWinGraphicsWindow:: begin_frame(FrameMode mode, Thread *current_thread) { begin_frame_spam(mode); - if (_gsg == (GraphicsStateGuardian *)NULL) { + if (_gsg == nullptr) { return false; } @@ -90,7 +90,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { void TinyWinGraphicsWindow:: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); - nassertv(_gsg != (GraphicsStateGuardian *)NULL); + nassertv(_gsg != nullptr); if (mode == FM_render) { // end_render_texture(); @@ -166,10 +166,10 @@ supports_pixel_zoom() const { */ void TinyWinGraphicsWindow:: close_window() { - if (_gsg != (GraphicsStateGuardian *)NULL) { + if (_gsg != nullptr) { TinyGraphicsStateGuardian *tinygsg; DCAST_INTO_V(tinygsg, _gsg); - tinygsg->_current_frame_buffer = NULL; + tinygsg->_current_frame_buffer = nullptr; _gsg.clear(); } @@ -192,7 +192,7 @@ open_window() { TinyGraphicsStateGuardian *tinygsg; if (_gsg == 0) { // There is no old gsg. Create a new one. - tinygsg = new TinyGraphicsStateGuardian(_engine, _pipe, NULL); + tinygsg = new TinyGraphicsStateGuardian(_engine, _pipe, nullptr); _gsg = tinygsg; } else { DCAST_INTO_R(tinygsg, _gsg, false); @@ -201,7 +201,7 @@ open_window() { _hdc = GetDC(_hWnd); create_frame_buffer(); - if (_frame_buffer == NULL) { + if (_frame_buffer == nullptr) { tinydisplay_cat.error() << "Could not create frame buffer.\n"; return false; @@ -225,8 +225,8 @@ open_window() { void TinyWinGraphicsWindow:: handle_reshape() { WinGraphicsWindow::handle_reshape(); - if (_frame_buffer != NULL) { - ZB_resize(_frame_buffer, NULL, _properties.get_x_size(), _properties.get_y_size()); + if (_frame_buffer != nullptr) { + ZB_resize(_frame_buffer, nullptr, _properties.get_x_size(), _properties.get_y_size()); setup_bitmap_info(); } } @@ -238,7 +238,7 @@ handle_reshape() { bool TinyWinGraphicsWindow:: do_fullscreen_resize(int x_size, int y_size) { bool result = WinGraphicsWindow::do_fullscreen_resize(x_size, y_size); - ZB_resize(_frame_buffer, NULL, _properties.get_x_size(), _properties.get_y_size()); + ZB_resize(_frame_buffer, nullptr, _properties.get_x_size(), _properties.get_y_size()); setup_bitmap_info(); return result; } @@ -248,9 +248,9 @@ do_fullscreen_resize(int x_size, int y_size) { */ void TinyWinGraphicsWindow:: create_frame_buffer() { - if (_frame_buffer != NULL) { + if (_frame_buffer != nullptr) { ZB_close(_frame_buffer); - _frame_buffer = NULL; + _frame_buffer = nullptr; } _frame_buffer = ZB_open(_properties.get_x_size(), _properties.get_y_size(), ZB_MODE_RGBA, 0, 0, 0, 0); diff --git a/panda/src/tinydisplay/tinyWinGraphicsWindow.h b/panda/src/tinydisplay/tinyWinGraphicsWindow.h index 3140e61d27..ecc1365a0b 100644 --- a/panda/src/tinydisplay/tinyWinGraphicsWindow.h +++ b/panda/src/tinydisplay/tinyWinGraphicsWindow.h @@ -28,7 +28,7 @@ class EXPCL_TINYDISPLAY TinyWinGraphicsWindow : public WinGraphicsWindow { public: TinyWinGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/tinydisplay/tinyXGraphicsPipe.cxx b/panda/src/tinydisplay/tinyXGraphicsPipe.cxx index 9bb2c4c2d6..76cf30050e 100644 --- a/panda/src/tinydisplay/tinyXGraphicsPipe.cxx +++ b/panda/src/tinydisplay/tinyXGraphicsPipe.cxx @@ -27,7 +27,7 @@ TypeHandle TinyXGraphicsPipe::_type_handle; * */ TinyXGraphicsPipe:: -TinyXGraphicsPipe(const string &display) : x11GraphicsPipe(display) { +TinyXGraphicsPipe(const std::string &display) : x11GraphicsPipe(display) { } /** @@ -43,7 +43,7 @@ TinyXGraphicsPipe:: * choose between several possible GraphicsPipes available on a particular * platform, so the name should be meaningful and unique for a given platform. */ -string TinyXGraphicsPipe:: +std::string TinyXGraphicsPipe:: get_interface_name() const { return "TinyPanda"; } @@ -61,7 +61,7 @@ pipe_constructor() { * Creates a new window on the pipe, if possible. */ PT(GraphicsOutput) TinyXGraphicsPipe:: -make_output(const string &name, +make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -72,7 +72,7 @@ make_output(const string &name, bool &precertify) { TinyGraphicsStateGuardian *tinygsg = 0; if (gsg != 0) { - DCAST_INTO_R(tinygsg, gsg, NULL); + DCAST_INTO_R(tinygsg, gsg, nullptr); } // First thing to try: a TinyXGraphicsWindow @@ -88,7 +88,7 @@ make_output(const string &name, ((flags&BF_rtt_cumulative)!=0)|| ((flags&BF_can_bind_color)!=0)|| ((flags&BF_can_bind_every)!=0)) { - return NULL; + return nullptr; } return new TinyXGraphicsWindow(engine, this, name, fb_prop, win_prop, flags, gsg, host); @@ -101,13 +101,13 @@ make_output(const string &name, if (retry == 1) { if (((flags&BF_require_parasite)!=0)|| ((flags&BF_require_window)!=0)) { - return NULL; + return nullptr; } return new TinyGraphicsBuffer(engine, this, name, fb_prop, win_prop, flags, gsg, host); } // Nothing else left to try. - return NULL; + return nullptr; } #endif // HAVE_X11 diff --git a/panda/src/tinydisplay/tinyXGraphicsPipe.h b/panda/src/tinydisplay/tinyXGraphicsPipe.h index c6ecf15817..c0f7f69eeb 100644 --- a/panda/src/tinydisplay/tinyXGraphicsPipe.h +++ b/panda/src/tinydisplay/tinyXGraphicsPipe.h @@ -30,14 +30,14 @@ */ class EXPCL_TINYDISPLAY TinyXGraphicsPipe : public x11GraphicsPipe { public: - TinyXGraphicsPipe(const string &display = string()); + TinyXGraphicsPipe(const std::string &display = std::string()); virtual ~TinyXGraphicsPipe(); - virtual string get_interface_name() const; + virtual std::string get_interface_name() const; static PT(GraphicsPipe) pipe_constructor(); protected: - virtual PT(GraphicsOutput) make_output(const string &name, + virtual PT(GraphicsOutput) make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/tinydisplay/tinyXGraphicsWindow.cxx b/panda/src/tinydisplay/tinyXGraphicsWindow.cxx index 7b34ba0fb7..e84fa4d834 100644 --- a/panda/src/tinydisplay/tinyXGraphicsWindow.cxx +++ b/panda/src/tinydisplay/tinyXGraphicsWindow.cxx @@ -37,7 +37,7 @@ TypeHandle TinyXGraphicsWindow::_type_handle; */ TinyXGraphicsWindow:: TinyXGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -45,11 +45,11 @@ TinyXGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, GraphicsOutput *host) : x11GraphicsWindow(engine, pipe, name, fb_prop, win_prop, flags, gsg, host) { - _gc = (GC)NULL; + _gc = (GC)nullptr; - _reduced_frame_buffer = NULL; - _full_frame_buffer = NULL; - _ximage = NULL; + _reduced_frame_buffer = nullptr; + _full_frame_buffer = nullptr; + _ximage = nullptr; update_pixel_factor(); } @@ -58,12 +58,12 @@ TinyXGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, */ TinyXGraphicsWindow:: ~TinyXGraphicsWindow() { - if (_gc != NULL && _display != NULL) { + if (_gc != nullptr && _display != nullptr) { XFreeGC(_display, _gc); } - if (_ximage != NULL) { + if (_ximage != nullptr) { PANDA_FREE_ARRAY(_ximage->data); - _ximage->data = NULL; + _ximage->data = nullptr; XDestroyImage(_ximage); } } @@ -78,12 +78,12 @@ bool TinyXGraphicsWindow:: begin_frame(FrameMode mode, Thread *current_thread) { PStatTimer timer(_make_current_pcollector, current_thread); - if (_xwindow == (X11_Window)NULL) { + if (_xwindow == (X11_Window)nullptr) { return false; } begin_frame_spam(mode); - if (_gsg == (GraphicsStateGuardian *)NULL) { + if (_gsg == nullptr) { return false; } if (_awaiting_configure) { @@ -95,7 +95,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { TinyGraphicsStateGuardian *tinygsg; DCAST_INTO_R(tinygsg, _gsg, false); - if (_reduced_frame_buffer != (ZBuffer *)NULL) { + if (_reduced_frame_buffer != nullptr) { tinygsg->_current_frame_buffer = _reduced_frame_buffer; } else { tinygsg->_current_frame_buffer = _full_frame_buffer; @@ -114,7 +114,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { void TinyXGraphicsWindow:: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); - nassertv(_gsg != (GraphicsStateGuardian *)NULL); + nassertv(_gsg != nullptr); if (mode == FM_render) { // end_render_texture(); @@ -138,12 +138,12 @@ end_frame(FrameMode mode, Thread *current_thread) { */ void TinyXGraphicsWindow:: end_flip() { - if (_xwindow == (X11_Window)NULL || !_flip_ready) { + if (_xwindow == (X11_Window)nullptr || !_flip_ready) { GraphicsWindow::end_flip(); return; } - if (_reduced_frame_buffer != (ZBuffer *)NULL) { + if (_reduced_frame_buffer != nullptr) { // Zoom the reduced buffer onto the full buffer. ZB_zoomFrameBuffer(_full_frame_buffer, 0, 0, _full_frame_buffer->xsize, _full_frame_buffer->ysize, @@ -261,7 +261,7 @@ process_events() { // A normal window may be resized by the user at will. properties.set_size(event.xconfigure.width, event.xconfigure.height); system_changed_properties(properties); - ZB_resize(_full_frame_buffer, NULL, _properties.get_x_size(), _properties.get_y_size()); + ZB_resize(_full_frame_buffer, nullptr, _properties.get_x_size(), _properties.get_y_size()); _pitch = (_full_frame_buffer->xsize * _bytes_per_pixel + 3) & ~3; create_reduced_frame_buffer(); create_ximage(); @@ -334,7 +334,7 @@ process_events() { if ((Atom)(event.xclient.data.l[0]) == _wm_delete_window) { // This is a message from the window manager indicating that the user // has requested to close the window. - string close_request_event = get_close_request_event(); + std::string close_request_event = get_close_request_event(); if (!close_request_event.empty()) { // In this case, the app has indicated a desire to intercept the // request and process it directly. @@ -377,10 +377,10 @@ process_events() { */ void TinyXGraphicsWindow:: close_window() { - if (_gsg != (GraphicsStateGuardian *)NULL) { + if (_gsg != nullptr) { TinyGraphicsStateGuardian *tinygsg; DCAST_INTO_V(tinygsg, _gsg); - tinygsg->_current_frame_buffer = NULL; + tinygsg->_current_frame_buffer = nullptr; _gsg.clear(); } @@ -400,7 +400,7 @@ open_window() { TinyGraphicsStateGuardian *tinygsg; if (_gsg == 0) { // There is no old gsg. Create a new one. - tinygsg = new TinyGraphicsStateGuardian(_engine, _pipe, NULL); + tinygsg = new TinyGraphicsStateGuardian(_engine, _pipe, nullptr); _gsg = tinygsg; } else { DCAST_INTO_R(tinygsg, _gsg, false); @@ -478,17 +478,17 @@ open_window() { return false; } - _gc = XCreateGC(_display, _xwindow, 0, NULL); + _gc = XCreateGC(_display, _xwindow, 0, nullptr); create_full_frame_buffer(); - if (_full_frame_buffer == NULL) { + if (_full_frame_buffer == nullptr) { tinydisplay_cat.error() << "Could not create frame buffer.\n"; return false; } create_reduced_frame_buffer(); create_ximage(); - nassertr(_ximage != NULL, false); + nassertr(_ximage != nullptr, false); tinygsg->_current_frame_buffer = _full_frame_buffer; @@ -513,7 +513,7 @@ open_window() { _window_handle = NativeWindowHandle::make_x11(_xwindow); // And tell our parent window that we're now its child. - if (_parent_window_handle != (WindowHandle *)NULL) { + if (_parent_window_handle != nullptr) { _parent_window_handle->attach_child(_window_handle); } @@ -534,9 +534,9 @@ pixel_factor_changed() { */ void TinyXGraphicsWindow:: create_full_frame_buffer() { - if (_full_frame_buffer != NULL) { + if (_full_frame_buffer != nullptr) { ZB_close(_full_frame_buffer); - _full_frame_buffer = NULL; + _full_frame_buffer = nullptr; } int mode; @@ -570,9 +570,9 @@ create_reduced_frame_buffer() { return; } - if (_reduced_frame_buffer != NULL) { + if (_reduced_frame_buffer != nullptr) { ZB_close(_reduced_frame_buffer); - _reduced_frame_buffer = NULL; + _reduced_frame_buffer = nullptr; } int x_size = get_fb_x_size(); @@ -594,11 +594,11 @@ create_reduced_frame_buffer() { */ void TinyXGraphicsWindow:: create_ximage() { - if (_ximage != NULL) { + if (_ximage != nullptr) { PANDA_FREE_ARRAY(_ximage->data); - _ximage->data = NULL; + _ximage->data = nullptr; XDestroyImage(_ximage); - _ximage = NULL; + _ximage = nullptr; } int image_size = _full_frame_buffer->ysize * _pitch; diff --git a/panda/src/tinydisplay/tinyXGraphicsWindow.h b/panda/src/tinydisplay/tinyXGraphicsWindow.h index e533f2b67d..da60c70eeb 100644 --- a/panda/src/tinydisplay/tinyXGraphicsWindow.h +++ b/panda/src/tinydisplay/tinyXGraphicsWindow.h @@ -28,7 +28,7 @@ class EXPCL_TINYDISPLAY TinyXGraphicsWindow : public x11GraphicsWindow { public: TinyXGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/tinydisplay/zbuffer.cxx b/panda/src/tinydisplay/zbuffer.cxx index cc25320646..ceab7790d8 100644 --- a/panda/src/tinydisplay/zbuffer.cxx +++ b/panda/src/tinydisplay/zbuffer.cxx @@ -24,6 +24,9 @@ int pixel_count_smooth_multitex2; int pixel_count_smooth_multitex3; #endif // DO_PSTATS +using std::max; +using std::min; + ZBuffer * ZB_open(int xsize, int ysize, int mode, int nb_colors, @@ -34,8 +37,8 @@ ZB_open(int xsize, int ysize, int mode, int size; zb = (ZBuffer *)gl_malloc(sizeof(ZBuffer)); - if (zb == NULL) - return NULL; + if (zb == nullptr) + return nullptr; memset(zb, 0, sizeof(ZBuffer)); /* xsize must be a multiple of 4 */ @@ -68,12 +71,12 @@ ZB_open(int xsize, int ysize, int mode, size = zb->xsize * zb->ysize * sizeof(ZPOINT); zb->zbuf = (ZPOINT *)gl_malloc(size); - if (zb->zbuf == NULL) + if (zb->zbuf == nullptr) goto error; - if (frame_buffer == NULL) { + if (frame_buffer == nullptr) { zb->pbuf = (PIXEL *)gl_malloc(zb->ysize * zb->linesize); - if (zb->pbuf == NULL) { + if (zb->pbuf == nullptr) { gl_free(zb->zbuf); goto error; } @@ -86,7 +89,7 @@ ZB_open(int xsize, int ysize, int mode, return zb; error: gl_free(zb); - return NULL; + return nullptr; } void @@ -107,7 +110,7 @@ void ZB_resize(ZBuffer * zb, void *frame_buffer, int xsize, int ysize) { int size; - nassertv(zb != NULL); + nassertv(zb != nullptr); /* xsize must be a multiple of 4 */ xsize = (xsize + 3) & ~3; @@ -123,7 +126,7 @@ ZB_resize(ZBuffer * zb, void *frame_buffer, int xsize, int ysize) { if (zb->frame_buffer_allocated) gl_free(zb->pbuf); - if (frame_buffer == NULL) { + if (frame_buffer == nullptr) { zb->pbuf = (PIXEL *)gl_malloc(zb->ysize * zb->linesize); zb->frame_buffer_allocated = 1; } else { diff --git a/panda/src/tinydisplay/zfeatures.h b/panda/src/tinydisplay/zfeatures.h index 6092b87c24..73a61d95c5 100644 --- a/panda/src/tinydisplay/zfeatures.h +++ b/panda/src/tinydisplay/zfeatures.h @@ -39,4 +39,10 @@ /* Number of simultaneous texture stages supported (multitexture). */ #define MAX_TEXTURE_STAGES 3 +#ifdef __GNUC__ +#define UNUSED __attribute__((unused)) +#else +#define UNUSED +#endif + #endif /* _tgl_features_h_ */ diff --git a/panda/src/tinydisplay/ztriangle.h b/panda/src/tinydisplay/ztriangle.h index c8fdfc4c53..72f3c1ae11 100644 --- a/panda/src/tinydisplay/ztriangle.h +++ b/panda/src/tinydisplay/ztriangle.h @@ -14,7 +14,7 @@ int error, derror; int x1, dxdy_min, dxdy_max; /* warning: x2 is multiplied by 2^16 */ - int x2, dx2dy2; + int x2, dx2dy2; #ifdef INTERP_Z int z1 = 0, dzdx = 0, dzdy = 0, dzdl_min = 0, dzdl_max = 0; diff --git a/panda/src/tinydisplay/ztriangle_two.h b/panda/src/tinydisplay/ztriangle_two.h index 6bb255ce01..0d9db0df0f 100644 --- a/panda/src/tinydisplay/ztriangle_two.h +++ b/panda/src/tinydisplay/ztriangle_two.h @@ -1,3 +1,9 @@ +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" +#pragma GCC diagnostic ignored "-Wunused-but-set-variable" +#endif + static void FNAME(white_untextured) (ZBuffer *zb, ZBufferPoint *p0,ZBufferPoint *p1,ZBufferPoint *p2) @@ -31,8 +37,8 @@ static void FNAME(flat_untextured) (ZBuffer *zb, ZBufferPoint *p0,ZBufferPoint *p1,ZBufferPoint *p2) { - int color; - int or0, og0, ob0, oa0; + UNUSED int color; + UNUSED int or0, og0, ob0, oa0; #define INTERP_Z @@ -160,7 +166,7 @@ FNAME(flat_textured) (ZBuffer *zb, ZBufferPoint *p0,ZBufferPoint *p1,ZBufferPoint *p2) { ZTextureDef *texture_def; - int or0, og0, ob0, oa0; + UNUSED int or0, og0, ob0, oa0; #define INTERP_Z #define INTERP_ST @@ -187,7 +193,7 @@ FNAME(flat_textured) (ZBuffer *zb, zz=z >> ZB_POINT_Z_FRAC_BITS; \ if (ZCMP(pz[_a], zz)) { \ tmp = ZB_LOOKUP_TEXTURE(texture_def, s, t, mipmap_level, mipmap_dx); \ - int a = PALPHA_MULT(oa0, PIXEL_A(tmp)); \ + UNUSED int a = PALPHA_MULT(oa0, PIXEL_A(tmp)); \ if (ACMP(zb, a)) { \ STORE_PIX(pp[_a], \ RGBA_TO_PIXEL(PCOMPONENT_MULT(or0, PIXEL_R(tmp)), \ @@ -229,7 +235,7 @@ FNAME(smooth_textured) (ZBuffer *zb, c2 = RGBA_TO_PIXEL(p2->r, p2->g, p2->b, p2->a); \ if (c0 == c1 && c0 == c2) { \ /* It's really a flat-shaded triangle. */ \ - if (c0 == 0xffffffff) { \ + if (c0 == 0xffffffffu) { \ /* Actually, it's a white triangle. */ \ FNAME(white_textured)(zb, p0, p1, p2); \ return; \ @@ -249,7 +255,7 @@ FNAME(smooth_textured) (ZBuffer *zb, zz=z >> ZB_POINT_Z_FRAC_BITS; \ if (ZCMP(pz[_a], zz)) { \ tmp = ZB_LOOKUP_TEXTURE(texture_def, s, t, mipmap_level, mipmap_dx); \ - int a = PALPHA_MULT(oa1, PIXEL_A(tmp)); \ + UNUSED int a = PALPHA_MULT(oa1, PIXEL_A(tmp)); \ if (ACMP(zb, a)) { \ STORE_PIX(pp[_a], \ RGBA_TO_PIXEL(PCOMPONENT_MULT(or1, PIXEL_R(tmp)), \ @@ -399,7 +405,7 @@ FNAME(flat_perspective) (ZBuffer *zb, { ZTextureDef *texture_def; PN_stdfloat fdzdx,fndzdx,ndszdx,ndtzdx; - int or0, og0, ob0, oa0; + UNUSED int or0, og0, ob0, oa0; #define INTERP_Z #define INTERP_STZ @@ -431,7 +437,7 @@ FNAME(flat_perspective) (ZBuffer *zb, zz=z >> ZB_POINT_Z_FRAC_BITS; \ if (ZCMP(pz[_a], zz)) { \ tmp = ZB_LOOKUP_TEXTURE(texture_def, s, t, mipmap_level, mipmap_dx); \ - int a = PALPHA_MULT(oa0, PIXEL_A(tmp)); \ + UNUSED int a = PALPHA_MULT(oa0, PIXEL_A(tmp)); \ if (ACMP(zb, a)) { \ STORE_PIX(pp[_a], \ RGBA_TO_PIXEL(PCOMPONENT_MULT(or0, PIXEL_R(tmp)), \ @@ -456,7 +462,7 @@ FNAME(flat_perspective) (ZBuffer *zb, PIXEL *pp; \ int s,t,z,zz; \ int n,dsdx,dtdx; \ - int or1,og1,ob1,oa1; \ + UNUSED int or1,og1,ob1,oa1; \ PN_stdfloat sz,tz,fz,zinv; \ n=(x2>>16)-x1; \ fz=(PN_stdfloat)z1; \ @@ -537,13 +543,13 @@ FNAME(smooth_perspective) (ZBuffer *zb, #define EARLY_OUT() \ { \ - int c0, c1, c2; \ + unsigned int c0, c1, c2; \ c0 = RGBA_TO_PIXEL(p0->r, p0->g, p0->b, p0->a); \ c1 = RGBA_TO_PIXEL(p1->r, p1->g, p1->b, p1->a); \ c2 = RGBA_TO_PIXEL(p2->r, p2->g, p2->b, p2->a); \ if (c0 == c1 && c0 == c2) { \ /* It's really a flat-shaded triangle. */ \ - if (c0 == 0xffffffff) { \ + if (c0 == 0xffffffffu) { \ /* Actually, it's a white triangle. */ \ FNAME(white_perspective)(zb, p0, p1, p2); \ return; \ @@ -567,7 +573,7 @@ FNAME(smooth_perspective) (ZBuffer *zb, zz=z >> ZB_POINT_Z_FRAC_BITS; \ if (ZCMP(pz[_a], zz)) { \ tmp = ZB_LOOKUP_TEXTURE(texture_def, s, t, mipmap_level, mipmap_dx); \ - int a = PALPHA_MULT(oa1, PIXEL_A(tmp)); \ + UNUSED int a = PALPHA_MULT(oa1, PIXEL_A(tmp)); \ if (ACMP(zb, a)) { \ STORE_PIX(pp[_a], \ RGBA_TO_PIXEL(PCOMPONENT_MULT(or1, PIXEL_R(tmp)), \ @@ -596,7 +602,7 @@ FNAME(smooth_perspective) (ZBuffer *zb, PIXEL *pp; \ int s,t,z,zz; \ int n,dsdx,dtdx; \ - int or1,og1,ob1,oa1; \ + UNUSED int or1,og1,ob1,oa1; \ PN_stdfloat sz,tz,fz,zinv; \ n=(x2>>16)-x1; \ fz=(PN_stdfloat)z1; \ @@ -695,9 +701,9 @@ FNAME(smooth_multitex2) (ZBuffer *zb, zz=z >> ZB_POINT_Z_FRAC_BITS; \ if (ZCMP(pz[_a], zz)) { \ tmp = ZB_LOOKUP_TEXTURE(&zb->current_textures[0], s, t, mipmap_level, mipmap_dx); \ - int a = PALPHA_MULT(oa1, PIXEL_A(tmp)); \ + UNUSED int a = PALPHA_MULT(oa1, PIXEL_A(tmp)); \ if (ACMP(zb, a)) { \ - int tmpa = ZB_LOOKUP_TEXTURE(&zb->current_textures[1], sa, ta, mipmap_levela, mipmap_dxa); \ + UNUSED int tmpa = ZB_LOOKUP_TEXTURE(&zb->current_textures[1], sa, ta, mipmap_levela, mipmap_dxa); \ STORE_PIX(pp[_a], \ RGBA_TO_PIXEL(PCOMPONENT_MULT3(or1, PIXEL_R(tmp), PIXEL_R(tmpa)), \ PCOMPONENT_MULT3(og1, PIXEL_G(tmp), PIXEL_G(tmpa)), \ @@ -727,7 +733,7 @@ FNAME(smooth_multitex2) (ZBuffer *zb, PIXEL *pp; \ int s,t,sa,ta,z,zz; \ int n,dsdx,dtdx,dsadx,dtadx; \ - int or1,og1,ob1,oa1; \ + UNUSED int or1,og1,ob1,oa1; \ PN_stdfloat sz,tz,sza,tza,fz,zinv; \ n=(x2>>16)-x1; \ fz=(PN_stdfloat)z1; \ @@ -853,10 +859,10 @@ FNAME(smooth_multitex3) (ZBuffer *zb, zz=z >> ZB_POINT_Z_FRAC_BITS; \ if (ZCMP(pz[_a], zz)) { \ tmp = ZB_LOOKUP_TEXTURE(&zb->current_textures[0], s, t, mipmap_level, mipmap_dx); \ - int a = PALPHA_MULT(oa1, PIXEL_A(tmp)); \ + UNUSED int a = PALPHA_MULT(oa1, PIXEL_A(tmp)); \ if (ACMP(zb, a)) { \ - int tmpa = ZB_LOOKUP_TEXTURE(&zb->current_textures[1], sa, ta, mipmap_levela, mipmap_dxa); \ - int tmpb = ZB_LOOKUP_TEXTURE(&zb->current_textures[2], sb, tb, mipmap_levelb, mipmap_dxb); \ + UNUSED int tmpa = ZB_LOOKUP_TEXTURE(&zb->current_textures[1], sa, ta, mipmap_levela, mipmap_dxa); \ + UNUSED int tmpb = ZB_LOOKUP_TEXTURE(&zb->current_textures[2], sb, tb, mipmap_levelb, mipmap_dxb); \ STORE_PIX(pp[_a], \ RGBA_TO_PIXEL(PCOMPONENT_MULT4(or1, PIXEL_R(tmp), PIXEL_R(tmpa), PIXEL_R(tmpb)), \ PCOMPONENT_MULT4(og1, PIXEL_G(tmp), PIXEL_G(tmpa), PIXEL_G(tmpb)), \ @@ -888,7 +894,7 @@ FNAME(smooth_multitex3) (ZBuffer *zb, PIXEL *pp; \ int s,t,sa,ta,sb,tb,z,zz; \ int n,dsdx,dtdx,dsadx,dtadx,dsbdx,dtbdx; \ - int or1,og1,ob1,oa1; \ + UNUSED int or1,og1,ob1,oa1; \ PN_stdfloat sz,tz,sza,tza,szb,tzb,fz,zinv; \ n=(x2>>16)-x1; \ fz=(PN_stdfloat)z1; \ @@ -1008,3 +1014,7 @@ FNAME(smooth_multitex3) (ZBuffer *zb, #undef INTERP_MIPMAP #undef CALC_MIPMAP_LEVEL #undef ZB_LOOKUP_TEXTURE + +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC diagnostic pop +#endif diff --git a/panda/src/vision/arToolKit.cxx b/panda/src/vision/arToolKit.cxx index 0c68f5cd46..cb9a73508d 100644 --- a/panda/src/vision/arToolKit.cxx +++ b/panda/src/vision/arToolKit.cxx @@ -145,7 +145,7 @@ make(NodePath camera, const Filename ¶mfile, double marker_size) { } ARParam wparam; - string fn = paramfile.to_os_specific(); + std::string fn = paramfile.to_os_specific(); if( arParamLoad(fn.c_str(), 1, &wparam) < 0 ) { vision_cat.error() << "Cannot load ARToolKit camera config\n"; return 0; @@ -206,7 +206,7 @@ get_pattern(const Filename &filename) { return (*ptf).second; } - string fn = filename.to_os_specific(); + std::string fn = filename.to_os_specific(); int id = arLoadPatt(fn.c_str()); if (id < 0) { vision_cat.error() << "Could not load AR ToolKit Pattern: " << fn << "\n"; @@ -280,7 +280,7 @@ analyze(Texture *tex, bool do_flip_texture) { CPTA_uchar ri = tex->get_ram_image(); const unsigned char *ram = ri.p(); - if (ram == NULL) { + if (ram == nullptr) { vision_cat.warning() << "No data in texture!\n"; return; } diff --git a/panda/src/vision/openCVTexture.I b/panda/src/vision/openCVTexture.I index d9f5fa6f37..91234c31b6 100644 --- a/panda/src/vision/openCVTexture.I +++ b/panda/src/vision/openCVTexture.I @@ -16,7 +16,7 @@ */ INLINE bool OpenCVTexture::VideoStream:: is_valid() const { - return (_capture != NULL); + return (_capture != nullptr); } /** diff --git a/panda/src/vision/openCVTexture.cxx b/panda/src/vision/openCVTexture.cxx index 7d09636b0c..58c233232a 100644 --- a/panda/src/vision/openCVTexture.cxx +++ b/panda/src/vision/openCVTexture.cxx @@ -43,23 +43,11 @@ TypeHandle OpenCVTexture::_type_handle; * Sets up the texture to read frames from a camera */ OpenCVTexture:: -OpenCVTexture(const string &name) : +OpenCVTexture(const std::string &name) : VideoTexture(name) { } -/** - * Use OpenCVTexture::make_copy() to make a duplicate copy of an existing - * OpenCVTexture. - */ -OpenCVTexture:: -OpenCVTexture(const OpenCVTexture ©) : - VideoTexture(copy), - _pages(copy._pages) -{ - nassertv(false); -} - /** * */ @@ -82,7 +70,7 @@ consider_update() { } else { // Loop through the pages to see if there's any camera stream to update. Texture::CDWriter cdata(Texture::_cycler, false); - int max_z = max(cdata->_z_size, (int)_pages.size()); + int max_z = std::max(cdata->_z_size, (int)_pages.size()); for (int z = 0; z < max_z; ++z) { VideoPage &page = _pages[z]; if (!page._color.is_from_file() || !page._alpha.is_from_file()) { @@ -104,13 +92,13 @@ consider_update() { * independently of the original. */ PT(Texture) OpenCVTexture:: -make_copy_impl() { +make_copy_impl() const { Texture::CDReader cdata_tex(Texture::_cycler); PT(OpenCVTexture) copy = new OpenCVTexture(get_name()); Texture::CDWriter cdata_copy_tex(copy->Texture::_cycler, true); copy->do_assign(cdata_copy_tex, this, cdata_tex); - return copy.p(); + return copy; } /** @@ -270,7 +258,7 @@ make_texture() { */ void OpenCVTexture:: do_update_frame(Texture::CData *cdata, int frame) { - int max_z = max(cdata->_z_size, (int)_pages.size()); + int max_z = std::max(cdata->_z_size, (int)_pages.size()); for (int z = 0; z < max_z; ++z) { do_update_frame(cdata, frame, z); } @@ -383,7 +371,7 @@ do_read_one(Texture::CData *cdata, int z, int n, int primary_file_num_channels, int alpha_file_channel, const LoaderOptions &options, bool header_only, BamCacheRecord *record) { - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { record->add_dependent_file(fullpath); } @@ -458,7 +446,7 @@ do_read_one(Texture::CData *cdata, */ bool OpenCVTexture:: do_load_one(Texture::CData *cdata, - const PNMImage &pnmimage, const string &name, + const PNMImage &pnmimage, const std::string &name, int z, int n, const LoaderOptions &options) { if (z <= (int)_pages.size()) { VideoPage &page = do_modify_page(cdata, z); @@ -491,7 +479,7 @@ register_with_read_factory() { */ OpenCVTexture::VideoStream:: VideoStream() : - _capture(NULL), + _capture(nullptr), _camera_index(-1), _next_frame(0) { @@ -502,7 +490,7 @@ VideoStream() : */ OpenCVTexture::VideoStream:: VideoStream(const OpenCVTexture::VideoStream ©) : - _capture(NULL), + _capture(nullptr), _camera_index(-1) { // Rather than copying the _capture pointer, we must open a new stream that @@ -553,7 +541,7 @@ get_frame_data(int frame, _next_frame = frame + 1; IplImage *image = cvQueryFrame(_capture); - if (image == NULL) { + if (image == nullptr) { return false; } @@ -593,9 +581,9 @@ bool OpenCVTexture::VideoStream:: read(const Filename &filename) { clear(); - string os_specific = filename.to_os_specific(); + std::string os_specific = filename.to_os_specific(); _capture = cvCaptureFromFile(os_specific.c_str()); - if (_capture == NULL) { + if (_capture == nullptr) { return false; } _filename = filename; @@ -611,7 +599,7 @@ from_camera(int camera_index) { clear(); _capture = cvCaptureFromCAM(camera_index); - if (_capture == NULL) { + if (_capture == nullptr) { return false; } _camera_index = camera_index; @@ -623,9 +611,9 @@ from_camera(int camera_index) { */ void OpenCVTexture::VideoStream:: clear() { - if (_capture != NULL) { + if (_capture != nullptr) { cvReleaseCapture(&_capture); - _capture = NULL; + _capture = nullptr; } _filename = Filename(); _camera_index = -1; diff --git a/panda/src/vision/openCVTexture.h b/panda/src/vision/openCVTexture.h index 1ad8e11a7a..e3fa1a3edb 100644 --- a/panda/src/vision/openCVTexture.h +++ b/panda/src/vision/openCVTexture.h @@ -28,10 +28,8 @@ struct CvCapture; */ class EXPCL_VISION OpenCVTexture : public VideoTexture { PUBLISHED: - OpenCVTexture(const string &name = string()); -protected: - OpenCVTexture(const OpenCVTexture ©); -PUBLISHED: + OpenCVTexture(const std::string &name = std::string()); + OpenCVTexture(const OpenCVTexture ©) = delete; virtual ~OpenCVTexture(); bool from_camera(int camera_index = -1, int z = 0, @@ -43,7 +41,7 @@ public: protected: virtual void consider_update(); - virtual PT(Texture) make_copy_impl(); + virtual PT(Texture) make_copy_impl() const; void do_assign(Texture::CData *cdata_tex, const OpenCVTexture *copy, const Texture::CData *cdata_copy_tex); @@ -56,7 +54,7 @@ protected: const LoaderOptions &options, bool header_only, BamCacheRecord *record); virtual bool do_load_one(Texture::CData *cdata, - const PNMImage &pnmimage, const string &name, + const PNMImage &pnmimage, const std::string &name, int z, int n, const LoaderOptions &options); private: diff --git a/panda/src/vision/webcamVideo.I b/panda/src/vision/webcamVideo.I index dcc0f473ca..c0c2e1fe74 100644 --- a/panda/src/vision/webcamVideo.I +++ b/panda/src/vision/webcamVideo.I @@ -39,7 +39,7 @@ get_fps() const { /** * Returns the camera's pixel format, as a FourCC code, if known. */ -INLINE const string &WebcamVideo:: +INLINE const std::string &WebcamVideo:: get_pixel_format() const { return _pixel_format; } @@ -49,7 +49,7 @@ get_pixel_format() const { * FPS to the output stream. */ INLINE void WebcamVideo:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_name() << ": " << get_size_x() << "x" << get_size_y(); if (!_pixel_format.empty()) { @@ -59,7 +59,7 @@ output(ostream &out) const { out << " @ " << get_fps() << "Hz"; } -INLINE ostream &operator << (ostream &out, const WebcamVideo &n) { +INLINE std::ostream &operator << (std::ostream &out, const WebcamVideo &n) { n.output(out); return out; } diff --git a/panda/src/vision/webcamVideo.cxx b/panda/src/vision/webcamVideo.cxx index f13587c39b..8badc4eeec 100644 --- a/panda/src/vision/webcamVideo.cxx +++ b/panda/src/vision/webcamVideo.cxx @@ -75,6 +75,6 @@ get_num_options() { PT(WebcamVideo) WebcamVideo:: get_option(int n) { find_all_webcams(); - nassertr((n >= 0) && (n < (int)_all_webcams.size()), NULL); + nassertr((n >= 0) && (n < (int)_all_webcams.size()), nullptr); return _all_webcams[n]; } diff --git a/panda/src/vision/webcamVideo.h b/panda/src/vision/webcamVideo.h index cdcf5e393d..903afa87f3 100644 --- a/panda/src/vision/webcamVideo.h +++ b/panda/src/vision/webcamVideo.h @@ -33,11 +33,11 @@ PUBLISHED: INLINE int get_size_x() const; INLINE int get_size_y() const; INLINE double get_fps() const; - INLINE const string &get_pixel_format() const; + INLINE const std::string &get_pixel_format() const; virtual PT(MovieVideoCursor) open() = 0; - INLINE void output(ostream &out) const; + INLINE void output(std::ostream &out) const; public: static void find_all_webcams(); @@ -46,7 +46,7 @@ protected: int _size_x; int _size_y; double _fps; - string _pixel_format; + std::string _pixel_format; static pvector _all_webcams; @@ -68,7 +68,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const WebcamVideo &n); +INLINE std::ostream &operator << (std::ostream &out, const WebcamVideo &n); #include "webcamVideo.I" diff --git a/panda/src/vision/webcamVideoCursorOpenCV.cxx b/panda/src/vision/webcamVideoCursorOpenCV.cxx index 814ad9d5bb..444557fde8 100644 --- a/panda/src/vision/webcamVideoCursorOpenCV.cxx +++ b/panda/src/vision/webcamVideoCursorOpenCV.cxx @@ -35,7 +35,7 @@ WebcamVideoCursorOpenCV(WebcamVideoOpenCV *src) : MovieVideoCursor(src) { _ready = false; _capture = cvCaptureFromCAM(src->_camera_index); - if (_capture != NULL) { + if (_capture != nullptr) { _size_x = (int)cvGetCaptureProperty(_capture, CV_CAP_PROP_FRAME_WIDTH); _size_y = (int)cvGetCaptureProperty(_capture, CV_CAP_PROP_FRAME_HEIGHT); _ready = true; @@ -47,9 +47,9 @@ WebcamVideoCursorOpenCV(WebcamVideoOpenCV *src) : MovieVideoCursor(src) { */ WebcamVideoCursorOpenCV:: ~WebcamVideoCursorOpenCV() { - if (_capture != NULL) { + if (_capture != nullptr) { cvReleaseCapture(&_capture); - _capture = NULL; + _capture = nullptr; } } @@ -59,13 +59,13 @@ WebcamVideoCursorOpenCV:: PT(MovieVideoCursor::Buffer) WebcamVideoCursorOpenCV:: fetch_buffer() { if (!_ready) { - return NULL; + return nullptr; } PT(Buffer) buffer = get_standard_buffer(); unsigned char *dest = buffer->_block; int num_components = get_num_components(); - nassertr(num_components == 3, NULL); + nassertr(num_components == 3, nullptr); int dest_x_pitch = num_components; // Assume component_width == 1 int dest_y_pitch = _size_x * dest_x_pitch; @@ -75,7 +75,7 @@ fetch_buffer() { if (num_components == 3 && x_pitch == 3) { // The easy case--copy the whole thing in, row by row. int copy_bytes = _size_x * dest_x_pitch; - nassertr(copy_bytes <= dest_y_pitch && copy_bytes <= abs(y_pitch), NULL); + nassertr(copy_bytes <= dest_y_pitch && copy_bytes <= abs(y_pitch), nullptr); for (int y = 0; y < _size_y; ++y) { memcpy(dest, r, copy_bytes); @@ -129,7 +129,7 @@ get_frame_data(const unsigned char *&r, nassertr(ready(), false); IplImage *image = cvQueryFrame(_capture); - if (image == NULL) { + if (image == nullptr) { return false; } diff --git a/panda/src/vision/webcamVideoCursorV4L.cxx b/panda/src/vision/webcamVideoCursorV4L.cxx index a78c55135a..95565f9428 100644 --- a/panda/src/vision/webcamVideoCursorV4L.cxx +++ b/panda/src/vision/webcamVideoCursorV4L.cxx @@ -30,7 +30,7 @@ extern "C" { TypeHandle WebcamVideoCursorV4L::_type_handle; -#define clamp(x) min(max(x, 0.0), 255.0) +#define clamp(x) std::min(std::max(x, 0.0), 255.0) INLINE static void yuv_to_bgr(unsigned char *dest, const unsigned char *src) { double y1 = (255 / 219.0) * (src[0] - 16); @@ -207,8 +207,8 @@ WebcamVideoCursorV4L(WebcamVideoV4L *src) : MovieVideoCursor(src) { _ready = false; memset(&_format, 0, sizeof(struct v4l2_format)); - _buffers = NULL; - _buflens = NULL; + _buffers = nullptr; + _buflens = nullptr; int mode = O_RDWR; if (!v4l_blocking) { @@ -326,7 +326,7 @@ WebcamVideoCursorV4L(WebcamVideoV4L *src) : MovieVideoCursor(src) { } _buflens[i] = buf.length; - _buffers[i] = mmap (NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, _fd, buf.m.offset); + _buffers[i] = mmap (nullptr, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, _fd, buf.m.offset); if (_buffers[i] == MAP_FAILED) { vision_cat.error() << "Failed to map buffer!\n"; @@ -393,7 +393,7 @@ WebcamVideoCursorV4L:: PT(MovieVideoCursor::Buffer) WebcamVideoCursorV4L:: fetch_buffer() { if (!_ready) { - return NULL; + return nullptr; } PT(Buffer) buffer = get_standard_buffer(); @@ -405,12 +405,12 @@ fetch_buffer() { if (-1 == ioctl(_fd, VIDIOC_DQBUF, &vbuf) && errno != EIO) { if (errno == EAGAIN) { // Simply nothing is available yet. - return NULL; + return nullptr; } vision_cat.error() << "Failed to dequeue buffer!\n"; - return NULL; + return nullptr; } - nassertr(vbuf.index < _bufcount, NULL); + nassertr(vbuf.index < _bufcount, nullptr); size_t bufsize = _buflens[vbuf.index]; size_t old_bpl = _format.fmt.pix.bytesperline; size_t new_bpl = _size_x * _num_components; @@ -435,7 +435,7 @@ fetch_buffer() { _cinfo.src->next_input_byte = buf; if (jpeg_read_header(&_cinfo, TRUE) == JPEG_HEADER_OK) { - if (_cinfo.dc_huff_tbl_ptrs[0] == NULL) { + if (_cinfo.dc_huff_tbl_ptrs[0] == nullptr) { // Many MJPEG streams do not include huffman tables. Remedy this. _cinfo.dc_huff_tbl_ptrs[0] = &dc_luminance_tbl; _cinfo.dc_huff_tbl_ptrs[1] = &dc_chrominance_tbl; @@ -482,7 +482,7 @@ fetch_buffer() { block[i + 2] = ex; } #else - nassertr(false /* Not compiled with JPEG support*/, NULL); + nassertr(false /* Not compiled with JPEG support*/, nullptr); #endif break; } @@ -500,7 +500,7 @@ fetch_buffer() { case V4L2_PIX_FMT_BGR32: case V4L2_PIX_FMT_GREY: // Simplest case: copying every row verbatim. - nassertr(old_bpl == new_bpl, NULL); + nassertr(old_bpl == new_bpl, nullptr); for (size_t row = 0; row < _size_y; ++row) { memcpy(block + (_size_y - row - 1) * new_bpl, buf + row * old_bpl, new_bpl); @@ -509,7 +509,7 @@ fetch_buffer() { case V4L2_PIX_FMT_RGB24: // Swap components. - nassertr(old_bpl == new_bpl, NULL); + nassertr(old_bpl == new_bpl, nullptr); for (size_t row = 0; row < _size_y; ++row) { for (size_t i = 0; i < old_bpl; i += 3) { @@ -520,7 +520,7 @@ fetch_buffer() { case V4L2_PIX_FMT_RGB32: // Swap components. - nassertr(old_bpl == new_bpl, NULL); + nassertr(old_bpl == new_bpl, nullptr); for (size_t row = 0; row < _size_y; ++row) { for (size_t i = 0; i < old_bpl; i += 4) { diff --git a/panda/src/vision/webcamVideoDS.cxx b/panda/src/vision/webcamVideoDS.cxx index 0996070b45..531328b206 100644 --- a/panda/src/vision/webcamVideoDS.cxx +++ b/panda/src/vision/webcamVideoDS.cxx @@ -58,6 +58,9 @@ #include #include +using std::cerr; +using std::string; + /* * This used to work back when qedit.h still existed. The hacks served to * prevent it from including the defunct dxtrans.h. #pragma include_alias( @@ -236,18 +239,18 @@ media_fps(AM_MEDIA_TYPE *media) { */ void WebcamVideoDS:: delete_media_type(AM_MEDIA_TYPE *pmt) { - if (pmt == NULL) { + if (pmt == nullptr) { return; } if (pmt->cbFormat != 0) { CoTaskMemFree((PVOID)pmt->pbFormat); pmt->cbFormat = 0; - pmt->pbFormat = NULL; + pmt->pbFormat = nullptr; } - if (pmt->pUnk != NULL) { + if (pmt->pUnk != nullptr) { // Unecessary because pUnk should not be used, but safest. pmt->pUnk->Release(); - pmt->pUnk = NULL; + pmt->pUnk = nullptr; } CoTaskMemFree(pmt); } @@ -272,7 +275,7 @@ bstr_to_string(const BSTR &source) { string WebcamVideoDS:: get_moniker_name(IMoniker *pMoniker) { string res = "Unknown Device"; - IPropertyBag *propBag=NULL; + IPropertyBag *propBag=nullptr; VARIANT name; HRESULT hResult; pMoniker->BindToStorage(0, 0, IID_IPropertyBag, (void**)&propBag); VariantInit(&name); @@ -334,25 +337,25 @@ find_all_webcams_ds() { pvector list; - ICreateDevEnum *pCreateDevEnum=NULL; - IEnumMoniker *pEnumMoniker=NULL; - IGraphBuilder *pGraphBuilder=NULL; - ICaptureGraphBuilder2 *pCaptureGraphBuilder2=NULL; - IMoniker *pMoniker=NULL; - IBaseFilter *pBaseFilter=NULL; - IAMStreamConfig *pStreamConfig=NULL; + ICreateDevEnum *pCreateDevEnum=nullptr; + IEnumMoniker *pEnumMoniker=nullptr; + IGraphBuilder *pGraphBuilder=nullptr; + ICaptureGraphBuilder2 *pCaptureGraphBuilder2=nullptr; + IMoniker *pMoniker=nullptr; + IBaseFilter *pBaseFilter=nullptr; + IAMStreamConfig *pStreamConfig=nullptr; HRESULT hResult; ULONG cFetched; - hResult=CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC, + hResult=CoCreateInstance(CLSID_FilterGraph, nullptr, CLSCTX_INPROC, IID_IGraphBuilder,(void**)&pGraphBuilder); if (hResult != S_OK) goto cleanup; - hResult=CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC, + hResult=CoCreateInstance(CLSID_CaptureGraphBuilder2, nullptr, CLSCTX_INPROC, IID_ICaptureGraphBuilder2, (void**)&pCaptureGraphBuilder2); if (hResult != S_OK) goto cleanup; hResult = pCaptureGraphBuilder2->SetFiltergraph(pGraphBuilder); if (hResult != S_OK) goto cleanup; - hResult=CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, + hResult=CoCreateInstance(CLSID_SystemDeviceEnum, nullptr, CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, (void**)&pCreateDevEnum); if (hResult != S_OK) goto cleanup; hResult=pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, @@ -367,7 +370,7 @@ find_all_webcams_ds() { hResult = pEnumMoniker->Next(1, &pMoniker, &cFetched); if (hResult != S_OK) break; - hResult = pMoniker->BindToObject(NULL,NULL,IID_IBaseFilter, (void**)&pBaseFilter); + hResult = pMoniker->BindToObject(nullptr,nullptr,IID_IBaseFilter, (void**)&pBaseFilter); if (hResult != S_OK) continue; hResult = pCaptureGraphBuilder2->FindInterface(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video, pBaseFilter, IID_IAMStreamConfig, (void **)&pStreamConfig); @@ -425,23 +428,23 @@ open() { WebcamVideoCursorDS:: WebcamVideoCursorDS(WebcamVideoDS *src) : MovieVideoCursor(src), - _pGraphBuilder(NULL), - _pCaptureBuilder(NULL), - _pSrcFilter(NULL), - _pStreamConfig(NULL), - _pStreamRenderer(NULL), - _pMediaCtrl(NULL) + _pGraphBuilder(nullptr), + _pCaptureBuilder(nullptr), + _pSrcFilter(nullptr), + _pStreamConfig(nullptr), + _pStreamRenderer(nullptr), + _pMediaCtrl(nullptr) { AM_MEDIA_TYPE mediaType; VIDEOINFOHEADER *pVideoInfo; HRESULT hResult; - hResult=CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC, + hResult=CoCreateInstance(CLSID_FilterGraph, nullptr, CLSCTX_INPROC, IID_IGraphBuilder,(void**)&_pGraphBuilder); if(hResult != S_OK) { cleanup(); return; } - hResult=CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC, + hResult=CoCreateInstance(CLSID_CaptureGraphBuilder2, nullptr, CLSCTX_INPROC, IID_ICaptureGraphBuilder2, (void**)&_pCaptureBuilder); if(hResult != S_OK) { cleanup(); return; } @@ -454,8 +457,8 @@ WebcamVideoCursorDS(WebcamVideoDS *src) : cleanup(); return; } cerr << " IID_IMediaControl interface is acquired.\n"; - src->_moniker->BindToObject(NULL,NULL,IID_IBaseFilter, (void**)&_pSrcFilter); - if(_pSrcFilter == NULL) + src->_moniker->BindToObject(nullptr,nullptr,IID_IBaseFilter, (void**)&_pSrcFilter); + if(_pSrcFilter == nullptr) { cerr << " Such capture device is not found.\n"; cleanup(); return; } cerr << " The capture filter is acquired.\n"; @@ -479,7 +482,7 @@ WebcamVideoCursorDS(WebcamVideoDS *src) : cleanup(); return; } - hResult = CoCreateInstance(CLSID_SampleGrabber, NULL, CLSCTX_INPROC, IID_PPV_ARGS(&_pSampleGrabber)); + hResult = CoCreateInstance(CLSID_SampleGrabber, nullptr, CLSCTX_INPROC, IID_PPV_ARGS(&_pSampleGrabber)); if(hResult != S_OK) { cerr << " Can not create the sample grabber, maybe qedit.dll is not registered?"; cleanup(); return; } @@ -487,7 +490,7 @@ WebcamVideoCursorDS(WebcamVideoDS *src) : // hResult = CoCreateInstance(CLSID_SampleGrabber,) CComQIPtr< IBaseFilter, // &IID_IBaseFilter > pGrabberFilter(_pSampleGrabber); - IBaseFilter *pGrabberFilter = NULL; + IBaseFilter *pGrabberFilter = nullptr; hResult = _pSampleGrabber->QueryInterface(IID_PPV_ARGS(&pGrabberFilter)); cerr << " IID_IBaseFilter of CLSID_SampleGrabber is acquired.\n"; @@ -507,7 +510,7 @@ WebcamVideoCursorDS(WebcamVideoDS *src) : cerr << " The sample grabber has been added to the graph.\n"; // used to give the video stream somewhere to go to. - hResult = CoCreateInstance(CLSID_NullRenderer, NULL, CLSCTX_INPROC_SERVER, IID_IBaseFilter, (void**)&_pStreamRenderer); + hResult = CoCreateInstance(CLSID_NullRenderer, nullptr, CLSCTX_INPROC_SERVER, IID_IBaseFilter, (void**)&_pStreamRenderer); if(hResult != S_OK) { cerr << " Can not create the null renderer."; cleanup(); return; } @@ -566,17 +569,17 @@ WebcamVideoCursorDS(WebcamVideoDS *src) : if(mediaType.cbFormat != 0) { CoTaskMemFree((PVOID)mediaType.pbFormat); mediaType.cbFormat=0; - mediaType.pbFormat=NULL; + mediaType.pbFormat=nullptr; } - if(mediaType.pUnk != NULL) { + if(mediaType.pUnk != nullptr) { mediaType.pUnk->Release(); - mediaType.pUnk=NULL; + mediaType.pUnk=nullptr; } - if(pGrabberFilter != NULL) { + if(pGrabberFilter != nullptr) { pGrabberFilter->Release(); - pGrabberFilter=NULL; + pGrabberFilter=nullptr; } _pSampleGrabber->SetBufferSamples(FALSE); @@ -605,13 +608,13 @@ cleanup() { _pMediaCtrl->Stop(); } - if(_pMediaCtrl) { _pMediaCtrl->Release(); _pMediaCtrl=NULL; } - if(_pCaptureBuilder) { _pCaptureBuilder->Release(); _pCaptureBuilder=NULL; } - if(_pGraphBuilder) { _pGraphBuilder->Release(); _pGraphBuilder=NULL; } - if(_pSampleGrabber) { _pSampleGrabber->Release(); _pSampleGrabber=NULL; } - if(_pStreamRenderer) { _pStreamRenderer->Release(); _pStreamRenderer=NULL; } - if(_pSrcFilter) { _pSrcFilter->Release(); _pSrcFilter=NULL; } - if(_pStreamConfig) { _pStreamConfig->Release(); _pStreamConfig=NULL; } + if(_pMediaCtrl) { _pMediaCtrl->Release(); _pMediaCtrl=nullptr; } + if(_pCaptureBuilder) { _pCaptureBuilder->Release(); _pCaptureBuilder=nullptr; } + if(_pGraphBuilder) { _pGraphBuilder->Release(); _pGraphBuilder=nullptr; } + if(_pSampleGrabber) { _pSampleGrabber->Release(); _pSampleGrabber=nullptr; } + if(_pStreamRenderer) { _pStreamRenderer->Release(); _pStreamRenderer=nullptr; } + if(_pSrcFilter) { _pSrcFilter->Release(); _pSrcFilter=nullptr; } + if(_pStreamConfig) { _pStreamConfig->Release(); _pStreamConfig=nullptr; } } /** @@ -628,7 +631,7 @@ WebcamVideoCursorDS:: PT(MovieVideoCursor::Buffer) WebcamVideoCursorDS:: fetch_buffer() { if (!_ready) { - return NULL; + return nullptr; } Buffer *buffer = get_standard_buffer(); diff --git a/panda/src/vision/webcamVideoOpenCV.cxx b/panda/src/vision/webcamVideoOpenCV.cxx index d4c68070fa..e7cadf8c69 100644 --- a/panda/src/vision/webcamVideoOpenCV.cxx +++ b/panda/src/vision/webcamVideoOpenCV.cxx @@ -46,7 +46,7 @@ WebcamVideoOpenCV:: WebcamVideoOpenCV(int camera_index) : _camera_index(camera_index) { - ostringstream strm; + std::ostringstream strm; strm << "OpenCV webcam " << _camera_index; set_name(strm.str()); } diff --git a/panda/src/vision/webcamVideoV4L.cxx b/panda/src/vision/webcamVideoV4L.cxx index 7d5636f4e0..bc6cad7a1b 100644 --- a/panda/src/vision/webcamVideoV4L.cxx +++ b/panda/src/vision/webcamVideoV4L.cxx @@ -94,7 +94,7 @@ TypeHandle WebcamVideoV4L::_type_handle; * */ void WebcamVideoV4L:: -add_options_for_size(int fd, const string &dev, const char *name, unsigned width, unsigned height, unsigned pixelformat) { +add_options_for_size(int fd, const std::string &dev, const char *name, unsigned width, unsigned height, unsigned pixelformat) { struct v4l2_frmivalenum frmivalenum; for (int k = 0;; k++) { memset(&frmivalenum, 0, sizeof frmivalenum); @@ -132,7 +132,7 @@ add_options_for_size(int fd, const string &dev, const char *name, unsigned width wc->_size_y = height; wc->_fps = fps; wc->_pformat = pixelformat; - wc->_pixel_format = string((char*) &pixelformat, 4); + wc->_pixel_format = std::string((char*) &pixelformat, 4); WebcamVideoV4L::_all_webcams.push_back(DCAST(WebcamVideo, wc)); } diff --git a/panda/src/vision/webcamVideoV4L.h b/panda/src/vision/webcamVideoV4L.h index 374daf6f76..40045ee402 100644 --- a/panda/src/vision/webcamVideoV4L.h +++ b/panda/src/vision/webcamVideoV4L.h @@ -31,11 +31,11 @@ private: friend class WebcamVideoCursorV4L; friend void find_all_webcams_v4l(); - static void add_options_for_size(int fd, const string &dev, const char *name, + static void add_options_for_size(int fd, const std::string &dev, const char *name, unsigned width, unsigned height, unsigned pixelformat); - string _device; + std::string _device; uint32_t _pformat; public: diff --git a/panda/src/vrpn/vrpnAnalog.I b/panda/src/vrpn/vrpnAnalog.I index 61efae3f51..afd951e417 100644 --- a/panda/src/vrpn/vrpnAnalog.I +++ b/panda/src/vrpn/vrpnAnalog.I @@ -15,7 +15,7 @@ * Returns the name of the analog device that was used to create this * VrpnAnalog. */ -INLINE const string &VrpnAnalog:: +INLINE const std::string &VrpnAnalog:: get_analog_name() const { return _analog_name; } diff --git a/panda/src/vrpn/vrpnAnalog.cxx b/panda/src/vrpn/vrpnAnalog.cxx index 0934f7a8d8..d0d1b773ca 100644 --- a/panda/src/vrpn/vrpnAnalog.cxx +++ b/panda/src/vrpn/vrpnAnalog.cxx @@ -24,7 +24,7 @@ * */ VrpnAnalog:: -VrpnAnalog(const string &analog_name, vrpn_Connection *connection) : +VrpnAnalog(const std::string &analog_name, vrpn_Connection *connection) : _analog_name(analog_name) { _analog = new vrpn_Analog_Remote(_analog_name.c_str(), connection); @@ -74,7 +74,7 @@ unmark(VrpnAnalogDevice *device) { * */ void VrpnAnalog:: -output(ostream &out) const { +output(std::ostream &out) const { out << _analog_name; } @@ -82,7 +82,7 @@ output(ostream &out) const { * */ void VrpnAnalog:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_analog_name() << " (" << _devices.size() << " devices)\n"; diff --git a/panda/src/vrpn/vrpnAnalog.h b/panda/src/vrpn/vrpnAnalog.h index 0816c48ff5..07f3c84b21 100644 --- a/panda/src/vrpn/vrpnAnalog.h +++ b/panda/src/vrpn/vrpnAnalog.h @@ -37,10 +37,10 @@ class VrpnAnalogDevice; */ class VrpnAnalog { public: - VrpnAnalog(const string &analog_name, vrpn_Connection *connection); + VrpnAnalog(const std::string &analog_name, vrpn_Connection *connection); ~VrpnAnalog(); - INLINE const string &get_analog_name() const; + INLINE const std::string &get_analog_name() const; INLINE bool is_empty() const; void mark(VrpnAnalogDevice *device); @@ -48,22 +48,22 @@ public: INLINE void poll(); - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; private: static void VRPN_CALLBACK vrpn_analog_callback(void *userdata, const vrpn_ANALOGCB info); private: - string _analog_name; + std::string _analog_name; vrpn_Analog_Remote *_analog; typedef pvector Devices; Devices _devices; }; -INLINE ostream &operator << (ostream &out, const VrpnAnalog &analog) { +INLINE std::ostream &operator << (std::ostream &out, const VrpnAnalog &analog) { analog.output(out); return out; } diff --git a/panda/src/vrpn/vrpnAnalogDevice.cxx b/panda/src/vrpn/vrpnAnalogDevice.cxx index 00da1a2240..101f097c52 100644 --- a/panda/src/vrpn/vrpnAnalogDevice.cxx +++ b/panda/src/vrpn/vrpnAnalogDevice.cxx @@ -20,7 +20,7 @@ TypeHandle VrpnAnalogDevice::_type_handle; * */ VrpnAnalogDevice:: -VrpnAnalogDevice(VrpnClient *client, const string &device_name, +VrpnAnalogDevice(VrpnClient *client, const std::string &device_name, VrpnAnalog *vrpn_analog) : ClientAnalogDevice(client, device_name), _vrpn_analog(vrpn_analog) diff --git a/panda/src/vrpn/vrpnAnalogDevice.h b/panda/src/vrpn/vrpnAnalogDevice.h index e34f864d1c..a778857f60 100644 --- a/panda/src/vrpn/vrpnAnalogDevice.h +++ b/panda/src/vrpn/vrpnAnalogDevice.h @@ -29,7 +29,7 @@ class VrpnAnalog; */ class VrpnAnalogDevice : public ClientAnalogDevice { public: - VrpnAnalogDevice(VrpnClient *client, const string &device_name, + VrpnAnalogDevice(VrpnClient *client, const std::string &device_name, VrpnAnalog *vrpn_analog); virtual ~VrpnAnalogDevice(); diff --git a/panda/src/vrpn/vrpnButton.I b/panda/src/vrpn/vrpnButton.I index e5252a8e19..ed10b89fae 100644 --- a/panda/src/vrpn/vrpnButton.I +++ b/panda/src/vrpn/vrpnButton.I @@ -15,7 +15,7 @@ * Returns the name of the button device that was used to create this * VrpnButton. */ -INLINE const string &VrpnButton:: +INLINE const std::string &VrpnButton:: get_button_name() const { return _button_name; } diff --git a/panda/src/vrpn/vrpnButton.cxx b/panda/src/vrpn/vrpnButton.cxx index cf17f6bade..71af239f88 100644 --- a/panda/src/vrpn/vrpnButton.cxx +++ b/panda/src/vrpn/vrpnButton.cxx @@ -24,7 +24,7 @@ * */ VrpnButton:: -VrpnButton(const string &button_name, vrpn_Connection *connection) : +VrpnButton(const std::string &button_name, vrpn_Connection *connection) : _button_name(button_name) { _button = new vrpn_Button_Remote(_button_name.c_str(), connection); @@ -74,7 +74,7 @@ unmark(VrpnButtonDevice *device) { * */ void VrpnButton:: -output(ostream &out) const { +output(std::ostream &out) const { out << _button_name; } @@ -82,7 +82,7 @@ output(ostream &out) const { * */ void VrpnButton:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_button_name() << " (" << _devices.size() << " devices)\n"; diff --git a/panda/src/vrpn/vrpnButton.h b/panda/src/vrpn/vrpnButton.h index bdd829ab98..1b9fc14cf4 100644 --- a/panda/src/vrpn/vrpnButton.h +++ b/panda/src/vrpn/vrpnButton.h @@ -36,10 +36,10 @@ class VrpnButtonDevice; */ class VrpnButton { public: - VrpnButton(const string &button_name, vrpn_Connection *connection); + VrpnButton(const std::string &button_name, vrpn_Connection *connection); ~VrpnButton(); - INLINE const string &get_button_name() const; + INLINE const std::string &get_button_name() const; INLINE bool is_empty() const; void mark(VrpnButtonDevice *device); @@ -47,22 +47,22 @@ public: INLINE void poll(); - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; private: static void VRPN_CALLBACK vrpn_button_callback(void *userdata, const vrpn_BUTTONCB info); private: - string _button_name; + std::string _button_name; vrpn_Button_Remote *_button; typedef pvector Devices; Devices _devices; }; -INLINE ostream &operator << (ostream &out, const VrpnButton &button) { +INLINE std::ostream &operator << (std::ostream &out, const VrpnButton &button) { button.output(out); return out; } diff --git a/panda/src/vrpn/vrpnButtonDevice.cxx b/panda/src/vrpn/vrpnButtonDevice.cxx index a392bbce49..eb287d2f5e 100644 --- a/panda/src/vrpn/vrpnButtonDevice.cxx +++ b/panda/src/vrpn/vrpnButtonDevice.cxx @@ -20,7 +20,7 @@ TypeHandle VrpnButtonDevice::_type_handle; * */ VrpnButtonDevice:: -VrpnButtonDevice(VrpnClient *client, const string &device_name, +VrpnButtonDevice(VrpnClient *client, const std::string &device_name, VrpnButton *vrpn_button) : ClientButtonDevice(client, device_name), _vrpn_button(vrpn_button) diff --git a/panda/src/vrpn/vrpnButtonDevice.h b/panda/src/vrpn/vrpnButtonDevice.h index 3c88da7f2b..45ba3df694 100644 --- a/panda/src/vrpn/vrpnButtonDevice.h +++ b/panda/src/vrpn/vrpnButtonDevice.h @@ -29,7 +29,7 @@ class VrpnButton; */ class VrpnButtonDevice : public ClientButtonDevice { public: - VrpnButtonDevice(VrpnClient *client, const string &device_name, + VrpnButtonDevice(VrpnClient *client, const std::string &device_name, VrpnButton *vrpn_button); virtual ~VrpnButtonDevice(); diff --git a/panda/src/vrpn/vrpnClient.I b/panda/src/vrpn/vrpnClient.I index 563428d917..486a4e29f6 100644 --- a/panda/src/vrpn/vrpnClient.I +++ b/panda/src/vrpn/vrpnClient.I @@ -14,7 +14,7 @@ /** * Returns the name of the server as passed to the VrpnClient constructor. */ -INLINE const string &VrpnClient:: +INLINE const std::string &VrpnClient:: get_server_name() const { return _server_name; } @@ -55,7 +55,7 @@ convert_to_secs(struct timeval msg_time) { * */ INLINE VrpnClient:: -VrpnClient(const string &server) : +VrpnClient(const std::string &server) : ClientBase(server) { _connection = vrpn_get_connection_by_name(server.c_str()); @@ -66,7 +66,7 @@ VrpnClient(const string &server) : * particular sensor we have interest in) */ INLINE void VrpnClient:: -tracker_position(const string &tracker, const vrpn_TRACKERCB info) { +tracker_position(const std::string &tracker, const vrpn_TRACKERCB info) { double ptime = convert_to_secs(info.msg_time); LPoint3 pos(info.pos[0], info.pos[1], info.pos[2]); LVector4 pquat(info.quat[0], info.quat[1], info.quat[2], info.quat[3]); @@ -79,7 +79,7 @@ tracker_position(const string &tracker, const vrpn_TRACKERCB info) { * particular sensor we have interest in) */ INLINE void VrpnClient:: -tracker_velocity(const string &tracker, const vrpn_TRACKERVELCB info) { +tracker_velocity(const std::string &tracker, const vrpn_TRACKERVELCB info) { double vtime = convert_to_secs(info.msg_time); LPoint3 vel(info.vel[0], info.vel[1], info.vel[2]); LVector4 vquat(info.vel_quat[0], info.vel_quat[1], @@ -93,7 +93,7 @@ tracker_velocity(const string &tracker, const vrpn_TRACKERVELCB info) { * particular sensor we have interest in) */ INLINE void VrpnClient:: -tracker_acceleration(const string &tracker, const vrpn_TRACKERACCCB info) { +tracker_acceleration(const std::string &tracker, const vrpn_TRACKERACCCB info) { double atime = convert_to_secs(info.msg_time); LPoint3 acc(info.acc[0], info.acc[1], info.acc[2]); LVector4 aquat(info.acc_quat[0], info.acc_quat[1], @@ -107,7 +107,7 @@ tracker_acceleration(const string &tracker, const vrpn_TRACKERACCCB info) { * Stores the latest information as sent by the analog device */ INLINE void VrpnClient:: -analog(const string &analog, const vrpn_ANALOGCB info) { +analog(const std::string &analog, const vrpn_ANALOGCB info) { double atime = convert_to_secs(info.msg_time); push_analog(analog, atime, info.channel, info.num_channel); @@ -117,7 +117,7 @@ analog(const string &analog, const vrpn_ANALOGCB info) { * Stores the latest button pressed information as sent by the button */ INLINE void VrpnClient:: -button(const string &button, const vrpn_BUTTONCB info) { +button(const std::string &button, const vrpn_BUTTONCB info) { double btime = convert_to_secs(info.msg_time); push_button(button, btime, info.button, info.state); @@ -127,7 +127,7 @@ button(const string &button, const vrpn_BUTTONCB info) { * Stores the latest change information as sent by the dial */ INLINE void VrpnClient:: -dial(const string &dial, const vrpn_DIALCB info) { +dial(const std::string &dial, const vrpn_DIALCB info) { double dtime = convert_to_secs(info.msg_time); push_dial(dial, dtime, info.dial, info.change); diff --git a/panda/src/vrpn/vrpnClient.cxx b/panda/src/vrpn/vrpnClient.cxx index 1e7ec5abf0..1fb7fcb4ff 100644 --- a/panda/src/vrpn/vrpnClient.cxx +++ b/panda/src/vrpn/vrpnClient.cxx @@ -26,6 +26,8 @@ #include "string_utils.h" #include "indent.h" +using std::string; + TypeHandle VrpnClient::_type_handle; /** @@ -41,7 +43,7 @@ VrpnClient(const string &server_name) : << "\n"; } _connection = vrpn_get_connection_by_name(_server_name.c_str()); - nassertv(_connection != (vrpn_Connection *)NULL); + nassertv(_connection != nullptr); if (!is_valid()) { vrpn_cat.warning() @@ -63,7 +65,7 @@ VrpnClient:: * polling each frame. */ void VrpnClient:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "VrpnClient, server " << _server_name << "\n"; @@ -140,7 +142,7 @@ make_device(TypeHandle device_type, const string &device_name) { return make_dial_device(device_name); } else { - return NULL; + return nullptr; } } @@ -625,7 +627,7 @@ bool VrpnClient:: add_remote_tracker(const string &tracker, int sensor) { vrpn_Tracker_Remote *vrpn_tracker = new vrpn_Tracker_Remote(tracker.c_str(), _connection); - if (vrpn_tracker == (vrpn_Tracker_Remote *)NULL) { + if (vrpn_tracker == nullptr) { return false; } @@ -654,7 +656,7 @@ bool VrpnClient:: add_remote_analog(const string &analog) { vrpn_Analog_Remote *vrpn_analog = new vrpn_Analog_Remote(analog.c_str(), _connection); - if (vrpn_analog == (vrpn_Analog_Remote *)NULL) { + if (vrpn_analog == nullptr) { return false; } @@ -680,7 +682,7 @@ bool VrpnClient:: add_remote_button(const string &button) { vrpn_Button_Remote *vrpn_button = new vrpn_Button_Remote(button.c_str(), _connection); - if (vrpn_button == (vrpn_Button_Remote *)NULL) { + if (vrpn_button == nullptr) { return false; } @@ -706,7 +708,7 @@ bool VrpnClient:: add_remote_dial(const string &dial) { vrpn_Dial_Remote *vrpn_dial = new vrpn_Dial_Remote(dial.c_str(), _connection); - if (vrpn_dial == (vrpn_Dial_Remote *)NULL) { + if (vrpn_dial == nullptr) { return false; } diff --git a/panda/src/vrpn/vrpnClient.h b/panda/src/vrpn/vrpnClient.h index 501c0e2ae8..127492d9cf 100644 --- a/panda/src/vrpn/vrpnClient.h +++ b/panda/src/vrpn/vrpnClient.h @@ -34,58 +34,58 @@ class VrpnDialDevice; */ class EXPCL_VRPN VrpnClient : public ClientBase { PUBLISHED: - explicit VrpnClient(const string &server_name); + explicit VrpnClient(const std::string &server_name); ~VrpnClient(); - INLINE const string &get_server_name() const; + INLINE const std::string &get_server_name() const; INLINE bool is_valid() const; INLINE bool is_connected() const; - void write(ostream &out, int indent_level = 0) const; + void write(std::ostream &out, int indent_level = 0) const; public: INLINE static double convert_to_secs(struct timeval msg_time); protected: virtual PT(ClientDevice) make_device(TypeHandle device_type, - const string &device_name); + const std::string &device_name); virtual bool disconnect_device(TypeHandle device_type, - const string &device_name, + const std::string &device_name, ClientDevice *device); virtual void do_poll(); private: - PT(ClientDevice) make_tracker_device(const string &device_name); - PT(ClientDevice) make_button_device(const string &device_name); - PT(ClientDevice) make_analog_device(const string &device_name); - PT(ClientDevice) make_dial_device(const string &device_name); + PT(ClientDevice) make_tracker_device(const std::string &device_name); + PT(ClientDevice) make_button_device(const std::string &device_name); + PT(ClientDevice) make_analog_device(const std::string &device_name); + PT(ClientDevice) make_dial_device(const std::string &device_name); void disconnect_tracker_device(VrpnTrackerDevice *device); void disconnect_button_device(VrpnButtonDevice *device); void disconnect_analog_device(VrpnAnalogDevice *device); void disconnect_dial_device(VrpnDialDevice *device); - VrpnTracker *get_tracker(const string &tracker_name); + VrpnTracker *get_tracker(const std::string &tracker_name); void free_tracker(VrpnTracker *vrpn_tracker); - VrpnButton *get_button(const string &button_name); + VrpnButton *get_button(const std::string &button_name); void free_button(VrpnButton *vrpn_button); - VrpnAnalog *get_analog(const string &analog_name); + VrpnAnalog *get_analog(const std::string &analog_name); void free_analog(VrpnAnalog *vrpn_analog); - VrpnDial *get_dial(const string &dial_name); + VrpnDial *get_dial(const std::string &dial_name); void free_dial(VrpnDial *vrpn_dial); private: - string _server_name; + std::string _server_name; vrpn_Connection *_connection; - typedef pmap Trackers; - typedef pmap Buttons; - typedef pmap Analogs; - typedef pmap Dials; + typedef pmap Trackers; + typedef pmap Buttons; + typedef pmap Analogs; + typedef pmap Dials; Trackers _trackers; Buttons _buttons; diff --git a/panda/src/vrpn/vrpnDial.I b/panda/src/vrpn/vrpnDial.I index 240f51fa40..2cb9981826 100644 --- a/panda/src/vrpn/vrpnDial.I +++ b/panda/src/vrpn/vrpnDial.I @@ -14,7 +14,7 @@ /** * Returns the name of the dial device that was used to create this VrpnDial. */ -INLINE const string &VrpnDial:: +INLINE const std::string &VrpnDial:: get_dial_name() const { return _dial_name; } diff --git a/panda/src/vrpn/vrpnDial.cxx b/panda/src/vrpn/vrpnDial.cxx index 57de1bd59c..5c06f797ee 100644 --- a/panda/src/vrpn/vrpnDial.cxx +++ b/panda/src/vrpn/vrpnDial.cxx @@ -24,7 +24,7 @@ * */ VrpnDial:: -VrpnDial(const string &dial_name, vrpn_Connection *connection) : +VrpnDial(const std::string &dial_name, vrpn_Connection *connection) : _dial_name(dial_name) { _dial = new vrpn_Dial_Remote(_dial_name.c_str(), connection); @@ -74,7 +74,7 @@ unmark(VrpnDialDevice *device) { * */ void VrpnDial:: -output(ostream &out) const { +output(std::ostream &out) const { out << _dial_name; } @@ -82,7 +82,7 @@ output(ostream &out) const { * */ void VrpnDial:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_dial_name() << " (" << _devices.size() << " devices)\n"; diff --git a/panda/src/vrpn/vrpnDial.h b/panda/src/vrpn/vrpnDial.h index 5500d730e0..e98fd7d99d 100644 --- a/panda/src/vrpn/vrpnDial.h +++ b/panda/src/vrpn/vrpnDial.h @@ -36,10 +36,10 @@ class VrpnDialDevice; */ class VrpnDial { public: - VrpnDial(const string &dial_name, vrpn_Connection *connection); + VrpnDial(const std::string &dial_name, vrpn_Connection *connection); ~VrpnDial(); - INLINE const string &get_dial_name() const; + INLINE const std::string &get_dial_name() const; INLINE bool is_empty() const; void mark(VrpnDialDevice *device); @@ -47,22 +47,22 @@ public: INLINE void poll(); - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; private: static void VRPN_CALLBACK vrpn_dial_callback(void *userdata, const vrpn_DIALCB info); private: - string _dial_name; + std::string _dial_name; vrpn_Dial_Remote *_dial; typedef pvector Devices; Devices _devices; }; -INLINE ostream &operator << (ostream &out, const VrpnDial &dial) { +INLINE std::ostream &operator << (std::ostream &out, const VrpnDial &dial) { dial.output(out); return out; } diff --git a/panda/src/vrpn/vrpnDialDevice.cxx b/panda/src/vrpn/vrpnDialDevice.cxx index 77be871f73..6331fb8a02 100644 --- a/panda/src/vrpn/vrpnDialDevice.cxx +++ b/panda/src/vrpn/vrpnDialDevice.cxx @@ -20,7 +20,7 @@ TypeHandle VrpnDialDevice::_type_handle; * */ VrpnDialDevice:: -VrpnDialDevice(VrpnClient *client, const string &device_name, +VrpnDialDevice(VrpnClient *client, const std::string &device_name, VrpnDial *vrpn_dial) : ClientDialDevice(client, device_name), _vrpn_dial(vrpn_dial) diff --git a/panda/src/vrpn/vrpnDialDevice.h b/panda/src/vrpn/vrpnDialDevice.h index 533f3b3f97..52bb88c587 100644 --- a/panda/src/vrpn/vrpnDialDevice.h +++ b/panda/src/vrpn/vrpnDialDevice.h @@ -29,7 +29,7 @@ class VrpnDial; */ class VrpnDialDevice : public ClientDialDevice { public: - VrpnDialDevice(VrpnClient *client, const string &device_name, + VrpnDialDevice(VrpnClient *client, const std::string &device_name, VrpnDial *vrpn_dial); virtual ~VrpnDialDevice(); diff --git a/panda/src/vrpn/vrpnTracker.I b/panda/src/vrpn/vrpnTracker.I index 9c97e92968..b651121923 100644 --- a/panda/src/vrpn/vrpnTracker.I +++ b/panda/src/vrpn/vrpnTracker.I @@ -15,7 +15,7 @@ * Returns the name of the tracker device that was used to create this * VrpnTracker. */ -INLINE const string &VrpnTracker:: +INLINE const std::string &VrpnTracker:: get_tracker_name() const { return _tracker_name; } diff --git a/panda/src/vrpn/vrpnTracker.cxx b/panda/src/vrpn/vrpnTracker.cxx index 6427c6c392..6e4e196769 100644 --- a/panda/src/vrpn/vrpnTracker.cxx +++ b/panda/src/vrpn/vrpnTracker.cxx @@ -24,7 +24,7 @@ * */ VrpnTracker:: -VrpnTracker(const string &tracker_name, vrpn_Connection *connection) : +VrpnTracker(const std::string &tracker_name, vrpn_Connection *connection) : _tracker_name(tracker_name) { _tracker = new vrpn_Tracker_Remote(_tracker_name.c_str(), connection); @@ -76,7 +76,7 @@ unmark(VrpnTrackerDevice *device) { * */ void VrpnTracker:: -output(ostream &out) const { +output(std::ostream &out) const { out << _tracker_name; } @@ -84,7 +84,7 @@ output(ostream &out) const { * */ void VrpnTracker:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_tracker_name() << " (" << _devices.size() << " devices)\n"; diff --git a/panda/src/vrpn/vrpnTracker.h b/panda/src/vrpn/vrpnTracker.h index acfdcaff5b..1b6c30347d 100644 --- a/panda/src/vrpn/vrpnTracker.h +++ b/panda/src/vrpn/vrpnTracker.h @@ -36,10 +36,10 @@ class VrpnTrackerDevice; */ class VrpnTracker { public: - VrpnTracker(const string &tracker_name, vrpn_Connection *connection); + VrpnTracker(const std::string &tracker_name, vrpn_Connection *connection); ~VrpnTracker(); - INLINE const string &get_tracker_name() const; + INLINE const std::string &get_tracker_name() const; INLINE bool is_empty() const; void mark(VrpnTrackerDevice *device); @@ -47,8 +47,8 @@ public: INLINE void poll(); - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; private: static void VRPN_CALLBACK @@ -59,14 +59,14 @@ private: vrpn_acceleration_callback(void *userdata, const vrpn_TRACKERACCCB info); private: - string _tracker_name; + std::string _tracker_name; vrpn_Tracker_Remote *_tracker; typedef pvector Devices; Devices _devices; }; -INLINE ostream &operator << (ostream &out, const VrpnTracker &tracker) { +INLINE std::ostream &operator << (std::ostream &out, const VrpnTracker &tracker) { tracker.output(out); return out; } diff --git a/panda/src/vrpn/vrpnTrackerDevice.cxx b/panda/src/vrpn/vrpnTrackerDevice.cxx index 5484df2c23..980f9cf77c 100644 --- a/panda/src/vrpn/vrpnTrackerDevice.cxx +++ b/panda/src/vrpn/vrpnTrackerDevice.cxx @@ -20,7 +20,7 @@ TypeHandle VrpnTrackerDevice::_type_handle; * */ VrpnTrackerDevice:: -VrpnTrackerDevice(VrpnClient *client, const string &device_name, +VrpnTrackerDevice(VrpnClient *client, const std::string &device_name, int sensor, VrpnTrackerDevice::DataType data_type, VrpnTracker *vrpn_tracker) : ClientTrackerDevice(client, device_name), diff --git a/panda/src/vrpn/vrpnTrackerDevice.h b/panda/src/vrpn/vrpnTrackerDevice.h index 17a626795e..58ddf9068b 100644 --- a/panda/src/vrpn/vrpnTrackerDevice.h +++ b/panda/src/vrpn/vrpnTrackerDevice.h @@ -39,7 +39,7 @@ public: DT_acceleration }; - VrpnTrackerDevice(VrpnClient *client, const string &device_name, + VrpnTrackerDevice(VrpnClient *client, const std::string &device_name, int sensor, DataType data_type, VrpnTracker *vrpn_tracker); virtual ~VrpnTrackerDevice(); diff --git a/panda/src/vrpn/vrpn_interface.h b/panda/src/vrpn/vrpn_interface.h index e3626e9055..a788d7ae73 100644 --- a/panda/src/vrpn/vrpn_interface.h +++ b/panda/src/vrpn/vrpn_interface.h @@ -19,7 +19,6 @@ #ifdef CPPPARSER // For correct interrogate parsing of UNC's vrpn library. #if defined(WIN32_VC) || defined(WIN64_VC) - #define _WIN32 #define SOCKET int #else #define linux diff --git a/panda/src/wgldisplay/config_wgldisplay.cxx b/panda/src/wgldisplay/config_wgldisplay.cxx index 93dc2ad36c..fa04606dca 100644 --- a/panda/src/wgldisplay/config_wgldisplay.cxx +++ b/panda/src/wgldisplay/config_wgldisplay.cxx @@ -20,8 +20,8 @@ #include "dconfig.h" #include "pandaSystem.h" -#if !defined(CPPPARSER) && !defined(BUILDING_PANDAGL) - #error Buildsystem error: BUILDING_PANDAGL not defined +#if !defined(CPPPARSER) && !defined(BUILDING_PANDA_WGLDISPLAY) + #error Buildsystem error: BUILDING_PANDA_WGLDISPLAY not defined #endif Configure(config_wgldisplay); diff --git a/panda/src/wgldisplay/config_wgldisplay.h b/panda/src/wgldisplay/config_wgldisplay.h index 400b565bbd..e4c2096b5e 100644 --- a/panda/src/wgldisplay/config_wgldisplay.h +++ b/panda/src/wgldisplay/config_wgldisplay.h @@ -19,12 +19,12 @@ #include "configVariableInt.h" #include "configVariableBool.h" -NotifyCategoryDecl(wgldisplay, EXPCL_PANDAGL, EXPTP_PANDAGL); +NotifyCategoryDecl(wgldisplay, EXPCL_PANDA_WGLDISPLAY, EXPTP_PANDA_WGLDISPLAY); extern ConfigVariableInt gl_force_pixfmt; extern ConfigVariableBool gl_force_invalid; extern ConfigVariableBool gl_do_vidmemsize_check; -extern EXPCL_PANDAGL void init_libwgldisplay(); +extern EXPCL_PANDA_WGLDISPLAY void init_libwgldisplay(); #endif diff --git a/panda/src/wgldisplay/wglGraphicsBuffer.cxx b/panda/src/wgldisplay/wglGraphicsBuffer.cxx index 309533df4b..aacedf0ae3 100644 --- a/panda/src/wgldisplay/wglGraphicsBuffer.cxx +++ b/panda/src/wgldisplay/wglGraphicsBuffer.cxx @@ -28,7 +28,7 @@ TypeHandle wglGraphicsBuffer::_type_handle; */ wglGraphicsBuffer:: wglGraphicsBuffer(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -62,7 +62,7 @@ bool wglGraphicsBuffer:: begin_frame(FrameMode mode, Thread *current_thread) { begin_frame_spam(mode); - if (_gsg == (GraphicsStateGuardian *)NULL) { + if (_gsg == nullptr) { return false; } @@ -117,7 +117,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { void wglGraphicsBuffer:: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); - nassertv(_gsg != (GraphicsStateGuardian *)NULL); + nassertv(_gsg != nullptr); if (mode == FM_render) { copy_to_textures(); @@ -171,7 +171,7 @@ bind_texture_to_pbuffer() { } } TextureContext *tc = tex->prepare_now(0, _gsg->get_prepared_objects(), _gsg); - nassertv(tc != (TextureContext *)NULL); + nassertv(tc != nullptr); CLP(TextureContext) *gtc = DCAST(CLP(TextureContext), tc); GLenum target = wglgsg->get_texture_target(tex->get_texture_type()); if (target == GL_NONE) { @@ -205,7 +205,7 @@ select_target_tex_page(int page) { wglGraphicsStateGuardian *wglgsg; DCAST_INTO_V(wglgsg, _gsg); - nassertv(wglgsg->_wglSetPbufferAttribARB != NULL); + nassertv(wglgsg->_wglSetPbufferAttribARB != nullptr); static const int max_attrib_list = 64; int iattrib_list[max_attrib_list]; @@ -236,7 +236,7 @@ process_events() { // Handle all the messages on the queue in a row. Some of these might be // for another window, but they will get dispatched appropriately. - while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { + while (PeekMessage(&msg, nullptr, 0, 0, PM_NOREMOVE)) { process_1_event(); } } @@ -248,7 +248,7 @@ process_events() { */ bool wglGraphicsBuffer:: get_supports_render_texture() const { - if (_gsg == (GraphicsStateGuardian *)NULL) { + if (_gsg == nullptr) { return false; } @@ -262,7 +262,7 @@ get_supports_render_texture() const { */ void wglGraphicsBuffer:: close_buffer() { - if (_gsg != (GraphicsStateGuardian *)NULL) { + if (_gsg != nullptr) { wglGraphicsStateGuardian *wglgsg; DCAST_INTO_V(wglgsg, _gsg); @@ -294,7 +294,7 @@ open_buffer() { wglGraphicsStateGuardian *wglgsg; if (_gsg == 0) { // There is no old gsg. Create a new one. - wglgsg = new wglGraphicsStateGuardian(_engine, _pipe, NULL); + wglgsg = new wglGraphicsStateGuardian(_engine, _pipe, nullptr); wglgsg->choose_pixel_format(_fb_properties, true); _gsg = wglgsg; } else { @@ -315,12 +315,12 @@ open_buffer() { HDC twindow_dc = wglgsg->get_twindow_dc(); if (twindow_dc == 0) { // If we couldn't make a window, we can't get a GL context. - _gsg = NULL; + _gsg = nullptr; return false; } HGLRC context = wglgsg->get_context(twindow_dc); if (context == 0) { - _gsg = NULL; + _gsg = nullptr; return false; } wglGraphicsPipe::wgl_make_current(twindow_dc, context, @@ -329,7 +329,7 @@ open_buffer() { wglgsg->report_my_gl_errors(); if (!wglgsg->get_fb_properties().verify_hardware_software (_fb_properties,wglgsg->get_gl_renderer())) { - _gsg = NULL; + _gsg = nullptr; return false; } _fb_properties = wglgsg->get_fb_properties(); @@ -340,7 +340,7 @@ open_buffer() { if (!rebuild_bitplanes()) { wglGraphicsPipe::wgl_make_current(0, 0, &_make_current_pcollector); - _gsg = NULL; + _gsg = nullptr; return false; } @@ -366,7 +366,7 @@ release_pbuffer() { _pbuffer_bound->release(wglgsg->get_prepared_objects()); _pbuffer_bound = 0; } - wglGraphicsPipe::wgl_make_current(0, 0, NULL); + wglGraphicsPipe::wgl_make_current(0, 0, nullptr); if (_pbuffer_dc) { wglgsg->_wglReleasePbufferDCARB(_pbuffer, _pbuffer_dc); } @@ -398,7 +398,7 @@ rebuild_bitplanes() { } // Find the texture to bind to the color buffer. - Texture *bindtexture = NULL; + Texture *bindtexture = nullptr; for (int i=0; iget_format() != Texture::F_depth_stencil)) { @@ -530,7 +530,7 @@ void wglGraphicsBuffer:: process_1_event() { MSG msg; - if (!GetMessage(&msg, NULL, 0, 0)) { + if (!GetMessage(&msg, nullptr, 0, 0)) { // WM_QUIT received. We need a cleaner way to deal with this. // DestroyAllWindows(false); exit(msg.wParam); // this will invoke AtExitFn diff --git a/panda/src/wgldisplay/wglGraphicsBuffer.h b/panda/src/wgldisplay/wglGraphicsBuffer.h index e5155e8653..3560d3f4b5 100644 --- a/panda/src/wgldisplay/wglGraphicsBuffer.h +++ b/panda/src/wgldisplay/wglGraphicsBuffer.h @@ -32,10 +32,10 @@ * we can use, and thus makes it difficult to support one GSG rendering into * an offscreen buffer and also into a window. */ -class EXPCL_PANDAGL wglGraphicsBuffer : public GraphicsBuffer { +class EXPCL_PANDA_WGLDISPLAY wglGraphicsBuffer : public GraphicsBuffer { public: wglGraphicsBuffer(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/wgldisplay/wglGraphicsPipe.cxx b/panda/src/wgldisplay/wglGraphicsPipe.cxx index ee2c2a7522..4186c35a35 100644 --- a/panda/src/wgldisplay/wglGraphicsPipe.cxx +++ b/panda/src/wgldisplay/wglGraphicsPipe.cxx @@ -18,12 +18,11 @@ #include "wglGraphicsBuffer.h" #include "wglGraphicsStateGuardian.h" -typedef enum {Software, MCD, ICD} OGLDriverType; - TypeHandle wglGraphicsPipe::_type_handle; bool wglGraphicsPipe::_current_valid; HDC wglGraphicsPipe::_current_hdc; HGLRC wglGraphicsPipe::_current_hglrc; +Thread *wglGraphicsPipe::_current_thread; /** * @@ -43,16 +42,19 @@ wglGraphicsPipe:: /** * a thin wrapper around wglMakeCurrent to avoid unnecessary OS-call overhead. */ -void wglGraphicsPipe:: +bool wglGraphicsPipe:: wgl_make_current(HDC hdc, HGLRC hglrc, PStatCollector *collector) { + Thread *thread = Thread::get_current_thread(); if ((_current_valid) && (_current_hdc == hdc) && - (_current_hglrc == hglrc)) { - return; + (_current_hglrc == hglrc) && + (_current_thread == thread)) { + return true; } _current_valid = true; _current_hdc = hdc; _current_hglrc = hglrc; + _current_thread = thread; BOOL res; if (collector) { PStatTimer timer(*collector); @@ -60,6 +62,7 @@ wgl_make_current(HDC hdc, HGLRC hglrc, PStatCollector *collector) { } else { res = wglMakeCurrent(hdc, hglrc); } + return (res != 0); } /** @@ -68,7 +71,7 @@ wgl_make_current(HDC hdc, HGLRC hglrc, PStatCollector *collector) { * choose between several possible GraphicsPipes available on a particular * platform, so the name should be meaningful and unique for a given platform. */ -string wglGraphicsPipe:: +std::string wglGraphicsPipe:: get_interface_name() const { return "OpenGL"; } @@ -87,7 +90,7 @@ pipe_constructor() { * only called from GraphicsEngine::make_output. */ PT(GraphicsOutput) wglGraphicsPipe:: -make_output(const string &name, +make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -98,12 +101,12 @@ make_output(const string &name, bool &precertify) { if (!_is_valid) { - return NULL; + return nullptr; } wglGraphicsStateGuardian *wglgsg = 0; if (gsg != 0) { - DCAST_INTO_R(wglgsg, gsg, NULL); + DCAST_INTO_R(wglgsg, gsg, nullptr); } bool support_rtt; @@ -125,13 +128,13 @@ make_output(const string &name, ((flags&BF_can_bind_color)!=0)|| ((flags&BF_can_bind_every)!=0)|| ((flags&BF_can_bind_layered)!=0)) { - return NULL; + return nullptr; } if ((flags & BF_fb_props_optional)==0) { if ((fb_prop.get_aux_rgba() > 0)|| (fb_prop.get_aux_hrgba() > 0)|| (fb_prop.get_aux_float() > 0)) { - return NULL; + return nullptr; } } return new wglGraphicsWindow(engine, this, name, fb_prop, win_prop, @@ -141,9 +144,9 @@ make_output(const string &name, // Second thing to try: a GLGraphicsBuffer if (retry == 1) { - if (!gl_support_fbo || host == NULL || + if (!gl_support_fbo || host == nullptr || (flags & (BF_require_parasite | BF_require_window)) != 0) { - return NULL; + return nullptr; } // Early failure - if we are sure that this buffer WONT meet specs, we can // bail out early. @@ -151,13 +154,13 @@ make_output(const string &name, if (fb_prop.get_indexed_color() || fb_prop.get_back_buffers() > 0 || fb_prop.get_accum_bits() > 0) { - return NULL; + return nullptr; } } - if (wglgsg != NULL && wglgsg->is_valid() && !wglgsg->needs_reset()) { + if (wglgsg != nullptr && wglgsg->is_valid() && !wglgsg->needs_reset()) { if (!wglgsg->_supports_framebuffer_object || - wglgsg->_glDrawBuffers == NULL) { - return NULL; + wglgsg->_glDrawBuffers == nullptr) { + return nullptr; } else { // Early success - if we are sure that this buffer WILL meet specs, we // can precertify it. @@ -174,13 +177,13 @@ make_output(const string &name, if (((flags&BF_require_parasite)!=0)|| ((flags&BF_require_window)!=0)|| ((flags&BF_can_bind_layered)!=0)) { - return NULL; + return nullptr; } if ((wglgsg != 0) && (wglgsg->is_valid()) && (!wglgsg->needs_reset()) && !wglgsg->_supports_pbuffer) { - return NULL; + return nullptr; } if (!support_rtt) { @@ -188,7 +191,7 @@ make_output(const string &name, ((flags&BF_can_bind_every)!=0)) { // If we require Render-to-Texture, but can't be sure we support it, // bail. - return NULL; + return nullptr; } } @@ -198,7 +201,7 @@ make_output(const string &name, if ((fb_prop.get_aux_rgba() > 0)|| (fb_prop.get_aux_rgba() > 0)|| (fb_prop.get_aux_float() > 0)) { - return NULL; + return nullptr; } } // Early success - if we are sure that this buffer WILL meet specs, we can @@ -216,7 +219,7 @@ make_output(const string &name, } // Nothing else left to try. - return NULL; + return nullptr; } /** @@ -227,14 +230,14 @@ make_output(const string &name, */ PT(GraphicsStateGuardian) wglGraphicsPipe:: make_callback_gsg(GraphicsEngine *engine) { - return new wglGraphicsStateGuardian(engine, this, NULL); + return new wglGraphicsStateGuardian(engine, this, nullptr); } /** * Returns pfd_flags formatted as a string in a user-friendly way. */ -string wglGraphicsPipe:: +std::string wglGraphicsPipe:: format_pfd_flags(DWORD pfd_flags) { struct FlagDef { DWORD flag; @@ -257,7 +260,7 @@ format_pfd_flags(DWORD pfd_flags) { }; static const int num_flag_defs = sizeof(flag_def) / sizeof(FlagDef); - ostringstream out; + std::ostringstream out; const char *sep = ""; bool got_any = false; @@ -271,7 +274,7 @@ format_pfd_flags(DWORD pfd_flags) { } if (pfd_flags != 0 || !got_any) { - out << sep << hex << "0x" << pfd_flags << dec; + out << sep << std::hex << "0x" << pfd_flags << std::dec; } return out.str(); diff --git a/panda/src/wgldisplay/wglGraphicsPipe.h b/panda/src/wgldisplay/wglGraphicsPipe.h index 2ac6d8d29d..49ff95cd5a 100644 --- a/panda/src/wgldisplay/wglGraphicsPipe.h +++ b/panda/src/wgldisplay/wglGraphicsPipe.h @@ -23,16 +23,16 @@ class wglGraphicsStateGuardian; * This graphics pipe represents the interface for creating OpenGL graphics * windows on the various Windows OSes. */ -class EXPCL_PANDAGL wglGraphicsPipe : public WinGraphicsPipe { +class EXPCL_PANDA_WGLDISPLAY wglGraphicsPipe : public WinGraphicsPipe { public: wglGraphicsPipe(); virtual ~wglGraphicsPipe(); - virtual string get_interface_name() const; + virtual std::string get_interface_name() const; static PT(GraphicsPipe) pipe_constructor(); protected: - virtual PT(GraphicsOutput) make_output(const string &name, + virtual PT(GraphicsOutput) make_output(const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -45,12 +45,13 @@ protected: private: - static string format_pfd_flags(DWORD pfd_flags); - static void wgl_make_current(HDC hdc, HGLRC hglrc, PStatCollector *collector); + static std::string format_pfd_flags(DWORD pfd_flags); + static bool wgl_make_current(HDC hdc, HGLRC hglrc, PStatCollector *collector); static bool _current_valid; static HDC _current_hdc; static HGLRC _current_hglrc; + static Thread *_current_thread; public: static TypeHandle get_class_type() { diff --git a/panda/src/wgldisplay/wglGraphicsStateGuardian.cxx b/panda/src/wgldisplay/wglGraphicsStateGuardian.cxx index 9d916129a4..735f7fc409 100644 --- a/panda/src/wgldisplay/wglGraphicsStateGuardian.cxx +++ b/panda/src/wgldisplay/wglGraphicsStateGuardian.cxx @@ -32,7 +32,7 @@ wglGraphicsStateGuardian(GraphicsEngine *engine, GraphicsPipe *pipe, _share_with(share_with) { _made_context = false; - _context = (HGLRC)NULL; + _context = (HGLRC)nullptr; _twindow = (HWND)0; _twindow_dc = (HDC)0; @@ -46,7 +46,7 @@ wglGraphicsStateGuardian(GraphicsEngine *engine, GraphicsPipe *pipe, _supports_wgl_multisample = false; _supports_wgl_render_texture = false; - _wglCreateContextAttribsARB = NULL; + _wglCreateContextAttribsARB = nullptr; get_gamma_table(); atexit(atexit_function); @@ -58,9 +58,9 @@ wglGraphicsStateGuardian(GraphicsEngine *engine, GraphicsPipe *pipe, wglGraphicsStateGuardian:: ~wglGraphicsStateGuardian() { release_twindow(); - if (_context != (HGLRC)NULL) { + if (_context != (HGLRC)nullptr) { wglDeleteContext(_context); - _context = (HGLRC)NULL; + _context = (HGLRC)nullptr; } } @@ -123,7 +123,6 @@ get_properties(FrameBufferProperties &properties, HDC hdc, int pfnum) { pfd.cBlueBits, pfd.cAlphaBits); } - int mode = 0; if (pfd.dwFlags & PFD_DOUBLEBUFFER) { properties.set_back_buffers(1); } @@ -193,7 +192,6 @@ get_properties_advanced(FrameBufferProperties &properties, properties.clear(); properties.set_all_specified(); - int frame_buffer_mode = 0; if (ivalue_list[acceleration_i] == WGL_NO_ACCELERATION_ARB) { properties.set_force_software(true); } else { @@ -270,9 +268,9 @@ choose_pixel_format(const FrameBufferProperties &properties, int best_quality = 0; FrameBufferProperties best_prop; - HDC hdc = GetDC(NULL); + HDC hdc = GetDC(nullptr); - int max_pfnum = DescribePixelFormat(hdc, 1, 0, NULL); + int max_pfnum = DescribePixelFormat(hdc, 1, 0, nullptr); for (int pfnum = 0; pfnum 0) { attrib_list[n++] = WGL_CONTEXT_MAJOR_VERSION_ARB; @@ -614,14 +617,14 @@ make_context(HDC hdc) { attrib_list[n++] = WGL_CONTEXT_PROFILE_MASK_ARB; attrib_list[n++] = WGL_CONTEXT_CORE_PROFILE_BIT_ARB; #endif - attrib_list[n] = NULL; + attrib_list[n] = 0; _context = _wglCreateContextAttribsARB(hdc, 0, attrib_list); } else { _context = wglCreateContext(hdc); } - if (_context == NULL) { + if (_context == nullptr) { wgldisplay_cat.error() << "Could not create GL context.\n"; _is_valid = false; @@ -629,9 +632,9 @@ make_context(HDC hdc) { } // Now share texture context with the indicated GSG. - if (_share_with != (wglGraphicsStateGuardian *)NULL) { + if (_share_with != nullptr) { HGLRC share_context = _share_with->get_share_context(); - if (share_context == NULL) { + if (share_context == nullptr) { // Whoops, the target context hasn't yet made its own context. In that // case, it will share context with us. _share_with->redirect_share_pool(this); @@ -649,7 +652,7 @@ make_context(HDC hdc) { } } - _share_with = (wglGraphicsStateGuardian *)NULL; + _share_with = nullptr; } } @@ -665,10 +668,10 @@ get_share_context() const { if (_made_context) { return _context; } - if (_share_with != (wglGraphicsStateGuardian *)NULL) { + if (_share_with != nullptr) { return _share_with->get_share_context(); } - return NULL; + return nullptr; } /** @@ -682,7 +685,7 @@ get_share_context() const { void wglGraphicsStateGuardian:: redirect_share_pool(wglGraphicsStateGuardian *share_with) { nassertv(!_made_context); - if (_share_with != (wglGraphicsStateGuardian *)NULL) { + if (_share_with != nullptr) { _share_with->redirect_share_pool(share_with); } else { _share_with = share_with; @@ -702,13 +705,13 @@ make_twindow() { DWORD window_style = 0; register_twindow_class(); - HINSTANCE hinstance = GetModuleHandle(NULL); + HINSTANCE hinstance = GetModuleHandle(nullptr); _twindow = CreateWindow(_twindow_class_name, "twindow", window_style, - 0, 0, 1, 1, NULL, NULL, hinstance, 0); + 0, 0, 1, 1, nullptr, nullptr, hinstance, 0); if (!_twindow) { wgldisplay_cat.error() - << "CreateWindow() failed!" << endl; + << "CreateWindow() failed!" << std::endl; return false; } @@ -755,7 +758,7 @@ register_twindow_class() { WNDCLASS wc; - HINSTANCE instance = GetModuleHandle(NULL); + HINSTANCE instance = GetModuleHandle(nullptr); // Clear before filling in window structure! ZeroMemory(&wc, sizeof(WNDCLASS)); @@ -766,7 +769,7 @@ register_twindow_class() { if (!RegisterClass(&wc)) { wgldisplay_cat.error() - << "could not register window class!" << endl; + << "could not register window class!" << std::endl; return; } _twindow_class_registered = true; @@ -836,7 +839,7 @@ get_gamma_table(void) { get = false; if (_gamma_table_initialized == false) { - HDC hdc = GetDC(NULL); + HDC hdc = GetDC(nullptr); if (hdc) { if (GetDeviceGammaRamp (hdc, (LPVOID) _orignial_gamma_table)) { @@ -844,7 +847,7 @@ get_gamma_table(void) { get = true; } - ReleaseDC (NULL, hdc); + ReleaseDC (nullptr, hdc); } } @@ -857,7 +860,7 @@ get_gamma_table(void) { bool wglGraphicsStateGuardian:: static_set_gamma(bool restore, PN_stdfloat gamma) { bool set; - HDC hdc = GetDC(NULL); + HDC hdc = GetDC(nullptr); set = false; if (hdc) { @@ -874,7 +877,7 @@ static_set_gamma(bool restore, PN_stdfloat gamma) { set = true; } - ReleaseDC (NULL, hdc); + ReleaseDC (nullptr, hdc); } return set; diff --git a/panda/src/wgldisplay/wglGraphicsWindow.cxx b/panda/src/wgldisplay/wglGraphicsWindow.cxx index 06fc3d3ed4..6ff5b88c36 100644 --- a/panda/src/wgldisplay/wglGraphicsWindow.cxx +++ b/panda/src/wgldisplay/wglGraphicsWindow.cxx @@ -28,7 +28,7 @@ TypeHandle wglGraphicsWindow::_type_handle; */ wglGraphicsWindow:: wglGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -56,7 +56,7 @@ bool wglGraphicsWindow:: begin_frame(FrameMode mode, Thread *current_thread) { begin_frame_spam(mode); - if (_gsg == (GraphicsStateGuardian *)NULL) { + if (_gsg == nullptr) { return false; } @@ -79,7 +79,11 @@ begin_frame(FrameMode mode, Thread *current_thread) { HGLRC context = wglgsg->get_context(_hdc); nassertr(context, false); - wglGraphicsPipe::wgl_make_current(_hdc, context, &_make_current_pcollector); + if (!wglGraphicsPipe::wgl_make_current(_hdc, context, &_make_current_pcollector)) { + wgldisplay_cat.error() + << "Failed to make WGL context current.\n"; + return false; + } wglgsg->reset_if_new(); if (mode == FM_render) { @@ -99,7 +103,7 @@ void wglGraphicsWindow:: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); - nassertv(_gsg != (GraphicsStateGuardian *)NULL); + nassertv(_gsg != nullptr); if (mode == FM_render) { copy_to_textures(); @@ -164,7 +168,7 @@ ready_flip() { */ void wglGraphicsWindow:: end_flip() { - if (_hdc != NULL && _flip_ready) { + if (_hdc != nullptr && _flip_ready) { // The documentation on SwapBuffers() is not at all clear on whether the // GL context needs to be current before it can be called. Empirically, // it appears that it is not necessary in many cases, but it definitely is @@ -184,8 +188,8 @@ end_flip() { */ void wglGraphicsWindow:: close_window() { - if (_gsg != (GraphicsStateGuardian *)NULL) { - wglGraphicsPipe::wgl_make_current(_hdc, NULL, &_make_current_pcollector); + if (_gsg != nullptr) { + wglGraphicsPipe::wgl_make_current(_hdc, nullptr, &_make_current_pcollector); _gsg.clear(); } ReleaseDC(_hWnd, _hdc); @@ -208,7 +212,7 @@ open_window() { wglGraphicsStateGuardian *wglgsg; if (_gsg == 0) { // There is no old gsg. Create a new one. - wglgsg = new wglGraphicsStateGuardian(_engine, _pipe, NULL); + wglgsg = new wglGraphicsStateGuardian(_engine, _pipe, nullptr); wglgsg->choose_pixel_format(_fb_properties, false); _gsg = wglgsg; } else { @@ -357,8 +361,8 @@ setup_colormap(const PIXELFORMATDESCRIPTOR &pixelformat) { #ifdef NOTIFY_DEBUG -// typedef enum {Software, MCD, ICD} OGLDriverType; -static char *OGLDrvStrings[3] = {"Software","MCD","ICD"}; +typedef enum {Software, MCD, ICD} OGLDriverType; +static const char *OGLDrvStrings[3] = {"Software","MCD","ICD"}; /** * Reports information about the selected pixel format descriptor, along with @@ -386,7 +390,7 @@ print_pfd(PIXELFORMATDESCRIPTOR *pfd, char *msg) { wgldisplay_cat.debug() << msg << ", " << OGLDrvStrings[drvtype] << " driver\n" - << "PFD flags: 0x" << hex << pfd->dwFlags << dec << " (" + << "PFD flags: 0x" << std::hex << pfd->dwFlags << std::dec << " (" << PRINT_FLAG(GENERIC_ACCELERATED) << PRINT_FLAG(GENERIC_FORMAT) << PRINT_FLAG(DOUBLEBUFFER) @@ -403,15 +407,15 @@ print_pfd(PIXELFORMATDESCRIPTOR *pfd, char *msg) { << PRINT_FLAG(SUPPORT_DIRECTDRAW) << ")\n" << "PFD iPixelType: " << ((pfd->iPixelType==PFD_TYPE_RGBA) ? "PFD_TYPE_RGBA":"PFD_TYPE_COLORINDEX") - << endl + << std::endl << "PFD cColorBits: " << (DWORD)pfd->cColorBits << " R: " << (DWORD)pfd->cRedBits <<" G: " << (DWORD)pfd->cGreenBits - <<" B: " << (DWORD)pfd->cBlueBits << endl + <<" B: " << (DWORD)pfd->cBlueBits << std::endl << "PFD cAlphaBits: " << (DWORD)pfd->cAlphaBits << " DepthBits: " << (DWORD)pfd->cDepthBits <<" StencilBits: " << (DWORD)pfd->cStencilBits <<" AccumBits: " << (DWORD)pfd->cAccumBits - << endl; + << std::endl; } #endif diff --git a/panda/src/wgldisplay/wglGraphicsWindow.h b/panda/src/wgldisplay/wglGraphicsWindow.h index 9236640876..06a74aa501 100644 --- a/panda/src/wgldisplay/wglGraphicsWindow.h +++ b/panda/src/wgldisplay/wglGraphicsWindow.h @@ -20,10 +20,10 @@ /** * A single graphics window for rendering OpenGL under Microsoft Windows. */ -class EXPCL_PANDAGL wglGraphicsWindow : public WinGraphicsWindow { +class EXPCL_PANDA_WGLDISPLAY wglGraphicsWindow : public WinGraphicsWindow { public: wglGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, diff --git a/panda/src/windisplay/winDetectDx.h b/panda/src/windisplay/winDetectDx.h index 8a3a9c340e..df7d89f0ff 100644 --- a/panda/src/windisplay/winDetectDx.h +++ b/panda/src/windisplay/winDetectDx.h @@ -72,9 +72,9 @@ static DWORD _GetLastError (char *message_prefix) { error = GetLastError ( ); if (FormatMessage ( FORMAT_MESSAGE_ALLOCATE_BUFFER |FORMAT_MESSAGE_FROM_SYSTEM, - NULL, error, MAKELANGID( LANG_ENGLISH, SUBLANG_ENGLISH_US ), - (LPTSTR)&ptr,0, NULL)) { - cout << "ERROR: "<< message_prefix << " result = " << (char*) ptr << "\n"; + nullptr, error, MAKELANGID( LANG_ENGLISH, SUBLANG_ENGLISH_US ), + (LPTSTR)&ptr,0, nullptr)) { + std::cout << "ERROR: "<< message_prefix << " result = " << (char*) ptr << "\n"; LocalFree( ptr ); } @@ -94,13 +94,13 @@ static DWORD print_GetLastError (char *message_prefix) error = GetLastError ( ); if (FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, + nullptr, error, MAKELANGID( LANG_ENGLISH, SUBLANG_ENGLISH_US ), (LPTSTR)&ptr, - 0, NULL)) + 0, nullptr)) { - cout << "ERROR: "<< message_prefix << " result = " << (char*) ptr << "\n"; + std::cout << "ERROR: "<< message_prefix << " result = " << (char*) ptr << "\n"; LocalFree( ptr ); } @@ -153,7 +153,7 @@ static int get_display_information (DisplaySearchParameters &display_search_para window_height = 0; window_bits_per_pixel = 0; total_display_modes = 0; - display_mode_array = NULL; + display_mode_array = nullptr; minimum_width = display_search_parameters._minimum_width; minimum_height = display_search_parameters._minimum_height; @@ -195,7 +195,7 @@ static int get_display_information (DisplaySearchParameters &display_search_para DIRECT_3D direct_3d; direct_3d = Direct3DCreate (D3D_SDK_VERSION); - if (direct_3d != NULL) { + if (direct_3d != nullptr) { DWORD flags; UINT adapter; D3DDEVTYPE device_type; @@ -471,15 +471,15 @@ static int get_display_information (DisplaySearchParameters &display_search_para WNDCLASSEX window_class = { sizeof (WNDCLASSEX), CS_CLASSDC, window_procedure, 0L, 0L, - GetModuleHandle(NULL), NULL, NULL, NULL, NULL, - "class_name", NULL + GetModuleHandle(nullptr), nullptr, nullptr, nullptr, nullptr, + "class_name", nullptr }; RegisterClassEx (&window_class); HWND window_handle; - window_handle = CreateWindow ("class_name", "window_name", WS_DISABLED, 0, 0, width, height, (HWND) NULL, (HMENU) NULL, window_class.hInstance, NULL); - if (window_handle != NULL) { + window_handle = CreateWindow ("class_name", "window_name", WS_DISABLED, 0, 0, width, height, (HWND) nullptr, (HMENU) nullptr, window_class.hInstance, nullptr); + if (window_handle != nullptr) { ShowWindow (window_handle, SW_HIDE); DIRECT_3D_DEVICE direct_3d_device; @@ -538,7 +538,7 @@ static int get_display_information (DisplaySearchParameters &display_search_para D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &texture_array [total_textures], - NULL); + nullptr); if (texture_result == D3D_OK) { total_textures++; } diff --git a/panda/src/windisplay/winGraphicsPipe.cxx b/panda/src/windisplay/winGraphicsPipe.cxx index cf76e06296..6f19ca2f14 100644 --- a/panda/src/windisplay/winGraphicsPipe.cxx +++ b/panda/src/windisplay/winGraphicsPipe.cxx @@ -48,7 +48,6 @@ typedef long (__stdcall *CallNtPowerInformationType) (POWER_INFORMATION_LEVEL in static int initialize = false; static HMODULE psapi_dll = 0; -static HMODULE power_dll = 0; static GetProcessMemoryInfoType GetProcessMemoryInfoFunction = 0; static CallNtPowerInformationType CallNtPowerInformationFunction = 0; @@ -123,7 +122,7 @@ int update_cpu_frequency_function(int processor_number, DisplayInformation *disp } information_level = ProcessorInformation; - input_buffer = NULL; + input_buffer = nullptr; output_buffer = processor_power_information_array; input_buffer_size = 0; output_buffer_size = sizeof(PROCESSOR_POWER_INFORMATION) * MAXIMUM_PROCESSORS; @@ -162,7 +161,7 @@ count_number_of_cpus(DisplayInformation *display_information) { LPFN_GLPI glpi; glpi = (LPFN_GLPI)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation"); - if (glpi == NULL) { + if (glpi == nullptr) { windisplay_cat.info() << "GetLogicalProcessorInformation is not supported.\n"; return; @@ -170,17 +169,17 @@ count_number_of_cpus(DisplayInformation *display_information) { // Allocate a buffer to hold the result of the // GetLogicalProcessorInformation call. - PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL; + PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = nullptr; DWORD buffer_length = 0; DWORD rc = glpi(buffer, &buffer_length); while (!rc) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { - if (buffer != NULL) { + if (buffer != nullptr) { PANDA_FREE_ARRAY(buffer); } buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)PANDA_MALLOC_ARRAY(buffer_length); - nassertv(buffer != NULL); + nassertv(buffer != nullptr); } else { windisplay_cat.info() << "GetLogicalProcessorInformation failed: " << GetLastError() @@ -225,13 +224,13 @@ WinGraphicsPipe() { _supported_types = OT_window | OT_fullscreen_window; HMODULE user32 = GetModuleHandleA("user32.dll"); - if (user32 != NULL) { + if (user32 != nullptr) { if (dpi_aware) { typedef HRESULT (WINAPI *PFN_SETPROCESSDPIAWARENESS)(Process_DPI_Awareness); PFN_SETPROCESSDPIAWARENESS pfnSetProcessDpiAwareness = (PFN_SETPROCESSDPIAWARENESS)GetProcAddress(user32, "SetProcessDpiAwarenessInternal"); - if (pfnSetProcessDpiAwareness == NULL) { + if (pfnSetProcessDpiAwareness == nullptr) { if (windisplay_cat.is_debug()) { windisplay_cat.debug() << "Unable to find SetProcessDpiAwareness in user32.dll.\n"; } @@ -261,9 +260,9 @@ WinGraphicsPipe() { windisplay_cat.debug() << "Using EnumDisplaySettings to fetch display information.\n"; } pvector display_modes; - DEVMODE dm = {0}; + DEVMODE dm{}; dm.dmSize = sizeof(dm); - for (int i = 0; EnumDisplaySettings(NULL, i, &dm) != 0; ++i) { + for (int i = 0; EnumDisplaySettings(nullptr, i, &dm) != 0; ++i) { DisplayMode mode; mode.width = dm.dmPelsWidth; mode.height = dm.dmPelsHeight; @@ -293,7 +292,7 @@ WinGraphicsPipe() { version_info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if (GetVersionEx(&version_info)) { if (windisplay_cat.is_info()) { - sprintf(string, "OS version: %d.%d.%d.%d\n", version_info.dwMajorVersion, version_info.dwMinorVersion, version_info.dwPlatformId, version_info.dwBuildNumber); + sprintf(string, "OS version: %lu.%lu.%lu.%lu\n", version_info.dwMajorVersion, version_info.dwMinorVersion, version_info.dwPlatformId, version_info.dwBuildNumber); windisplay_cat.info() << string; windisplay_cat.info() << " " << version_info.szCSDVersion << "\n"; } diff --git a/panda/src/windisplay/winGraphicsWindow.I b/panda/src/windisplay/winGraphicsWindow.I index 1a51d47988..9a873d9181 100644 --- a/panda/src/windisplay/winGraphicsWindow.I +++ b/panda/src/windisplay/winGraphicsWindow.I @@ -49,7 +49,7 @@ set_cursor_in_window() { INLINE void WinGraphicsWindow:: set_cursor_out_of_window() { if (_cursor_window == this) { - update_cursor_window(NULL); + update_cursor_window(nullptr); } } @@ -74,7 +74,7 @@ get_ime_hwnd() { if (_ime_active) return _ime_hWnd; else - return NULL; + return nullptr; } /** diff --git a/panda/src/windisplay/winGraphicsWindow.cxx b/panda/src/windisplay/winGraphicsWindow.cxx index f8fa283020..954d8aca41 100644 --- a/panda/src/windisplay/winGraphicsWindow.cxx +++ b/panda/src/windisplay/winGraphicsWindow.cxx @@ -37,6 +37,9 @@ // Not used on Windows XP, but we still need to define it. #define TOUCH_COORD_TO_PIXEL(l) ((l) / 100) +using std::endl; +using std::wstring; + DECLARE_HANDLE(HTOUCHINPUT); #endif @@ -44,9 +47,9 @@ TypeHandle WinGraphicsWindow::_type_handle; TypeHandle WinGraphicsWindow::WinWindowHandle::_type_handle; WinGraphicsWindow::WindowHandles WinGraphicsWindow::_window_handles; -WinGraphicsWindow *WinGraphicsWindow::_creating_window = NULL; +WinGraphicsWindow *WinGraphicsWindow::_creating_window = nullptr; -WinGraphicsWindow *WinGraphicsWindow::_cursor_window = NULL; +WinGraphicsWindow *WinGraphicsWindow::_cursor_window = nullptr; bool WinGraphicsWindow::_cursor_hidden = false; RECT WinGraphicsWindow::_mouse_unconfined_cliprect; @@ -69,9 +72,9 @@ static const char * const errorbox_title = "Panda3D Error"; // These static variables contain pointers to the touch input functions, which // are dynamically extracted from USER32.DLL -typedef WINUSERAPI BOOL (WINAPI *PFN_REGISTERTOUCHWINDOW)(IN HWND hWnd, IN ULONG ulFlags); -typedef WINUSERAPI BOOL (WINAPI *PFN_GETTOUCHINPUTINFO)(IN HTOUCHINPUT hTouchInput, IN UINT cInputs, OUT PTOUCHINPUT pInputs, IN int cbSize); -typedef WINUSERAPI BOOL (WINAPI *PFN_CLOSETOUCHINPUTHANDLE)(IN HTOUCHINPUT hTouchInput); +typedef BOOL (WINAPI *PFN_REGISTERTOUCHWINDOW)(IN HWND hWnd, IN ULONG ulFlags); +typedef BOOL (WINAPI *PFN_GETTOUCHINPUTINFO)(IN HTOUCHINPUT hTouchInput, IN UINT cInputs, OUT PTOUCHINPUT pInputs, IN int cbSize); +typedef BOOL (WINAPI *PFN_CLOSETOUCHINPUTHANDLE)(IN HTOUCHINPUT hTouchInput); static PFN_REGISTERTOUCHWINDOW pRegisterTouchWindow = 0; static PFN_GETTOUCHINPUTINFO pGetTouchInputInfo = 0; @@ -82,7 +85,7 @@ static PFN_CLOSETOUCHINPUTHANDLE pCloseTouchInputHandle = 0; */ WinGraphicsWindow:: WinGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -103,7 +106,7 @@ WinGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, _rcontrol_down = false; _lalt_down = false; _ralt_down = false; - _hparent = NULL; + _hparent = nullptr; _num_touches = 0; } @@ -112,11 +115,35 @@ WinGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, */ WinGraphicsWindow:: ~WinGraphicsWindow() { - if (_window_handle != (WindowHandle *)NULL) { + if (_window_handle != nullptr) { DCAST(WinWindowHandle, _window_handle)->clear_window(); } } +/** + * Returns the MouseData associated with the nth input device's pointer. + */ +MouseData WinGraphicsWindow:: +get_pointer(int device) const { + MouseData result; + { + LightMutexHolder holder(_input_lock); + nassertr(device >= 0 && device < (int)_input_devices.size(), MouseData()); + + result = _input_devices[device].get_pointer(); + + // We recheck this immediately to get the most up-to-date value. + POINT cpos; + if (device == 0 && result._in_window && GetCursorPos(&cpos) && ScreenToClient(_hWnd, &cpos)) { + double time = ClockObject::get_global_clock()->get_real_time(); + result._xpos = cpos.x; + result._ypos = cpos.y; + ((GraphicsWindowInputDevice &)_input_devices[0]).set_pointer(result._in_window, result._xpos, result._ypos, time); + } + } + return result; +} + /** * Forces the pointer to the indicated position within the window, if * possible. @@ -229,7 +256,7 @@ process_events() { // Handle all the messages on the queue in a row. Some of these might be // for another window, but they will get dispatched appropriately. - while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { + while (PeekMessage(&msg, nullptr, 0, 0, PM_NOREMOVE)) { process_1_event(); } } @@ -257,7 +284,7 @@ set_properties_now(WindowProperties &properties) { } if (properties.has_title()) { - string title = properties.get_title(); + std::string title = properties.get_title(); _properties.set_title(title); TextEncoder encoder; wstring title_w = encoder.decode_text(title); @@ -292,7 +319,7 @@ set_properties_now(WindowProperties &properties) { _cursor = get_cursor(filename); if (_cursor == 0) { - _cursor = LoadCursor(NULL, IDC_ARROW); + _cursor = LoadCursor(nullptr, IDC_ARROW); } if (_cursor_window == this) { @@ -361,7 +388,7 @@ set_properties_now(WindowProperties &properties) { case WindowProperties::M_relative: // not implemented, treat as absolute if (_properties.get_mouse_mode() == WindowProperties::M_confined) { - ClipCursor(NULL); + ClipCursor(nullptr); windisplay_cat.info() << "Unconfining cursor from window\n"; } _properties.set_mouse_mode(WindowProperties::M_absolute); @@ -409,7 +436,7 @@ trigger_flip() { // Now that we've drawn or whatever, invalidate the rectangle so we won't // redraw again until we get the WM_PAINT message. - InvalidateRect(_hWnd, NULL, FALSE); + InvalidateRect(_hWnd, nullptr, FALSE); _got_expose_event = false; if (windisplay_cat.is_spam()) { @@ -449,7 +476,7 @@ open_window() { _cursor = get_cursor(_properties.get_cursor_filename()); } if (_cursor == 0) { - _cursor = LoadCursor(NULL, IDC_ARROW); + _cursor = LoadCursor(nullptr, IDC_ARROW); } bool want_foreground = (!_properties.has_foreground() || _properties.get_foreground()); bool want_minimized = (_properties.has_minimized() && _properties.get_minimized()) && !want_foreground; @@ -461,7 +488,7 @@ open_window() { // it gives us a handle. Warning: this is not thread safe! _creating_window = this; bool opened = open_graphic_window(is_fullscreen()); - _creating_window = (WinGraphicsWindow *)NULL; + _creating_window = nullptr; if (!opened) { return false; @@ -530,7 +557,7 @@ open_window() { _window_handle = new WinWindowHandle(this, *_window_handle); // And tell our parent window that we're now its child. - if (_parent_window_handle != (WindowHandle *)NULL) { + if (_parent_window_handle != nullptr) { _parent_window_handle->attach_child(_window_handle); } @@ -551,7 +578,7 @@ open_window() { } // Register for Win7 touch events. - if (pRegisterTouchWindow != NULL) { + if (pRegisterTouchWindow != nullptr) { pRegisterTouchWindow(_hWnd, 0); } @@ -579,7 +606,7 @@ initialize_input_devices() { add_input_device(device); // Get the number of devices. - if (GetRawInputDeviceList(NULL, &nInputDevices, sizeof(RAWINPUTDEVICELIST)) != 0) { + if (GetRawInputDeviceList(nullptr, &nInputDevices, sizeof(RAWINPUTDEVICELIST)) != 0) { return; } @@ -704,7 +731,7 @@ do_reshape_request(int x_origin, int y_origin, bool has_origin, flags |= SWP_NOMOVE; } - SetWindowPos(_hWnd, NULL, x_origin, y_origin, + SetWindowPos(_hWnd, nullptr, x_origin, y_origin, view_rect.right - view_rect.left, view_rect.bottom - view_rect.top, flags); @@ -801,7 +828,7 @@ do_fullscreen_resize(int x_size, int y_size) { } // this causes WM_SIZE msg to be produced - SetWindowPos(_hWnd, NULL, 0,0, x_size, y_size, + SetWindowPos(_hWnd, nullptr, 0,0, x_size, y_size, SWP_NOZORDER | SWP_NOMOVE | SWP_NOSENDCHANGING); int chg_result = ChangeDisplaySettings(&dm, CDS_FULLSCREEN); @@ -1009,17 +1036,17 @@ open_graphic_window(bool fullscreen) { } const WindowClass &wclass = register_window_class(_properties); - HINSTANCE hinstance = GetModuleHandle(NULL); + HINSTANCE hinstance = GetModuleHandle(nullptr); - _hparent = NULL; + _hparent = nullptr; if (!fullscreen){ WindowHandle *window_handle = _properties.get_parent_window(); - if (window_handle != NULL) { + if (window_handle != nullptr) { windisplay_cat.info() << "Got parent_window " << *window_handle << "\n"; WindowHandle::OSHandle *os_handle = window_handle->get_os_handle(); - if (os_handle != NULL) { + if (os_handle != nullptr) { windisplay_cat.info() << "os_handle type " << os_handle->get_type() << "\n"; @@ -1034,7 +1061,7 @@ open_graphic_window(bool fullscreen) { } _parent_window_handle = window_handle; } else { - _parent_window_handle = NULL; + _parent_window_handle = nullptr; } if (!_hparent) { // This can be a regular window or a fullscreen window @@ -1042,7 +1069,7 @@ open_graphic_window(bool fullscreen) { metrics.x, metrics.y, metrics.width, metrics.height, - NULL, NULL, hinstance, 0); + nullptr, nullptr, hinstance, 0); } else { // This is a regular window with a parent int x_origin = 0; int y_origin = 0; @@ -1056,7 +1083,7 @@ open_graphic_window(bool fullscreen) { WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS , x_origin, y_origin, _properties.get_x_size(), _properties.get_y_size(), - _hparent, NULL, hinstance, 0); + _hparent, nullptr, hinstance, 0); if (_hWnd) { // join our keyboard state with the parents @@ -1151,7 +1178,7 @@ do_fullscreen_enable() { */ bool WinGraphicsWindow:: do_fullscreen_disable() { - int chg_result = ChangeDisplaySettings(NULL, 0x0); + int chg_result = ChangeDisplaySettings(nullptr, 0x0); if (chg_result != DISP_CHANGE_SUCCESSFUL) { windisplay_cat.warning() << "ChangeDisplaySettings failed to restore Windowed mode\n"; @@ -1247,13 +1274,13 @@ track_mouse_leaving(HWND hwnd) { */ void WinGraphicsWindow:: set_focus() { - if (SetFocus(_hWnd) == NULL && GetLastError() != 0) { + if (SetFocus(_hWnd) == nullptr && GetLastError() != 0) { // If the SetFocus() request failed, maybe we're running in the plugin // environment on Vista, with UAC enabled. In this case, we're not // allowed to assign focus to the Panda window for some stupid reason. So // instead, we have to ask the parent window (in the browser process) to // proxy our keyboard events for us. - if (_parent_window_handle != NULL && _window_handle != NULL) { + if (_parent_window_handle != nullptr && _window_handle != nullptr) { _parent_window_handle->request_keyboard_focus(_window_handle); } else { // Otherwise, something is wrong. @@ -1292,7 +1319,6 @@ window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { << msg << ", " << wparam << ", " << lparam << ")\n"; } WindowProperties properties; - int button = -1; switch (msg) { case WM_MOUSEMOVE: @@ -1360,7 +1386,7 @@ window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { // This is a message from the system indicating that the user has // requested to close the window (e.g. alt-f4). { - string close_request_event = get_close_request_event(); + std::string close_request_event = get_close_request_event(); if (!close_request_event.empty()) { // In this case, the app has indicated a desire to intercept the // request and process it directly. @@ -1457,7 +1483,7 @@ window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { windisplay_cat.debug() << "WM_WINDOWPOSCHANGED: " << hwnd << ", " << wparam << "\n"; } - if (_hWnd != NULL) { + if (_hWnd != nullptr) { handle_reshape(); } adjust_z_order(); @@ -1467,7 +1493,7 @@ window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { // In response to WM_PAINT, we check to see if there are any update // regions at all; if there are, we declare the window exposed. This is // used to implement !_unexposed_draw. - if (GetUpdateRect(_hWnd, NULL, false)) { + if (GetUpdateRect(_hWnd, nullptr, false)) { if (windisplay_cat.is_spam()) { windisplay_cat.spam() << "Got update regions: " << this << "\n"; @@ -1716,17 +1742,17 @@ window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { } if (lparam & GCS_COMPSTR) { - result_size = ImmGetCompositionStringW(hIMC, GCS_CURSORPOS, NULL, 0); + result_size = ImmGetCompositionStringW(hIMC, GCS_CURSORPOS, nullptr, 0); cursor_pos = result_size & 0xffff; - result_size = ImmGetCompositionStringW(hIMC, GCS_DELTASTART, NULL, 0); + result_size = ImmGetCompositionStringW(hIMC, GCS_DELTASTART, nullptr, 0); delta_start = result_size & 0xffff; result_size = ImmGetCompositionStringW(hIMC, GCS_COMPSTR, ime_buffer, ime_buffer_size); size_t num_chars = result_size / sizeof(wchar_t); _input_devices[0].candidate(wstring(ime_buffer, num_chars), - min(cursor_pos, delta_start), - max(cursor_pos, delta_start), + std::min(cursor_pos, delta_start), + std::max(cursor_pos, delta_start), cursor_pos); } ImmReleaseContext(hwnd, hIMC); @@ -1864,14 +1890,14 @@ window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { HGLOBAL hglb; char *lptstr; - if (IsClipboardFormatAvailable(CF_TEXT) && OpenClipboard(NULL)) { + if (IsClipboardFormatAvailable(CF_TEXT) && OpenClipboard(nullptr)) { // Maybe we should support CF_UNICODETEXT if it is available too? hglb = GetClipboardData(CF_TEXT); - if (hglb!=NULL) { + if (hglb!=nullptr) { lptstr = (char *) GlobalLock(hglb); - if (lptstr != NULL) { + if (lptstr != nullptr) { char *pChar; - for (pChar=lptstr; *pChar!=NULL; pChar++) { + for (pChar=lptstr; *pChar; pChar++) { _input_devices[0].keystroke((uchar)*pChar); } GlobalUnlock(hglb); @@ -2106,7 +2132,7 @@ static_window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { } // The window wasn't in the map; we must be creating it right now. - if (_creating_window != (WinGraphicsWindow *)NULL) { + if (_creating_window != nullptr) { return _creating_window->window_proc(hwnd, msg, wparam, lparam); } @@ -2122,7 +2148,7 @@ void WinGraphicsWindow:: process_1_event() { MSG msg; - if (!GetMessage(&msg, NULL, 0, 0)) { + if (!GetMessage(&msg, nullptr, 0, 0)) { // WM_QUIT received. We need a cleaner way to deal with this. // DestroyAllWindows(false); exit(msg.wParam); // this will invoke AtExitFn @@ -2156,16 +2182,16 @@ resend_lost_keypresses() { void WinGraphicsWindow:: update_cursor_window(WinGraphicsWindow *to_window) { bool hide_cursor = false; - if (to_window == (WinGraphicsWindow *)NULL) { + if (to_window == nullptr) { // We are leaving a graphics window; we should restore the Win2000 // effects. if (_got_saved_params) { - SystemParametersInfo(SPI_SETMOUSETRAILS, NULL, - (PVOID)_saved_mouse_trails, NULL); - SystemParametersInfo(SPI_SETCURSORSHADOW, NULL, - (PVOID)_saved_cursor_shadow, NULL); - SystemParametersInfo(SPI_SETMOUSEVANISH, NULL, - (PVOID)_saved_mouse_vanish, NULL); + SystemParametersInfo(SPI_SETMOUSETRAILS, 0, + (PVOID)_saved_mouse_trails, 0); + SystemParametersInfo(SPI_SETCURSORSHADOW, 0, + (PVOID)_saved_cursor_shadow, 0); + SystemParametersInfo(SPI_SETMOUSEVANISH, 0, + (PVOID)_saved_mouse_vanish, 0); _got_saved_params = false; } @@ -2179,17 +2205,17 @@ update_cursor_window(WinGraphicsWindow *to_window) { // These parameters are only defined for Win2000XP, but they should just // cause a silent error on earlier OS's, which is OK. if (!_got_saved_params) { - SystemParametersInfo(SPI_GETMOUSETRAILS, NULL, - &_saved_mouse_trails, NULL); - SystemParametersInfo(SPI_GETCURSORSHADOW, NULL, - &_saved_cursor_shadow, NULL); - SystemParametersInfo(SPI_GETMOUSEVANISH, NULL, - &_saved_mouse_vanish, NULL); + SystemParametersInfo(SPI_GETMOUSETRAILS, 0, + &_saved_mouse_trails, 0); + SystemParametersInfo(SPI_GETCURSORSHADOW, 0, + &_saved_cursor_shadow, 0); + SystemParametersInfo(SPI_GETMOUSEVANISH, 0, + &_saved_mouse_vanish, 0); _got_saved_params = true; - SystemParametersInfo(SPI_SETMOUSETRAILS, NULL, (PVOID)0, NULL); - SystemParametersInfo(SPI_SETCURSORSHADOW, NULL, (PVOID)false, NULL); - SystemParametersInfo(SPI_SETMOUSEVANISH, NULL, (PVOID)false, NULL); + SystemParametersInfo(SPI_SETMOUSETRAILS, 0, (PVOID)0, 0); + SystemParametersInfo(SPI_SETCURSORSHADOW, 0, (PVOID)false, 0); + SystemParametersInfo(SPI_SETMOUSEVANISH, 0, (PVOID)false, 0); } SetCursor(to_window->_cursor); @@ -2238,7 +2264,7 @@ find_acceptable_display_mode(DWORD dwWidth, DWORD dwHeight, DWORD bpp, DEVMODE cur_dm; ZeroMemory(&cur_dm, sizeof(cur_dm)); cur_dm.dmSize = sizeof(cur_dm); - EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &cur_dm); + EnumDisplaySettings(nullptr, ENUM_CURRENT_SETTINGS, &cur_dm); int modenum = 0; int saved_modenum = -1; @@ -2247,7 +2273,7 @@ find_acceptable_display_mode(DWORD dwWidth, DWORD dwHeight, DWORD bpp, ZeroMemory(&dm, sizeof(dm)); dm.dmSize = sizeof(dm); - if (!EnumDisplaySettings(NULL, modenum, &dm)) { + if (!EnumDisplaySettings(nullptr, modenum, &dm)) { break; } @@ -2270,7 +2296,7 @@ find_acceptable_display_mode(DWORD dwWidth, DWORD dwHeight, DWORD bpp, ZeroMemory(&dm, sizeof(dm)); dm.dmSize = sizeof(dm); - if (EnumDisplaySettings(NULL, saved_modenum, &dm)) { + if (EnumDisplaySettings(nullptr, saved_modenum, &dm)) { return true; } } @@ -2291,10 +2317,10 @@ show_error_message(DWORD message_id) { } FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, message_id, + nullptr, message_id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), //The user default language (LPTSTR)&message_buffer, // the weird ptrptr->ptr cast is intentional, see FORMAT_MESSAGE_ALLOCATE_BUFFER - 1024, NULL); + 1024, nullptr); MessageBox(GetDesktopWindow(), message_buffer, _T(errorbox_title), MB_OK); windisplay_cat.fatal() << "System error msg: " << message_buffer << endl; LocalFree(message_buffer); @@ -2637,12 +2663,12 @@ handle_raw_input(HRAWINPUT hraw) { if (hraw == 0) { return; } - if (GetRawInputData(hraw, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER)) == -1) { + if (GetRawInputData(hraw, RID_INPUT, nullptr, &dwSize, sizeof(RAWINPUTHEADER)) == -1) { return; } lpb = (LPBYTE)alloca(sizeof(LPBYTE) * dwSize); - if (lpb == NULL) { + if (lpb == nullptr) { return; } @@ -2756,7 +2782,7 @@ get_icon(const Filename &filename) { Filename os = resolved.to_os_specific(); - HANDLE h = LoadImage(NULL, os.c_str(), + HANDLE h = LoadImage(nullptr, os.c_str(), IMAGE_ICON, 0, 0, LR_LOADFROMFILE | LR_DEFAULTSIZE); if (h == 0) { windisplay_cat.warning() @@ -2804,7 +2830,7 @@ get_cursor(const Filename &filename) { Filename os = resolved.to_os_specific(); - HANDLE h = LoadImage(NULL, os.c_str(), + HANDLE h = LoadImage(nullptr, os.c_str(), IMAGE_CURSOR, 0, 0, LR_LOADFROMFILE); if (h == 0) { windisplay_cat.warning() @@ -2826,11 +2852,11 @@ static HCURSOR get_cursor(const Filename &filename); const WinGraphicsWindow::WindowClass &WinGraphicsWindow:: register_window_class(const WindowProperties &props) { WindowClass wcreg(props); - wostringstream wclass_name; + std::wostringstream wclass_name; wclass_name << L"WinGraphicsWindow" << _window_class_index; wcreg._name = wclass_name.str(); - pair found = _window_classes.insert(wcreg); + std::pair found = _window_classes.insert(wcreg); const WindowClass &wclass = (*found.first); if (!found.second) { @@ -2843,7 +2869,7 @@ register_window_class(const WindowProperties &props) { WNDCLASSW wc; - HINSTANCE instance = GetModuleHandle(NULL); + HINSTANCE instance = GetModuleHandle(nullptr); // Clear before filling in window structure! ZeroMemory(&wc, sizeof(wc)); @@ -2854,7 +2880,7 @@ register_window_class(const WindowProperties &props) { wc.hIcon = wclass._icon; wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); - wc.lpszMenuName = NULL; + wc.lpszMenuName = nullptr; wc.lpszClassName = wclass._name.c_str(); if (!RegisterClassW(&wc)) { @@ -2883,7 +2909,7 @@ WinWindowHandle(WinGraphicsWindow *window, const WindowHandle ©) : */ void WinGraphicsWindow::WinWindowHandle:: clear_window() { - _window = NULL; + _window = nullptr; } /** @@ -2892,7 +2918,7 @@ clear_window() { */ void WinGraphicsWindow::WinWindowHandle:: receive_windows_message(unsigned int msg, int wparam, int lparam) { - if (_window != NULL) { + if (_window != nullptr) { _window->receive_windows_message(msg, wparam, lparam); } } @@ -2906,10 +2932,10 @@ void PrintErrorMessage(DWORD msgID) { msgID=GetLastError(); FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - NULL,msgID, + nullptr,msgID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), //The user default language (LPTSTR) &pMessageBuffer, // the weird ptrptr->ptr cast is intentional, see FORMAT_MESSAGE_ALLOCATE_BUFFER - 1024, NULL); + 1024, nullptr); MessageBox(GetDesktopWindow(),pMessageBuffer,_T(errorbox_title),MB_OK); windisplay_cat.fatal() << "System error msg: " << pMessageBuffer << endl; LocalFree( pMessageBuffer ); @@ -2969,7 +2995,7 @@ void get_client_rect_screen(HWND hwnd, RECT *view_rect) { * */ void WinGraphicsWindow::add_window_proc( const GraphicsWindowProc* wnd_proc ){ - nassertv(wnd_proc != NULL); + nassertv(wnd_proc != nullptr); _window_proc_classes.insert( (GraphicsWindowProc*)wnd_proc ); } @@ -2978,7 +3004,7 @@ void WinGraphicsWindow::add_window_proc( const GraphicsWindowProc* wnd_proc ){ * */ void WinGraphicsWindow::remove_window_proc( const GraphicsWindowProc* wnd_proc ){ - nassertv(wnd_proc != NULL); + nassertv(wnd_proc != nullptr); _window_proc_classes.erase( (GraphicsWindowProc*)wnd_proc ); } diff --git a/panda/src/windisplay/winGraphicsWindow.h b/panda/src/windisplay/winGraphicsWindow.h index ec7e1217ff..ff0340aa0d 100644 --- a/panda/src/windisplay/winGraphicsWindow.h +++ b/panda/src/windisplay/winGraphicsWindow.h @@ -64,7 +64,7 @@ typedef struct tagTOUCHINPUT { class EXPCL_PANDAWIN WinGraphicsWindow : public GraphicsWindow { public: WinGraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -72,6 +72,7 @@ public: GraphicsOutput *host); virtual ~WinGraphicsWindow(); + virtual MouseData get_pointer(int device) const; virtual bool move_pointer(int device, int x, int y); virtual void close_ime(); @@ -197,7 +198,7 @@ private: private: // We need this map to support per-window calls to window_proc(). - typedef map WindowHandles; + typedef std::map WindowHandles; static WindowHandles _window_handles; // And we need a static pointer to the current WinGraphicsWindow we are @@ -242,7 +243,7 @@ private: INLINE WindowClass(const WindowProperties &props); INLINE bool operator < (const WindowClass &other) const; - wstring _name; + std::wstring _name; HICON _icon; }; diff --git a/panda/src/x11display/x11GraphicsPipe.I b/panda/src/x11display/x11GraphicsPipe.I index fb56700299..a516b2e6a2 100644 --- a/panda/src/x11display/x11GraphicsPipe.I +++ b/panda/src/x11display/x11GraphicsPipe.I @@ -62,7 +62,7 @@ get_hidden_cursor() { */ INLINE bool x11GraphicsPipe:: supports_relative_mouse() const { - return (_XF86DGADirectVideo != NULL); + return (_XF86DGADirectVideo != nullptr); } /** @@ -70,7 +70,7 @@ supports_relative_mouse() const { */ INLINE bool x11GraphicsPipe:: enable_relative_mouse() { - if (_XF86DGADirectVideo != NULL) { + if (_XF86DGADirectVideo != nullptr) { x11display_cat.info() << "Enabling relative mouse using XF86DGA extension\n"; _XF86DGADirectVideo(_display, _screen, XF86DGADirectMouse); return true; @@ -83,7 +83,7 @@ enable_relative_mouse() { */ INLINE void x11GraphicsPipe:: disable_relative_mouse() { - if (_XF86DGADirectVideo != NULL) { + if (_XF86DGADirectVideo != nullptr) { x11display_cat.info() << "Disabling relative mouse using XF86DGA extension\n"; _XF86DGADirectVideo(_display, _screen, 0); } diff --git a/panda/src/x11display/x11GraphicsPipe.cxx b/panda/src/x11display/x11GraphicsPipe.cxx index a0d4e8ffae..2348d58706 100644 --- a/panda/src/x11display/x11GraphicsPipe.cxx +++ b/panda/src/x11display/x11GraphicsPipe.cxx @@ -33,12 +33,12 @@ LightReMutex x11GraphicsPipe::_x_mutex; * */ x11GraphicsPipe:: -x11GraphicsPipe(const string &display) : +x11GraphicsPipe(const std::string &display) : _have_xrandr(false), _xcursor_size(-1), - _XF86DGADirectVideo(NULL) { + _XF86DGADirectVideo(nullptr) { - string display_spec = display; + std::string display_spec = display; if (display_spec.empty()) { display_spec = display_cfg; } @@ -60,10 +60,10 @@ x11GraphicsPipe(const string &display) : _is_valid = false; _supported_types = OT_window | OT_buffer | OT_texture_buffer; - _display = NULL; + _display = nullptr; _screen = 0; - _root = (X11_Window)NULL; - _im = (XIM)NULL; + _root = (X11_Window)nullptr; + _im = (XIM)nullptr; _hidden_cursor = None; install_error_handlers(); @@ -82,7 +82,7 @@ x11GraphicsPipe(const string &display) : if (!XSupportsLocale()) { x11display_cat.warning() - << "X does not support locale " << setlocale(LC_ALL, NULL) << "\n"; + << "X does not support locale " << setlocale(LC_ALL, nullptr) << "\n"; } XSetLocaleModifiers(""); @@ -94,20 +94,20 @@ x11GraphicsPipe(const string &display) : // Dynamically load the xf86dga extension. void *xf86dga = dlopen("libXxf86dga.so.1", RTLD_NOW | RTLD_LOCAL); - if (xf86dga != NULL) { + if (xf86dga != nullptr) { pfn_XF86DGAQueryVersion _XF86DGAQueryVersion = (pfn_XF86DGAQueryVersion)dlsym(xf86dga, "XF86DGAQueryVersion"); _XF86DGADirectVideo = (pfn_XF86DGADirectVideo)dlsym(xf86dga, "XF86DGADirectVideo"); int major_ver, minor_ver; - if (_XF86DGAQueryVersion == NULL || _XF86DGADirectVideo == NULL) { + if (_XF86DGAQueryVersion == nullptr || _XF86DGADirectVideo == nullptr) { x11display_cat.warning() << "libXxf86dga.so.1 does not provide required functions; relative mouse mode will not work.\n"; } else if (!_XF86DGAQueryVersion(_display, &major_ver, &minor_ver)) { - _XF86DGADirectVideo = NULL; + _XF86DGADirectVideo = nullptr; } } else { - _XF86DGADirectVideo = NULL; + _XF86DGADirectVideo = nullptr; if (x11display_cat.is_debug()) { x11display_cat.debug() << "cannot dlopen libXxf86dga.so.1; cursor changing will not work.\n"; @@ -116,7 +116,7 @@ x11GraphicsPipe(const string &display) : // Dynamically load the XCursor extension. void *xcursor = dlopen("libXcursor.so.1", RTLD_NOW | RTLD_LOCAL); - if (xcursor != NULL) { + if (xcursor != nullptr) { pfn_XcursorGetDefaultSize _XcursorGetDefaultSize = (pfn_XcursorGetDefaultSize)dlsym(xcursor, "XcursorGetDefaultSize"); _XcursorXcFileLoadImages = (pfn_XcursorXcFileLoadImages)dlsym(xcursor, "XcursorXcFileLoadImages"); _XcursorImagesLoadCursor = (pfn_XcursorImagesLoadCursor)dlsym(xcursor, "XcursorImagesLoadCursor"); @@ -125,10 +125,10 @@ x11GraphicsPipe(const string &display) : _XcursorImageLoadCursor = (pfn_XcursorImageLoadCursor)dlsym(xcursor, "XcursorImageLoadCursor"); _XcursorImageDestroy = (pfn_XcursorImageDestroy)dlsym(xcursor, "XcursorImageDestroy"); - if (_XcursorGetDefaultSize == NULL || _XcursorXcFileLoadImages == NULL || - _XcursorImagesLoadCursor == NULL || _XcursorImagesDestroy == NULL || - _XcursorImageCreate == NULL || _XcursorImageLoadCursor == NULL || - _XcursorImageDestroy == NULL) { + if (_XcursorGetDefaultSize == nullptr || _XcursorXcFileLoadImages == nullptr || + _XcursorImagesLoadCursor == nullptr || _XcursorImagesDestroy == nullptr || + _XcursorImageCreate == nullptr || _XcursorImageLoadCursor == nullptr || + _XcursorImageDestroy == nullptr) { _xcursor_size = -1; x11display_cat.warning() << "libXcursor.so.1 does not provide required functions; cursor changing will not work.\n"; @@ -148,7 +148,7 @@ x11GraphicsPipe(const string &display) : // Dynamically load the XRandr extension. void *xrandr = dlopen("libXrandr.so.2", RTLD_NOW | RTLD_LOCAL); - if (xrandr != NULL) { + if (xrandr != nullptr) { pfn_XRRQueryExtension _XRRQueryExtension = (pfn_XRRQueryExtension)dlsym(xrandr, "XRRQueryExtension"); _XRRSizes = (pfn_XRRSizes)dlsym(xrandr, "XRRSizes"); _XRRRates = (pfn_XRRRates)dlsym(xrandr, "XRRRates"); @@ -156,9 +156,9 @@ x11GraphicsPipe(const string &display) : _XRRConfigCurrentConfiguration = (pfn_XRRConfigCurrentConfiguration)dlsym(xrandr, "XRRConfigCurrentConfiguration"); _XRRSetScreenConfig = (pfn_XRRSetScreenConfig)dlsym(xrandr, "XRRSetScreenConfig"); - if (_XRRQueryExtension == NULL || _XRRSizes == NULL || _XRRRates == NULL || - _XRRGetScreenInfo == NULL || _XRRConfigCurrentConfiguration == NULL || - _XRRSetScreenConfig == NULL) { + if (_XRRQueryExtension == nullptr || _XRRSizes == nullptr || _XRRRates == nullptr || + _XRRGetScreenInfo == nullptr || _XRRConfigCurrentConfiguration == nullptr || + _XRRSetScreenConfig == nullptr) { _have_xrandr = false; x11display_cat.warning() << "libXrandr.so.2 does not provide required functions; resolution setting will not work.\n"; @@ -204,8 +204,8 @@ x11GraphicsPipe(const string &display) : } // Connect to an input method for supporting international text entry. - _im = XOpenIM(_display, NULL, NULL, NULL); - if (_im == (XIM)NULL) { + _im = XOpenIM(_display, nullptr, nullptr, nullptr); + if (_im == (XIM)nullptr) { x11display_cat.warning() << "Couldn't open input method.\n"; } diff --git a/panda/src/x11display/x11GraphicsPipe.h b/panda/src/x11display/x11GraphicsPipe.h index 4da09d3144..c13b192627 100644 --- a/panda/src/x11display/x11GraphicsPipe.h +++ b/panda/src/x11display/x11GraphicsPipe.h @@ -46,7 +46,7 @@ class FrameBufferProperties; */ class x11GraphicsPipe : public GraphicsPipe { public: - x11GraphicsPipe(const string &display = string()); + x11GraphicsPipe(const std::string &display = std::string()); virtual ~x11GraphicsPipe(); INLINE X11_Display *get_display() const; diff --git a/panda/src/x11display/x11GraphicsWindow.cxx b/panda/src/x11display/x11GraphicsWindow.cxx index 0a1539bd42..d1f49eedc3 100644 --- a/panda/src/x11display/x11GraphicsWindow.cxx +++ b/panda/src/x11display/x11GraphicsWindow.cxx @@ -38,6 +38,10 @@ #include #endif +using std::istream; +using std::ostringstream; +using std::string; + struct _XcursorFile { void *closure; int (*read)(XcursorFile *, unsigned char *, int); @@ -105,9 +109,9 @@ x11GraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, DCAST_INTO_V(x11_pipe, _pipe); _display = x11_pipe->get_display(); _screen = x11_pipe->get_screen(); - _xwindow = (X11_Window)NULL; - _ic = (XIC)NULL; - _visual_info = NULL; + _xwindow = (X11_Window)nullptr; + _ic = (XIC)nullptr; + _visual_info = nullptr; _orig_size_id = -1; if (x11_pipe->_have_xrandr) { @@ -132,13 +136,48 @@ x11GraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, */ x11GraphicsWindow:: ~x11GraphicsWindow() { - pmap::iterator it; - - for (it = _cursor_filenames.begin(); it != _cursor_filenames.end(); it++) { - XFreeCursor(_display, it->second); + if (!_cursor_filenames.empty()) { + LightReMutexHolder holder(x11GraphicsPipe::_x_mutex); + for (auto item : _cursor_filenames) { + XFreeCursor(_display, item.second); + } } } +/** + * Returns the MouseData associated with the nth input device's pointer. This + * is deprecated; use get_pointer_device().get_pointer() instead, or for raw + * mice, use the InputDeviceManager interface. + */ +MouseData x11GraphicsWindow:: +get_pointer(int device) const { + MouseData result; + { + LightMutexHolder holder(_input_lock); + nassertr(device >= 0 && device < (int)_input_devices.size(), MouseData()); + + result = _input_devices[device].get_pointer(); + + // We recheck this immediately to get the most up-to-date value, but we + // won't bother waiting for the lock if we can't. + if (device == 0 && !_dga_mouse_enabled && result._in_window && + x11GraphicsPipe::_x_mutex.try_lock()) { + XEvent event; + LightReMutexHolder holder(x11GraphicsPipe::_x_mutex); + if (XQueryPointer(_display, _xwindow, &event.xbutton.root, + &event.xbutton.window, &event.xbutton.x_root, &event.xbutton.y_root, + &event.xbutton.x, &event.xbutton.y, &event.xbutton.state)) { + double time = ClockObject::get_global_clock()->get_real_time(); + result._xpos = event.xbutton.x; + result._ypos = event.xbutton.y; + ((GraphicsWindowInputDevice &)_input_devices[0]).set_pointer_in_window(result._xpos, result._ypos, time); + } + x11GraphicsPipe::_x_mutex.release(); + } + } + return result; +} + /** * Forces the pointer to the indicated position within the window, if * possible. @@ -163,6 +202,7 @@ move_pointer(int device, int x, int y) { const MouseData &md = _input_devices[0].get_pointer(); if (!md.get_in_window() || md.get_x() != x || md.get_y() != y) { if (!_dga_mouse_enabled) { + LightReMutexHolder holder(x11GraphicsPipe::_x_mutex); XWarpPointer(_display, None, _xwindow, 0, 0, 0, 0, x, y); } _input_devices[0].set_pointer_in_window(x, y); @@ -170,7 +210,7 @@ move_pointer(int device, int x, int y) { return true; } else { // Move a raw mouse. - if ((device < 1)||(device >= _input_devices.size())) { + if (device < 1 || (size_t)device >= _input_devices.size()) { return false; } _input_devices[device].set_pointer_in_window(x, y); @@ -189,7 +229,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { PStatTimer timer(_make_current_pcollector, current_thread); begin_frame_spam(mode); - if (_gsg == (GraphicsStateGuardian *)NULL) { + if (_gsg == nullptr) { return false; } if (_awaiting_configure) { @@ -220,7 +260,7 @@ begin_frame(FrameMode mode, Thread *current_thread) { void x11GraphicsWindow:: end_frame(FrameMode mode, Thread *current_thread) { end_frame_spam(mode); - nassertv(_gsg != (GraphicsStateGuardian *)NULL); + nassertv(_gsg != nullptr); if (mode == FM_render) { // end_render_texture(); @@ -489,7 +529,7 @@ process_events() { */ void x11GraphicsWindow:: set_properties_now(WindowProperties &properties) { - if (_pipe == (GraphicsPipe *)NULL) { + if (_pipe == nullptr) { // If the pipe is null, we're probably closing down. GraphicsWindow::set_properties_now(properties); return; @@ -498,6 +538,8 @@ set_properties_now(WindowProperties &properties) { x11GraphicsPipe *x11_pipe; DCAST_INTO_V(x11_pipe, _pipe); + LightReMutexHolder holder(x11GraphicsPipe::_x_mutex); + // We're either going into or out of fullscreen, or are in fullscreen and // are changing the resolution. bool is_fullscreen = _properties.has_fullscreen() && _properties.get_fullscreen(); @@ -820,18 +862,19 @@ mouse_mode_relative() { */ void x11GraphicsWindow:: close_window() { - if (_gsg != (GraphicsStateGuardian *)NULL) { + if (_gsg != nullptr) { _gsg.clear(); } - if (_ic != (XIC)NULL) { + LightReMutexHolder holder(x11GraphicsPipe::_x_mutex); + if (_ic != (XIC)nullptr) { XDestroyIC(_ic); - _ic = (XIC)NULL; + _ic = (XIC)nullptr; } - if (_xwindow != (X11_Window)NULL) { + if (_xwindow != (X11_Window)nullptr) { XDestroyWindow(_display, _xwindow); - _xwindow = (X11_Window)NULL; + _xwindow = (X11_Window)nullptr; // This may be necessary if we just closed the last X window in an // application, so the server hears the close request. @@ -842,7 +885,7 @@ close_window() { // typecast! if (_orig_size_id != (SizeID) -1) { X11_Window root; - if (_pipe != NULL) { + if (_pipe != nullptr) { x11GraphicsPipe *x11_pipe; DCAST_INTO_V(x11_pipe, _pipe); root = x11_pipe->get_root(); @@ -865,7 +908,7 @@ close_window() { */ bool x11GraphicsWindow:: open_window() { - if (_visual_info == NULL) { + if (_visual_info == nullptr) { // No X visual for this fbconfig; how can we open the window? x11display_cat.error() << "No X visual: cannot open window.\n"; @@ -882,6 +925,9 @@ open_window() { _properties.set_size(100, 100); } + // Make sure we are not making X11 calls from other threads. + LightReMutexHolder holder(x11GraphicsPipe::_x_mutex); + if (_properties.get_fullscreen() && x11_pipe->_have_xrandr) { XRRScreenConfiguration* conf = _XRRGetScreenInfo(_display, x11_pipe->get_root()); if (_orig_size_id == (SizeID) -1) { @@ -912,11 +958,11 @@ open_window() { X11_Window parent_window = x11_pipe->get_root(); WindowHandle *window_handle = _properties.get_parent_window(); - if (window_handle != NULL) { + if (window_handle != nullptr) { x11display_cat.info() << "Got parent_window " << *window_handle << "\n"; WindowHandle::OSHandle *os_handle = window_handle->get_os_handle(); - if (os_handle != NULL) { + if (os_handle != nullptr) { x11display_cat.info() << "os_handle type " << os_handle->get_type() << "\n"; @@ -973,13 +1019,13 @@ open_window() { // can wait until we have an X server that actually supports these to test // it on. XIM im = x11_pipe->get_im(); - _ic = NULL; + _ic = nullptr; if (im) { _ic = XCreateIC (im, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, - (void*)NULL); - if (_ic == (XIC)NULL) { + nullptr); + if (_ic == (XIC)nullptr) { x11display_cat.warning() << "Couldn't create input context.\n"; } @@ -1009,7 +1055,7 @@ open_window() { _window_handle = NativeWindowHandle::make_x11(_xwindow); // And tell our parent window that we're now its child. - if (_parent_window_handle != (WindowHandle *)NULL) { + if (_parent_window_handle != nullptr) { _parent_window_handle->attach_child(_window_handle); } @@ -1025,6 +1071,8 @@ open_window() { * If already_mapped is true, the window has already been mapped (manifested) * on the display. This means we may need to use a different action in some * cases. + * + * Assumes the X11 lock is held. */ void x11GraphicsWindow:: set_wm_properties(const WindowProperties &properties, bool already_mapped) { @@ -1033,7 +1081,7 @@ set_wm_properties(const WindowProperties &properties, bool already_mapped) { // Name the window if there is a name XTextProperty window_name; - XTextProperty *window_name_p = (XTextProperty *)NULL; + XTextProperty *window_name_p = nullptr; if (properties.has_title()) { const char *name = properties.get_title().c_str(); if (XStringListToTextProperty((char **)&name, 1, &window_name) != 0) { @@ -1043,10 +1091,10 @@ set_wm_properties(const WindowProperties &properties, bool already_mapped) { // The size hints request a window of a particular size andor a particular // placement onscreen. - XSizeHints *size_hints_p = NULL; + XSizeHints *size_hints_p = nullptr; if (properties.has_origin() || properties.has_size()) { size_hints_p = XAllocSizeHints(); - if (size_hints_p != (XSizeHints *)NULL) { + if (size_hints_p != nullptr) { if (properties.has_origin()) { if (_properties.get_fullscreen()) { size_hints_p->x = 0; @@ -1076,9 +1124,9 @@ set_wm_properties(const WindowProperties &properties, bool already_mapped) { // The window manager hints include requests to the window manager other // than those specific to window geometry. - XWMHints *wm_hints_p = NULL; + XWMHints *wm_hints_p = nullptr; wm_hints_p = XAllocWMHints(); - if (wm_hints_p != (XWMHints *)NULL) { + if (wm_hints_p != nullptr) { if (properties.has_minimized() && properties.get_minimized()) { wm_hints_p->initial_state = IconicState; } else { @@ -1135,7 +1183,7 @@ set_wm_properties(const WindowProperties &properties, bool already_mapped) { // For other users, we'll totally punt and just set the window's Class to // "Undecorated", and let the user configure hisher window manager not to // put a border around windows of this class. - XClassHint *class_hints_p = NULL; + XClassHint *class_hints_p = nullptr; if (!x_wm_class.empty()) { // Unless the user wanted to use his own WM_CLASS, of course. class_hints_p = XAllocClassHint(); @@ -1226,15 +1274,15 @@ set_wm_properties(const WindowProperties &properties, bool already_mapped) { } XSetWMProperties(_display, _xwindow, window_name_p, window_name_p, - NULL, 0, size_hints_p, wm_hints_p, class_hints_p); + nullptr, 0, size_hints_p, wm_hints_p, class_hints_p); - if (size_hints_p != (XSizeHints *)NULL) { + if (size_hints_p != nullptr) { XFree(size_hints_p); } - if (wm_hints_p != (XWMHints *)NULL) { + if (wm_hints_p != nullptr) { XFree(wm_hints_p); } - if (class_hints_p != (XClassHint *)NULL) { + if (class_hints_p != nullptr) { XFree(class_hints_p); } @@ -1348,9 +1396,7 @@ open_raw_mice() { void x11GraphicsWindow:: poll_raw_mice() { #ifdef PHAVE_LINUX_INPUT_H - for (int di = 0; di < _mouse_device_info.size(); ++di) { - MouseDeviceInfo &inf = _mouse_device_info[di]; - + for (MouseDeviceInfo &inf : _mouse_device_info) { // Read all bytes into buffer. if (inf._fd >= 0) { while (1) { @@ -1417,7 +1463,7 @@ handle_keystroke(XKeyEvent &event) { static const int buffer_size = 256; wchar_t buffer[buffer_size]; Status status; - int len = XwcLookupString(_ic, &event, buffer, buffer_size, NULL, + int len = XwcLookupString(_ic, &event, buffer, buffer_size, nullptr, &status); if (status == XBufferOverflow) { x11display_cat.error() @@ -1912,7 +1958,7 @@ map_button(KeySym key) const { } if (x11display_cat.is_debug()) { x11display_cat.debug() - << "Unrecognized keysym 0x" << hex << key << dec << "\n"; + << "Unrecognized keysym 0x" << std::hex << key << std::dec << "\n"; } return ButtonHandle::none(); } @@ -2133,7 +2179,7 @@ get_cursor(const Filename &filename) { // Open the file through the virtual file system. istream *str = vfs->open_read_file(resolved, true); - if (str == NULL) { + if (str == nullptr) { x11display_cat.warning() << "Could not open cursor file " << filename << "\n"; return None; @@ -2161,7 +2207,7 @@ get_cursor(const Filename &filename) { xcfile.seek = &xcursor_seek; XcursorImages *images = x11_pipe->_XcursorXcFileLoadImages(&xcfile, x11_pipe->_xcursor_size); - if (images != NULL) { + if (images != nullptr) { h = x11_pipe->_XcursorImagesLoadCursor(_display, images); x11_pipe->_XcursorImagesDestroy(images); } @@ -2221,13 +2267,13 @@ read_ico(istream &ico) { size_t colorCount, bitsPerPixel; IcoHeader header; IcoInfoHeader infoHeader; - IcoEntry *entries = NULL; - IcoColor color, *palette = NULL; + IcoEntry *entries = nullptr; + IcoColor color, *palette = nullptr; size_t xorBmpSize, andBmpSize; char *curXor, *curAnd; - char *xorBmp = NULL, *andBmp = NULL; - XcursorImage *image = NULL; + char *xorBmp = nullptr, *andBmp = nullptr; + XcursorImage *image = nullptr; X11_Cursor ret = None; int def_size = x11_pipe->_xcursor_size; @@ -2273,7 +2319,7 @@ read_ico(istream &ico) { size_t num_pixels = (size_t)img.get_x_size() * (size_t)img.get_y_size(); unsigned int *dest = image->pixels; - if (alpha != NULL) { + if (alpha != nullptr) { for (size_t p = 0; p < num_pixels; ++p) { *dest++ = (*alpha << 24U) | (ptr->r << 16U) | (ptr->g << 8U) | (ptr->b); ++ptr; diff --git a/panda/src/x11display/x11GraphicsWindow.h b/panda/src/x11display/x11GraphicsWindow.h index 5b55bf3619..078b016262 100644 --- a/panda/src/x11display/x11GraphicsWindow.h +++ b/panda/src/x11display/x11GraphicsWindow.h @@ -26,7 +26,7 @@ class x11GraphicsWindow : public GraphicsWindow { public: x11GraphicsWindow(GraphicsEngine *engine, GraphicsPipe *pipe, - const string &name, + const std::string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, @@ -34,6 +34,7 @@ public: GraphicsOutput *host); virtual ~x11GraphicsWindow(); + virtual MouseData get_pointer(int device) const; virtual bool move_pointer(int device, int x, int y); virtual bool begin_frame(FrameMode mode, Thread *current_thread); virtual void end_frame(FrameMode mode, Thread *current_thread); @@ -71,7 +72,7 @@ protected: private: X11_Cursor get_cursor(const Filename &filename); - X11_Cursor read_ico(istream &ico); + X11_Cursor read_ico(std::istream &ico); protected: X11_Display *_display; @@ -94,7 +95,7 @@ protected: struct MouseDeviceInfo { int _fd; int _input_device_index; - string _io_buffer; + std::string _io_buffer; }; pvector _mouse_device_info; diff --git a/pandatool/src/assimp/assimpLoader.cxx b/pandatool/src/assimp/assimpLoader.cxx index fb383a1b7f..61c7514aa6 100644 --- a/pandatool/src/assimp/assimpLoader.cxx +++ b/pandatool/src/assimp/assimpLoader.cxx @@ -41,6 +41,10 @@ #include "postprocess.h" +using std::ostringstream; +using std::stringstream; +using std::string; + struct BoneWeight { CPT(JointVertexTransform) joint_vertex_xform; float weight; @@ -57,7 +61,7 @@ typedef pvector BoneWeightList; AssimpLoader:: AssimpLoader() : _error (false), - _geoms (NULL) { + _geoms (nullptr) { PandaLogger::set_default(); _importer.SetIOHandler(new PandaIOSystem); @@ -82,11 +86,11 @@ get_extensions(string &ext) const { // The format is like: *.mdc;*.mdl;*.mesh.xml;*.mot char *sub = strtok(aexts.data, ";"); - while (sub != NULL) { + while (sub != nullptr) { ext += sub + 2; - sub = strtok(NULL, ";"); + sub = strtok(nullptr, ";"); - if (sub != NULL) { + if (sub != nullptr) { ext += ' '; } } @@ -102,7 +106,7 @@ read(const Filename &filename) { // I really don't know why we need to flip the winding order, but otherwise // the models I tested with are showing inside out. _scene = _importer.ReadFile(_filename.c_str(), aiProcess_Triangulate | aiProcess_GenUVCoords | aiProcess_FlipWindingOrder); - if (_scene == NULL) { + if (_scene == nullptr) { _error = true; return false; } @@ -117,7 +121,7 @@ read(const Filename &filename) { */ void AssimpLoader:: build_graph() { - nassertv(_scene != NULL); // read() must be called first + nassertv(_scene != nullptr); // read() must be called first nassertv(!_error); // and have succeeded // Protect the import process @@ -145,7 +149,7 @@ build_graph() { } // And now the node structure. - if (_scene->mRootNode != NULL) { + if (_scene->mRootNode != nullptr) { load_node(*_scene->mRootNode, _root); } @@ -178,7 +182,7 @@ find_node(const aiNode &root, const aiString &name) { } } - return NULL; + return nullptr; } /** @@ -215,7 +219,7 @@ load_texture(size_t index) { if (img.read(str, "", ftype)) { ptex->load(img); } else { - ptex = NULL; + ptex = nullptr; } } } else { @@ -255,7 +259,7 @@ load_texture_stage(const aiMaterial &mat, const aiTextureType &ttype, CPT(Textur aiTextureMapMode mapmode; for (size_t i = 0; i < mat.GetTextureCount(ttype); ++i) { - mat.GetTexture(ttype, i, &path, &mapping, NULL, &blend, &op, &mapmode); + mat.GetTexture(ttype, i, &path, &mapping, nullptr, &blend, &op, &mapmode); if (AI_SUCCESS != mat.Get(AI_MATKEY_UVWSRC(ttype, i), uvindex)) { // If there's no texture coordinate set for this texture, assume that @@ -270,12 +274,12 @@ load_texture_stage(const aiMaterial &mat, const aiTextureType &ttype, CPT(Textur if (uvindex > 0) { stage->set_texcoord_name(InternalName::get_texcoord_name(str.str())); } - PT(Texture) ptex = NULL; + PT(Texture) ptex = nullptr; // I'm not sure if this is the right way to handle it, as I couldn't find // much information on embedded textures. if (path.data[0] == '*') { - long num = strtol(path.data + 1, NULL, 10); + long num = strtol(path.data + 1, nullptr, 10); ptex = _textures[num]; } else if (path.length > 0) { @@ -308,7 +312,7 @@ load_texture_stage(const aiMaterial &mat, const aiTextureType &ttype, CPT(Textur ptex = TexturePool::load_texture(fn); } - if (ptex != NULL) { + if (ptex != nullptr) { tattr = DCAST(TextureAttrib, tattr->add_on_stage(stage, ptex)); } } @@ -424,7 +428,7 @@ create_anim_channel(const aiAnimation &anim, AnimBundle *bundle, AnimGroup *pare PT(AnimChannelMatrixXfmTable) group = new AnimChannelMatrixXfmTable(parent, node.mName.C_Str()); // See if there is a channel for this node - aiNodeAnim *node_anim = NULL; + aiNodeAnim *node_anim = nullptr; for (size_t i = 0; i < anim.mNumChannels; ++i) { if (anim.mChannels[i]->mNodeName == node.mName) { node_anim = anim.mChannels[i]; @@ -502,7 +506,7 @@ load_mesh(size_t index) { const aiMesh &mesh = *_scene->mMeshes[index]; // Check if we need to make a Character - PT(Character) character = NULL; + PT(Character) character = nullptr; if (mesh.HasBones()) { assimp_cat.debug() << "Creating character for " << mesh.mName.C_Str() << "\n"; @@ -544,7 +548,7 @@ load_mesh(size_t index) { for (size_t i = 0; i < mesh.mNumBones; ++i) { const aiBone &bone = *mesh.mBones[i]; CharacterJoint *joint = character->find_joint(bone.mName.C_Str()); - if (joint == NULL) { + if (joint == nullptr) { assimp_cat.debug() << "Could not find joint for bone: " << bone.mName.C_Str() << "\n"; continue; diff --git a/pandatool/src/assimp/assimpLoader.h b/pandatool/src/assimp/assimpLoader.h index 41ac3e1dc6..35a9bb6947 100644 --- a/pandatool/src/assimp/assimpLoader.h +++ b/pandatool/src/assimp/assimpLoader.h @@ -46,7 +46,7 @@ public: AssimpLoader(); virtual ~AssimpLoader(); - void get_extensions(string &ext) const; + void get_extensions(std::string &ext) const; bool read(const Filename &filename); void build_graph(); diff --git a/pandatool/src/assimp/loaderFileTypeAssimp.cxx b/pandatool/src/assimp/loaderFileTypeAssimp.cxx index b4a667d5fe..73c27ee7d4 100644 --- a/pandatool/src/assimp/loaderFileTypeAssimp.cxx +++ b/pandatool/src/assimp/loaderFileTypeAssimp.cxx @@ -15,6 +15,8 @@ #include "config_assimp.h" #include "assimpLoader.h" +using std::string; + TypeHandle LoaderFileTypeAssimp::_type_handle; /** @@ -29,7 +31,7 @@ LoaderFileTypeAssimp() : _loader(new AssimpLoader) { */ LoaderFileTypeAssimp:: ~LoaderFileTypeAssimp() { - if (_loader != NULL) { + if (_loader != nullptr) { delete _loader; } } @@ -81,7 +83,7 @@ load_file(const Filename &path, const LoaderOptions &options, << "Reading " << path << "\n"; if (!_loader->read(path)) { - return NULL; + return nullptr; } _loader->build_graph(); diff --git a/pandatool/src/assimp/loaderFileTypeAssimp.h b/pandatool/src/assimp/loaderFileTypeAssimp.h index 495130a40e..45d810f964 100644 --- a/pandatool/src/assimp/loaderFileTypeAssimp.h +++ b/pandatool/src/assimp/loaderFileTypeAssimp.h @@ -28,9 +28,9 @@ public: LoaderFileTypeAssimp(); virtual ~LoaderFileTypeAssimp(); - virtual string get_name() const; - virtual string get_extension() const; - virtual string get_additional_extensions() const; + virtual std::string get_name() const; + virtual std::string get_extension() const; + virtual std::string get_additional_extensions() const; virtual bool supports_compressed() const; virtual PT(PandaNode) load_file(const Filename &path, const LoaderOptions &options, diff --git a/pandatool/src/assimp/pandaIOStream.cxx b/pandatool/src/assimp/pandaIOStream.cxx index e4dde48e79..ad610d608f 100644 --- a/pandatool/src/assimp/pandaIOStream.cxx +++ b/pandatool/src/assimp/pandaIOStream.cxx @@ -13,12 +13,13 @@ #include "pandaIOStream.h" +using std::ios; /** * */ PandaIOStream:: -PandaIOStream(istream &stream) : _istream(stream) { +PandaIOStream(std::istream &stream) : _istream(stream) { } /** @@ -26,9 +27,9 @@ PandaIOStream(istream &stream) : _istream(stream) { */ size_t PandaIOStream:: FileSize() const { - streampos cur = _istream.tellg(); + std::streampos cur = _istream.tellg(); _istream.seekg(0, ios::end); - streampos end = _istream.tellg(); + std::streampos end = _istream.tellg(); _istream.seekg(cur, ios::beg); return end; } diff --git a/pandatool/src/assimp/pandaIOStream.h b/pandatool/src/assimp/pandaIOStream.h index cb4ddf251c..fa5cc2bb1e 100644 --- a/pandatool/src/assimp/pandaIOStream.h +++ b/pandatool/src/assimp/pandaIOStream.h @@ -26,7 +26,7 @@ class PandaIOSystem; */ class PandaIOStream : public Assimp::IOStream { public: - PandaIOStream(istream &stream); + PandaIOStream(std::istream &stream); virtual ~PandaIOStream() {}; size_t FileSize() const; @@ -37,7 +37,7 @@ public: size_t Write(const void *buffer, size_t size, size_t count); private: - istream &_istream; + std::istream &_istream; friend class PandaIOSystem; }; diff --git a/pandatool/src/assimp/pandaIOSystem.cxx b/pandatool/src/assimp/pandaIOSystem.cxx index d64b52466f..87dea240d2 100644 --- a/pandatool/src/assimp/pandaIOSystem.cxx +++ b/pandatool/src/assimp/pandaIOSystem.cxx @@ -72,14 +72,14 @@ Open(const char *file, const char *mode) { Filename fn = Filename::from_os_specific(file); if (mode[0] == 'r') { - istream *stream = _vfs->open_read_file(file, true); - if (stream == NULL) { - return NULL; + std::istream *stream = _vfs->open_read_file(file, true); + if (stream == nullptr) { + return nullptr; } return new PandaIOStream(*stream); } else { - nassertr(false, NULL); // Not implemented on purpose. - return NULL; + nassertr(false, nullptr); // Not implemented on purpose. + return nullptr; } } diff --git a/pandatool/src/assimp/pandaLogger.cxx b/pandatool/src/assimp/pandaLogger.cxx index cab31e1c06..b6432e132e 100644 --- a/pandatool/src/assimp/pandaLogger.cxx +++ b/pandatool/src/assimp/pandaLogger.cxx @@ -15,7 +15,7 @@ #include "DefaultLogger.hpp" -PandaLogger *PandaLogger::_ptr = NULL; +PandaLogger *PandaLogger::_ptr = nullptr; /** * Makes sure there's a global PandaLogger object and makes sure that it is @@ -23,7 +23,7 @@ PandaLogger *PandaLogger::_ptr = NULL; */ void PandaLogger:: set_default() { - if (_ptr == NULL) { + if (_ptr == nullptr) { _ptr = new PandaLogger; } if (_ptr != Assimp::DefaultLogger::get()) { diff --git a/pandatool/src/bam/bamInfo.cxx b/pandatool/src/bam/bamInfo.cxx index 44d015c2fe..a30a5066dd 100644 --- a/pandatool/src/bam/bamInfo.cxx +++ b/pandatool/src/bam/bamInfo.cxx @@ -132,7 +132,7 @@ get_info(const Filename &filename) { Objects objects; TypedWritable *object = bam_file.read_object(); - if (object != (TypedWritable *)NULL && + if (object != nullptr && object->is_exact_type(BamCacheRecord::get_class_type())) { // Here's a special case: if the first object in the file is a // BamCacheRecord, it's a cache data file; in this case, we output the @@ -142,8 +142,8 @@ get_info(const Filename &filename) { object = bam_file.read_object(); } - while (object != (TypedWritable *)NULL || !bam_file.is_eof()) { - if (object != (TypedWritable *)NULL) { + while (object != nullptr || !bam_file.is_eof()) { + if (object != nullptr) { objects.push_back(object); } object = bam_file.read_object(); @@ -234,7 +234,7 @@ describe_session(RecorderHeader *header, const BamInfo::Objects &objects) { strftime(time_buffer, 1024, "%c", localtime(&header->_start_time)); - pset recorders; + pset recorders; double last_timestamp = 0.0; for (size_t i = 1; i < objects.size(); i++) { @@ -256,7 +256,7 @@ describe_session(RecorderHeader *header, const BamInfo::Objects &objects) { << " secs, " << objects.size() - 1 << " frames, " << time_buffer << ".\n" << "Recorders:"; - for (pset::iterator ni = recorders.begin(); + for (pset::iterator ni = recorders.begin(); ni != recorders.end(); ++ni) { nout << " " << (*ni); @@ -271,7 +271,7 @@ describe_session(RecorderHeader *header, const BamInfo::Objects &objects) { */ void BamInfo:: describe_general_object(TypedWritable *object) { - nassertv(object != (TypedWritable *)NULL); + nassertv(object != nullptr); nout << " " << object->get_type() << "\n"; } diff --git a/pandatool/src/bam/bamToEgg.cxx b/pandatool/src/bam/bamToEgg.cxx index 7f70255ce9..96aa14e449 100644 --- a/pandatool/src/bam/bamToEgg.cxx +++ b/pandatool/src/bam/bamToEgg.cxx @@ -59,7 +59,7 @@ run() { Objects objects; TypedWritable *object = bam_file.read_object(); - if (object != (TypedWritable *)NULL && + if (object != nullptr && object->is_exact_type(BamCacheRecord::get_class_type())) { // Here's a special case: if the first object in the file is a // BamCacheRecord, it's really a cache data file and not a true bam file; @@ -68,10 +68,10 @@ run() { object = bam_file.read_object(); } - while (object != (TypedWritable *)NULL || !bam_file.is_eof()) { - if (object != (TypedWritable *)NULL) { + while (object != nullptr || !bam_file.is_eof()) { + if (object != nullptr) { ReferenceCount *ref_ptr = object->as_reference_count(); - if (ref_ptr != NULL) { + if (ref_ptr != nullptr) { ref_ptr->ref(); } objects.push_back(object); diff --git a/pandatool/src/bam/eggToBam.cxx b/pandatool/src/bam/eggToBam.cxx index f6c9bf4b52..a7e760d29c 100644 --- a/pandatool/src/bam/eggToBam.cxx +++ b/pandatool/src/bam/eggToBam.cxx @@ -80,7 +80,7 @@ EggToBam() : "egg geometry tagged as \"hidden\" will be removed from the final " "scene graph; otherwise, it will be preserved (but stashed). The " "default is nonzero, to remove it.", - &EggToBam::dispatch_int, NULL, &_egg_suppress_hidden); + &EggToBam::dispatch_int, nullptr, &_egg_suppress_hidden); add_option ("ls", "", 0, @@ -185,7 +185,7 @@ EggToBam() : "Set it to 'default' to use whatever is specified by the Config.prc " "file. This is a global setting only; individual texture quality " "settings appearing within the egg file will override this.", - &EggToBam::dispatch_string, NULL, &_ctex_quality); + &EggToBam::dispatch_string, nullptr, &_ctex_quality); add_option ("load-display", "display name", 0, @@ -197,7 +197,7 @@ EggToBam() : "Panda can compress textures without loading a display module." #endif // HAVE_SQUISH , - &EggToBam::dispatch_string, NULL, &_load_display); + &EggToBam::dispatch_string, nullptr, &_load_display); redescribe_option ("cs", @@ -246,7 +246,7 @@ run() { if (_ctex_quality != "default") { // Override the user's config file with the command-line parameter for // texture compression. - string prc = "texture-quality-level " + _ctex_quality; + std::string prc = "texture-quality-level " + _ctex_quality; load_prc_file_data("prc", prc); } @@ -257,7 +257,7 @@ run() { } PT(PandaNode) root = load_egg_data(_data); - if (root == (PandaNode *)NULL) { + if (root == nullptr) { nout << "Unable to build scene graph from egg file.\n"; exit(1); } @@ -385,7 +385,7 @@ collect_textures(PandaNode *node) { void EggToBam:: collect_textures(const RenderState *state) { const TextureAttrib *tex_attrib = DCAST(TextureAttrib, state->get_attrib(TextureAttrib::get_class_type())); - if (tex_attrib != (TextureAttrib *)NULL) { + if (tex_attrib != nullptr) { int num_on_stages = tex_attrib->get_num_on_stages(); for (int i = 0; i < num_on_stages; ++i) { _textures.insert(tex_attrib->get_on_texture(tex_attrib->get_on_stage(i))); @@ -442,13 +442,13 @@ bool EggToBam:: make_buffer() { if (!_load_display.empty()) { // Override the user's config file with the command-line parameter. - string prc = "load-display " + _load_display; + std::string prc = "load-display " + _load_display; load_prc_file_data("prc", prc); } GraphicsPipeSelection *selection = GraphicsPipeSelection::get_global_ptr(); _pipe = selection->make_default_pipe(); - if (_pipe == (GraphicsPipe *)NULL) { + if (_pipe == nullptr) { nout << "Unable to create graphics pipe.\n"; return false; } @@ -473,7 +473,7 @@ make_buffer() { fbprops, winprops, GraphicsPipe::BF_fb_props_optional); _engine->open_windows(); - if (_buffer == (GraphicsOutput *)NULL || !_buffer->is_valid()) { + if (_buffer == nullptr || !_buffer->is_valid()) { nout << "Unable to create graphics window.\n"; return false; } diff --git a/pandatool/src/bam/eggToBam.h b/pandatool/src/bam/eggToBam.h index a2fb838871..1ab262a52a 100644 --- a/pandatool/src/bam/eggToBam.h +++ b/pandatool/src/bam/eggToBam.h @@ -64,8 +64,8 @@ private: bool _tex_txopz; bool _tex_ctex; bool _tex_mipmap; - string _ctex_quality; - string _load_display; + std::string _ctex_quality; + std::string _load_display; // The rest of this is required to support -ctex. PT(GraphicsPipe) _pipe; diff --git a/pandatool/src/bam/ptsToBam.cxx b/pandatool/src/bam/ptsToBam.cxx index 4db96663ca..0059df8616 100644 --- a/pandatool/src/bam/ptsToBam.cxx +++ b/pandatool/src/bam/ptsToBam.cxx @@ -22,6 +22,8 @@ #include "string_utils.h" #include "config_egg2pg.h" +using std::string; + /** * */ @@ -49,7 +51,7 @@ PtsToBam() : WithOutputFile(true, false, true) "Decimates the point cloud by the indicated divisor. The number of points\n" "added is 1/divisor; numbers larger than 1.0 mean correspondingly fewer\n" "points.", - &PtsToBam::dispatch_double, NULL, &_decimate_divisor); + &PtsToBam::dispatch_double, nullptr, &_decimate_divisor); _decimate_divisor = 1.0; } @@ -71,13 +73,13 @@ run() { _num_points_expected = 0; _num_points_found = 0; _num_points_added = 0; - _decimate_factor = 1.0 / max(1.0, _decimate_divisor); + _decimate_factor = 1.0 / std::max(1.0, _decimate_divisor); _line_number = 0; _point_number = 0; _decimated_point_number = 0.0; _num_vdatas = 0; string line; - while (getline(pts, line)) { + while (std::getline(pts, line)) { process_line(line); } close_vertex_data(); @@ -132,7 +134,7 @@ process_line(const string &line) { _line_number++; if (_line_number % 1000000 == 0) { - cerr << "." << flush; + std::cerr << "." << std::flush; } if (line.empty() || !isdigit(line[0])) { @@ -172,7 +174,7 @@ process_line(const string &line) { */ void PtsToBam:: add_point(const vector_string &words) { - if (_data == NULL || _data->get_num_rows() >= egg_max_vertices) { + if (_data == nullptr || _data->get_num_rows() >= egg_max_vertices) { open_vertex_data(); } @@ -190,7 +192,7 @@ add_point(const vector_string &words) { */ void PtsToBam:: open_vertex_data() { - if (_data != (GeomVertexData *)NULL) { + if (_data != nullptr) { close_vertex_data(); } CPT(GeomVertexFormat) format = GeomVertexFormat::get_v3(); @@ -203,7 +205,7 @@ open_vertex_data() { */ void PtsToBam:: close_vertex_data() { - if (_data == NULL) { + if (_data == nullptr) { return; } @@ -215,7 +217,7 @@ close_vertex_data() { int num_vertices = _data->get_num_rows(); int vertices_so_far = 0; while (num_vertices > 0) { - int this_num_vertices = min(num_vertices, (int)egg_max_indices); + int this_num_vertices = std::min(num_vertices, (int)egg_max_indices); PT(GeomPrimitive) points = new GeomPoints(GeomEnums::UH_static); points->add_consecutive_vertices(vertices_so_far, this_num_vertices); geom->add_primitive(points); @@ -225,7 +227,7 @@ close_vertex_data() { _gnode->add_geom(geom); - _data = NULL; + _data = nullptr; } int main(int argc, char *argv[]) { diff --git a/pandatool/src/bam/ptsToBam.h b/pandatool/src/bam/ptsToBam.h index 9e6f7ac63e..20fa76e7a9 100644 --- a/pandatool/src/bam/ptsToBam.h +++ b/pandatool/src/bam/ptsToBam.h @@ -37,7 +37,7 @@ protected: virtual bool handle_args(Args &args); private: - void process_line(const string &line); + void process_line(const std::string &line); void add_point(const vector_string &words); void open_vertex_data(); diff --git a/pandatool/src/converter/eggToSomethingConverter.I b/pandatool/src/converter/eggToSomethingConverter.I index 5e80c2cad8..5432082413 100644 --- a/pandatool/src/converter/eggToSomethingConverter.I +++ b/pandatool/src/converter/eggToSomethingConverter.I @@ -34,7 +34,7 @@ had_error() const { */ INLINE void EggToSomethingConverter:: clear_egg_data() { - set_egg_data((EggData *)NULL); + set_egg_data(nullptr); } /** diff --git a/pandatool/src/converter/eggToSomethingConverter.cxx b/pandatool/src/converter/eggToSomethingConverter.cxx index f786c81f00..0f357883c8 100644 --- a/pandatool/src/converter/eggToSomethingConverter.cxx +++ b/pandatool/src/converter/eggToSomethingConverter.cxx @@ -20,7 +20,7 @@ */ EggToSomethingConverter:: EggToSomethingConverter() { - _egg_data = (EggData *)NULL; + _egg_data = nullptr; _error = false; } @@ -29,7 +29,7 @@ EggToSomethingConverter() { */ EggToSomethingConverter:: EggToSomethingConverter(const EggToSomethingConverter ©) { - _egg_data = (EggData *)NULL; + _egg_data = nullptr; _error = false; } @@ -54,9 +54,9 @@ set_egg_data(EggData *egg_data) { * Returns a space-separated list of extension, in addition to the one * returned by get_extension(), that are recognized by this converter. */ -string EggToSomethingConverter:: +std::string EggToSomethingConverter:: get_additional_extensions() const { - return string(); + return std::string(); } /** diff --git a/pandatool/src/converter/eggToSomethingConverter.h b/pandatool/src/converter/eggToSomethingConverter.h index 47838859d4..0e95958c39 100644 --- a/pandatool/src/converter/eggToSomethingConverter.h +++ b/pandatool/src/converter/eggToSomethingConverter.h @@ -51,9 +51,9 @@ public: INLINE void set_output_coordinate_system(CoordinateSystem output_coordinate_system) const; INLINE CoordinateSystem get_output_coordinate_system() const; - virtual string get_name() const=0; - virtual string get_extension() const=0; - virtual string get_additional_extensions() const; + virtual std::string get_name() const=0; + virtual std::string get_extension() const=0; + virtual std::string get_additional_extensions() const; virtual bool supports_compressed() const; virtual bool write_file(const Filename &filename)=0; diff --git a/pandatool/src/converter/somethingToEggConverter.I b/pandatool/src/converter/somethingToEggConverter.I index 42e9f4b2cf..b3fed0cb11 100644 --- a/pandatool/src/converter/somethingToEggConverter.I +++ b/pandatool/src/converter/somethingToEggConverter.I @@ -82,14 +82,14 @@ get_animation_convert() const { * its associated animations. */ INLINE void SomethingToEggConverter:: -set_character_name(const string &character_name) { +set_character_name(const std::string &character_name) { _character_name = character_name; } /** * Returns the name of the character generated. See set_character_name(). */ -INLINE const string &SomethingToEggConverter:: +INLINE const std::string &SomethingToEggConverter:: get_character_name() const { return _character_name; } @@ -370,7 +370,7 @@ get_merge_externals() const { */ INLINE void SomethingToEggConverter:: clear_egg_data() { - set_egg_data((EggData *)NULL); + set_egg_data(nullptr); } /** diff --git a/pandatool/src/converter/somethingToEggConverter.cxx b/pandatool/src/converter/somethingToEggConverter.cxx index fd5a17abf7..8911021a0a 100644 --- a/pandatool/src/converter/somethingToEggConverter.cxx +++ b/pandatool/src/converter/somethingToEggConverter.cxx @@ -33,7 +33,7 @@ SomethingToEggConverter() { _output_frame_rate = 0.0; _control_flags = 0; _merge_externals = false; - _egg_data = (EggData *)NULL; + _egg_data = nullptr; _error = false; } @@ -46,7 +46,7 @@ SomethingToEggConverter(const SomethingToEggConverter ©) : _path_replace(copy._path_replace), _merge_externals(copy._merge_externals) { - _egg_data = (EggData *)NULL; + _egg_data = nullptr; _error = false; } @@ -71,9 +71,9 @@ set_egg_data(EggData *egg_data) { * Returns a space-separated list of extension, in addition to the one * returned by get_extension(), that are recognized by this converter. */ -string SomethingToEggConverter:: +std::string SomethingToEggConverter:: get_additional_extensions() const { - return string(); + return std::string(); } /** @@ -116,7 +116,7 @@ get_input_units() { */ PT(PandaNode) SomethingToEggConverter:: convert_to_node(const LoaderOptions &options, const Filename &filename) { - return NULL; + return nullptr; } /** diff --git a/pandatool/src/converter/somethingToEggConverter.h b/pandatool/src/converter/somethingToEggConverter.h index b3e71b6ab5..16d16df50d 100644 --- a/pandatool/src/converter/somethingToEggConverter.h +++ b/pandatool/src/converter/somethingToEggConverter.h @@ -55,8 +55,8 @@ public: INLINE void set_animation_convert(AnimationConvert animation_convert); INLINE AnimationConvert get_animation_convert() const; - INLINE void set_character_name(const string &character_name); - INLINE const string &get_character_name() const; + INLINE void set_character_name(const std::string &character_name); + INLINE const std::string &get_character_name() const; INLINE void set_start_frame(double start_frame); INLINE bool has_start_frame() const; @@ -97,9 +97,9 @@ public: INLINE void clear_egg_data(); INLINE EggData *get_egg_data(); - virtual string get_name() const=0; - virtual string get_extension() const=0; - virtual string get_additional_extensions() const; + virtual std::string get_name() const=0; + virtual std::string get_extension() const=0; + virtual std::string get_additional_extensions() const; virtual bool supports_compressed() const; virtual bool supports_convert_to_node(const LoaderOptions &options) const; @@ -119,7 +119,7 @@ protected: PT(PathReplace) _path_replace; AnimationConvert _animation_convert; - string _character_name; + std::string _character_name; double _start_frame; double _end_frame; double _frame_inc; diff --git a/pandatool/src/cvscopy/cvsCopy.cxx b/pandatool/src/cvscopy/cvsCopy.cxx index 1b8b43449a..17dd07eb66 100644 --- a/pandatool/src/cvscopy/cvsCopy.cxx +++ b/pandatool/src/cvscopy/cvsCopy.cxx @@ -17,6 +17,8 @@ #include "pnotify.h" #include +using std::string; + /** * */ @@ -26,8 +28,8 @@ CVSCopy() { _key_filename = "Sources.pp"; _cvs_binary = "cvs"; _user_aborted = false; - _model_dir = (CVSSourceDirectory *)NULL; - _map_dir = (CVSSourceDirectory *)NULL; + _model_dir = nullptr; + _map_dir = nullptr; clear_runlines(); add_runline("[opts] file [file ... ]"); @@ -73,7 +75,7 @@ CVSCopy() { "is the ppremake convention, \"Sources.pp\". Other likely candidates " "are \"CVS\" to search a CVS hierarchy, or \".\" to include " "all subdirectories indiscriminately.", - &CVSCopy::dispatch_filename, NULL, &_key_filename); + &CVSCopy::dispatch_filename, nullptr, &_key_filename); add_option ("nc", "", 80, @@ -85,7 +87,7 @@ CVSCopy() { ("cvs", "cvs_binary", 80, "Specify how to run the cvs program for adding newly-created files. " "The default is simply \"cvs\".", - &CVSCopy::dispatch_string, NULL, &_cvs_binary); + &CVSCopy::dispatch_string, nullptr, &_cvs_binary); } /** @@ -212,7 +214,7 @@ post_command_line() { } _model_dir = _tree.find_directory(_model_dirname); - if (_model_dir == (CVSSourceDirectory *)NULL) { + if (_model_dir == nullptr) { if (_got_model_dirname) { nout << "Warning: model directory " << _model_dirname << " is not within the source hierarchy.\n"; @@ -222,7 +224,7 @@ post_command_line() { if (_got_map_dirname) { _map_dir = _tree.find_directory(_map_dirname); - if (_map_dir == (CVSSourceDirectory *)NULL) { + if (_map_dir == nullptr) { nout << "Warning: map directory " << _map_dirname << " is not within the source hierarchy.\n"; } @@ -230,7 +232,7 @@ post_command_line() { } else { _map_dir = _tree.find_relpath("src/maps"); - if (_map_dir == (CVSSourceDirectory *)NULL) { + if (_map_dir == nullptr) { nout << "Warning: no directory " << _tree.get_root_dirname() << "/src/maps.\n"; _map_dir = _model_dir; @@ -264,7 +266,7 @@ verify_binary_file(Filename source, Filename dest) { source.set_binary(); dest.set_binary(); - ifstream s, d; + std::ifstream s, d; if (!source.open_read(s)) { return false; } @@ -313,8 +315,8 @@ copy_binary_file(Filename source, Filename dest) { source.set_binary(); dest.set_binary(); - ifstream in; - ofstream out; + std::ifstream in; + std::ofstream out; if (!source.open_read(in)) { nout << "Cannot read " << source << "\n"; return false; @@ -475,11 +477,11 @@ scan_for_root(const string &dirname) { */ string CVSCopy:: prompt(const string &message) { - nout << flush; + nout << std::flush; while (true) { - cerr << message << flush; - string response; - getline(cin, response); + std::cerr << message << std::flush; + std::string response; + std::getline(std::cin, response); // Remove leading and trailing whitespace. size_t p = 0; diff --git a/pandatool/src/cvscopy/cvsCopy.h b/pandatool/src/cvscopy/cvsCopy.h index e8957eaa59..d820edf84d 100644 --- a/pandatool/src/cvscopy/cvsCopy.h +++ b/pandatool/src/cvscopy/cvsCopy.h @@ -52,14 +52,14 @@ protected: bool copy_binary_file(Filename source, Filename dest); bool cvs_add(const Filename &filename); - static string protect_from_shell(const string &source); + static std::string protect_from_shell(const std::string &source); - virtual string filter_filename(const string &source); + virtual std::string filter_filename(const std::string &source); private: bool scan_hierarchy(); - bool scan_for_root(const string &dirname); - string prompt(const string &message); + bool scan_for_root(const std::string &dirname); + std::string prompt(const std::string &message); protected: bool _force; @@ -72,7 +72,7 @@ protected: Filename _root_dirname; Filename _key_filename; bool _no_cvs; - string _cvs_binary; + std::string _cvs_binary; bool _user_aborted; typedef pvector SourceFiles; @@ -82,7 +82,7 @@ protected: CVSSourceDirectory *_model_dir; CVSSourceDirectory *_map_dir; - typedef pmap CopiedFiles; + typedef pmap CopiedFiles; CopiedFiles _copied_files; }; diff --git a/pandatool/src/cvscopy/cvsSourceDirectory.cxx b/pandatool/src/cvscopy/cvsSourceDirectory.cxx index 02e6a9ced1..0eb741044d 100644 --- a/pandatool/src/cvscopy/cvsSourceDirectory.cxx +++ b/pandatool/src/cvscopy/cvsSourceDirectory.cxx @@ -17,6 +17,8 @@ #include "pnotify.h" +using std::string; + /** * */ @@ -27,7 +29,7 @@ CVSSourceDirectory(CVSSourceTree *tree, CVSSourceDirectory *parent, _parent(parent), _dirname(dirname) { - if (_parent == (CVSSourceDirectory *)NULL) { + if (_parent == nullptr) { _depth = 0; } else { _depth = _parent->_depth + 1; @@ -58,7 +60,7 @@ get_dirname() const { */ Filename CVSSourceDirectory:: get_fullpath() const { - if (_parent == (CVSSourceDirectory *)NULL) { + if (_parent == nullptr) { return _tree->get_root_fullpath(); } return Filename(_parent->get_fullpath(), _dirname); @@ -70,7 +72,7 @@ get_fullpath() const { */ Filename CVSSourceDirectory:: get_path() const { - if (_parent == (CVSSourceDirectory *)NULL) { + if (_parent == nullptr) { return _dirname; } return Filename(_parent->get_path(), _dirname); @@ -93,13 +95,13 @@ get_rel_to(const CVSSourceDirectory *other) const { while (a->_depth > b->_depth) { prefix += "../"; a = a->_parent; - nassertr(a != (CVSSourceDirectory *)NULL, string()); + nassertr(a != nullptr, string()); } while (b->_depth > a->_depth) { postfix = b->_dirname + "/" + postfix; b = b->_parent; - nassertr(b != (CVSSourceDirectory *)NULL, string()); + nassertr(b != nullptr, string()); } while (a != b) { @@ -107,8 +109,8 @@ get_rel_to(const CVSSourceDirectory *other) const { postfix = b->_dirname + "/" + postfix; a = a->_parent; b = b->_parent; - nassertr(a != (CVSSourceDirectory *)NULL, string()); - nassertr(b != (CVSSourceDirectory *)NULL, string()); + nassertr(a != nullptr, string()); + nassertr(b != nullptr, string()); } string result = prefix + postfix; @@ -129,7 +131,7 @@ get_num_children() const { */ CVSSourceDirectory *CVSSourceDirectory:: get_child(int n) const { - nassertr(n >= 0 && n < (int)_children.size(), NULL); + nassertr(n >= 0 && n < (int)_children.size(), nullptr); return _children[n]; } @@ -154,11 +156,11 @@ find_relpath(const string &relpath) { return find_relpath(rest); } else if (first == "..") { - if (_parent != NULL) { + if (_parent != nullptr) { return _parent->find_relpath(rest); } // Tried to back out past the root directory. - return (CVSSourceDirectory *)NULL; + return nullptr; } // Check for a child with the name indicated by first. @@ -170,7 +172,7 @@ find_relpath(const string &relpath) { } // No match. - return (CVSSourceDirectory *)NULL; + return nullptr; } /** @@ -186,12 +188,12 @@ find_dirname(const string &dirname) { Children::const_iterator ci; for (ci = _children.begin(); ci != _children.end(); ++ci) { CVSSourceDirectory *result = (*ci)->find_dirname(dirname); - if (result != (CVSSourceDirectory *)NULL) { + if (result != nullptr) { return result; } } - return (CVSSourceDirectory *)NULL; + return nullptr; } /** diff --git a/pandatool/src/cvscopy/cvsSourceDirectory.h b/pandatool/src/cvscopy/cvsSourceDirectory.h index e8e379c8f0..eb452612e4 100644 --- a/pandatool/src/cvscopy/cvsSourceDirectory.h +++ b/pandatool/src/cvscopy/cvsSourceDirectory.h @@ -35,10 +35,10 @@ class CVSSourceTree; class CVSSourceDirectory { public: CVSSourceDirectory(CVSSourceTree *tree, CVSSourceDirectory *parent, - const string &dirname); + const std::string &dirname); ~CVSSourceDirectory(); - string get_dirname() const; + std::string get_dirname() const; Filename get_fullpath() const; Filename get_path() const; Filename get_rel_to(const CVSSourceDirectory *other) const; @@ -46,16 +46,16 @@ public: int get_num_children() const; CVSSourceDirectory *get_child(int n) const; - CVSSourceDirectory *find_relpath(const string &relpath); - CVSSourceDirectory *find_dirname(const string &dirname); + CVSSourceDirectory *find_relpath(const std::string &relpath); + CVSSourceDirectory *find_dirname(const std::string &dirname); public: - bool scan(const Filename &directory, const string &key_filename); + bool scan(const Filename &directory, const std::string &key_filename); private: CVSSourceTree *_tree; CVSSourceDirectory *_parent; - string _dirname; + std::string _dirname; int _depth; typedef pvector Children; diff --git a/pandatool/src/cvscopy/cvsSourceTree.cxx b/pandatool/src/cvscopy/cvsSourceTree.cxx index 5fea69e430..8511afac6a 100644 --- a/pandatool/src/cvscopy/cvsSourceTree.cxx +++ b/pandatool/src/cvscopy/cvsSourceTree.cxx @@ -28,6 +28,8 @@ #include // for chdir #endif +using std::string; + bool CVSSourceTree::_got_start_fullpath = false; Filename CVSSourceTree::_start_fullpath; @@ -36,7 +38,7 @@ Filename CVSSourceTree::_start_fullpath; */ CVSSourceTree:: CVSSourceTree() { - _root = (CVSSourceDirectory *)NULL; + _root = nullptr; _got_root_fullpath = false; } @@ -45,7 +47,7 @@ CVSSourceTree() { */ CVSSourceTree:: ~CVSSourceTree() { - if (_root != (CVSSourceDirectory *)NULL) { + if (_root != nullptr) { delete _root; } } @@ -67,9 +69,9 @@ set_root(const Filename &root_path) { */ bool CVSSourceTree:: scan(const Filename &key_filename) { - nassertr(_root == (CVSSourceDirectory *)NULL, false); + nassertr(_root == nullptr, false); Filename root_fullpath = get_root_fullpath(); - _root = new CVSSourceDirectory(this, NULL, root_fullpath.get_basename()); + _root = new CVSSourceDirectory(this, nullptr, root_fullpath.get_basename()); return _root->scan(_path, key_filename); } @@ -95,7 +97,7 @@ find_directory(const Filename &path) { if (root_fullpath.length() > fullpath.length() || cmp_nocase(fullpath.substr(0, root_fullpath.length()), root_fullpath) != 0) { // Nope! - return (CVSSourceDirectory *)NULL; + return nullptr; } // The relative name is the part of fullpath not in root_fullpath. @@ -112,7 +114,7 @@ find_directory(const Filename &path) { CVSSourceDirectory *CVSSourceTree:: find_relpath(const string &relpath) { CVSSourceDirectory *result = _root->find_relpath(relpath); - if (result != (CVSSourceDirectory *)NULL) { + if (result != nullptr) { return result; } @@ -129,7 +131,7 @@ find_relpath(const string &relpath) { return _root->find_relpath(rest); } - return (CVSSourceDirectory *)NULL; + return nullptr; } /** @@ -185,7 +187,7 @@ get_root_fullpath() { */ Filename CVSSourceTree:: get_root_dirname() const { - nassertr(_root != (CVSSourceDirectory *)NULL, Filename()); + nassertr(_root != nullptr, Filename()); return _root->get_dirname(); } @@ -407,14 +409,14 @@ ask_any(const string &basename, // relative path from the root (with or without the root's dirname), or // the dirname of the particular directory. CVSSourceDirectory *dir = find_directory(result); - if (dir == (CVSSourceDirectory *)NULL) { + if (dir == nullptr) { dir = find_relpath(result); } - if (dir == (CVSSourceDirectory *)NULL) { + if (dir == nullptr) { dir = find_dirname(result); } - if (dir != (CVSSourceDirectory *)NULL) { + if (dir != nullptr) { // If the file is already in this directory, we must preserve its // existing case. FilePaths::const_iterator pi; @@ -438,11 +440,11 @@ ask_any(const string &basename, */ string CVSSourceTree:: prompt(const string &message) { - nout << flush; + nout << std::flush; while (true) { - cerr << message << flush; - string response; - getline(cin, response); + std::cerr << message << std::flush; + std::string response; + std::getline(std::cin, response); // Remove leading and trailing whitespace. size_t p = 0; @@ -491,7 +493,7 @@ get_start_fullpath() { */ CVSSourceTree::FilePath:: FilePath() : - _dir(NULL) + _dir(nullptr) { } @@ -512,7 +514,7 @@ FilePath(CVSSourceDirectory *dir, const string &basename) : */ bool CVSSourceTree::FilePath:: is_valid() const { - return (_dir != (CVSSourceDirectory *)NULL); + return (_dir != nullptr); } /** @@ -520,7 +522,7 @@ is_valid() const { */ Filename CVSSourceTree::FilePath:: get_path() const { - nassertr(_dir != (CVSSourceDirectory *)NULL, Filename()); + nassertr(_dir != nullptr, Filename()); return Filename(_dir->get_path(), _basename); } @@ -529,7 +531,7 @@ get_path() const { */ Filename CVSSourceTree::FilePath:: get_fullpath() const { - nassertr(_dir != (CVSSourceDirectory *)NULL, Filename()); + nassertr(_dir != nullptr, Filename()); return Filename(_dir->get_fullpath(), _basename); } @@ -539,6 +541,6 @@ get_fullpath() const { */ Filename CVSSourceTree::FilePath:: get_rel_from(const CVSSourceDirectory *other) const { - nassertr(_dir != (CVSSourceDirectory *)NULL, Filename()); + nassertr(_dir != nullptr, Filename()); return Filename(other->get_rel_to(_dir), _basename); } diff --git a/pandatool/src/cvscopy/cvsSourceTree.h b/pandatool/src/cvscopy/cvsSourceTree.h index b512ce6db0..238431f78d 100644 --- a/pandatool/src/cvscopy/cvsSourceTree.h +++ b/pandatool/src/cvscopy/cvsSourceTree.h @@ -41,8 +41,8 @@ public: CVSSourceDirectory *get_root() const; CVSSourceDirectory *find_directory(const Filename &path); - CVSSourceDirectory *find_relpath(const string &relpath); - CVSSourceDirectory *find_dirname(const string &dirname); + CVSSourceDirectory *find_relpath(const std::string &relpath); + CVSSourceDirectory *find_dirname(const std::string &dirname); // This nested class represents the selection of a particular directory in // which to place a given file, given its basename. The basename of the @@ -52,17 +52,17 @@ public: class FilePath { public: FilePath(); - FilePath(CVSSourceDirectory *dir, const string &basename); + FilePath(CVSSourceDirectory *dir, const std::string &basename); bool is_valid() const; Filename get_path() const; Filename get_fullpath() const; Filename get_rel_from(const CVSSourceDirectory *other) const; CVSSourceDirectory *_dir; - string _basename; + std::string _basename; }; - FilePath choose_directory(const string &basename, + FilePath choose_directory(const std::string &basename, CVSSourceDirectory *suggested_dir, bool force, bool interactive); @@ -73,22 +73,22 @@ public: static void restore_cwd(); public: - void add_file(const string &basename, CVSSourceDirectory *dir); + void add_file(const std::string &basename, CVSSourceDirectory *dir); private: typedef pvector FilePaths; FilePath - prompt_user(const string &basename, CVSSourceDirectory *suggested_dir, + prompt_user(const std::string &basename, CVSSourceDirectory *suggested_dir, const FilePaths &paths, bool force, bool interactive); - FilePath ask_existing(const string &filename, const FilePath &path); - FilePath ask_existing(const string &filename, const FilePaths &paths, + FilePath ask_existing(const std::string &filename, const FilePath &path); + FilePath ask_existing(const std::string &filename, const FilePaths &paths, CVSSourceDirectory *suggested_dir); - FilePath ask_new(const string &filename, CVSSourceDirectory *dir); - FilePath ask_any(const string &filename, const FilePaths &paths); + FilePath ask_new(const std::string &filename, CVSSourceDirectory *dir); + FilePath ask_any(const std::string &filename, const FilePaths &paths); - string prompt(const string &message); + std::string prompt(const std::string &message); static Filename get_actual_fullpath(const Filename &path); static Filename get_start_fullpath(); @@ -97,7 +97,7 @@ private: Filename _path; CVSSourceDirectory *_root; - typedef pmap Basenames; + typedef pmap Basenames; Basenames _basenames; static bool _got_start_fullpath; diff --git a/pandatool/src/cvscopy/testCopy.cxx b/pandatool/src/cvscopy/testCopy.cxx index 4947bc8d5c..78010c58bb 100644 --- a/pandatool/src/cvscopy/testCopy.cxx +++ b/pandatool/src/cvscopy/testCopy.cxx @@ -39,7 +39,7 @@ run() { SourceFiles::iterator fi; for (fi = _source_files.begin(); fi != _source_files.end(); ++fi) { CVSSourceDirectory *dest = import(*fi, 0, _model_dir); - if (dest == (CVSSourceDirectory *)NULL) { + if (dest == nullptr) { exit(1); } } diff --git a/pandatool/src/daeegg/daeCharacter.cxx b/pandatool/src/daeegg/daeCharacter.cxx index 31d8db02cb..39aee067bd 100644 --- a/pandatool/src/daeegg/daeCharacter.cxx +++ b/pandatool/src/daeegg/daeCharacter.cxx @@ -42,14 +42,14 @@ DaeCharacter(EggGroup *node_group, const FCDControllerInstance *instance) : _node_group(node_group), _name(node_group->get_name()), _instance(instance), - _skin_controller(NULL), - _skin_mesh(NULL) { + _skin_controller(nullptr), + _skin_mesh(nullptr) { _bind_shape_mat = LMatrix4d::ident_mat(); // If it's a skin controller, add the controller joints. const FCDController *controller = (const FCDController *)instance->GetEntity(); - if (controller == NULL) { + if (controller == nullptr) { return; } _skin_mesh = controller->GetBaseGeometry()->GetMesh(); @@ -76,7 +76,7 @@ bind_joints(JointMap &joint_map) { // Record the bind pose for each joint. for (size_t j = 0; j < num_joints; ++j) { const FCDSkinControllerJoint *skin_joint = _skin_controller->GetJoint(j); - string sid = FROM_FSTRING(skin_joint->GetId()); + std::string sid = FROM_FSTRING(skin_joint->GetId()); LMatrix4d bind_pose; bind_pose.invert_from(DAEToEggConverter::convert_matrix( skin_joint->GetBindPoseInverse())); @@ -86,7 +86,7 @@ bind_joints(JointMap &joint_map) { if (ji != joint_map.end()) { Joint &joint = ji->second; - if (joint._character != (DaeCharacter *)NULL) { + if (joint._character != nullptr) { // In some cases, though, multiple controllers share the same joints. // We can't support this without duplicating the joint structure, so // we check if the bind poses are the same. @@ -108,7 +108,7 @@ bind_joints(JointMap &joint_map) { << "Unknown joint sid being referenced: '" << sid << "'\n"; // We still have to add a dummy joint or the index will be off. - _joints.push_back(Joint(NULL, NULL)); + _joints.push_back(Joint(nullptr, nullptr)); } } } @@ -126,7 +126,7 @@ adjust_joints(FCDSceneNode *node, const JointMap &joint_map, LMatrix4d this_transform = transform; if (node->IsJoint()) { - string sid = FROM_FSTRING(node->GetSubId()); + std::string sid = FROM_FSTRING(node->GetSubId()); JointMap::const_iterator ji = joint_map.find(sid); if (ji != joint_map.end()) { @@ -179,7 +179,7 @@ influence_vertex(int index, EggVertex *vertex) { if (jwpair->jointIndex >= 0 && jwpair->jointIndex < (int)_joints.size()) { EggGroup *joint = _joints[jwpair->jointIndex]._group.p(); - if (joint != NULL) { + if (joint != nullptr) { joint->ref_vertex(vertex, jwpair->weight); } } else { @@ -218,7 +218,7 @@ r_collect_keys(FCDSceneNode* node, pset &keys) { FCDTransform *transform = node->GetTransform(t); FCDAnimated *animated = transform->GetAnimated(); - if (animated != NULL) { + if (animated != nullptr) { const FCDAnimationCurveListList &all_curves = animated->GetCurves(); for (size_t ci = 0; ci < all_curves.size(); ++ci) { @@ -243,7 +243,7 @@ r_collect_keys(FCDSceneNode* node, pset &keys) { */ void DaeCharacter:: build_table(EggTable *parent, FCDSceneNode* node, const pset &keys) { - nassertv(node != NULL); + nassertv(node != nullptr); if (!node->IsJoint()) { for (size_t ch = 0; ch < node->GetChildrenCount(); ++ch) { @@ -252,7 +252,7 @@ build_table(EggTable *parent, FCDSceneNode* node, const pset &keys) { return; } - string node_id = FROM_FSTRING(node->GetDaeId()); + std::string node_id = FROM_FSTRING(node->GetDaeId()); PT(EggTable) table = new EggTable(node_id); table->set_table_type(EggTable::TT_table); parent->add_child(table); @@ -267,7 +267,7 @@ build_table(EggTable *parent, FCDSceneNode* node, const pset &keys) { for (size_t t = 0; t < node->GetTransformCount(); ++t) { FCDTransform *transform = node->GetTransform(t); FCDAnimated *animated = transform->GetAnimated(); - if (animated != (FCDAnimated *)NULL) { + if (animated != nullptr) { if (animated->HasCurve()) { animateds.push_back(animated); } diff --git a/pandatool/src/daeegg/daeCharacter.h b/pandatool/src/daeegg/daeCharacter.h index 78ff504e2e..25378b684d 100644 --- a/pandatool/src/daeegg/daeCharacter.h +++ b/pandatool/src/daeegg/daeCharacter.h @@ -40,7 +40,7 @@ public: INLINE Joint(EggGroup *group, const FCDSceneNode *scene_node) : _group(group), _scene_node(scene_node), - _character(NULL), + _character(nullptr), _bind_pose(LMatrix4d::ident_mat()) {} LMatrix4d _bind_pose; @@ -49,7 +49,7 @@ public: DaeCharacter *_character; }; typedef epvector Joints; - typedef pmap JointMap; + typedef pmap JointMap; void bind_joints(JointMap &joint_map); void adjust_joints(FCDSceneNode *node, const JointMap &joint_map, @@ -69,7 +69,7 @@ public: LMatrix4d _bind_shape_mat; private: - string _name; + std::string _name; const FCDSkinController *_skin_controller; Joints _joints; JointMap _bound_joints; diff --git a/pandatool/src/daeegg/daeMaterials.cxx b/pandatool/src/daeegg/daeMaterials.cxx index e345c4b6bd..6aab105cc7 100644 --- a/pandatool/src/daeegg/daeMaterials.cxx +++ b/pandatool/src/daeegg/daeMaterials.cxx @@ -25,6 +25,9 @@ #include "filename.h" #include "string_utils.h" +using std::endl; +using std::string; + TypeHandle DaeMaterials::_type_handle; // luminance function, based on the ISOCIE color standards see ITU-R @@ -45,7 +48,7 @@ DaeMaterials(const FCDGeometryInstance* geometry_instance) { * Adds a material instance. Normally automatically done by constructor. */ void DaeMaterials::add_material_instance(const FCDMaterialInstance* instance) { - nassertv(instance != NULL); + nassertv(instance != nullptr); const string semantic (FROM_FSTRING(instance->GetSemantic())); if (_materials.count(semantic) > 0) { daeegg_cat.warning() << "Ignoring duplicate material with semantic " << semantic << endl; @@ -56,7 +59,7 @@ void DaeMaterials::add_material_instance(const FCDMaterialInstance* instance) { // Load in the uvsets for (size_t vib = 0; vib < instance->GetVertexInputBindingCount(); ++vib) { const FCDMaterialInstanceBindVertexInput* mivib = instance->GetVertexInputBinding(vib); - assert(mivib != NULL); + assert(mivib != nullptr); PT(DaeVertexInputBinding) bvi = new DaeVertexInputBinding(); bvi->_input_set = mivib->inputSet; #if FCOLLADA_VERSION >= 0x00030005 @@ -74,12 +77,12 @@ void DaeMaterials::add_material_instance(const FCDMaterialInstance* instance) { PT_EggMaterial egg_material = new EggMaterial(semantic); pvector egg_textures; const FCDEffect* effect = instance->GetMaterial()->GetEffect(); - if (effect == NULL) { + if (effect == nullptr) { daeegg_cat.debug() << "Ignoring material (semantic: " << semantic << ") without assigned effect" << endl; } else { // Grab the common profile effect const FCDEffectStandard* effect_common = (FCDEffectStandard *)effect->FindProfile(FUDaeProfileType::COMMON); - if (effect_common == NULL) { + if (effect_common == nullptr) { daeegg_cat.info() << "Ignoring effect referenced by material with semantic " << semantic << " because it has no common profile" << endl; } else { @@ -124,7 +127,7 @@ void DaeMaterials:: process_texture_bucket(const string semantic, const FCDEffectStandard* effect_common, FUDaeTextureChannel::Channel bucket, EggTexture::EnvType envtype, EggTexture::Format format) { for (size_t tx = 0; tx < effect_common->GetTextureCount(bucket); ++tx) { const FCDImage* image = effect_common->GetTexture(bucket, tx)->GetImage(); - if (image == NULL) { + if (image == nullptr) { daeegg_cat.warning() << "Texture references a nonexisting image!" << endl; } else { const FCDEffectParameterSampler* sampler = effect_common->GetTexture(bucket, tx)->GetSampler(); @@ -145,7 +148,7 @@ process_texture_bucket(const string semantic, const FCDEffectStandard* effect_co PT_EggTexture egg_texture = new EggTexture(FROM_FSTRING(image->GetDaeId()), texpath.to_os_generic()); // Find a set of UV coordinates const FCDEffectParameterInt* uvset = effect_common->GetTexture(bucket, tx)->GetSet(); - if (uvset != NULL) { + if (uvset != nullptr) { daeegg_cat.debug() << "Texture has uv name '" << FROM_FSTRING(uvset->GetSemantic()) << "'\n"; string uvset_semantic (FROM_FSTRING(uvset->GetSemantic())); @@ -158,7 +161,7 @@ process_texture_bucket(const string semantic, const FCDEffectStandard* effect_co } } // Apply sampler stuff - if (sampler != NULL) { + if (sampler != nullptr) { egg_texture->set_texture_type(convert_texture_type(sampler->GetSamplerType())); egg_texture->set_wrap_u(convert_wrap_mode(sampler->GetWrapS())); if (sampler->GetSamplerType() != FCDEffectParameterSampler::SAMPLER1D) { @@ -187,12 +190,12 @@ process_texture_bucket(const string semantic, const FCDEffectStandard* effect_co */ void DaeMaterials:: process_extra(const string semantic, const FCDExtra* extra) { - if (extra == NULL) return; + if (extra == nullptr) return; const FCDEType* etype = extra->GetDefaultType(); - if (etype == NULL) return; + if (etype == nullptr) return; for (size_t et = 0; et < etype->GetTechniqueCount(); ++et) { const FCDENode* enode = ((const FCDENode*)(etype->GetTechnique(et)))->FindChildNode("double_sided"); - if (enode != NULL) { + if (enode != nullptr) { string content = trim(enode->GetContent()); if (content == "1" || content == "true") { _materials[semantic]->_double_sided = true; diff --git a/pandatool/src/daeegg/daeMaterials.h b/pandatool/src/daeegg/daeMaterials.h index 7c2ba0d563..c18e631535 100644 --- a/pandatool/src/daeegg/daeMaterials.h +++ b/pandatool/src/daeegg/daeMaterials.h @@ -41,9 +41,9 @@ public: virtual ~DaeMaterials() {}; void add_material_instance(const FCDMaterialInstance* instance); - void apply_to_primitive(const string semantic, const PT(EggPrimitive) to); - void apply_to_group(const string semantic, const PT(EggGroup) to, bool invert_transparency=false); - const string get_uvset_name(const string semantic, FUDaeGeometryInput::Semantic input_semantic, int32 input_set); + void apply_to_primitive(const std::string semantic, const PT(EggPrimitive) to); + void apply_to_group(const std::string semantic, const PT(EggGroup) to, bool invert_transparency=false); + const std::string get_uvset_name(const std::string semantic, FUDaeGeometryInput::Semantic input_semantic, int32 input_set); static EggTexture::TextureType convert_texture_type(const FCDEffectParameterSampler::SamplerType orig_type); static EggTexture::WrapMode convert_wrap_mode(const FUDaeTextureWrapMode::WrapMode orig_mode); @@ -62,7 +62,7 @@ private: struct DaeVertexInputBinding : public ReferenceCount { int32 _input_set; FUDaeGeometryInput::Semantic _input_semantic; - string _semantic; + std::string _semantic; }; // Holds stuff for an individual material. @@ -74,11 +74,11 @@ private: PT(DaeBlendSettings) _blend; }; - void process_texture_bucket(const string semantic, const FCDEffectStandard* effect_common, FUDaeTextureChannel::Channel bucket, EggTexture::EnvType envtype = EggTexture::ET_unspecified, EggTexture::Format format = EggTexture::F_unspecified); - void process_extra(const string semantic, const FCDExtra* extra); + void process_texture_bucket(const std::string semantic, const FCDEffectStandard* effect_common, FUDaeTextureChannel::Channel bucket, EggTexture::EnvType envtype = EggTexture::ET_unspecified, EggTexture::Format format = EggTexture::F_unspecified); + void process_extra(const std::string semantic, const FCDExtra* extra); static PT(DaeBlendSettings) convert_blend(FCDEffectStandard::TransparencyMode mode, const LColor &transparent, double transparency); - pmap _materials; + pmap _materials; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/daeegg/daeToEggConverter.cxx b/pandatool/src/daeegg/daeToEggConverter.cxx index 0b3844549f..00c20a36da 100644 --- a/pandatool/src/daeegg/daeToEggConverter.cxx +++ b/pandatool/src/daeegg/daeToEggConverter.cxx @@ -48,6 +48,9 @@ #include "FCDocument/FCDGeometryPolygonsInput.h" #endif +using std::endl; +using std::string; + /** * */ @@ -55,9 +58,9 @@ DAEToEggConverter:: DAEToEggConverter() { _unit_name = "meter"; _unit_meters = 1.0; - _document = NULL; - _table = NULL; - _error_handler = NULL; + _document = nullptr; + _table = nullptr; + _error_handler = nullptr; _invert_transparency = false; } @@ -75,7 +78,7 @@ DAEToEggConverter(const DAEToEggConverter ©) : */ DAEToEggConverter:: ~DAEToEggConverter() { - if (_error_handler != NULL) { + if (_error_handler != nullptr) { delete _error_handler; } } @@ -114,7 +117,7 @@ convert_file(const Filename &filename) { // Reset stuff clear_error(); _joints.clear(); - if (_error_handler == NULL) { + if (_error_handler == nullptr) { _error_handler = new FUErrorSimpleHandler; } @@ -126,13 +129,13 @@ convert_file(const Filename &filename) { // Read the file FCollada::Initialize(); _document = FCollada::LoadDocument(filename.to_os_specific().c_str()); - if (_document == NULL) { + if (_document == nullptr) { daeegg_cat.error() << "Failed to load document: " << _error_handler->GetErrorString() << endl; FCollada::Release(); return false; } // Make sure the file uses consistent coordinate system and length - if (_document->GetAsset() != NULL) { + if (_document->GetAsset() != nullptr) { FCDocumentTools::StandardizeUpAxisAndLength(_document); } @@ -142,7 +145,7 @@ convert_file(const Filename &filename) { string model_name = _character_name; FCDSceneNode* visual_scene = _document->GetVisualSceneInstance(); - if (visual_scene != NULL) { + if (visual_scene != nullptr) { if (model_name.empty()) { // By lack of anything better... model_name = FROM_FSTRING(visual_scene->GetName()); @@ -170,7 +173,7 @@ convert_file(const Filename &filename) { const FCDGeometryMesh *mesh = character->_skin_mesh; - if (mesh != NULL) { + if (mesh != nullptr) { PT(DaeMaterials) materials = new DaeMaterials(character->_instance); daeegg_cat.spam() << "Processing mesh for controller\n"; process_mesh(character->_node_group, mesh, materials, character); @@ -183,7 +186,7 @@ convert_file(const Filename &filename) { character->adjust_joints(visual_scene->GetChild(ch), _joints, LMatrix4d::ident_mat()); } - if (scene_group != NULL) { + if (scene_group != nullptr) { // Mark the scene as character. if (get_animation_convert() == AC_chan) { _egg_data->remove_child(scene_group); @@ -342,7 +345,7 @@ get_input_units() { void DAEToEggConverter:: process_asset() { const FCDAsset *asset = _document->GetAsset(); - if (_document->GetAsset() == NULL) { + if (_document->GetAsset() == nullptr) { return; } @@ -368,7 +371,7 @@ process_asset() { // to be a skeleton root. void DAEToEggConverter:: process_node(EggGroupNode *parent, const FCDSceneNode* node, bool forced) { - nassertv(node != NULL); + nassertv(node != nullptr); string node_id = FROM_FSTRING(node->GetDaeId()); daeegg_cat.spam() << "Processing node with ID '" << node_id << "'" << endl; @@ -416,15 +419,15 @@ process_node(EggGroupNode *parent, const FCDSceneNode* node, bool forced) { void DAEToEggConverter:: process_instance(EggGroup *parent, const FCDEntityInstance* instance) { - nassertv(instance != NULL); - nassertv(instance->GetEntity() != NULL); + nassertv(instance != nullptr); + nassertv(instance->GetEntity() != nullptr); // Check what kind of instance this is switch (instance->GetType()) { case FCDEntityInstance::GEOMETRY: { if (get_animation_convert() != AC_chan) { const FCDGeometry* geometry = (const FCDGeometry*) instance->GetEntity(); - assert(geometry != NULL); + assert(geometry != nullptr); if (geometry->IsMesh()) { // Now, handle the mesh. process_mesh(parent, geometry->GetMesh(), new DaeMaterials((const FCDGeometryInstance*) instance)); @@ -466,7 +469,7 @@ void DAEToEggConverter:: process_mesh(EggGroup *parent, const FCDGeometryMesh* mesh, DaeMaterials *materials, DaeCharacter *character) { - nassertv(mesh != NULL); + nassertv(mesh != nullptr); daeegg_cat.debug() << "Processing mesh with id " << FROM_FSTRING(mesh->GetDaeId()) << endl; // Create the egg stuff to hold this mesh @@ -481,7 +484,7 @@ process_mesh(EggGroup *parent, const FCDGeometryMesh* mesh, return; } const FCDGeometrySource* vsource = mesh->FindSourceByType(FUDaeGeometryInput::POSITION); - if (vsource == NULL) { + if (vsource == nullptr) { daeegg_cat.debug() << "Mesh with id " << FROM_FSTRING(mesh->GetDaeId()) << " has no source for POSITION data" << endl; return; } @@ -501,7 +504,7 @@ process_mesh(EggGroup *parent, const FCDGeometryMesh* mesh, PT(EggGroup) primitiveholder; // If we have materials, make a group for each material. Then, apply the // material's per-group stuff. - if (materials != NULL && (!polygons->GetMaterialSemantic().empty()) && mesh->GetPolygonsCount() > 1) { + if (materials != nullptr && (!polygons->GetMaterialSemantic().empty()) && mesh->GetPolygonsCount() > 1) { // primitiveholder = new EggGroup(FROM_FSTRING(mesh->GetDaeId()) + "." + // material_semantic); primitiveholder = new EggGroup; @@ -511,41 +514,41 @@ process_mesh(EggGroup *parent, const FCDGeometryMesh* mesh, } primitive_holders[gr] = primitiveholder; // Apply the per-group data of the materials, if we have it. - if (materials != NULL) { + if (materials != nullptr) { materials->apply_to_group(material_semantic, primitiveholder, _invert_transparency); } // Find the position sources const FCDGeometryPolygonsInput* pinput = polygons->FindInput(FUDaeGeometryInput::POSITION); - assert(pinput != NULL); + assert(pinput != nullptr); const uint32* indices = pinput->GetIndices(); // Find the normal sources const FCDGeometrySource* nsource = mesh->FindSourceByType(FUDaeGeometryInput::NORMAL); const FCDGeometryPolygonsInput* ninput = polygons->FindInput(FUDaeGeometryInput::NORMAL); const uint32* nindices; - if (ninput != NULL) nindices = ninput->GetIndices(); + if (ninput != nullptr) nindices = ninput->GetIndices(); // Find texcoord sources const FCDGeometrySource* tcsource = mesh->FindSourceByType(FUDaeGeometryInput::TEXCOORD); const FCDGeometryPolygonsInput* tcinput = polygons->FindInput(FUDaeGeometryInput::TEXCOORD); const uint32* tcindices; - if (tcinput != NULL) tcindices = tcinput->GetIndices(); + if (tcinput != nullptr) tcindices = tcinput->GetIndices(); // Find vcolor sources const FCDGeometrySource* csource = mesh->FindSourceByType(FUDaeGeometryInput::COLOR); const FCDGeometryPolygonsInput* cinput = polygons->FindInput(FUDaeGeometryInput::COLOR); const uint32* cindices; - if (cinput != NULL) cindices = cinput->GetIndices(); + if (cinput != nullptr) cindices = cinput->GetIndices(); // Find binormal sources const FCDGeometrySource* bsource = mesh->FindSourceByType(FUDaeGeometryInput::TEXBINORMAL); const FCDGeometryPolygonsInput* binput = polygons->FindInput(FUDaeGeometryInput::TEXBINORMAL); const uint32* bindices; - if (binput != NULL) bindices = binput->GetIndices(); + if (binput != nullptr) bindices = binput->GetIndices(); // Find tangent sources const FCDGeometrySource* tsource = mesh->FindSourceByType(FUDaeGeometryInput::TEXTANGENT); const FCDGeometryPolygonsInput* tinput = polygons->FindInput(FUDaeGeometryInput::TEXTANGENT); const uint32* tindices; - if (tinput != NULL) tindices = tinput->GetIndices(); + if (tinput != nullptr) tindices = tinput->GetIndices(); // Get a name for potential coordinate sets string tcsetname; - if (materials != NULL && tcinput != NULL) { + if (materials != nullptr && tcinput != nullptr) { if (daeegg_cat.is_debug()) { daeegg_cat.debug() << "Assigning texcoord set " << tcinput->GetSet() @@ -555,7 +558,7 @@ process_mesh(EggGroup *parent, const FCDGeometryMesh* mesh, FUDaeGeometryInput::TEXCOORD, tcinput->GetSet()); } string tbsetname; - if (materials != NULL && binput != NULL) { + if (materials != nullptr && binput != nullptr) { if (daeegg_cat.is_debug()) { daeegg_cat.debug() << "Assigning texbinormal set " << binput->GetSet() @@ -565,7 +568,7 @@ process_mesh(EggGroup *parent, const FCDGeometryMesh* mesh, FUDaeGeometryInput::TEXBINORMAL, binput->GetSet()); } string ttsetname; - if (materials != NULL && tinput != NULL) { + if (materials != nullptr && tinput != nullptr) { if (daeegg_cat.is_debug()) { daeegg_cat.debug() << "Assigning textangent set " << tinput->GetSet() @@ -580,19 +583,19 @@ process_mesh(EggGroup *parent, const FCDGeometryMesh* mesh, const float* data = &vsource->GetData()[indices[ix]*3]; vertex->set_pos(LPoint3d(data[0], data[1], data[2])); - if (character != NULL) { + if (character != nullptr) { // If this is skinned geometry, add the vertex influences. character->influence_vertex(indices[ix], vertex); } // Process the normal - if (nsource != NULL && ninput != NULL) { + if (nsource != nullptr && ninput != nullptr) { assert(nsource->GetStride() == 3); data = &nsource->GetData()[nindices[ix]*3]; vertex->set_normal(LVecBase3d(data[0], data[1], data[2])); } // Process the texcoords - if (tcsource != NULL && tcinput != NULL) { + if (tcsource != nullptr && tcinput != nullptr) { assert(tcsource->GetStride() == 2 || tcsource->GetStride() == 3); data = &tcsource->GetData()[tcindices[ix]*tcsource->GetStride()]; if (tcsource->GetStride() == 2) { @@ -602,7 +605,7 @@ process_mesh(EggGroup *parent, const FCDGeometryMesh* mesh, } } // Process the color - if (csource != NULL && cinput != NULL) { + if (csource != nullptr && cinput != nullptr) { assert(csource->GetStride() == 3 || csource->GetStride() == 4); if (csource->GetStride() == 3) { data = &csource->GetData()[cindices[ix]*3]; @@ -613,21 +616,21 @@ process_mesh(EggGroup *parent, const FCDGeometryMesh* mesh, } } // Possibly add a UV object - if ((bsource != NULL && binput != NULL) || (tsource != NULL && tinput != NULL)) { - if (bsource != NULL && binput != NULL) { + if ((bsource != nullptr && binput != nullptr) || (tsource != nullptr && tinput != nullptr)) { + if (bsource != nullptr && binput != nullptr) { assert(bsource->GetStride() == 3); data = &bsource->GetData()[bindices[ix]*3]; PT(EggVertexUV) uv_obj = vertex->modify_uv_obj(tbsetname); - if (uv_obj == NULL) { + if (uv_obj == nullptr) { uv_obj = new EggVertexUV(tbsetname, LTexCoordd()); } uv_obj->set_binormal(LVecBase3d(data[0], data[1], data[2])); } - if (tsource != NULL && tinput != NULL) { + if (tsource != nullptr && tinput != nullptr) { assert(tsource->GetStride() == 3); data = &tsource->GetData()[tindices[ix]*3]; PT(EggVertexUV) uv_obj = vertex->modify_uv_obj(ttsetname); - if (uv_obj == NULL) { + if (uv_obj == nullptr) { uv_obj = new EggVertexUV(ttsetname, LTexCoordd()); } uv_obj->set_tangent(LVecBase3d(data[0], data[1], data[2])); @@ -642,7 +645,7 @@ process_mesh(EggGroup *parent, const FCDGeometryMesh* mesh, // Now loop through the faces uint32 offset = 0; for (size_t fa = 0; fa < polygons->GetFaceVertexCountCount(); ++fa) { - PT(EggPrimitive) primitive = NULL; + PT(EggPrimitive) primitive = nullptr; // Create a primitive that matches the fcollada type switch (polygons->GetPrimitiveType()) { case FCDGeometryPolygons::LINES: @@ -666,9 +669,9 @@ process_mesh(EggGroup *parent, const FCDGeometryMesh* mesh, default: daeegg_cat.warning() << "Unsupported primitive type found!" << endl; } - if (primitive != NULL) { + if (primitive != nullptr) { primitive_holders[gr]->add_child(primitive); - if (materials != NULL) { + if (materials != nullptr) { materials->apply_to_primitive(FROM_FSTRING(polygons->GetMaterialSemantic()), primitive); } for (size_t ve = 0; ve < polygons->GetFaceVertexCount(fa); ++ve) { @@ -684,7 +687,7 @@ process_mesh(EggGroup *parent, const FCDGeometryMesh* mesh, void DAEToEggConverter:: process_spline(EggGroup *parent, const string group_name, FCDGeometrySpline* geometry_spline) { - assert(geometry_spline != NULL); + assert(geometry_spline != nullptr); PT(EggGroup) result = new EggGroup(group_name); parent->add_child(result); // TODO: if its not a nurbs, make it convert between the types @@ -700,7 +703,7 @@ process_spline(EggGroup *parent, const string group_name, FCDGeometrySpline* geo void DAEToEggConverter:: process_spline(EggGroup *parent, const FCDSpline* spline) { - assert(spline != NULL); + assert(spline != nullptr); nassertv(spline->GetSplineType() == FUDaeSplineType::NURBS); // Now load in the nurbs curve to the egg library PT(EggNurbsCurve) nurbs_curve = new EggNurbsCurve(FROM_FSTRING(spline->GetName())); @@ -709,7 +712,7 @@ process_spline(EggGroup *parent, const FCDSpline* spline) { nurbs_curve->setup(0, ((const FCDNURBSSpline*) spline)->GetKnotCount()); for (size_t kn = 0; kn < ((const FCDNURBSSpline*) spline)->GetKnotCount(); ++kn) { const float* knot = ((const FCDNURBSSpline*) spline)->GetKnot(kn); - assert(knot != NULL); + assert(knot != nullptr); nurbs_curve->set_knot(kn, *knot); } for (size_t cv = 0; cv < spline->GetCVCount(); ++cv) { @@ -722,14 +725,14 @@ process_spline(EggGroup *parent, const FCDSpline* spline) { void DAEToEggConverter:: process_controller(EggGroup *parent, const FCDControllerInstance *instance) { - assert(instance != NULL); + assert(instance != nullptr); const FCDController* controller = (const FCDController *)instance->GetEntity(); - assert(controller != NULL); + assert(controller != nullptr); if (get_animation_convert() == AC_none) { // If we're exporting a static mesh, export the base geometry as-is. const FCDGeometryMesh *mesh = controller->GetBaseGeometry()->GetMesh(); - if (mesh != NULL) { + if (mesh != nullptr) { PT(DaeMaterials) materials = new DaeMaterials(instance); daeegg_cat.spam() << "Processing mesh for controller\n"; process_mesh(parent, mesh, materials); @@ -741,9 +744,9 @@ process_controller(EggGroup *parent, const FCDControllerInstance *instance) { } if (controller->IsMorph()) { - assert(controller != NULL); + assert(controller != nullptr); const FCDMorphController* morph_controller = controller->GetMorphController(); - assert(morph_controller != NULL); + assert(morph_controller != nullptr); PT(EggTable) bundle = new EggTable(parent->get_name()); bundle->set_table_type(EggTable::TT_bundle); PT(EggTable) morph = new EggTable("morph"); @@ -752,7 +755,7 @@ process_controller(EggGroup *parent, const FCDControllerInstance *instance) { // Loop through the morph targets. for (size_t mt = 0; mt < morph_controller->GetTargetCount(); ++mt) { const FCDMorphTarget* morph_target = morph_controller->GetTarget(mt); - assert(morph_target != NULL); + assert(morph_target != nullptr); PT(EggSAnimData) target = new EggSAnimData(FROM_FSTRING(morph_target->GetGeometry()->GetName())); if (morph_target->IsAnimated()) { // TODO @@ -766,18 +769,18 @@ process_controller(EggGroup *parent, const FCDControllerInstance *instance) { void DAEToEggConverter:: process_extra(EggGroup *group, const FCDExtra* extra) { - if (extra == NULL) { + if (extra == nullptr) { return; } - nassertv(group != NULL); + nassertv(group != nullptr); const FCDEType* etype = extra->GetDefaultType(); - if (etype == NULL) { + if (etype == nullptr) { return; } const FCDENode* enode = (const FCDENode*) etype->FindTechnique("PANDA3D"); - if (enode == NULL) { + if (enode == nullptr) { return; } @@ -802,8 +805,8 @@ convert_matrix(const FMMatrix44 &matrix) { void DAEToEggConverter:: apply_transform(EggGroup *to, const FCDTransform* from) { - assert(from != NULL); - assert(to != NULL); + assert(from != nullptr); + assert(to != nullptr); // to->set_transform3d(convert_matrix(from->ToMatrix()) * // to->get_transform3d()); switch (from->GetType()) { diff --git a/pandatool/src/daeegg/daeToEggConverter.h b/pandatool/src/daeegg/daeToEggConverter.h index b31d439526..a1203c2f2c 100644 --- a/pandatool/src/daeegg/daeToEggConverter.h +++ b/pandatool/src/daeegg/daeToEggConverter.h @@ -49,8 +49,8 @@ public: virtual SomethingToEggConverter *make_copy(); - virtual string get_name() const; - virtual string get_extension() const; + virtual std::string get_name() const; + virtual std::string get_extension() const; virtual bool convert_file(const Filename &filename); virtual DistanceUnit get_input_units(); @@ -58,7 +58,7 @@ public: bool _invert_transparency; private: - string _unit_name; + std::string _unit_name; double _unit_meters; PT(EggTable) _table; FCDocument* _document; @@ -72,8 +72,8 @@ private: void process_node(EggGroupNode *parent, const FCDSceneNode* node, bool forced = false); void process_instance(EggGroup *parent, const FCDEntityInstance* instance); void process_mesh(EggGroup *parent, const FCDGeometryMesh* mesh, - DaeMaterials *materials, DaeCharacter *character = NULL); - void process_spline(EggGroup *parent, const string group_name, FCDGeometrySpline* geometry_spline); + DaeMaterials *materials, DaeCharacter *character = nullptr); + void process_spline(EggGroup *parent, const std::string group_name, FCDGeometrySpline* geometry_spline); void process_spline(EggGroup *parent, const FCDSpline* spline); void process_controller(EggGroup *parent, const FCDControllerInstance* instance); void process_extra(EggGroup *group, const FCDExtra* extra); diff --git a/pandatool/src/daeegg/fcollada_utils.h b/pandatool/src/daeegg/fcollada_utils.h index eefe990bac..cf1a3069f3 100644 --- a/pandatool/src/daeegg/fcollada_utils.h +++ b/pandatool/src/daeegg/fcollada_utils.h @@ -33,6 +33,6 @@ inline LColor TO_COLOR(FMVector4 v) { #define FROM_VEC3(v) (FMVector3(v[0], v[1], v[2])) #define FROM_VEC4(v) (FMVector4(v[0], v[1], v[2], v[3])) #define FROM_MAT4(v) (FMMatrix44(v.getData())) -#define FROM_FSTRING(fs) (string(fs.c_str())) +#define FROM_FSTRING(fs) (std::string(fs.c_str())) #endif diff --git a/pandatool/src/daeegg/pre_fcollada_include.h b/pandatool/src/daeegg/pre_fcollada_include.h index 18cbe7a45d..59ad054c2a 100644 --- a/pandatool/src/daeegg/pre_fcollada_include.h +++ b/pandatool/src/daeegg/pre_fcollada_include.h @@ -38,4 +38,8 @@ #define NO_LIBXML #define FCOLLADA_NOMINMAX +// FCollada does use global min/max. +using std::min; +using std::max; + #endif diff --git a/pandatool/src/daeprogs/daeToEgg.cxx b/pandatool/src/daeprogs/daeToEgg.cxx index c3ba781361..e00747344a 100644 --- a/pandatool/src/daeprogs/daeToEgg.cxx +++ b/pandatool/src/daeprogs/daeToEgg.cxx @@ -49,7 +49,7 @@ void DAEToEgg:: run() { if (_animation_convert != AC_both && _animation_convert != AC_none && _animation_convert != AC_chan && _animation_convert != AC_model) { - cerr << "Unsupported animation convert option.\n"; + std::cerr << "Unsupported animation convert option.\n"; exit(1); } diff --git a/pandatool/src/daeprogs/eggToDAE.cxx b/pandatool/src/daeprogs/eggToDAE.cxx index dff2286b88..b9652e698f 100644 --- a/pandatool/src/daeprogs/eggToDAE.cxx +++ b/pandatool/src/daeprogs/eggToDAE.cxx @@ -28,6 +28,8 @@ #define FROM_MAT4(v) (FMMatrix44(v.get_data())) #define FROM_FSTRING(fs) (fs.c_str()) +using std::cerr; + /** * */ @@ -41,7 +43,7 @@ EggToDAE() : ("This program converts files from the egg format to the COLLADA " ".dae (Digital Asset Exchange) format."); - _document = NULL; + _document = nullptr; } /** @@ -50,7 +52,7 @@ EggToDAE() : void EggToDAE:: run() { nassertv(has_output_filename()); - nassertv(_data != NULL); + nassertv(_data != nullptr); FCollada::Initialize(); _document = FCollada::NewTopDocument(); @@ -58,8 +60,8 @@ run() { // Add the contributor part to the asset FCDAssetContributor* contributor = _document->GetAsset()->AddContributor(); const char* user_name = getenv("USER"); - if (user_name == NULL) user_name = getenv("USERNAME"); - if (user_name != NULL) contributor->SetAuthor(TO_FSTRING(user_name)); + if (user_name == nullptr) user_name = getenv("USERNAME"); + if (user_name != nullptr) contributor->SetAuthor(TO_FSTRING(user_name)); // contributor->SetSourceData(); char authoring_tool[1024]; snprintf(authoring_tool, 1024, "Panda3D %s eggToDAE converter | FCollada v%d.%02d", PANDA_VERSION_STR, FCOLLADA_VERSION >> 16, FCOLLADA_VERSION & 0xFFFF); @@ -93,7 +95,7 @@ run() { } void EggToDAE::process_node(FCDSceneNode* parent, const PT(EggGroup) node) { - assert(node != NULL); + assert(node != nullptr); FCDSceneNode* scene_node = parent->AddChildNode(); // Set the parameters scene_node->SetDaeId(node->get_name().c_str()); @@ -109,8 +111,8 @@ void EggToDAE::process_node(FCDSceneNode* parent, const PT(EggGroup) node) { } void EggToDAE::apply_transform(FCDSceneNode* to, const PT(EggGroup) from) { - assert(to != NULL); - assert(from != NULL); + assert(to != nullptr); + assert(from != nullptr); for (int co = 0; co < from->get_num_components(); ++co) { switch (from->get_component_type(co)) { case EggTransform::CT_translate2d: diff --git a/pandatool/src/dxf/dxfFile.cxx b/pandatool/src/dxf/dxfFile.cxx index b716ea11ba..f5bb6e0912 100644 --- a/pandatool/src/dxf/dxfFile.cxx +++ b/pandatool/src/dxf/dxfFile.cxx @@ -15,6 +15,10 @@ #include "string_utils.h" #include "virtualFileSystem.h" +using std::istream; +using std::ostream; +using std::string; + DXFFile::Color DXFFile::_colors[DXF_num_colors] = { { 1, 1, 1 }, // Color 0 is not used. { 1, 0, 0 }, // Color 1 = Red @@ -280,9 +284,9 @@ DXFFile::Color DXFFile::_colors[DXF_num_colors] = { */ DXFFile:: DXFFile() { - _in = NULL; + _in = nullptr; _owns_in = false; - _layer = NULL; + _layer = nullptr; reset_entity(); _color_index = -1; } @@ -308,7 +312,7 @@ process(Filename filename) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); istream *in = vfs->open_read_file(filename, true); - if (in == (istream *)NULL) { + if (in == nullptr) { return; } process(in, true); @@ -552,7 +556,7 @@ get_group() { in.get(); } - getline(in, _string); + std::getline(in, _string); _string = trim_right(_string); if (!in) { @@ -620,7 +624,7 @@ change_section(Section new_section) { */ void DXFFile:: change_layer(const string &layer_name) { - if (_layer == NULL || _layer->get_name() != layer_name) { + if (_layer == nullptr || _layer->get_name() != layer_name) { _layer = _layers.get_layer(layer_name, this); } } diff --git a/pandatool/src/dxf/dxfFile.h b/pandatool/src/dxf/dxfFile.h index 59d37d3057..e555960e6a 100644 --- a/pandatool/src/dxf/dxfFile.h +++ b/pandatool/src/dxf/dxfFile.h @@ -38,7 +38,7 @@ public: virtual ~DXFFile(); void process(Filename filename); - void process(istream *in, bool owns_in); + void process(std::istream *in, bool owns_in); // These functions are called as the file is processed. These are the main // hooks for redefining how the class should dispense its data. As each @@ -57,7 +57,7 @@ public: // definition, and must allocate a DXFLayer instance. This function is // provided so that user code may force allocate of a specialized DXFLayer // instance instead. - virtual DXFLayer *new_layer(const string &name) { + virtual DXFLayer *new_layer(const std::string &name) { return new DXFLayer(name); } @@ -140,18 +140,18 @@ protected: bool _vertices_follow; LMatrix4d _ocs2wcs; - istream *_in; + std::istream *_in; bool _owns_in; int _code; - string _string; + std::string _string; void compute_ocs(); bool get_group(); void change_state(State new_state); void change_section(Section new_section); - void change_layer(const string &layer_name); + void change_layer(const std::string &layer_name); void change_entity(Entity new_entity); void reset_entity(); @@ -161,8 +161,8 @@ protected: void state_verts(); }; -ostream &operator << (ostream &out, const DXFFile::State &state); -ostream &operator << (ostream &out, const DXFFile::Section §ion); -ostream &operator << (ostream &out, const DXFFile::Entity &entity); +std::ostream &operator << (std::ostream &out, const DXFFile::State &state); +std::ostream &operator << (std::ostream &out, const DXFFile::Section §ion); +std::ostream &operator << (std::ostream &out, const DXFFile::Entity &entity); #endif diff --git a/pandatool/src/dxf/dxfLayer.cxx b/pandatool/src/dxf/dxfLayer.cxx index 5ffc96a5cc..6803cc179e 100644 --- a/pandatool/src/dxf/dxfLayer.cxx +++ b/pandatool/src/dxf/dxfLayer.cxx @@ -18,7 +18,7 @@ * */ DXFLayer:: -DXFLayer(const string &name) : Namable(name) { +DXFLayer(const std::string &name) : Namable(name) { } /** diff --git a/pandatool/src/dxf/dxfLayer.h b/pandatool/src/dxf/dxfLayer.h index dab55adb4d..745197280c 100644 --- a/pandatool/src/dxf/dxfLayer.h +++ b/pandatool/src/dxf/dxfLayer.h @@ -27,7 +27,7 @@ */ class DXFLayer : public Namable { public: - DXFLayer(const string &name); + DXFLayer(const std::string &name); virtual ~DXFLayer(); }; diff --git a/pandatool/src/dxf/dxfLayerMap.cxx b/pandatool/src/dxf/dxfLayerMap.cxx index 447b27e8ca..d2049c8191 100644 --- a/pandatool/src/dxf/dxfLayerMap.cxx +++ b/pandatool/src/dxf/dxfLayerMap.cxx @@ -22,7 +22,7 @@ * this function to create a specialized time, if desired. */ DXFLayer *DXFLayerMap:: -get_layer(const string &name, DXFFile *dxffile) { +get_layer(const std::string &name, DXFFile *dxffile) { iterator lmi; lmi = find(name); if (lmi != end()) { diff --git a/pandatool/src/dxf/dxfLayerMap.h b/pandatool/src/dxf/dxfLayerMap.h index 1dfabca80b..f2fabe5373 100644 --- a/pandatool/src/dxf/dxfLayerMap.h +++ b/pandatool/src/dxf/dxfLayerMap.h @@ -25,9 +25,9 @@ class DXFFile; * ordered by name. This is used as a lookup within DXFFile to locate the * layer associated with a particular entity. */ -class DXFLayerMap : public pmap { +class DXFLayerMap : public pmap { public: - DXFLayer *get_layer(const string &name, DXFFile *dxffile); + DXFLayer *get_layer(const std::string &name, DXFFile *dxffile); }; #endif diff --git a/pandatool/src/dxfegg/dxfToEggConverter.cxx b/pandatool/src/dxfegg/dxfToEggConverter.cxx index 58f2c7a758..6ba6411940 100644 --- a/pandatool/src/dxfegg/dxfToEggConverter.cxx +++ b/pandatool/src/dxfegg/dxfToEggConverter.cxx @@ -50,7 +50,7 @@ make_copy() { /** * Returns the English name of the file type this converter supports. */ -string DXFToEggConverter:: +std::string DXFToEggConverter:: get_name() const { return "DXF"; } @@ -58,7 +58,7 @@ get_name() const { /** * Returns the common extension of the file type this converter supports. */ -string DXFToEggConverter:: +std::string DXFToEggConverter:: get_extension() const { return "dxf"; } @@ -92,7 +92,7 @@ convert_file(const Filename &filename) { * */ DXFLayer *DXFToEggConverter:: -new_layer(const string &name) { +new_layer(const std::string &name) { return new DXFToEggLayer(name, get_egg_data()); } @@ -112,11 +112,11 @@ done_entity() { if (_flags & PF_closed) { // it's closed; create a polygon. - nassertv(_layer!=NULL); + nassertv(_layer!=nullptr); ((DXFToEggLayer *)_layer)->add_polygon(this); } else { // It's open; create a series of line segments. - nassertv(_layer!=NULL); + nassertv(_layer!=nullptr); ((DXFToEggLayer *)_layer)->add_line(this); } @@ -130,7 +130,7 @@ done_entity() { _verts.push_back(DXFVertex(_q)); _verts.push_back(DXFVertex(_p)); - nassertv(_layer!=NULL); + nassertv(_layer!=nullptr); ((DXFToEggLayer *)_layer)->add_polygon(this); } } diff --git a/pandatool/src/dxfegg/dxfToEggConverter.h b/pandatool/src/dxfegg/dxfToEggConverter.h index 8a10a50fc3..56969e7482 100644 --- a/pandatool/src/dxfegg/dxfToEggConverter.h +++ b/pandatool/src/dxfegg/dxfToEggConverter.h @@ -31,14 +31,14 @@ public: virtual SomethingToEggConverter *make_copy(); - virtual string get_name() const; - virtual string get_extension() const; + virtual std::string get_name() const; + virtual std::string get_extension() const; virtual bool supports_compressed() const; virtual bool convert_file(const Filename &filename); protected: - virtual DXFLayer *new_layer(const string &name); + virtual DXFLayer *new_layer(const std::string &name); virtual void done_entity(); virtual void error(); diff --git a/pandatool/src/dxfegg/dxfToEggLayer.cxx b/pandatool/src/dxfegg/dxfToEggLayer.cxx index 333cd5a69e..3ecb915efb 100644 --- a/pandatool/src/dxfegg/dxfToEggLayer.cxx +++ b/pandatool/src/dxfegg/dxfToEggLayer.cxx @@ -26,7 +26,7 @@ * */ DXFToEggLayer:: -DXFToEggLayer(const string &name, EggGroupNode *parent) : DXFLayer(name) { +DXFToEggLayer(const std::string &name, EggGroupNode *parent) : DXFLayer(name) { _group = new EggGroup(name); parent->add_child(_group); _vpool = new EggVertexPool(name); diff --git a/pandatool/src/dxfegg/dxfToEggLayer.h b/pandatool/src/dxfegg/dxfToEggLayer.h index 45a053e4df..9067cc702f 100644 --- a/pandatool/src/dxfegg/dxfToEggLayer.h +++ b/pandatool/src/dxfegg/dxfToEggLayer.h @@ -34,7 +34,7 @@ class DXFToEggConverter; */ class DXFToEggLayer : public DXFLayer { public: - DXFToEggLayer(const string &name, EggGroupNode *parent); + DXFToEggLayer(const std::string &name, EggGroupNode *parent); void add_polygon(const DXFToEggConverter *entity); void add_line(const DXFToEggConverter *entity); diff --git a/pandatool/src/dxfprogs/eggToDXF.cxx b/pandatool/src/dxfprogs/eggToDXF.cxx index e3fb8a85d5..412b815601 100644 --- a/pandatool/src/dxfprogs/eggToDXF.cxx +++ b/pandatool/src/dxfprogs/eggToDXF.cxx @@ -52,7 +52,7 @@ run() { // uniquify_names("layer", _layers.begin(), _layers.end()); - ostream &out = get_output(); + std::ostream &out = get_output(); // Autodesk says we don't need the header, but some DXF-reading programs // might get confused if it's missing. We'll write an empty header. @@ -107,7 +107,7 @@ get_layers(EggGroupNode *group) { * gets written later, in write_entities(). */ void EggToDXF:: -write_tables(ostream &out) { +write_tables(std::ostream &out) { out << "0\nSECTION\n" << "2\nTABLES\n" // Begin TABLES section. << "0\nTABLE\n" @@ -127,7 +127,7 @@ write_tables(ostream &out) { * Writes out the "entities", e.g. polygons, defined for all layers. */ void EggToDXF:: -write_entities(ostream &out) { +write_entities(std::ostream &out) { out << "0\nSECTION\n" << "2\nENTITIES\n"; // Begin ENTITIES section. diff --git a/pandatool/src/dxfprogs/eggToDXF.h b/pandatool/src/dxfprogs/eggToDXF.h index 0af0e999de..da7764fb85 100644 --- a/pandatool/src/dxfprogs/eggToDXF.h +++ b/pandatool/src/dxfprogs/eggToDXF.h @@ -34,8 +34,8 @@ public: private: void get_layers(EggGroupNode *group); - void write_tables(ostream &out); - void write_entities(ostream &out); + void write_tables(std::ostream &out); + void write_entities(std::ostream &out); EggToDXFLayers _layers; }; diff --git a/pandatool/src/dxfprogs/eggToDXFLayer.cxx b/pandatool/src/dxfprogs/eggToDXFLayer.cxx index c10c51f862..6922f0b8a6 100644 --- a/pandatool/src/dxfprogs/eggToDXFLayer.cxx +++ b/pandatool/src/dxfprogs/eggToDXFLayer.cxx @@ -19,6 +19,8 @@ #include "eggPolygon.h" #include "dcast.h" +using std::ostream; + /** * */ diff --git a/pandatool/src/dxfprogs/eggToDXFLayer.h b/pandatool/src/dxfprogs/eggToDXFLayer.h index 314346f7d0..a5fe7b7517 100644 --- a/pandatool/src/dxfprogs/eggToDXFLayer.h +++ b/pandatool/src/dxfprogs/eggToDXFLayer.h @@ -35,10 +35,10 @@ public: void add_color(const LColor &color); void choose_overall_color(); - void write_layer(ostream &out); - void write_polyline(EggPolygon *poly, ostream &out); - void write_3d_face(EggPolygon *poly, ostream &out); - void write_entities(ostream &out); + void write_layer(std::ostream &out); + void write_polyline(EggPolygon *poly, std::ostream &out); + void write_3d_face(EggPolygon *poly, std::ostream &out); + void write_entities(std::ostream &out); private: int get_autocad_color(const LColor &color); diff --git a/pandatool/src/egg-mkfont/eggMakeFont.cxx b/pandatool/src/egg-mkfont/eggMakeFont.cxx index 024f302199..4efa4a5ad5 100644 --- a/pandatool/src/egg-mkfont/eggMakeFont.cxx +++ b/pandatool/src/egg-mkfont/eggMakeFont.cxx @@ -32,6 +32,8 @@ #include +using std::string; + /** * */ @@ -60,7 +62,7 @@ EggMakeFont() : EggWriter(true, false) { "Specifies the foreground color of the generated texture map. The " "default is white: 1,1,1,1, which leads to the most flexibility " "as the color can be modulated at runtime to any suitable color.", - &EggMakeFont::dispatch_color, NULL, &_fg[0]); + &EggMakeFont::dispatch_color, nullptr, &_fg[0]); add_option ("bg", "r,g,b[,a]", 0, @@ -72,7 +74,7 @@ EggMakeFont() : EggWriter(true, false) { "alpha component; if both colors specify an alpha component of 1 " "(or do not specify an alpha compenent), then the generated images " "will not include an alpha component.", - &EggMakeFont::dispatch_color, NULL, &_bg[0]); + &EggMakeFont::dispatch_color, nullptr, &_bg[0]); add_option ("interior", "r,g,b[,a]", 0, @@ -93,7 +95,7 @@ EggMakeFont() : EggWriter(true, false) { "within square brackets, e.g. '[A-Za-z0-9]'. If this is not specified, " "the default set has all ASCII characters and an assorted set of " "latin-1 characters, diacritics and punctuation marks.", - &EggMakeFont::dispatch_range, NULL, &_range); + &EggMakeFont::dispatch_range, nullptr, &_range); add_option ("extra", "file.egg", 0, @@ -103,7 +105,7 @@ EggMakeFont() : EggWriter(true, false) { "number of a character and should contain one polygon. These groups " "are simply copied into the output egg file as if they were generated " "locally. This option may be repeated.", - &EggMakeFont::dispatch_vector_string, NULL, &_extra_filenames); + &EggMakeFont::dispatch_vector_string, nullptr, &_extra_filenames); add_option ("ppu", "pixels", 0, @@ -112,27 +114,27 @@ EggMakeFont() : EggWriter(true, false) { "10 points of font; see -ps). Setting this number larger results in " "an easier-to-read font, but at the cost of more texture memory. " "The default is 40.", - &EggMakeFont::dispatch_double, NULL, &_pixels_per_unit); + &EggMakeFont::dispatch_double, nullptr, &_pixels_per_unit); add_option ("ps", "size", 0, "Specify the point size of the resulting font. This controls the " "apparent size of the font when it is rendered onscreen. By convention, " "a 10 point font is 1 screen unit high, so the default is 10.", - &EggMakeFont::dispatch_double, NULL, &_point_size); + &EggMakeFont::dispatch_double, nullptr, &_point_size); add_option ("sdf", "", 0, "If this is set, a signed distance field will be generated, which " "results in crisp text even when the text is enlarged or zoomed in.", - &EggMakeFont::dispatch_true, NULL, &_generate_distance_field); + &EggMakeFont::dispatch_true, nullptr, &_generate_distance_field); add_option ("pm", "n", 0, "The number of extra pixels around a single character in the " "generated polygon. This may be a floating-point number. The " "default is 1.", - &EggMakeFont::dispatch_double, NULL, &_poly_margin); + &EggMakeFont::dispatch_double, nullptr, &_poly_margin); add_option ("tm", "n", 0, @@ -140,7 +142,7 @@ EggMakeFont() : EggWriter(true, false) { "This may only be an integer. The default is 2. This is meaningful " "when -nopal is also used; in the normal case, use -pm to control " "both the polygon size and the texture map spacing.", - &EggMakeFont::dispatch_int, NULL, &_tex_margin); + &EggMakeFont::dispatch_int, nullptr, &_tex_margin); add_option ("rm", "n", 0, @@ -149,7 +151,7 @@ EggMakeFont() : EggWriter(true, false) { "generated texture map, only on the generated egg. Use this in order to " "space the characters out in case they appear to be too close together " "when rendered. The default is 0.", - &EggMakeFont::dispatch_double, NULL, &_render_margin); + &EggMakeFont::dispatch_double, nullptr, &_render_margin); add_option ("sf", "factor", 0, @@ -192,7 +194,7 @@ EggMakeFont() : EggWriter(true, false) { "If it is omitted, the default is based on the name of the egg file. " "This is used only if -nopal is specified; in the normal case, " "without -nopal, use -pp instead.", - &EggMakeFont::dispatch_string, NULL, &_output_glyph_pattern); + &EggMakeFont::dispatch_string, nullptr, &_output_glyph_pattern); add_option ("pp", "pattern", 0, @@ -200,20 +202,20 @@ EggMakeFont() : EggWriter(true, false) { "string is effectively passed to egg-palettize as the -tn option, and " "thus should contain %i for the palette index number. This is used " "if -nopal is not specified.", - &EggMakeFont::dispatch_string, NULL, &_output_palette_pattern); + &EggMakeFont::dispatch_string, nullptr, &_output_palette_pattern); add_option ("palsize", "xsize,ysize", 0, "Specify the size of the palette texture images. This is used if " "-nopal is not specified.", - &EggMakeFont::dispatch_int_pair, NULL, _palette_size); + &EggMakeFont::dispatch_int_pair, nullptr, _palette_size); add_option ("face", "index", 0, "Specify the face index of the particular face within the font file " "to use. Some font files contain multiple faces, indexed beginning " "at 0. The default is face 0.", - &EggMakeFont::dispatch_int, NULL, &_face_index); + &EggMakeFont::dispatch_int, nullptr, &_face_index); _fg.set(1.0, 1.0, 1.0, 1.0); _bg.set(1.0, 1.0, 1.0, 0.0); @@ -227,9 +229,9 @@ EggMakeFont() : EggWriter(true, false) { _face_index = 0; _generate_distance_field = false; - _text_maker = NULL; - _vpool = NULL; - _group = NULL; + _text_maker = nullptr; + _vpool = nullptr; + _group = nullptr; } @@ -424,7 +426,7 @@ run() { _bg[0], _bg[1], _bg[2], _bg[3], _palette_size[0], _palette_size[1], 100.0 / _palettize_scale_factor); - istringstream txa_script(buffer); + std::istringstream txa_script(buffer); pal->read_txa_file(txa_script, "default script"); pal->all_params_set(); @@ -538,7 +540,7 @@ make_vertex(const LPoint2d &xy) { void EggMakeFont:: add_character(int code) { PNMTextGlyph *glyph = _text_maker->get_glyph(code); - if (glyph == (PNMTextGlyph *)NULL) { + if (glyph == nullptr) { nout << "No definition in font for character " << code << ".\n"; return; } diff --git a/pandatool/src/egg-mkfont/eggMakeFont.h b/pandatool/src/egg-mkfont/eggMakeFont.h index 20bd99f01f..3df12af6fa 100644 --- a/pandatool/src/egg-mkfont/eggMakeFont.h +++ b/pandatool/src/egg-mkfont/eggMakeFont.h @@ -46,7 +46,7 @@ public: void run(); private: - static bool dispatch_range(const string &, const string &arg, void *var); + static bool dispatch_range(const std::string &, const std::string &arg, void *var); EggVertex *make_vertex(const LPoint2d &xy); void add_character(int code); @@ -55,7 +55,7 @@ private: EggTexture *make_tref(PNMTextGlyph *glyph, int character); void add_extra_glyphs(const Filename &extra_filename); void r_add_extra_glyphs(EggGroupNode *egg_group); - static bool is_numeric(const string &str); + static bool is_numeric(const std::string &str); private: @@ -79,8 +79,8 @@ private: double _palettize_scale_factor; Filename _input_font_filename; int _face_index; - string _output_glyph_pattern; - string _output_palette_pattern; + std::string _output_glyph_pattern; + std::string _output_palette_pattern; PNMTextMaker *_text_maker; diff --git a/pandatool/src/egg-mkfont/rangeDescription.I b/pandatool/src/egg-mkfont/rangeDescription.I index b19912d303..39a20162f5 100644 --- a/pandatool/src/egg-mkfont/rangeDescription.I +++ b/pandatool/src/egg-mkfont/rangeDescription.I @@ -55,7 +55,7 @@ Range(int from_code, int to_code) : { } -INLINE ostream &operator << (ostream &out, const RangeDescription &range) { +INLINE std::ostream &operator << (std::ostream &out, const RangeDescription &range) { range.output(out); return out; } diff --git a/pandatool/src/egg-mkfont/rangeDescription.cxx b/pandatool/src/egg-mkfont/rangeDescription.cxx index bedfc086ea..2833f53359 100644 --- a/pandatool/src/egg-mkfont/rangeDescription.cxx +++ b/pandatool/src/egg-mkfont/rangeDescription.cxx @@ -15,6 +15,8 @@ #include "string_utils.h" #include "pnotify.h" +using std::string; + /** * */ @@ -71,7 +73,7 @@ parse_parameter(const string ¶m) { * */ void RangeDescription:: -output(ostream &out) const { +output(std::ostream &out) const { bool first_time = true; RangeList::const_iterator ri; for (ri = _range_list.begin(); ri != _range_list.end(); ++ri) { diff --git a/pandatool/src/egg-mkfont/rangeDescription.h b/pandatool/src/egg-mkfont/rangeDescription.h index d1e26b573d..25119cb16f 100644 --- a/pandatool/src/egg-mkfont/rangeDescription.h +++ b/pandatool/src/egg-mkfont/rangeDescription.h @@ -25,17 +25,17 @@ class RangeDescription { public: RangeDescription(); - bool parse_parameter(const string ¶m); + bool parse_parameter(const std::string ¶m); INLINE void add_singleton(int code); INLINE void add_range(int from_code, int to_code); INLINE bool is_empty() const; - void output(ostream &out) const; + void output(std::ostream &out) const; private: - bool parse_word(const string &word); - bool parse_code(const string &word, int &code); - bool parse_bracket(const string &str); + bool parse_word(const std::string &word); + bool parse_code(const std::string &word, int &code); + bool parse_bracket(const std::string &str); private: class Range { @@ -53,7 +53,7 @@ private: friend class RangeIterator; }; -INLINE ostream &operator << (ostream &out, const RangeDescription &range); +INLINE std::ostream &operator << (std::ostream &out, const RangeDescription &range); #include "rangeDescription.I" diff --git a/pandatool/src/egg-optchar/eggOptchar.cxx b/pandatool/src/egg-optchar/eggOptchar.cxx index bc1d3058b3..182b657968 100644 --- a/pandatool/src/egg-optchar/eggOptchar.cxx +++ b/pandatool/src/egg-optchar/eggOptchar.cxx @@ -34,6 +34,10 @@ #include +using std::cout; +using std::setw; +using std::string; + /** * */ @@ -74,19 +78,19 @@ EggOptchar() { ("keep", "joint[,joint...]", 0, "Keep the named joints (or sliders) in the character, even if they do " "not appear to be needed by the animation.", - &EggOptchar::dispatch_vector_string_comma, NULL, &_keep_components); + &EggOptchar::dispatch_vector_string_comma, nullptr, &_keep_components); add_option ("drop", "joint[,joint...]", 0, "Removes the named joints or sliders, even if they appear to be needed.", - &EggOptchar::dispatch_vector_string_comma, NULL, &_drop_components); + &EggOptchar::dispatch_vector_string_comma, nullptr, &_drop_components); add_option ("expose", "joint[,joint...]", 0, "Expose the named joints by flagging them with a DCS attribute, so " "each one can be found in the scene graph when the character is loaded, " "and objects can be parented to it. This implies -keep.", - &EggOptchar::dispatch_vector_string_comma, NULL, &_expose_components); + &EggOptchar::dispatch_vector_string_comma, nullptr, &_expose_components); add_option ("suppress", "joint[,joint...]", 0, @@ -95,7 +99,7 @@ EggOptchar() { "rigid geometry. The default is to create an implicit node for any " "joint that contains rigid geometry, to take advantage of display " "list and/or vertex buffer caching. This does not imply -keep.", - &EggOptchar::dispatch_vector_string_comma, NULL, &_suppress_components); + &EggOptchar::dispatch_vector_string_comma, nullptr, &_suppress_components); add_option ("flag", "node[,node...][=name]", 0, @@ -107,7 +111,7 @@ EggOptchar() { "joints; the revealed node can be hidden or its attributes changed " "at runtime, but it will be animated by its vertices, not the node, so " "objects parented to this node will not inherit its animation.", - &EggOptchar::dispatch_flag_groups, NULL, &_flag_groups); + &EggOptchar::dispatch_flag_groups, nullptr, &_flag_groups); add_option ("defpose", "anim.egg,frame", 0, @@ -117,7 +121,7 @@ EggOptchar() { "pose will be held by the model in " "the absence of any animation, and need not be the same " "pose in which the model was originally skinned.", - &EggOptchar::dispatch_string, NULL, &_defpose); + &EggOptchar::dispatch_string, nullptr, &_defpose); add_option ("preload", "", 0, @@ -132,7 +136,7 @@ EggOptchar() { "a subset of the component letters hprxyzijkabc is included, the " "operation is restricted to just those components; otherwise the " "entire transform is cleared.", - &EggOptchar::dispatch_name_components, NULL, &_zero_channels); + &EggOptchar::dispatch_name_components, nullptr, &_zero_channels); add_option ("keepall", "", 0, @@ -146,18 +150,18 @@ EggOptchar() { "\"-p joint,\" to reparent a joint to the root. The joint transform " "is recomputed appropriately under its new parent so that the animation " "is not affected (the effect is similar to NodePath::wrt_reparent_to).", - &EggOptchar::dispatch_vector_string_pair, NULL, &_reparent_joints); + &EggOptchar::dispatch_vector_string_pair, nullptr, &_reparent_joints); add_option ("new", "joint,source", 0, "Creates a new joint under the named parent joint. The new " "joint will inherit the same net transform as its parent.", - &EggOptchar::dispatch_vector_string_pair, NULL, &_new_joints); + &EggOptchar::dispatch_vector_string_pair, nullptr, &_new_joints); add_option ("rename", "joint,newjoint", 0, "Renames the indicated joint, if present, to the given name.", - &EggOptchar::dispatch_vector_string_pair, NULL, &_rename_joints); + &EggOptchar::dispatch_vector_string_pair, nullptr, &_rename_joints); if (FFTCompressor::is_compression_available()) { add_option @@ -182,7 +186,7 @@ EggOptchar() { "benefit for eliminating small differences in joint memberships " "between neighboring vertices. The default is 0.01; specifying " "0 means to preserve the original values.", - &EggOptchar::dispatch_double, NULL, &_vref_quantum); + &EggOptchar::dispatch_double, nullptr, &_vref_quantum); add_option ("qa", "quantum[,hprxyzijkabc]", 0, @@ -193,12 +197,12 @@ EggOptchar() { "animation. However, sometimes it is a useful tool for animation " "analysis and comparison. This option may be repeated several times " "to quantize different channels by a different amount.", - &EggOptchar::dispatch_double_components, NULL, &_quantize_anims); + &EggOptchar::dispatch_double_components, nullptr, &_quantize_anims); add_option ("dart", "[default, sync, nosync, or structured]", 0, "change the dart value in the given eggs", - &EggOptchar::dispatch_string, NULL, &_dart_type); + &EggOptchar::dispatch_string, nullptr, &_dart_type); _optimal_hierarchy = false; @@ -381,7 +385,7 @@ dispatch_name_components(const string &opt, const string &arg, void *var) { sp._b = matrix_component_letters; } else { for (string::const_iterator si = sp._b.begin(); si != sp._b.end(); ++si) { - if (strchr(matrix_component_letters, *si) == NULL) { + if (strchr(matrix_component_letters, *si) == nullptr) { nout << "Not a standard matrix component: \"" << *si << "\"\n" << "-" << opt << " requires a joint name followed by a set " << "of component names. The standard component names are \"" @@ -436,7 +440,7 @@ dispatch_double_components(const string &opt, const string &arg, void *var) { sp._b = matrix_component_letters; } else { for (string::const_iterator si = sp._b.begin(); si != sp._b.end(); ++si) { - if (strchr(matrix_component_letters, *si) == NULL) { + if (strchr(matrix_component_letters, *si) == nullptr) { nout << "Not a standard matrix component: \"" << *si << "\"\n" << "-" << opt << " requires a joint name followed by a set " << "of component names. The standard component names are \"" @@ -535,11 +539,11 @@ determine_removed_components() { nout << char_data->get_name() << " has " << num_components << " components.\n"; for (int i = 0; i < num_components; i++) { EggComponentData *comp_data = char_data->get_component(i); - nassertv(comp_data != (EggComponentData *)NULL); + nassertv(comp_data != nullptr); EggOptcharUserData *user_data = DCAST(EggOptcharUserData, comp_data->get_user_data()); - nassertv(user_data != (EggOptcharUserData *)NULL); + nassertv(user_data != nullptr); const string &name = comp_data->get_name(); if (suppress_names.find(name) != suppress_names.end()) { @@ -636,7 +640,7 @@ move_vertices() { joint_data->move_vertices_to(best_joint); // Now we can't remove the joint. - if (best_joint != (EggJointData *)NULL) { + if (best_joint != nullptr) { EggOptcharUserData *best_user_data = DCAST(EggOptcharUserData, best_joint->get_user_data()); best_user_data->_flags &= ~(EggOptcharUserData::F_empty | EggOptcharUserData::F_remove); @@ -673,7 +677,7 @@ process_joints() { if ((user_data->_flags & EggOptcharUserData::F_remove) != 0) { // This joint will be removed, so reparent it to nothing. - joint_data->reparent_to((EggJointData *)NULL); + joint_data->reparent_to(nullptr); // Determine what kind of node it is we're removing, for the user's // information. @@ -740,7 +744,7 @@ find_best_parent(EggJointData *joint_data) const { if ((user_data->_flags & EggOptcharUserData::F_remove) != 0) { // Keep going. - if (joint_data->get_parent() != (EggJointData *)NULL) { + if (joint_data->get_parent() != nullptr) { return find_best_parent(joint_data->get_parent()); } } @@ -755,8 +759,8 @@ find_best_parent(EggJointData *joint_data) const { */ EggJointData *EggOptchar:: find_best_vertex_joint(EggJointData *joint_data) const { - if (joint_data == (EggJointData *)NULL) { - return NULL; + if (joint_data == nullptr) { + return nullptr; } EggOptcharUserData *user_data = @@ -794,11 +798,11 @@ apply_user_reparents() { node_b = char_data->find_joint(p._b); } - if (node_b == (EggJointData *)NULL) { + if (node_b == nullptr) { nout << "No joint named " << p._b << " in " << char_data->get_name() << ".\n"; - } else if (node_a != (EggJointData *)NULL) { + } else if (node_a != nullptr) { nout << "Joint " << p._a << " already exists in " << char_data->get_name() << ".\n"; @@ -823,10 +827,10 @@ apply_user_reparents() { node_b = char_data->find_joint(p._b); } - if (node_b == (EggJointData *)NULL) { + if (node_b == nullptr) { nout << "No joint named " << p._b << " in " << char_data->get_name() << ".\n"; - } else if (node_a == (EggJointData *)NULL) { + } else if (node_a == nullptr) { nout << "No joint named " << p._a << " in " << char_data->get_name() << ".\n"; } else { @@ -869,7 +873,7 @@ zero_channels() { EggCharacterData *char_data = _collection->get_character(ci); EggJointData *joint_data = char_data->find_joint(p._a); - if (joint_data == (EggJointData *)NULL) { + if (joint_data == nullptr) { nout << "No joint named " << p._a << " in " << char_data->get_name() << ".\n"; } else { @@ -900,7 +904,7 @@ quantize_channels() { EggCharacterData *char_data = _collection->get_character(ci); EggJointData *joint_data = char_data->get_root_joint(); - if (joint_data != (EggJointData *)NULL) { + if (joint_data != nullptr) { joint_data->quantize_channels(p._b, p._a); did_anything = true; } @@ -1314,7 +1318,7 @@ rename_joints() { for (ci = 0; ci < num_characters; ++ci) { EggCharacterData *char_data = _collection->get_character(ci); EggJointData *joint = char_data->find_joint(sp._a); - if (joint != (EggJointData *)NULL) { + if (joint != nullptr) { nout << "Renaming joint " << sp._a << " to " << sp._b << "\n"; joint->set_name(sp._b); diff --git a/pandatool/src/egg-optchar/eggOptchar.h b/pandatool/src/egg-optchar/eggOptchar.h index 5d461a3442..30ea4cddae 100644 --- a/pandatool/src/egg-optchar/eggOptchar.h +++ b/pandatool/src/egg-optchar/eggOptchar.h @@ -44,10 +44,10 @@ protected: virtual bool handle_args(Args &args); private: - static bool dispatch_vector_string_pair(const string &opt, const string &arg, void *var); - static bool dispatch_name_components(const string &opt, const string &arg, void *var); - static bool dispatch_double_components(const string &opt, const string &arg, void *var); - static bool dispatch_flag_groups(const string &opt, const string &arg, void *var); + static bool dispatch_vector_string_pair(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_name_components(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_double_components(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_flag_groups(const std::string &opt, const std::string &arg, void *var); void determine_removed_components(); void move_vertices(); @@ -73,8 +73,8 @@ private: void do_flag_groups(EggGroupNode *egg_group); void rename_joints(); - void rename_primitives(EggGroupNode *egg_group, const string &name); - void change_dart_type(EggGroupNode *egg_group, const string &new_dart_type); + void rename_primitives(EggGroupNode *egg_group, const std::string &name); + void change_dart_type(EggGroupNode *egg_group, const std::string &new_dart_type); void do_preload(); void do_defpose(); @@ -86,8 +86,8 @@ private: class StringPair { public: - string _a; - string _b; + std::string _a; + std::string _b; }; typedef pvector StringPairs; StringPairs _new_joints; @@ -100,12 +100,12 @@ private: vector_string _expose_components; vector_string _suppress_components; - string _dart_type; + std::string _dart_type; class DoubleString { public: double _a; - string _b; + std::string _b; }; typedef pvector DoubleStrings; DoubleStrings _quantize_anims; @@ -115,12 +115,12 @@ private: class FlagGroupsEntry { public: Globs _groups; - string _name; + std::string _name; }; typedef pvector FlagGroups; FlagGroups _flag_groups; - string _defpose; + std::string _defpose; bool _optimal_hierarchy; double _vref_quantum; diff --git a/pandatool/src/egg-palettize/eggPalettize.cxx b/pandatool/src/egg-palettize/eggPalettize.cxx index 200b62e798..afa7fa00b7 100644 --- a/pandatool/src/egg-palettize/eggPalettize.cxx +++ b/pandatool/src/egg-palettize/eggPalettize.cxx @@ -571,7 +571,7 @@ run() { // instead. Notify *notify = Notify::ptr(); NotifyCategory *loader_cat = notify->get_category(":loader"); - if (loader_cat != (NotifyCategory *)NULL && + if (loader_cat != nullptr && loader_cat->get_severity() == NS_info) { loader_cat->set_severity(NS_warning); } @@ -639,7 +639,7 @@ run() { } TypedWritable *obj = state_file.read_object(); - if (obj == (TypedWritable *)NULL || !state_file.resolve()) { + if (obj == nullptr || !state_file.resolve()) { nout << FilenameUnifier::make_user_filename(state_filename) << " exists, but appears to be corrupt. Perhaps you " << "should remove it so a new one can be created.\n"; @@ -696,12 +696,12 @@ run() { bool okflag = true; if (_got_txa_script) { - istringstream txa_script(_txa_script); + std::istringstream txa_script(_txa_script); pal->read_txa_file(txa_script, "command line"); } else { _txa_filename.set_text(); - ifstream txa_file; + std::ifstream txa_file; if (!_txa_filename.open_read(txa_file)) { nout << "Unable to open " << _txa_filename << "\n"; exit(1); @@ -757,13 +757,13 @@ run() { // And process the egg files named for addition. bool all_eggs_valid = true; - string egg_comment = get_exec_command(); + std::string egg_comment = get_exec_command(); Eggs::const_iterator ei; for (ei = _eggs.begin(); ei != _eggs.end(); ++ei) { EggData *egg_data = (*ei); Filename source_filename = egg_data->get_egg_filename(); Filename dest_filename = get_output_filename(source_filename); - string name = source_filename.get_basename(); + std::string name = source_filename.get_basename(); EggFile *egg_file = pal->get_egg_file(name); if (!egg_file->from_command_line(egg_data, source_filename, dest_filename, @@ -834,7 +834,7 @@ run() { // state file into place. We do this in case the user interrupts us (or // we core dump) before we're done; that way we won't leave the state file // incompletely written. - string dirname = state_filename.get_dirname(); + std::string dirname = state_filename.get_dirname(); if (dirname.empty()) { dirname = "."; } diff --git a/pandatool/src/egg-palettize/eggPalettize.h b/pandatool/src/egg-palettize/eggPalettize.h index a0c6208d31..d30a9d4fb6 100644 --- a/pandatool/src/egg-palettize/eggPalettize.h +++ b/pandatool/src/egg-palettize/eggPalettize.h @@ -37,19 +37,19 @@ public: bool _got_txa_filename; Filename _txa_filename; bool _got_txa_script; - string _txa_script; + std::string _txa_script; bool _nodb; - string _generated_image_pattern; + std::string _generated_image_pattern; bool _got_generated_image_pattern; - string _map_dirname; + std::string _map_dirname; bool _got_map_dirname; Filename _shadow_dirname; bool _got_shadow_dirname; Filename _rel_dirname; bool _got_rel_dirname; - string _default_groupname; + std::string _default_groupname; bool _got_default_groupname; - string _default_groupdir; + std::string _default_groupdir; bool _got_default_groupdir; private: @@ -62,7 +62,6 @@ private: bool _omitall; bool _redo_all; bool _redo_eggs; - bool _dont_lock_txa; bool _describe_input_file; bool _remove_eggs; diff --git a/pandatool/src/egg-palettize/txaFileFilter.cxx b/pandatool/src/egg-palettize/txaFileFilter.cxx index 5c673c51a1..f8c20cfb0c 100644 --- a/pandatool/src/egg-palettize/txaFileFilter.cxx +++ b/pandatool/src/egg-palettize/txaFileFilter.cxx @@ -52,7 +52,7 @@ post_load(Texture *tex) { } TextureImage tex_image; - string name = tex->get_filename().get_basename_wo_extension(); + std::string name = tex->get_filename().get_basename_wo_extension(); tex_image.set_name(name); SourceTextureImage *source = tex_image.get_source @@ -111,7 +111,7 @@ read_txa_file() { // We need to create a global Palettizer object to hold some of the global // properties that may be specified in a txa file. - if (pal == (Palettizer *)NULL) { + if (pal == nullptr) { pal = new Palettizer; } @@ -131,8 +131,8 @@ read_txa_file() { << "Filename " << filename << " not found.\n"; } else { filename.set_text(); - istream *ifile = vfs->open_read_file(filename, true); - if (ifile == (istream *)NULL) { + std::istream *ifile = vfs->open_read_file(filename, true); + if (ifile == nullptr) { txafile_cat.warning() << "Filename " << filename << " cannot be read.\n"; } else { diff --git a/pandatool/src/egg-qtess/eggQtess.cxx b/pandatool/src/egg-qtess/eggQtess.cxx index 21bc6317fb..37473557bf 100644 --- a/pandatool/src/egg-qtess/eggQtess.cxx +++ b/pandatool/src/egg-qtess/eggQtess.cxx @@ -37,14 +37,14 @@ EggQtess() { ("f", "filename", 0, "Read the indicated parameter file. Type egg-qtess -H " "to print a description of the parameter file format.", - &EggQtess::dispatch_filename, NULL, &_qtess_filename); + &EggQtess::dispatch_filename, nullptr, &_qtess_filename); add_option ("up", "subdiv", 0, "Specify a uniform subdivision per patch (isoparam). Each NURBS " "surface is made up of N x M patches, each of which is divided " "into subdiv x subdiv quads. A fractional number is allowed.", - &EggQtess::dispatch_double, NULL, &_uniform_per_isoparam); + &EggQtess::dispatch_double, nullptr, &_uniform_per_isoparam); add_option ("us", "subdiv", 0, @@ -52,7 +52,7 @@ EggQtess() { "surface is subdivided into subdiv x subdiv quads, regardless " "of the number of isoparams it has. A fractional number is " "meaningless.", - &EggQtess::dispatch_int, NULL, &_uniform_per_surface); + &EggQtess::dispatch_int, nullptr, &_uniform_per_surface); add_option ("t", "tris", 0, @@ -60,7 +60,7 @@ EggQtess() { "is the total number of triangles for the entire egg file, " "including those surfaces that have already been given an " "explicit tessellation by a parameter file.", - &EggQtess::dispatch_int, NULL, &_total_tris); + &EggQtess::dispatch_int, nullptr, &_total_tris); add_option ("ap", "", 0, @@ -83,7 +83,7 @@ EggQtess() { "-ad. A value of 0 forces placement by curvature only; a very " "large value (like 1000) forces placement by size only. The " "default is 5.0.", - &EggQtess::dispatch_double, NULL, &QtessGlobals::_curvature_ratio); + &EggQtess::dispatch_double, nullptr, &QtessGlobals::_curvature_ratio); add_option ("e", "", 0, @@ -155,9 +155,9 @@ run() { if (_total_tris != 0) { // Whatever number of triangles we have unaccounted for, assign to the // default bucket. - int extra_tris = max(0, _total_tris - num_tris); + int extra_tris = std::max(0, _total_tris - num_tris); if (read_qtess && default_entry.get_num_surfaces() != 0) { - cerr << extra_tris << " triangles unaccounted for.\n"; + std::cerr << extra_tris << " triangles unaccounted for.\n"; } default_entry.set_num_tris(extra_tris); @@ -180,13 +180,13 @@ run() { int tris = 0; - ostream &out = get_output(); + std::ostream &out = get_output(); Surfaces::const_iterator si; for (si = _surfaces.begin(); si != _surfaces.end(); ++si) { tris += (*si)->write_qtess_parameter(out); } - cerr << tris << " tris generated.\n"; + std::cerr << tris << " tris generated.\n"; } else { @@ -197,7 +197,7 @@ run() { tris += (*si)->tesselate(); } - cerr << tris << " tris generated.\n"; + std::cerr << tris << " tris generated.\n"; // Clear out the surfaces list before removing the vertices, since each // surface is holding reference counts to the previously-used vertices. diff --git a/pandatool/src/egg-qtess/isoPlacer.cxx b/pandatool/src/egg-qtess/isoPlacer.cxx index 25c7a38b0a..fda96904e3 100644 --- a/pandatool/src/egg-qtess/isoPlacer.cxx +++ b/pandatool/src/egg-qtess/isoPlacer.cxx @@ -82,7 +82,7 @@ get_scores(int subdiv, int across, double ratio, // non-equal points. double d = v1.dot(v2); - _cscore[i] += acos(max(min(d, 1.0), -1.0)); + _cscore[i] += acos(std::max(std::min(d, 1.0), -1.0)); } } } diff --git a/pandatool/src/egg-qtess/qtessInputEntry.I b/pandatool/src/egg-qtess/qtessInputEntry.I index 5c8adde257..d8ab6de61e 100644 --- a/pandatool/src/egg-qtess/qtessInputEntry.I +++ b/pandatool/src/egg-qtess/qtessInputEntry.I @@ -23,7 +23,7 @@ QtessInputEntry(const QtessInputEntry ©) { * */ INLINE void QtessInputEntry:: -add_node_name(const string &name) { +add_node_name(const std::string &name) { _node_names.push_back(GlobPattern(name)); } @@ -42,7 +42,7 @@ set_importance(double i) { INLINE void QtessInputEntry:: set_match_uu() { _type = T_match_uu; - _constrain_u = NULL; + _constrain_u = nullptr; } /** @@ -51,7 +51,7 @@ set_match_uu() { INLINE void QtessInputEntry:: set_match_vv() { _type = T_match_vv; - _constrain_v = NULL; + _constrain_v = nullptr; } /** @@ -60,7 +60,7 @@ set_match_vv() { INLINE void QtessInputEntry:: set_match_uv() { _type = T_match_uv; - _constrain_u = NULL; + _constrain_u = nullptr; } /** @@ -69,7 +69,7 @@ set_match_uv() { INLINE void QtessInputEntry:: set_match_vu() { _type = T_match_vu; - _constrain_v = NULL; + _constrain_v = nullptr; } /** @@ -120,7 +120,7 @@ set_num_tris(int nt) { */ INLINE void QtessInputEntry:: set_uv(int u, int v) { - set_uv(u, v, NULL, 0); + set_uv(u, v, nullptr, 0); } /** @@ -150,7 +150,7 @@ get_num_surfaces() const { } -INLINE ostream &operator << (ostream &out, const QtessInputEntry &entry) { +INLINE std::ostream &operator << (std::ostream &out, const QtessInputEntry &entry) { entry.output(out); return out; } diff --git a/pandatool/src/egg-qtess/qtessInputEntry.cxx b/pandatool/src/egg-qtess/qtessInputEntry.cxx index e7547e359e..66df4c8813 100644 --- a/pandatool/src/egg-qtess/qtessInputEntry.cxx +++ b/pandatool/src/egg-qtess/qtessInputEntry.cxx @@ -21,6 +21,8 @@ #include #include +using std::string; + /** * */ @@ -222,7 +224,7 @@ match(QtessSurface *surface) { // Similarly for type "matchUU". This indicates that all the surfaces // that match this one must all share the U-tesselation with whichever // surface first matched against the first node name. - if (nni == _node_names.begin() && _constrain_u==NULL) { + if (nni == _node_names.begin() && _constrain_u==nullptr) { // This is the lucky surface that dominates! _constrain_u = surface; } else { @@ -237,7 +239,7 @@ match(QtessSurface *surface) { case T_match_vv: case T_match_vu: // Ditto for "matchVV". - if (nni == _node_names.begin() && _constrain_v==NULL) { + if (nni == _node_names.begin() && _constrain_v==nullptr) { // This is the lucky surface that dominates! _constrain_v = surface; } else { @@ -354,7 +356,7 @@ count_tris(double tri_factor, int attempts) { * user control. */ void QtessInputEntry:: -output_extra(ostream &out, const pvector &iso, char axis) { +output_extra(std::ostream &out, const pvector &iso, char axis) { pvector::const_iterator di; int expect = 0; for (di = iso.begin(); di != iso.end(); ++di) { @@ -376,7 +378,7 @@ output_extra(ostream &out, const pvector &iso, char axis) { * */ void QtessInputEntry:: -output(ostream &out) const { +output(std::ostream &out) const { NodeNames::const_iterator nni; for (nni = _node_names.begin(); nni != _node_names.end(); @@ -458,6 +460,6 @@ output(ostream &out) const { * */ void QtessInputEntry:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << (*this) << "\n"; } diff --git a/pandatool/src/egg-qtess/qtessInputEntry.h b/pandatool/src/egg-qtess/qtessInputEntry.h index 170d0fadf3..bffcca0d4a 100644 --- a/pandatool/src/egg-qtess/qtessInputEntry.h +++ b/pandatool/src/egg-qtess/qtessInputEntry.h @@ -32,11 +32,11 @@ public: T_min_u, T_min_v }; - QtessInputEntry(const string &name = string()); + QtessInputEntry(const std::string &name = std::string()); INLINE QtessInputEntry(const QtessInputEntry ©); void operator = (const QtessInputEntry ©); - INLINE void add_node_name(const string &name); + INLINE void add_node_name(const std::string &name); INLINE void set_importance(double i); INLINE void set_match_uu(); INLINE void set_match_vv(); @@ -48,7 +48,7 @@ public: INLINE void set_omit(); INLINE void set_num_tris(int nt); INLINE void set_uv(int u, int v); - void set_uv(int u, int v, const string params[], int num_params); + void set_uv(int u, int v, const std::string params[], int num_params); INLINE void set_per_isoparam(double pi); INLINE void set_per_score(double pi); void add_extra_u_isoparam(double u); @@ -58,9 +58,9 @@ public: INLINE int get_num_surfaces() const; int count_tris(double tri_factor = 1.0, int attempts = 0); - static void output_extra(ostream &out, const pvector &iso, char axis); - void output(ostream &out) const; - void write(ostream &out, int indent_level) const; + static void output_extra(std::ostream &out, const pvector &iso, char axis); + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level) const; bool _auto_place, _auto_distribute; double _curvature_ratio; @@ -83,7 +83,7 @@ private: double _num_patches; }; -INLINE ostream &operator << (ostream &out, const QtessInputEntry &entry); +INLINE std::ostream &operator << (std::ostream &out, const QtessInputEntry &entry); #include "qtessInputEntry.I" diff --git a/pandatool/src/egg-qtess/qtessInputFile.cxx b/pandatool/src/egg-qtess/qtessInputFile.cxx index 647f0b8471..180a2e9547 100644 --- a/pandatool/src/egg-qtess/qtessInputFile.cxx +++ b/pandatool/src/egg-qtess/qtessInputFile.cxx @@ -15,6 +15,8 @@ #include "config_egg_qtess.h" #include "string_utils.h" +using std::string; + /** * */ @@ -30,7 +32,7 @@ read(const Filename &filename) { _filename = Filename::text_filename(filename); _entries.clear(); - ifstream input; + std::ifstream input; if (!_filename.open_read(input)) { qtess_cat.error() << "Unable to open input file " << _filename << "\n"; @@ -41,7 +43,7 @@ read(const Filename &filename) { int line_number = 0; string line; - while (getline(input, line)) { + while (std::getline(input, line)) { line_number++; // Eliminate comments. We have to scan the line repeatedly until we find @@ -306,7 +308,7 @@ count_tris() { * */ void QtessInputFile:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { Entries::const_iterator ei; for (ei = _entries.begin(); ei != _entries.end(); ++ei) { (*ei).write(out, indent_level); diff --git a/pandatool/src/egg-qtess/qtessInputFile.h b/pandatool/src/egg-qtess/qtessInputFile.h index 7b015b46ac..d0e6b62464 100644 --- a/pandatool/src/egg-qtess/qtessInputFile.h +++ b/pandatool/src/egg-qtess/qtessInputFile.h @@ -37,7 +37,7 @@ public: QtessInputEntry::Type match(QtessSurface *surface); int count_tris(); - void write(ostream &out, int indent_level = 0) const; + void write(std::ostream &out, int indent_level = 0) const; private: void add_default_entry(); diff --git a/pandatool/src/egg-qtess/qtessSurface.I b/pandatool/src/egg-qtess/qtessSurface.I index cc53d0f403..d65f82c32c 100644 --- a/pandatool/src/egg-qtess/qtessSurface.I +++ b/pandatool/src/egg-qtess/qtessSurface.I @@ -14,7 +14,7 @@ /** * */ -INLINE const string &QtessSurface:: +INLINE const std::string &QtessSurface:: get_name() const { return _egg_surface->get_name(); } @@ -24,7 +24,7 @@ get_name() const { */ INLINE bool QtessSurface:: is_valid() const { - return (_nurbs != (NurbsSurfaceEvaluator *)NULL); + return (_nurbs != nullptr); } /** @@ -126,7 +126,7 @@ get_joint_membership_index(EggGroup *joint) { * Dxyz morph offset should be stored. */ INLINE int QtessSurface:: -get_dxyz_index(const string &morph_name) { +get_dxyz_index(const std::string &morph_name) { MorphTable::iterator mti = _dxyz_table.find(morph_name); if (mti != _dxyz_table.end()) { return (*mti).second; @@ -142,7 +142,7 @@ get_dxyz_index(const string &morph_name) { * Drgba morph offset should be stored. */ INLINE int QtessSurface:: -get_drgba_index(const string &morph_name) { +get_drgba_index(const std::string &morph_name) { MorphTable::iterator mti = _drgba_table.find(morph_name); if (mti != _drgba_table.end()) { return (*mti).second; diff --git a/pandatool/src/egg-qtess/qtessSurface.cxx b/pandatool/src/egg-qtess/qtessSurface.cxx index c0bfc175f9..d7ccebe76f 100644 --- a/pandatool/src/egg-qtess/qtessSurface.cxx +++ b/pandatool/src/egg-qtess/qtessSurface.cxx @@ -23,6 +23,9 @@ #include "pset.h" #include "pmap.h" +using std::max; +using std::string; + /** * */ @@ -38,7 +41,7 @@ QtessSurface(EggNurbsSurface *egg_surface) : _importance = 1.0; _importance2 = 1.0; - _match_u = _match_v = NULL; + _match_u = _match_v = nullptr; _tess_u = _tess_v = 0; _got_scores = false; @@ -53,7 +56,7 @@ QtessSurface(EggNurbsSurface *egg_surface) : _min_v = 3; } - if (_nurbs == (NurbsSurfaceEvaluator *)NULL) { + if (_nurbs == nullptr) { _num_u = _num_v = 0; } else { @@ -86,7 +89,7 @@ QtessSurface(EggNurbsSurface *egg_surface) : */ double QtessSurface:: get_score(double ratio) { - if (_nurbs == (NurbsSurfaceEvaluator *)NULL) { + if (_nurbs == nullptr) { return 0.0; } @@ -115,13 +118,13 @@ tesselate() { PT(EggGroup) group = do_uniform_tesselate(tris); PT(EggNode) new_node = group.p(); - if (new_node == (EggNode *)NULL) { + if (new_node == nullptr) { new_node = new EggComment(_egg_surface->get_name(), "Omitted NURBS surface."); tris = 0; } EggGroupNode *parent = _egg_surface->get_parent(); - nassertr(parent != (EggGroupNode *)NULL, 0); + nassertr(parent != nullptr, 0); parent->remove_child(_egg_surface); parent->add_child(new_node); @@ -133,7 +136,7 @@ tesselate() { * should be tesselated uniformly. Returns the number of tris. */ int QtessSurface:: -write_qtess_parameter(ostream &out) { +write_qtess_parameter(std::ostream &out) { apply_match(); if (_tess_u == 0 || _tess_v == 0) { @@ -301,9 +304,9 @@ record_vertex_extras() { */ void QtessSurface:: apply_match() { - if (_match_u != NULL) { + if (_match_u != nullptr) { QtessSurface *m = *_match_u; - if (m == NULL) { + if (m == nullptr) { qtess_cat.warning() << "No surface to match " << get_name() << " to in U.\n"; } else { @@ -322,9 +325,9 @@ apply_match() { } } - if (_match_v != NULL) { + if (_match_v != nullptr) { QtessSurface *m = *_match_v; - if (m == NULL) { + if (m == nullptr) { qtess_cat.warning() << "No surface to match " << get_name() << " in V.\n"; } else { @@ -358,7 +361,7 @@ do_uniform_tesselate(int &tris) const { qtess_cat.debug() << get_name() << " : omit\n"; } - return NULL; + return nullptr; } PT(EggGroup) group = new EggGroup(_egg_surface->get_name()); @@ -416,7 +419,7 @@ do_uniform_tesselate(int &tris) const { n_collection[egg_vertex->get_pos3()].insert(egg_vertex); } } - nassertr((int)new_verts.size() == num_verts, NULL); + nassertr((int)new_verts.size() == num_verts, nullptr); // Now create a bunch of quads. for (vi = 1; vi < num_v; vi++) { @@ -460,7 +463,7 @@ do_uniform_tesselate(int &tris) const { pri != egg_vertex->pref_end(); ++pri) { EggPrimitive *egg_primitive = (*pri); - nassertr(egg_primitive->has_normal(), NULL); + nassertr(egg_primitive->has_normal(), nullptr); normal += egg_primitive->get_normal(); num_polys++; } diff --git a/pandatool/src/egg-qtess/qtessSurface.h b/pandatool/src/egg-qtess/qtessSurface.h index f93c57c52e..fc3720e524 100644 --- a/pandatool/src/egg-qtess/qtessSurface.h +++ b/pandatool/src/egg-qtess/qtessSurface.h @@ -33,7 +33,7 @@ class QtessSurface : public ReferenceCount { public: QtessSurface(EggNurbsSurface *egg_surface); - INLINE const string &get_name() const; + INLINE const std::string &get_name() const; INLINE bool is_valid() const; INLINE void set_importance(double importance2); @@ -48,7 +48,7 @@ public: double get_score(double ratio); int tesselate(); - int write_qtess_parameter(ostream &out); + int write_qtess_parameter(std::ostream &out); void omit(); void tesselate_uv(int u, int v, bool autoplace, double ratio); void tesselate_specific(const pvector &u_list, @@ -60,8 +60,8 @@ public: private: void record_vertex_extras(); INLINE int get_joint_membership_index(EggGroup *joint); - INLINE int get_dxyz_index(const string &morph_name); - INLINE int get_drgba_index(const string &morph_name); + INLINE int get_dxyz_index(const std::string &morph_name); + INLINE int get_drgba_index(const std::string &morph_name); void apply_match(); PT(EggGroup) do_uniform_tesselate(int &tris) const; @@ -75,9 +75,9 @@ private: // Mapping arbitrary attributes to integer extended dimension values, so we // can hang arbitrary data in the extra dimensional space of the surface. int _next_d; - typedef map JointTable; + typedef std::map JointTable; JointTable _joint_table; - typedef map MorphTable; + typedef std::map MorphTable; MorphTable _dxyz_table; MorphTable _drgba_table; diff --git a/pandatool/src/eggbase/eggBase.cxx b/pandatool/src/eggbase/eggBase.cxx index 7fa0889610..83d07a0a6a 100644 --- a/pandatool/src/eggbase/eggBase.cxx +++ b/pandatool/src/eggbase/eggBase.cxx @@ -20,6 +20,8 @@ #include "dcast.h" #include "string_utils.h" +using std::string; + /** * */ @@ -63,24 +65,24 @@ add_normals_options() { add_option ("no", "", 48, "Strip all normals.", - &EggBase::dispatch_normals, NULL, &strip); + &EggBase::dispatch_normals, nullptr, &strip); add_option ("np", "", 48, "Strip existing normals and redefine polygon normals.", - &EggBase::dispatch_normals, NULL, &polygon); + &EggBase::dispatch_normals, nullptr, &polygon); add_option ("nv", "threshold", 48, "Strip existing normals and redefine vertex normals. Consider an edge " "between adjacent polygons to be smooth if the angle between them " "is less than threshold degrees.", - &EggBase::dispatch_normals, NULL, &vertex); + &EggBase::dispatch_normals, nullptr, &vertex); add_option ("nn", "", 48, "Preserve normals exactly as they are. This is the default.", - &EggBase::dispatch_normals, NULL, &preserve); + &EggBase::dispatch_normals, nullptr, &preserve); add_option ("tbn", "name", 48, @@ -90,7 +92,7 @@ add_normals_options() { "above options. The tangent and binormal are used to implement " "bump mapping and related texture-based lighting effects. This option " "may be repeated as necessary to name multiple texture coordinate sets.", - &EggBase::dispatch_vector_string, NULL, &_tbn_names); + &EggBase::dispatch_vector_string, nullptr, &_tbn_names); add_option ("tbnall", "", 48, diff --git a/pandatool/src/eggbase/eggBase.h b/pandatool/src/eggbase/eggBase.h index 3b2bb1ed68..4c6b156721 100644 --- a/pandatool/src/eggbase/eggBase.h +++ b/pandatool/src/eggbase/eggBase.h @@ -39,17 +39,17 @@ public: protected: void append_command_comment(EggData *_data); - static void append_command_comment(EggData *_data, const string &comment); + static void append_command_comment(EggData *_data, const std::string &comment); - static bool dispatch_normals(ProgramBase *self, const string &opt, const string &arg, void *mode); - bool ns_dispatch_normals(const string &opt, const string &arg, void *mode); + static bool dispatch_normals(ProgramBase *self, const std::string &opt, const std::string &arg, void *mode); + bool ns_dispatch_normals(const std::string &opt, const std::string &arg, void *mode); - static bool dispatch_scale(const string &opt, const string &arg, void *var); - static bool dispatch_rotate_xyz(ProgramBase *self, const string &opt, const string &arg, void *var); - bool ns_dispatch_rotate_xyz(const string &opt, const string &arg, void *var); - static bool dispatch_rotate_axis(ProgramBase *self, const string &opt, const string &arg, void *var); - bool ns_dispatch_rotate_axis(const string &opt, const string &arg, void *var); - static bool dispatch_translate(const string &opt, const string &arg, void *var); + static bool dispatch_scale(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_rotate_xyz(ProgramBase *self, const std::string &opt, const std::string &arg, void *var); + bool ns_dispatch_rotate_xyz(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_rotate_axis(ProgramBase *self, const std::string &opt, const std::string &arg, void *var); + bool ns_dispatch_rotate_axis(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_translate(const std::string &opt, const std::string &arg, void *var); protected: enum NormalsMode { diff --git a/pandatool/src/eggbase/eggConverter.cxx b/pandatool/src/eggbase/eggConverter.cxx index a55d68856f..036b7dea18 100644 --- a/pandatool/src/eggbase/eggConverter.cxx +++ b/pandatool/src/eggbase/eggConverter.cxx @@ -21,8 +21,8 @@ * with a leading dot. */ EggConverter:: -EggConverter(const string &format_name, - const string &preferred_extension, +EggConverter(const std::string &format_name, + const std::string &preferred_extension, bool allow_last_param, bool allow_stdout) : EggFilter(allow_last_param, allow_stdout), diff --git a/pandatool/src/eggbase/eggConverter.h b/pandatool/src/eggbase/eggConverter.h index 1dfa1b00dc..3922a6b842 100644 --- a/pandatool/src/eggbase/eggConverter.h +++ b/pandatool/src/eggbase/eggConverter.h @@ -24,13 +24,13 @@ */ class EggConverter : public EggFilter { public: - EggConverter(const string &format_name, - const string &preferred_extension = string(), + EggConverter(const std::string &format_name, + const std::string &preferred_extension = std::string(), bool allow_last_param = true, bool allow_stdout = true); protected: - string _format_name; + std::string _format_name; }; #endif diff --git a/pandatool/src/eggbase/eggMultiBase.cxx b/pandatool/src/eggbase/eggMultiBase.cxx index cc591d4c18..426b62a956 100644 --- a/pandatool/src/eggbase/eggMultiBase.cxx +++ b/pandatool/src/eggbase/eggMultiBase.cxx @@ -148,13 +148,13 @@ read_egg(const Filename &filename) { if (!data->read(filename)) { // Failure reading. - return (EggData *)NULL; + return nullptr; } if (_noabs && data->original_had_absolute_pathnames()) { nout << filename.get_basename() << " includes absolute pathnames!\n"; - return (EggData *)NULL; + return nullptr; } DSearchPath file_path; @@ -168,7 +168,7 @@ read_egg(const Filename &filename) { if (_force_complete) { if (!data->load_externals()) { - return (EggData *)NULL; + return nullptr; } } diff --git a/pandatool/src/eggbase/eggMultiFilter.cxx b/pandatool/src/eggbase/eggMultiFilter.cxx index 8b8fd61a15..981c8ad4cf 100644 --- a/pandatool/src/eggbase/eggMultiFilter.cxx +++ b/pandatool/src/eggbase/eggMultiFilter.cxx @@ -76,14 +76,14 @@ handle_args(ProgramBase::Args &args) { nout << "Populating args from input file: " << _input_filename << "\n"; // Makes sure the file is set is_text _filename = Filename::text_filename(_input_filename); - ifstream input; + std::ifstream input; if (!_filename.open_read(input)) { nout << "Error opening file: " << _input_filename << "\n"; return false; } - string line; + std::string line; // File should be a space-delimited list of egg files - while (getline(input, line, ' ')) { + while (std::getline(input, line, ' ')) { args.push_back(line); } } @@ -135,7 +135,7 @@ handle_args(ProgramBase::Args &args) { Args::const_iterator ai; for (ai = args.begin(); ai != args.end(); ++ai) { PT(EggData) data = read_egg(Filename::from_os_specific(*ai)); - if (data == (EggData *)NULL) { + if (data == nullptr) { // Rather than returning false, we simply exit here, so the ProgramBase // won't try to tell the user how to run the program just because we got // a bad egg file. diff --git a/pandatool/src/eggbase/eggReader.cxx b/pandatool/src/eggbase/eggReader.cxx index e570b8aa9d..16c5e2ad28 100644 --- a/pandatool/src/eggbase/eggReader.cxx +++ b/pandatool/src/eggbase/eggReader.cxx @@ -50,7 +50,7 @@ EggReader() { "which should be self-contained and include only relative pathnames.", &EggReader::dispatch_none, &_noabs); - _tex_type = (PNMFileType *)NULL; + _tex_type = nullptr; _delod = -1.0; _got_tex_dirname = false; @@ -90,7 +90,7 @@ add_texture_options() { "the image format can be determined by the extension, but sometimes " "the extension is insufficient to unambiguously specify an image " "type.", - &EggReader::dispatch_image_type, NULL, &_tex_type); + &EggReader::dispatch_image_type, nullptr, &_tex_type); } /** @@ -111,7 +111,7 @@ add_delod_options(double default_delod) { "a camera at the indicated fixed distance from each LOD. " "Use -delod -1 to keep all the LOD's as they are, which is " "the default.\n", - &EggReader::dispatch_double, NULL, &_delod); + &EggReader::dispatch_double, nullptr, &_delod); } else { add_option @@ -120,7 +120,7 @@ add_delod_options(double default_delod) { "a camera at the indicated fixed distance from each LOD. " "Use -delod -1 to keep all the LOD's as they are. The default value " "is " + format_string(default_delod) + ".", - &EggReader::dispatch_double, NULL, &_delod); + &EggReader::dispatch_double, nullptr, &_delod); } } @@ -178,7 +178,7 @@ handle_args(ProgramBase::Args &args) { exit(1); } } else { - if (!file_data.read(cin)) { + if (!file_data.read(std::cin)) { exit(1); } } diff --git a/pandatool/src/eggbase/eggReader.h b/pandatool/src/eggbase/eggReader.h index c195b0c07d..134799431d 100644 --- a/pandatool/src/eggbase/eggReader.h +++ b/pandatool/src/eggbase/eggReader.h @@ -51,7 +51,7 @@ protected: private: Filename _tex_dirname; bool _got_tex_dirname; - string _tex_extension; + std::string _tex_extension; bool _got_tex_extension; PNMFileType *_tex_type; double _delod; diff --git a/pandatool/src/eggbase/eggSingleBase.cxx b/pandatool/src/eggbase/eggSingleBase.cxx index b7fc71c45b..a3cda11736 100644 --- a/pandatool/src/eggbase/eggSingleBase.cxx +++ b/pandatool/src/eggbase/eggSingleBase.cxx @@ -40,7 +40,7 @@ EggSingleBase() : */ EggReader *EggSingleBase:: as_reader() { - return (EggReader *)NULL; + return nullptr; } /** @@ -54,7 +54,7 @@ as_reader() { */ EggWriter *EggSingleBase:: as_writer() { - return (EggWriter *)NULL; + return nullptr; } /** diff --git a/pandatool/src/eggbase/eggToSomething.cxx b/pandatool/src/eggbase/eggToSomething.cxx index 942a0d82db..eb6adc89e5 100644 --- a/pandatool/src/eggbase/eggToSomething.cxx +++ b/pandatool/src/eggbase/eggToSomething.cxx @@ -19,8 +19,8 @@ * just used in printing error messages and such. */ EggToSomething:: -EggToSomething(const string &format_name, - const string &preferred_extension, +EggToSomething(const std::string &format_name, + const std::string &preferred_extension, bool allow_last_param, bool allow_stdout) : EggConverter(format_name, preferred_extension, allow_last_param, allow_stdout) @@ -34,7 +34,7 @@ EggToSomething(const string &format_name, add_runline("[opts] input.egg >output" + _preferred_extension); } - string o_description; + std::string o_description; if (_allow_stdout) { if (_allow_last_param) { @@ -93,13 +93,13 @@ add_units_options() { "specified, the vertices in the egg file will be scaled as " "necessary to make the appropriate units conversion; otherwise, " "the vertices will be left as they are.", - &EggToSomething::dispatch_units, NULL, &_input_units); + &EggToSomething::dispatch_units, nullptr, &_input_units); add_option ("uo", "units", 40, "Specify the units of the resulting " + _format_name + " file. Normally, the default units for the format are used.", - &EggToSomething::dispatch_units, NULL, &_output_units); + &EggToSomething::dispatch_units, nullptr, &_output_units); } /** diff --git a/pandatool/src/eggbase/eggToSomething.h b/pandatool/src/eggbase/eggToSomething.h index 56885c33aa..aafc045a3d 100644 --- a/pandatool/src/eggbase/eggToSomething.h +++ b/pandatool/src/eggbase/eggToSomething.h @@ -25,8 +25,8 @@ */ class EggToSomething : public EggConverter { public: - EggToSomething(const string &format_name, - const string &preferred_extension = string(), + EggToSomething(const std::string &format_name, + const std::string &preferred_extension = std::string(), bool allow_last_param = true, bool allow_stdout = true); diff --git a/pandatool/src/eggbase/eggWriter.cxx b/pandatool/src/eggbase/eggWriter.cxx index 28365de2c1..c881991a08 100644 --- a/pandatool/src/eggbase/eggWriter.cxx +++ b/pandatool/src/eggbase/eggWriter.cxx @@ -47,7 +47,7 @@ EggWriter(bool allow_last_param, bool allow_stdout) : add_runline("[opts] >output.egg"); } - string o_description; + std::string o_description; if (_allow_stdout) { if (_allow_last_param) { diff --git a/pandatool/src/eggbase/eggWriter.h b/pandatool/src/eggbase/eggWriter.h index 7d08eab3a0..9037fe7e54 100644 --- a/pandatool/src/eggbase/eggWriter.h +++ b/pandatool/src/eggbase/eggWriter.h @@ -39,8 +39,7 @@ protected: virtual bool post_command_line(); private: - ofstream _output_stream; - ostream *_output_ptr; + std::ofstream _output_stream; }; #endif diff --git a/pandatool/src/eggbase/somethingToEgg.cxx b/pandatool/src/eggbase/somethingToEgg.cxx index 4f33599761..45d705f12c 100644 --- a/pandatool/src/eggbase/somethingToEgg.cxx +++ b/pandatool/src/eggbase/somethingToEgg.cxx @@ -22,8 +22,8 @@ * just used in printing error messages and such. */ SomethingToEgg:: -SomethingToEgg(const string &format_name, - const string &preferred_extension, +SomethingToEgg(const std::string &format_name, + const std::string &preferred_extension, bool allow_last_param, bool allow_stdout) : EggConverter(format_name, preferred_extension, allow_last_param, allow_stdout) { @@ -89,7 +89,7 @@ add_units_options() { ("ui", "units", 40, "Specify the units of the input " + _format_name + " file. Normally, this can be inferred from the file itself.", - &SomethingToEgg::dispatch_units, NULL, &_input_units); + &SomethingToEgg::dispatch_units, nullptr, &_input_units); add_option ("uo", "units", 40, @@ -97,7 +97,7 @@ add_units_options() { "specified, the vertices in the egg file will be scaled as " "necessary to make the appropriate units conversion; otherwise, " "the vertices will be left as they are.", - &SomethingToEgg::dispatch_units, NULL, &_output_units); + &SomethingToEgg::dispatch_units, nullptr, &_output_units); } /** @@ -111,14 +111,14 @@ add_animation_options() { "converted to egg, if at all. At present, the following keywords " "are supported: none, pose, flip, strobe, model, chan, or both. " "The default is none, which means not to convert animation.", - &SomethingToEgg::dispatch_animation_convert, NULL, &_animation_convert); + &SomethingToEgg::dispatch_animation_convert, nullptr, &_animation_convert); add_option ("cn", "name", 40, "Specifies the name of the animation character. This should match " "between all of the model files and all of the channel files for a " "particular model and its associated channels.", - &SomethingToEgg::dispatch_string, NULL, &_character_name); + &SomethingToEgg::dispatch_string, nullptr, &_character_name); add_option ("sf", "start-frame", 40, @@ -316,7 +316,7 @@ post_process_egg_file() { * specified parameter. var is a pointer to an AnimationConvert variable. */ bool SomethingToEgg:: -dispatch_animation_convert(const string &opt, const string &arg, void *var) { +dispatch_animation_convert(const std::string &opt, const std::string &arg, void *var) { AnimationConvert *ip = (AnimationConvert *)var; (*ip) = string_animation_convert(arg); if ((*ip) == AC_invalid) { diff --git a/pandatool/src/eggbase/somethingToEgg.h b/pandatool/src/eggbase/somethingToEgg.h index 263cfd5336..5c5427dcde 100644 --- a/pandatool/src/eggbase/somethingToEgg.h +++ b/pandatool/src/eggbase/somethingToEgg.h @@ -28,8 +28,8 @@ class SomethingToEggConverter; */ class SomethingToEgg : public EggConverter { public: - SomethingToEgg(const string &format_name, - const string &preferred_extension = string(), + SomethingToEgg(const std::string &format_name, + const std::string &preferred_extension = std::string(), bool allow_last_param = true, bool allow_stdout = true); @@ -45,7 +45,7 @@ protected: virtual bool post_command_line(); virtual void post_process_egg_file(); - static bool dispatch_animation_convert(const string &opt, const string &arg, void *var); + static bool dispatch_animation_convert(const std::string &opt, const std::string &arg, void *var); Filename _input_filename; @@ -54,7 +54,7 @@ protected: DistanceUnit _output_units; AnimationConvert _animation_convert; - string _character_name; + std::string _character_name; double _start_frame; double _end_frame; double _frame_inc; diff --git a/pandatool/src/eggcharbase/eggBackPointer.cxx b/pandatool/src/eggcharbase/eggBackPointer.cxx index aa4a95f73a..400d9e3b2f 100644 --- a/pandatool/src/eggcharbase/eggBackPointer.cxx +++ b/pandatool/src/eggcharbase/eggBackPointer.cxx @@ -55,5 +55,5 @@ has_vertices() const { * Applies the indicated name change to the egg file. */ void EggBackPointer:: -set_name(const string &name) { +set_name(const std::string &name) { } diff --git a/pandatool/src/eggcharbase/eggBackPointer.h b/pandatool/src/eggcharbase/eggBackPointer.h index 6a0e864046..2595c09d18 100644 --- a/pandatool/src/eggcharbase/eggBackPointer.h +++ b/pandatool/src/eggcharbase/eggBackPointer.h @@ -37,7 +37,7 @@ public: virtual void extend_to(int num_frames); virtual bool has_vertices() const; - virtual void set_name(const string &name); + virtual void set_name(const std::string &name); public: static TypeHandle get_class_type() { diff --git a/pandatool/src/eggcharbase/eggCharacterCollection.I b/pandatool/src/eggcharbase/eggCharacterCollection.I index 0e1c81f62a..fc1f26964d 100644 --- a/pandatool/src/eggcharbase/eggCharacterCollection.I +++ b/pandatool/src/eggcharbase/eggCharacterCollection.I @@ -25,7 +25,7 @@ get_num_eggs() const { */ INLINE EggData *EggCharacterCollection:: get_egg(int i) const { - nassertr(i >= 0 && i < (int)_eggs.size(), (EggData *)NULL); + nassertr(i >= 0 && i < (int)_eggs.size(), nullptr); return _eggs[i]._egg; } @@ -71,7 +71,7 @@ get_num_characters() const { */ INLINE EggCharacterData *EggCharacterCollection:: get_character(int i) const { - nassertr(i >= 0 && i < (int)_characters.size(), (EggCharacterData *)NULL); + nassertr(i >= 0 && i < (int)_characters.size(), nullptr); return _characters[i]; } @@ -81,7 +81,7 @@ get_character(int i) const { INLINE EggCharacterData *EggCharacterCollection:: get_character_by_model_index(int model_index) const { nassertr(model_index >= 0 && model_index < (int)_characters_by_model_index.size(), - (EggCharacterData *)NULL); + nullptr); return _characters_by_model_index[model_index]; } @@ -90,5 +90,5 @@ get_character_by_model_index(int model_index) const { */ INLINE EggCharacterCollection::ModelDescription:: ModelDescription() { - _root_node = (EggObject *)NULL; + _root_node = nullptr; } diff --git a/pandatool/src/eggcharbase/eggCharacterCollection.cxx b/pandatool/src/eggcharbase/eggCharacterCollection.cxx index 2a97862ea6..f90c7d9a91 100644 --- a/pandatool/src/eggcharbase/eggCharacterCollection.cxx +++ b/pandatool/src/eggcharbase/eggCharacterCollection.cxx @@ -29,6 +29,8 @@ #include +using std::string; + /** * @@ -125,7 +127,7 @@ get_character_by_name(const string &character_name) const { } } - return (EggCharacterData *)NULL; + return nullptr; } @@ -617,7 +619,7 @@ rename_char(int i, const string &name) { EggCharacterData *char_data = _characters[i]; if (char_data->get_name() != name) { - nassertv(get_character_by_name(name) == (EggCharacterData *)NULL); + nassertv(get_character_by_name(name) == nullptr); char_data->rename_char(name); } } @@ -626,7 +628,7 @@ rename_char(int i, const string &name) { * */ void EggCharacterCollection:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { Characters::const_iterator ci; for (ci = _characters.begin(); ci != _characters.end(); ++ci) { @@ -646,7 +648,7 @@ write(ostream &out, int indent_level) const { * initially different. */ void EggCharacterCollection:: -check_errors(ostream &out, bool force_initial_rest_frame) { +check_errors(std::ostream &out, bool force_initial_rest_frame) { Characters::const_iterator ci; for (ci = _characters.begin(); ci != _characters.end(); ++ci) { EggCharacterData *char_data = (*ci); diff --git a/pandatool/src/eggcharbase/eggCharacterCollection.h b/pandatool/src/eggcharbase/eggCharacterCollection.h index 57c3bc984d..8a0bbd4f28 100644 --- a/pandatool/src/eggcharbase/eggCharacterCollection.h +++ b/pandatool/src/eggcharbase/eggCharacterCollection.h @@ -43,21 +43,21 @@ public: INLINE int get_num_characters() const; INLINE EggCharacterData *get_character(int i) const; - EggCharacterData *get_character_by_name(const string &character_name) const; + EggCharacterData *get_character_by_name(const std::string &character_name) const; INLINE EggCharacterData *get_character_by_model_index(int model_index) const; - void rename_char(int i, const string &name); + void rename_char(int i, const std::string &name); - virtual void write(ostream &out, int indent_level = 0) const; - void check_errors(ostream &out, bool force_initial_rest_frame); + virtual void write(std::ostream &out, int indent_level = 0) const; + void check_errors(std::ostream &out, bool force_initial_rest_frame); virtual EggCharacterData *make_character_data(); virtual EggJointData *make_joint_data(EggCharacterData *char_data); virtual EggSliderData *make_slider_data(EggCharacterData *char_data); public: - EggCharacterData *make_character(const string &character_name); + EggCharacterData *make_character(const std::string &character_name); class EggInfo { public: @@ -77,9 +77,9 @@ public: private: bool scan_hierarchy(EggNode *egg_node); void scan_for_top_joints(EggNode *egg_node, EggNode *model_root, - const string &character_name); + const std::string &character_name); void scan_for_top_tables(EggTable *bundle, EggNode *model_root, - const string &character_name); + const std::string &character_name); void scan_for_morphs(EggNode *egg_node, int model_index, EggCharacterData *char_data); void scan_for_sliders(EggNode *egg_node, int model_index, @@ -101,7 +101,7 @@ private: }; typedef pmap TopEggNodes; - typedef pmap TopEggNodesByName; + typedef pmap TopEggNodesByName; TopEggNodesByName _top_egg_nodes; int _next_model_index; diff --git a/pandatool/src/eggcharbase/eggCharacterData.I b/pandatool/src/eggcharbase/eggCharacterData.I index 7b19b079b6..fc3d3f1bcc 100644 --- a/pandatool/src/eggcharbase/eggCharacterData.I +++ b/pandatool/src/eggcharbase/eggCharacterData.I @@ -47,7 +47,7 @@ get_model_index(int n) const { */ INLINE EggNode *EggCharacterData:: get_model_root(int n) const { - nassertr(n >= 0 && n < (int)_models.size(), (EggNode *)NULL); + nassertr(n >= 0 && n < (int)_models.size(), nullptr); return _models[n]._model_root; } @@ -57,7 +57,7 @@ get_model_root(int n) const { */ INLINE EggData *EggCharacterData:: get_egg_data(int n) const { - nassertr(n >= 0 && n < (int)_models.size(), (EggData *)NULL); + nassertr(n >= 0 && n < (int)_models.size(), nullptr); return _models[n]._egg_data; } @@ -77,7 +77,7 @@ get_root_joint() const { * has that name. */ INLINE EggJointData *EggCharacterData:: -find_joint(const string &name) const { +find_joint(const std::string &name) const { return _root_joint->find_joint(name); } @@ -87,7 +87,7 @@ find_joint(const string &name) const { * inherits the net transform of the indicated parent joint. */ INLINE EggJointData *EggCharacterData:: -make_new_joint(const string &name, EggJointData *parent) { +make_new_joint(const std::string &name, EggJointData *parent) { EggJointData *joint = parent->make_new_joint(name); _joints.push_back(joint); _components.push_back(joint); @@ -108,7 +108,7 @@ get_num_joints() const { */ INLINE EggJointData *EggCharacterData:: get_joint(int n) const { - nassertr(n >= 0 && n < (int)_joints.size(), NULL); + nassertr(n >= 0 && n < (int)_joints.size(), nullptr); return _joints[n]; } @@ -125,7 +125,7 @@ get_num_sliders() const { */ INLINE EggSliderData *EggCharacterData:: get_slider(int n) const { - nassertr(n >= 0 && n < (int)_sliders.size(), NULL); + nassertr(n >= 0 && n < (int)_sliders.size(), nullptr); return _sliders[n]; } @@ -145,6 +145,6 @@ get_num_components() const { */ INLINE EggComponentData *EggCharacterData:: get_component(int n) const { - nassertr(n >= 0 && n < (int)_components.size(), NULL); + nassertr(n >= 0 && n < (int)_components.size(), nullptr); return _components[n]; } diff --git a/pandatool/src/eggcharbase/eggCharacterData.cxx b/pandatool/src/eggcharbase/eggCharacterData.cxx index 6c444e6c91..d3c7a54530 100644 --- a/pandatool/src/eggcharbase/eggCharacterData.cxx +++ b/pandatool/src/eggcharbase/eggCharacterData.cxx @@ -63,7 +63,7 @@ EggCharacterData:: * as if they are expected to have the same skeleton hierarchy. */ void EggCharacterData:: -rename_char(const string &name) { +rename_char(const std::string &name) { Models::iterator mi; for (mi = _models.begin(); mi != _models.end(); ++mi) { (*mi)._model_root->set_name(name); @@ -107,7 +107,7 @@ get_num_frames(int model_index) const { // We have a winner. Assume all other components will be similar. return num_frames; } - max_num_frames = max(max_num_frames, num_frames); + max_num_frames = std::max(max_num_frames, num_frames); } // Every component had either 1 frame or 0 frames. Return the maximum of @@ -154,7 +154,7 @@ check_num_frames(int model_index) { // than 0 or 1), we have a discrepency. This is an error condition. any_violations = true; } - max_num_frames = max(max_num_frames, num_frames); + max_num_frames = std::max(max_num_frames, num_frames); } if (any_violations) { @@ -265,7 +265,7 @@ do_reparent() { EggJointData *joint_data = (*si); // Don't bother reporting joints that no longer have a parent, since we // don't care about joints that are now outside the hierarchy. - if (joint_data->get_parent() != (EggJointData *)NULL) { + if (joint_data->get_parent() != nullptr) { nout << "Warning: reparenting " << joint_data->get_name() << " to "; if (joint_data->get_parent() == _root_joint) { @@ -324,7 +324,7 @@ choose_optimal_hierarchy() { } } - if (best_parent != (EggJointData *)NULL && + if (best_parent != nullptr && best_parent != joint_data->_parent) { nout << "best parent for " << joint_data->get_name() << " is " << best_parent->get_name() << "\n"; @@ -338,14 +338,14 @@ choose_optimal_hierarchy() { * name. */ EggSliderData *EggCharacterData:: -find_slider(const string &name) const { +find_slider(const std::string &name) const { SlidersByName::const_iterator si; si = _sliders_by_name.find(name); if (si != _sliders_by_name.end()) { return (*si).second; } - return NULL; + return nullptr; } /** @@ -353,7 +353,7 @@ find_slider(const string &name) const { * already, creates a new one. */ EggSliderData *EggCharacterData:: -make_slider(const string &name) { +make_slider(const std::string &name) { SlidersByName::const_iterator si; si = _sliders_by_name.find(name); if (si != _sliders_by_name.end()) { @@ -397,7 +397,7 @@ estimate_db_size() const { * */ void EggCharacterData:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "Character " << get_name() << ":\n"; get_root_joint()->write(out, indent_level + 2); diff --git a/pandatool/src/eggcharbase/eggCharacterData.h b/pandatool/src/eggcharbase/eggCharacterData.h index d4b7125487..f488e33536 100644 --- a/pandatool/src/eggcharbase/eggCharacterData.h +++ b/pandatool/src/eggcharbase/eggCharacterData.h @@ -54,7 +54,7 @@ public: EggCharacterData(EggCharacterCollection *collection); virtual ~EggCharacterData(); - void rename_char(const string &name); + void rename_char(const std::string &name); void add_model(int model_index, EggNode *model_root, EggData *egg_data); INLINE int get_num_models() const; @@ -66,8 +66,8 @@ public: double get_frame_rate(int model_index) const; INLINE EggJointData *get_root_joint() const; - INLINE EggJointData *find_joint(const string &name) const; - INLINE EggJointData *make_new_joint(const string &name, EggJointData *parent); + INLINE EggJointData *find_joint(const std::string &name) const; + INLINE EggJointData *make_new_joint(const std::string &name, EggJointData *parent); INLINE int get_num_joints() const; INLINE EggJointData *get_joint(int n) const; @@ -76,15 +76,15 @@ public: INLINE int get_num_sliders() const; INLINE EggSliderData *get_slider(int n) const; - EggSliderData *find_slider(const string &name) const; - EggSliderData *make_slider(const string &name); + EggSliderData *find_slider(const std::string &name) const; + EggSliderData *make_slider(const std::string &name); INLINE int get_num_components() const; INLINE EggComponentData *get_component(int n) const; size_t estimate_db_size() const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; private: class Model { @@ -99,7 +99,7 @@ private: EggCharacterCollection *_collection; EggJointData *_root_joint; - typedef pmap SlidersByName; + typedef pmap SlidersByName; SlidersByName _sliders_by_name; typedef pvector Sliders; diff --git a/pandatool/src/eggcharbase/eggCharacterFilter.cxx b/pandatool/src/eggcharbase/eggCharacterFilter.cxx index aba5834a66..9b23e7804d 100644 --- a/pandatool/src/eggcharbase/eggCharacterFilter.cxx +++ b/pandatool/src/eggcharbase/eggCharacterFilter.cxx @@ -21,7 +21,7 @@ */ EggCharacterFilter:: EggCharacterFilter() : EggMultiFilter(false) { - _collection = (EggCharacterCollection *)NULL; + _collection = nullptr; _force_initial_rest_frame = false; } @@ -31,7 +31,7 @@ EggCharacterFilter() : EggMultiFilter(false) { */ EggCharacterFilter:: ~EggCharacterFilter() { - if (_collection != (EggCharacterCollection *)NULL) { + if (_collection != nullptr) { delete _collection; } } @@ -57,7 +57,7 @@ add_fixrest_option() { */ bool EggCharacterFilter:: post_command_line() { - if (_collection == (EggCharacterCollection *)NULL) { + if (_collection == nullptr) { _collection = make_collection(); } diff --git a/pandatool/src/eggcharbase/eggComponentData.I b/pandatool/src/eggcharbase/eggComponentData.I index f706ab4b5a..e0064948de 100644 --- a/pandatool/src/eggcharbase/eggComponentData.I +++ b/pandatool/src/eggcharbase/eggComponentData.I @@ -29,7 +29,7 @@ get_num_models() const { INLINE bool EggComponentData:: has_model(int model_index) const { if (model_index >= 0 && model_index < (int)_back_pointers.size()) { - return _back_pointers[model_index] != (EggBackPointer *)NULL; + return _back_pointers[model_index] != nullptr; } return false; } @@ -43,5 +43,5 @@ get_model(int model_index) const { if (model_index >= 0 && model_index < (int)_back_pointers.size()) { return _back_pointers[model_index]; } - return (EggBackPointer *)NULL; + return nullptr; } diff --git a/pandatool/src/eggcharbase/eggComponentData.cxx b/pandatool/src/eggcharbase/eggComponentData.cxx index ceea3582a7..5af9dd3d57 100644 --- a/pandatool/src/eggcharbase/eggComponentData.cxx +++ b/pandatool/src/eggcharbase/eggComponentData.cxx @@ -39,7 +39,7 @@ EggComponentData:: BackPointers::iterator bpi; for (bpi = _back_pointers.begin(); bpi != _back_pointers.end(); ++bpi) { EggBackPointer *back = (*bpi); - if (back != (EggBackPointer *)NULL) { + if (back != nullptr) { delete back; } } @@ -53,7 +53,7 @@ EggComponentData:: * matched_name(). */ void EggComponentData:: -add_name(const string &name, NameUniquifier &uniquifier) { +add_name(const std::string &name, NameUniquifier &uniquifier) { if (_names.insert(name).second) { // This is a new name for this component. if (!has_name()) { @@ -71,7 +71,7 @@ add_name(const string &name, NameUniquifier &uniquifier) { * with this particular joint, false otherwise. */ bool EggComponentData:: -matches_name(const string &name) const { +matches_name(const std::string &name) const { if (name == get_name()) { return true; } @@ -85,7 +85,7 @@ matches_name(const string &name) const { int EggComponentData:: get_num_frames(int model_index) const { EggBackPointer *back = get_model(model_index); - if (back == (EggBackPointer *)NULL) { + if (back == nullptr) { return 0; } return back->get_num_frames(); @@ -98,7 +98,7 @@ get_num_frames(int model_index) const { void EggComponentData:: extend_to(int model_index, int num_frames) const { EggBackPointer *back = get_model(model_index); - nassertv(back != (EggBackPointer *)NULL); + nassertv(back != nullptr); back->extend_to(num_frames); } @@ -109,7 +109,7 @@ extend_to(int model_index, int num_frames) const { double EggComponentData:: get_frame_rate(int model_index) const { EggBackPointer *back = get_model(model_index); - if (back == (EggBackPointer *)NULL) { + if (back == nullptr) { return 0.0; } return back->get_frame_rate(); @@ -121,10 +121,10 @@ get_frame_rate(int model_index) const { void EggComponentData:: set_model(int model_index, EggBackPointer *back) { while ((int)_back_pointers.size() <= model_index) { - _back_pointers.push_back((EggBackPointer *)NULL); + _back_pointers.push_back(nullptr); } - if (_back_pointers[model_index] != (EggBackPointer *)NULL) { + if (_back_pointers[model_index] != nullptr) { nout << "Warning: deleting old back pointer.\n"; delete _back_pointers[model_index]; } diff --git a/pandatool/src/eggcharbase/eggComponentData.h b/pandatool/src/eggcharbase/eggComponentData.h index 4445d51fe1..b54c20ffb6 100644 --- a/pandatool/src/eggcharbase/eggComponentData.h +++ b/pandatool/src/eggcharbase/eggComponentData.h @@ -37,15 +37,15 @@ public: EggCharacterData *char_data); virtual ~EggComponentData(); - void add_name(const string &name, NameUniquifier &uniquifier); - bool matches_name(const string &name) const; + void add_name(const std::string &name, NameUniquifier &uniquifier); + bool matches_name(const std::string &name) const; int get_num_frames(int model_index) const; void extend_to(int model_index, int num_frames) const; double get_frame_rate(int model_index) const; virtual void add_back_pointer(int model_index, EggObject *egg_object)=0; - virtual void write(ostream &out, int indent_level = 0) const=0; + virtual void write(std::ostream &out, int indent_level = 0) const=0; INLINE int get_num_models() const; INLINE bool has_model(int model_index) const; @@ -59,7 +59,7 @@ protected: typedef pvector BackPointers; BackPointers _back_pointers; - typedef pset Names; + typedef pset Names; Names _names; EggCharacterCollection *_collection; diff --git a/pandatool/src/eggcharbase/eggJointData.I b/pandatool/src/eggcharbase/eggJointData.I index c6349809ae..c8b81967ee 100644 --- a/pandatool/src/eggcharbase/eggJointData.I +++ b/pandatool/src/eggcharbase/eggJointData.I @@ -32,7 +32,7 @@ get_num_children() const { */ INLINE EggJointData *EggJointData:: get_child(int n) const { - nassertr(n >= 0 && n < (int)_children.size(), (EggJointData *)NULL); + nassertr(n >= 0 && n < (int)_children.size(), nullptr); return _children[n]; } @@ -41,9 +41,9 @@ get_child(int n) const { * if no joint has that name. */ INLINE EggJointData *EggJointData:: -find_joint(const string &name) { +find_joint(const std::string &name) { EggJointData *joint = find_joint_exact(name); - if (joint == (EggJointData *)NULL) { + if (joint == nullptr) { joint = find_joint_matches(name); } return joint; diff --git a/pandatool/src/eggcharbase/eggJointData.cxx b/pandatool/src/eggcharbase/eggJointData.cxx index 8104ee1ad7..65ed9505a5 100644 --- a/pandatool/src/eggcharbase/eggJointData.cxx +++ b/pandatool/src/eggcharbase/eggJointData.cxx @@ -22,6 +22,8 @@ #include "fftCompressor.h" #include "zStream.h" +using std::string; + TypeHandle EggJointData::_type_handle; @@ -33,8 +35,8 @@ EggJointData(EggCharacterCollection *collection, EggCharacterData *char_data) : EggComponentData(collection, char_data) { - _parent = (EggJointData *)NULL; - _new_parent = (EggJointData *)NULL; + _parent = nullptr; + _new_parent = nullptr; _has_rest_frame = false; _rest_frames_differ = false; } @@ -46,7 +48,7 @@ EggJointData(EggCharacterCollection *collection, LMatrix4d EggJointData:: get_frame(int model_index, int n) const { EggBackPointer *back = get_model(model_index); - if (back == (EggBackPointer *)NULL) { + if (back == nullptr) { return LMatrix4d::ident_mat(); } @@ -63,7 +65,7 @@ get_frame(int model_index, int n) const { LMatrix4d EggJointData:: get_net_frame(int model_index, int n, EggCharacterDb &db) const { EggBackPointer *back = get_model(model_index); - if (back == (EggBackPointer *)NULL) { + if (back == nullptr) { return LMatrix4d::ident_mat(); } @@ -74,7 +76,7 @@ get_net_frame(int model_index, int n, EggCharacterDb &db) const { if (!db.get_matrix(joint, EggCharacterDb::TT_net_frame, n, mat)) { // Compute this frame's net, and stuff it in. mat = get_frame(model_index, n); - if (_parent != (EggJointData *)NULL) { + if (_parent != nullptr) { mat = mat * _parent->get_net_frame(model_index, n, db); } db.set_matrix(joint, EggCharacterDb::TT_net_frame, n, mat); @@ -89,7 +91,7 @@ get_net_frame(int model_index, int n, EggCharacterDb &db) const { LMatrix4d EggJointData:: get_net_frame_inv(int model_index, int n, EggCharacterDb &db) const { EggBackPointer *back = get_model(model_index); - if (back == (EggBackPointer *)NULL) { + if (back == nullptr) { return LMatrix4d::ident_mat(); } @@ -139,12 +141,12 @@ void EggJointData:: move_vertices_to(EggJointData *new_owner) { int num_models = get_num_models(); - if (new_owner == (EggJointData *)NULL) { + if (new_owner == nullptr) { for (int model_index = 0; model_index < num_models; model_index++) { if (has_model(model_index)) { EggJointPointer *joint; DCAST_INTO_V(joint, get_model(model_index)); - joint->move_vertices_to((EggJointPointer *)NULL); + joint->move_vertices_to(nullptr); } } } else { @@ -184,7 +186,7 @@ score_reparent_to(EggJointData *new_parent, EggCharacterDb &db) { int num_models = get_num_models(); for (int model_index = 0; model_index < num_models; model_index++) { EggBackPointer *back = get_model(model_index); - if (back != (EggBackPointer *)NULL) { + if (back != nullptr) { EggJointPointer *joint; DCAST_INTO_R(joint, back, false); @@ -195,11 +197,11 @@ score_reparent_to(EggJointData *new_parent, EggCharacterDb &db) { // We already have this parent. transform = LMatrix4d::ident_mat(); - } else if (_parent == (EggJointData *)NULL) { + } else if (_parent == nullptr) { // We are moving from outside the joint hierarchy to within it. transform = new_parent->get_net_frame_inv(model_index, n, db); - } else if (new_parent == (EggJointData *)NULL) { + } else if (new_parent == nullptr) { // We are moving from within the hierarchy to outside it. transform = _parent->get_net_frame(model_index, n, db); @@ -259,7 +261,7 @@ score_reparent_to(EggJointData *new_parent, EggCharacterDb &db) { #else // The FFTCompressor does minimal run-length encoding, but to really get an // accurate measure we should zlib-compress the resulting stream. - ostringstream sstr; + std::ostringstream sstr; OCompressStream zstr(&sstr, false); zstr.write((const char *)dg.get_data(), dg.get_length()); zstr.flush(); @@ -278,7 +280,7 @@ do_rebuild_all(EggCharacterDb &db) { BackPointers::iterator bpi; for (bpi = _back_pointers.begin(); bpi != _back_pointers.end(); ++bpi) { EggBackPointer *back = (*bpi); - if (back != (EggBackPointer *)NULL) { + if (back != nullptr) { EggJointPointer *joint; DCAST_INTO_R(joint, back, false); if (!joint->do_rebuild(db)) { @@ -307,7 +309,7 @@ optimize() { BackPointers::iterator bpi; for (bpi = _back_pointers.begin(); bpi != _back_pointers.end(); ++bpi) { EggBackPointer *back = (*bpi); - if (back != (EggBackPointer *)NULL) { + if (back != nullptr) { EggJointPointer *joint; DCAST_INTO_V(joint, back); joint->optimize(); @@ -330,7 +332,7 @@ expose(EggGroup::DCSType dcs_type) { BackPointers::iterator bpi; for (bpi = _back_pointers.begin(); bpi != _back_pointers.end(); ++bpi) { EggBackPointer *back = (*bpi); - if (back != (EggBackPointer *)NULL) { + if (back != nullptr) { EggJointPointer *joint; DCAST_INTO_V(joint, back); joint->expose(dcs_type); @@ -347,7 +349,7 @@ zero_channels(const string &components) { BackPointers::iterator bpi; for (bpi = _back_pointers.begin(); bpi != _back_pointers.end(); ++bpi) { EggBackPointer *back = (*bpi); - if (back != (EggBackPointer *)NULL) { + if (back != nullptr) { EggJointPointer *joint; DCAST_INTO_V(joint, back); joint->zero_channels(components); @@ -364,7 +366,7 @@ quantize_channels(const string &components, double quantum) { BackPointers::iterator bpi; for (bpi = _back_pointers.begin(); bpi != _back_pointers.end(); ++bpi) { EggBackPointer *back = (*bpi); - if (back != (EggBackPointer *)NULL) { + if (back != nullptr) { EggJointPointer *joint; DCAST_INTO_V(joint, back); joint->quantize_channels(components, quantum); @@ -391,7 +393,7 @@ apply_default_pose(int source_model, int frame) { BackPointers::iterator bpi; for (bpi = _back_pointers.begin(); bpi != _back_pointers.end(); ++bpi) { EggBackPointer *back = (*bpi); - if (back != (EggBackPointer *)NULL) { + if (back != nullptr) { EggJointPointer *joint; DCAST_INTO_V(joint, back); joint->apply_default_pose(source_joint, frame); @@ -411,7 +413,7 @@ apply_default_pose(int source_model, int frame) { */ void EggJointData:: add_back_pointer(int model_index, EggObject *egg_object) { - nassertv(egg_object != (EggObject *)NULL); + nassertv(egg_object != nullptr); if (egg_object->is_of_type(EggGroup::get_class_type())) { // It must be a . EggJointNodePointer *joint = new EggJointNodePointer(egg_object); @@ -442,7 +444,7 @@ add_back_pointer(int model_index, EggObject *egg_object) { * */ void EggJointData:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "Joint " << get_name() << " (models:"; @@ -488,7 +490,7 @@ calc_new_parent_depth(pset &chain) { if (_got_new_parent_depth) { return false; } - if (_new_parent == (EggJointData *)NULL) { + if (_new_parent == nullptr) { // Here's the top of the new hierarchy. _got_new_parent_depth = true; _new_parent_depth = 0; @@ -537,7 +539,7 @@ do_compute_reparent(int model_index, int n, EggCharacterDb &db) { } EggBackPointer *back = get_model(model_index); - if (back == (EggBackPointer *)NULL) { + if (back == nullptr) { // This joint doesn't have any data to modify. _computed_ok = true; return true; @@ -547,11 +549,11 @@ do_compute_reparent(int model_index, int n, EggCharacterDb &db) { DCAST_INTO_R(joint, back, false); LMatrix4d transform; - if (_parent == (EggJointData *)NULL) { + if (_parent == nullptr) { // We are moving from outside the joint hierarchy to within it. transform = _new_parent->get_new_net_frame_inv(model_index, n, db); - } else if (_new_parent == (EggJointData *)NULL) { + } else if (_new_parent == nullptr) { // We are moving from within the hierarchy to outside it. transform = _parent->get_net_frame(model_index, n, db); @@ -577,8 +579,8 @@ bool EggJointData:: do_joint_rebuild(int model_index, EggCharacterDb &db) { bool all_ok = true; - EggJointPointer *parent_joint = NULL; - if (_new_parent != NULL && _new_parent->has_model(model_index)) { + EggJointPointer *parent_joint = nullptr; + if (_new_parent != nullptr && _new_parent->has_model(model_index)) { DCAST_INTO_R(parent_joint, _new_parent->get_model(model_index), false); } @@ -601,8 +603,8 @@ void EggJointData:: do_finish_reparent() { int num_models = get_num_models(); for (int model_index = 0; model_index < num_models; model_index++) { - EggJointPointer *parent_joint = NULL; - if (_new_parent != NULL && _new_parent->has_model(model_index)) { + EggJointPointer *parent_joint = nullptr; + if (_new_parent != nullptr && _new_parent->has_model(model_index)) { DCAST_INTO_V(parent_joint, _new_parent->get_model(model_index)); } @@ -614,7 +616,7 @@ do_finish_reparent() { } _parent = _new_parent; - if (_parent != (EggJointData *)NULL) { + if (_parent != nullptr) { _parent->_children.push_back(this); } } @@ -636,7 +638,7 @@ make_new_joint(const string &name) { for (int i = 0; i < num_models; i++) { if (has_model(i)) { EggJointPointer *joint; - DCAST_INTO_R(joint, get_model(i), NULL); + DCAST_INTO_R(joint, get_model(i), nullptr); EggJointPointer *new_joint = joint->make_new_joint(name); child->set_model(i, new_joint); } @@ -658,12 +660,12 @@ find_joint_exact(const string &name) { return child; } EggJointData *result = child->find_joint_exact(name); - if (result != (EggJointData *)NULL) { + if (result != nullptr) { return result; } } - return (EggJointData *)NULL; + return nullptr; } /** @@ -679,12 +681,12 @@ find_joint_matches(const string &name) { return child; } EggJointData *result = child->find_joint_matches(name); - if (result != (EggJointData *)NULL) { + if (result != nullptr) { return result; } } - return (EggJointData *)NULL; + return nullptr; } /** @@ -698,7 +700,7 @@ is_new_ancestor(EggJointData *child) const { return true; } - if (child->_new_parent == (EggJointData *)NULL) { + if (child->_new_parent == nullptr) { return false; } @@ -714,7 +716,7 @@ const LMatrix4d &EggJointData:: get_new_net_frame(int model_index, int n, EggCharacterDb &db) { if (!_got_new_net_frame) { _new_net_frame = get_new_frame(model_index, n, db); - if (_new_parent != (EggJointData *)NULL) { + if (_new_parent != nullptr) { _new_net_frame = _new_net_frame * _new_parent->get_new_net_frame(model_index, n, db); } _got_new_net_frame = true; @@ -729,7 +731,7 @@ const LMatrix4d &EggJointData:: get_new_net_frame_inv(int model_index, int n, EggCharacterDb &db) { if (!_got_new_net_frame_inv) { _new_net_frame_inv.invert_from(get_new_frame(model_index, n, db)); - if (_new_parent != (EggJointData *)NULL) { + if (_new_parent != nullptr) { _new_net_frame_inv = _new_parent->get_new_net_frame_inv(model_index, n, db) * _new_net_frame_inv; } _got_new_net_frame_inv = true; @@ -747,7 +749,7 @@ get_new_frame(int model_index, int n, EggCharacterDb &db) { do_compute_reparent(model_index, n, db); EggBackPointer *back = get_model(model_index); - if (back == (EggBackPointer *)NULL) { + if (back == nullptr) { return LMatrix4d::ident_mat(); } diff --git a/pandatool/src/eggcharbase/eggJointData.h b/pandatool/src/eggcharbase/eggJointData.h index aff56459cc..bf9cf7b3d1 100644 --- a/pandatool/src/eggcharbase/eggJointData.h +++ b/pandatool/src/eggcharbase/eggJointData.h @@ -36,7 +36,7 @@ public: INLINE EggJointData *get_parent() const; INLINE int get_num_children() const; INLINE EggJointData *get_child(int n) const; - INLINE EggJointData *find_joint(const string &name); + INLINE EggJointData *find_joint(const std::string &name); LMatrix4d get_frame(int model_index, int n) const; LMatrix4d get_net_frame(int model_index, int n, EggCharacterDb &db) const; @@ -54,12 +54,12 @@ public: bool do_rebuild_all(EggCharacterDb &db); void optimize(); void expose(EggGroup::DCSType dcs_type = EggGroup::DC_default); - void zero_channels(const string &components); - void quantize_channels(const string &components, double quantum); + void zero_channels(const std::string &components); + void quantize_channels(const std::string &components, double quantum); void apply_default_pose(int source_model, int frame); virtual void add_back_pointer(int model_index, EggObject *egg_object); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; protected: void do_begin_reparent(); @@ -70,9 +70,9 @@ protected: void do_finish_reparent(); private: - EggJointData *make_new_joint(const string &name); - EggJointData *find_joint_exact(const string &name); - EggJointData *find_joint_matches(const string &name); + EggJointData *make_new_joint(const std::string &name); + EggJointData *find_joint_exact(const std::string &name); + EggJointData *find_joint_matches(const std::string &name); bool is_new_ancestor(EggJointData *child) const; const LMatrix4d &get_new_net_frame(int model_index, int n, EggCharacterDb &db); diff --git a/pandatool/src/eggcharbase/eggJointNodePointer.cxx b/pandatool/src/eggcharbase/eggJointNodePointer.cxx index 3ebc85c3d4..c9c891606b 100644 --- a/pandatool/src/eggcharbase/eggJointNodePointer.cxx +++ b/pandatool/src/eggcharbase/eggJointNodePointer.cxx @@ -28,7 +28,7 @@ EggJointNodePointer:: EggJointNodePointer(EggObject *object) { _joint = DCAST(EggGroup, object); - if (_joint != (EggGroup *)NULL && _joint->is_joint()) { + if (_joint != nullptr && _joint->is_joint()) { // Quietly insist that the joint has a transform, for neatness. If it // does not, give it the identity transform. if (!_joint->has_transform()) { @@ -83,10 +83,10 @@ set_frame(int n, const LMatrix4d &mat) { */ void EggJointNodePointer:: do_finish_reparent(EggJointPointer *new_parent) { - if (new_parent == (EggJointPointer *)NULL) { + if (new_parent == nullptr) { // No new parent; unparent the joint. EggGroupNode *egg_parent = _joint->get_parent(); - if (egg_parent != (EggGroupNode *)NULL) { + if (egg_parent != nullptr) { egg_parent->remove_child(_joint.p()); egg_parent->steal_children(*_joint); } @@ -107,7 +107,7 @@ do_finish_reparent(EggJointPointer *new_parent) { */ void EggJointNodePointer:: move_vertices_to(EggJointPointer *new_joint) { - if (new_joint == (EggJointPointer *)NULL) { + if (new_joint == nullptr) { _joint->unref_all_vertices(); } else { @@ -150,7 +150,7 @@ do_rebuild(EggCharacterDb &db) { */ void EggJointNodePointer:: expose(EggGroup::DCSType dcs_type) { - if (_joint != (EggGroup *)NULL) { + if (_joint != nullptr) { _joint->set_dcs_type(dcs_type); } } @@ -161,7 +161,7 @@ expose(EggGroup::DCSType dcs_type) { */ void EggJointNodePointer:: apply_default_pose(EggJointPointer *source_joint, int frame) { - if (_joint != (EggGroup *)NULL) { + if (_joint != nullptr) { LMatrix4d pose; if (frame >= 0 && frame < source_joint->get_num_frames()) { pose = source_joint->get_frame(frame); @@ -180,7 +180,7 @@ apply_default_pose(EggJointPointer *source_joint, int frame) { */ bool EggJointNodePointer:: has_vertices() const { - if (_joint != (EggGroup *)NULL) { + if (_joint != nullptr) { return (_joint->vref_size() != 0) || _joint->joint_has_primitives(); } @@ -192,7 +192,7 @@ has_vertices() const { * pointer to it. */ EggJointPointer *EggJointNodePointer:: -make_new_joint(const string &name) { +make_new_joint(const std::string &name) { EggGroup *new_joint = new EggGroup(name); new_joint->set_group_type(EggGroup::GT_joint); _joint->add_child(new_joint); @@ -203,6 +203,6 @@ make_new_joint(const string &name) { * Applies the indicated name change to the egg file. */ void EggJointNodePointer:: -set_name(const string &name) { +set_name(const std::string &name) { _joint->set_name(name); } diff --git a/pandatool/src/eggcharbase/eggJointNodePointer.h b/pandatool/src/eggcharbase/eggJointNodePointer.h index 52aacbd042..8a979f11d5 100644 --- a/pandatool/src/eggcharbase/eggJointNodePointer.h +++ b/pandatool/src/eggcharbase/eggJointNodePointer.h @@ -41,9 +41,9 @@ public: virtual bool has_vertices() const; - virtual EggJointPointer *make_new_joint(const string &name); + virtual EggJointPointer *make_new_joint(const std::string &name); - virtual void set_name(const string &name); + virtual void set_name(const std::string &name); private: PT(EggGroup) _joint; diff --git a/pandatool/src/eggcharbase/eggJointPointer.cxx b/pandatool/src/eggcharbase/eggJointPointer.cxx index 350931d635..6a5ed44003 100644 --- a/pandatool/src/eggcharbase/eggJointPointer.cxx +++ b/pandatool/src/eggcharbase/eggJointPointer.cxx @@ -69,7 +69,7 @@ expose(EggGroup::DCSType) { * Zeroes out the named components of the transform in the animation frames. */ void EggJointPointer:: -zero_channels(const string &) { +zero_channels(const std::string &) { } /** @@ -77,7 +77,7 @@ zero_channels(const string &) { * quantum. */ void EggJointPointer:: -quantize_channels(const string &, double) { +quantize_channels(const std::string &, double) { } /** diff --git a/pandatool/src/eggcharbase/eggJointPointer.h b/pandatool/src/eggcharbase/eggJointPointer.h index cbb759c9d4..94a8a3180e 100644 --- a/pandatool/src/eggcharbase/eggJointPointer.h +++ b/pandatool/src/eggcharbase/eggJointPointer.h @@ -42,11 +42,11 @@ public: virtual void optimize(); virtual void expose(EggGroup::DCSType dcs_type); - virtual void zero_channels(const string &components); - virtual void quantize_channels(const string &components, double quantum); + virtual void zero_channels(const std::string &components); + virtual void quantize_channels(const std::string &components, double quantum); virtual void apply_default_pose(EggJointPointer *source_joint, int frame); - virtual EggJointPointer *make_new_joint(const string &name)=0; + virtual EggJointPointer *make_new_joint(const std::string &name)=0; public: static TypeHandle get_class_type() { diff --git a/pandatool/src/eggcharbase/eggMatrixTablePointer.cxx b/pandatool/src/eggcharbase/eggMatrixTablePointer.cxx index c81ae1bd1a..21c9c63516 100644 --- a/pandatool/src/eggcharbase/eggMatrixTablePointer.cxx +++ b/pandatool/src/eggcharbase/eggMatrixTablePointer.cxx @@ -17,6 +17,8 @@ #include "eggXfmAnimData.h" #include "eggXfmSAnim.h" +using std::string; + TypeHandle EggMatrixTablePointer::_type_handle; /** @@ -26,7 +28,7 @@ EggMatrixTablePointer:: EggMatrixTablePointer(EggObject *object) { _table = DCAST(EggTable, object); - if (_table != (EggTable *)NULL) { + if (_table != nullptr) { // Now search for the child named "xform". This contains the actual table // data. EggGroupNode::iterator ci; @@ -58,7 +60,7 @@ EggMatrixTablePointer(EggObject *object) { */ double EggMatrixTablePointer:: get_frame_rate() const { - if (_xform == (EggXfmSAnim *)NULL || !_xform->has_fps()) { + if (_xform == nullptr || !_xform->has_fps()) { return 0.0; } else { return _xform->get_fps(); @@ -70,7 +72,7 @@ get_frame_rate() const { */ int EggMatrixTablePointer:: get_num_frames() const { - if (_xform == (EggXfmSAnim *)NULL) { + if (_xform == nullptr) { return 0; } else { return _xform->get_num_rows(); @@ -82,7 +84,7 @@ get_num_frames() const { */ void EggMatrixTablePointer:: extend_to(int num_frames) { - nassertv(_xform != (EggXfmSAnim *)NULL); + nassertv(_xform != nullptr); _xform->normalize(); int num_rows = _xform->get_num_rows(); LMatrix4d last_mat; @@ -136,7 +138,7 @@ set_frame(int n, const LMatrix4d &mat) { */ bool EggMatrixTablePointer:: add_frame(const LMatrix4d &mat) { - if (_xform == (EggXfmSAnim *)NULL) { + if (_xform == nullptr) { return false; } @@ -149,10 +151,10 @@ add_frame(const LMatrix4d &mat) { */ void EggMatrixTablePointer:: do_finish_reparent(EggJointPointer *new_parent) { - if (new_parent == (EggJointPointer *)NULL) { + if (new_parent == nullptr) { // No new parent; unparent the joint. EggGroupNode *egg_parent = _table->get_parent(); - if (egg_parent != (EggGroupNode *)NULL) { + if (egg_parent != nullptr) { egg_parent->remove_child(_table.p()); } @@ -184,7 +186,7 @@ do_rebuild(EggCharacterDb &db) { return true; } - if (_xform == (EggXfmSAnim *)NULL) { + if (_xform == nullptr) { return false; } @@ -213,7 +215,7 @@ do_rebuild(EggCharacterDb &db) { */ void EggMatrixTablePointer:: optimize() { - if (_xform != (EggXfmSAnim *)NULL) { + if (_xform != nullptr) { _xform->optimize(); } } @@ -223,7 +225,7 @@ optimize() { */ void EggMatrixTablePointer:: zero_channels(const string &components) { - if (_xform == (EggXfmSAnim *)NULL) { + if (_xform == nullptr) { return; } @@ -233,7 +235,7 @@ zero_channels(const string &components) { for (si = components.begin(); si != components.end(); ++si) { string table_name(1, *si); EggNode *child = _xform->find_child(table_name); - if (child != (EggNode *)NULL) { + if (child != nullptr) { _xform->remove_child(child); } } @@ -245,7 +247,7 @@ zero_channels(const string &components) { */ void EggMatrixTablePointer:: quantize_channels(const string &components, double quantum) { - if (_xform == (EggXfmSAnim *)NULL) { + if (_xform == nullptr) { return; } @@ -255,7 +257,7 @@ quantize_channels(const string &components, double quantum) { for (si = components.begin(); si != components.end(); ++si) { string table_name(1, *si); EggNode *child = _xform->find_child(table_name); - if (child != (EggNode *)NULL && + if (child != nullptr && child->is_of_type(EggSAnimData::get_class_type())) { EggSAnimData *anim = DCAST(EggSAnimData, child); anim->quantize(quantum); @@ -272,7 +274,7 @@ make_new_joint(const string &name) { EggTable *new_table = new EggTable(name); _table->add_child(new_table); CoordinateSystem cs = CS_default; - if (_xform != (EggXfmSAnim *)NULL) { + if (_xform != nullptr) { cs = _xform->get_coordinate_system(); } EggXfmSAnim *new_xform = new EggXfmSAnim("xform", cs); diff --git a/pandatool/src/eggcharbase/eggMatrixTablePointer.h b/pandatool/src/eggcharbase/eggMatrixTablePointer.h index c23187955b..cbdeeecc5a 100644 --- a/pandatool/src/eggcharbase/eggMatrixTablePointer.h +++ b/pandatool/src/eggcharbase/eggMatrixTablePointer.h @@ -43,12 +43,12 @@ public: virtual bool do_rebuild(EggCharacterDb &db); virtual void optimize(); - virtual void zero_channels(const string &components); - virtual void quantize_channels(const string &components, double quantum); + virtual void zero_channels(const std::string &components); + virtual void quantize_channels(const std::string &components, double quantum); - virtual EggJointPointer *make_new_joint(const string &name); + virtual EggJointPointer *make_new_joint(const std::string &name); - virtual void set_name(const string &name); + virtual void set_name(const std::string &name); private: PT(EggTable) _table; diff --git a/pandatool/src/eggcharbase/eggScalarTablePointer.cxx b/pandatool/src/eggcharbase/eggScalarTablePointer.cxx index da104af2bd..450bb548ce 100644 --- a/pandatool/src/eggcharbase/eggScalarTablePointer.cxx +++ b/pandatool/src/eggcharbase/eggScalarTablePointer.cxx @@ -31,7 +31,7 @@ EggScalarTablePointer(EggObject *object) { */ double EggScalarTablePointer:: get_frame_rate() const { - if (_data == (EggSAnimData *)NULL || !_data->has_fps()) { + if (_data == nullptr || !_data->has_fps()) { return 0.0; } else { return _data->get_fps(); @@ -43,7 +43,7 @@ get_frame_rate() const { */ int EggScalarTablePointer:: get_num_frames() const { - if (_data == (EggSAnimData *)NULL) { + if (_data == nullptr) { return 0; } else { return _data->get_num_rows(); @@ -55,7 +55,7 @@ get_num_frames() const { */ void EggScalarTablePointer:: extend_to(int num_frames) { - nassertv(_data != (EggSAnimData *)NULL); + nassertv(_data != nullptr); int num_rows = _data->get_num_rows(); double last_value; if (num_rows == 0) { @@ -89,7 +89,7 @@ get_frame(int n) const { * Applies the indicated name change to the egg file. */ void EggScalarTablePointer:: -set_name(const string &name) { +set_name(const std::string &name) { // Actually, let's not rename the slider table (yet), because we haven't // written the code to rename all of the morph targets. diff --git a/pandatool/src/eggcharbase/eggScalarTablePointer.h b/pandatool/src/eggcharbase/eggScalarTablePointer.h index f1cd226c1f..c0a7487973 100644 --- a/pandatool/src/eggcharbase/eggScalarTablePointer.h +++ b/pandatool/src/eggcharbase/eggScalarTablePointer.h @@ -35,7 +35,7 @@ public: virtual void extend_to(int num_frames); virtual double get_frame(int n) const; - virtual void set_name(const string &name); + virtual void set_name(const std::string &name); private: PT(EggSAnimData) _data; diff --git a/pandatool/src/eggcharbase/eggSliderData.cxx b/pandatool/src/eggcharbase/eggSliderData.cxx index d597adcc17..91d041366f 100644 --- a/pandatool/src/eggcharbase/eggSliderData.cxx +++ b/pandatool/src/eggcharbase/eggSliderData.cxx @@ -40,7 +40,7 @@ EggSliderData(EggCharacterCollection *collection, double EggSliderData:: get_frame(int model_index, int n) const { EggBackPointer *back = get_model(model_index); - if (back == (EggBackPointer *)NULL) { + if (back == nullptr) { return 0.0; } @@ -58,7 +58,7 @@ add_back_pointer(int model_index, EggObject *egg_object) { if (egg_object->is_of_type(EggPrimitive::get_class_type())) { // A primitive! EggBackPointer *back = get_model(model_index); - if (back == (EggBackPointer *)NULL) { + if (back == nullptr) { back = new EggVertexPointer(egg_object); set_model(model_index, back); } @@ -66,7 +66,7 @@ add_back_pointer(int model_index, EggObject *egg_object) { } else if (egg_object->is_of_type(EggVertex::get_class_type())) { // A vertex! EggBackPointer *back = get_model(model_index); - if (back == (EggBackPointer *)NULL) { + if (back == nullptr) { back = new EggVertexPointer(egg_object); set_model(model_index, back); } @@ -74,7 +74,7 @@ add_back_pointer(int model_index, EggObject *egg_object) { } else if (egg_object->is_of_type(EggSAnimData::get_class_type())) { // A slider animation table! Woo hoo! EggBackPointer *back = get_model(model_index); - if (back == (EggBackPointer *)NULL) { + if (back == nullptr) { back = new EggScalarTablePointer(egg_object); set_model(model_index, back); } @@ -88,7 +88,7 @@ add_back_pointer(int model_index, EggObject *egg_object) { * */ void EggSliderData:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "Slider " << get_name() << " (models:"; diff --git a/pandatool/src/eggcharbase/eggSliderData.h b/pandatool/src/eggcharbase/eggSliderData.h index 03c1d2fe3f..dd0e4c3486 100644 --- a/pandatool/src/eggcharbase/eggSliderData.h +++ b/pandatool/src/eggcharbase/eggSliderData.h @@ -33,7 +33,7 @@ public: double get_frame(int model_index, int n) const; virtual void add_back_pointer(int model_index, EggObject *egg_object); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: diff --git a/pandatool/src/eggprogs/eggListTextures.cxx b/pandatool/src/eggprogs/eggListTextures.cxx index c804a8110b..fd44c73a48 100644 --- a/pandatool/src/eggprogs/eggListTextures.cxx +++ b/pandatool/src/eggprogs/eggListTextures.cxx @@ -48,10 +48,10 @@ run() { Filename fullpath = (*ti)->get_fullpath(); PNMImageHeader header; if (header.read_header(fullpath)) { - cout << fullpath.get_basename() << " : " + std::cout << fullpath.get_basename() << " : " << header.get_x_size() << " " << header.get_y_size() << "\n"; } else { - cout << fullpath.get_basename() << " : unknown\n"; + std::cout << fullpath.get_basename() << " : unknown\n"; } } } diff --git a/pandatool/src/eggprogs/eggMakeTube.cxx b/pandatool/src/eggprogs/eggMakeTube.cxx index 37adfd8d59..7017e97dcd 100644 --- a/pandatool/src/eggprogs/eggMakeTube.cxx +++ b/pandatool/src/eggprogs/eggMakeTube.cxx @@ -36,7 +36,7 @@ EggMakeTube() { add_option ("a", "x,y,z", 0, "Specify the first endpoint of the tube.", - &EggWriter::dispatch_double_triple, NULL, _point_a); + &EggWriter::dispatch_double_triple, nullptr, _point_a); add_option ("b", "x,y,z", 0, @@ -47,23 +47,23 @@ EggMakeTube() { ("r", "radius", 0, "Specify the radius of the tube. The tube will extend beyond " "the endpoints in each direction by the amount of radius.", - &EggWriter::dispatch_double, NULL, &_radius); + &EggWriter::dispatch_double, nullptr, &_radius); add_option ("slices", "count", 0, "Specify the number of slices appearing radially around the tube.", - &EggWriter::dispatch_int, NULL, &_num_slices); + &EggWriter::dispatch_int, nullptr, &_num_slices); add_option ("crings", "count", 0, "Specify the number of rings appearing in each endcap of the tube.", - &EggWriter::dispatch_int, NULL, &_num_crings); + &EggWriter::dispatch_int, nullptr, &_num_crings); add_option ("trings", "count", 0, "Specify the number of rings appearing in the cylindrical body " "of the tube.", - &EggWriter::dispatch_int, NULL, &_num_trings); + &EggWriter::dispatch_int, nullptr, &_num_trings); _point_a[0] = 0.0; _point_a[1] = 0.0; @@ -111,8 +111,8 @@ run() { EggVertex *vtx_2; for (ri = 0; ri < _num_crings; ri++) { - vtx_1 = NULL; - vtx_2 = NULL; + vtx_1 = nullptr; + vtx_2 = nullptr; for (si = 0; si <= _num_slices; si++) { EggVertex *vtx_3 = calc_sphere1_vertex(ri, si); EggVertex *vtx_4 = calc_sphere1_vertex(ri + 1, si); @@ -125,8 +125,8 @@ run() { // Now the cylinder sides. if (_length != 0.0) { for (ri = 0; ri < _num_trings; ri++) { - vtx_1 = NULL; - vtx_2 = NULL; + vtx_1 = nullptr; + vtx_2 = nullptr; for (si = 0; si <= _num_slices; si++) { EggVertex *vtx_3 = calc_tube_vertex(ri, si); EggVertex *vtx_4 = calc_tube_vertex(ri + 1, si); @@ -139,8 +139,8 @@ run() { // And the second endcap. for (ri = _num_crings - 1; ri >= 0; ri--) { - vtx_1 = NULL; - vtx_2 = NULL; + vtx_1 = nullptr; + vtx_2 = nullptr; for (si = 0; si <= _num_slices; si++) { EggVertex *vtx_3 = calc_sphere2_vertex(ri + 1, si); EggVertex *vtx_4 = calc_sphere2_vertex(ri, si); @@ -244,7 +244,7 @@ calc_sphere2_vertex(int ri, int si) { */ void EggMakeTube:: add_polygon(EggVertex *a, EggVertex *b, EggVertex *c, EggVertex *d) { - if (a == (EggVertex *)NULL) { + if (a == nullptr) { return; } diff --git a/pandatool/src/eggprogs/eggRename.cxx b/pandatool/src/eggprogs/eggRename.cxx index abde299e2d..532f096dbb 100644 --- a/pandatool/src/eggprogs/eggRename.cxx +++ b/pandatool/src/eggprogs/eggRename.cxx @@ -26,7 +26,7 @@ EggRename() { add_option ("strip_prefix", "name", 0, "strips out the prefix that is put on all nodes, by maya ext. ref", - &EggRename::dispatch_vector_string, NULL, &_strip_prefix); + &EggRename::dispatch_vector_string, nullptr, &_strip_prefix); } /** diff --git a/pandatool/src/eggprogs/eggRetargetAnim.cxx b/pandatool/src/eggprogs/eggRetargetAnim.cxx index f354eb57b9..ba55d19b7f 100644 --- a/pandatool/src/eggprogs/eggRetargetAnim.cxx +++ b/pandatool/src/eggprogs/eggRetargetAnim.cxx @@ -48,13 +48,13 @@ EggRetargetAnim() { ("r", "file.egg", 0, "Read the reference model from the indicated egg file. All of the " "animations will be retargeted to match the indicated file.", - &EggRetargetAnim::dispatch_filename, NULL, &_reference_filename); + &EggRetargetAnim::dispatch_filename, nullptr, &_reference_filename); add_option ("keep", "joint[,joint...]", 0, "Preserve the full animation on the named joint(s). This is especially " "appropriate for the root joint.", - &EggRetargetAnim::dispatch_vector_string_comma, NULL, &_keep_joints); + &EggRetargetAnim::dispatch_vector_string_comma, nullptr, &_keep_joints); } /** @@ -62,7 +62,7 @@ EggRetargetAnim() { */ void EggRetargetAnim:: run() { - nassertv(_collection != (EggCharacterCollection *)NULL); + nassertv(_collection != nullptr); nassertv(_collection->get_num_eggs() > 0); if (_reference_filename.empty()) { @@ -78,7 +78,7 @@ run() { // Read in the extra egg file that we use for extracting the references out. PT(EggData) reference_egg = read_egg(_reference_filename); - if (reference_egg == (EggData *)NULL) { + if (reference_egg == nullptr) { nout << "Cannot read " << _reference_filename << "\n"; exit(1); } @@ -97,7 +97,7 @@ run() { exit(1); } - string ref_name = col.get_character(0)->get_name(); + std::string ref_name = col.get_character(0)->get_name(); // Now rename all of the animations to the same name as the reference model, // and add the reference animation in to the same collection to match it up @@ -111,7 +111,7 @@ run() { EggCharacterData *char_data = _collection->get_character(0); nout << "Processing " << char_data->get_name() << "\n"; - typedef pset Names; + typedef pset Names; Names keep_names; vector_string::const_iterator si; @@ -133,7 +133,7 @@ run() { */ void EggRetargetAnim:: retarget_anim(EggCharacterData *char_data, EggJointData *joint_data, - int reference_model, const pset &keep_names, + int reference_model, const pset &keep_names, EggCharacterDb &db) { if (keep_names.find(joint_data->get_name()) != keep_names.end()) { // Don't retarget this joint; keep the translation and scale and whatever. @@ -146,7 +146,7 @@ retarget_anim(EggCharacterData *char_data, EggJointData *joint_data, int num_frames = char_data->get_num_frames(i); EggBackPointer *back = joint_data->get_model(i); - nassertv(back != (EggBackPointer *)NULL); + nassertv(back != nullptr); EggJointPointer *joint; DCAST_INTO_V(joint, back); diff --git a/pandatool/src/eggprogs/eggRetargetAnim.h b/pandatool/src/eggprogs/eggRetargetAnim.h index bf9d94cd38..455942ae94 100644 --- a/pandatool/src/eggprogs/eggRetargetAnim.h +++ b/pandatool/src/eggprogs/eggRetargetAnim.h @@ -37,7 +37,7 @@ public: void run(); void retarget_anim(EggCharacterData *char_data, EggJointData *joint_data, - int reference_model, const pset &keep_names, + int reference_model, const pset &keep_names, EggCharacterDb &db); Filename _reference_filename; diff --git a/pandatool/src/eggprogs/eggTextureCards.cxx b/pandatool/src/eggprogs/eggTextureCards.cxx index 03cb811809..bb3350f02c 100644 --- a/pandatool/src/eggprogs/eggTextureCards.cxx +++ b/pandatool/src/eggprogs/eggTextureCards.cxx @@ -22,6 +22,8 @@ #include +using std::string; + /** * */ @@ -49,7 +51,7 @@ EggTextureCards() : EggWriter(true, true) { "centered on the origin: -0.5,0.5,-0.5,0.5. Polygons are always created " "on the X-Y plane. If -p is not also specified, all polygons will be " "the same size and shape.", - &EggTextureCards::dispatch_double_quad, NULL, &_polygon_geometry[0]); + &EggTextureCards::dispatch_double_quad, nullptr, &_polygon_geometry[0]); add_option ("p", "xpixels,ypixels", 0, @@ -70,44 +72,44 @@ EggTextureCards() : EggWriter(true, true) { "This option specifies an ignorable suffix in the texture filename(s); " "if this suffix is present, it is not included in the polygon's name. " "This option may be repeated multiple times.", - &EggTextureCards::dispatch_vector_string, NULL, &_suffixes); + &EggTextureCards::dispatch_vector_string, nullptr, &_suffixes); add_option ("c", "r,g,b[,a]", 0, "Specifies the color of each polygon. The default is white: 1,1,1,1.", - &EggTextureCards::dispatch_color, NULL, &_polygon_color[0]); + &EggTextureCards::dispatch_color, nullptr, &_polygon_color[0]); add_option ("wm", "wrap", 0, "Indicates the wrap mode of the texture: \"repeat\", \"clamp\", " "or any of the other modes supported by egg syntax. " "The default is to leave this unspecified.", - &EggTextureCards::dispatch_wrap_mode, NULL, &_wrap_mode); + &EggTextureCards::dispatch_wrap_mode, nullptr, &_wrap_mode); add_option ("wmu", "wrap_u", 0, "Indicates the wrap mode of the texture in the U direction. This " "overrides -wm, if specified.", - &EggTextureCards::dispatch_wrap_mode, NULL, &_wrap_u); + &EggTextureCards::dispatch_wrap_mode, nullptr, &_wrap_u); add_option ("wmv", "wrap_v", 0, "Indicates the wrap mode of the texture in the V direction. This " "overrides -wm, if specified.", - &EggTextureCards::dispatch_wrap_mode, NULL, &_wrap_v); + &EggTextureCards::dispatch_wrap_mode, nullptr, &_wrap_v); add_option ("minf", "filter", 0, "Indicates the minfilter mode of the texture: \"linear\", \"mipmap\", " "or any of the other modes supported by egg syntax. " "The default is to leave this unspecified.", - &EggTextureCards::dispatch_filter_type, NULL, &_minfilter); + &EggTextureCards::dispatch_filter_type, nullptr, &_minfilter); add_option ("magf", "filter", 0, "Indicates the magfilter mode of the texture: \"linear\" or \"nearest\". " "The default is to leave this unspecified.", - &EggTextureCards::dispatch_filter_type, NULL, &_magfilter); + &EggTextureCards::dispatch_filter_type, nullptr, &_magfilter); add_option ("aniso", "degree", 0, @@ -119,37 +121,37 @@ EggTextureCards() : EggWriter(true, true) { ("ql", "[default | fastest | normal | best]", 0, "Specifies the quality level of the texture. This mainly affects " "the tinydisplay software renderer.", - &EggTextureCards::dispatch_quality_level, NULL, &_quality_level); + &EggTextureCards::dispatch_quality_level, nullptr, &_quality_level); add_option ("f", "format", 0, "Indicates the format for all textures: typical choices are \"rgba12\" " "or \"rgb5\" or \"alpha\". The default is to leave this unspecified.", - &EggTextureCards::dispatch_format, NULL, &_format); + &EggTextureCards::dispatch_format, nullptr, &_format); add_option ("f1", "format", 0, "Indicates the format for one-channel textures only. If specified, this " "overrides the format specified by -f.", - &EggTextureCards::dispatch_format, NULL, &_format_1); + &EggTextureCards::dispatch_format, nullptr, &_format_1); add_option ("f2", "format", 0, "Indicates the format for two-channel textures only. If specified, this " "overrides the format specified by -f.", - &EggTextureCards::dispatch_format, NULL, &_format_2); + &EggTextureCards::dispatch_format, nullptr, &_format_2); add_option ("f3", "format", 0, "Indicates the format for three-channel textures only. If specified, this " "overrides the format specified by -f.", - &EggTextureCards::dispatch_format, NULL, &_format_3); + &EggTextureCards::dispatch_format, nullptr, &_format_3); add_option ("f4", "format", 0, "Indicates the format for four-channel textures only. If specified, this " "overrides the format specified by -f.", - &EggTextureCards::dispatch_format, NULL, &_format_4); + &EggTextureCards::dispatch_format, nullptr, &_format_4); add_option ("b", "", 0, @@ -164,7 +166,7 @@ EggTextureCards() : EggWriter(true, true) { "nice side-effect of creating an automatic texture flip that can be " "used directly by applications; use this parameter to specify the " "frame rate of that texture flip.", - &EggTextureCards::dispatch_double, NULL, &_frame_rate); + &EggTextureCards::dispatch_double, nullptr, &_frame_rate); add_option ("noexist", "", 0, diff --git a/pandatool/src/eggprogs/eggTextureCards.h b/pandatool/src/eggprogs/eggTextureCards.h index f3adde8b34..c30e926d8e 100644 --- a/pandatool/src/eggprogs/eggTextureCards.h +++ b/pandatool/src/eggprogs/eggTextureCards.h @@ -36,10 +36,10 @@ public: protected: virtual bool handle_args(Args &args); - static bool dispatch_wrap_mode(const string &opt, const string &arg, void *var); - static bool dispatch_filter_type(const string &opt, const string &arg, void *var); - static bool dispatch_quality_level(const string &opt, const string &arg, void *var); - static bool dispatch_format(const string &opt, const string &arg, void *var); + static bool dispatch_wrap_mode(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_filter_type(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_quality_level(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_format(const std::string &opt, const std::string &arg, void *var); private: bool scan_texture(const Filename &filename, LVecBase4d &geometry, diff --git a/pandatool/src/eggprogs/eggToC.cxx b/pandatool/src/eggprogs/eggToC.cxx index 28fcb2f36e..bafc37fde9 100644 --- a/pandatool/src/eggprogs/eggToC.cxx +++ b/pandatool/src/eggprogs/eggToC.cxx @@ -22,6 +22,9 @@ #include "eggBin.h" #include "string_utils.h" +using std::ostream; +using std::string; + /** * */ @@ -158,7 +161,7 @@ write_vertex_pool(EggVertexPool *vpool) { << "] = {\n"; for (i = 0; i < highest_index; i++) { EggVertex *vert = vpool->get_vertex(i); - if (vert == (EggVertex *)NULL) { + if (vert == nullptr) { out << " vertex(), /* " << i << " */\n"; } else { LPoint4d p = vert->get_pos4(); @@ -196,7 +199,7 @@ write_vertex_pool(EggVertexPool *vpool) { << "] = {\n"; for (i = 0; i < highest_index; i++) { EggVertex *vert = vpool->get_vertex(i); - if (vert == (EggVertex *)NULL || !vert->has_uv()) { + if (vert == nullptr || !vert->has_uv()) { out << " uv(), /* " << i << " */\n"; } else { LTexCoordd uv = vert->get_uv(); @@ -213,7 +216,7 @@ write_vertex_pool(EggVertexPool *vpool) { << "] = {\n"; for (i = 0; i < highest_index; i++) { EggVertex *vert = vpool->get_vertex(i); - if (vert == (EggVertex *)NULL || !vert->has_normal()) { + if (vert == nullptr || !vert->has_normal()) { out << " normal(), /* " << i << " */\n"; } else { LNormald n = vert->get_normal(); @@ -230,7 +233,7 @@ write_vertex_pool(EggVertexPool *vpool) { << "] = {\n"; for (i = 0; i < highest_index; i++) { EggVertex *vert = vpool->get_vertex(i); - if (vert == (EggVertex *)NULL || !vert->has_color()) { + if (vert == nullptr || !vert->has_color()) { out << " color(), /* " << i << " */\n"; } else { LColor c = vert->get_color(); diff --git a/pandatool/src/eggprogs/eggTopstrip.cxx b/pandatool/src/eggprogs/eggTopstrip.cxx index e0bbcf4e7e..2a46431f25 100644 --- a/pandatool/src/eggprogs/eggTopstrip.cxx +++ b/pandatool/src/eggprogs/eggTopstrip.cxx @@ -44,7 +44,7 @@ EggTopstrip() { ("t", "name", 0, "Specify the name of the 'top' joint, from which to draw the " "animation channels which will be applied to the entire animation.", - &EggTopstrip::dispatch_string, NULL, &_top_joint_name); + &EggTopstrip::dispatch_string, nullptr, &_top_joint_name); add_option ("i", "", 0, @@ -64,13 +64,13 @@ EggTopstrip() { "any combination of the nine token letters: i, j, k represent the " "three scale axes; h, p, r represent rotation; and x, y, z represent " "translation. The default is everything: -s ijkphrxyz.", - &EggTopstrip::dispatch_string, NULL, &_transform_channels); + &EggTopstrip::dispatch_string, nullptr, &_transform_channels); add_option ("r", "file.egg", 0, "Read the animation channel from the indicated egg file. If this " "is not specified, each egg file will supply its own animation channel.", - &EggTopstrip::dispatch_filename, NULL, &_channel_filename); + &EggTopstrip::dispatch_filename, nullptr, &_channel_filename); _invert_transform = true; _transform_channels = "ijkphrxyz"; @@ -81,7 +81,7 @@ EggTopstrip() { */ void EggTopstrip:: run() { - nassertv(_collection != (EggCharacterCollection *)NULL); + nassertv(_collection != nullptr); nassertv(_collection->get_num_eggs() > 0); check_transform_channels(); @@ -97,7 +97,7 @@ run() { if (!_channel_filename.empty()) { // Read in the extra egg file that we use for extracting the channels out. PT(EggData) channel_egg = read_egg(_channel_filename); - if (channel_egg == (EggData *)NULL) { + if (channel_egg == nullptr) { nout << "Cannot read " << _channel_filename << "\n"; exit(1); } @@ -134,7 +134,7 @@ run() { } // Determine which joint we'll use to extract the transform to apply. - EggJointData *top_joint = (EggJointData *)NULL; + EggJointData *top_joint = nullptr; if (_top_joint_name.empty()) { // The default top joint name is the alphabetically first joint in the // top level. @@ -145,7 +145,7 @@ run() { top_joint = root_joint->get_child(0); } else { top_joint = from_char->find_joint(_top_joint_name); - if (top_joint == (EggJointData *)NULL) { + if (top_joint == nullptr) { nout << "Character " << from_char->get_name() << " has no joint named " << _top_joint_name << "\n"; exit(1); @@ -185,14 +185,14 @@ run() { */ void EggTopstrip:: check_transform_channels() { - static string expected = "ijkphrxyz"; + static std::string expected = "ijkphrxyz"; static const int num_channels = 9; bool has_each[num_channels]; memset(has_each, 0, num_channels * sizeof(bool)); for (size_t p = 0; p < _transform_channels.size(); p++) { int i = expected.find(_transform_channels[p]); - if (i == (int)string::npos) { + if (i == (int)std::string::npos) { nout << "Invalid letter for -s: " << _transform_channels[p] << "\n"; exit(1); } @@ -235,10 +235,10 @@ strip_anim(EggCharacterData *char_data, EggJointData *joint_data, int num_into_frames = char_data->get_num_frames(i); int num_from_frames = from_char->get_num_frames(model); - int num_frames = max(num_into_frames, num_from_frames); + int num_frames = std::max(num_into_frames, num_from_frames); EggBackPointer *back = joint_data->get_model(i); - nassertv(back != (EggBackPointer *)NULL); + nassertv(back != nullptr); EggJointPointer *joint; DCAST_INTO_V(joint, back); diff --git a/pandatool/src/eggprogs/eggTopstrip.h b/pandatool/src/eggprogs/eggTopstrip.h index efdd4c0e82..8e04b7e0af 100644 --- a/pandatool/src/eggprogs/eggTopstrip.h +++ b/pandatool/src/eggprogs/eggTopstrip.h @@ -48,10 +48,10 @@ public: void adjust_transform(LMatrix4d &mat) const; - string _top_joint_name; + std::string _top_joint_name; bool _got_invert_transform; bool _invert_transform; - string _transform_channels; + std::string _transform_channels; Filename _channel_filename; }; diff --git a/pandatool/src/flt/fltBead.cxx b/pandatool/src/flt/fltBead.cxx index bfa5b3f656..8cc21f8c4f 100644 --- a/pandatool/src/flt/fltBead.cxx +++ b/pandatool/src/flt/fltBead.cxx @@ -100,7 +100,7 @@ get_num_transform_steps() const { FltTransformRecord *FltBead:: get_transform_step(int n) { nassertr(n >= 0 && n < (int)_transform_steps.size(), - (FltTransformRecord *)NULL); + nullptr); return _transform_steps[n]; } @@ -111,7 +111,7 @@ get_transform_step(int n) { const FltTransformRecord *FltBead:: get_transform_step(int n) const { nassertr(n >= 0 && n < (int)_transform_steps.size(), - (const FltTransformRecord *)NULL); + nullptr); return _transform_steps[n]; } @@ -172,7 +172,7 @@ extract_record(FltRecordReader &reader) { */ bool FltBead:: extract_ancillary(FltRecordReader &reader) { - FltTransformRecord *step = (FltTransformRecord *)NULL; + FltTransformRecord *step = nullptr; switch (reader.get_opcode()) { case FO_transform_matrix: @@ -214,7 +214,7 @@ extract_ancillary(FltRecordReader &reader) { } // A transform step. - nassertr(step != (FltTransformRecord *)NULL, false); + nassertr(step != nullptr, false); if (!step->extract_record(reader)) { return false; } diff --git a/pandatool/src/flt/fltBeadID.cxx b/pandatool/src/flt/fltBeadID.cxx index 32348d583e..4b6dc695a7 100644 --- a/pandatool/src/flt/fltBeadID.cxx +++ b/pandatool/src/flt/fltBeadID.cxx @@ -28,7 +28,7 @@ FltBeadID(FltHeader *header) : FltBead(header) { * Returns the id (name) of this particular bead. Each MultiGen bead will * have a unique name. */ -const string &FltBeadID:: +const std::string &FltBeadID:: get_id() const { return _id; } @@ -38,7 +38,7 @@ get_id() const { * is unique to this bead. */ void FltBeadID:: -set_id(const string &id) { +set_id(const std::string &id) { _id = id; } @@ -48,7 +48,7 @@ set_id(const string &id) { * flt file, use FltHeader::write_flt(). */ void FltBeadID:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type(); if (!_id.empty()) { out << " " << _id; diff --git a/pandatool/src/flt/fltBeadID.h b/pandatool/src/flt/fltBeadID.h index c14b82b4a3..d7e943b207 100644 --- a/pandatool/src/flt/fltBeadID.h +++ b/pandatool/src/flt/fltBeadID.h @@ -25,10 +25,10 @@ class FltBeadID : public FltBead { public: FltBeadID(FltHeader *header); - const string &get_id() const; - void set_id(const string &id); + const std::string &get_id() const; + void set_id(const std::string &id); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual bool extract_record(FltRecordReader &reader); @@ -38,7 +38,7 @@ protected: virtual FltError write_ancillary(FltRecordWriter &writer) const; private: - string _id; + std::string _id; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/flt/fltError.cxx b/pandatool/src/flt/fltError.cxx index fe9cf918bb..b0b58ea6ae 100644 --- a/pandatool/src/flt/fltError.cxx +++ b/pandatool/src/flt/fltError.cxx @@ -13,8 +13,8 @@ #include "fltError.h" -ostream & -operator << (ostream &out, FltError error) { +std::ostream & +operator << (std::ostream &out, FltError error) { switch (error) { case FE_ok: return out << "no error"; diff --git a/pandatool/src/flt/fltError.h b/pandatool/src/flt/fltError.h index 5d4ac08165..29c4453869 100644 --- a/pandatool/src/flt/fltError.h +++ b/pandatool/src/flt/fltError.h @@ -32,6 +32,6 @@ enum FltError { FE_internal }; -ostream &operator << (ostream &out, FltError error); +std::ostream &operator << (std::ostream &out, FltError error); #endif diff --git a/pandatool/src/flt/fltExternalReference.cxx b/pandatool/src/flt/fltExternalReference.cxx index 1780e577ba..fa6aaa05f4 100644 --- a/pandatool/src/flt/fltExternalReference.cxx +++ b/pandatool/src/flt/fltExternalReference.cxx @@ -45,7 +45,7 @@ apply_converted_filenames() { * flt file, use FltHeader::write_flt(). */ void FltExternalReference:: -output(ostream &out) const { +output(std::ostream &out) const { out << "External " << get_ref_filename(); if (!_bead_id.empty()) { out << " (" << _bead_id << ")"; @@ -83,7 +83,7 @@ extract_record(FltRecordReader &reader) { nassertr(reader.get_opcode() == FO_external_ref, false); DatagramIterator &iterator = reader.get_iterator(); - string name = iterator.get_fixed_string(200); + std::string name = iterator.get_fixed_string(200); iterator.skip_bytes(1 + 1); iterator.skip_bytes(2); // Undocumented additional padding. _flags = iterator.get_be_uint32(); @@ -95,7 +95,7 @@ extract_record(FltRecordReader &reader) { if (!name.empty() && name[name.length() - 1] == '>') { // Extract out the bead name. size_t open = name.rfind('<'); - if (open != string::npos) { + if (open != std::string::npos) { _orig_filename = name.substr(0, open); _bead_id = name.substr(open + 1, name.length() - open - 2); } @@ -120,7 +120,7 @@ build_record(FltRecordWriter &writer) const { writer.set_opcode(FO_external_ref); Datagram &datagram = writer.update_datagram(); - string name = _orig_filename; + std::string name = _orig_filename; if (!_bead_id.empty()) { name += "<" + _bead_id + ">"; } diff --git a/pandatool/src/flt/fltExternalReference.h b/pandatool/src/flt/fltExternalReference.h index 5afe57d091..03cac968cb 100644 --- a/pandatool/src/flt/fltExternalReference.h +++ b/pandatool/src/flt/fltExternalReference.h @@ -29,7 +29,7 @@ public: FltExternalReference(FltHeader *header); virtual void apply_converted_filenames(); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; enum Flags { F_color_palette_override = 0x80000000, @@ -40,9 +40,9 @@ public: F_light_palette_override = 0x04000000 }; - string _orig_filename; + std::string _orig_filename; Filename _converted_filename; - string _bead_id; + std::string _bead_id; int _flags; Filename get_ref_filename() const; diff --git a/pandatool/src/flt/fltGeometry.I b/pandatool/src/flt/fltGeometry.I index 3c4fae7918..c584c52003 100644 --- a/pandatool/src/flt/fltGeometry.I +++ b/pandatool/src/flt/fltGeometry.I @@ -34,7 +34,7 @@ get_texture() const { */ INLINE void FltGeometry:: set_texture(FltTexture *texture) { - if (texture == (FltTexture *)NULL) { + if (texture == nullptr) { _texture_index = -1; } else { _header->add_texture(texture); @@ -65,7 +65,7 @@ get_material() const { */ INLINE void FltGeometry:: set_material(FltMaterial *material) { - if (material == (FltMaterial *)NULL) { + if (material == nullptr) { _material_index = -1; } else { _header->add_material(material); diff --git a/pandatool/src/flt/fltHeader.cxx b/pandatool/src/flt/fltHeader.cxx index 062afe15fa..a08748637e 100644 --- a/pandatool/src/flt/fltHeader.cxx +++ b/pandatool/src/flt/fltHeader.cxx @@ -37,7 +37,7 @@ TypeHandle FltHeader::_type_handle; */ FltHeader:: FltHeader(PathReplace *path_replace) : FltBeadID(this) { - if (path_replace == (PathReplace *)NULL) { + if (path_replace == nullptr) { _path_replace = new PathReplace; _path_replace->_path_store = PS_absolute; } else { @@ -190,8 +190,8 @@ read_flt(Filename filename) { _flt_filename = filename; VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); - istream *in = vfs->open_read_file(filename, true); - if (in == (istream *)NULL) { + std::istream *in = vfs->open_read_file(filename, true); + if (in == nullptr) { assert(!flt_error_abort); return FE_could_not_open; } @@ -205,7 +205,7 @@ read_flt(Filename filename) { * Returns FE_ok on success, otherwise on failure. */ FltError FltHeader:: -read_flt(istream &in) { +read_flt(std::istream &in) { FltRecordReader reader(in); FltError result = reader.advance(); if (result == FE_end_of_file) { @@ -237,7 +237,7 @@ FltError FltHeader:: write_flt(Filename filename) { filename.set_binary(); - ofstream out; + std::ofstream out; if (!filename.open_write(out)) { assert(!flt_error_abort); return FE_could_not_open; @@ -260,7 +260,7 @@ write_flt(Filename filename) { * Returns FE_ok on success, otherwise on failure. */ FltError FltHeader:: -write_flt(ostream &out) { +write_flt(std::ostream &out) { FltRecordWriter writer(out); FltError result = write_record_and_children(writer); @@ -425,7 +425,7 @@ get_instance(int instance_index) const { if (mi != _instances.end()) { return (*mi).second; } - return (FltInstanceDefinition *)NULL; + return nullptr; } /** @@ -467,7 +467,7 @@ get_num_vertices() const { */ FltVertex *FltHeader:: get_vertex(int n) const { - nassertr(n >= 0 && n < (int)_vertices.size(), 0); + nassertr(n >= 0 && n < (int)_vertices.size(), nullptr); return _vertices[n]; } @@ -512,7 +512,7 @@ get_vertex_by_offset(int offset) { vi = _vertices_by_offset.find(offset); if (vi == _vertices_by_offset.end()) { nout << "No vertex with offset " << offset << "\n"; - return (FltVertex *)NULL; + return nullptr; } return (*vi).second; } @@ -600,14 +600,14 @@ has_color_name(int color_index) const { /** * Returns the name associated with the given color, if any. */ -string FltHeader:: +std::string FltHeader:: get_color_name(int color_index) const { ColorNames::const_iterator ni; ni = _color_names.find(color_index); if (ni != _color_names.end()) { return (*ni).second; } - return string(); + return std::string(); } /** @@ -810,7 +810,7 @@ get_material(int material_index) const { if (mi != _materials.end()) { return (*mi).second; } - return (FltMaterial *)NULL; + return nullptr; } /** @@ -836,7 +836,7 @@ add_material(FltMaterial *material) { } else { // Make sure our next generated material index will be different from any // existing material indices. - _next_material_index = max(_next_material_index, material->_material_index + 1); + _next_material_index = std::max(_next_material_index, material->_material_index + 1); } _materials[material->_material_index] = material; @@ -869,7 +869,7 @@ get_texture(int texture_index) const { if (mi != _textures.end()) { return (*mi).second; } - return (FltTexture *)NULL; + return nullptr; } /** @@ -895,7 +895,7 @@ add_texture(FltTexture *texture) { } else { // Make sure our next generated pattern index will be different from any // existing texture indices. - _next_pattern_index = max(_next_pattern_index, texture->_pattern_index + 1); + _next_pattern_index = std::max(_next_pattern_index, texture->_pattern_index + 1); } _textures[texture->_pattern_index] = texture; @@ -928,7 +928,7 @@ get_light_source(int light_index) const { if (li != _light_sources.end()) { return (*li).second; } - return (FltLightSourceDefinition *)NULL; + return nullptr; } /** @@ -993,7 +993,7 @@ get_num_eyepoints() const { */ FltEyepoint *FltHeader:: get_eyepoint(int n) { - nassertr(n >= 0 && n < get_num_eyepoints(), (FltEyepoint *)NULL); + nassertr(n >= 0 && n < get_num_eyepoints(), nullptr); return &_eyepoints[n]; } @@ -1011,7 +1011,7 @@ get_num_trackplanes() const { */ FltTrackplane *FltHeader:: get_trackplane(int n) { - nassertr(n >= 0 && n < get_num_trackplanes(), (FltTrackplane *)NULL); + nassertr(n >= 0 && n < get_num_trackplanes(), nullptr); return &_trackplanes[n]; } @@ -1563,7 +1563,7 @@ write_color_palette(FltRecordWriter &writer) const { // Now append all the names at the end. ColorNames::const_iterator ni; for (ni = _color_names.begin(); ni != _color_names.end(); ++ni) { - string name = (*ni).second.substr(0, 80); + std::string name = (*ni).second.substr(0, 80); int entry_length = name.length() + 8; datagram.add_be_uint16(entry_length); datagram.pad_bytes(2); diff --git a/pandatool/src/flt/fltHeader.h b/pandatool/src/flt/fltHeader.h index 0cde95d1ad..620e553ad9 100644 --- a/pandatool/src/flt/fltHeader.h +++ b/pandatool/src/flt/fltHeader.h @@ -57,9 +57,9 @@ public: const Filename &get_flt_filename() const; FltError read_flt(Filename filename); - FltError read_flt(istream &in); + FltError read_flt(std::istream &in); FltError write_flt(Filename filename); - FltError write_flt(ostream &out); + FltError write_flt(std::ostream &out); enum AttrUpdate { AU_none, @@ -113,7 +113,7 @@ public: int _format_revision_level; int _edit_revision_level; - string _last_revision; + std::string _last_revision; int _next_group_id; int _next_lod_id; int _next_object_id; @@ -181,7 +181,7 @@ public: LColor get_color(int color_index) const; LRGBColor get_rgb(int color_index) const; bool has_color_name(int color_index) const; - string get_color_name(int color_index) const; + std::string get_color_name(int color_index) const; int get_closest_color(const LColor &color) const; int get_closest_rgb(const LRGBColor &color) const; @@ -262,7 +262,7 @@ private: // Support for the color palette. bool _got_color_palette; typedef pvector Colors; - typedef pmap ColorNames; + typedef pmap ColorNames; Colors _colors; ColorNames _color_names; diff --git a/pandatool/src/flt/fltInstanceRef.cxx b/pandatool/src/flt/fltInstanceRef.cxx index 7f0ffd2e67..f33ef3b145 100644 --- a/pandatool/src/flt/fltInstanceRef.cxx +++ b/pandatool/src/flt/fltInstanceRef.cxx @@ -42,10 +42,10 @@ get_instance() const { * flt file, use FltHeader::write_flt(). */ void FltInstanceRef:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << "instance"; FltInstanceDefinition *def = _header->get_instance(_instance_index); - if (def != (FltInstanceDefinition *)NULL) { + if (def != nullptr) { def->write_children(out, indent_level + 2); indent(out, indent_level) << "}\n"; } else { diff --git a/pandatool/src/flt/fltInstanceRef.h b/pandatool/src/flt/fltInstanceRef.h index 6bbbe11ebd..2f8e281c9f 100644 --- a/pandatool/src/flt/fltInstanceRef.h +++ b/pandatool/src/flt/fltInstanceRef.h @@ -33,7 +33,7 @@ public: FltInstanceDefinition *get_instance() const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; protected: virtual bool extract_record(FltRecordReader &reader); diff --git a/pandatool/src/flt/fltLightSourceDefinition.h b/pandatool/src/flt/fltLightSourceDefinition.h index 80f307de13..e96d275254 100644 --- a/pandatool/src/flt/fltLightSourceDefinition.h +++ b/pandatool/src/flt/fltLightSourceDefinition.h @@ -36,7 +36,7 @@ public: }; int _light_index; - string _light_name; + std::string _light_name; LColor _ambient; LColor _diffuse; LColor _specular; diff --git a/pandatool/src/flt/fltMaterial.h b/pandatool/src/flt/fltMaterial.h index c801efc993..fadc3accd1 100644 --- a/pandatool/src/flt/fltMaterial.h +++ b/pandatool/src/flt/fltMaterial.h @@ -34,7 +34,7 @@ public: }; int _material_index; - string _material_name; + std::string _material_name; unsigned int _flags; LRGBColor _ambient; LRGBColor _diffuse; diff --git a/pandatool/src/flt/fltMesh.cxx b/pandatool/src/flt/fltMesh.cxx index 47506e732a..e77b8636d6 100644 --- a/pandatool/src/flt/fltMesh.cxx +++ b/pandatool/src/flt/fltMesh.cxx @@ -95,7 +95,7 @@ build_record(FltRecordWriter &writer) const { */ FltError FltMesh:: write_ancillary(FltRecordWriter &writer) const { - if (_vpool != (FltLocalVertexPool *)NULL) { + if (_vpool != nullptr) { if (!_vpool->build_record(writer)) { assert(!flt_error_abort); return FE_bad_data; diff --git a/pandatool/src/flt/fltMeshPrimitive.cxx b/pandatool/src/flt/fltMeshPrimitive.cxx index 0456cad142..6db78c8059 100644 --- a/pandatool/src/flt/fltMeshPrimitive.cxx +++ b/pandatool/src/flt/fltMeshPrimitive.cxx @@ -91,7 +91,7 @@ build_record(FltRecordWriter &writer) const { int max_index = 0; Vertices::const_iterator vi; for (vi = _vertices.begin(); vi != _vertices.end(); ++vi) { - max_index = max(max_index, (*vi)); + max_index = std::max(max_index, (*vi)); } int vertex_width; diff --git a/pandatool/src/flt/fltOpcode.cxx b/pandatool/src/flt/fltOpcode.cxx index 4ca497a9ee..92fd64afda 100644 --- a/pandatool/src/flt/fltOpcode.cxx +++ b/pandatool/src/flt/fltOpcode.cxx @@ -13,8 +13,8 @@ #include "fltOpcode.h" -ostream & -operator << (ostream &out, FltOpcode opcode) { +std::ostream & +operator << (std::ostream &out, FltOpcode opcode) { switch (opcode) { case FO_none: return out << "null opcode"; diff --git a/pandatool/src/flt/fltOpcode.h b/pandatool/src/flt/fltOpcode.h index 2cadaeacb5..f9bbeb9eab 100644 --- a/pandatool/src/flt/fltOpcode.h +++ b/pandatool/src/flt/fltOpcode.h @@ -117,6 +117,6 @@ enum FltOpcode { FO_road_construction = 127 }; -ostream &operator << (ostream &out, FltOpcode opcode); +std::ostream &operator << (std::ostream &out, FltOpcode opcode); #endif diff --git a/pandatool/src/flt/fltPackedColor.I b/pandatool/src/flt/fltPackedColor.I index 9b42f4d64d..50ae590650 100644 --- a/pandatool/src/flt/fltPackedColor.I +++ b/pandatool/src/flt/fltPackedColor.I @@ -11,8 +11,8 @@ * @date 2000-08-25 */ -INLINE ostream & -operator << (ostream &out, const FltPackedColor &color) { +INLINE std::ostream & +operator << (std::ostream &out, const FltPackedColor &color) { color.output(out); return out; } diff --git a/pandatool/src/flt/fltPackedColor.cxx b/pandatool/src/flt/fltPackedColor.cxx index cc5dc7540d..0faa4eb644 100644 --- a/pandatool/src/flt/fltPackedColor.cxx +++ b/pandatool/src/flt/fltPackedColor.cxx @@ -19,7 +19,7 @@ * */ void FltPackedColor:: -output(ostream &out) const { +output(std::ostream &out) const { out << "(" << _r << " " << _g << " " << _b << " " << _a << ")"; } diff --git a/pandatool/src/flt/fltPackedColor.h b/pandatool/src/flt/fltPackedColor.h index d8897363aa..1e38e02bc8 100644 --- a/pandatool/src/flt/fltPackedColor.h +++ b/pandatool/src/flt/fltPackedColor.h @@ -35,7 +35,7 @@ public: INLINE void set_color(const LColor &color); INLINE void set_rgb(const LRGBColor &rgb); - void output(ostream &out) const; + void output(std::ostream &out) const; bool extract_record(FltRecordReader &reader); bool build_record(FltRecordWriter &writer) const; @@ -46,7 +46,7 @@ public: int _r; }; -INLINE ostream &operator << (ostream &out, const FltPackedColor &color); +INLINE std::ostream &operator << (std::ostream &out, const FltPackedColor &color); #include "fltPackedColor.I" diff --git a/pandatool/src/flt/fltRecord.I b/pandatool/src/flt/fltRecord.I index 39d8765018..add78f2d7a 100644 --- a/pandatool/src/flt/fltRecord.I +++ b/pandatool/src/flt/fltRecord.I @@ -11,8 +11,8 @@ * @date 2000-08-24 */ -INLINE ostream & -operator << (ostream &out, const FltRecord &record) { +INLINE std::ostream & +operator << (std::ostream &out, const FltRecord &record) { record.output(out); return out; } diff --git a/pandatool/src/flt/fltRecord.cxx b/pandatool/src/flt/fltRecord.cxx index 53844f0636..9fcc52fcfa 100644 --- a/pandatool/src/flt/fltRecord.cxx +++ b/pandatool/src/flt/fltRecord.cxx @@ -69,7 +69,7 @@ get_num_children() const { */ FltRecord *FltRecord:: get_child(int n) const { - nassertr(n >= 0 && n < (int)_children.size(), (FltRecord *)NULL); + nassertr(n >= 0 && n < (int)_children.size(), nullptr); return _children[n]; } @@ -104,7 +104,7 @@ get_num_subfaces() const { */ FltRecord *FltRecord:: get_subface(int n) const { - nassertr(n >= 0 && n < (int)_subfaces.size(), (FltRecord *)NULL); + nassertr(n >= 0 && n < (int)_subfaces.size(), nullptr); return _subfaces[n]; } @@ -139,7 +139,7 @@ get_num_extensions() const { */ FltRecord *FltRecord:: get_extension(int n) const { - nassertr(n >= 0 && n < (int)_extensions.size(), (FltRecord *)NULL); + nassertr(n >= 0 && n < (int)_extensions.size(), nullptr); return _extensions[n]; } @@ -178,7 +178,7 @@ get_num_ancillary() const { */ FltRecord *FltRecord:: get_ancillary(int n) const { - nassertr(n >= 0 && n < (int)_ancillary.size(), (FltRecord *)NULL); + nassertr(n >= 0 && n < (int)_ancillary.size(), nullptr); return _ancillary[n]; } @@ -220,7 +220,7 @@ has_comment() const { * Retrieves the comment for this record, or empty string if the record has no * comment. */ -const string &FltRecord:: +const std::string &FltRecord:: get_comment() const { return _comment; } @@ -237,7 +237,7 @@ clear_comment() { * Changes the comment for this record. */ void FltRecord:: -set_comment(const string &comment) { +set_comment(const std::string &comment) { _comment = comment; } @@ -251,7 +251,7 @@ set_comment(const string &comment) { * this is exactly the sort of thing we expect. */ void FltRecord:: -check_remaining_size(const DatagramIterator &di, const string &name) const { +check_remaining_size(const DatagramIterator &di, const std::string &name) const { if (di.get_remaining_size() == 0) { return; } @@ -291,7 +291,7 @@ apply_converted_filenames() { * flt file, use FltHeader::write_flt(). */ void FltRecord:: -output(ostream &out) const { +output(std::ostream &out) const { out << get_type(); } @@ -301,7 +301,7 @@ output(ostream &out) const { * flt file, use FltHeader::write_flt(). */ void FltRecord:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << *this; write_children(out, indent_level); } @@ -311,7 +311,7 @@ write(ostream &out, int indent_level) const { * line of the record description, writes out the list of children. */ void FltRecord:: -write_children(ostream &out, int indent_level) const { +write_children(std::ostream &out, int indent_level) const { if (!_ancillary.empty()) { out << " + " << _ancillary.size() << " ancillary"; } diff --git a/pandatool/src/flt/fltRecord.h b/pandatool/src/flt/fltRecord.h index fc64441c7f..9fc8e3ad3e 100644 --- a/pandatool/src/flt/fltRecord.h +++ b/pandatool/src/flt/fltRecord.h @@ -59,20 +59,20 @@ public: void add_ancillary(FltRecord *ancillary); bool has_comment() const; - const string &get_comment() const; + const std::string &get_comment() const; void clear_comment(); - void set_comment(const string &comment); + void set_comment(const std::string &comment); void check_remaining_size(const DatagramIterator &di, - const string &name = string()) const; + const std::string &name = std::string()) const; virtual void apply_converted_filenames(); - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; protected: - void write_children(ostream &out, int indent_level) const; + void write_children(std::ostream &out, int indent_level) const; static bool is_ancillary(FltOpcode opcode); @@ -95,7 +95,7 @@ private: Records _extensions; Records _ancillary; - string _comment; + std::string _comment; public: @@ -116,7 +116,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const FltRecord &record); +INLINE std::ostream &operator << (std::ostream &out, const FltRecord &record); #include "fltRecord.I" diff --git a/pandatool/src/flt/fltRecordReader.cxx b/pandatool/src/flt/fltRecordReader.cxx index b90e911964..c999001d64 100644 --- a/pandatool/src/flt/fltRecordReader.cxx +++ b/pandatool/src/flt/fltRecordReader.cxx @@ -22,12 +22,12 @@ * */ FltRecordReader:: -FltRecordReader(istream &in) : +FltRecordReader(std::istream &in) : _in(in) { _opcode = FO_none; _record_length = 0; - _iterator = (DatagramIterator *)NULL; + _iterator = nullptr; _state = S_begin; _next_error = FE_ok; _next_opcode = FO_none; @@ -42,9 +42,9 @@ FltRecordReader(istream &in) : */ FltRecordReader:: ~FltRecordReader() { - if (_iterator != (DatagramIterator *)NULL) { + if (_iterator != nullptr) { delete _iterator; - _iterator = (DatagramIterator *)NULL; + _iterator = nullptr; } } @@ -101,9 +101,9 @@ advance(bool ok_eof) { assert(!flt_error_abort); return FE_read_error; } - if (_iterator != (DatagramIterator *)NULL) { + if (_iterator != nullptr) { delete _iterator; - _iterator = (DatagramIterator *)NULL; + _iterator = nullptr; } if (_next_error == FE_end_of_file) { diff --git a/pandatool/src/flt/fltRecordReader.h b/pandatool/src/flt/fltRecordReader.h index 09800f7e42..8817e800c2 100644 --- a/pandatool/src/flt/fltRecordReader.h +++ b/pandatool/src/flt/fltRecordReader.h @@ -29,7 +29,7 @@ */ class FltRecordReader { public: - FltRecordReader(istream &in); + FltRecordReader(std::istream &in); ~FltRecordReader(); FltOpcode get_opcode() const; @@ -45,7 +45,7 @@ public: private: void read_next_header(); - istream &_in; + std::istream &_in; Datagram _datagram; FltOpcode _opcode; int _record_length; diff --git a/pandatool/src/flt/fltRecordWriter.cxx b/pandatool/src/flt/fltRecordWriter.cxx index 55ca9fc0d4..909e5ce298 100644 --- a/pandatool/src/flt/fltRecordWriter.cxx +++ b/pandatool/src/flt/fltRecordWriter.cxx @@ -28,7 +28,7 @@ static const int max_write_length = 65532; * */ FltRecordWriter:: -FltRecordWriter(ostream &out) : +FltRecordWriter(std::ostream &out) : _out(out) { } @@ -75,7 +75,7 @@ FltError FltRecordWriter:: advance() { int start_byte = 0; int write_length = - min((int)_datagram.get_length() - start_byte, max_write_length - header_size); + std::min((int)_datagram.get_length() - start_byte, max_write_length - header_size); FltOpcode opcode = _opcode; do { @@ -107,7 +107,7 @@ advance() { start_byte += write_length; write_length = - min((int)_datagram.get_length() - start_byte, max_write_length - header_size); + std::min((int)_datagram.get_length() - start_byte, max_write_length - header_size); opcode = FO_continuation; } while (write_length > 0); @@ -142,7 +142,7 @@ write_instance_def(FltHeader *header, int instance_index) { } FltInstanceDefinition *instance = header->get_instance(instance_index); - if (instance == (FltInstanceDefinition *)NULL) { + if (instance == nullptr) { assert(!flt_error_abort); return FE_undefined_instance; } diff --git a/pandatool/src/flt/fltRecordWriter.h b/pandatool/src/flt/fltRecordWriter.h index 6c8798937c..8cd4e4b6d1 100644 --- a/pandatool/src/flt/fltRecordWriter.h +++ b/pandatool/src/flt/fltRecordWriter.h @@ -30,7 +30,7 @@ class FltHeader; */ class FltRecordWriter { public: - FltRecordWriter(ostream &out); + FltRecordWriter(std::ostream &out); ~FltRecordWriter(); void set_opcode(FltOpcode opcode); @@ -46,7 +46,7 @@ public: FltError write_instance_def(FltHeader *header, int instance_index); private: - ostream &_out; + std::ostream &_out; Datagram _datagram; FltOpcode _opcode; diff --git a/pandatool/src/flt/fltTexture.cxx b/pandatool/src/flt/fltTexture.cxx index c3c61cf130..c65f5a05e2 100644 --- a/pandatool/src/flt/fltTexture.cxx +++ b/pandatool/src/flt/fltTexture.cxx @@ -123,7 +123,7 @@ set_texture_filename(const Filename &filename) { */ Filename FltTexture:: get_attr_filename() const { - string texture_filename = get_texture_filename(); + std::string texture_filename = get_texture_filename(); return Filename::binary_filename(texture_filename + ".attr"); } @@ -136,21 +136,21 @@ FltError FltTexture:: read_attr_data() { Filename attr_filename = get_attr_filename(); - ifstream attr; + std::ifstream attr; if (!attr_filename.open_read(attr)) { return FE_could_not_open; } // Determine the file's size so we can read it all into one big datagram. - attr.seekg(0, ios::end); + attr.seekg(0, std::ios::end); if (attr.fail()) { return FE_read_error; } - streampos length = attr.tellg(); + std::streampos length = attr.tellg(); char *buffer = new char[length]; - attr.seekg(0, ios::beg); + attr.seekg(0, std::ios::beg); attr.read(buffer, length); if (attr.fail()) { return FE_read_error; @@ -184,7 +184,7 @@ write_attr_data(Filename attr_filename) const { } attr_filename.set_binary(); - ofstream attr; + std::ofstream attr; if (!attr_filename.open_write(attr)) { return FE_could_not_open; } diff --git a/pandatool/src/flt/fltTexture.h b/pandatool/src/flt/fltTexture.h index 21e1a24141..34a487e16b 100644 --- a/pandatool/src/flt/fltTexture.h +++ b/pandatool/src/flt/fltTexture.h @@ -30,7 +30,7 @@ public: virtual void apply_converted_filenames(); - string _orig_filename; + std::string _orig_filename; Filename _converted_filename; int _pattern_index; int _x_location; @@ -157,7 +157,7 @@ public: typedef pvector GeospecificControlPoints; struct SubtextureDef { - string _name; + std::string _name; int _left; int _bottom; int _right; @@ -216,7 +216,7 @@ public: ImageOrigin _image_origin; PointsUnits _geospecific_points_units; Hemisphere _geospecific_hemisphere; - string _comment; + std::string _comment; int _file_version; GeospecificControlPoints _geospecific_control_points; SubtextureDefs _subtexture_defs; diff --git a/pandatool/src/flt/fltUnsupportedRecord.cxx b/pandatool/src/flt/fltUnsupportedRecord.cxx index e3bcc07a2a..7a6e67aa84 100644 --- a/pandatool/src/flt/fltUnsupportedRecord.cxx +++ b/pandatool/src/flt/fltUnsupportedRecord.cxx @@ -31,7 +31,7 @@ FltUnsupportedRecord(FltHeader *header) : FltRecord(header) { * flt file, use FltHeader::write_flt(). */ void FltUnsupportedRecord:: -output(ostream &out) const { +output(std::ostream &out) const { out << "Unsupported(" << _opcode << ")"; } diff --git a/pandatool/src/flt/fltUnsupportedRecord.h b/pandatool/src/flt/fltUnsupportedRecord.h index 02131f35f7..a358577dfa 100644 --- a/pandatool/src/flt/fltUnsupportedRecord.h +++ b/pandatool/src/flt/fltUnsupportedRecord.h @@ -27,7 +27,7 @@ class FltUnsupportedRecord : public FltRecord { public: FltUnsupportedRecord(FltHeader *header); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual bool extract_record(FltRecordReader &reader); diff --git a/pandatool/src/flt/fltVertexList.cxx b/pandatool/src/flt/fltVertexList.cxx index 9659a56063..65da9b5923 100644 --- a/pandatool/src/flt/fltVertexList.cxx +++ b/pandatool/src/flt/fltVertexList.cxx @@ -38,7 +38,7 @@ get_num_vertices() const { */ FltVertex *FltVertexList:: get_vertex(int n) const { - nassertr(n >= 0 && n < (int)_vertices.size(), 0); + nassertr(n >= 0 && n < (int)_vertices.size(), nullptr); return _vertices[n]; } @@ -65,7 +65,7 @@ add_vertex(FltVertex *vertex) { * flt file, use FltHeader::write_flt(). */ void FltVertexList:: -output(ostream &out) const { +output(std::ostream &out) const { out << _vertices.size() << " vertices"; } diff --git a/pandatool/src/flt/fltVertexList.h b/pandatool/src/flt/fltVertexList.h index 449c5ab5ce..5fd53ad884 100644 --- a/pandatool/src/flt/fltVertexList.h +++ b/pandatool/src/flt/fltVertexList.h @@ -34,7 +34,7 @@ public: void clear_vertices(); void add_vertex(FltVertex *vertex); - virtual void output(ostream &out) const; + virtual void output(std::ostream &out) const; protected: virtual bool extract_record(FltRecordReader &reader); diff --git a/pandatool/src/fltegg/fltToEggConverter.cxx b/pandatool/src/fltegg/fltToEggConverter.cxx index 0f2b78e268..98b01938c5 100644 --- a/pandatool/src/fltegg/fltToEggConverter.cxx +++ b/pandatool/src/fltegg/fltToEggConverter.cxx @@ -35,6 +35,8 @@ #include "eggExternalReference.h" #include "string_utils.h" +using std::string; + /** * @@ -353,16 +355,16 @@ convert_face(const FltFace *flt_face, FltToEggLevelState &state) { // Collect the vertices for this primitive. pvector< PT_EggVertex > vertices; - const FltVertexList *vlist = (FltVertexList *)NULL; + const FltVertexList *vlist = nullptr; int num_children = flt_face->get_num_children(); - for (int i = 0; i < num_children && vlist == (FltVertexList *)NULL; i++) { + for (int i = 0; i < num_children && vlist == nullptr; i++) { const FltRecord *child = flt_face->get_child(i); if (child->is_of_type(FltVertexList::get_class_type())) { vlist = DCAST(FltVertexList, child); } } - if (vlist != (FltVertexList *)NULL) { + if (vlist != nullptr) { int num_vertices = vlist->get_num_vertices(); for (int i = 0; i < num_vertices; i++) { FltVertex *flt_vertex = vlist->get_vertex(i); @@ -440,7 +442,7 @@ setup_geometry(const FltGeometry *flt_geom, FltToEggLevelState &state, LColor face_color = flt_geom->get_color(); - if (state._flt_object != (FltObject *)NULL) { + if (state._flt_object != nullptr) { // If we have a FltObject above us, it might also specify a transparency. // This combines with our existing transparency. PN_stdfloat alpha = 1.0 - (state._flt_object->_transparency / 65535.0); diff --git a/pandatool/src/fltegg/fltToEggConverter.h b/pandatool/src/fltegg/fltToEggConverter.h index 5188c3fce4..c9e8cc61c1 100644 --- a/pandatool/src/fltegg/fltToEggConverter.h +++ b/pandatool/src/fltegg/fltToEggConverter.h @@ -54,8 +54,8 @@ public: virtual SomethingToEggConverter *make_copy(); - virtual string get_name() const; - virtual string get_extension() const; + virtual std::string get_name() const; + virtual std::string get_extension() const; virtual bool supports_compressed() const; virtual bool convert_file(const Filename &filename); @@ -91,7 +91,7 @@ private: bool parse_comment(const FltBeadID *flt_bead, EggNode *egg_node); bool parse_comment(const FltBead *flt_bead, EggNode *egg_node); bool parse_comment(const FltTexture *flt_texture, EggNode *egg_node); - bool parse_comment(const string &comment, const string &name, + bool parse_comment(const std::string &comment, const std::string &name, EggNode *egg_node); PT_EggVertex make_egg_vertex(const FltVertex *flt_vertex); diff --git a/pandatool/src/fltegg/fltToEggLevelState.I b/pandatool/src/fltegg/fltToEggLevelState.I index 0a1cef8f43..e5460717a6 100644 --- a/pandatool/src/fltegg/fltToEggLevelState.I +++ b/pandatool/src/fltegg/fltToEggLevelState.I @@ -18,8 +18,8 @@ INLINE FltToEggLevelState:: FltToEggLevelState(FltToEggConverter *converter) : _converter(converter) { - _flt_object = (FltObject *)NULL; - _egg_parent = (EggGroupNode *)NULL; + _flt_object = nullptr; + _egg_parent = nullptr; } /** diff --git a/pandatool/src/fltegg/fltToEggLevelState.cxx b/pandatool/src/fltegg/fltToEggLevelState.cxx index 1fbe548d50..ef396fd818 100644 --- a/pandatool/src/fltegg/fltToEggLevelState.cxx +++ b/pandatool/src/fltegg/fltToEggLevelState.cxx @@ -39,9 +39,9 @@ FltToEggLevelState:: */ FltToEggLevelState::ParentNodes:: ParentNodes() { - _axial_billboard = (EggGroup *)NULL; - _point_billboard = (EggGroup *)NULL; - _plain = (EggGroup *)NULL; + _axial_billboard = nullptr; + _point_billboard = nullptr; + _plain = nullptr; } /** @@ -56,7 +56,7 @@ ParentNodes() { * group per polygon. */ EggGroupNode *FltToEggLevelState:: -get_synthetic_group(const string &name, +get_synthetic_group(const std::string &name, const FltBead *transform_bead, FltGeometry::BillboardType type) { LMatrix4d transform = transform_bead->get_transform(); @@ -82,7 +82,7 @@ get_synthetic_group(const string &name, switch (type) { case FltGeometry::BT_axial: - if (nodes->_axial_billboard == (EggGroupNode *)NULL) { + if (nodes->_axial_billboard == nullptr) { nodes->_axial_billboard = new EggGroup(name); _egg_parent->add_child(nodes->_axial_billboard); nodes->_axial_billboard->set_billboard_type(EggGroup::BT_axis); @@ -94,7 +94,7 @@ get_synthetic_group(const string &name, return nodes->_axial_billboard; case FltGeometry::BT_point: - if (nodes->_point_billboard == (EggGroupNode *)NULL) { + if (nodes->_point_billboard == nullptr) { nodes->_point_billboard = new EggGroup(name); _egg_parent->add_child(nodes->_point_billboard); nodes->_point_billboard->set_billboard_type(EggGroup::BT_point_world_relative); @@ -107,7 +107,7 @@ get_synthetic_group(const string &name, default: // Normally, BT_none, although we've occasionally seen a // value of 3 come in here, whatever that's supposed to mean. - if (nodes->_plain == (EggGroupNode *)NULL) { + if (nodes->_plain == nullptr) { nodes->_plain = new EggGroup(name); _egg_parent->add_child(nodes->_plain); if (!is_identity) { diff --git a/pandatool/src/fltegg/fltToEggLevelState.h b/pandatool/src/fltegg/fltToEggLevelState.h index 876d9835e1..91877e2306 100644 --- a/pandatool/src/fltegg/fltToEggLevelState.h +++ b/pandatool/src/fltegg/fltToEggLevelState.h @@ -34,7 +34,7 @@ public: INLINE void operator = (const FltToEggLevelState ©); ~FltToEggLevelState(); - EggGroupNode *get_synthetic_group(const string &name, + EggGroupNode *get_synthetic_group(const std::string &name, const FltBead *transform_bead, FltGeometry::BillboardType type = FltGeometry::BT_none); diff --git a/pandatool/src/fltprogs/eggToFlt.cxx b/pandatool/src/fltprogs/eggToFlt.cxx index 90e9d123a3..f6cbc9d24f 100644 --- a/pandatool/src/fltprogs/eggToFlt.cxx +++ b/pandatool/src/fltprogs/eggToFlt.cxx @@ -61,7 +61,7 @@ EggToFlt() : "if this is \"new\", these files will only be generated if they " "do not already exist (even if the properties have changed). " "Specifying \"all\" causes these to be rewritten every time.", - &EggToFlt::dispatch_attr, NULL, &_auto_attr_update); + &EggToFlt::dispatch_attr, nullptr, &_auto_attr_update); // Flt files are always in the z-up coordinate system. Don't confuse the // user with this meaningless option. @@ -93,7 +93,7 @@ run() { * Dispatch function for the -attr parameter. */ bool EggToFlt:: -dispatch_attr(const string &opt, const string &arg, void *var) { +dispatch_attr(const std::string &opt, const std::string &arg, void *var) { FltHeader::AttrUpdate *ip = (FltHeader::AttrUpdate *)var; if (cmp_nocase(arg, "none") == 0) { @@ -231,7 +231,7 @@ convert_primitive(EggPrimitive *egg_primitive, FltBead *flt_node, void EggToFlt:: convert_group(EggGroup *egg_group, FltBead *flt_node, FltGeometry::BillboardType billboard) { - ostringstream egg_syntax; + std::ostringstream egg_syntax; FltGroup *flt_group = new FltGroup(_flt_header); flt_node->add_child(flt_group); @@ -450,9 +450,9 @@ apply_transform(EggTransform *egg_transform, FltBead *flt_node) { * comment, so that flt2egg will reapply it to the egg groups. */ void EggToFlt:: -apply_egg_syntax(const string &egg_syntax, FltRecord *flt_record) { +apply_egg_syntax(const std::string &egg_syntax, FltRecord *flt_record) { if (!egg_syntax.empty()) { - ostringstream out; + std::ostringstream out; out << " {\n" << egg_syntax << "}"; @@ -489,7 +489,7 @@ get_flt_vertex(EggVertex *egg_vertex, EggNode *context) { flt_vertex->_has_uv = true; } - if (frame != (const LMatrix4d *)NULL) { + if (frame != nullptr) { flt_vertex->_pos = flt_vertex->_pos * (*frame); flt_vertex->_normal = flt_vertex->_normal * LCAST(PN_stdfloat, (*frame)); } diff --git a/pandatool/src/fltprogs/eggToFlt.h b/pandatool/src/fltprogs/eggToFlt.h index ebae3de586..0cbcb2126d 100644 --- a/pandatool/src/fltprogs/eggToFlt.h +++ b/pandatool/src/fltprogs/eggToFlt.h @@ -42,7 +42,7 @@ public: void run(); private: - static bool dispatch_attr(const string &opt, const string &arg, void *var); + static bool dispatch_attr(const std::string &opt, const std::string &arg, void *var); void traverse(EggNode *egg_node, FltBead *flt_node, FltGeometry::BillboardType billboard); @@ -51,7 +51,7 @@ private: void convert_group(EggGroup *egg_group, FltBead *flt_node, FltGeometry::BillboardType billboard); void apply_transform(EggTransform *egg_transform, FltBead *flt_node); - void apply_egg_syntax(const string &egg_syntax, FltRecord *flt_record); + void apply_egg_syntax(const std::string &egg_syntax, FltRecord *flt_record); FltVertex *get_flt_vertex(EggVertex *egg_vertex, EggNode *context); FltTexture *get_flt_texture(EggTexture *egg_texture); diff --git a/pandatool/src/fltprogs/fltInfo.cxx b/pandatool/src/fltprogs/fltInfo.cxx index a6d4649bff..bd0e9d8a83 100644 --- a/pandatool/src/fltprogs/fltInfo.cxx +++ b/pandatool/src/fltprogs/fltInfo.cxx @@ -65,7 +65,7 @@ run() { void FltInfo:: list_hierarchy(FltRecord *record, int indent_level) { // Maybe in the future we can do something fancier here. - record->write(cout, indent_level); + record->write(std::cout, indent_level); } diff --git a/pandatool/src/gtk-stats/gtkStats.cxx b/pandatool/src/gtk-stats/gtkStats.cxx index 5f3cf83e82..e6889ff23b 100644 --- a/pandatool/src/gtk-stats/gtkStats.cxx +++ b/pandatool/src/gtk-stats/gtkStats.cxx @@ -17,7 +17,7 @@ #include "config_pstatclient.h" GtkWidget *main_window; -static GtkStatsServer *server = NULL; +static GtkStatsServer *server = nullptr; static gboolean delete_event(GtkWidget *widget, @@ -61,14 +61,14 @@ main(int argc, char *argv[]) { // Connect the delete and destroy events, so the user can exit the // application by closing the main window. g_signal_connect(G_OBJECT(main_window), "delete_event", - G_CALLBACK(delete_event), NULL); + G_CALLBACK(delete_event), nullptr); g_signal_connect(G_OBJECT(main_window), "destroy", - G_CALLBACK(destroy), NULL); + G_CALLBACK(destroy), nullptr); - ostringstream stream; + std::ostringstream stream; stream << "Listening on port " << pstats_port; - string str = stream.str(); + std::string str = stream.str(); GtkWidget *label = gtk_label_new(str.c_str()); gtk_container_add(GTK_CONTAINER(main_window), label); gtk_widget_show(label); @@ -76,12 +76,12 @@ main(int argc, char *argv[]) { // Create the server object. server = new GtkStatsServer; if (!server->listen()) { - ostringstream stream; + std::ostringstream stream; stream << "Unable to open port " << pstats_port << ". Try specifying a different\n" << "port number using pstats-port in your Config file."; - string str = stream.str(); + std::string str = stream.str(); GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(main_window), @@ -97,7 +97,7 @@ main(int argc, char *argv[]) { gtk_widget_show(main_window); // Set up a timer to poll the pstats every so often. - g_timeout_add(200, timer, NULL); + g_timeout_add(200, timer, nullptr); // Now get lost in the message loop. gtk_main(); diff --git a/pandatool/src/gtk-stats/gtkStatsChartMenu.cxx b/pandatool/src/gtk-stats/gtkStatsChartMenu.cxx index dfed8e1028..c7f8b3f4be 100644 --- a/pandatool/src/gtk-stats/gtkStatsChartMenu.cxx +++ b/pandatool/src/gtk-stats/gtkStatsChartMenu.cxx @@ -48,7 +48,7 @@ get_menu_widget() { void GtkStatsChartMenu:: add_to_menu_bar(GtkWidget *menu_bar, int position) { const PStatClientData *client_data = _monitor->get_client_data(); - string thread_name; + std::string thread_name; if (_thread_index == 0) { // A special case for the main thread. thread_name = "Graphs"; @@ -142,7 +142,7 @@ add_view(GtkWidget *parent_menu, const PStatViewLevel *view_level, int collector = view_level->get_collector(); const PStatClientData *client_data = _monitor->get_client_data(); - string collector_name = client_data->get_collector_name(collector); + std::string collector_name = client_data->get_collector_name(collector); GtkStatsMonitor::MenuDef smd(_thread_index, collector, show_level); const GtkStatsMonitor::MenuDef *menu_def = _monitor->add_menu(smd); @@ -158,7 +158,7 @@ add_view(GtkWidget *parent_menu, const PStatViewLevel *view_level, if (num_children > 1) { // If the collector has more than one child, add a menu entry to go // directly to each of its children. - string submenu_name = collector_name + " components"; + std::string submenu_name = collector_name + " components"; GtkWidget *submenu_item = gtk_menu_item_new_with_label(submenu_name.c_str()); gtk_widget_show(submenu_item); @@ -185,7 +185,7 @@ handle_menu(gpointer data) { const GtkStatsMonitor::MenuDef *menu_def = (GtkStatsMonitor::MenuDef *)data; GtkStatsMonitor *monitor = menu_def->_monitor; - if (monitor == NULL) { + if (monitor == nullptr) { return; } diff --git a/pandatool/src/gtk-stats/gtkStatsGraph.cxx b/pandatool/src/gtk-stats/gtkStatsGraph.cxx index 0c2b21f355..e56e262d23 100644 --- a/pandatool/src/gtk-stats/gtkStatsGraph.cxx +++ b/pandatool/src/gtk-stats/gtkStatsGraph.cxx @@ -38,18 +38,18 @@ GtkStatsGraph:: GtkStatsGraph(GtkStatsMonitor *monitor) : _monitor(monitor) { - _parent_window = NULL; - _window = NULL; - _graph_window = NULL; - _scale_area = NULL; + _parent_window = nullptr; + _window = nullptr; + _graph_window = nullptr; + _scale_area = nullptr; GtkWidget *parent_window = monitor->get_window(); GdkDisplay *display = gdk_drawable_get_display(parent_window->window); _hand_cursor = gdk_cursor_new_for_display(display, GDK_HAND2); - _pixmap = 0; - _pixmap_gc = 0; + _pixmap = nullptr; + _pixmap_gc = nullptr; _pixmap_xsize = 0; _pixmap_ysize = 0; @@ -91,7 +91,7 @@ GtkStatsGraph(GtkStatsMonitor *monitor) : G_CALLBACK(motion_notify_event_callback), this); // A Frame to hold the graph. - GtkWidget *graph_frame = gtk_frame_new(NULL); + GtkWidget *graph_frame = gtk_frame_new(nullptr); gtk_frame_set_shadow_type(GTK_FRAME(graph_frame), GTK_SHADOW_IN); gtk_container_add(GTK_CONTAINER(graph_frame), _graph_window); @@ -127,7 +127,7 @@ GtkStatsGraph(GtkStatsMonitor *monitor) : */ GtkStatsGraph:: ~GtkStatsGraph() { - _monitor = (GtkStatsMonitor *)NULL; + _monitor = nullptr; release_pixmap(); Brushes::iterator bi; @@ -138,9 +138,9 @@ GtkStatsGraph:: _label_stack.clear_labels(); - if (_window != (GtkWidget *)NULL) { + if (_window != nullptr) { GtkWidget *window = _window; - _window = NULL; + _window = nullptr; gtk_widget_destroy(window); } } @@ -204,7 +204,7 @@ set_pause(bool pause) { */ void GtkStatsGraph:: user_guide_bars_changed() { - if (_scale_area != NULL) { + if (_scale_area != nullptr) { gtk_widget_queue_draw(_scale_area); } gtk_widget_queue_draw(_graph_window); @@ -224,12 +224,12 @@ clicked_label(int collector_index) { void GtkStatsGraph:: close() { _label_stack.clear_labels(false); - if (_window != (GtkWidget *)NULL) { - _window = NULL; + if (_window != nullptr) { + _window = nullptr; GtkStatsMonitor *monitor = _monitor; - _monitor = (GtkStatsMonitor *)NULL; - if (monitor != (GtkStatsMonitor *)NULL) { + _monitor = nullptr; + if (monitor != nullptr) { monitor->remove_graph(this); } } @@ -328,7 +328,7 @@ handle_motion(GtkWidget *widget, int graph_x, int graph_y) { gdk_window_set_cursor(_window->window, _hand_cursor); } else { - gdk_window_set_cursor(_window->window, NULL); + gdk_window_set_cursor(_window->window, nullptr); } return TRUE; @@ -341,8 +341,8 @@ void GtkStatsGraph:: setup_pixmap(int xsize, int ysize) { release_pixmap(); - _pixmap_xsize = max(xsize, 0); - _pixmap_ysize = max(ysize, 0); + _pixmap_xsize = std::max(xsize, 0); + _pixmap_ysize = std::max(ysize, 0); _pixmap = gdk_pixmap_new(_graph_window->window, _pixmap_xsize, _pixmap_ysize, -1); // g_object_ref(_pixmap); Should this be ref_sink? @@ -359,7 +359,7 @@ setup_pixmap(int xsize, int ysize) { */ void GtkStatsGraph:: release_pixmap() { - if (_pixmap != NULL) { + if (_pixmap != nullptr) { g_object_unref(_pixmap); g_object_unref(_pixmap_gc); } @@ -391,7 +391,7 @@ gboolean GtkStatsGraph:: graph_expose_callback(GtkWidget *widget, GdkEventExpose *event, gpointer data) { GtkStatsGraph *self = (GtkStatsGraph *)data; - if (self->_pixmap != NULL) { + if (self->_pixmap != nullptr) { gdk_draw_drawable(self->_graph_window->window, self->_graph_window->style->fg_gc[0], self->_pixmap, 0, 0, 0, 0, diff --git a/pandatool/src/gtk-stats/gtkStatsLabel.cxx b/pandatool/src/gtk-stats/gtkStatsLabel.cxx index 846aeb8a15..cac7be3859 100644 --- a/pandatool/src/gtk-stats/gtkStatsLabel.cxx +++ b/pandatool/src/gtk-stats/gtkStatsLabel.cxx @@ -31,7 +31,7 @@ GtkStatsLabel(GtkStatsMonitor *monitor, GtkStatsGraph *graph, _thread_index(thread_index), _collector_index(collector_index) { - _widget = NULL; + _widget = nullptr; if (use_fullname) { _text = _monitor->get_client_data()->get_collector_fullname(_collector_index); } else { @@ -117,6 +117,14 @@ get_collector_index() const { return _collector_index; } +/** + * Returns the thread index. + */ +int GtkStatsLabel:: +get_thread_index() const { + return _thread_index; +} + /** * Enables or disables the visual highlight for this label. */ diff --git a/pandatool/src/gtk-stats/gtkStatsLabel.h b/pandatool/src/gtk-stats/gtkStatsLabel.h index 80f697dc4f..624e4193f9 100644 --- a/pandatool/src/gtk-stats/gtkStatsLabel.h +++ b/pandatool/src/gtk-stats/gtkStatsLabel.h @@ -36,6 +36,7 @@ public: int get_height() const; int get_collector_index() const; + int get_thread_index() const; void set_highlight(bool highlight); bool get_highlight() const; @@ -58,7 +59,7 @@ private: GtkStatsGraph *_graph; int _thread_index; int _collector_index; - string _text; + std::string _text; GtkWidget *_widget; GdkColor _fg_color; GdkColor _bg_color; diff --git a/pandatool/src/gtk-stats/gtkStatsMonitor.I b/pandatool/src/gtk-stats/gtkStatsMonitor.I index 71f5b43404..65a5bfbf64 100644 --- a/pandatool/src/gtk-stats/gtkStatsMonitor.I +++ b/pandatool/src/gtk-stats/gtkStatsMonitor.I @@ -19,7 +19,7 @@ MenuDef(int thread_index, int collector_index, bool show_level) : _thread_index(thread_index), _collector_index(collector_index), _show_level(show_level), - _monitor(NULL) + _monitor(nullptr) { } diff --git a/pandatool/src/gtk-stats/gtkStatsMonitor.cxx b/pandatool/src/gtk-stats/gtkStatsMonitor.cxx index fe4926cbc5..4f78d88450 100644 --- a/pandatool/src/gtk-stats/gtkStatsMonitor.cxx +++ b/pandatool/src/gtk-stats/gtkStatsMonitor.cxx @@ -25,18 +25,18 @@ typedef void vc(); GtkItemFactoryEntry GtkStatsMonitor::menu_entries[] = { - { (gchar *)"/Options", NULL, NULL, 0, (gchar *)"" }, - { (gchar *)"/Options/Units", NULL, NULL, 0, (gchar *)"" }, - { (gchar *)"/Options/Units/ms", NULL, (vc *)&handle_menu_command, MI_time_ms, (gchar *)"" }, - { (gchar *)"/Options/Units/Hz", NULL, (vc *)&handle_menu_command, MI_time_hz, (gchar *)"/Options/Units/ms" }, - { (gchar *)"/Speed", NULL, NULL, 0, (gchar *)"" }, - { (gchar *)"/Speed/1", NULL, (vc *)&handle_menu_command, MI_speed_1, (gchar *)"" }, - { (gchar *)"/Speed/2", NULL, (vc *)&handle_menu_command, MI_speed_2, (gchar *)"/Speed/1" }, - { (gchar *)"/Speed/3", NULL, (vc *)&handle_menu_command, MI_speed_3, (gchar *)"/Speed/1" }, - { (gchar *)"/Speed/6", NULL, (vc *)&handle_menu_command, MI_speed_6, (gchar *)"/Speed/1" }, - { (gchar *)"/Speed/12", NULL, (vc *)&handle_menu_command, MI_speed_12, (gchar *)"/Speed/1" }, - { (gchar *)"/Speed/sep", NULL, NULL, 0, (gchar *)"" }, - { (gchar *)"/Speed/pause", NULL, (vc *)&handle_menu_command, MI_pause, (gchar *)"" }, + { (gchar *)"/Options", nullptr, nullptr, 0, (gchar *)"" }, + { (gchar *)"/Options/Units", nullptr, nullptr, 0, (gchar *)"" }, + { (gchar *)"/Options/Units/ms", nullptr, (vc *)&handle_menu_command, MI_time_ms, (gchar *)"" }, + { (gchar *)"/Options/Units/Hz", nullptr, (vc *)&handle_menu_command, MI_time_hz, (gchar *)"/Options/Units/ms" }, + { (gchar *)"/Speed", nullptr, nullptr, 0, (gchar *)"" }, + { (gchar *)"/Speed/1", nullptr, (vc *)&handle_menu_command, MI_speed_1, (gchar *)"" }, + { (gchar *)"/Speed/2", nullptr, (vc *)&handle_menu_command, MI_speed_2, (gchar *)"/Speed/1" }, + { (gchar *)"/Speed/3", nullptr, (vc *)&handle_menu_command, MI_speed_3, (gchar *)"/Speed/1" }, + { (gchar *)"/Speed/6", nullptr, (vc *)&handle_menu_command, MI_speed_6, (gchar *)"/Speed/1" }, + { (gchar *)"/Speed/12", nullptr, (vc *)&handle_menu_command, MI_speed_12, (gchar *)"/Speed/1" }, + { (gchar *)"/Speed/sep", nullptr, nullptr, 0, (gchar *)"" }, + { (gchar *)"/Speed/pause", nullptr, (vc *)&handle_menu_command, MI_pause, (gchar *)"" }, }; int GtkStatsMonitor::num_menu_entries = sizeof(menu_entries) / sizeof(GtkItemFactoryEntry); @@ -46,8 +46,8 @@ int GtkStatsMonitor::num_menu_entries = sizeof(menu_entries) / sizeof(GtkItemFac */ GtkStatsMonitor:: GtkStatsMonitor(GtkStatsServer *server) : PStatMonitor(server) { - _window = NULL; - _item_factory = NULL; + _window = nullptr; + _item_factory = nullptr; // These will be filled in later when the menu is created. _time_units = 0; @@ -67,7 +67,7 @@ GtkStatsMonitor:: * Should be redefined to return a descriptive name for the type of * PStatsMonitor this is. */ -string GtkStatsMonitor:: +std::string GtkStatsMonitor:: get_monitor_name() { return "GtkStats"; } @@ -103,7 +103,7 @@ got_hello() { void GtkStatsMonitor:: got_bad_version(int client_major, int client_minor, int server_major, int server_minor) { - ostringstream str; + std::ostringstream str; str << "Unable to honor connection attempt from " << get_client_progname() << " on " << get_client_hostname() << ": unsupported PStats version " @@ -117,7 +117,7 @@ got_bad_version(int client_major, int client_minor, << ".0 through " << server_major << "." << server_minor << ")."; } - string message = str.str(); + std::string message = str.str(); GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(main_window), GTK_DIALOG_DESTROY_WITH_PARENT, @@ -279,7 +279,7 @@ open_piano_roll(int thread_index) { */ const GtkStatsMonitor::MenuDef *GtkStatsMonitor:: add_menu(const MenuDef &menu_def) { - pair result = _menus.insert(menu_def); + std::pair result = _menus.insert(menu_def); Menus::iterator mi = result.first; const GtkStatsMonitor::MenuDef &new_menu_def = (*mi); if (result.second) { @@ -362,7 +362,7 @@ remove_graph(GtkStatsGraph *graph) { */ void GtkStatsMonitor:: create_window() { - if (_window != NULL) { + if (_window != nullptr) { return; } @@ -432,9 +432,9 @@ shutdown() { } _chart_menus.clear(); - if (_window != NULL) { + if (_window != nullptr) { gtk_widget_destroy(_window); - _window = NULL; + _window = nullptr; } #ifdef DEVELOP_GTKSTATS diff --git a/pandatool/src/gtk-stats/gtkStatsMonitor.h b/pandatool/src/gtk-stats/gtkStatsMonitor.h index 704a919cf8..be1f1c7d42 100644 --- a/pandatool/src/gtk-stats/gtkStatsMonitor.h +++ b/pandatool/src/gtk-stats/gtkStatsMonitor.h @@ -48,7 +48,7 @@ public: GtkStatsMonitor(GtkStatsServer *server); virtual ~GtkStatsMonitor(); - virtual string get_monitor_name(); + virtual std::string get_monitor_name(); virtual void initialized(); virtual void got_hello(); @@ -100,7 +100,7 @@ private: int _next_chart_index; GtkWidget *_frame_rate_menu_item; GtkWidget *_frame_rate_label; - string _window_title; + std::string _window_title; int _time_units; double _scroll_speed; bool _pause; diff --git a/pandatool/src/gtk-stats/gtkStatsPianoRoll.cxx b/pandatool/src/gtk-stats/gtkStatsPianoRoll.cxx index f29ae4955c..60a3dc7887 100644 --- a/pandatool/src/gtk-stats/gtkStatsPianoRoll.cxx +++ b/pandatool/src/gtk-stats/gtkStatsPianoRoll.cxx @@ -47,8 +47,8 @@ GtkStatsPianoRoll(GtkStatsMonitor *monitor, int thread_index) : const PStatClientData *client_data = GtkStatsGraph::_monitor->get_client_data(); - string thread_name = client_data->get_thread_name(_thread_index); - string window_title = thread_name + " thread piano roll"; + std::string thread_name = client_data->get_thread_name(_thread_index); + std::string window_title = thread_name + " thread piano roll"; gtk_window_set_title(GTK_WINDOW(_window), window_title.c_str()); gtk_widget_show_all(_window); @@ -441,7 +441,7 @@ draw_guide_label(const PStatGraph::GuideBar &bar) { } int x = height_to_pixel(bar._height); - const string &label = bar._label; + const std::string &label = bar._label; PangoLayout *layout = gtk_widget_create_pango_layout(_window, label.c_str()); int width, height; diff --git a/pandatool/src/gtk-stats/gtkStatsStripChart.cxx b/pandatool/src/gtk-stats/gtkStatsStripChart.cxx index 8370cd958b..117ef96576 100644 --- a/pandatool/src/gtk-stats/gtkStatsStripChart.cxx +++ b/pandatool/src/gtk-stats/gtkStatsStripChart.cxx @@ -111,7 +111,7 @@ new_collector(int collector_index) { void GtkStatsStripChart:: new_data(int thread_index, int frame_number) { if (is_title_unknown()) { - string window_title = get_title_text(); + std::string window_title = get_title_text(); if (!is_title_unknown()) { gtk_window_set_title(GTK_WINDOW(_window), window_title.c_str()); } @@ -120,7 +120,7 @@ new_data(int thread_index, int frame_number) { if (!_pause) { update(); - string text = format_number(get_average_net_value(), get_guide_bar_units(), get_guide_bar_unit_name()); + std::string text = format_number(get_average_net_value(), get_guide_bar_units(), get_guide_bar_unit_name()); if (_net_value_text != text) { _net_value_text = text; gtk_label_set_text(GTK_LABEL(_total_label), _net_value_text.c_str()); @@ -575,7 +575,7 @@ draw_guide_label(const PStatGraph::GuideBar &bar, int last_y) { } int y = height_to_pixel(bar._height); - const string &label = bar._label; + const std::string &label = bar._label; PangoLayout *layout = gtk_widget_create_pango_layout(_window, label.c_str()); int width, height; diff --git a/pandatool/src/gtk-stats/gtkStatsStripChart.h b/pandatool/src/gtk-stats/gtkStatsStripChart.h index 65bd50b598..484d669c9f 100644 --- a/pandatool/src/gtk-stats/gtkStatsStripChart.h +++ b/pandatool/src/gtk-stats/gtkStatsStripChart.h @@ -75,7 +75,7 @@ private: private: int _brush_origin; - string _net_value_text; + std::string _net_value_text; GtkWidget *_top_hbox; GtkWidget *_smooth_check_box; diff --git a/pandatool/src/imagebase/imageWriter.cxx b/pandatool/src/imagebase/imageWriter.cxx index 3a4bfc1d56..eb50188e29 100644 --- a/pandatool/src/imagebase/imageWriter.cxx +++ b/pandatool/src/imagebase/imageWriter.cxx @@ -26,7 +26,7 @@ ImageWriter(bool allow_last_param) : } add_runline("[opts] -o outputimage"); - string o_description; + std::string o_description; if (_allow_last_param) { o_description = "Specify the filename to which the resulting image file will be written. " diff --git a/pandatool/src/imageprogs/imageFixHiddenColor.cxx b/pandatool/src/imageprogs/imageFixHiddenColor.cxx index bb56bcc659..a3d176bfb4 100644 --- a/pandatool/src/imageprogs/imageFixHiddenColor.cxx +++ b/pandatool/src/imageprogs/imageFixHiddenColor.cxx @@ -41,19 +41,19 @@ ImageFixHiddenColor() : ImageFilter(true) { "alpha channel on the source image. If this file has an alpha " "channel, that alpha channel is used; otherwise, the grayscale " "value of the image is used.", - &ImageFixHiddenColor::dispatch_filename, NULL, &_alpha_filename); + &ImageFixHiddenColor::dispatch_filename, nullptr, &_alpha_filename); add_option ("opaque", "alpha", 0, "Specifies the minimum alpha value (in the range of 0 to 1) for a " "pixel to be considered fully opaque. The default is 1.", - &ImageFixHiddenColor::dispatch_double, NULL, &_min_opaque_alpha); + &ImageFixHiddenColor::dispatch_double, nullptr, &_min_opaque_alpha); add_option ("transparent", "alpha", 0, "Specifies the maximum alpha value (in the range of 0 to 1) for a " "pixel to be considered fully transparent. The default is 0.", - &ImageFixHiddenColor::dispatch_double, NULL, &_max_transparent_alpha); + &ImageFixHiddenColor::dispatch_double, nullptr, &_max_transparent_alpha); _min_opaque_alpha = 1.0; _max_transparent_alpha = 0.0; diff --git a/pandatool/src/imageprogs/imageInfo.cxx b/pandatool/src/imageprogs/imageInfo.cxx index 175a5dba1d..7cbde06913 100644 --- a/pandatool/src/imageprogs/imageInfo.cxx +++ b/pandatool/src/imageprogs/imageInfo.cxx @@ -29,7 +29,7 @@ ImageInfo() { "Report only images that have a non-power-of-two size in either " "dimension. Images whose dimensions are both a power of two will " "not be mentioned.", - &ImageInfo::dispatch_none, &_report_power_2, NULL); + &ImageInfo::dispatch_none, &_report_power_2, nullptr); } /** diff --git a/pandatool/src/imageprogs/imageResize.cxx b/pandatool/src/imageprogs/imageResize.cxx index ae5a746c1a..a41ff771de 100644 --- a/pandatool/src/imageprogs/imageResize.cxx +++ b/pandatool/src/imageprogs/imageResize.cxx @@ -29,14 +29,14 @@ ImageResize() : ImageFilter(true) { "Specify the width of the output image in pixels, or as a percentage " "of the original width (if a trailing percent sign is included). " "If this is omitted, the ratio is taken from the ysize parameter.", - &ImageResize::dispatch_size_request, NULL, &_x_size); + &ImageResize::dispatch_size_request, nullptr, &_x_size); add_option ("y", "ysize", 0, "Specify the height of the output image in pixels, or as a percentage " "of the original height (if a trailing percent sign is included). " "If this is omitted, the ratio is taken from the xsize parameter.", - &ImageResize::dispatch_size_request, NULL, &_y_size); + &ImageResize::dispatch_size_request, nullptr, &_y_size); add_option ("g", "radius", 0, @@ -47,7 +47,7 @@ ImageResize() : ImageFilter(true) { ("1", "", 0, "This option is ignored. It is provided only for backward compatibility " "with a previous version of image-resize.", - &ImageResize::dispatch_none, NULL, NULL); + &ImageResize::dispatch_none, nullptr, nullptr); _filter_radius = 1.0; } @@ -87,11 +87,11 @@ run() { * Interprets the -x or -y parameters. */ bool ImageResize:: -dispatch_size_request(const string &opt, const string &arg, void *var) { +dispatch_size_request(const std::string &opt, const std::string &arg, void *var) { SizeRequest *ip = (SizeRequest *)var; if (!arg.empty() && arg[arg.length() - 1] == '%') { // A ratio. - string str = arg.substr(0, arg.length() - 1); + std::string str = arg.substr(0, arg.length() - 1); double ratio; if (!string_to_double(str, ratio)) { nout << "Invalid ratio for -" << opt << ": " diff --git a/pandatool/src/imageprogs/imageResize.h b/pandatool/src/imageprogs/imageResize.h index c7e71076db..731786a4cb 100644 --- a/pandatool/src/imageprogs/imageResize.h +++ b/pandatool/src/imageprogs/imageResize.h @@ -29,7 +29,7 @@ public: void run(); private: - static bool dispatch_size_request(const string &opt, const string &arg, void *var); + static bool dispatch_size_request(const std::string &opt, const std::string &arg, void *var); enum RequestType { RT_none, diff --git a/pandatool/src/imageprogs/imageTrans.cxx b/pandatool/src/imageprogs/imageTrans.cxx index da33516eeb..517abee647 100644 --- a/pandatool/src/imageprogs/imageTrans.cxx +++ b/pandatool/src/imageprogs/imageTrans.cxx @@ -33,7 +33,7 @@ ImageTrans() : ImageFilter(true) { "l, la, rgb, or rgba, respectively, or any of the keywords r, g, b, or " "a to extract out just the indicated channel as a single grayscale " "image.", - &ImageTrans::dispatch_channels, NULL, &_channels); + &ImageTrans::dispatch_channels, nullptr, &_channels); add_option ("cscale", "r,g,b[,a]", 50, @@ -144,7 +144,7 @@ run() { * Interprets the -chan parameter. */ bool ImageTrans:: -dispatch_channels(const string &opt, const string &arg, void *var) { +dispatch_channels(const std::string &opt, const std::string &arg, void *var) { Channels *ip = (Channels *)var; if (cmp_nocase(arg, "l") == 0) { (*ip) = C_l; diff --git a/pandatool/src/imageprogs/imageTrans.h b/pandatool/src/imageprogs/imageTrans.h index 8a4d3fffd6..a41d3ef5ef 100644 --- a/pandatool/src/imageprogs/imageTrans.h +++ b/pandatool/src/imageprogs/imageTrans.h @@ -29,7 +29,7 @@ public: void run(); private: - static bool dispatch_channels(const string &opt, const string &arg, void *var); + static bool dispatch_channels(const std::string &opt, const std::string &arg, void *var); void extract_alpha(); enum Channels { diff --git a/pandatool/src/imageprogs/imageTransformColors.cxx b/pandatool/src/imageprogs/imageTransformColors.cxx index a18629f798..0efee4aab0 100644 --- a/pandatool/src/imageprogs/imageTransformColors.cxx +++ b/pandatool/src/imageprogs/imageTransformColors.cxx @@ -16,6 +16,10 @@ #include "pnmImage.h" #include +using std::max; +using std::min; +using std::string; + /** * */ @@ -40,36 +44,36 @@ ImageTransformColors() { "space, instead of the default RGB space. In this mode, the first " "component controls hue, the second controls lightness, and the third " "controls saturation.", - &ImageTransformColors::dispatch_none, &_hls, NULL); + &ImageTransformColors::dispatch_none, &_hls, nullptr); add_option ("range", "min,max", 0, "Compresses the overall dynamic range from 0,1 to min,max. If min,max " "exceed 0,1, the dynamic range is expanded. This doesn't make sense in " "HLS mode.", - &ImageTransformColors::dispatch_range, NULL, &_mat); + &ImageTransformColors::dispatch_range, nullptr, &_mat); add_option ("scale", "r,g,b", 0, "Scales the r,g,b components by the indicated values. In HLS mode, " "the scale is applied to the h,l,s components.", - &ImageTransformColors::dispatch_scale, NULL, &_mat); + &ImageTransformColors::dispatch_scale, nullptr, &_mat); add_option ("add", "r,g,b", 0, "Adds the indicated values to the r,g,b components. In HLS mode, " "the sum is applied to the h,l,s components.", - &ImageTransformColors::dispatch_add, NULL, &_mat); + &ImageTransformColors::dispatch_add, nullptr, &_mat); add_option ("mat4", "m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33", 0, "Defines an arbitrary 4x4 RGB matrix.", - &ImageTransformColors::dispatch_mat4, NULL, &_mat); + &ImageTransformColors::dispatch_mat4, nullptr, &_mat); add_option ("mat3", "m00,m01,m02,m10,m11,m12,m20,m21,m22", 0, "Defines an arbitrary 3x3 RGB matrix.", - &ImageTransformColors::dispatch_mat3, NULL, &_mat); + &ImageTransformColors::dispatch_mat3, nullptr, &_mat); add_option ("o", "filename", 50, diff --git a/pandatool/src/imageprogs/imageTransformColors.h b/pandatool/src/imageprogs/imageTransformColors.h index d668ea5895..a6d11bb143 100644 --- a/pandatool/src/imageprogs/imageTransformColors.h +++ b/pandatool/src/imageprogs/imageTransformColors.h @@ -33,11 +33,11 @@ public: void run(); protected: - static bool dispatch_mat4(const string &opt, const string &arg, void *var); - static bool dispatch_mat3(const string &opt, const string &arg, void *var); - static bool dispatch_range(const string &opt, const string &arg, void *var); - static bool dispatch_scale(const string &opt, const string &arg, void *var); - static bool dispatch_add(const string &opt, const string &arg, void *var); + static bool dispatch_mat4(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_mat3(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_range(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_scale(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_add(const std::string &opt, const std::string &arg, void *var); virtual bool handle_args(Args &args); Filename get_output_filename(const Filename &source_filename) const; diff --git a/pandatool/src/lwo/iffChunk.cxx b/pandatool/src/lwo/iffChunk.cxx index e3ba7107a5..a86ac62dd9 100644 --- a/pandatool/src/lwo/iffChunk.cxx +++ b/pandatool/src/lwo/iffChunk.cxx @@ -22,7 +22,7 @@ TypeHandle IffChunk::_type_handle; * */ void IffChunk:: -output(ostream &out) const { +output(std::ostream &out) const { out << _id << " (" << get_type() << ")"; } @@ -30,7 +30,7 @@ output(ostream &out) const { * */ void IffChunk:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << _id << " { ... }\n"; } diff --git a/pandatool/src/lwo/iffChunk.h b/pandatool/src/lwo/iffChunk.h index dd162497ae..58de26470b 100644 --- a/pandatool/src/lwo/iffChunk.h +++ b/pandatool/src/lwo/iffChunk.h @@ -36,8 +36,8 @@ public: virtual bool read_iff(IffInputFile *in, size_t stop_at)=0; - virtual void output(ostream &out) const; - virtual void write(ostream &out, int indent_level = 0) const; + virtual void output(std::ostream &out) const; + virtual void write(std::ostream &out, int indent_level = 0) const; virtual IffChunk *make_new_chunk(IffInputFile *in, IffId id); @@ -64,7 +64,7 @@ private: #include "iffChunk.I" -INLINE ostream &operator << (ostream &out, const IffChunk &chunk) { +INLINE std::ostream &operator << (std::ostream &out, const IffChunk &chunk) { chunk.output(out); return out; } diff --git a/pandatool/src/lwo/iffGenericChunk.cxx b/pandatool/src/lwo/iffGenericChunk.cxx index 87625c2193..c8eaf015ee 100644 --- a/pandatool/src/lwo/iffGenericChunk.cxx +++ b/pandatool/src/lwo/iffGenericChunk.cxx @@ -37,7 +37,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void IffGenericChunk:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { " << _data.get_length() << " bytes }\n"; } diff --git a/pandatool/src/lwo/iffGenericChunk.h b/pandatool/src/lwo/iffGenericChunk.h index bb50fb36d4..e1e9902443 100644 --- a/pandatool/src/lwo/iffGenericChunk.h +++ b/pandatool/src/lwo/iffGenericChunk.h @@ -33,7 +33,7 @@ public: INLINE void set_data(const Datagram &data); virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; private: Datagram _data; diff --git a/pandatool/src/lwo/iffId.I b/pandatool/src/lwo/iffId.I index b5775dcbaa..938e26c4cc 100644 --- a/pandatool/src/lwo/iffId.I +++ b/pandatool/src/lwo/iffId.I @@ -78,7 +78,7 @@ operator < (const IffId &other) const { /** * Returns the four-character name of the Id, for outputting. */ -INLINE string IffId:: +INLINE std::string IffId:: get_name() const { - return string(_id._c, 4); + return std::string(_id._c, 4); } diff --git a/pandatool/src/lwo/iffId.cxx b/pandatool/src/lwo/iffId.cxx index 6d31a79bad..eda63c0b5d 100644 --- a/pandatool/src/lwo/iffId.cxx +++ b/pandatool/src/lwo/iffId.cxx @@ -19,7 +19,7 @@ * */ void IffId:: -output(ostream &out) const { +output(std::ostream &out) const { // If all of the characters are printable, just output them. if (isprint(_id._c[0]) && isprint(_id._c[1]) && isprint(_id._c[2]) && isprint(_id._c[3])) { @@ -32,10 +32,10 @@ output(ostream &out) const { } else { // Otherwise, write out the hex. - out << "0x" << hex << setfill('0'); + out << "0x" << std::hex << std::setfill('0'); for (int i = 0; i < 4; i++) { - out << setw(2) << (int)(unsigned char)_id._c[i]; + out << std::setw(2) << (int)(unsigned char)_id._c[i]; } - out << dec << setfill(' '); + out << std::dec << std::setfill(' '); } } diff --git a/pandatool/src/lwo/iffId.h b/pandatool/src/lwo/iffId.h index 2d20b9b99c..c3d14a7abd 100644 --- a/pandatool/src/lwo/iffId.h +++ b/pandatool/src/lwo/iffId.h @@ -34,9 +34,9 @@ public: INLINE bool operator != (const IffId &other) const; INLINE bool operator < (const IffId &other) const; - INLINE string get_name() const; + INLINE std::string get_name() const; - void output(ostream &out) const; + void output(std::ostream &out) const; private: union { @@ -47,7 +47,7 @@ private: #include "iffId.I" -INLINE ostream &operator << (ostream &out, const IffId &id) { +INLINE std::ostream &operator << (std::ostream &out, const IffId &id) { id.output(out); return out; } diff --git a/pandatool/src/lwo/iffInputFile.cxx b/pandatool/src/lwo/iffInputFile.cxx index 17f4225625..f00dbf5469 100644 --- a/pandatool/src/lwo/iffInputFile.cxx +++ b/pandatool/src/lwo/iffInputFile.cxx @@ -24,7 +24,7 @@ TypeHandle IffInputFile::_type_handle; */ IffInputFile:: IffInputFile() { - _input = (istream *)NULL; + _input = nullptr; _owns_istream = false; _eof = true; _unexpected_eof = false; @@ -51,8 +51,8 @@ open_read(Filename filename) { filename.set_binary(); VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); - istream *in = vfs->open_read_file(filename, true); - if (in == (istream *)NULL) { + std::istream *in = vfs->open_read_file(filename, true); + if (in == nullptr) { return false; } @@ -68,7 +68,7 @@ open_read(Filename filename) { * IffInputFile destructs. */ void IffInputFile:: -set_input(istream *input, bool owns_istream) { +set_input(std::istream *input, bool owns_istream) { if (_owns_istream) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->close_read_file(_input); @@ -174,9 +174,9 @@ get_be_float32() { /** * Extracts a null-terminated string. */ -string IffInputFile:: +std::string IffInputFile:: get_string() { - string result; + std::string result; char byte; while (read_byte(byte)) { if (byte == 0) { @@ -211,7 +211,7 @@ get_id() { PT(IffChunk) IffInputFile:: get_chunk() { if (is_eof()) { - return (IffChunk *)NULL; + return nullptr; } IffId id = get_id(); @@ -230,14 +230,14 @@ get_chunk() { nout << "Unexpected EOF on file reading " << *chunk << "\n"; _unexpected_eof = true; } - return (IffChunk *)NULL; + return nullptr; } size_t num_bytes_read = get_bytes_read() - start_point; if (num_bytes_read > length) { nout << *chunk << " read " << num_bytes_read << " instead of " << length << " bytes.\n"; - return (IffChunk *)NULL; + return nullptr; } else if (num_bytes_read < length) { size_t skip_count = length - num_bytes_read; @@ -249,7 +249,7 @@ get_chunk() { } } - return (IffChunk *)NULL; + return nullptr; } /** @@ -261,7 +261,7 @@ get_chunk() { PT(IffChunk) IffInputFile:: get_subchunk(IffChunk *context) { if (is_eof()) { - return (IffChunk *)NULL; + return nullptr; } IffId id = get_id(); @@ -280,14 +280,14 @@ get_subchunk(IffChunk *context) { nout << "Unexpected EOF on file reading " << *chunk << "\n"; _unexpected_eof = true; } - return (IffChunk *)NULL; + return nullptr; } size_t num_bytes_read = get_bytes_read() - start_point; if (num_bytes_read > length) { nout << *chunk << " read " << num_bytes_read << " instead of " << length << " bytes.\n"; - return (IffChunk *)NULL; + return nullptr; } else if (num_bytes_read < length) { size_t skip_count = length - num_bytes_read; @@ -299,7 +299,7 @@ get_subchunk(IffChunk *context) { } } - return (IffChunk *)NULL; + return nullptr; } /** diff --git a/pandatool/src/lwo/iffInputFile.h b/pandatool/src/lwo/iffInputFile.h index 2b788f07a0..dc39be7da0 100644 --- a/pandatool/src/lwo/iffInputFile.h +++ b/pandatool/src/lwo/iffInputFile.h @@ -33,7 +33,7 @@ public: virtual ~IffInputFile(); bool open_read(Filename filename); - void set_input(istream *input, bool owns_istream); + void set_input(std::istream *input, bool owns_istream); INLINE void set_filename(const Filename &filename); INLINE const Filename &get_filename() const; @@ -52,7 +52,7 @@ public: uint32_t get_be_uint32(); PN_stdfloat get_be_float32(); - string get_string(); + std::string get_string(); IffId get_id(); @@ -66,7 +66,7 @@ public: protected: virtual IffChunk *make_new_chunk(IffId id); - istream *_input; + std::istream *_input; Filename _filename; bool _owns_istream; bool _eof; diff --git a/pandatool/src/lwo/lwoBoundingBox.cxx b/pandatool/src/lwo/lwoBoundingBox.cxx index 8f23e7b403..10ef60a7b0 100644 --- a/pandatool/src/lwo/lwoBoundingBox.cxx +++ b/pandatool/src/lwo/lwoBoundingBox.cxx @@ -39,7 +39,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoBoundingBox:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { min = " << _min << ", max = " << _max << " }\n"; } diff --git a/pandatool/src/lwo/lwoBoundingBox.h b/pandatool/src/lwo/lwoBoundingBox.h index 3120bee5b0..993425ffce 100644 --- a/pandatool/src/lwo/lwoBoundingBox.h +++ b/pandatool/src/lwo/lwoBoundingBox.h @@ -30,7 +30,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/lwo/lwoClip.cxx b/pandatool/src/lwo/lwoClip.cxx index d0bda7993f..fd1e602a0e 100644 --- a/pandatool/src/lwo/lwoClip.cxx +++ b/pandatool/src/lwo/lwoClip.cxx @@ -36,7 +36,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoClip:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " {\n"; indent(out, indent_level + 2) diff --git a/pandatool/src/lwo/lwoClip.h b/pandatool/src/lwo/lwoClip.h index 647a2e69dd..3955efa526 100644 --- a/pandatool/src/lwo/lwoClip.h +++ b/pandatool/src/lwo/lwoClip.h @@ -28,7 +28,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; virtual IffChunk *make_new_chunk(IffInputFile *in, IffId id); diff --git a/pandatool/src/lwo/lwoDiscontinuousVertexMap.cxx b/pandatool/src/lwo/lwoDiscontinuousVertexMap.cxx index f0cab49c18..3e4b0c003c 100644 --- a/pandatool/src/lwo/lwoDiscontinuousVertexMap.cxx +++ b/pandatool/src/lwo/lwoDiscontinuousVertexMap.cxx @@ -82,7 +82,7 @@ read_iff(IffInputFile *in, size_t stop_at) { } VMap &vmap = _vmad[polygon_index]; - pair ir = + std::pair ir = vmap.insert(VMap::value_type(vertex_index, value)); if (!ir.second) { // This polygonvertex pair was repeated in the vmad. Is it simply @@ -115,7 +115,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoDiscontinuousVertexMap:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { map_type = " << _map_type << ", dimension = " << _dimension diff --git a/pandatool/src/lwo/lwoDiscontinuousVertexMap.h b/pandatool/src/lwo/lwoDiscontinuousVertexMap.h index 1404d02ccd..2f48e146e7 100644 --- a/pandatool/src/lwo/lwoDiscontinuousVertexMap.h +++ b/pandatool/src/lwo/lwoDiscontinuousVertexMap.h @@ -32,11 +32,11 @@ public: IffId _map_type; int _dimension; - string _name; + std::string _name; public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; private: typedef pmap VMap; diff --git a/pandatool/src/lwo/lwoGroupChunk.cxx b/pandatool/src/lwo/lwoGroupChunk.cxx index 69cd426f57..481f27bb28 100644 --- a/pandatool/src/lwo/lwoGroupChunk.cxx +++ b/pandatool/src/lwo/lwoGroupChunk.cxx @@ -31,7 +31,7 @@ get_num_chunks() const { */ IffChunk *LwoGroupChunk:: get_chunk(int n) const { - nassertr(n >= 0 && n < (int)_chunks.size(), (IffChunk *)NULL); + nassertr(n >= 0 && n < (int)_chunks.size(), nullptr); return _chunks[n]; } @@ -44,7 +44,7 @@ bool LwoGroupChunk:: read_chunks_iff(IffInputFile *in, size_t stop_at) { while (in->get_bytes_read() < stop_at && !in->is_eof()) { PT(IffChunk) chunk = in->get_chunk(); - if (chunk == (IffChunk *)NULL) { + if (chunk == nullptr) { return false; } _chunks.push_back(chunk); @@ -60,7 +60,7 @@ bool LwoGroupChunk:: read_subchunks_iff(IffInputFile *in, size_t stop_at) { while (in->get_bytes_read() < stop_at && !in->is_eof()) { PT(IffChunk) chunk = in->get_subchunk(this); - if (chunk == (IffChunk *)NULL) { + if (chunk == nullptr) { return false; } _chunks.push_back(chunk); @@ -74,7 +74,7 @@ read_subchunks_iff(IffInputFile *in, size_t stop_at) { * debugging), one per line. */ void LwoGroupChunk:: -write_chunks(ostream &out, int indent_level) const { +write_chunks(std::ostream &out, int indent_level) const { Chunks::const_iterator ci; for (ci = _chunks.begin(); ci != _chunks.end(); ++ci) { (*ci)->write(out, indent_level); diff --git a/pandatool/src/lwo/lwoGroupChunk.h b/pandatool/src/lwo/lwoGroupChunk.h index fb2db24f11..2a72dd7943 100644 --- a/pandatool/src/lwo/lwoGroupChunk.h +++ b/pandatool/src/lwo/lwoGroupChunk.h @@ -35,7 +35,7 @@ public: protected: bool read_chunks_iff(IffInputFile *in, size_t stop_at); bool read_subchunks_iff(IffInputFile *in, size_t stop_at); - void write_chunks(ostream &out, int indent_level) const; + void write_chunks(std::ostream &out, int indent_level) const; typedef pvector< PT(IffChunk) > Chunks; Chunks _chunks; diff --git a/pandatool/src/lwo/lwoHeader.cxx b/pandatool/src/lwo/lwoHeader.cxx index 4fe302f54d..aba632eb93 100644 --- a/pandatool/src/lwo/lwoHeader.cxx +++ b/pandatool/src/lwo/lwoHeader.cxx @@ -61,7 +61,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoHeader:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " {\n"; indent(out, indent_level + 2) diff --git a/pandatool/src/lwo/lwoHeader.h b/pandatool/src/lwo/lwoHeader.h index f4bbc93c8f..539d49764c 100644 --- a/pandatool/src/lwo/lwoHeader.h +++ b/pandatool/src/lwo/lwoHeader.h @@ -32,7 +32,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; private: bool _valid; diff --git a/pandatool/src/lwo/lwoInputFile.cxx b/pandatool/src/lwo/lwoInputFile.cxx index 78e7dfa10c..a6737855ea 100644 --- a/pandatool/src/lwo/lwoInputFile.cxx +++ b/pandatool/src/lwo/lwoInputFile.cxx @@ -24,6 +24,8 @@ #include "lwoSurface.h" #include "lwoVertexMap.h" +using std::string; + TypeHandle LwoInputFile::_type_handle; /** diff --git a/pandatool/src/lwo/lwoLayer.cxx b/pandatool/src/lwo/lwoLayer.cxx index 75f4a18606..1fea2cd546 100644 --- a/pandatool/src/lwo/lwoLayer.cxx +++ b/pandatool/src/lwo/lwoLayer.cxx @@ -63,9 +63,9 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoLayer:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { number = " << _number << ", flags = 0x" - << hex << _flags << dec << ", pivot = " << _pivot + << std::hex << _flags << std::dec << ", pivot = " << _pivot << ", _name = \"" << _name << "\", _parent = " << _parent << " }\n"; } diff --git a/pandatool/src/lwo/lwoLayer.h b/pandatool/src/lwo/lwoLayer.h index 641311a5e6..a959d4890e 100644 --- a/pandatool/src/lwo/lwoLayer.h +++ b/pandatool/src/lwo/lwoLayer.h @@ -36,12 +36,12 @@ public: int _number; int _flags; LPoint3 _pivot; - string _name; + std::string _name; int _parent; public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/lwo/lwoPoints.cxx b/pandatool/src/lwo/lwoPoints.cxx index 875d6e8909..7abfeea668 100644 --- a/pandatool/src/lwo/lwoPoints.cxx +++ b/pandatool/src/lwo/lwoPoints.cxx @@ -58,7 +58,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoPoints:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { " << _points.size() << " points }\n"; } diff --git a/pandatool/src/lwo/lwoPoints.h b/pandatool/src/lwo/lwoPoints.h index 5cc44bebca..27f2a36ccb 100644 --- a/pandatool/src/lwo/lwoPoints.h +++ b/pandatool/src/lwo/lwoPoints.h @@ -30,7 +30,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; private: typedef pvector Points; diff --git a/pandatool/src/lwo/lwoPolygonTags.cxx b/pandatool/src/lwo/lwoPolygonTags.cxx index aef4b051aa..48f81b47e0 100644 --- a/pandatool/src/lwo/lwoPolygonTags.cxx +++ b/pandatool/src/lwo/lwoPolygonTags.cxx @@ -73,7 +73,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoPolygonTags:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { tag_type = " << _tag_type << ", " << _tmap.size() << " values }\n"; diff --git a/pandatool/src/lwo/lwoPolygonTags.h b/pandatool/src/lwo/lwoPolygonTags.h index bd93f1d524..8603492cda 100644 --- a/pandatool/src/lwo/lwoPolygonTags.h +++ b/pandatool/src/lwo/lwoPolygonTags.h @@ -32,7 +32,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; private: typedef pmap TMap; diff --git a/pandatool/src/lwo/lwoPolygons.cxx b/pandatool/src/lwo/lwoPolygons.cxx index 76736c4f41..22d03c2121 100644 --- a/pandatool/src/lwo/lwoPolygons.cxx +++ b/pandatool/src/lwo/lwoPolygons.cxx @@ -32,7 +32,7 @@ get_num_polygons() const { */ LwoPolygons::Polygon *LwoPolygons:: get_polygon(int n) const { - nassertr(n >= 0 && n < (int)_polygons.size(), (Polygon *)NULL); + nassertr(n >= 0 && n < (int)_polygons.size(), nullptr); return _polygons[n]; } @@ -113,7 +113,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoPolygons:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { polygon_type = " << _polygon_type << ", " << _polygons.size() << " polygons }\n"; diff --git a/pandatool/src/lwo/lwoPolygons.h b/pandatool/src/lwo/lwoPolygons.h index 69d2d20e8b..d7ad655669 100644 --- a/pandatool/src/lwo/lwoPolygons.h +++ b/pandatool/src/lwo/lwoPolygons.h @@ -56,7 +56,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; private: typedef pvector< PT(Polygon) > Polygons; diff --git a/pandatool/src/lwo/lwoStillImage.cxx b/pandatool/src/lwo/lwoStillImage.cxx index 851aa6c8ef..9a31986c43 100644 --- a/pandatool/src/lwo/lwoStillImage.cxx +++ b/pandatool/src/lwo/lwoStillImage.cxx @@ -38,7 +38,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoStillImage:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { filename = \"" << _filename << "\" }\n"; } diff --git a/pandatool/src/lwo/lwoStillImage.h b/pandatool/src/lwo/lwoStillImage.h index c2dc02e4e2..c800cfb006 100644 --- a/pandatool/src/lwo/lwoStillImage.h +++ b/pandatool/src/lwo/lwoStillImage.h @@ -29,7 +29,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/lwo/lwoSurface.cxx b/pandatool/src/lwo/lwoSurface.cxx index edbc67506a..e1318947d9 100644 --- a/pandatool/src/lwo/lwoSurface.cxx +++ b/pandatool/src/lwo/lwoSurface.cxx @@ -41,7 +41,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoSurface:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " {\n"; indent(out, indent_level + 2) diff --git a/pandatool/src/lwo/lwoSurface.h b/pandatool/src/lwo/lwoSurface.h index 96bb1f13d4..75523f0cd2 100644 --- a/pandatool/src/lwo/lwoSurface.h +++ b/pandatool/src/lwo/lwoSurface.h @@ -24,12 +24,12 @@ */ class LwoSurface : public LwoGroupChunk { public: - string _name; - string _source; + std::string _name; + std::string _source; public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; virtual IffChunk *make_new_chunk(IffInputFile *in, IffId id); diff --git a/pandatool/src/lwo/lwoSurfaceBlock.cxx b/pandatool/src/lwo/lwoSurfaceBlock.cxx index c1482bdb7d..8dd32652fa 100644 --- a/pandatool/src/lwo/lwoSurfaceBlock.cxx +++ b/pandatool/src/lwo/lwoSurfaceBlock.cxx @@ -36,7 +36,7 @@ TypeHandle LwoSurfaceBlock::_type_handle; bool LwoSurfaceBlock:: read_iff(IffInputFile *in, size_t stop_at) { PT(IffChunk) chunk = in->get_subchunk(this); - if (chunk == (IffChunk *)NULL) { + if (chunk == nullptr) { return false; } if (!chunk->is_of_type(LwoSurfaceBlockHeader::get_class_type())) { @@ -54,7 +54,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoSurfaceBlock:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " {\n"; _header->write(out, indent_level + 2); diff --git a/pandatool/src/lwo/lwoSurfaceBlock.h b/pandatool/src/lwo/lwoSurfaceBlock.h index acd45a1dd9..bfac032aff 100644 --- a/pandatool/src/lwo/lwoSurfaceBlock.h +++ b/pandatool/src/lwo/lwoSurfaceBlock.h @@ -25,7 +25,7 @@ class LwoSurfaceBlock : public LwoGroupChunk { public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; virtual IffChunk *make_new_chunk(IffInputFile *in, IffId id); diff --git a/pandatool/src/lwo/lwoSurfaceBlockAxis.cxx b/pandatool/src/lwo/lwoSurfaceBlockAxis.cxx index 8698e9dea5..3390debdea 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockAxis.cxx +++ b/pandatool/src/lwo/lwoSurfaceBlockAxis.cxx @@ -38,7 +38,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoSurfaceBlockAxis:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { axis = " << (int)_axis << " }\n"; } diff --git a/pandatool/src/lwo/lwoSurfaceBlockAxis.h b/pandatool/src/lwo/lwoSurfaceBlockAxis.h index 81633ed066..4e0920c57d 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockAxis.h +++ b/pandatool/src/lwo/lwoSurfaceBlockAxis.h @@ -34,7 +34,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/lwo/lwoSurfaceBlockChannel.cxx b/pandatool/src/lwo/lwoSurfaceBlockChannel.cxx index 523b379e4b..94dc45c8af 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockChannel.cxx +++ b/pandatool/src/lwo/lwoSurfaceBlockChannel.cxx @@ -38,7 +38,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoSurfaceBlockChannel:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { channel_id = " << _channel_id << " }\n"; } diff --git a/pandatool/src/lwo/lwoSurfaceBlockChannel.h b/pandatool/src/lwo/lwoSurfaceBlockChannel.h index 0849d185a1..00e35bc28a 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockChannel.h +++ b/pandatool/src/lwo/lwoSurfaceBlockChannel.h @@ -28,7 +28,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/lwo/lwoSurfaceBlockCoordSys.cxx b/pandatool/src/lwo/lwoSurfaceBlockCoordSys.cxx index 4e1e3f0766..e2c9b77a84 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockCoordSys.cxx +++ b/pandatool/src/lwo/lwoSurfaceBlockCoordSys.cxx @@ -38,7 +38,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoSurfaceBlockCoordSys:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { type = " << (int)_type << " }\n"; } diff --git a/pandatool/src/lwo/lwoSurfaceBlockCoordSys.h b/pandatool/src/lwo/lwoSurfaceBlockCoordSys.h index 4c9d777ff3..a9be9419c7 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockCoordSys.h +++ b/pandatool/src/lwo/lwoSurfaceBlockCoordSys.h @@ -33,7 +33,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/lwo/lwoSurfaceBlockEnabled.cxx b/pandatool/src/lwo/lwoSurfaceBlockEnabled.cxx index c4d01dd557..8240539502 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockEnabled.cxx +++ b/pandatool/src/lwo/lwoSurfaceBlockEnabled.cxx @@ -38,7 +38,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoSurfaceBlockEnabled:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { enabled = " << _enabled << " }\n"; } diff --git a/pandatool/src/lwo/lwoSurfaceBlockEnabled.h b/pandatool/src/lwo/lwoSurfaceBlockEnabled.h index 59c42165e9..a07c6ea31c 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockEnabled.h +++ b/pandatool/src/lwo/lwoSurfaceBlockEnabled.h @@ -28,7 +28,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/lwo/lwoSurfaceBlockHeader.cxx b/pandatool/src/lwo/lwoSurfaceBlockHeader.cxx index a4a88d982a..69351fa403 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockHeader.cxx +++ b/pandatool/src/lwo/lwoSurfaceBlockHeader.cxx @@ -43,18 +43,18 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoSurfaceBlockHeader:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " {\n"; indent(out, indent_level + 2) - << "ordinal = 0x" << hex << setfill('0'); + << "ordinal = 0x" << std::hex << std::setfill('0'); - string::const_iterator si; + std::string::const_iterator si; for (si = _ordinal.begin(); si != _ordinal.end(); ++si) { - out << setw(2) << (int)(unsigned char)(*si); + out << std::setw(2) << (int)(unsigned char)(*si); } - out << dec << setfill(' ') << "\n"; + out << std::dec << std::setfill(' ') << "\n"; write_chunks(out, indent_level + 2); indent(out, indent_level) diff --git a/pandatool/src/lwo/lwoSurfaceBlockHeader.h b/pandatool/src/lwo/lwoSurfaceBlockHeader.h index 4ae37b45a5..6249db26bc 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockHeader.h +++ b/pandatool/src/lwo/lwoSurfaceBlockHeader.h @@ -23,11 +23,11 @@ */ class LwoSurfaceBlockHeader : public LwoGroupChunk { public: - string _ordinal; + std::string _ordinal; public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; virtual IffChunk *make_new_chunk(IffInputFile *in, IffId id); diff --git a/pandatool/src/lwo/lwoSurfaceBlockImage.cxx b/pandatool/src/lwo/lwoSurfaceBlockImage.cxx index dce817b6aa..520d8cef2a 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockImage.cxx +++ b/pandatool/src/lwo/lwoSurfaceBlockImage.cxx @@ -38,7 +38,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoSurfaceBlockImage:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { index = " << _index << " }\n"; } diff --git a/pandatool/src/lwo/lwoSurfaceBlockImage.h b/pandatool/src/lwo/lwoSurfaceBlockImage.h index b7710d7561..968f5d3a71 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockImage.h +++ b/pandatool/src/lwo/lwoSurfaceBlockImage.h @@ -28,7 +28,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/lwo/lwoSurfaceBlockOpacity.cxx b/pandatool/src/lwo/lwoSurfaceBlockOpacity.cxx index d6554d0b82..456e1383ca 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockOpacity.cxx +++ b/pandatool/src/lwo/lwoSurfaceBlockOpacity.cxx @@ -40,7 +40,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoSurfaceBlockOpacity:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { type = " << (int)_type << ", opacity = " << _opacity * 100.0 << "%, envelope = " << _envelope diff --git a/pandatool/src/lwo/lwoSurfaceBlockOpacity.h b/pandatool/src/lwo/lwoSurfaceBlockOpacity.h index e923eb538b..906c86154b 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockOpacity.h +++ b/pandatool/src/lwo/lwoSurfaceBlockOpacity.h @@ -40,7 +40,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/lwo/lwoSurfaceBlockProjection.cxx b/pandatool/src/lwo/lwoSurfaceBlockProjection.cxx index 2f6d214177..500d90c2ed 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockProjection.cxx +++ b/pandatool/src/lwo/lwoSurfaceBlockProjection.cxx @@ -38,7 +38,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoSurfaceBlockProjection:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { mode = " << (int)_mode << " }\n"; } diff --git a/pandatool/src/lwo/lwoSurfaceBlockProjection.h b/pandatool/src/lwo/lwoSurfaceBlockProjection.h index 49c816f156..bcbbff41e0 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockProjection.h +++ b/pandatool/src/lwo/lwoSurfaceBlockProjection.h @@ -37,7 +37,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/lwo/lwoSurfaceBlockRefObj.cxx b/pandatool/src/lwo/lwoSurfaceBlockRefObj.cxx index d7dccc5693..1c19fedfac 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockRefObj.cxx +++ b/pandatool/src/lwo/lwoSurfaceBlockRefObj.cxx @@ -38,7 +38,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoSurfaceBlockRefObj:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { name = \"" << _name << "\" }\n"; } diff --git a/pandatool/src/lwo/lwoSurfaceBlockRefObj.h b/pandatool/src/lwo/lwoSurfaceBlockRefObj.h index 65b70a958b..77818957a3 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockRefObj.h +++ b/pandatool/src/lwo/lwoSurfaceBlockRefObj.h @@ -24,11 +24,11 @@ */ class LwoSurfaceBlockRefObj : public LwoChunk { public: - string _name; + std::string _name; public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/lwo/lwoSurfaceBlockRepeat.cxx b/pandatool/src/lwo/lwoSurfaceBlockRepeat.cxx index e264667caa..9036c143fc 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockRepeat.cxx +++ b/pandatool/src/lwo/lwoSurfaceBlockRepeat.cxx @@ -39,7 +39,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoSurfaceBlockRepeat:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { cycles = " << _cycles << ", envelope = " << _envelope << " }\n"; diff --git a/pandatool/src/lwo/lwoSurfaceBlockRepeat.h b/pandatool/src/lwo/lwoSurfaceBlockRepeat.h index eb3beb251c..73c77a4537 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockRepeat.h +++ b/pandatool/src/lwo/lwoSurfaceBlockRepeat.h @@ -31,7 +31,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/lwo/lwoSurfaceBlockTMap.cxx b/pandatool/src/lwo/lwoSurfaceBlockTMap.cxx index f404910611..1f355d2d4d 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockTMap.cxx +++ b/pandatool/src/lwo/lwoSurfaceBlockTMap.cxx @@ -41,7 +41,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoSurfaceBlockTMap:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " {\n"; write_chunks(out, indent_level + 2); diff --git a/pandatool/src/lwo/lwoSurfaceBlockTMap.h b/pandatool/src/lwo/lwoSurfaceBlockTMap.h index 8da9841f46..273522d50a 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockTMap.h +++ b/pandatool/src/lwo/lwoSurfaceBlockTMap.h @@ -24,7 +24,7 @@ class LwoSurfaceBlockTMap : public LwoGroupChunk { public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; virtual IffChunk *make_new_chunk(IffInputFile *in, IffId id); diff --git a/pandatool/src/lwo/lwoSurfaceBlockTransform.cxx b/pandatool/src/lwo/lwoSurfaceBlockTransform.cxx index e2fdccad18..2ed2738161 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockTransform.cxx +++ b/pandatool/src/lwo/lwoSurfaceBlockTransform.cxx @@ -39,7 +39,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoSurfaceBlockTransform:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { vec = " << _vec << ", envelope = " << _envelope << " }\n"; diff --git a/pandatool/src/lwo/lwoSurfaceBlockTransform.h b/pandatool/src/lwo/lwoSurfaceBlockTransform.h index f8fce53163..e3e07a49b8 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockTransform.h +++ b/pandatool/src/lwo/lwoSurfaceBlockTransform.h @@ -33,7 +33,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/lwo/lwoSurfaceBlockVMapName.cxx b/pandatool/src/lwo/lwoSurfaceBlockVMapName.cxx index 208f309e4c..f4db699457 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockVMapName.cxx +++ b/pandatool/src/lwo/lwoSurfaceBlockVMapName.cxx @@ -38,7 +38,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoSurfaceBlockVMapName:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { name = \"" << _name << "\" }\n"; } diff --git a/pandatool/src/lwo/lwoSurfaceBlockVMapName.h b/pandatool/src/lwo/lwoSurfaceBlockVMapName.h index 30de8f3ad6..1433bfad9e 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockVMapName.h +++ b/pandatool/src/lwo/lwoSurfaceBlockVMapName.h @@ -24,11 +24,11 @@ */ class LwoSurfaceBlockVMapName : public LwoChunk { public: - string _name; + std::string _name; public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/lwo/lwoSurfaceBlockWrap.cxx b/pandatool/src/lwo/lwoSurfaceBlockWrap.cxx index ec7cc24796..006be5f8be 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockWrap.cxx +++ b/pandatool/src/lwo/lwoSurfaceBlockWrap.cxx @@ -39,7 +39,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoSurfaceBlockWrap:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { width = " << (int)_width << ", height = " << (int)_height << " }\n"; diff --git a/pandatool/src/lwo/lwoSurfaceBlockWrap.h b/pandatool/src/lwo/lwoSurfaceBlockWrap.h index b046657242..bf18e92da1 100644 --- a/pandatool/src/lwo/lwoSurfaceBlockWrap.h +++ b/pandatool/src/lwo/lwoSurfaceBlockWrap.h @@ -33,7 +33,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/lwo/lwoSurfaceColor.cxx b/pandatool/src/lwo/lwoSurfaceColor.cxx index ceeb5ab747..5a4526eb55 100644 --- a/pandatool/src/lwo/lwoSurfaceColor.cxx +++ b/pandatool/src/lwo/lwoSurfaceColor.cxx @@ -39,7 +39,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoSurfaceColor:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { color = " << _color << ", envelope = " << _envelope << " }\n"; diff --git a/pandatool/src/lwo/lwoSurfaceColor.h b/pandatool/src/lwo/lwoSurfaceColor.h index 77d0740665..584d1e7892 100644 --- a/pandatool/src/lwo/lwoSurfaceColor.h +++ b/pandatool/src/lwo/lwoSurfaceColor.h @@ -30,7 +30,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/lwo/lwoSurfaceParameter.cxx b/pandatool/src/lwo/lwoSurfaceParameter.cxx index f1ff64203b..fd3543f18a 100644 --- a/pandatool/src/lwo/lwoSurfaceParameter.cxx +++ b/pandatool/src/lwo/lwoSurfaceParameter.cxx @@ -39,7 +39,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoSurfaceParameter:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { value = " << _value << ", envelope = " << _envelope << " }\n"; diff --git a/pandatool/src/lwo/lwoSurfaceParameter.h b/pandatool/src/lwo/lwoSurfaceParameter.h index 70a6188f40..075383b370 100644 --- a/pandatool/src/lwo/lwoSurfaceParameter.h +++ b/pandatool/src/lwo/lwoSurfaceParameter.h @@ -30,7 +30,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/lwo/lwoSurfaceSidedness.cxx b/pandatool/src/lwo/lwoSurfaceSidedness.cxx index b67c1492be..2c773b25f6 100644 --- a/pandatool/src/lwo/lwoSurfaceSidedness.cxx +++ b/pandatool/src/lwo/lwoSurfaceSidedness.cxx @@ -38,7 +38,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoSurfaceSidedness:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { sidedness = " << (int)_sidedness << " }\n"; } diff --git a/pandatool/src/lwo/lwoSurfaceSidedness.h b/pandatool/src/lwo/lwoSurfaceSidedness.h index cb8c75ebb2..f64ef112e0 100644 --- a/pandatool/src/lwo/lwoSurfaceSidedness.h +++ b/pandatool/src/lwo/lwoSurfaceSidedness.h @@ -33,7 +33,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/lwo/lwoSurfaceSmoothingAngle.cxx b/pandatool/src/lwo/lwoSurfaceSmoothingAngle.cxx index 1b0570c46b..49c1f729f5 100644 --- a/pandatool/src/lwo/lwoSurfaceSmoothingAngle.cxx +++ b/pandatool/src/lwo/lwoSurfaceSmoothingAngle.cxx @@ -39,7 +39,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoSurfaceSmoothingAngle:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { angle = " << rad_2_deg(_angle) << " degrees }\n"; } diff --git a/pandatool/src/lwo/lwoSurfaceSmoothingAngle.h b/pandatool/src/lwo/lwoSurfaceSmoothingAngle.h index 97600b80aa..c27b9a3080 100644 --- a/pandatool/src/lwo/lwoSurfaceSmoothingAngle.h +++ b/pandatool/src/lwo/lwoSurfaceSmoothingAngle.h @@ -28,7 +28,7 @@ public: public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; public: virtual TypeHandle get_type() const { diff --git a/pandatool/src/lwo/lwoTags.cxx b/pandatool/src/lwo/lwoTags.cxx index c2d9ebbc8d..43eaa2ab70 100644 --- a/pandatool/src/lwo/lwoTags.cxx +++ b/pandatool/src/lwo/lwoTags.cxx @@ -30,9 +30,9 @@ get_num_tags() const { /** * Returns the nth tag of this group. */ -string LwoTags:: +std::string LwoTags:: get_tag(int n) const { - nassertr(n >= 0 && n < (int)_tags.size(), string()); + nassertr(n >= 0 && n < (int)_tags.size(), std::string()); return _tags[n]; } @@ -47,7 +47,7 @@ read_iff(IffInputFile *in, size_t stop_at) { LwoInputFile *lin = DCAST(LwoInputFile, in); while (lin->get_bytes_read() < stop_at && !lin->is_eof()) { - string tag = lin->get_string(); + std::string tag = lin->get_string(); _tags.push_back(tag); } @@ -58,7 +58,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoTags:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { "; diff --git a/pandatool/src/lwo/lwoTags.h b/pandatool/src/lwo/lwoTags.h index 5812965be6..03ac6ede30 100644 --- a/pandatool/src/lwo/lwoTags.h +++ b/pandatool/src/lwo/lwoTags.h @@ -31,11 +31,11 @@ class LwoTags : public LwoChunk { public: int get_num_tags() const; - string get_tag(int n) const; + std::string get_tag(int n) const; public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; private: typedef vector_string Tags; diff --git a/pandatool/src/lwo/lwoVertexMap.cxx b/pandatool/src/lwo/lwoVertexMap.cxx index 396ab91b33..a0ecbf9cd5 100644 --- a/pandatool/src/lwo/lwoVertexMap.cxx +++ b/pandatool/src/lwo/lwoVertexMap.cxx @@ -79,7 +79,7 @@ read_iff(IffInputFile *in, size_t stop_at) { * */ void LwoVertexMap:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_id() << " { map_type = " << _map_type << ", dimension = " << _dimension diff --git a/pandatool/src/lwo/lwoVertexMap.h b/pandatool/src/lwo/lwoVertexMap.h index abbcc0f3cc..e2b059063d 100644 --- a/pandatool/src/lwo/lwoVertexMap.h +++ b/pandatool/src/lwo/lwoVertexMap.h @@ -31,11 +31,11 @@ public: IffId _map_type; int _dimension; - string _name; + std::string _name; public: virtual bool read_iff(IffInputFile *in, size_t stop_at); - virtual void write(ostream &out, int indent_level = 0) const; + virtual void write(std::ostream &out, int indent_level = 0) const; private: typedef pmap VMap; diff --git a/pandatool/src/lwo/test_lwo.cxx b/pandatool/src/lwo/test_lwo.cxx index b541fb8360..baba598440 100644 --- a/pandatool/src/lwo/test_lwo.cxx +++ b/pandatool/src/lwo/test_lwo.cxx @@ -30,7 +30,7 @@ main(int argc, char *argv[]) { } PT(IffChunk) chunk = in.get_chunk(); - while (chunk != (IffChunk *)NULL) { + while (chunk != nullptr) { nout << "Got chunk type " << chunk->get_type() << ":\n"; chunk->write(nout, 2); chunk = in.get_chunk(); diff --git a/pandatool/src/lwoegg/cLwoLayer.cxx b/pandatool/src/lwoegg/cLwoLayer.cxx index 4794ef1429..7356212545 100644 --- a/pandatool/src/lwoegg/cLwoLayer.cxx +++ b/pandatool/src/lwoegg/cLwoLayer.cxx @@ -39,7 +39,7 @@ void CLwoLayer:: connect_egg() { if (_layer->_parent != -1) { const CLwoLayer *parent = _converter->get_layer(_layer->_parent); - if (parent != (CLwoLayer *)NULL) { + if (parent != nullptr) { parent->_egg_group->add_child(_egg_group.p()); return; } diff --git a/pandatool/src/lwoegg/cLwoPoints.cxx b/pandatool/src/lwoegg/cLwoPoints.cxx index 43f48ee690..93a89f79c6 100644 --- a/pandatool/src/lwoegg/cLwoPoints.cxx +++ b/pandatool/src/lwoegg/cLwoPoints.cxx @@ -26,7 +26,7 @@ void CLwoPoints:: add_vmap(const LwoVertexMap *lwo_vmap) { IffId map_type = lwo_vmap->_map_type; - const string &name = lwo_vmap->_name; + const std::string &name = lwo_vmap->_name; bool inserted; if (map_type == IffId("TXUV")) { @@ -52,7 +52,7 @@ add_vmap(const LwoVertexMap *lwo_vmap) { * given vertex, false otherwise. If true, fills in uv with the value. */ bool CLwoPoints:: -get_uv(const string &uv_name, int n, LPoint2 &uv) const { +get_uv(const std::string &uv_name, int n, LPoint2 &uv) const { VMap::const_iterator ni = _txuv.find(uv_name); if (ni == _txuv.end()) { return false; @@ -82,7 +82,7 @@ void CLwoPoints:: make_egg() { // Generate a vpool name based on the layer index, for lack of anything // better. - string vpool_name = "layer" + format_string(_layer->get_number()); + std::string vpool_name = "layer" + format_string(_layer->get_number()); _egg_vpool = new EggVertexPool(vpool_name); } diff --git a/pandatool/src/lwoegg/cLwoPoints.h b/pandatool/src/lwoegg/cLwoPoints.h index b235c3de31..a4dbf642ac 100644 --- a/pandatool/src/lwoegg/cLwoPoints.h +++ b/pandatool/src/lwoegg/cLwoPoints.h @@ -36,7 +36,7 @@ public: CLwoLayer *layer); void add_vmap(const LwoVertexMap *lwo_vmap); - bool get_uv(const string &uv_name, int n, LPoint2 &uv) const; + bool get_uv(const std::string &uv_name, int n, LPoint2 &uv) const; void make_egg(); void connect_egg(); @@ -48,7 +48,7 @@ public: // A number of vertex maps of different types may be associated, but we only // care about some of the types here. - typedef pmap VMap; + typedef pmap VMap; VMap _txuv; VMap _pick; }; diff --git a/pandatool/src/lwoegg/cLwoPolygons.I b/pandatool/src/lwoegg/cLwoPolygons.I index 691d706324..94908debd9 100644 --- a/pandatool/src/lwoegg/cLwoPolygons.I +++ b/pandatool/src/lwoegg/cLwoPolygons.I @@ -21,6 +21,6 @@ CLwoPolygons(LwoToEggConverter *converter, const LwoPolygons *polygons, _polygons(polygons), _points(points) { - _tags = (LwoTags *)NULL; - _surf_ptags = (LwoPolygonTags *)NULL; + _tags = nullptr; + _surf_ptags = nullptr; } diff --git a/pandatool/src/lwoegg/cLwoPolygons.cxx b/pandatool/src/lwoegg/cLwoPolygons.cxx index ad1f600a04..e6a0fac4cf 100644 --- a/pandatool/src/lwoegg/cLwoPolygons.cxx +++ b/pandatool/src/lwoegg/cLwoPolygons.cxx @@ -25,6 +25,8 @@ #include "eggPoint.h" #include "deg_2_rad.h" +using std::string; + /** * Associates the indicated PolygonTags and Tags with the polygons in this * chunk. This may define features such as per-polygon surfaces, parts, and @@ -32,7 +34,7 @@ */ void CLwoPolygons:: add_ptags(const LwoPolygonTags *lwo_ptags, const LwoTags *tags) { - if (_tags != (LwoTags *)NULL && _tags != tags) { + if (_tags != nullptr && _tags != tags) { nout << "Multiple Tags fields in effect on the same polygons.\n"; } _tags = tags; @@ -82,31 +84,31 @@ add_vmad(const LwoDiscontinuousVertexMap *lwo_vmad) { */ CLwoSurface *CLwoPolygons:: get_surface(int polygon_index) const { - if (_surf_ptags == (LwoPolygonTags *)NULL) { + if (_surf_ptags == nullptr) { // No surface definitions. - return (CLwoSurface *)NULL; + return nullptr; } if (!_surf_ptags->has_tag(polygon_index)) { // The polygon isn't tagged. - return (CLwoSurface *)NULL; + return nullptr; } int tag_index = _surf_ptags->get_tag(polygon_index); - if (_tags == (LwoTags *)NULL || tag_index < 0 || + if (_tags == nullptr || tag_index < 0 || tag_index >= _tags->get_num_tags()) { // The tag index is out-of-bounds. nout << "Invalid polygon tag index " << tag_index << "\n"; - return (CLwoSurface *)NULL; + return nullptr; } string tag = _tags->get_tag(tag_index); // Now look up the surface name in the header. CLwoSurface *surface = _converter->get_surface(tag); - if (surface == (CLwoSurface *)NULL) { + if (surface == nullptr) { nout << "Unknown surface " << tag << "\n"; - return (CLwoSurface *)NULL; + return nullptr; } return surface; @@ -182,8 +184,8 @@ make_egg() { */ void CLwoPolygons:: connect_egg() { - nassertv(_points->_layer->_egg_group != (EggGroup *)NULL); - nassertv(_egg_group != (EggGroup *)NULL); + nassertv(_points->_layer->_egg_group != nullptr); + nassertv(_egg_group != nullptr); _points->_layer->_egg_group->steal_children(*_egg_group); } @@ -236,7 +238,7 @@ make_faces() { egg_vertex->set_pos(pos); // Does the vertex used named UV's? - if (surface != (CLwoSurface *)NULL && surface->has_named_uvs()) { + if (surface != nullptr && surface->has_named_uvs()) { string uv_name = surface->get_uv_name(); LPoint2 uv; if (get_uv(uv_name, pindex, vindex, uv)) { @@ -256,7 +258,7 @@ make_faces() { } if (is_valid) { - if (surface != (CLwoSurface *)NULL) { + if (surface != nullptr) { surface->apply_properties(egg_prim, egg_vertices, smooth_angle); } diff --git a/pandatool/src/lwoegg/cLwoPolygons.h b/pandatool/src/lwoegg/cLwoPolygons.h index a11dc0987a..d5c4b4afda 100644 --- a/pandatool/src/lwoegg/cLwoPolygons.h +++ b/pandatool/src/lwoegg/cLwoPolygons.h @@ -43,7 +43,7 @@ public: void add_vmad(const LwoDiscontinuousVertexMap *lwo_vmad); CLwoSurface *get_surface(int polygon_index) const; - bool get_uv(const string &uv_name, int pi, int vi, LPoint2 &uv) const; + bool get_uv(const std::string &uv_name, int pi, int vi, LPoint2 &uv) const; void make_egg(); void connect_egg(); @@ -61,7 +61,7 @@ public: // There might be named maps associated with the polygons to bring a per- // polygon mapping to the UV's. - typedef pmap VMad; + typedef pmap VMad; VMad _txuv; private: diff --git a/pandatool/src/lwoegg/cLwoSurface.I b/pandatool/src/lwoegg/cLwoSurface.I index 80c4c2c3d6..8c39871a08 100644 --- a/pandatool/src/lwoegg/cLwoSurface.I +++ b/pandatool/src/lwoegg/cLwoSurface.I @@ -15,7 +15,7 @@ * Returns the name of the surface. Each surface in a given Lightwave file * should have a unique name. */ -INLINE const string &CLwoSurface:: +INLINE const std::string &CLwoSurface:: get_name() const { return _surface->_name; } @@ -28,7 +28,7 @@ get_name() const { */ INLINE bool CLwoSurface:: has_named_uvs() const { - return (_block != (CLwoSurfaceBlock *)NULL && + return (_block != nullptr && _block->_projection_mode == LwoSurfaceBlockProjection::M_uv); } @@ -36,7 +36,7 @@ has_named_uvs() const { * Returns the name of the set of UV's that are associated with this surface, * if has_named_uvs() is true. */ -INLINE const string &CLwoSurface:: +INLINE const std::string &CLwoSurface:: get_uv_name() const { return _block->_uv_name; } diff --git a/pandatool/src/lwoegg/cLwoSurface.cxx b/pandatool/src/lwoegg/cLwoSurface.cxx index f75932b975..63559dd62f 100644 --- a/pandatool/src/lwoegg/cLwoSurface.cxx +++ b/pandatool/src/lwoegg/cLwoSurface.cxx @@ -39,8 +39,8 @@ CLwoSurface(LwoToEggConverter *converter, const LwoSurface *surface) : _rgb.set(1.0, 1.0, 1.0); _checked_material = false; _checked_texture = false; - _map_uvs = NULL; - _block = (CLwoSurfaceBlock *)NULL; + _map_uvs = nullptr; + _block = nullptr; // Walk through the chunk list, looking for some basic properties. int num_chunks = _surface->get_num_chunks(); @@ -107,7 +107,7 @@ CLwoSurface(LwoToEggConverter *converter, const LwoSurface *surface) : block->_channel_id == IffId("COLR") && block->_enabled) { // Now save the block with the lowest ordinal. - if (_block == (CLwoSurfaceBlock *)NULL) { + if (_block == nullptr) { _block = block; } else if (block->_ordinal < _block->_ordinal) { @@ -146,7 +146,7 @@ CLwoSurface(LwoToEggConverter *converter, const LwoSurface *surface) : */ CLwoSurface:: ~CLwoSurface() { - if (_block != (CLwoSurfaceBlock *)NULL) { + if (_block != nullptr) { delete _block; } } @@ -164,7 +164,7 @@ apply_properties(EggPrimitive *egg_prim, vector_PT_EggVertex &egg_vertices, if (!_surface->_source.empty()) { // This surface is derived from another surface; apply that one first. CLwoSurface *parent = _converter->get_surface(_surface->_source); - if (parent != (CLwoSurface *)NULL && parent != this) { + if (parent != nullptr && parent != this) { parent->apply_properties(egg_prim, egg_vertices, smooth_angle); } } @@ -190,7 +190,7 @@ apply_properties(EggPrimitive *egg_prim, vector_PT_EggVertex &egg_vertices, } if ((_flags & F_smooth_angle) != 0) { - smooth_angle = max(smooth_angle, _smooth_angle); + smooth_angle = std::max(smooth_angle, _smooth_angle); } } @@ -204,13 +204,13 @@ apply_properties(EggPrimitive *egg_prim, vector_PT_EggVertex &egg_vertices, bool CLwoSurface:: check_texture() { if (_checked_texture) { - return (_egg_texture != (EggTexture *)NULL); + return (_egg_texture != nullptr); } _checked_texture = true; - _egg_texture = (EggTexture *)NULL; - _map_uvs = NULL; + _egg_texture = nullptr; + _map_uvs = nullptr; - if (_block == (CLwoSurfaceBlock *)NULL) { + if (_block == nullptr) { // No texture. Not even a shader block. return false; } @@ -222,7 +222,7 @@ check_texture() { } CLwoClip *clip = _converter->get_clip(clip_index); - if (clip == (CLwoClip *)NULL) { + if (clip == nullptr) { nout << "No clip image with index " << clip_index << "\n"; return false; } @@ -281,10 +281,10 @@ check_texture() { bool CLwoSurface:: check_material() { if (_checked_material) { - return (_egg_material != (EggMaterial *)NULL); + return (_egg_material != nullptr); } _checked_material = true; - _egg_material = (EggMaterial *)NULL; + _egg_material = nullptr; if (!_converter->_make_materials) { // If we aren't making materials, then don't make a material. @@ -336,7 +336,7 @@ check_material() { */ void CLwoSurface:: generate_uvs(vector_PT_EggVertex &egg_vertices) { - if (_map_uvs == NULL) { + if (_map_uvs == nullptr) { return; } diff --git a/pandatool/src/lwoegg/cLwoSurface.h b/pandatool/src/lwoegg/cLwoSurface.h index 09b3762656..ec098f182f 100644 --- a/pandatool/src/lwoegg/cLwoSurface.h +++ b/pandatool/src/lwoegg/cLwoSurface.h @@ -41,7 +41,7 @@ public: CLwoSurface(LwoToEggConverter *converter, const LwoSurface *surface); ~CLwoSurface(); - INLINE const string &get_name() const; + INLINE const std::string &get_name() const; void apply_properties(EggPrimitive *egg_prim, vector_PT_EggVertex &egg_vertices, @@ -50,7 +50,7 @@ public: bool check_material(); INLINE bool has_named_uvs() const; - INLINE const string &get_uv_name() const; + INLINE const std::string &get_uv_name() const; enum Flags { diff --git a/pandatool/src/lwoegg/cLwoSurfaceBlock.cxx b/pandatool/src/lwoegg/cLwoSurfaceBlock.cxx index 1902a28377..98d4c502f0 100644 --- a/pandatool/src/lwoegg/cLwoSurfaceBlock.cxx +++ b/pandatool/src/lwoegg/cLwoSurfaceBlock.cxx @@ -45,7 +45,7 @@ CLwoSurfaceBlock(LwoToEggConverter *converter, const LwoSurfaceBlock *block) : _h_wrap = LwoSurfaceBlockWrap::M_repeat; _w_repeat = 1.0; _h_repeat = 1.0; - _tmap = (CLwoSurfaceBlockTMap *)NULL; + _tmap = nullptr; // Scan the chunks in the header. int num_hchunks = _block->_header->get_num_chunks(); @@ -71,7 +71,7 @@ CLwoSurfaceBlock(LwoToEggConverter *converter, const LwoSurfaceBlock *block) : if (chunk->is_of_type(LwoSurfaceBlockTMap::get_class_type())) { const LwoSurfaceBlockTMap *lwo_tmap = DCAST(LwoSurfaceBlockTMap, chunk); - if (_tmap != (CLwoSurfaceBlockTMap *)NULL) { + if (_tmap != nullptr) { nout << "Two TMAP chunks encountered within surface block.\n"; delete _tmap; } @@ -113,7 +113,7 @@ CLwoSurfaceBlock(LwoToEggConverter *converter, const LwoSurfaceBlock *block) : } } - if (_tmap != (CLwoSurfaceBlockTMap *)NULL) { + if (_tmap != nullptr) { _tmap->get_transform(_transform); } @@ -144,7 +144,7 @@ CLwoSurfaceBlock(LwoToEggConverter *converter, const LwoSurfaceBlock *block) : */ CLwoSurfaceBlock:: ~CLwoSurfaceBlock() { - if (_tmap != (CLwoSurfaceBlockTMap *)NULL) { + if (_tmap != nullptr) { delete _tmap; } } diff --git a/pandatool/src/lwoegg/cLwoSurfaceBlock.h b/pandatool/src/lwoegg/cLwoSurfaceBlock.h index d62f73684d..cf86126f26 100644 --- a/pandatool/src/lwoegg/cLwoSurfaceBlock.h +++ b/pandatool/src/lwoegg/cLwoSurfaceBlock.h @@ -38,7 +38,7 @@ public: IffId _block_type; IffId _channel_id; - string _ordinal; + std::string _ordinal; bool _enabled; LwoSurfaceBlockOpacity::Type _opacity_type; @@ -54,7 +54,7 @@ public: LwoSurfaceBlockWrap::Mode _h_wrap; PN_stdfloat _w_repeat; PN_stdfloat _h_repeat; - string _uv_name; + std::string _uv_name; LwoToEggConverter *_converter; CPT(LwoSurfaceBlock) _block; diff --git a/pandatool/src/lwoegg/cLwoSurfaceBlockTMap.h b/pandatool/src/lwoegg/cLwoSurfaceBlockTMap.h index 4fde4938ca..075ed4182e 100644 --- a/pandatool/src/lwoegg/cLwoSurfaceBlockTMap.h +++ b/pandatool/src/lwoegg/cLwoSurfaceBlockTMap.h @@ -37,7 +37,7 @@ public: LVecBase3 _size; LVecBase3 _rotation; - string _reference_object; + std::string _reference_object; LwoSurfaceBlockCoordSys::Type _csys; diff --git a/pandatool/src/lwoegg/lwoToEggConverter.cxx b/pandatool/src/lwoegg/lwoToEggConverter.cxx index fa94f560be..42844f19f0 100644 --- a/pandatool/src/lwoegg/lwoToEggConverter.cxx +++ b/pandatool/src/lwoegg/lwoToEggConverter.cxx @@ -37,7 +37,7 @@ */ LwoToEggConverter:: LwoToEggConverter() { - _generic_layer = (CLwoLayer *)NULL; + _generic_layer = nullptr; _make_materials = true; } @@ -69,7 +69,7 @@ make_copy() { /** * Returns the English name of the file type this converter supports. */ -string LwoToEggConverter:: +std::string LwoToEggConverter:: get_name() const { return "Lightwave"; } @@ -77,7 +77,7 @@ get_name() const { /** * Returns the common extension of the file type this converter supports. */ -string LwoToEggConverter:: +std::string LwoToEggConverter:: get_extension() const { return "lwo"; } @@ -110,7 +110,7 @@ convert_file(const Filename &filename) { } PT(IffChunk) chunk = in.get_chunk(); - if (chunk == (IffChunk *)NULL) { + if (chunk == nullptr) { nout << "Unable to read " << filename << "\n"; return false; } @@ -162,7 +162,7 @@ get_layer(int number) const { if (number >= 0 && number < (int)_layers.size()) { return _layers[number]; } - return (CLwoLayer *)NULL; + return nullptr; } /** @@ -174,7 +174,7 @@ get_clip(int number) const { if (number >= 0 && number < (int)_clips.size()) { return _clips[number]; } - return (CLwoClip *)NULL; + return nullptr; } /** @@ -182,13 +182,13 @@ get_clip(int number) const { * there is no such surface. */ CLwoSurface *LwoToEggConverter:: -get_surface(const string &name) const { +get_surface(const std::string &name) const { Surfaces::const_iterator si; si = _surfaces.find(name); if (si != _surfaces.end()) { return (*si).second; } - return (CLwoSurface *)NULL; + return nullptr; } /** @@ -199,15 +199,15 @@ void LwoToEggConverter:: cleanup() { _lwo_header.clear(); - if (_generic_layer != (CLwoLayer *)NULL) { + if (_generic_layer != nullptr) { delete _generic_layer; - _generic_layer = (CLwoLayer *)NULL; + _generic_layer = nullptr; } Layers::iterator li; for (li = _layers.begin(); li != _layers.end(); ++li) { CLwoLayer *layer = (*li); - if (layer != (CLwoLayer *)NULL) { + if (layer != nullptr) { delete layer; } } @@ -216,7 +216,7 @@ cleanup() { Clips::iterator ci; for (ci = _clips.begin(); ci != _clips.end(); ++ci) { CLwoClip *clip = (*ci); - if (clip != (CLwoClip *)NULL) { + if (clip != nullptr) { delete clip; } } @@ -250,11 +250,11 @@ cleanup() { */ void LwoToEggConverter:: collect_lwo() { - CLwoLayer *last_layer = (CLwoLayer *)NULL; - CLwoPoints *last_points = (CLwoPoints *)NULL; - CLwoPolygons *last_polygons = (CLwoPolygons *)NULL; + CLwoLayer *last_layer = nullptr; + CLwoPoints *last_points = nullptr; + CLwoPolygons *last_polygons = nullptr; - const LwoTags *tags = (const LwoTags *)NULL; + const LwoTags *tags = nullptr; int num_chunks = _lwo_header->get_num_chunks(); for (int i = 0; i < num_chunks; i++) { @@ -266,13 +266,13 @@ collect_lwo() { int number = layer->get_number(); slot_layer(number); - if (_layers[number] != (CLwoLayer *)NULL) { + if (_layers[number] != nullptr) { nout << "Warning: multiple layers with number " << number << "\n"; } _layers[number] = layer; last_layer = layer; - last_points = (CLwoPoints *)NULL; - last_polygons = (CLwoPolygons *)NULL; + last_points = nullptr; + last_polygons = nullptr; } else if (chunk->is_of_type(LwoClip::get_class_type())) { const LwoClip *lwo_clip = DCAST(LwoClip, chunk); @@ -281,13 +281,13 @@ collect_lwo() { int index = clip->get_index(); slot_clip(index); - if (_clips[index] != (CLwoClip *)NULL) { + if (_clips[index] != nullptr) { nout << "Warning: multiple clips with index " << index << "\n"; } _clips[index] = clip; } else if (chunk->is_of_type(LwoPoints::get_class_type())) { - if (last_layer == (CLwoLayer *)NULL) { + if (last_layer == nullptr) { last_layer = make_generic_layer(); } @@ -297,7 +297,7 @@ collect_lwo() { last_points = points; } else if (chunk->is_of_type(LwoVertexMap::get_class_type())) { - if (last_points == (CLwoPoints *)NULL) { + if (last_points == nullptr) { nout << "Vertex map chunk encountered without a preceding points chunk.\n"; } else { const LwoVertexMap *lwo_vmap = DCAST(LwoVertexMap, chunk); @@ -305,7 +305,7 @@ collect_lwo() { } } else if (chunk->is_of_type(LwoDiscontinuousVertexMap::get_class_type())) { - if (last_polygons == (CLwoPolygons *)NULL) { + if (last_polygons == nullptr) { nout << "Discontinous vertex map chunk encountered without a preceding polygons chunk.\n"; } else { const LwoDiscontinuousVertexMap *lwo_vmad = DCAST(LwoDiscontinuousVertexMap, chunk); @@ -316,7 +316,7 @@ collect_lwo() { tags = DCAST(LwoTags, chunk); } else if (chunk->is_of_type(LwoPolygons::get_class_type())) { - if (last_points == (CLwoPoints *)NULL) { + if (last_points == nullptr) { nout << "Polygon chunk encountered without a preceding points chunk.\n"; } else { const LwoPolygons *lwo_polygons = DCAST(LwoPolygons, chunk); @@ -327,9 +327,9 @@ collect_lwo() { } } else if (chunk->is_of_type(LwoPolygonTags::get_class_type())) { - if (last_polygons == (CLwoPolygons *)NULL) { + if (last_polygons == nullptr) { nout << "Polygon tags chunk encountered without a preceding polygons chunk.\n"; - } else if (tags == (LwoTags *)NULL) { + } else if (tags == nullptr) { nout << "Polygon tags chunk encountered without a preceding tags chunk.\n"; } else { const LwoPolygonTags *lwo_ptags = DCAST(LwoPolygonTags, chunk); @@ -337,7 +337,7 @@ collect_lwo() { } } else if (chunk->is_of_type(LwoSurface::get_class_type())) { - if (last_layer == (CLwoLayer *)NULL) { + if (last_layer == nullptr) { last_layer = make_generic_layer(); } @@ -358,14 +358,14 @@ collect_lwo() { */ void LwoToEggConverter:: make_egg() { - if (_generic_layer != (CLwoLayer *)NULL) { + if (_generic_layer != nullptr) { _generic_layer->make_egg(); } Layers::iterator li; for (li = _layers.begin(); li != _layers.end(); ++li) { CLwoLayer *layer = (*li); - if (layer != (CLwoLayer *)NULL) { + if (layer != nullptr) { layer->make_egg(); } } @@ -388,14 +388,14 @@ make_egg() { */ void LwoToEggConverter:: connect_egg() { - if (_generic_layer != (CLwoLayer *)NULL) { + if (_generic_layer != nullptr) { _generic_layer->connect_egg(); } Layers::iterator li; for (li = _layers.begin(); li != _layers.end(); ++li) { CLwoLayer *layer = (*li); - if (layer != (CLwoLayer *)NULL) { + if (layer != nullptr) { layer->connect_egg(); } } @@ -421,7 +421,7 @@ void LwoToEggConverter:: slot_layer(int number) { nassertv(number - (int)_layers.size() < 1000); while (number >= (int)_layers.size()) { - _layers.push_back((CLwoLayer *)NULL); + _layers.push_back(nullptr); } nassertv(number >= 0 && number < (int)_layers.size()); } @@ -434,7 +434,7 @@ void LwoToEggConverter:: slot_clip(int number) { nassertv(number - (int)_clips.size() < 1000); while (number >= (int)_clips.size()) { - _clips.push_back((CLwoClip *)NULL); + _clips.push_back(nullptr); } nassertv(number >= 0 && number < (int)_clips.size()); } @@ -447,7 +447,7 @@ slot_clip(int number) { */ CLwoLayer *LwoToEggConverter:: make_generic_layer() { - nassertr(_generic_layer == (CLwoLayer *)NULL, _generic_layer); + nassertr(_generic_layer == nullptr, _generic_layer); PT(LwoLayer) layer = new LwoLayer; layer->make_generic(); diff --git a/pandatool/src/lwoegg/lwoToEggConverter.h b/pandatool/src/lwoegg/lwoToEggConverter.h index bd4a5a2e41..c4380a21f7 100644 --- a/pandatool/src/lwoegg/lwoToEggConverter.h +++ b/pandatool/src/lwoegg/lwoToEggConverter.h @@ -43,8 +43,8 @@ public: virtual SomethingToEggConverter *make_copy(); - virtual string get_name() const; - virtual string get_extension() const; + virtual std::string get_name() const; + virtual std::string get_extension() const; virtual bool convert_file(const Filename &filename); bool convert_lwo(const LwoHeader *lwo_header); @@ -53,7 +53,7 @@ public: CLwoLayer *get_layer(int number) const; CLwoClip *get_clip(int number) const; - CLwoSurface *get_surface(const string &name) const; + CLwoSurface *get_surface(const std::string &name) const; bool _make_materials; @@ -83,7 +83,7 @@ private: typedef pvector Polygons; Polygons _polygons; - typedef pmap Surfaces; + typedef pmap Surfaces; Surfaces _surfaces; }; diff --git a/pandatool/src/lwoprogs/lwoScan.cxx b/pandatool/src/lwoprogs/lwoScan.cxx index a7fbf46933..c299a3a783 100644 --- a/pandatool/src/lwoprogs/lwoScan.cxx +++ b/pandatool/src/lwoprogs/lwoScan.cxx @@ -44,11 +44,11 @@ run() { } PT(IffChunk) chunk = in.get_chunk(); - if (chunk == (IffChunk *)NULL) { + if (chunk == nullptr) { nout << "Unable to read file.\n"; } else { - while (chunk != (IffChunk *)NULL) { - chunk->write(cout, 0); + while (chunk != nullptr) { + chunk->write(std::cout, 0); chunk = in.get_chunk(); } } diff --git a/pandatool/src/maxegg/maxEgg.cxx b/pandatool/src/maxegg/maxEgg.cxx index 2b77f06767..798192e26c 100644 --- a/pandatool/src/maxegg/maxEgg.cxx +++ b/pandatool/src/maxegg/maxEgg.cxx @@ -297,7 +297,7 @@ ClassDesc* GetMaxEggPluginDesc() { return &MaxEggPluginDesc; } // Initialize class-static variables Mesh MaxEggPlugin::mesh; short MaxEggPlugin::meshBuilt=0; -HWND MaxEggPlugin::hMaxEggParams = NULL; +HWND MaxEggPlugin::hMaxEggParams = nullptr; IObjParam *MaxEggPlugin::iObjParams; /* MaxEggPluginOptionsDlgProc() - This is the callback function for the @@ -454,9 +454,9 @@ void MaxEggPlugin::EndEditParams( IObjParam *ip, ULONG flags,Animatable *prev) if ( flags&END_EDIT_REMOVEUI ) { ip->UnRegisterDlgWnd(hMaxEggParams); ip->DeleteRollupPage(hMaxEggParams); - hMaxEggParams = NULL; + hMaxEggParams = nullptr; } else { - SetWindowLongPtr( hMaxEggParams, GWLP_USERDATA, NULL ); + SetWindowLongPtr( hMaxEggParams, GWLP_USERDATA, 0L ); } } @@ -585,8 +585,8 @@ void MaxEggPlugin::DoExport() { } else { _stprintf(cmdLine, _T("pview \"%s\""), eggList[i]->_file_name); } - CreateProcess(NULL, cmdLine, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, - NULL, NULL, &si, &pi); + CreateProcess(nullptr, cmdLine, nullptr, nullptr, FALSE, CREATE_NEW_CONSOLE, + nullptr, nullptr, &si, &pi); pviewed += 1; } } @@ -634,10 +634,10 @@ int MaxEggPluginCreateMouseCallBack::proc(ViewExp *vpt,int msg, int point, int f if (msg==MOUSE_POINT||msg==MOUSE_MOVE) { switch(point) { case 0: - mat.SetTrans(vpt->SnapPoint(m,m,NULL,SNAP_IN_PLANE)); + mat.SetTrans(vpt->SnapPoint(m,m,nullptr,SNAP_IN_PLANE)); break; case 1: - mat.SetTrans(vpt->SnapPoint(m,m,NULL,SNAP_IN_PLANE)); + mat.SetTrans(vpt->SnapPoint(m,m,nullptr,SNAP_IN_PLANE)); if (msg==MOUSE_POINT) return CREATE_STOP; break; } @@ -718,7 +718,7 @@ int MaxEggPlugin::Display(TimeValue t, INode* inode, ViewExp *vpt, int flags) gw->setColor( LINE_COLOR, GetSelColor()); else if(!inode->IsFrozen()) gw->setColor( LINE_COLOR, GetUIColor(COLOR_TAPE_OBJ)); - mesh.render( gw, mtl, NULL, COMP_ALL); + mesh.render( gw, mtl, nullptr, COMP_ALL); return 0; } @@ -838,7 +838,7 @@ __declspec( dllexport ) ClassDesc* LibClassDesc(int i) { switch(i) { case 0: return GetMaxEggPluginDesc(); - default: return NULL; + default: return nullptr; } } @@ -855,6 +855,6 @@ TCHAR *GetString(int id) static TCHAR buf[256]; if (hInstance) - return LoadString(hInstance, id, buf, sizeof(buf)) ? buf : NULL; - return NULL; + return LoadString(hInstance, id, buf, sizeof(buf)) ? buf : nullptr; + return nullptr; } diff --git a/pandatool/src/maxegg/maxEgg.h b/pandatool/src/maxegg/maxEgg.h index d10d449a0f..2d9765ee01 100644 --- a/pandatool/src/maxegg/maxEgg.h +++ b/pandatool/src/maxegg/maxEgg.h @@ -19,6 +19,10 @@ #include #include #include "errno.h" + +using std::min; +using std::max; + #include "Max.h" #include "eggGroup.h" #include "eggTable.h" @@ -119,7 +123,7 @@ class MaxEggPlugin : public HelperObject void AddEgg(MaxOptionsDialog *newEgg); void RemoveEgg(int i); - MaxOptionsDialog *GetEgg(int i) { return (i >= 0 && i < numEggs) ? eggList[i] : NULL; } + MaxOptionsDialog *GetEgg(int i) { return (i >= 0 && i < numEggs) ? eggList[i] : nullptr; } // Required implimented virtual methods: inherited virtual methods for // Reference-management diff --git a/pandatool/src/maxegg/maxEggLoader.cxx b/pandatool/src/maxegg/maxEggLoader.cxx index ba4c705965..a6855657e6 100644 --- a/pandatool/src/maxegg/maxEggLoader.cxx +++ b/pandatool/src/maxegg/maxEggLoader.cxx @@ -26,6 +26,9 @@ #include "eggPolysetMaker.h" #include "eggBin.h" +using std::min; +using std::max; + #include #include "Max.h" #include "istdplug.h" @@ -39,6 +42,8 @@ #include "maxEggLoader.h" +using std::vector; + class MaxEggMesh; class MaxEggJoint; class MaxEggTex; @@ -64,7 +69,7 @@ public: typedef second_of_pair_iterator MeshIterator; typedef phash_map JointTable; typedef second_of_pair_iterator JointIterator; - typedef phash_map TexTable; + typedef phash_map TexTable; typedef second_of_pair_iterator TexIterator; MeshTable _mesh_tab; @@ -296,7 +301,7 @@ void MaxEggJoint::CreateMaxBone(void) // MaxEggMesh -typedef pair MaxEggWeight; +typedef std::pair MaxEggWeight; struct MaxEggVertex { @@ -344,7 +349,7 @@ class MaxEggMesh { public: - string _name; + std::string _name; TriObject *_obj; Mesh *_mesh; INode *_node; @@ -434,7 +439,7 @@ MaxEggMesh *MaxEggLoader::GetMesh(EggVertexPool *pool) { MaxEggMesh *result = _mesh_tab[pool]; if (result == 0) { - string name = pool->get_name(); + std::string name = pool->get_name(); int nsize = name.size(); if ((nsize > 6) && (name.rfind(".verts")==(nsize-6))) name.resize(nsize-6); @@ -637,7 +642,7 @@ bool MaxEggLoader::ConvertEggData(EggData *data, bool merge, bool model, bool an AnimateOff(); _next_tex = 0; - TraverseEggNode(data, NULL); + TraverseEggNode(data, nullptr); for (ci = _mesh_tab.begin(); ci != _mesh_tab.end(); ++ci) { MaxEggMesh *mesh = (*ci); diff --git a/pandatool/src/maxegg/maxNodeDesc.cxx b/pandatool/src/maxegg/maxNodeDesc.cxx index 57a9d7385f..7e0ed3d964 100644 --- a/pandatool/src/maxegg/maxNodeDesc.cxx +++ b/pandatool/src/maxegg/maxNodeDesc.cxx @@ -23,7 +23,7 @@ MaxNodeDesc:: MaxNodeDesc(MaxNodeDesc *parent, INode *max_node) : _parent(parent) { - if (max_node != NULL) { + if (max_node != nullptr) { const TCHAR *max_name = max_node->GetName(); #ifdef _UNICODE char name_mb [1024]; @@ -35,15 +35,15 @@ MaxNodeDesc(MaxNodeDesc *parent, INode *max_node) : #endif } - _max_node = (INode *)NULL; - _egg_group = (EggGroup *)NULL; - _egg_table = (EggTable *)NULL; - _anim = (EggXfmSAnim *)NULL; + _max_node = nullptr; + _egg_group = nullptr; + _egg_table = nullptr; + _anim = nullptr; _joint_type = JT_none; - _joint_entry = NULL; + _joint_entry = nullptr; // Add ourselves to our parent. - if (_parent != (MaxNodeDesc *)NULL) { + if (_parent != nullptr) { _parent->_children.push_back(this); } } @@ -59,7 +59,7 @@ MaxNodeDesc:: */ void MaxNodeDesc:: from_INode(INode *max_node) { - if (_max_node == (INode *)NULL) { + if (_max_node == nullptr) { _max_node = max_node; // This is how I decided to check to see if this max node is a joint. It @@ -78,7 +78,7 @@ from_INode(INode *max_node) { // This node is a joint. _joint_type = JT_node_joint; - if (_parent != (MaxNodeDesc *)NULL) { + if (_parent != nullptr) { _parent->mark_joint_parent(); } } @@ -91,7 +91,7 @@ from_INode(INode *max_node) { */ bool MaxNodeDesc:: has_max_node() const { - return (_max_node != (INode *)NULL); + return (_max_node != nullptr); } /** @@ -100,7 +100,7 @@ has_max_node() const { */ INode *MaxNodeDesc:: get_max_node() const { - nassertr(_max_node != (INode *)NULL, _max_node); + nassertr(_max_node != nullptr, _max_node); return _max_node; } @@ -142,9 +142,9 @@ is_node_joint() const { */ void MaxNodeDesc:: clear_egg() { - _egg_group = (EggGroup *)NULL; - _egg_table = (EggTable *)NULL; - _anim = (EggXfmSAnim *)NULL; + _egg_group = nullptr; + _egg_table = nullptr; + _anim = nullptr; Children::const_iterator ci; for (ci = _children.begin(); ci != _children.end(); ++ci) { @@ -161,7 +161,7 @@ void MaxNodeDesc:: mark_joint_parent() { if (_joint_type == JT_none) { _joint_type = JT_joint_parent; - if (_parent != (MaxNodeDesc *)NULL) { + if (_parent != nullptr) { _parent->mark_joint_parent(); } } diff --git a/pandatool/src/maxegg/maxNodeDesc.h b/pandatool/src/maxegg/maxNodeDesc.h index 42bb1f4acc..3b45fe0793 100644 --- a/pandatool/src/maxegg/maxNodeDesc.h +++ b/pandatool/src/maxegg/maxNodeDesc.h @@ -21,7 +21,7 @@ */ class MaxNodeDesc : public ReferenceCount, public Namable { public: - MaxNodeDesc(MaxNodeDesc *parent = NULL, INode *max_node = NULL); + MaxNodeDesc(MaxNodeDesc *parent = nullptr, INode *max_node = nullptr); ~MaxNodeDesc(); void from_INode(INode *max_node); diff --git a/pandatool/src/maxegg/maxNodeTree.cxx b/pandatool/src/maxegg/maxNodeTree.cxx index 58f980c281..bb52b887f1 100644 --- a/pandatool/src/maxegg/maxNodeTree.cxx +++ b/pandatool/src/maxegg/maxNodeTree.cxx @@ -21,9 +21,9 @@ MaxNodeTree() { _root = new MaxNodeDesc; _fps = 0.0; _export_mesh = false; - _egg_data = (EggData *)NULL; - _egg_root = (EggGroupNode *)NULL; - _skeleton_node = (EggGroupNode *)NULL; + _egg_data = nullptr; + _egg_root = nullptr; + _skeleton_node = nullptr; } /** @@ -88,7 +88,7 @@ bool MaxNodeTree:: build_complete_hierarchy(INode *root, ULONG *selection_list, int len) { // Get the entire Max scene. - if (root == NULL) { + if (root == nullptr) { // *** Log an error return false; } @@ -117,7 +117,7 @@ get_num_nodes() const { */ MaxNodeDesc *MaxNodeTree:: get_node(int n) const { - nassertr(n >= 0 && n < (int)_nodes.size(), NULL); + nassertr(n >= 0 && n < (int)_nodes.size(), nullptr); return _nodes[n]; } @@ -140,13 +140,13 @@ clear_egg(EggData *egg_data, EggGroupNode *egg_root, */ EggGroup *MaxNodeTree:: get_egg_group(MaxNodeDesc *node_desc) { - nassertr(_egg_root != (EggGroupNode *)NULL, NULL); + nassertr(_egg_root != nullptr, nullptr); - if (node_desc->_egg_group == (EggGroup *)NULL) { + if (node_desc->_egg_group == nullptr) { // We need to make a new group node. EggGroup *egg_group; - nassertr(node_desc->_parent != (MaxNodeDesc *)NULL, NULL); + nassertr(node_desc->_parent != nullptr, nullptr); egg_group = new EggGroup(node_desc->get_name()); if (node_desc->is_joint()) { egg_group->set_group_type(EggGroup::GT_joint); @@ -186,12 +186,12 @@ get_egg_group(MaxNodeDesc *node_desc) { */ EggTable *MaxNodeTree:: get_egg_table(MaxNodeDesc *node_desc) { - nassertr(_skeleton_node != (EggGroupNode *)NULL, NULL); - nassertr(node_desc->is_joint(), NULL); + nassertr(_skeleton_node != nullptr, nullptr); + nassertr(node_desc->is_joint(), nullptr); - if (node_desc->_egg_table == (EggTable *)NULL) { + if (node_desc->_egg_table == nullptr) { // We need to make a new table node. - nassertr(node_desc->_parent != (MaxNodeDesc *)NULL, NULL); + nassertr(node_desc->_parent != nullptr, nullptr); EggTable *egg_table = new EggTable(node_desc->get_name()); node_desc->_anim = new EggXfmSAnim("xform", @@ -256,7 +256,7 @@ r_build_node(INode* max_node) { INode *parent_node; if (max_node->IsRootNode()) { - parent_node = NULL; + parent_node = nullptr; } else { parent_node = max_node->GetParentNode(); } @@ -309,7 +309,7 @@ find_node(INode* max_node) { return (*ni).second; } - return NULL; + return nullptr; } /** diff --git a/pandatool/src/maxegg/maxOptionsDialog.cxx b/pandatool/src/maxegg/maxOptionsDialog.cxx index 556b1a0888..fdcd46cf3e 100644 --- a/pandatool/src/maxegg/maxOptionsDialog.cxx +++ b/pandatool/src/maxegg/maxOptionsDialog.cxx @@ -245,7 +245,7 @@ void RemoveNodeCB::proc(INodeTab &nodeTab) { } MaxEggOptions::MaxEggOptions() { - _max_interface = NULL; + _max_interface = nullptr; _anim_type = MaxEggOptions::AT_model; _start_frame = INT_MIN; _end_frame = INT_MIN; @@ -593,7 +593,7 @@ bool MaxOptionsDialog::UpdateFromUI(HWND hWnd) { _stprintf(_short_name, _T("%.*s..."), sizeof(_short_name)-4, temp); else { _tcscpy(_short_name, temp); - _short_name[_tcslen(_short_name) - 4] = NULL; //Cut off the .egg + _short_name[_tcslen(_short_name) - 4] = 0; //Cut off the .egg } _start_frame = newSF; diff --git a/pandatool/src/maxegg/maxToEggConverter.cxx b/pandatool/src/maxegg/maxToEggConverter.cxx index 6e79178fc5..41718f66e8 100644 --- a/pandatool/src/maxegg/maxToEggConverter.cxx +++ b/pandatool/src/maxegg/maxToEggConverter.cxx @@ -27,6 +27,8 @@ #include "maxEgg.h" #include "config_putil.h" +using std::string; + /** * */ @@ -51,7 +53,7 @@ void MaxToEggConverter::reset() { _cur_tref = 0; _current_frame = 0; _textures.clear(); - _egg_data = NULL; + _egg_data = nullptr; } /** @@ -103,7 +105,7 @@ bool MaxToEggConverter::convert(MaxEggOptions *options) { if (_options->_export_whole_scene) { _tree._export_mesh = false; - all_ok = _tree.build_complete_hierarchy(_options->_max_interface->GetRootNode(), NULL, 0); + all_ok = _tree.build_complete_hierarchy(_options->_max_interface->GetRootNode(), nullptr, 0); } else { _tree._export_mesh = true; all_ok = _tree.build_complete_hierarchy(_options->_max_interface->GetRootNode(), &_options->_node_list.front(), _options->_node_list.size()); @@ -211,7 +213,7 @@ convert_char_chan(double start_frame, double end_frame, double frame_inc, // Set the frame rate before we start asking for anim tables to be // created. _tree._fps = output_frame_rate / frame_inc; - _tree.clear_egg(_egg_data, NULL, skeleton_node); + _tree.clear_egg(_egg_data, nullptr, skeleton_node); // Now we can get the animation data by walking through all of the frames, // one at a time, and getting the joint angles at each frame. @@ -241,7 +243,7 @@ convert_char_chan(double start_frame, double end_frame, double frame_inc, get_joint_transform(max_node, node_desc->_parent->get_max_node(), tgroup); } else { - get_joint_transform(max_node, NULL, tgroup); + get_joint_transform(max_node, nullptr, tgroup); } EggXfmSAnim *anim = _tree.get_egg_anim(node_desc); @@ -275,7 +277,7 @@ bool MaxToEggConverter:: convert_hierarchy(EggGroupNode *egg_root) { // int num_nodes = _tree.get_num_nodes(); - _tree.clear_egg(_egg_data, egg_root, NULL); + _tree.clear_egg(_egg_data, egg_root, nullptr); for (int i = 0; i < _tree.get_num_nodes(); i++) { if (!process_model_node(_tree.get_node(i))) { return false; @@ -316,7 +318,7 @@ process_model_node(MaxNodeDesc *node_desc) { } } else { if (state.obj) { - EggGroup *egg_group = NULL; + EggGroup *egg_group = nullptr; TriObject *myMaxTriObject; Mesh max_mesh; // Call the correct exporter based on what type of object this is. @@ -704,7 +706,7 @@ make_polyset(INode *max_node, Mesh *mesh, // standard material to the object for (int iChan=0; iChanref_vertex(vert, 1.0f); } } @@ -900,7 +902,7 @@ get_vertex_weights(INode *max_node, EggVertexPool *vpool) { MaxNodeDesc *joint_node_desc = _tree.find_joint(bone_node); if (joint_node_desc){ EggGroup *joint = _tree.get_egg_group(joint_node_desc); - if (joint != (EggGroup *)NULL) + if (joint != nullptr) joint->ref_vertex(vert, weight); } } @@ -936,7 +938,7 @@ get_vertex_weights(INode *max_node, EggVertexPool *vpool) { MaxNodeDesc *joint_node_desc = _tree.find_joint(bone_node); if (joint_node_desc){ EggGroup *joint = _tree.get_egg_group(joint_node_desc); - if (joint != (EggGroup *)NULL) { + if (joint != nullptr) { joint->ref_vertex(vert, weight); } } @@ -1272,7 +1274,7 @@ void MaxToEggConverter::add_map_channel(PandaMaterial &pandaMat, int chan) { * Generates an arbitrary unused texture name. */ std::string MaxToEggConverter::generate_tex_name() { - ostringstream name_strm; + std::ostringstream name_strm; name_strm << "Tex" << ++_cur_tref; return name_strm.str(); } @@ -1281,7 +1283,7 @@ std::string MaxToEggConverter::generate_tex_name() { * Returns the UV-name of the nth map-channel. */ std::string MaxToEggConverter::get_uv_name(int channel) { - ostringstream uvname; + std::ostringstream uvname; uvname << "m" << channel; return uvname.str(); } @@ -1322,7 +1324,7 @@ reparent_decals(EggGroupNode *egg_parent) { // First, walk through all children of this node, looking for the one // decal base, if any. - EggGroup *decal_base = (EggGroup *)NULL; + EggGroup *decal_base = nullptr; pvector decal_children; EggGroupNode::iterator ci; @@ -1331,7 +1333,7 @@ reparent_decals(EggGroupNode *egg_parent) { if (child->is_of_type(EggGroup::get_class_type())) { EggGroup *child_group = (EggGroup *) child; if (child_group->has_object_type("decalbase")) { - if (decal_base != (EggNode *)NULL) { + if (decal_base != nullptr) { // error okflag = false; } @@ -1345,7 +1347,7 @@ reparent_decals(EggGroupNode *egg_parent) { } } - if (decal_base == (EggGroup *)NULL) { + if (decal_base == nullptr) { if (!decal_children.empty()) { // warning } @@ -1388,7 +1390,7 @@ Modifier* MaxToEggConverter::FindSkinModifier (INode* node, const Class_ID &type { // Get object from node. Abort if no object. Object* pObj = node->GetObjectRef(); - if (!pObj) return NULL; + if (!pObj) return nullptr; // Is derived object ? while (pObj->SuperClassID() == GEN_DERIVOB_CLASS_ID) { @@ -1410,5 +1412,5 @@ Modifier* MaxToEggConverter::FindSkinModifier (INode* node, const Class_ID &type } // Not found. - return NULL; + return nullptr; } diff --git a/pandatool/src/maxegg/maxToEggConverter.h b/pandatool/src/maxegg/maxToEggConverter.h index 0225565843..86cb2303c1 100644 --- a/pandatool/src/maxegg/maxToEggConverter.h +++ b/pandatool/src/maxegg/maxToEggConverter.h @@ -56,7 +56,7 @@ class MaxToEggConverter { MaxEggOptions *_options; int _current_frame; PT(EggData) _egg_data; - string _program_name; + std::string _program_name; MaxNodeTree _tree; int _cur_tref; EggTextureCollection _textures; @@ -81,7 +81,7 @@ class MaxToEggConverter { void make_polyset(INode *max_node, Mesh *mesh, EggGroup *egg_group, - Shader *default_shader = NULL); + Shader *default_shader = nullptr); Point3 get_max_vertex_normal(Mesh *mesh, int faceNo, int vertNo); VertColor get_max_vertex_color(Mesh *mesh, int FaceNo, int VertexNo); diff --git a/pandatool/src/maxprogs/maxEggImport.cxx b/pandatool/src/maxprogs/maxEggImport.cxx index 8565a612b4..08a0184a8e 100644 --- a/pandatool/src/maxprogs/maxEggImport.cxx +++ b/pandatool/src/maxprogs/maxEggImport.cxx @@ -22,6 +22,9 @@ // Include this before everything #include "pandatoolbase.h" +using std::min; +using std::max; + // MAX includes #include "maxEggLoader.h" #include "Max.h" @@ -198,14 +201,14 @@ DoImport(const TCHAR *name, ImpInterface *ii, Interface *i, BOOL suppressPrompts bool ok = MaxLoadEggFile(name, _merge ? true:false, _importmodel ? true:false, _importanim ? true:false); #endif - string txt = log.str(); + std::string txt = log.str(); if (txt != "") { - MessageBoxA(NULL, txt.c_str(), "Panda3D Importer", MB_OK); + MessageBoxA(nullptr, txt.c_str(), "Panda3D Importer", MB_OK); } else if (!ok) { - MessageBoxA(NULL, "Import Failed, unknown reason\n", "Panda3D Importer", MB_OK); + MessageBoxA(nullptr, "Import Failed, unknown reason\n", "Panda3D Importer", MB_OK); } - Notify::ptr()->set_ostream_ptr(NULL, false); + Notify::ptr()->set_ostream_ptr(nullptr, false); return 1; } diff --git a/pandatool/src/maya/mayaApi.cxx b/pandatool/src/maya/mayaApi.cxx index 015ce7d4c6..b045f45f32 100644 --- a/pandatool/src/maya/mayaApi.cxx +++ b/pandatool/src/maya/mayaApi.cxx @@ -29,7 +29,9 @@ #include // for chdir() #endif -MayaApi *MayaApi::_global_api = (MayaApi *)NULL; +using std::string; + +MayaApi *MayaApi::_global_api = nullptr; // We need this bogus object just to force the application to link with // OpenMayaAnim.lib; otherwise, Maya will complain (when compiled on Windows) @@ -125,7 +127,7 @@ MayaApi:: // Maya code. MLibrary::cleanup(); } - _global_api = (MayaApi *)NULL; + _global_api = nullptr; } /** @@ -141,7 +143,7 @@ MayaApi:: */ PT(MayaApi) MayaApi:: open_api(string program_name, bool view_license, bool revertdir) { - if (_global_api == (MayaApi *)NULL) { + if (_global_api == nullptr) { // We need to create a new MayaApi object. if (program_name.empty()) { program_name = ExecutionEnvironment::get_binary_name(); @@ -255,7 +257,7 @@ read(const Filename &filename) { string dirname = _cwd.to_os_specific(); if (maya_cat.is_debug()) { - maya_cat.debug() << "cwd(read:before): " << dirname.c_str() << endl; + maya_cat.debug() << "cwd(read:before): " << dirname.c_str() << std::endl; } MFileIO::newFile(true); @@ -293,7 +295,7 @@ write(const Filename &filename) { string dirname = _cwd.to_os_specific(); if (maya_cat.is_debug()) { - maya_cat.debug() << "cwd(write:before): " << dirname.c_str() << endl; + maya_cat.debug() << "cwd(write:before): " << dirname.c_str() << std::endl; } const char *type = "mayaBinary"; diff --git a/pandatool/src/maya/mayaApi.h b/pandatool/src/maya/mayaApi.h index 590f7b4817..02cc421955 100644 --- a/pandatool/src/maya/mayaApi.h +++ b/pandatool/src/maya/mayaApi.h @@ -29,14 +29,14 @@ class Filename; */ class MayaApi : public ReferenceCount { protected: - MayaApi(const string &program_name, bool view_license = false, bool revertdir = true); + MayaApi(const std::string &program_name, bool view_license = false, bool revertdir = true); MayaApi(const MayaApi ©); void operator = (const MayaApi ©); public: ~MayaApi(); - static PT(MayaApi) open_api(string program_name = "", bool view_license = false, bool revertdir = true); + static PT(MayaApi) open_api(std::string program_name = "", bool view_license = false, bool revertdir = true); bool is_valid() const; bool read(const Filename &filename); diff --git a/pandatool/src/maya/mayaShader.cxx b/pandatool/src/maya/mayaShader.cxx index f012539b81..9be62a60d3 100644 --- a/pandatool/src/maya/mayaShader.cxx +++ b/pandatool/src/maya/mayaShader.cxx @@ -32,6 +32,9 @@ #include #include "post_maya_include.h" +using std::endl; +using std::string; + /** * Reads the Maya "shading engine" to determine the relevant shader * properties. @@ -92,7 +95,7 @@ MayaShader:: * */ void MayaShader:: -output(ostream &out) const { +output(std::ostream &out) const { out << "Shader " << get_name(); } @@ -100,7 +103,7 @@ output(ostream &out) const { * */ void MayaShader:: -write(ostream &out) const { +write(std::ostream &out) const { out << "Shader " << get_name() << "\n"; } @@ -113,7 +116,7 @@ get_color_def(size_t idx) const { if (_color.size() > 0) return _color[idx]; else - return (MayaShaderColorDef *)NULL; + return nullptr; } /** * Returns the overall color of the shader as a single-precision rgba value, diff --git a/pandatool/src/maya/mayaShader.h b/pandatool/src/maya/mayaShader.h index b998588122..41c9bdf77f 100644 --- a/pandatool/src/maya/mayaShader.h +++ b/pandatool/src/maya/mayaShader.h @@ -33,8 +33,8 @@ public: MayaShader(MObject engine, bool legacy_shader); ~MayaShader(); - void output(ostream &out) const; - void write(ostream &out) const; + void output(std::ostream &out) const; + void write(std::ostream &out) const; private: bool find_textures_modern(MObject shader); @@ -64,7 +64,7 @@ private: bool try_pair(MayaShaderColorDef *map1, MayaShaderColorDef *map2, bool perfect); - string get_file_prefix(const string &fn); + std::string get_file_prefix(const std::string &fn); bool _legacy_shader; public: // relevant only to legacy mode. MayaShaderColorList _color; @@ -73,7 +73,7 @@ public: // relevant only to legacy mode. MayaShaderColorDef *get_color_def(size_t idx=0) const; }; -INLINE ostream &operator << (ostream &out, const MayaShader &shader) { +INLINE std::ostream &operator << (std::ostream &out, const MayaShader &shader) { shader.output(out); return out; } diff --git a/pandatool/src/maya/mayaShaderColorDef.cxx b/pandatool/src/maya/mayaShaderColorDef.cxx index ede0bbf0d5..73d2978d7c 100644 --- a/pandatool/src/maya/mayaShaderColorDef.cxx +++ b/pandatool/src/maya/mayaShaderColorDef.cxx @@ -29,6 +29,9 @@ #include #include "post_maya_include.h" +using std::endl; +using std::string; + /** * */ @@ -63,7 +66,7 @@ MayaShaderColorDef() { _opposite = 0; - _color_object = (MObject *)NULL; + _color_object = nullptr; _has_texture = false; _has_flat_color = false; @@ -74,7 +77,7 @@ MayaShaderColorDef() { _interpolate = false; _uvset_name = "map1"; - _map_uvs = NULL; + _map_uvs = nullptr; } /** @@ -128,7 +131,7 @@ MayaShaderColorDef(MayaShaderColorDef ©) { */ MayaShaderColorDef:: ~MayaShaderColorDef() { - if (_color_object != (MObject *)NULL) { + if (_color_object != nullptr) { delete _color_object; } } @@ -169,7 +172,7 @@ has_projection() const { */ LTexCoordd MayaShaderColorDef:: project_uv(const LPoint3d &pos, const LPoint3d ¢roid) const { - nassertr(_map_uvs != NULL, LTexCoordd::zero()); + nassertr(_map_uvs != nullptr, LTexCoordd::zero()); return (this->*_map_uvs)(pos * _projection_matrix, centroid * _projection_matrix); } @@ -177,7 +180,7 @@ project_uv(const LPoint3d &pos, const LPoint3d ¢roid) const { * */ void MayaShaderColorDef:: -write(ostream &out) const { +write(std::ostream &out) const { if (_has_texture) { out << " texture filename is " << _texture_filename << "\n" << " texture name is " << _texture_name << "\n" @@ -205,7 +208,7 @@ write(ostream &out) const { */ bool MayaShaderColorDef:: reset_maya_texture(const Filename &texture) { - if (_color_object != (MObject *)NULL) { + if (_color_object != nullptr) { _has_texture = set_string_attribute(*_color_object, "fileTextureName", texture.to_os_generic()); _texture_filename = texture; @@ -686,7 +689,7 @@ set_projection_type(const string &type) { maya_cat.error() << "Don't know how to handle type " << type << " projections.\n"; _projection_type = PT_off; - _map_uvs = NULL; + _map_uvs = nullptr; } } diff --git a/pandatool/src/maya/mayaShaderColorDef.h b/pandatool/src/maya/mayaShaderColorDef.h index 522146fc53..ca2d532f13 100644 --- a/pandatool/src/maya/mayaShaderColorDef.h +++ b/pandatool/src/maya/mayaShaderColorDef.h @@ -26,7 +26,7 @@ class MPlug; class MayaShader; class MayaShaderColorDef; typedef pvector MayaShaderColorList; -typedef pmap MayaFileToUVSetMap; +typedef pmap MayaFileToUVSetMap; /** * This defines the various attributes that Maya may associate with the @@ -39,14 +39,14 @@ public: MayaShaderColorDef (MayaShaderColorDef&); ~MayaShaderColorDef(); - string strip_prefix(string full_name); + std::string strip_prefix(std::string full_name); LMatrix3d compute_texture_matrix() const; bool has_projection() const; LTexCoordd project_uv(const LPoint3d &pos, const LPoint3d &ref_point) const; bool reset_maya_texture(const Filename &texture); - void write(ostream &out) const; + void write(std::ostream &out) const; enum BlendType { BT_unspecified, @@ -85,7 +85,7 @@ public: double _v_angle; Filename _texture_filename; - string _texture_name; + std::string _texture_name; LColor _color_gain; LVector2 _coverage; @@ -103,19 +103,19 @@ public: bool _is_alpha; - string _uvset_name; + std::string _uvset_name; MayaShaderColorDef *_opposite; - string get_panda_uvset_name(); + std::string get_panda_uvset_name(); private: MObject *_color_object; private: - static void find_textures_modern(const string &shadername, MayaShaderColorList &list, MPlug inplug, bool is_alpha); + static void find_textures_modern(const std::string &shadername, MayaShaderColorList &list, MPlug inplug, bool is_alpha); void find_textures_legacy(MayaShader *shader, MObject color, bool trans=false); - void set_projection_type(const string &type); + void set_projection_type(const std::string &type); LPoint2d map_planar(const LPoint3d &pos, const LPoint3d ¢roid) const; LPoint2d map_spherical(const LPoint3d &pos, const LPoint3d ¢roid) const; diff --git a/pandatool/src/maya/mayaShaders.cxx b/pandatool/src/maya/mayaShaders.cxx index a100ad8a4e..dca3712366 100644 --- a/pandatool/src/maya/mayaShaders.cxx +++ b/pandatool/src/maya/mayaShaders.cxx @@ -27,6 +27,8 @@ #include #include "post_maya_include.h" +using std::string; + /** * */ @@ -55,7 +57,7 @@ find_shader_for_node(MObject node, bool legacy_shader) { // The node is not renderable. What are you thinking? maya_cat.error() << node_fn.name().asChar() << " : not a renderable object.\n"; - return (MayaShader *)NULL; + return nullptr; } // instObjGroups is a multi attribute, whatever that means. For now, we'll @@ -69,7 +71,7 @@ find_shader_for_node(MObject node, bool legacy_shader) { // No shading group defined for this object. maya_cat.error() << node_fn.name().asChar() << " : no shading group defined.\n"; - return (MayaShader *)NULL; + return nullptr; } // Now we have a number of ShadingEngines defined, one for each of these @@ -87,7 +89,7 @@ find_shader_for_node(MObject node, bool legacy_shader) { // Well, we didn't find a ShadingEngine after all. Huh. maya_cat.debug() << node_fn.name().asChar() << " : no shading engine found.\n"; - return (MayaShader *)NULL; + return nullptr; } /** @@ -175,7 +177,7 @@ get_num_shaders() const { */ MayaShader *MayaShaders:: get_shader(int n) const { - nassertr(n >= 0 && n < (int)_shaders_in_order.size(), NULL); + nassertr(n >= 0 && n < (int)_shaders_in_order.size(), nullptr); return _shaders_in_order[n]; } diff --git a/pandatool/src/maya/mayaShaders.h b/pandatool/src/maya/mayaShaders.h index 7c92ae4416..f1c107a755 100644 --- a/pandatool/src/maya/mayaShaders.h +++ b/pandatool/src/maya/mayaShaders.h @@ -37,13 +37,13 @@ public: MayaShader *get_shader(int n) const; MayaFileToUVSetMap _file_to_uvset; - pvector _uvset_names; + pvector _uvset_names; void clear(); void bind_uvsets(MObject mesh); - string find_uv_link(const string &match); + std::string find_uv_link(const std::string &match); private: - typedef pmap Shaders; + typedef pmap Shaders; Shaders _shaders; typedef pvector ShadersInOrder; ShadersInOrder _shaders_in_order; diff --git a/pandatool/src/maya/maya_funcs.I b/pandatool/src/maya/maya_funcs.I index 422b525751..1a56126c44 100644 --- a/pandatool/src/maya/maya_funcs.I +++ b/pandatool/src/maya/maya_funcs.I @@ -14,13 +14,13 @@ /** * */ -INLINE ostream &operator << (ostream &out, const MString &str) { +INLINE std::ostream &operator << (std::ostream &out, const MString &str) { return out << str.asChar(); } /** * */ -INLINE ostream &operator << (ostream &out, const MVector &vec) { +INLINE std::ostream &operator << (std::ostream &out, const MVector &vec) { return out << vec.x << " " << vec.y << " " << vec.z; } diff --git a/pandatool/src/maya/maya_funcs.T b/pandatool/src/maya/maya_funcs.T index 04ecfab83f..3418ce3647 100644 --- a/pandatool/src/maya/maya_funcs.T +++ b/pandatool/src/maya/maya_funcs.T @@ -1,27 +1,23 @@ -// Filename: maya_funcs.I -// Created by: drose (16Feb00) -// -//////////////////////////////////////////////////////////////////// -// -// PANDA 3D SOFTWARE -// Copyright (c) Carnegie Mellon University. All rights reserved. -// -// All use of this software is subject to the terms of the revised BSD -// license. You should have received a copy of this license along -// with this source code in a file named "LICENSE." -// -//////////////////////////////////////////////////////////////////// +/** + * PANDA 3D SOFTWARE + * Copyright (c) Carnegie Mellon University. All rights reserved. + * + * All use of this software is subject to the terms of the revised BSD + * license. You should have received a copy of this license along + * with this source code in a file named "LICENSE." + * + * @file maya_funcs.T + * @author drose + * @date 2000-02-16 + */ - -//////////////////////////////////////////////////////////////////// -// Function: get_maya_attribute -// Description: A generic function to extract an attribute of some -// type from an MObject. This is used to implement -// get_bool_attribute(), etc. -//////////////////////////////////////////////////////////////////// +/** + * A generic function to extract an attribute of some type from an MObject. + * This is used to implement get_bool_attribute(), etc. + */ template bool -get_maya_attribute(MObject &node, const string &attribute_name, +get_maya_attribute(MObject &node, const std::string &attribute_name, ValueType &value) { bool status = false; @@ -33,15 +29,13 @@ get_maya_attribute(MObject &node, const string &attribute_name, return status; } -//////////////////////////////////////////////////////////////////// -// Function: set_maya_attribute -// Description: A generic function to set an attribute of some -// type on an MObject. This is used to implement -// set_bool_attribute(), etc. -//////////////////////////////////////////////////////////////////// +/** + * A generic function to set an attribute of some type on an MObject. This is + * used to implement set_bool_attribute(), etc. + */ template bool -set_maya_attribute(MObject &node, const string &attribute_name, +set_maya_attribute(MObject &node, const std::string &attribute_name, ValueType &value) { bool status = false; diff --git a/pandatool/src/maya/maya_funcs.cxx b/pandatool/src/maya/maya_funcs.cxx index 184a903f66..2f21adefb3 100644 --- a/pandatool/src/maya/maya_funcs.cxx +++ b/pandatool/src/maya/maya_funcs.cxx @@ -31,6 +31,9 @@ #include #include "post_maya_include.h" +using std::endl; +using std::string; + /** * Gets the named MPlug associated, if any. */ diff --git a/pandatool/src/maya/maya_funcs.h b/pandatool/src/maya/maya_funcs.h index 7b2ef5df13..2966fef9e3 100644 --- a/pandatool/src/maya/maya_funcs.h +++ b/pandatool/src/maya/maya_funcs.h @@ -31,77 +31,77 @@ class MObject; bool -get_maya_plug(MObject &node, const string &attribute_name, MPlug &plug); +get_maya_plug(MObject &node, const std::string &attribute_name, MPlug &plug); bool -is_connected(MObject &node, const string &attribute_name); +is_connected(MObject &node, const std::string &attribute_name); template bool -get_maya_attribute(MObject &node, const string &attribute_name, +get_maya_attribute(MObject &node, const std::string &attribute_name, ValueType &value); template bool -set_maya_attribute(MObject &node, const string &attribute_name, +set_maya_attribute(MObject &node, const std::string &attribute_name, ValueType &value); bool -has_attribute(MObject &node, const string &attribute_name); +has_attribute(MObject &node, const std::string &attribute_name); bool -remove_attribute(MObject &node, const string &attribute_name); +remove_attribute(MObject &node, const std::string &attribute_name); bool -get_bool_attribute(MObject &node, const string &attribute_name, +get_bool_attribute(MObject &node, const std::string &attribute_name, bool &value); bool -get_angle_attribute(MObject &node, const string &attribute_name, +get_angle_attribute(MObject &node, const std::string &attribute_name, double &value); bool -get_vec2_attribute(MObject &node, const string &attribute_name, +get_vec2_attribute(MObject &node, const std::string &attribute_name, LVecBase2 &value); bool -get_vec3_attribute(MObject &node, const string &attribute_name, +get_vec3_attribute(MObject &node, const std::string &attribute_name, LVecBase3 &value); bool -get_vec2d_attribute(MObject &node, const string &attribute_name, +get_vec2d_attribute(MObject &node, const std::string &attribute_name, LVecBase2d &value); bool -get_vec3d_attribute(MObject &node, const string &attribute_name, +get_vec3d_attribute(MObject &node, const std::string &attribute_name, LVecBase3d &value); bool -get_mat4d_attribute(MObject &node, const string &attribute_name, +get_mat4d_attribute(MObject &node, const std::string &attribute_name, LMatrix4d &value); void -get_tag_attribute_names(MObject &node, pvector &tag_names); +get_tag_attribute_names(MObject &node, pvector &tag_names); bool -get_enum_attribute(MObject &node, const string &attribute_name, - string &value); +get_enum_attribute(MObject &node, const std::string &attribute_name, + std::string &value); bool -get_string_attribute(MObject &node, const string &attribute_name, - string &value); +get_string_attribute(MObject &node, const std::string &attribute_name, + std::string &value); bool -set_string_attribute(MObject &node, const string &attribute_name, - const string &value); +set_string_attribute(MObject &node, const std::string &attribute_name, + const std::string &value); void -describe_maya_attribute(MObject &node, const string &attribute_name); +describe_maya_attribute(MObject &node, const std::string &attribute_name); bool describe_compound_attribute(MObject &node); -string +std::string string_mfndata_type(MFnData::Type type); void @@ -110,8 +110,8 @@ list_maya_attributes(MObject &node); // Also, we must define some output functions for Maya objects, since we can't // use those built into Maya (which forward-defines the ostream type // incorrectly). -INLINE ostream &operator << (ostream &out, const MString &str); -INLINE ostream &operator << (ostream &out, const MVector &vec); +INLINE std::ostream &operator << (std::ostream &out, const MString &str); +INLINE std::ostream &operator << (std::ostream &out, const MVector &vec); #include "maya_funcs.I" #include "maya_funcs.T" diff --git a/pandatool/src/mayaegg/mayaBlendDesc.cxx b/pandatool/src/mayaegg/mayaBlendDesc.cxx index c0977dcb3a..b396ed86b6 100644 --- a/pandatool/src/mayaegg/mayaBlendDesc.cxx +++ b/pandatool/src/mayaegg/mayaBlendDesc.cxx @@ -24,11 +24,11 @@ MayaBlendDesc(MFnBlendShapeDeformer &deformer, int weight_index) : _deformer(deformer.object()), _weight_index(weight_index) { - ostringstream strm; + std::ostringstream strm; strm << _deformer.name().asChar() << "." << _weight_index; set_name(strm.str()); - _anim = (EggSAnimData *)NULL; + _anim = nullptr; } /** @@ -65,5 +65,5 @@ get_slider() const { */ void MayaBlendDesc:: clear_egg() { - _anim = (EggSAnimData *)NULL; + _anim = nullptr; } diff --git a/pandatool/src/mayaegg/mayaEggLoader.cxx b/pandatool/src/mayaegg/mayaEggLoader.cxx index 82523d122f..4baf1dff86 100644 --- a/pandatool/src/mayaegg/mayaEggLoader.cxx +++ b/pandatool/src/mayaegg/mayaEggLoader.cxx @@ -71,6 +71,12 @@ #include "mayaEggLoader.h" +using std::cerr; +using std::endl; +using std::ostringstream; +using std::string; +using std::vector; + class MayaEggGroup; class MayaEggGeom; class MayaEggMesh; @@ -235,7 +241,7 @@ MayaEggTex *MayaEggLoader::GetTex(EggTexture* etex) { string name = ""; string fn = ""; - if (etex != NULL) { + if (etex != nullptr) { name = etex->get_name(); fn = etex->get_fullpath().to_os_specific(); } @@ -293,7 +299,7 @@ MayaEggTex *MayaEggLoader::GetTex(EggTexture* etex) // [gjeon] to create alpha channel connection LoaderOptions options; PT(Texture) tex = TexturePool::load_texture(etex->get_fullpath(), 0, false, options); - if (((tex != NULL) && (tex->get_num_components() == 4)) + if (((tex != nullptr) && (tex->get_num_components() == 4)) || (etex->get_format() == EggTexture::F_alpha) || (etex->get_format() == EggTexture::F_luminance_alpha)) dgmod.connect(filetex.findPlug("outTransparency"),shader.findPlug("transparency")); @@ -452,7 +458,7 @@ void MayaEggJoint::AssignNames(void) MayaEggJoint *MayaEggLoader::FindJoint(EggGroup *joint) { - if (joint==(EggGroup *)NULL) { + if (joint==nullptr) { if (mayaloader_cat.is_spam()) { mayaloader_cat.spam() << "joint:" << joint->get_name() << " is null: " << endl; } @@ -617,7 +623,7 @@ void MayaEggJoint::CreateMayaBone(MayaEggGroup *eggParent) // MayaEggGeom : base abstract class of MayaEggMesh and MayaEggNurbsSurface -typedef pair MayaEggWeight; +typedef std::pair MayaEggWeight; struct MayaEggVertex { @@ -1286,7 +1292,7 @@ void MayaEggLoader::CreateSkinCluster(MayaEggGeom *M) perror("skinCluster index"); return; } - skinCluster.setWeights(M->_shape_dag_path, component.object(), index, 0.0, false, NULL); + skinCluster.setWeights(M->_shape_dag_path, component.object(), index, 0.0, false, nullptr); } MFloatArray values; @@ -1302,7 +1308,7 @@ void MayaEggLoader::CreateSkinCluster(MayaEggGeom *M) values[vert->_index * joints.size() + joint->_index] = (PN_stdfloat)strength; } } - skinCluster.setWeights(M->_shape_dag_path, component.object(), influenceIndices, values, false, NULL); + skinCluster.setWeights(M->_shape_dag_path, component.object(), influenceIndices, values, false, nullptr); for (unsigned int i=0; ihas_transform()) uvtrans = etex->get_transform2d(); } else { - tex = GetTex(NULL); + tex = GetTex(nullptr); } EggPolygon::const_iterator ci; @@ -1364,7 +1370,6 @@ void MayaEggLoader::TraverseEggNode(EggNode *node, EggGroup *context, string del int numVertices = 0; for (ci = poly->begin(); ci != poly->end(); ++ci) { EggVertex *vtx = (*ci); - EggVertexPool *pool = poly->get_pool(); LTexCoordd uv(0,0); if (vtx->has_uv()) { uv = vtx->get_uv(); @@ -1451,7 +1456,7 @@ void MayaEggLoader::TraverseEggNode(EggNode *node, EggGroup *context, string del uvtrans = etex->get_transform2d(); } } else { - tex = GetTex(NULL); + tex = GetTex(nullptr); } surface->_tex = tex; @@ -1565,8 +1570,8 @@ void MayaEggLoader::TraverseEggNode(EggNode *node, EggGroup *context, string del mayaloader_cat.debug() << delim+delstring << "found an EggTable: " << node->get_name() << endl; } } else if (node->is_of_type(EggXfmSAnim::get_class_type())) { - MayaAnim *anim = GetAnim(DCAST(EggXfmSAnim, node)); - // anim->PrintData(); + //MayaAnim *anim = GetAnim(DCAST(EggXfmSAnim, node)); + //anim->PrintData(); if (mayaloader_cat.is_debug()) { mayaloader_cat.debug() << delim+delstring << "found an EggXfmSAnim: " << node->get_name() << endl; } @@ -1614,7 +1619,7 @@ bool MayaEggLoader::ConvertEggData(EggData *data, bool merge, bool model, bool a if (mayaloader_cat.is_debug()) { mayaloader_cat.debug() << "root node: " << data->get_type() << endl; } - TraverseEggNode(data, NULL, ""); + TraverseEggNode(data, nullptr, ""); MStatus status; @@ -1791,7 +1796,7 @@ bool MayaEggLoader::ConvertEggData(EggData *data, bool merge, bool model, bool a double thickness = 0.0; for (ji = _joint_tab.begin(); ji != _joint_tab.end(); ++ji) { MayaEggJoint *joint = (*ji).second; - double dfo = ((*ji).second->GetPos()).length(); + double dfo = (joint->GetPos()).length(); if (dfo > thickness) { thickness = dfo; } @@ -1886,15 +1891,15 @@ bool MayaEggLoader::ConvertEggData(EggData *data, bool merge, bool model, bool a MFnAnimCurve mfnAnimCurveSY; MFnAnimCurve mfnAnimCurveSZ; - mfnAnimCurveTX.create(node, attrTX, MFnAnimCurve::kAnimCurveTL, NULL, &status); - mfnAnimCurveTY.create(node, attrTY, MFnAnimCurve::kAnimCurveTL, NULL, &status); - mfnAnimCurveTZ.create(node, attrTZ, MFnAnimCurve::kAnimCurveTL, NULL, &status); - mfnAnimCurveRX.create(node, attrRX, MFnAnimCurve::kAnimCurveTA, NULL, &status); - mfnAnimCurveRY.create(node, attrRY, MFnAnimCurve::kAnimCurveTA, NULL, &status); - mfnAnimCurveRZ.create(node, attrRZ, MFnAnimCurve::kAnimCurveTA, NULL, &status); - mfnAnimCurveSX.create(node, attrSX, MFnAnimCurve::kAnimCurveTU, NULL, &status); - mfnAnimCurveSY.create(node, attrSY, MFnAnimCurve::kAnimCurveTU, NULL, &status); - mfnAnimCurveSZ.create(node, attrSZ, MFnAnimCurve::kAnimCurveTU, NULL, &status); + mfnAnimCurveTX.create(node, attrTX, MFnAnimCurve::kAnimCurveTL, nullptr, &status); + mfnAnimCurveTY.create(node, attrTY, MFnAnimCurve::kAnimCurveTL, nullptr, &status); + mfnAnimCurveTZ.create(node, attrTZ, MFnAnimCurve::kAnimCurveTL, nullptr, &status); + mfnAnimCurveRX.create(node, attrRX, MFnAnimCurve::kAnimCurveTA, nullptr, &status); + mfnAnimCurveRY.create(node, attrRY, MFnAnimCurve::kAnimCurveTA, nullptr, &status); + mfnAnimCurveRZ.create(node, attrRZ, MFnAnimCurve::kAnimCurveTA, nullptr, &status); + mfnAnimCurveSX.create(node, attrSX, MFnAnimCurve::kAnimCurveTU, nullptr, &status); + mfnAnimCurveSY.create(node, attrSY, MFnAnimCurve::kAnimCurveTU, nullptr, &status); + mfnAnimCurveSZ.create(node, attrSZ, MFnAnimCurve::kAnimCurveTU, nullptr, &status); MTransformationMatrix matrix( mMat ); MVector trans = matrix.translation(MSpace::kTransform, &status); @@ -1908,15 +1913,15 @@ bool MayaEggLoader::ConvertEggData(EggData *data, bool merge, bool model, bool a MFnAnimCurve::TangentType tangent = MFnAnimCurve::kTangentClamped; MTime time(_start_frame - 1, _timeUnit); - mfnAnimCurveTX.addKey(time, trans.x, tangent, tangent, NULL, &status); - mfnAnimCurveTY.addKey(time, trans.y, tangent, tangent, NULL, &status); - mfnAnimCurveTZ.addKey(time, trans.z, tangent, tangent, NULL, &status); - mfnAnimCurveRX.addKey(time, rot[0], tangent, tangent, NULL, &status); - mfnAnimCurveRY.addKey(time, rot[1], tangent, tangent, NULL, &status); - mfnAnimCurveRZ.addKey(time, rot[2], tangent, tangent, NULL, &status); - mfnAnimCurveSX.addKey(time, scale[0], tangent, tangent, NULL, &status); - mfnAnimCurveSY.addKey(time, scale[1], tangent, tangent, NULL, &status); - mfnAnimCurveSZ.addKey(time, scale[2], tangent, tangent, NULL, &status); + mfnAnimCurveTX.addKey(time, trans.x, tangent, tangent, nullptr, &status); + mfnAnimCurveTY.addKey(time, trans.y, tangent, tangent, nullptr, &status); + mfnAnimCurveTZ.addKey(time, trans.z, tangent, tangent, nullptr, &status); + mfnAnimCurveRX.addKey(time, rot[0], tangent, tangent, nullptr, &status); + mfnAnimCurveRY.addKey(time, rot[1], tangent, tangent, nullptr, &status); + mfnAnimCurveRZ.addKey(time, rot[2], tangent, tangent, nullptr, &status); + mfnAnimCurveSX.addKey(time, scale[0], tangent, tangent, nullptr, &status); + mfnAnimCurveSY.addKey(time, scale[1], tangent, tangent, nullptr, &status); + mfnAnimCurveSZ.addKey(time, scale[2], tangent, tangent, nullptr, &status); for (int frame = 0; frame < anim->_pool->get_num_rows(); frame++) { @@ -1935,15 +1940,15 @@ bool MayaEggLoader::ConvertEggData(EggData *data, bool merge, bool model, bool a status = matrix.getScale(scale, MSpace::kTransform); time = MTime(frame + _start_frame, _timeUnit); - mfnAnimCurveTX.addKey(time, trans.x, tangent, tangent, NULL, &status); - mfnAnimCurveTY.addKey(time, trans.y, tangent, tangent, NULL, &status); - mfnAnimCurveTZ.addKey(time, trans.z, tangent, tangent, NULL, &status); - mfnAnimCurveRX.addKey(time, rot[0], tangent, tangent, NULL, &status); - mfnAnimCurveRY.addKey(time, rot[1], tangent, tangent, NULL, &status); - mfnAnimCurveRZ.addKey(time, rot[2], tangent, tangent, NULL, &status); - mfnAnimCurveSX.addKey(time, scale[0], tangent, tangent, NULL, &status); - mfnAnimCurveSY.addKey(time, scale[1], tangent, tangent, NULL, &status); - mfnAnimCurveSZ.addKey(time, scale[2], tangent, tangent, NULL, &status); + mfnAnimCurveTX.addKey(time, trans.x, tangent, tangent, nullptr, &status); + mfnAnimCurveTY.addKey(time, trans.y, tangent, tangent, nullptr, &status); + mfnAnimCurveTZ.addKey(time, trans.z, tangent, tangent, nullptr, &status); + mfnAnimCurveRX.addKey(time, rot[0], tangent, tangent, nullptr, &status); + mfnAnimCurveRY.addKey(time, rot[1], tangent, tangent, nullptr, &status); + mfnAnimCurveRZ.addKey(time, rot[2], tangent, tangent, nullptr, &status); + mfnAnimCurveSX.addKey(time, scale[0], tangent, tangent, nullptr, &status); + mfnAnimCurveSY.addKey(time, scale[1], tangent, tangent, nullptr, &status); + mfnAnimCurveSZ.addKey(time, scale[2], tangent, tangent, nullptr, &status); } if (maxFrame < time) { maxFrame = time; @@ -2007,7 +2012,6 @@ void MayaEggLoader::PrintData(MayaEggMesh *mesh) void MayaEggLoader::ParseFrameInfo(string comment) { - int length = 0; int pos, ls, le; pos = comment.find("-fri"); diff --git a/pandatool/src/mayaegg/mayaNodeDesc.cxx b/pandatool/src/mayaegg/mayaNodeDesc.cxx index efef4879a8..8a86f1cb96 100644 --- a/pandatool/src/mayaegg/mayaNodeDesc.cxx +++ b/pandatool/src/mayaegg/mayaNodeDesc.cxx @@ -26,6 +26,8 @@ #include #include "post_maya_include.h" +using std::string; + TypeHandle MayaNodeDesc::_type_handle; // This is a list of the names of Maya connections that count as a transform. @@ -50,17 +52,17 @@ MayaNodeDesc(MayaNodeTree *tree, MayaNodeDesc *parent, const string &name) : _tree(tree), _parent(parent) { - _dag_path = (MDagPath *)NULL; - _egg_group = (EggGroup *)NULL; - _egg_table = (EggTable *)NULL; - _anim = (EggXfmSAnim *)NULL; + _dag_path = nullptr; + _egg_group = nullptr; + _egg_table = nullptr; + _anim = nullptr; _joint_type = JT_none; _is_lod = false; _tagged = false; _joint_tagged = false; // Add ourselves to our parent. - if (_parent != (MayaNodeDesc *)NULL) { + if (_parent != nullptr) { _parent->_children.push_back(this); } } @@ -70,7 +72,7 @@ MayaNodeDesc(MayaNodeTree *tree, MayaNodeDesc *parent, const string &name) : */ MayaNodeDesc:: ~MayaNodeDesc() { - if (_dag_path != (MDagPath *)NULL) { + if (_dag_path != nullptr) { delete _dag_path; } } @@ -82,7 +84,7 @@ void MayaNodeDesc:: from_dag_path(const MDagPath &dag_path, MayaToEggConverter *converter) { MStatus status; - if (_dag_path == (MDagPath *)NULL) { + if (_dag_path == nullptr) { _dag_path = new MDagPath(dag_path); string name; @@ -97,7 +99,7 @@ from_dag_path(const MDagPath &dag_path, MayaToEggConverter *converter) { // This node is a joint, or the user specifically asked to treat it like // a joint. _joint_type = JT_joint; - if (_parent != (MayaNodeDesc *)NULL) { + if (_parent != nullptr) { _parent->mark_joint_parent(); } @@ -120,7 +122,7 @@ from_dag_path(const MDagPath &dag_path, MayaToEggConverter *converter) { if (transform_connected) { _joint_type = JT_joint; - if (_parent != (MayaNodeDesc *)NULL) { + if (_parent != nullptr) { _parent->mark_joint_parent(); } } @@ -146,7 +148,7 @@ from_dag_path(const MDagPath &dag_path, MayaToEggConverter *converter) { */ bool MayaNodeDesc:: has_dag_path() const { - return (_dag_path != (MDagPath *)NULL); + return (_dag_path != nullptr); } /** @@ -155,7 +157,7 @@ has_dag_path() const { */ const MDagPath &MayaNodeDesc:: get_dag_path() const { - nassertr(_dag_path != (MDagPath *)NULL, *_dag_path); + nassertr(_dag_path != nullptr, *_dag_path); return *_dag_path; } @@ -174,7 +176,7 @@ get_num_blend_descs() const { */ MayaBlendDesc *MayaNodeDesc:: get_blend_desc(int n) const { - nassertr(n >= 0 && n < (int)_blend_descs.size(), NULL); + nassertr(n >= 0 && n < (int)_blend_descs.size(), nullptr); return _blend_descs[n]; } @@ -286,11 +288,11 @@ untag_recursively() { bool MayaNodeDesc:: has_object_type(string object_type) const { bool ret = false; - if ((_egg_group != (EggGroup*) NULL) + if ((_egg_group != nullptr) && _egg_group->has_object_type(object_type)) { return true; } - if (_parent != (MayaNodeDesc *)NULL) { + if (_parent != nullptr) { ret |= _parent->has_object_type(object_type); } return ret; @@ -301,9 +303,9 @@ has_object_type(string object_type) const { */ void MayaNodeDesc:: clear_egg() { - _egg_group = (EggGroup *)NULL; - _egg_table = (EggTable *)NULL; - _anim = (EggXfmSAnim *)NULL; + _egg_group = nullptr; + _egg_table = nullptr; + _anim = nullptr; Children::const_iterator ci; for (ci = _children.begin(); ci != _children.end(); ++ci) { @@ -320,7 +322,7 @@ void MayaNodeDesc:: mark_joint_parent() { if (_joint_type == JT_none) { _joint_type = JT_joint_parent; - if (_parent != (MayaNodeDesc *)NULL) { + if (_parent != nullptr) { _parent->mark_joint_parent(); } } @@ -339,7 +341,7 @@ check_pseudo_joints(bool joint_above) { space.append(" "); } if (mayaegg_cat.is_spam()) { - mayaegg_cat.spam() << "cpj:" << space << get_name() << " joint_type: " << _joint_type << endl; + mayaegg_cat.spam() << "cpj:" << space << get_name() << " joint_type: " << _joint_type << std::endl; } if (_joint_type == JT_joint_parent && joint_above) { // This is one such node: it is the parent of a joint (JT_joint_parent is @@ -387,11 +389,11 @@ check_pseudo_joints(bool joint_above) { child->_joint_type = JT_pseudo_joint; } else if (child->_joint_type == JT_none) { if (mayaegg_cat.is_spam()) { - mayaegg_cat.spam() << "cpj: " << space << "jt_none for " << child->get_name() << endl; + mayaegg_cat.spam() << "cpj: " << space << "jt_none for " << child->get_name() << std::endl; } if (type_name.find("transform") == string::npos) { if (mayaegg_cat.is_spam()) { - mayaegg_cat.spam() << "cpj: " << space << "all_joints false for " << get_name() << endl; + mayaegg_cat.spam() << "cpj: " << space << "all_joints false for " << get_name() << std::endl; } all_joints = false; } @@ -506,7 +508,7 @@ check_lods() { } // Now consider whether this node is an lodGroup. - if (_dag_path != (MDagPath *)NULL && + if (_dag_path != nullptr && _dag_path->hasFn(MFn::kLodGroup)) { // This node is a parent lodGroup; its children, therefore, are LOD's. MStatus status; diff --git a/pandatool/src/mayaegg/mayaNodeDesc.h b/pandatool/src/mayaegg/mayaNodeDesc.h index 1c28cb1698..f4123ee9a2 100644 --- a/pandatool/src/mayaegg/mayaNodeDesc.h +++ b/pandatool/src/mayaegg/mayaNodeDesc.h @@ -40,7 +40,7 @@ class EggXfmSAnim; class MayaNodeDesc : public ReferenceCount, public Namable { public: MayaNodeDesc(MayaNodeTree *tree, - MayaNodeDesc *parent = NULL, const string &name = string()); + MayaNodeDesc *parent = nullptr, const std::string &name = std::string()); ~MayaNodeDesc(); void from_dag_path(const MDagPath &dag_path, MayaToEggConverter *converter); @@ -55,7 +55,7 @@ public: bool is_tagged() const; bool is_joint_tagged() const; - bool has_object_type(string object_type) const; + bool has_object_type(std::string object_type) const; MayaNodeTree *_tree; MayaNodeDesc *_parent; @@ -74,7 +74,7 @@ private: void mark_joint_parent(); void check_pseudo_joints(bool joint_above); void check_blend_shapes(const MFnDagNode &node, - const string &attrib_name); + const std::string &attrib_name); void check_lods(); MDagPath *_dag_path; diff --git a/pandatool/src/mayaegg/mayaNodeTree.cxx b/pandatool/src/mayaegg/mayaNodeTree.cxx index def22d13b2..f80a3c95c1 100644 --- a/pandatool/src/mayaegg/mayaNodeTree.cxx +++ b/pandatool/src/mayaegg/mayaNodeTree.cxx @@ -32,6 +32,8 @@ #include #include "post_maya_include.h" +using std::string; + /** * */ @@ -41,10 +43,10 @@ MayaNodeTree(MayaToEggConverter *converter) : { _root = new MayaNodeDesc(this); _fps = 0.0; - _egg_data = (EggData *)NULL; - _egg_root = (EggGroupNode *)NULL; - _skeleton_node = (EggGroupNode *)NULL; - _morph_node = (EggGroupNode *)NULL; + _egg_data = nullptr; + _egg_root = nullptr; + _skeleton_node = nullptr; + _morph_node = nullptr; } /** @@ -259,7 +261,7 @@ get_num_nodes() const { */ MayaNodeDesc *MayaNodeTree:: get_node(int n) const { - nassertr(n >= 0 && n < (int)_nodes.size(), NULL); + nassertr(n >= 0 && n < (int)_nodes.size(), nullptr); return _nodes[n]; } @@ -270,10 +272,10 @@ void MayaNodeTree:: clear() { _root = new MayaNodeDesc(this); _fps = 0.0; - _egg_data = (EggData *)NULL; - _egg_root = (EggGroupNode *)NULL; - _skeleton_node = (EggGroupNode *)NULL; - _morph_node = (EggGroupNode *)NULL; + _egg_data = nullptr; + _egg_root = nullptr; + _skeleton_node = nullptr; + _morph_node = nullptr; _nodes_by_path.clear(); _nodes.clear(); } @@ -303,13 +305,13 @@ clear_egg(EggData *egg_data, EggGroupNode *egg_root, */ EggGroup *MayaNodeTree:: get_egg_group(MayaNodeDesc *node_desc) { - nassertr(_egg_root != (EggGroupNode *)NULL, NULL); + nassertr(_egg_root != nullptr, nullptr); - if (node_desc->_egg_group == (EggGroup *)NULL) { + if (node_desc->_egg_group == nullptr) { // We need to make a new group node. EggGroup *egg_group; - nassertr(node_desc->_parent != (MayaNodeDesc *)NULL, NULL); + nassertr(node_desc->_parent != nullptr, nullptr); egg_group = new EggGroup(node_desc->get_name()); if (node_desc->is_joint()) { if (_converter->get_animation_convert() == AC_model || @@ -318,7 +320,7 @@ get_egg_group(MayaNodeDesc *node_desc) { } } - MayaEggGroupUserData *parent_user_data = NULL; + MayaEggGroupUserData *parent_user_data = nullptr; if (node_desc->_parent == _root) { // The parent is the root. @@ -330,7 +332,7 @@ get_egg_group(MayaNodeDesc *node_desc) { parent_egg_group->add_child(egg_group); if (parent_egg_group->has_user_data()) { - DCAST_INTO_R(parent_user_data, parent_egg_group->get_user_data(), NULL); + DCAST_INTO_R(parent_user_data, parent_egg_group->get_user_data(), nullptr); } } @@ -406,7 +408,7 @@ get_egg_group(MayaNodeDesc *node_desc) { // And "vertex-color" and "double-sided" have meaning only to this // converter. MayaEggGroupUserData *user_data; - if (parent_user_data == (MayaEggGroupUserData *)NULL) { + if (parent_user_data == nullptr) { user_data = new MayaEggGroupUserData; } else { // Inherit the flags from above. @@ -443,12 +445,12 @@ get_egg_group(MayaNodeDesc *node_desc) { */ EggTable *MayaNodeTree:: get_egg_table(MayaNodeDesc *node_desc) { - nassertr(_skeleton_node != (EggGroupNode *)NULL, NULL); - nassertr(node_desc->is_joint(), NULL); + nassertr(_skeleton_node != nullptr, nullptr); + nassertr(node_desc->is_joint(), nullptr); - if (node_desc->_egg_table == (EggTable *)NULL) { + if (node_desc->_egg_table == nullptr) { // We need to make a new table node. - nassertr(node_desc->_parent != (MayaNodeDesc *)NULL, NULL); + nassertr(node_desc->_parent != nullptr, nullptr); EggTable *egg_table = new EggTable(node_desc->get_name()); node_desc->_anim = new EggXfmSAnim("xform", _egg_data->get_coordinate_system()); @@ -487,9 +489,9 @@ get_egg_anim(MayaNodeDesc *node_desc) { */ EggSAnimData *MayaNodeTree:: get_egg_slider(MayaBlendDesc *blend_desc) { - nassertr(_morph_node != (EggGroupNode *)NULL, NULL); + nassertr(_morph_node != nullptr, nullptr); - if (blend_desc->_anim == (EggSAnimData *)NULL) { + if (blend_desc->_anim == nullptr) { // We need to make a new anim table. EggSAnimData *egg_anim = new EggSAnimData(blend_desc->get_name()); egg_anim->set_fps(_fps); @@ -553,7 +555,7 @@ get_num_blend_descs() const { */ MayaBlendDesc *MayaNodeTree:: get_blend_desc(int n) const { - nassertr(n >= 0 && n < (int)_blend_descs.size(), NULL); + nassertr(n >= 0 && n < (int)_blend_descs.size(), nullptr); return _blend_descs[n]; } @@ -583,7 +585,7 @@ r_build_node(const string &path) { // Otherwise, we have to create it. Do this recursively, so we create each // node along the path. - MayaNodeDesc *node_desc = NULL; + MayaNodeDesc *node_desc = nullptr; // mayaegg_cat.info() << "path: " << path << endl; if (path.empty()) { @@ -610,8 +612,8 @@ r_build_node(const string &path) { if (node_desc != _root) { MayaNodeDesc *parent_node_desc = r_build_node(parent_path); - if (parent_node_desc == (MayaNodeDesc *)NULL) - mayaegg_cat.info() << "empty parent: " << local_name << endl; + if (parent_node_desc == nullptr) + mayaegg_cat.info() << "empty parent: " << local_name << std::endl; node_desc = new MayaNodeDesc(this, parent_node_desc, local_name); _nodes.push_back(node_desc); } diff --git a/pandatool/src/mayaegg/mayaNodeTree.h b/pandatool/src/mayaegg/mayaNodeTree.h index febb794f23..e355c45ff3 100644 --- a/pandatool/src/mayaegg/mayaNodeTree.h +++ b/pandatool/src/mayaegg/mayaNodeTree.h @@ -60,8 +60,8 @@ public: EggXfmSAnim *get_egg_anim(MayaNodeDesc *node_desc); EggSAnimData *get_egg_slider(MayaBlendDesc *blend_desc); - bool ignore_slider(const string &name) const; - void report_ignored_slider(const string &name); + bool ignore_slider(const std::string &name) const; + void report_ignored_slider(const std::string &name); MayaBlendDesc *add_blend_desc(MayaBlendDesc *blend_desc); int get_num_blend_descs() const; @@ -70,12 +70,12 @@ public: void reset_sliders(); public: - string _subroot_parent_name; + std::string _subroot_parent_name; PT(MayaNodeDesc) _root; PN_stdfloat _fps; private: - MayaNodeDesc *r_build_node(const string &path); + MayaNodeDesc *r_build_node(const std::string &path); MayaToEggConverter *_converter; @@ -84,7 +84,7 @@ private: EggGroupNode *_skeleton_node; EggGroupNode *_morph_node; - typedef pmap NodesByPath; + typedef pmap NodesByPath; NodesByPath _nodes_by_path; typedef pvector Nodes; @@ -93,7 +93,7 @@ private: typedef ov_set > BlendDescs; BlendDescs _blend_descs; - typedef pset Strings; + typedef pset Strings; Strings _ignored_slider_names; }; diff --git a/pandatool/src/mayaegg/mayaToEggConverter.cxx b/pandatool/src/mayaegg/mayaToEggConverter.cxx index d661af583b..7943f07f03 100644 --- a/pandatool/src/mayaegg/mayaToEggConverter.cxx +++ b/pandatool/src/mayaegg/mayaToEggConverter.cxx @@ -76,6 +76,9 @@ #include #include "post_maya_include.h" +using std::endl; +using std::string; + /** * @@ -537,7 +540,7 @@ convert_maya() { bool MayaToEggConverter:: open_api(bool revert_directory) { - if (_maya == (MayaApi *)NULL || !_maya->is_valid()) { + if (_maya == nullptr || !_maya->is_valid()) { // maya to egg converter only needs a read license. only egg2maya need // write lisences. _maya = MayaApi::open_api(_program_name, true, revert_directory); @@ -591,7 +594,7 @@ convert_flip(double start_frame, double end_frame, double frame_inc, while (frame <= frame_stop) { mayaegg_cat.info(false) << "frame " << frame.value() << "\n"; - ostringstream name_strm; + std::ostringstream name_strm; name_strm << "frame" << frame.value(); EggGroup *frame_root = new EggGroup(name_strm.str()); sequence_node->add_child(frame_root); @@ -653,7 +656,7 @@ convert_char_chan(double start_frame, double end_frame, double frame_inc, // Set the frame rate before we start asking for anim tables to be created. _tree._fps = output_frame_rate; - _tree.clear_egg(get_egg_data(), NULL, skeleton_node, morph_node); + _tree.clear_egg(get_egg_data(), nullptr, skeleton_node, morph_node); // Now we can get the animation data by walking through all of the frames, // one at a time, and getting the joint angles at each frame. @@ -675,7 +678,7 @@ convert_char_chan(double start_frame, double end_frame, double frame_inc, } else { // We have to write to cerr instead of mayaegg_cat to allow flushing // without writing a newline. - cerr << "." << flush; + std::cerr << "." << std::flush; } MGlobal::viewFrame(frame); @@ -758,7 +761,7 @@ convert_hierarchy(EggGroupNode *egg_root) { if (_legacy_shader) { mayaegg_cat.info() << "will disable modern Phong shader path. using legacy" << endl; } - _tree.clear_egg(get_egg_data(), egg_root, NULL, NULL); + _tree.clear_egg(get_egg_data(), egg_root, nullptr, nullptr); for (int i = 0; i < num_nodes; i++) { MayaNodeDesc *node = _tree.get_node(i); if (!process_model_node(node)) { @@ -1489,7 +1492,7 @@ make_nurbs_surface(MayaNodeDesc *node_desc, const MDagPath &dag_path, EggNurbsCurve *egg_curve = make_trim_curve(curve, name, egg_group, trim_curve_index); trim_curve_index++; - if (egg_curve != (EggNurbsCurve *)NULL) { + if (egg_curve != nullptr) { egg_loop.push_back(egg_curve); } } @@ -1509,7 +1512,7 @@ make_nurbs_surface(MayaNodeDesc *node_desc, const MDagPath &dag_path, // trim curves have been added. egg_group->add_child(egg_nurbs); - if (shader != (MayaShader *)NULL) { + if (shader != nullptr) { set_shader_attributes(*egg_nurbs, *shader); } @@ -1542,7 +1545,7 @@ make_nurbs_surface(MayaNodeDesc *node_desc, const MDagPath &dag_path, PN_stdfloat weight = weights[maya_vi * num_joints + ji]; if (weight != 0.0f) { EggGroup *joint = joints[ji]; - if (joint != (EggGroup *)NULL) { + if (joint != nullptr) { joint->ref_vertex(vert, weight); } } @@ -1581,13 +1584,13 @@ make_trim_curve(const MFnNurbsCurve &curve, const string &nurbs_name, status = curve.getCVs(cv_array, MSpace::kWorld); if (!status) { status.perror("MFnNurbsCurve::getCVs"); - return (EggNurbsCurve *)NULL; + return nullptr; } MDoubleArray knot_array; status = curve.getKnots(knot_array); if (!status) { status.perror("MFnNurbsCurve::getKnots"); - return (EggNurbsCurve *)NULL; + return nullptr; } /* @@ -1713,7 +1716,7 @@ make_nurbs_curve(const MDagPath &, const MFnNurbsCurve &curve, } } MayaShader *shader = _shaders.find_shader_for_node(curve.object(), _legacy_shader); - if (shader != (MayaShader *)NULL) { + if (shader != nullptr) { set_shader_attributes(*egg_curve, *shader); } } @@ -1838,7 +1841,7 @@ make_polyset(MayaNodeDesc *node_desc, const MDagPath &dag_path, // be two diverging paths for any Maya node with a Material (MayaShader) // on it This next bit kicks us out into mayaShader et al. to pull // textures and everything else. - MayaShader *shader = NULL; + MayaShader *shader = nullptr; int index = pi.index(); nassertv(index >= 0 && index < (int)poly_shader_indices.length()); int shader_index = poly_shader_indices[index]; @@ -1850,14 +1853,14 @@ make_polyset(MayaNodeDesc *node_desc, const MDagPath &dag_path, _shaders.find_shader_for_shading_engine(engine, _legacy_shader); //head out to the other classes // does this mean if we didn't find a Maya shader give it a default // value anyway? - } else if (default_shader != (MayaShader *)NULL) { + } else if (default_shader != nullptr) { shader = default_shader; } - const MayaShaderColorDef *default_color_def = NULL; + const MayaShaderColorDef *default_color_def = nullptr; // And apply the shader properties to the polygon. - if (shader != (MayaShader *)NULL) { + if (shader != nullptr) { set_shader_attributes(*egg_poly, *shader, true); default_color_def = shader->get_color_def(); } @@ -1874,7 +1877,7 @@ make_polyset(MayaNodeDesc *node_desc, const MDagPath &dag_path, // Furthermore, if _always_show_vertex_color is true, we pretend that the // "vertex-color" flag is always set. bool ignore_vertex_color = false; - if ( default_color_def != (MayaShaderColorDef *)NULL) { + if ( default_color_def != nullptr) { ignore_vertex_color = default_color_def->_has_texture && !(egg_vertex_color || _always_show_vertex_color); } @@ -1891,7 +1894,7 @@ make_polyset(MayaNodeDesc *node_desc, const MDagPath &dag_path, long i; LPoint3d centroid(0.0, 0.0, 0.0); - if (default_color_def != (MayaShaderColorDef *)NULL && default_color_def->has_projection()) { + if (default_color_def != nullptr && default_color_def->has_projection()) { // If the shader has a projection, we may need to compute the polygon's // centroid to avoid seams at the edges. for (i = 0; i < num_verts; i++) { @@ -1922,7 +1925,7 @@ make_polyset(MayaNodeDesc *node_desc, const MDagPath &dag_path, // Go thru all the texture references for this primitive and set uvs if (mayaegg_cat.is_spam()) { - if (shader != (MayaShader *)NULL) { + if (shader != nullptr) { mayaegg_cat.spam() << "shader->_color.size is " << shader->_color.size() << endl; } mayaegg_cat.spam() << "primitive->tref.size is " << egg_poly->get_num_textures() << endl; @@ -1946,7 +1949,7 @@ make_polyset(MayaNodeDesc *node_desc, const MDagPath &dag_path, bool project_uv = false; LTexCoordd uv_projection; - if (shader != (MayaShader *)NULL) { + if (shader != nullptr) { for (size_t tj = 0; tj < shader->_all_maps.size(); ++tj) { MayaShaderColorDef *def = shader->_all_maps[tj]; if (def->_uvset_name == uvset_name) { @@ -2082,7 +2085,7 @@ make_polyset(MayaNodeDesc *node_desc, const MDagPath &dag_path, PN_stdfloat weight = weights[maya_vi * num_joints + ji]; if (weight != 0.0f) { EggGroup *joint = joints[ji]; - if (joint != (EggGroup *)NULL) { + if (joint != nullptr) { joint->ref_vertex(vert, weight); } } @@ -2614,7 +2617,7 @@ set_shader_legacy(EggPrimitive &primitive, const MayaShader &shader, // determine if the base texture or any of the top texture need to be rgb // only - MayaShaderColorDef *color_def = NULL; + MayaShaderColorDef *color_def = nullptr; bool is_rgb = false; bool is_decal = false; bool is_interpolate = false; @@ -2644,7 +2647,7 @@ set_shader_legacy(EggPrimitive &primitive, const MayaShader &shader, is_decal = false; // new decal mode needs an extra dummy layers of textureStage - EggTexture *dummy_tex = (EggTexture *)NULL; + EggTexture *dummy_tex = nullptr; string dummy_uvset_name; // In Maya, a polygon is either textured or colored. The texture, if @@ -2856,7 +2859,7 @@ set_shader_legacy(EggPrimitive &primitive, const MayaShader &shader, } } } - if (dummy_tex != (EggTexture *)NULL) { + if (dummy_tex != nullptr) { primitive.add_texture(dummy_tex); dummy_tex->set_uv_name(dummy_uvset_name); } @@ -3052,7 +3055,7 @@ reparent_decals(EggGroupNode *egg_parent) { // First, walk through all children of this node, looking for the one decal // base, if any. - EggGroup *decal_base = (EggGroup *)NULL; + EggGroup *decal_base = nullptr; pvector decal_children; EggGroupNode::iterator ci; @@ -3061,7 +3064,7 @@ reparent_decals(EggGroupNode *egg_parent) { if (child->is_of_type(EggGroup::get_class_type())) { EggGroup *child_group = DCAST(EggGroup, child); if (child_group->has_object_type("decalbase")) { - if (decal_base != (EggNode *)NULL) { + if (decal_base != nullptr) { mayaegg_cat.error() << "Two children of " << egg_parent->get_name() << " both have decalbase set: " << decal_base->get_name() @@ -3078,7 +3081,7 @@ reparent_decals(EggGroupNode *egg_parent) { } } - if (decal_base == (EggGroup *)NULL) { + if (decal_base == nullptr) { if (!decal_children.empty()) { mayaegg_cat.warning() << decal_children.front()->get_name() @@ -3146,7 +3149,7 @@ string_transform_type(const string &arg) { */ void MayaToEggConverter:: set_vertex_color(EggVertex &vert, MItMeshPolygon &pi, int vert_index, const MayaShader *shader, const LColor &color) { - if (shader == (MayaShader *)NULL || shader->_legacy_mode) { + if (shader == nullptr || shader->_legacy_mode) { set_vertex_color_legacy(vert, pi, vert_index, shader, color); } else { set_vertex_color_modern(vert, pi, vert_index, shader, color); diff --git a/pandatool/src/mayaegg/mayaToEggConverter.h b/pandatool/src/mayaegg/mayaToEggConverter.h index 6662184bd1..3e3782a601 100644 --- a/pandatool/src/mayaegg/mayaToEggConverter.h +++ b/pandatool/src/mayaegg/mayaToEggConverter.h @@ -60,15 +60,15 @@ class MFloatArray; */ class MayaToEggConverter : public SomethingToEggConverter { public: - MayaToEggConverter(const string &program_name = ""); + MayaToEggConverter(const std::string &program_name = ""); MayaToEggConverter(const MayaToEggConverter ©); virtual ~MayaToEggConverter(); virtual SomethingToEggConverter *make_copy(); - virtual string get_name() const; - virtual string get_extension() const; - virtual string get_additional_extensions() const; + virtual std::string get_name() const; + virtual std::string get_extension() const; + virtual std::string get_additional_extensions() const; virtual bool convert_file(const Filename &filename); virtual DistanceUnit get_input_units(); @@ -84,11 +84,11 @@ public: void clear_ignore_sliders(); void add_ignore_slider(const GlobPattern &glob); - bool ignore_slider(const string &name) const; + bool ignore_slider(const std::string &name) const; void clear_force_joints(); void add_force_joint(const GlobPattern &glob); - bool force_joint(const string &name) const; + bool force_joint(const std::string &name) const; void set_from_selection(bool from_selection); @@ -123,7 +123,7 @@ private: MFnNurbsSurface &surface, EggGroup *group); EggNurbsCurve *make_trim_curve(const MFnNurbsCurve &curve, - const string &nurbs_name, + const std::string &nurbs_name, EggGroupNode *egg_group, int trim_curve_index); void make_nurbs_curve(const MDagPath &dag_path, @@ -131,7 +131,7 @@ private: EggGroup *group); void make_polyset(MayaNodeDesc *node_desc, const MDagPath &dag_path, const MFnMesh &mesh, EggGroup *egg_group, - MayaShader *default_shader = NULL); + MayaShader *default_shader = nullptr); void make_locator(const MDagPath &dag_path, const MFnDagNode &dag_node, EggGroup *egg_group); void make_camera_locator(const MDagPath &dag_path, const MFnDagNode &dag_node, @@ -167,10 +167,10 @@ private: int round(double value); - string _program_name; + std::string _program_name; bool _from_selection; - string _subroot; + std::string _subroot; typedef pvector Globs; Globs _subsets; Globs _subroots; @@ -205,7 +205,7 @@ public: }; TransformType _transform_type; - static TransformType string_transform_type(const string &arg); + static TransformType string_transform_type(const std::string &arg); }; diff --git a/pandatool/src/mayaprogs/blend_test.cxx b/pandatool/src/mayaprogs/blend_test.cxx index cf7e880731..ed03fd3661 100644 --- a/pandatool/src/mayaprogs/blend_test.cxx +++ b/pandatool/src/mayaprogs/blend_test.cxx @@ -21,7 +21,7 @@ #include #include -using namespace std; +using std::cerr; void scan_nodes() { @@ -177,7 +177,7 @@ output_vertices(const char *filename, MFnMesh &mesh) { exit(1); } - ofstream file(filename, ios::out | ios::trunc); + std::ofstream file(filename, std::ios::out | std::ios::trunc); if (!file) { cerr << "Couldn't open " << filename << " for output.\n"; exit(1); diff --git a/pandatool/src/mayaprogs/mayaCopy.cxx b/pandatool/src/mayaprogs/mayaCopy.cxx index 70cb614a2d..247e0b43ad 100644 --- a/pandatool/src/mayaprogs/mayaCopy.cxx +++ b/pandatool/src/mayaprogs/mayaCopy.cxx @@ -32,6 +32,9 @@ #include #include "post_maya_include.h" +using std::endl; +using std::string; + /** * */ diff --git a/pandatool/src/mayaprogs/mayaCopy.h b/pandatool/src/mayaprogs/mayaCopy.h index e48c2f9204..90ceddfbc0 100644 --- a/pandatool/src/mayaprogs/mayaCopy.h +++ b/pandatool/src/mayaprogs/mayaCopy.h @@ -41,7 +41,7 @@ protected: CVSSourceDirectory *dir, void *extra_data, bool new_file); - virtual string filter_filename(const string &source); + virtual std::string filter_filename(const std::string &source); private: enum FileType { diff --git a/pandatool/src/mayaprogs/mayaEggImport.cxx b/pandatool/src/mayaprogs/mayaEggImport.cxx index 4b4ee413f0..5e38271517 100644 --- a/pandatool/src/mayaprogs/mayaEggImport.cxx +++ b/pandatool/src/mayaprogs/mayaEggImport.cxx @@ -115,7 +115,7 @@ MStatus MayaEggImporter::reader ( const MFileObject& file, std::ostringstream log; Notify::ptr()->set_ostream_ptr(&log, false); bool ok = MayaLoadEggFile(fileName.asChar(), merge, model, anim, false); - string txt = log.str(); + std::string txt = log.str(); if (txt != "") { MGlobal::displayError(txt.c_str()); } else { diff --git a/pandatool/src/mayaprogs/mayaPview.cxx b/pandatool/src/mayaprogs/mayaPview.cxx index 286d94ad67..06fc171b14 100644 --- a/pandatool/src/mayaprogs/mayaPview.cxx +++ b/pandatool/src/mayaprogs/mayaPview.cxx @@ -119,16 +119,16 @@ doIt(const MArgList &args) { MProgressWindow::advanceProgress(1); // Now spawn a pview instance to view this temporary file. - string pview_args = "-clD"; + std::string pview_args = "-clD"; if (animate) { pview_args = "-clDa"; } // On Windows, we use the spawn function to run pview asynchronously. - string quoted = string("\"") + bam_filename.get_fullpath() + string("\""); + std::string quoted = std::string("\"") + bam_filename.get_fullpath() + std::string("\""); nout << "pview " << pview_args << " " << quoted << "\n"; int retval = _spawnlp(_P_DETACH, "pview", - "pview", pview_args.c_str(), quoted.c_str(), NULL); + "pview", pview_args.c_str(), quoted.c_str(), nullptr); if (retval == -1) { bam_filename.unlink(); MProgressWindow::endProgress(); @@ -146,7 +146,7 @@ doIt(const MArgList &args) { // create a separate PandaFramework for each invocation, even though in // principle we could be sharing one framework for all of them. int argc = 0; - char **argv = NULL; + char **argv = nullptr; PandaFramework framework; framework.open_framework(argc, argv); framework.set_window_title("Panda Viewer"); @@ -154,7 +154,7 @@ doIt(const MArgList &args) { PT(WindowFramework) window; window = framework.open_window(); - if (window == (WindowFramework *)NULL) { + if (window == nullptr) { // Couldn't open a window. nout << "Couldn't open a window!\n"; MProgressWindow::endProgress(); @@ -242,7 +242,7 @@ convert(const NodePath &parent, bool animate) { // Accept relative pathnames in the Maya file. Filename source_file = Filename::from_os_specific(MFileIO::currentFile().asChar()); - string source_dir = source_file.get_dirname(); + std::string source_dir = source_file.get_dirname(); if (!source_dir.empty()) { path_replace->_path.append_directory(source_dir); } @@ -281,7 +281,7 @@ convert(const NodePath &parent, bool animate) { egg_data->set_coordinate_system(CS_default); PT(PandaNode) result = load_egg_data(egg_data); - if (result == (PandaNode *)NULL) { + if (result == nullptr) { nout << "Unable to load converted egg data.\n"; return false; } diff --git a/pandatool/src/mayaprogs/mayaSavePview.cxx b/pandatool/src/mayaprogs/mayaSavePview.cxx index 60a115c14f..1537d95ce8 100644 --- a/pandatool/src/mayaprogs/mayaSavePview.cxx +++ b/pandatool/src/mayaprogs/mayaSavePview.cxx @@ -72,8 +72,8 @@ doIt(const MArgList &args) { #ifdef WIN32_VC // On Windows, we use the spawn function to run pview asynchronously. MString quoted = MString("\"") + filename + MString("\""); - int retval = _spawnlp(_P_DETACH, "pview", - "pview", pview_args.asChar(), quoted.asChar(), NULL); + intptr_t retval = _spawnlp(_P_DETACH, "pview", + "pview", pview_args.asChar(), quoted.asChar(), nullptr); if (retval == -1) { return MS::kFailure; } diff --git a/pandatool/src/mayaprogs/mayaToEgg.cxx b/pandatool/src/mayaprogs/mayaToEgg.cxx index 5ceb4cf1ee..1219f5389a 100644 --- a/pandatool/src/mayaprogs/mayaToEgg.cxx +++ b/pandatool/src/mayaprogs/mayaToEgg.cxx @@ -76,7 +76,7 @@ MayaToEgg() : "Specify the fit tolerance for Maya polygon tesselation. The smaller " "the number, the more polygons will be generated. The default is " "0.01.", - &MayaToEgg::dispatch_double, NULL, &_polygon_tolerance); + &MayaToEgg::dispatch_double, nullptr, &_polygon_tolerance); add_option ("bface", "", 0, @@ -130,7 +130,7 @@ MayaToEgg() : "transforms in the egg file. The option may be one of all, model, " "dcs, or none. The default is model, which means only transforms on " "nodes that have the model flag or the dcs flag are preserved.", - &MayaToEgg::dispatch_transform_type, NULL, &_transform_type); + &MayaToEgg::dispatch_transform_type, nullptr, &_transform_type); add_option ("subroot", "name", 0, @@ -140,7 +140,7 @@ MayaToEgg() : "like * or ?). This parameter may be repeated multiple times to name " "multiple roots. If it is omitted altogether, the entire file is " "converted.", - &MayaToEgg::dispatch_vector_string, NULL, &_subroots); + &MayaToEgg::dispatch_vector_string, nullptr, &_subroots); add_option ("subset", "name", 0, @@ -150,7 +150,7 @@ MayaToEgg() : "like * or ?). This parameter may be repeated multiple times to name " "multiple roots. If it is omitted altogether, the entire file is " "converted.", - &MayaToEgg::dispatch_vector_string, NULL, &_subsets); + &MayaToEgg::dispatch_vector_string, nullptr, &_subsets); add_option ("exclude", "name", 0, @@ -159,7 +159,7 @@ MayaToEgg() : "name matches the parameter (which may include globbing characters " "like * or ?). This parameter may be repeated multiple times to name " "multiple roots.", - &MayaToEgg::dispatch_vector_string, NULL, &_excludes); + &MayaToEgg::dispatch_vector_string, nullptr, &_excludes); add_option ("ignore-slider", "name", 0, @@ -168,19 +168,19 @@ MayaToEgg() : "and it will not become a part of the animation. This " "parameter may including globbing characters, and it may be repeated " "as needed.", - &MayaToEgg::dispatch_vector_string, NULL, &_ignore_sliders); + &MayaToEgg::dispatch_vector_string, nullptr, &_ignore_sliders); add_option ("force-joint", "name", 0, "Specifies the name of a DAG node that maya2egg " "should treat as a joint, even if it does not appear to be a Maya joint " "and does not appear to be animated.", - &MayaToEgg::dispatch_vector_string, NULL, &_force_joints); + &MayaToEgg::dispatch_vector_string, nullptr, &_force_joints); add_option ("v", "", 0, "Increase verbosity. More v's means more verbose.", - &MayaToEgg::dispatch_count, NULL, &_verbose); + &MayaToEgg::dispatch_count, nullptr, &_verbose); add_option ("legacy-shaders", "", 0, @@ -319,7 +319,7 @@ run() { * option. */ bool MayaToEgg:: -dispatch_transform_type(const string &opt, const string &arg, void *var) { +dispatch_transform_type(const std::string &opt, const std::string &arg, void *var) { MayaToEggConverter::TransformType *ip = (MayaToEggConverter::TransformType *)var; (*ip) = MayaToEggConverter::string_transform_type(arg); diff --git a/pandatool/src/mayaprogs/mayaToEgg.h b/pandatool/src/mayaprogs/mayaToEgg.h index 4b3661a104..a6ec0453f2 100644 --- a/pandatool/src/mayaprogs/mayaToEgg.h +++ b/pandatool/src/mayaprogs/mayaToEgg.h @@ -28,7 +28,7 @@ public: void run(); protected: - static bool dispatch_transform_type(const string &opt, const string &arg, void *var); + static bool dispatch_transform_type(const std::string &opt, const std::string &arg, void *var); int _verbose; bool _polygon_output; diff --git a/pandatool/src/mayaprogs/mayaToEgg_client.cxx b/pandatool/src/mayaprogs/mayaToEgg_client.cxx index dfde2661c1..a92e6195ec 100644 --- a/pandatool/src/mayaprogs/mayaToEgg_client.cxx +++ b/pandatool/src/mayaprogs/mayaToEgg_client.cxx @@ -41,7 +41,7 @@ int main(int argc, char *argv[]) { // Get the current working directory and make sure it's a string Filename cwd = ExecutionEnvironment::get_cwd(); - string s_cwd = (string)cwd.to_os_specific(); + std::string s_cwd = (std::string)cwd.to_os_specific(); NetDatagram datagram; // First part of the datagram is the argc diff --git a/pandatool/src/mayaprogs/mayaToEgg_server.cxx b/pandatool/src/mayaprogs/mayaToEgg_server.cxx index 30f88f99d0..e95118d33b 100644 --- a/pandatool/src/mayaprogs/mayaToEgg_server.cxx +++ b/pandatool/src/mayaprogs/mayaToEgg_server.cxx @@ -52,7 +52,7 @@ MayaToEggServer() : "Specify the fit tolerance for Maya polygon tesselation. The smaller " "the number, the more polygons will be generated. The default is " "0.01.", - &MayaToEggServer::dispatch_double, NULL, &_polygon_tolerance); + &MayaToEggServer::dispatch_double, nullptr, &_polygon_tolerance); add_option ("bface", "", 0, @@ -91,7 +91,7 @@ MayaToEggServer() : "transforms in the egg file. The option may be one of all, model, " "dcs, or none. The default is model, which means only transforms on " "nodes that have the model flag or the dcs flag are preserved.", - &MayaToEggServer::dispatch_transform_type, NULL, &_transform_type); + &MayaToEggServer::dispatch_transform_type, nullptr, &_transform_type); add_option ("subroot", "name", 0, @@ -101,7 +101,7 @@ MayaToEggServer() : "like * or ?). This parameter may be repeated multiple times to name " "multiple roots. If it is omitted altogether, the entire file is " "converted.", - &MayaToEggServer::dispatch_vector_string, NULL, &_subroots); + &MayaToEggServer::dispatch_vector_string, nullptr, &_subroots); add_option ("subset", "name", 0, @@ -111,7 +111,7 @@ MayaToEggServer() : "like * or ?). This parameter may be repeated multiple times to name " "multiple roots. If it is omitted altogether, the entire file is " "converted.", - &MayaToEggServer::dispatch_vector_string, NULL, &_subsets); + &MayaToEggServer::dispatch_vector_string, nullptr, &_subsets); add_option ("exclude", "name", 0, @@ -120,7 +120,7 @@ MayaToEggServer() : "name matches the parameter (which may include globbing characters " "like * or ?). This parameter may be repeated multiple times to name " "multiple roots.", - &MayaToEggServer::dispatch_vector_string, NULL, &_excludes); + &MayaToEggServer::dispatch_vector_string, nullptr, &_excludes); add_option ("ignore-slider", "name", 0, @@ -129,19 +129,19 @@ MayaToEggServer() : "and it will not become a part of the animation. This " "parameter may including globbing characters, and it may be repeated " "as needed.", - &MayaToEggServer::dispatch_vector_string, NULL, &_ignore_sliders); + &MayaToEggServer::dispatch_vector_string, nullptr, &_ignore_sliders); add_option ("force-joint", "name", 0, "Specifies the name of a DAG node that maya2egg " "should treat as a joint, even if it does not appear to be a Maya joint " "and does not appear to be animated.", - &MayaToEggServer::dispatch_vector_string, NULL, &_force_joints); + &MayaToEggServer::dispatch_vector_string, nullptr, &_force_joints); add_option ("v", "", 0, "Increase verbosity. More v's means more verbose.", - &MayaToEggServer::dispatch_count, NULL, &_verbose); + &MayaToEggServer::dispatch_count, nullptr, &_verbose); add_option ("legacy-shaders", "", 0, @@ -329,7 +329,7 @@ run() { * option. */ bool MayaToEggServer:: -dispatch_transform_type(const string &opt, const string &arg, void *var) { +dispatch_transform_type(const std::string &opt, const std::string &arg, void *var) { MayaToEggConverter::TransformType *ip = (MayaToEggConverter::TransformType *)var; (*ip) = MayaToEggConverter::string_transform_type(arg); @@ -389,7 +389,7 @@ poll() { // track of all the pointers we're gonna malloc. Needed later for // cleanup. vector_string vargv; - vector buffers; + std::vector buffers; // Get the strings from the datagram and put them into the string vector int i; @@ -399,7 +399,7 @@ poll() { // Last string is the current directory the client was run from. Not // part of the argument list, but we still need it - string cwd = data.get_string(); + std::string cwd = data.get_string(); // We allocate some memory to hold the pointers to the pointers we're // going to pass in to parse_command_line(). @@ -439,7 +439,7 @@ poll() { vargv.clear(); // No, iterate through the char * vector and cleanup the malloc'd // pointers - vector::iterator vi; + std::vector::iterator vi; for ( vi = buffers.begin() ; vi != buffers.end(); vi++) { free(*vi); } diff --git a/pandatool/src/mayaprogs/mayaToEgg_server.h b/pandatool/src/mayaprogs/mayaToEgg_server.h index 3eaf739ada..ba014f4846 100644 --- a/pandatool/src/mayaprogs/mayaToEgg_server.h +++ b/pandatool/src/mayaprogs/mayaToEgg_server.h @@ -43,7 +43,7 @@ public: protected: - static bool dispatch_transform_type(const string &opt, const string &arg, void *var); + static bool dispatch_transform_type(const std::string &opt, const std::string &arg, void *var); typedef pset< PT(Connection) > Clients; Clients _clients; diff --git a/pandatool/src/mayaprogs/mayapath.cxx b/pandatool/src/mayaprogs/mayapath.cxx index 428e4ba128..ae9ad39ac2 100644 --- a/pandatool/src/mayaprogs/mayapath.cxx +++ b/pandatool/src/mayaprogs/mayapath.cxx @@ -43,12 +43,18 @@ #include #if defined(_WIN32) +#ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN +#endif #include #else #include #endif +using std::cerr; +using std::endl; +using std::string; + #define QUOTESTR(x) #x #define TOSTRING(x) QUOTESTR(x) @@ -133,7 +139,7 @@ get_maya_location(const char *ver, string &loc) { DWORD dtype; DWORD size = 4096; char result[4096 + 1]; - res = RegQueryValueEx(hkey, "MAYA_INSTALL_LOCATION", NULL, &dtype, (LPBYTE)result, &size); + res = RegQueryValueEx(hkey, "MAYA_INSTALL_LOCATION", nullptr, &dtype, (LPBYTE)result, &size); if ((res == ERROR_SUCCESS)&&(dtype == REG_SZ)) { result[size] = 0; loc = result; @@ -222,7 +228,7 @@ main(int argc, char *argv[]) { Filename standard_maya_location; #ifdef MAYAVERSION const char *key = get_version_number(TOSTRING(MAYAVERSION)); - if (key == NULL) { + if (key == nullptr) { cerr << "Unknown Maya version: " << TOSTRING(MAYAVERSION) << "\n"; } else { string loc; @@ -386,7 +392,7 @@ main(int argc, char *argv[]) { #endif if (bin.is_directory()) { const char *path = getenv("PATH"); - if (path == NULL) { + if (path == nullptr) { path = ""; } string putenv_str = "PATH=" + bin.to_os_specific() + sep + path; @@ -398,7 +404,7 @@ main(int argc, char *argv[]) { // And on DYLD_LIBRARY_PATH. if (bin.is_directory()) { const char *path = getenv("DYLD_LIBRARY_PATH"); - if (path == NULL) { + if (path == nullptr) { path = ""; } string sep = ":"; @@ -411,7 +417,7 @@ main(int argc, char *argv[]) { Filename fw_dir = Filename(maya_location, "Frameworks"); if (fw_dir.is_directory()) { const char *path = getenv("DYLD_FALLBACK_FRAMEWORK_PATH"); - if (path == NULL) { + if (path == nullptr) { path = ""; } string sep = ":"; @@ -424,7 +430,7 @@ main(int argc, char *argv[]) { // Linux (or other non-Windows OS) gets it added to LD_LIBRARY_PATH. if (bin.is_directory()) { const char *path = getenv("LD_LIBRARY_PATH"); - if (path == NULL) { + if (path == nullptr) { path = ""; } string sep = ":"; @@ -451,8 +457,8 @@ main(int argc, char *argv[]) { GetStartupInfo(&startup_info); BOOL result = CreateProcess(os_command.c_str(), command_line, - NULL, NULL, true, 0, - NULL, NULL, + nullptr, nullptr, true, 0, + nullptr, nullptr, &startup_info, &process_info); if (result) { diff --git a/pandatool/src/mayaprogs/normal_test.cxx b/pandatool/src/mayaprogs/normal_test.cxx index e1015f2759..41680254de 100644 --- a/pandatool/src/mayaprogs/normal_test.cxx +++ b/pandatool/src/mayaprogs/normal_test.cxx @@ -23,7 +23,8 @@ #include #include -using namespace std; +using std::cerr; +using std::endl; void scan_nodes() { @@ -179,7 +180,7 @@ output_vertices(const char *filename, MFnMesh &mesh) { exit(1); } - ofstream file(filename, ios::out | ios::trunc); + std::ofstream file(filename, std::ios::out | std::ios::trunc); if (!file) { cerr << "Couldn't open " << filename << " for output.\n"; exit(1); diff --git a/pandatool/src/miscprogs/binToC.cxx b/pandatool/src/miscprogs/binToC.cxx index 8d1ee2dec8..f963c08986 100644 --- a/pandatool/src/miscprogs/binToC.cxx +++ b/pandatool/src/miscprogs/binToC.cxx @@ -38,7 +38,7 @@ BinToC() : add_option ("n", "name", 0, "Specify the name of the table that is generated.", - &BinToC::dispatch_string, NULL, &_table_name); + &BinToC::dispatch_string, nullptr, &_table_name); add_option ("static", "", 0, @@ -66,20 +66,20 @@ BinToC() : */ void BinToC:: run() { - ifstream in; + std::ifstream in; if (!_input_filename.open_read(in)) { nout << "Unable to read " << _input_filename << ".\n"; exit(1); } - ostream &out = get_output(); - string static_keyword; + std::ostream &out = get_output(); + std::string static_keyword; if (_static_table) { static_keyword = "static "; } - string table_type = "const unsigned char "; - string length_type = "const int "; + std::string table_type = "const unsigned char "; + std::string length_type = "const int "; if (_for_string) { // Actually, declaring the table as "const char" causes VC7 to yell about // truncating all of the values >= 0x80. table_type = "const char "; @@ -96,7 +96,7 @@ run() { << "#include \n" << "\n" << static_keyword << table_type << _table_name << "[] = {"; - out << hex << setfill('0'); + out << std::hex << std::setfill('0'); int count = 0; int col = 0; unsigned int ch; @@ -110,14 +110,14 @@ run() { } else { out << ", "; } - out << "0x" << setw(2) << ch; + out << "0x" << std::setw(2) << ch; col++; count++; ch = in.get(); } out << "\n};\n\n" << static_keyword << length_type << _table_name << "_len = " - << dec << count << ";\n\n"; + << std::dec << count << ";\n\n"; } /** diff --git a/pandatool/src/miscprogs/binToC.h b/pandatool/src/miscprogs/binToC.h index 39eff76766..f1ba6599b2 100644 --- a/pandatool/src/miscprogs/binToC.h +++ b/pandatool/src/miscprogs/binToC.h @@ -34,7 +34,7 @@ protected: virtual bool handle_args(Args &args); Filename _input_filename; - string _table_name; + std::string _table_name; bool _static_table; bool _for_string; }; diff --git a/pandatool/src/objegg/eggToObjConverter.cxx b/pandatool/src/objegg/eggToObjConverter.cxx index bd359e935a..a03630698c 100644 --- a/pandatool/src/objegg/eggToObjConverter.cxx +++ b/pandatool/src/objegg/eggToObjConverter.cxx @@ -23,6 +23,9 @@ #include "eggLine.h" #include "dcast.h" +using std::ostream; +using std::string; + /** * */ @@ -110,14 +113,14 @@ process(const Filename &filename) { Filename obj_filename = Filename::text_filename(filename); vfs->delete_file(obj_filename); ostream *file = vfs->open_write_file(obj_filename, true, true); - if (file == (ostream *)NULL) { + if (file == nullptr) { return false; } if (egg_precision != 0) { file->precision(egg_precision); } - _current_group = NULL; + _current_group = nullptr; /* (*file) << "\n#\n" @@ -134,7 +137,7 @@ process(const Filename &filename) { write_faces(*file, _egg_data); - bool success = (file != (ostream *)NULL); + bool success = (file != nullptr); vfs->close_write_file(file); return success; @@ -171,7 +174,7 @@ collect_vertices(EggNode *egg_node) { void EggToObjConverter:: write_faces(ostream &out, EggNode *egg_node) { if (egg_node->is_of_type(EggPrimitive::get_class_type())) { - const char *prim_type = NULL; + const char *prim_type = nullptr; if (egg_node->is_of_type(EggPolygon::get_class_type())) { prim_type = "f"; } else if (egg_node->is_of_type(EggPoint::get_class_type())) { @@ -180,7 +183,7 @@ write_faces(ostream &out, EggNode *egg_node) { prim_type = "l"; } - if (prim_type != NULL) { + if (prim_type != nullptr) { write_group_reference(out, egg_node); EggPrimitive *egg_prim = DCAST(EggPrimitive, egg_node); @@ -280,7 +283,7 @@ get_group_name(string &group_name, EggGroupNode *egg_group) { // Now recurse. EggGroupNode *egg_parent = egg_group->get_parent(); - if (egg_parent != NULL) { + if (egg_parent != nullptr) { get_group_name(group_name, egg_parent); } } @@ -379,7 +382,7 @@ write_vertices(ostream &out, const string &prefix, int num_components, int index = (*ui).second; const LVecBase4d &vec = (*ui).first; nassertv(index >= 0 && index < num_vertices); - nassertv(vertices[index] == NULL); + nassertv(vertices[index] == nullptr); vertices[index] = &vec; } diff --git a/pandatool/src/objegg/eggToObjConverter.h b/pandatool/src/objegg/eggToObjConverter.h index a36fa77500..51f940d56c 100644 --- a/pandatool/src/objegg/eggToObjConverter.h +++ b/pandatool/src/objegg/eggToObjConverter.h @@ -31,8 +31,8 @@ public: virtual EggToSomethingConverter *make_copy(); - virtual string get_name() const; - virtual string get_extension() const; + virtual std::string get_name() const; + virtual std::string get_extension() const; virtual bool supports_compressed() const; virtual bool write_file(const Filename &filename); @@ -53,9 +53,9 @@ private: bool process(const Filename &filename); void collect_vertices(EggNode *egg_node); - void write_faces(ostream &out, EggNode *egg_node); - void write_group_reference(ostream &out, EggNode *egg_node); - void get_group_name(string &group_name, EggGroupNode *egg_group); + void write_faces(std::ostream &out, EggNode *egg_node); + void write_group_reference(std::ostream &out, EggNode *egg_node); + void get_group_name(std::string &group_name, EggGroupNode *egg_group); void record_vertex(EggVertex *vertex); int record_unique(UniqueVertices &unique, const LVecBase4d &vec); @@ -63,12 +63,10 @@ private: int record_unique(UniqueVertices &unique, const LVecBase2d &vec); int record_unique(UniqueVertices &unique, double pos); - void write_vertices(ostream &out, const string &prefix, int num_components, + void write_vertices(std::ostream &out, const std::string &prefix, int num_components, const UniqueVertices &unique); private: - bool _triangulate_polygons; - UniqueVertices _unique_vert3, _unique_vert4, _unique_uv2, _unique_uv3, _unique_norm; VertexMap _vmap; EggGroupNode *_current_group; diff --git a/pandatool/src/objegg/objToEggConverter.cxx b/pandatool/src/objegg/objToEggConverter.cxx index c6df68710c..7044409ca5 100644 --- a/pandatool/src/objegg/objToEggConverter.cxx +++ b/pandatool/src/objegg/objToEggConverter.cxx @@ -27,6 +27,8 @@ #include "triangulator3.h" #include "config_egg2pg.h" +using std::string; + /** * */ @@ -135,7 +137,7 @@ convert_to_node(const LoaderOptions &options, const Filename &filename) { delete _current_vertex_data; if (had_error()) { - return NULL; + return nullptr; } return _root_node; @@ -147,8 +149,8 @@ convert_to_node(const LoaderOptions &options, const Filename &filename) { bool ObjToEggConverter:: process(const Filename &filename) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); - istream *strm = vfs->open_read_file(filename, true); - if (strm == NULL) { + std::istream *strm = vfs->open_read_file(filename, true); + if (strm == nullptr) { objegg_cat.error() << "Couldn't read " << filename << "\n"; return false; @@ -270,7 +272,6 @@ process_ref_plane_res(const string &line) { } bool okflag = true; - LPoint3d pos; okflag &= string_to_double(words[1], _ref_plane_res[0]); okflag &= string_to_double(words[2], _ref_plane_res[1]); @@ -449,7 +450,7 @@ process_f(vector_string &words) { PT(EggPolygon) poly = new EggPolygon; for (size_t i = 1; i < words.size(); ++i) { EggVertex *vertex = get_face_vertex(words[i]); - if (vertex == NULL) { + if (vertex == nullptr) { return false; } poly->add_vertex(vertex); @@ -475,7 +476,7 @@ process_g(vector_string &words) { while (i > 1) { --i; EggNode *child = group->find_child(words[i]); - if (child == NULL || !child->is_of_type(EggGroup::get_class_type())) { + if (child == nullptr || !child->is_of_type(EggGroup::get_class_type())) { child = new EggGroup(words[i]); group->add_child(child); } @@ -553,8 +554,8 @@ generate_egg_points() { bool ObjToEggConverter:: process_node(const Filename &filename) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); - istream *strm = vfs->open_read_file(filename, true); - if (strm == NULL) { + std::istream *strm = vfs->open_read_file(filename, true); + if (strm == nullptr) { objegg_cat.error() << "Couldn't read " << filename << "\n"; return false; @@ -648,7 +649,7 @@ process_f_node(vector_string &words) { _f_given = true; bool all_vn = true; - int non_vn_index = -1; + //int non_vn_index = -1; pvector verts; verts.reserve(words.size() - 1); @@ -657,7 +658,7 @@ process_f_node(vector_string &words) { verts.push_back(entry); if (entry._vni == 0) { all_vn = false; - non_vn_index = i; + //non_vn_index = i; } } @@ -705,7 +706,7 @@ process_f_node(vector_string &words) { } if (_current_vertex_data->_prim->get_num_vertices() + 3 * num_tris > egg_max_indices || - _current_vertex_data->_entries.size() + verts.size() > egg_max_vertices) { + _current_vertex_data->_entries.size() + verts.size() > (size_t)egg_max_vertices) { // We'll exceed our specified limit with these triangles; start a new // Geom. _current_vertex_data->close_geom(this); @@ -735,7 +736,7 @@ bool ObjToEggConverter:: process_g_node(vector_string &words) { _current_vertex_data->close_geom(this); delete _current_vertex_data; - _current_vertex_data = NULL; + _current_vertex_data = nullptr; NodePath np(_root_node); @@ -800,7 +801,7 @@ generate_points() { */ int ObjToEggConverter:: add_synth_normal(const LVecBase3d &normal) { - pair result = _unique_synth_vn_table.insert(UniqueVec3Table::value_type(normal, _unique_synth_vn_table.size())); + std::pair result = _unique_synth_vn_table.insert(UniqueVec3Table::value_type(normal, _unique_synth_vn_table.size())); UniqueVec3Table::iterator ni = result.first; int index = (*ni).second; @@ -879,7 +880,7 @@ ObjToEggConverter::VertexData:: VertexData(PandaNode *parent, const string &name) : _parent(parent), _name(name) { - _geom_node = NULL; + _geom_node = nullptr; _v4_given = false; _vt3_given = false; @@ -896,7 +897,7 @@ VertexData(PandaNode *parent, const string &name) : */ int ObjToEggConverter::VertexData:: add_vertex(const ObjToEggConverter *converter, const VertexEntry &entry) { - pair result; + std::pair result; UniqueVertexEntries::iterator ni; int index; @@ -1091,7 +1092,7 @@ close_geom(const ObjToEggConverter *converter) { PT(Geom) geom = new Geom(vdata); geom->add_primitive(_prim); - if (_geom_node == NULL) { + if (_geom_node == nullptr) { _geom_node = new GeomNode(_name); _parent->add_child(_geom_node); } diff --git a/pandatool/src/objegg/objToEggConverter.h b/pandatool/src/objegg/objToEggConverter.h index 062f08c6cd..528dab8e7a 100644 --- a/pandatool/src/objegg/objToEggConverter.h +++ b/pandatool/src/objegg/objToEggConverter.h @@ -38,8 +38,8 @@ public: virtual SomethingToEggConverter *make_copy(); - virtual string get_name() const; - virtual string get_extension() const; + virtual std::string get_name() const; + virtual std::string get_extension() const; virtual bool supports_compressed() const; virtual bool supports_convert_to_node(const LoaderOptions &options) const; @@ -48,8 +48,8 @@ public: protected: bool process(const Filename &filename); - bool process_line(const string &line); - bool process_ref_plane_res(const string &line); + bool process_line(const std::string &line); + bool process_ref_plane_res(const std::string &line); bool process_v(vector_string &words); bool process_vt(vector_string &words); @@ -59,11 +59,11 @@ protected: bool process_f(vector_string &words); bool process_g(vector_string &words); - EggVertex *get_face_vertex(const string &face_reference); + EggVertex *get_face_vertex(const std::string &face_reference); void generate_egg_points(); bool process_node(const Filename &filename); - bool process_line_node(const string &line); + bool process_line_node(const std::string &line); bool process_f_node(vector_string &words); bool process_g_node(vector_string &words); @@ -88,7 +88,7 @@ protected: bool _v4_given, _vt3_given; bool _f_given; - pset _ignored_tags; + pset _ignored_tags; // Structures filled when creating an egg file. PT(EggVertexPool) _vpool; @@ -101,7 +101,7 @@ protected: class VertexEntry { public: VertexEntry(); - VertexEntry(const ObjToEggConverter *converter, const string &obj_vertex); + VertexEntry(const ObjToEggConverter *converter, const std::string &obj_vertex); INLINE bool operator < (const VertexEntry &other) const; INLINE bool operator == (const VertexEntry &other) const; @@ -119,7 +119,7 @@ protected: class VertexData { public: - VertexData(PandaNode *parent, const string &name); + VertexData(PandaNode *parent, const std::string &name); int add_vertex(const ObjToEggConverter *converter, const VertexEntry &entry); void add_triangle(const ObjToEggConverter *converter, const VertexEntry &v0, @@ -128,7 +128,7 @@ protected: void close_geom(const ObjToEggConverter *converter); PT(PandaNode) _parent; - string _name; + std::string _name; PT(GeomNode) _geom_node; PT(GeomPrimitive) _prim; diff --git a/pandatool/src/palettizer/destTextureImage.cxx b/pandatool/src/palettizer/destTextureImage.cxx index 757772912e..38f9a879d1 100644 --- a/pandatool/src/palettizer/destTextureImage.cxx +++ b/pandatool/src/palettizer/destTextureImage.cxx @@ -48,8 +48,8 @@ DestTextureImage(TexturePlacement *placement) { _x_size = to_power_2(_x_size); _y_size = to_power_2(_y_size); } else { - _x_size = max(_x_size, 1); - _y_size = max(_y_size, 1); + _x_size = std::max(_x_size, 1); + _y_size = std::max(_y_size, 1); } } @@ -98,7 +98,7 @@ copy_if_stale(const DestTextureImage *other, TextureImage *texture) { // Also check the timestamps. SourceTextureImage *source = texture->get_preferred_source(); - if (source != (SourceTextureImage *)NULL && + if (source != nullptr && source->get_filename().compare_timestamps(get_filename()) > 0) { copy(texture); } diff --git a/pandatool/src/palettizer/destTextureImage.h b/pandatool/src/palettizer/destTextureImage.h index 0916661c6c..31075b8f99 100644 --- a/pandatool/src/palettizer/destTextureImage.h +++ b/pandatool/src/palettizer/destTextureImage.h @@ -65,8 +65,8 @@ private: static TypeHandle _type_handle; }; -INLINE ostream & -operator << (ostream &out, const DestTextureImage &dest) { +INLINE std::ostream & +operator << (std::ostream &out, const DestTextureImage &dest) { dest.output_filename(out); return out; } diff --git a/pandatool/src/palettizer/eggFile.cxx b/pandatool/src/palettizer/eggFile.cxx index 86e7bb1a6e..40376a7988 100644 --- a/pandatool/src/palettizer/eggFile.cxx +++ b/pandatool/src/palettizer/eggFile.cxx @@ -41,9 +41,9 @@ TypeHandle EggFile::_type_handle; */ EggFile:: EggFile() { - _data = (EggData *)NULL; + _data = nullptr; _first_txa_match = false; - _default_group = (PaletteGroup *)NULL; + _default_group = nullptr; _is_surprise = true; _is_stale = true; _had_data = false; @@ -57,7 +57,7 @@ bool EggFile:: from_command_line(EggData *data, const Filename &source_filename, const Filename &dest_filename, - const string &egg_comment) { + const std::string &egg_comment) { _data = data; _had_data = true; remove_backstage(_data); @@ -100,7 +100,7 @@ get_source_filename() const { */ void EggFile:: scan_textures() { - nassertv(_data != (EggData *)NULL); + nassertv(_data != nullptr); // Extract the set of textures referenced by this egg file. EggTextureCollection tc; @@ -338,7 +338,7 @@ build_cross_links() { for (ti = _textures.begin(); ti != _textures.end(); ++ti) { TextureReference *reference = (*ti); TextureImage *texture = reference->get_texture(); - nassertv(texture != (TextureImage *)NULL); + nassertv(texture != nullptr); texture->note_egg_file(this); // Actually, this may count the same egg file multiple times for a @@ -384,7 +384,7 @@ choose_placements() { TextureReference *reference = (*ti); TextureImage *texture = reference->get_texture(); - if (reference->get_placement() != (TexturePlacement *)NULL && + if (reference->get_placement() != nullptr && texture->get_groups().count(reference->get_placement()->get_group()) != 0) { // The egg file is already using a TexturePlacement that is suitable. // Don't bother changing it. @@ -413,7 +413,7 @@ choose_placements() { // Now get the TexturePlacement object that corresponds to the // placement of this texture into this group. TexturePlacement *placement = texture->get_placement(group); - nassertv(placement != (TexturePlacement *)NULL); + nassertv(placement != nullptr); reference->set_placement(placement); } @@ -427,7 +427,7 @@ choose_placements() { */ bool EggFile:: has_data() const { - return (_data != (EggData *)NULL); + return (_data != nullptr); } /** @@ -445,7 +445,7 @@ had_data() const { */ void EggFile:: update_egg() { - nassertv(_data != (EggData *)NULL); + nassertv(_data != nullptr); Textures::iterator ti; for (ti = _textures.begin(); ti != _textures.end(); ++ti) { @@ -478,7 +478,7 @@ remove_egg() { */ bool EggFile:: read_egg(bool noabs) { - nassertr(_data == (EggData *)NULL, false); + nassertr(_data == nullptr, false); nassertr(!_source_filename.empty(), false); Filename user_source_filename = @@ -551,8 +551,8 @@ read_egg(bool noabs) { */ void EggFile:: release_egg_data() { - if (_data != (EggData *)NULL) { - _data = NULL; + if (_data != nullptr) { + _data = nullptr; } Textures::iterator ti; for (ti = _textures.begin(); ti != _textures.end(); ++ti) { @@ -567,7 +567,7 @@ release_egg_data() { */ bool EggFile:: write_egg() { - nassertr(_data != (EggData *)NULL, false); + nassertr(_data != nullptr, false); nassertr(!_dest_filename.empty(), false); _dest_filename.make_dir(); @@ -588,10 +588,10 @@ write_egg() { * the indicated output stream. */ void EggFile:: -write_description(ostream &out, int indent_level) const { +write_description(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_name() << ": "; if (_explicitly_assigned_groups.empty()) { - if (_default_group != (PaletteGroup *)NULL) { + if (_default_group != nullptr) { out << _default_group->get_name(); } } else { @@ -609,7 +609,7 @@ write_description(ostream &out, int indent_level) const { * per line. */ void EggFile:: -write_texture_refs(ostream &out, int indent_level) const { +write_texture_refs(std::ostream &out, int indent_level) const { Textures::const_iterator ti; for (ti = _textures.begin(); ti != _textures.end(); ++ti) { TextureReference *reference = (*ti); @@ -654,7 +654,7 @@ remove_backstage(EggGroupNode *node) { */ void EggFile:: rescan_textures() { - nassertv(_data != (EggData *)NULL); + nassertv(_data != nullptr); // Extract the set of textures referenced by this egg file. EggTextureCollection tc; @@ -663,7 +663,7 @@ rescan_textures() { // Make sure each tref name is unique within a given file. tc.uniquify_trefs(); - typedef pmap ByTRefName; + typedef pmap ByTRefName; ByTRefName by_tref_name; for (Textures::const_iterator ti = _textures.begin(); ti != _textures.end(); @@ -751,7 +751,7 @@ complete_pointers(TypedWritable **p_list, BamReader *manager) { pi += _explicitly_assigned_groups.complete_pointers(p_list + pi, manager); - if (p_list[pi] != (TypedWritable *)NULL) { + if (p_list[pi] != nullptr) { DCAST_INTO_R(_default_group, p_list[pi], pi); } pi++; diff --git a/pandatool/src/palettizer/eggFile.h b/pandatool/src/palettizer/eggFile.h index 39f3b577df..cc3887242e 100644 --- a/pandatool/src/palettizer/eggFile.h +++ b/pandatool/src/palettizer/eggFile.h @@ -40,7 +40,7 @@ public: bool from_command_line(EggData *data, const Filename &source_filename, const Filename &dest_filename, - const string &egg_comment); + const std::string &egg_comment); const Filename &get_source_filename() const; @@ -73,8 +73,8 @@ public: void release_egg_data(); bool write_egg(); - void write_description(ostream &out, int indent_level = 0) const; - void write_texture_refs(ostream &out, int indent_level = 0) const; + void write_description(std::ostream &out, int indent_level = 0) const; + void write_texture_refs(std::ostream &out, int indent_level = 0) const; private: void remove_backstage(EggGroupNode *node); @@ -85,12 +85,11 @@ private: Filename _current_directory; Filename _source_filename; Filename _dest_filename; - string _egg_comment; + std::string _egg_comment; typedef pvector Textures; Textures _textures; - bool _noabs; bool _first_txa_match; PaletteGroups _explicitly_assigned_groups; PaletteGroup *_default_group; diff --git a/pandatool/src/palettizer/filenameUnifier.h b/pandatool/src/palettizer/filenameUnifier.h index b5646f5628..0f701b3ce5 100644 --- a/pandatool/src/palettizer/filenameUnifier.h +++ b/pandatool/src/palettizer/filenameUnifier.h @@ -44,7 +44,7 @@ private: static Filename _txa_dir; static Filename _rel_dirname; - typedef pmap CanonicalFilenames; + typedef pmap CanonicalFilenames; static CanonicalFilenames _canonical_filenames; }; diff --git a/pandatool/src/palettizer/imageFile.cxx b/pandatool/src/palettizer/imageFile.cxx index 54071d4cb1..15a5ebc4e6 100644 --- a/pandatool/src/palettizer/imageFile.cxx +++ b/pandatool/src/palettizer/imageFile.cxx @@ -24,6 +24,8 @@ #include "bamReader.h" #include "bamWriter.h" +using std::string; + TypeHandle ImageFile::_type_handle; /** @@ -160,7 +162,7 @@ set_filename(PaletteGroup *group, const string &basename) { break; case 'g': - if (group != (PaletteGroup *)NULL) { + if (group != nullptr) { dirname += group->get_dirname(); } break; @@ -199,12 +201,12 @@ set_filename(const string &dirname, const string &basename) { // be truncated at that dot. It is therefore important that the supplied // basename always contains either an extension or a terminating dot. - if (_properties._color_type != (PNMFileType *)NULL) { + if (_properties._color_type != nullptr) { _filename.set_extension (_properties._color_type->get_suggested_extension()); } - if (_properties._alpha_type != (PNMFileType *)NULL) { + if (_properties._alpha_type != nullptr) { _alpha_filename = _filename.get_fullpath_wo_extension() + "_a."; _alpha_filename.set_extension (_properties._alpha_type->get_suggested_extension()); @@ -255,7 +257,7 @@ exists() const { if (!_filename.exists()) { return false; } - if (_properties._alpha_type != (PNMFileType *)NULL && + if (_properties._alpha_type != nullptr && _properties.uses_alpha() && !_alpha_filename.empty()) { if (!_alpha_filename.exists()) { @@ -338,7 +340,7 @@ write(const PNMImage &image) const { nassertr(!_filename.empty(), false); if (!image.has_alpha() || - _properties._alpha_type == (PNMFileType *)NULL) { + _properties._alpha_type == nullptr) { if (!_alpha_filename.empty() && _alpha_filename.exists()) { nout << "Deleting " << FilenameUnifier::make_user_filename(_alpha_filename) << "\n"; _alpha_filename.unlink(); @@ -399,7 +401,7 @@ unlink() { */ void ImageFile:: update_egg_tex(EggTexture *egg_tex) const { - nassertv(egg_tex != (EggTexture *)NULL); + nassertv(egg_tex != nullptr); egg_tex->set_filename(FilenameUnifier::make_egg_filename(_filename)); @@ -419,7 +421,7 @@ update_egg_tex(EggTexture *egg_tex) const { * Writes the filename (or pair of filenames) to the indicated output stream. */ void ImageFile:: -output_filename(ostream &out) const { +output_filename(std::ostream &out) const { out << FilenameUnifier::make_user_filename(_filename); if (_properties.uses_alpha() && !_alpha_filename.empty()) { out << " " << FilenameUnifier::make_user_filename(_alpha_filename); diff --git a/pandatool/src/palettizer/imageFile.h b/pandatool/src/palettizer/imageFile.h index 80de6266f3..c4d8ed9014 100644 --- a/pandatool/src/palettizer/imageFile.h +++ b/pandatool/src/palettizer/imageFile.h @@ -34,7 +34,7 @@ class ImageFile : public TypedWritable { public: ImageFile(); - bool make_shadow_image(const string &basename); + bool make_shadow_image(const std::string &basename); bool is_size_known() const; int get_x_size() const; @@ -46,8 +46,8 @@ public: void clear_basic_properties(); void update_properties(const TextureProperties &properties); - bool set_filename(PaletteGroup *group, const string &basename); - bool set_filename(const string &dirname, const string &basename); + bool set_filename(PaletteGroup *group, const std::string &basename); + bool set_filename(const std::string &dirname, const std::string &basename); const Filename &get_filename() const; const Filename &get_alpha_filename() const; int get_alpha_file_channel() const; @@ -59,7 +59,7 @@ public: void update_egg_tex(EggTexture *egg_tex) const; - void output_filename(ostream &out) const; + void output_filename(std::ostream &out) const; protected: TextureProperties _properties; diff --git a/pandatool/src/palettizer/omitReason.cxx b/pandatool/src/palettizer/omitReason.cxx index 94848b865c..6bc14240f4 100644 --- a/pandatool/src/palettizer/omitReason.cxx +++ b/pandatool/src/palettizer/omitReason.cxx @@ -13,8 +13,8 @@ #include "omitReason.h" -ostream & -operator << (ostream &out, OmitReason omit) { +std::ostream & +operator << (std::ostream &out, OmitReason omit) { switch (omit) { case OR_none: return out << "none"; diff --git a/pandatool/src/palettizer/omitReason.h b/pandatool/src/palettizer/omitReason.h index db2a7bb03f..c60a86f364 100644 --- a/pandatool/src/palettizer/omitReason.h +++ b/pandatool/src/palettizer/omitReason.h @@ -52,6 +52,6 @@ enum OmitReason { // The texture is omitted because _omit_everything is set true. }; -ostream &operator << (ostream &out, OmitReason omit); +std::ostream &operator << (std::ostream &out, OmitReason omit); #endif diff --git a/pandatool/src/palettizer/pal_string_utils.cxx b/pandatool/src/palettizer/pal_string_utils.cxx index 4fd04bbe3f..279a7aad47 100644 --- a/pandatool/src/palettizer/pal_string_utils.cxx +++ b/pandatool/src/palettizer/pal_string_utils.cxx @@ -16,6 +16,8 @@ #include "pnmFileType.h" #include "pnmFileTypeRegistry.h" +using std::string; + // Extracts the first word of the string into param, and the remainder of the // line into value. @@ -51,8 +53,8 @@ bool parse_image_type_request(const string &word, PNMFileType *&color_type, PNMFileType *&alpha_type) { PNMFileTypeRegistry *registry = PNMFileTypeRegistry::get_global_ptr(); - color_type = (PNMFileType *)NULL; - alpha_type = (PNMFileType *)NULL; + color_type = nullptr; + alpha_type = nullptr; string color_name = word; string alpha_name; @@ -66,7 +68,7 @@ parse_image_type_request(const string &word, PNMFileType *&color_type, if (!color_name.empty()) { color_type = registry->get_type_from_extension(color_name); - if (color_type == (PNMFileType *)NULL) { + if (color_type == nullptr) { nout << "Image file type '" << color_name << "' is unknown.\n"; return false; } @@ -74,7 +76,7 @@ parse_image_type_request(const string &word, PNMFileType *&color_type, if (!alpha_name.empty()) { alpha_type = registry->get_type_from_extension(alpha_name); - if (alpha_type == (PNMFileType *)NULL) { + if (alpha_type == nullptr) { nout << "Image file type '" << alpha_name << "' is unknown.\n"; return false; } diff --git a/pandatool/src/palettizer/pal_string_utils.h b/pandatool/src/palettizer/pal_string_utils.h index 6eed342977..4f37b33063 100644 --- a/pandatool/src/palettizer/pal_string_utils.h +++ b/pandatool/src/palettizer/pal_string_utils.h @@ -19,9 +19,9 @@ class PNMFileType; -void extract_param_value(const string &str, string ¶m, string &value); +void extract_param_value(const std::string &str, std::string ¶m, std::string &value); -bool parse_image_type_request(const string &word, PNMFileType *&color_type, +bool parse_image_type_request(const std::string &word, PNMFileType *&color_type, PNMFileType *&alpha_type); #endif diff --git a/pandatool/src/palettizer/paletteGroup.cxx b/pandatool/src/palettizer/paletteGroup.cxx index 409bf28f33..182479216f 100644 --- a/pandatool/src/palettizer/paletteGroup.cxx +++ b/pandatool/src/palettizer/paletteGroup.cxx @@ -26,6 +26,8 @@ #include "indirectCompareNames.h" #include "pvector.h" +using std::string; + TypeHandle PaletteGroup::_type_handle; /** @@ -454,7 +456,7 @@ update_unknown_textures(const TxaFile &txa_file) { * their textures, to the indicated output stream. */ void PaletteGroup:: -write_image_info(ostream &out, int indent_level) const { +write_image_info(std::ostream &out, int indent_level) const { Pages::const_iterator pai; for (pai = _pages.begin(); pai != _pages.end(); ++pai) { PalettePage *page = (*pai).second; diff --git a/pandatool/src/palettizer/paletteGroup.h b/pandatool/src/palettizer/paletteGroup.h index 615663b571..54eaa08fc0 100644 --- a/pandatool/src/palettizer/paletteGroup.h +++ b/pandatool/src/palettizer/paletteGroup.h @@ -44,9 +44,9 @@ class PaletteGroup : public TypedWritable, public Namable { public: PaletteGroup(); - void set_dirname(const string &dirname); + void set_dirname(const std::string &dirname); bool has_dirname() const; - const string &get_dirname() const; + const std::string &get_dirname() const; void clear_depends(); void group_with(PaletteGroup *other); @@ -80,17 +80,17 @@ public: void place_all(); void update_unknown_textures(const TxaFile &txa_file); - void write_image_info(ostream &out, int indent_level = 0) const; + void write_image_info(std::ostream &out, int indent_level = 0) const; void optimal_resize(); void reset_images(); void setup_shadow_images(); void update_images(bool redo_all); - void add_texture_swap_info(const string sourceTextureName, const vector_string &swapTextures); + void add_texture_swap_info(const std::string sourceTextureName, const vector_string &swapTextures); bool is_none_texture_swap() const; private: - string _dirname; + std::string _dirname; int _egg_count; PaletteGroups _dependent; int _dependency_level; @@ -103,7 +103,7 @@ private: typedef pmap Pages; Pages _pages; - typedef pmap TextureSwapInfo; + typedef pmap TextureSwapInfo; TextureSwapInfo _textureSwapInfo; // The TypedWritable interface follows. diff --git a/pandatool/src/palettizer/paletteGroups.cxx b/pandatool/src/palettizer/paletteGroups.cxx index ae1f810d5e..c964f2b057 100644 --- a/pandatool/src/palettizer/paletteGroups.cxx +++ b/pandatool/src/palettizer/paletteGroups.cxx @@ -213,7 +213,7 @@ end() const { * */ void PaletteGroups:: -output(ostream &out) const { +output(std::ostream &out) const { if (!_groups.empty()) { // Sort the group names into order by name for output. pvector group_vector; @@ -239,7 +239,7 @@ output(ostream &out) const { * */ void PaletteGroups:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { // Sort the group names into order by name for output. pvector group_vector; group_vector.reserve(_groups.size()); diff --git a/pandatool/src/palettizer/paletteGroups.h b/pandatool/src/palettizer/paletteGroups.h index 2be2eb4602..9a2cdd2b52 100644 --- a/pandatool/src/palettizer/paletteGroups.h +++ b/pandatool/src/palettizer/paletteGroups.h @@ -60,8 +60,8 @@ public: iterator begin() const; iterator end() const; - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; private: void r_make_complete(Groups &result, PaletteGroup *group); @@ -103,7 +103,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const PaletteGroups &groups) { +INLINE std::ostream &operator << (std::ostream &out, const PaletteGroups &groups) { groups.output(out); return out; } diff --git a/pandatool/src/palettizer/paletteImage.cxx b/pandatool/src/palettizer/paletteImage.cxx index 9b664a159d..871b71ca40 100644 --- a/pandatool/src/palettizer/paletteImage.cxx +++ b/pandatool/src/palettizer/paletteImage.cxx @@ -130,7 +130,7 @@ fillin(DatagramIterator &scan) { */ PaletteImage:: PaletteImage() { - _page = (PalettePage *)NULL; + _page = nullptr; _index = 0; _new_image = false; _got_image = false; @@ -247,7 +247,7 @@ count_coverage() const { for (pi = _placements.begin(); pi != _placements.end(); ++pi) { TexturePlacement *placement = (*pi); TextureImage *texture = placement->get_texture(); - nassertr(texture != (TextureImage *)NULL, 0.0); + nassertr(texture != nullptr, 0.0); int orig_pixels = texture->get_x_size() * @@ -476,7 +476,7 @@ resize_swapped_image(int x_size, int y_size) { * indicated output stream, one per line. */ void PaletteImage:: -write_placements(ostream &out, int indent_level) const { +write_placements(std::ostream &out, int indent_level) const { Placements::const_iterator pi; for (pi = _placements.begin(); pi != _placements.end(); ++pi) { TexturePlacement *placement = (*pi); @@ -564,7 +564,7 @@ update_image(bool redo_all) { if (texture->is_texture_named()) { SourceTextureImage *source = texture->get_preferred_source(); - if (source != (SourceTextureImage *)NULL && + if (source != nullptr && source->get_filename().compare_timestamps(get_filename()) > 0) { // The source image is newer than the palette image; we need to // regenerate. @@ -581,7 +581,7 @@ update_image(bool redo_all) { if (swapTexture->is_texture_named()) { SourceTextureImage *sourceSwapTexture = swapTexture->get_preferred_source(); - if (sourceSwapTexture != (SourceTextureImage *)NULL && + if (sourceSwapTexture != nullptr && sourceSwapTexture->get_filename().compare_timestamps(get_filename()) > 0) { // The source image is newer than the palette image; we need to // regenerate. @@ -636,7 +636,7 @@ update_image(bool redo_all) { write(_image); - if (pal->_shadow_color_type != (PNMFileType *)NULL) { + if (pal->_shadow_color_type != nullptr) { _shadow_image.write(_image); } @@ -647,7 +647,7 @@ update_image(bool redo_all) { for (si = _swappedImages.begin(); si != _swappedImages.end(); ++si) { PaletteImage *swappedImage = (*si); swappedImage->write(swappedImage->_image); - if (pal->_shadow_color_type != (PNMFileType *)NULL) { + if (pal->_shadow_color_type != nullptr) { swappedImage->_shadow_image.write(swappedImage->_image); } swappedImage->release_image(); @@ -712,9 +712,9 @@ bool PaletteImage:: setup_filename() { // Build up the basename for the palette image, based on the supplied image // pattern. - _basename = string(); + _basename = std::string(); - string::iterator si = pal->_generated_image_pattern.begin(); + std::string::iterator si = pal->_generated_image_pattern.begin(); while (si != pal->_generated_image_pattern.end()) { if ((*si) == '%') { // Some keycode. @@ -794,13 +794,13 @@ find_hole(int &x, int &y, int x_size, int y_size) const { // Consider the spot at x, y. TexturePlacement *overlap = find_overlap(x, y, x_size, y_size); - if (overlap == (TexturePlacement *)NULL) { + if (overlap == nullptr) { // Hooray! return true; } next_x = overlap->get_placed_x() + overlap->get_placed_x_size(); - next_y = min(next_y, overlap->get_placed_y() + overlap->get_placed_y_size()); + next_y = std::min(next_y, overlap->get_placed_y() + overlap->get_placed_y_size()); nassertr(next_x > x, false); x = next_x; } @@ -831,7 +831,7 @@ find_overlap(int x, int y, int x_size, int y_size) const { } } - return (TexturePlacement *)NULL; + return nullptr; } /** @@ -845,7 +845,7 @@ get_image() { } if (!_new_image) { - if (pal->_shadow_color_type != (PNMFileType *)NULL) { + if (pal->_shadow_color_type != nullptr) { if (_shadow_image.get_filename().exists() && _shadow_image.read(_image)) { _got_image = true; return; @@ -891,7 +891,7 @@ get_swapped_image(int index) { } if (!_new_image) { - if (pal->_shadow_color_type != (PNMFileType *)NULL) { + if (pal->_shadow_color_type != nullptr) { if (_shadow_image.get_filename().exists() && _shadow_image.read(_image)) { _got_image = true; return; @@ -959,7 +959,7 @@ release_image() { void PaletteImage:: remove_image() { unlink(); - if (pal->_shadow_color_type != (PNMFileType *)NULL) { + if (pal->_shadow_color_type != nullptr) { _shadow_image.unlink(); } _new_image = true; @@ -1025,7 +1025,7 @@ complete_pointers(TypedWritable **p_list, BamReader *manager) { index++; } - if (p_list[index] != (TypedWritable *)NULL) { + if (p_list[index] != nullptr) { DCAST_INTO_R(_page, p_list[index], index); } index++; diff --git a/pandatool/src/palettizer/paletteImage.h b/pandatool/src/palettizer/paletteImage.h index 314942e8ab..60395fdc39 100644 --- a/pandatool/src/palettizer/paletteImage.h +++ b/pandatool/src/palettizer/paletteImage.h @@ -51,7 +51,7 @@ public: bool resize_image(int x_size, int y_size); void resize_swapped_image(int x_size, int y_size); - void write_placements(ostream &out, int indent_level = 0) const; + void write_placements(std::ostream &out, int indent_level = 0) const; void reset_image(); void setup_shadow_image(); void update_image(bool redo_all); @@ -96,7 +96,7 @@ private: PalettePage *_page; int _index; - string _basename; + std::string _basename; bool _new_image; bool _got_image; diff --git a/pandatool/src/palettizer/palettePage.cxx b/pandatool/src/palettizer/palettePage.cxx index 8c04405927..9bdc74c57e 100644 --- a/pandatool/src/palettizer/palettePage.cxx +++ b/pandatool/src/palettizer/palettePage.cxx @@ -32,7 +32,7 @@ TypeHandle PalettePage::_type_handle; */ PalettePage:: PalettePage() { - _group = (PaletteGroup *)NULL; + _group = nullptr; } /** @@ -141,7 +141,7 @@ unplace(TexturePlacement *placement) { * their textures, to the indicated output stream. */ void PalettePage:: -write_image_info(ostream &out, int indent_level) const { +write_image_info(std::ostream &out, int indent_level) const { Images::const_iterator ii; for (ii = _images.begin(); ii != _images.end(); ++ii) { PaletteImage *image = (*ii); @@ -248,7 +248,7 @@ int PalettePage:: complete_pointers(TypedWritable **p_list, BamReader *manager) { int pi = TypedWritable::complete_pointers(p_list, manager); - if (p_list[pi] != (TypedWritable *)NULL) { + if (p_list[pi] != nullptr) { DCAST_INTO_R(_group, p_list[pi], pi); } pi++; diff --git a/pandatool/src/palettizer/palettePage.h b/pandatool/src/palettizer/palettePage.h index 35a17841dd..91ba875219 100644 --- a/pandatool/src/palettizer/palettePage.h +++ b/pandatool/src/palettizer/palettePage.h @@ -45,7 +45,7 @@ public: void place(TexturePlacement *placement); void unplace(TexturePlacement *placement); - void write_image_info(ostream &out, int indent_level = 0) const; + void write_image_info(std::ostream &out, int indent_level = 0) const; void optimal_resize(); void reset_images(); void setup_shadow_images(); diff --git a/pandatool/src/palettizer/palettizer.cxx b/pandatool/src/palettizer/palettizer.cxx index 633647cb75..157c267730 100644 --- a/pandatool/src/palettizer/palettizer.cxx +++ b/pandatool/src/palettizer/palettizer.cxx @@ -29,7 +29,10 @@ #include "bamWriter.h" #include "indent.h" -Palettizer *pal = (Palettizer *)NULL; +using std::cout; +using std::string; + +Palettizer *pal = nullptr; // This number is written out as the first number to the pi file, to indicate // the version of egg-palettize that wrote it out. This allows us to easily @@ -60,7 +63,7 @@ int Palettizer::_read_pi_version = 0; TypeHandle Palettizer::_type_handle; -ostream &operator << (ostream &out, Palettizer::RemapUV remap) { +std::ostream &operator << (std::ostream &out, Palettizer::RemapUV remap) { switch (remap) { case Palettizer::RU_never: return out << "never"; @@ -116,9 +119,9 @@ Palettizer() { _aggressively_clean_mapdir = true; _force_power_2 = true; _color_type = PNMFileTypeRegistry::get_global_ptr()->get_type_from_extension("png"); - _alpha_type = (PNMFileType *)NULL; - _shadow_color_type = (PNMFileType *)NULL; - _shadow_alpha_type = (PNMFileType *)NULL; + _alpha_type = nullptr; + _shadow_color_type = nullptr; + _shadow_alpha_type = nullptr; _pal_x_size = _pal_y_size = 512; _background.set(0.0, 0.0, 0.0, 0.0); _cutout_mode = EggRenderMode::AM_dual; @@ -203,19 +206,19 @@ report_pi() const { << " remap UV's for characters: " << _remap_char_uv << "\n"; cout << " alpha cutouts: " << _cutout_mode << " " << _cutout_ratio << "\n"; - if (_color_type != (PNMFileType *)NULL) { + if (_color_type != nullptr) { cout << " generate image files of type: " << _color_type->get_suggested_extension(); - if (_alpha_type != (PNMFileType *)NULL) { + if (_alpha_type != nullptr) { cout << "," << _alpha_type->get_suggested_extension(); } cout << "\n"; } - if (_shadow_color_type != (PNMFileType *)NULL) { + if (_shadow_color_type != nullptr) { cout << " generate shadow palette files of type: " << _shadow_color_type->get_suggested_extension(); - if (_shadow_alpha_type != (PNMFileType *)NULL) { + if (_shadow_alpha_type != nullptr) { cout << "," << _shadow_alpha_type->get_suggested_extension(); } cout << "\n"; @@ -347,7 +350,7 @@ report_statistics() const { * files. */ void Palettizer:: -read_txa_file(istream &txa_file, const string &txa_filename) { +read_txa_file(std::istream &txa_file, const string &txa_filename) { // Clear out the group dependencies, in preparation for reading them again // from the .txa file. Groups::iterator gi; @@ -358,14 +361,14 @@ read_txa_file(istream &txa_file, const string &txa_filename) { } // Also reset _shadow_color_type. - _shadow_color_type = (PNMFileType *)NULL; - _shadow_alpha_type = (PNMFileType *)NULL; + _shadow_color_type = nullptr; + _shadow_alpha_type = nullptr; if (!_txa_file.read(txa_file, txa_filename)) { exit(1); } - if (_color_type == (PNMFileType *)NULL) { + if (_color_type == nullptr) { nout << "No valid output image file type available; cannot run.\n" << "Use :imagetype command in .txa file.\n"; exit(1); @@ -810,7 +813,7 @@ test_palette_group(const string &name) const { return (*gi).second; } - return (PaletteGroup *)NULL; + return nullptr; } /** @@ -890,7 +893,7 @@ string_remap(const string &str) { * texture placements, and reports this to the indicated output stream. */ void Palettizer:: -compute_statistics(ostream &out, int indent_level, +compute_statistics(std::ostream &out, int indent_level, const Palettizer::Placements &placements) const { TextureMemoryCounter counter; @@ -981,22 +984,22 @@ int Palettizer:: complete_pointers(TypedWritable **p_list, BamReader *manager) { int index = TypedWritable::complete_pointers(p_list, manager); - if (p_list[index] != (TypedWritable *)NULL) { + if (p_list[index] != nullptr) { DCAST_INTO_R(_color_type, p_list[index], index); } index++; - if (p_list[index] != (TypedWritable *)NULL) { + if (p_list[index] != nullptr) { DCAST_INTO_R(_alpha_type, p_list[index], index); } index++; - if (p_list[index] != (TypedWritable *)NULL) { + if (p_list[index] != nullptr) { DCAST_INTO_R(_shadow_color_type, p_list[index], index); } index++; - if (p_list[index] != (TypedWritable *)NULL) { + if (p_list[index] != nullptr) { DCAST_INTO_R(_shadow_alpha_type, p_list[index], index); } index++; @@ -1021,7 +1024,7 @@ complete_pointers(TypedWritable **p_list, BamReader *manager) { DCAST_INTO_R(texture, p_list[index], index); string name = downcase(texture->get_name()); - pair result = _textures.insert(Textures::value_type(name, texture)); + std::pair result = _textures.insert(Textures::value_type(name, texture)); if (!result.second) { // Two textures mapped to the same slot--probably a case error (since we // just changed this rule). diff --git a/pandatool/src/palettizer/palettizer.h b/pandatool/src/palettizer/palettizer.h index ad8c389df8..523968e952 100644 --- a/pandatool/src/palettizer/palettizer.h +++ b/pandatool/src/palettizer/palettizer.h @@ -47,7 +47,7 @@ public: void report_pi() const; void report_statistics() const; - void read_txa_file(istream &txa_file, const string &txa_filename); + void read_txa_file(std::istream &txa_file, const std::string &txa_filename); void all_params_set(); void process_command_line_eggs(bool force_texture_read, const Filename &state_filename); void process_all(bool force_texture_read, const Filename &state_filename); @@ -57,15 +57,15 @@ public: bool read_stale_eggs(bool redo_all); bool write_eggs(); - EggFile *get_egg_file(const string &name); - bool remove_egg_file(const string &name); + EggFile *get_egg_file(const std::string &name); + bool remove_egg_file(const std::string &name); void add_command_line_egg(EggFile *egg_file); - PaletteGroup *get_palette_group(const string &name); - PaletteGroup *test_palette_group(const string &name) const; + PaletteGroup *get_palette_group(const std::string &name); + PaletteGroup *test_palette_group(const std::string &name) const; PaletteGroup *get_default_group(); - TextureImage *get_texture(const string &name); + TextureImage *get_texture(const std::string &name); private: static const char *yesno(bool flag); @@ -82,22 +82,22 @@ public: RU_invalid }; - static RemapUV string_remap(const string &str); + static RemapUV string_remap(const std::string &str); bool _is_valid; // These values are not stored in the textures.boo file, but are specific to // each session. TxaFile _txa_file; - string _default_groupname; - string _default_groupdir; + std::string _default_groupname; + std::string _default_groupdir; bool _noabs; // The following parameter values specifically relate to textures and // palettes. These values are stored in the textures.boo file for future // reference. - string _generated_image_pattern; - string _map_dirname; + std::string _generated_image_pattern; + std::string _map_dirname; Filename _shadow_dirname; Filename _rel_dirname; int _pal_x_size, _pal_y_size; @@ -121,10 +121,10 @@ public: private: typedef pvector Placements; - void compute_statistics(ostream &out, int indent_level, + void compute_statistics(std::ostream &out, int indent_level, const Placements &placements) const; - typedef pmap EggFiles; + typedef pmap EggFiles; EggFiles _egg_files; typedef pvector CommandLineEggs; @@ -133,10 +133,10 @@ private: typedef pset CommandLineTextures; CommandLineTextures _command_line_textures; - typedef pmap Groups; + typedef pmap Groups; Groups _groups; - typedef pmap Textures; + typedef pmap Textures; Textures _textures; typedef pvector TextureConflicts; TextureConflicts _texture_conflicts; diff --git a/pandatool/src/palettizer/sourceTextureImage.cxx b/pandatool/src/palettizer/sourceTextureImage.cxx index df1afec310..aea0046ad1 100644 --- a/pandatool/src/palettizer/sourceTextureImage.cxx +++ b/pandatool/src/palettizer/sourceTextureImage.cxx @@ -28,7 +28,7 @@ TypeHandle SourceTextureImage::_type_handle; */ SourceTextureImage:: SourceTextureImage() { - _texture = (TextureImage *)NULL; + _texture = nullptr; _egg_count = 0; _read_header = false; diff --git a/pandatool/src/palettizer/sourceTextureImage.h b/pandatool/src/palettizer/sourceTextureImage.h index 09c1792222..1f1f64b9dc 100644 --- a/pandatool/src/palettizer/sourceTextureImage.h +++ b/pandatool/src/palettizer/sourceTextureImage.h @@ -76,8 +76,8 @@ private: static TypeHandle _type_handle; }; -INLINE ostream & -operator << (ostream &out, const SourceTextureImage &source) { +INLINE std::ostream & +operator << (std::ostream &out, const SourceTextureImage &source) { source.output_filename(out); return out; } diff --git a/pandatool/src/palettizer/textureImage.cxx b/pandatool/src/palettizer/textureImage.cxx index 54e213ed24..612aa5b3c6 100644 --- a/pandatool/src/palettizer/textureImage.cxx +++ b/pandatool/src/palettizer/textureImage.cxx @@ -31,6 +31,8 @@ #include +using std::string; + TypeHandle TextureImage::_type_handle; /** @@ -38,7 +40,7 @@ TypeHandle TextureImage::_type_handle; */ TextureImage:: TextureImage() { - _preferred_source = (SourceTextureImage *)NULL; + _preferred_source = nullptr; _read_source_image = false; _allow_release_source_image = true; _is_surprise = true; @@ -90,7 +92,7 @@ assign_groups() { if (_explicitly_assigned_groups.empty()) { // If we have no explicit group assignments, we must consider all the egg // files. - copy(_egg_files.begin(), _egg_files.end(), back_inserter(needed_eggs)); + std::copy(_egg_files.begin(), _egg_files.end(), std::back_inserter(needed_eggs)); } else { // Otherwise, we only need to consider the egg files that don't have any @@ -203,7 +205,7 @@ get_placement(PaletteGroup *group) const { Placement::const_iterator pi; pi = _placement.find(group); if (pi == _placement.end()) { - return (TexturePlacement *)NULL; + return nullptr; } return (*pi).second; @@ -267,7 +269,7 @@ pre_txa_file() { // Get our properties from the actual image for this texture. It's possible // the .txa file will update them further. SourceTextureImage *source = get_preferred_source(); - if (source != (SourceTextureImage *)NULL) { + if (source != nullptr) { _properties = source->get_properties(); } @@ -289,7 +291,7 @@ post_txa_file() { // First, get the actual size of the texture. SourceTextureImage *source = get_preferred_source(); - if (source != (SourceTextureImage *)NULL) { + if (source != nullptr) { if (source->get_size()) { _size_known = true; _x_size = source->get_x_size(); @@ -358,7 +360,7 @@ post_txa_file() { _properties._anisotropic_degree = _request._anisotropic_degree; - if (_properties._color_type == (PNMFileType *)NULL) { + if (_properties._color_type == nullptr) { _properties._color_type = _request._properties._color_type; _properties._alpha_type = _request._properties._alpha_type; } @@ -530,7 +532,7 @@ get_source(const Filename &filename, const Filename &alpha_filename, // Clear out the preferred source image to force us to rederive this next // time someone asks. - _preferred_source = (SourceTextureImage *)NULL; + _preferred_source = nullptr; _read_source_image = false; return source; @@ -543,7 +545,7 @@ get_source(const Filename &filename, const Filename &alpha_filename, */ SourceTextureImage *TextureImage:: get_preferred_source() { - if (_preferred_source != (SourceTextureImage *)NULL) { + if (_preferred_source != nullptr) { return _preferred_source; } @@ -569,7 +571,7 @@ get_preferred_source() { } } - SourceTextureImage *best = (SourceTextureImage *)NULL; + SourceTextureImage *best = nullptr; int best_size = 0; for (si = _sources.begin(); si != _sources.end(); ++si) { @@ -580,7 +582,7 @@ get_preferred_source() { if (source->exists() && source->get_size()) { int source_size = source->get_x_size() * source->get_y_size(); - if (best == (SourceTextureImage *)NULL) { + if (best == nullptr) { best = source; best_size = source_size; @@ -599,14 +601,14 @@ get_preferred_source() { } } - if (best == (SourceTextureImage *)NULL && !_sources.empty()) { + if (best == nullptr && !_sources.empty()) { // If we didn't pick any that pass, it must be that all of them are // unreadable. In this case, it really doesn't matter which one we pick, // but we should at least pick one that has an egg reference, if any of // them do. if (any_referenced) { for (si = _sources.begin(); - si != _sources.end() && best == (SourceTextureImage *)NULL; + si != _sources.end() && best == nullptr; ++si) { SourceTextureImage *source = (*si).second; if (source->get_egg_count() > 0) { @@ -661,7 +663,7 @@ copy_unplaced(bool redo_all) { Filename filename = dest->get_filename(); FilenameUnifier::make_canonical(filename); - pair insert_result = generate.insert + std::pair insert_result = generate.insert (Dests::value_type(filename, dest)); if (!insert_result.second) { // At least two DestTextureImages map to the same filename, no sweat. @@ -672,7 +674,7 @@ copy_unplaced(bool redo_all) { placement->set_dest(dest); } else { - placement->set_dest((DestTextureImage *)NULL); + placement->set_dest(nullptr); } } @@ -707,7 +709,7 @@ const PNMImage &TextureImage:: read_source_image() { if (!_read_source_image) { SourceTextureImage *source = get_preferred_source(); - if (source != (SourceTextureImage *)NULL) { + if (source != nullptr) { source->read(_source_image); } _read_source_image = true; @@ -752,7 +754,7 @@ void TextureImage:: read_header() { if (!_read_source_image) { SourceTextureImage *source = get_preferred_source(); - if (source != (SourceTextureImage *)NULL) { + if (source != nullptr) { source->read_header(); } } @@ -766,7 +768,7 @@ bool TextureImage:: is_newer_than(const Filename &reference_filename) { if (!_read_source_image) { SourceTextureImage *source = get_preferred_source(); - if (source != (SourceTextureImage *)NULL) { + if (source != nullptr) { const Filename &source_filename = source->get_filename(); return source_filename.compare_timestamps(reference_filename) >= 0; } @@ -780,7 +782,7 @@ is_newer_than(const Filename &reference_filename) { * to the indicated output stream, one per line. */ void TextureImage:: -write_source_pathnames(ostream &out, int indent_level) const { +write_source_pathnames(std::ostream &out, int indent_level) const { Sources::const_iterator si; for (si = _sources.begin(); si != _sources.end(); ++si) { SourceTextureImage *source = (*si).second; @@ -853,7 +855,7 @@ write_source_pathnames(ostream &out, int indent_level) const { * Writes the information about the texture's size and placement. */ void TextureImage:: -write_scale_info(ostream &out, int indent_level) { +write_scale_info(std::ostream &out, int indent_level) { SourceTextureImage *source = get_preferred_source(); indent(out, indent_level) << get_name(); @@ -874,7 +876,7 @@ write_scale_info(ostream &out, int indent_level) { out << " orig "; - if (source == (SourceTextureImage *)NULL || + if (source == nullptr || !source->is_size_known()) { out << "unknown"; } else { @@ -886,7 +888,7 @@ write_scale_info(ostream &out, int indent_level) { out << " new " << get_x_size() << " " << get_y_size() << " " << get_num_channels(); - if (source != (SourceTextureImage *)NULL && + if (source != nullptr && source->is_size_known()) { double scale = 100.0 * (((double)get_x_size() / (double)source->get_x_size()) + @@ -902,7 +904,7 @@ write_scale_info(ostream &out, int indent_level) { TexturePlacement *placement = (*pi).second; if (placement->get_omit_reason() == OR_none) { PaletteImage *image = placement->get_image(); - nassertv(image != (PaletteImage *)NULL); + nassertv(image != nullptr); indent(out, indent_level + 2) << "placed on " << FilenameUnifier::make_user_filename(image->get_filename()) @@ -914,7 +916,7 @@ write_scale_info(ostream &out, int indent_level) { } else { DestTextureImage *image = placement->get_dest(); - nassertv(image != (DestTextureImage *)NULL); + nassertv(image != nullptr); indent(out, indent_level + 2) << "copied to " << FilenameUnifier::make_user_filename(image->get_filename()); @@ -923,7 +925,7 @@ write_scale_info(ostream &out, int indent_level) { image->get_y_size() != get_y_size())) { out << " at size " << image->get_x_size() << " " << image->get_y_size(); - if (source != (SourceTextureImage *)NULL && + if (source != nullptr && source->is_size_known()) { double scale = 100.0 * (((double)image->get_x_size() / (double)source->get_x_size()) + diff --git a/pandatool/src/palettizer/textureImage.h b/pandatool/src/palettizer/textureImage.h index 4d9b1b84e9..1e590da621 100644 --- a/pandatool/src/palettizer/textureImage.h +++ b/pandatool/src/palettizer/textureImage.h @@ -88,14 +88,14 @@ public: void read_header(); bool is_newer_than(const Filename &reference_filename); - void write_source_pathnames(ostream &out, int indent_level = 0) const; - void write_scale_info(ostream &out, int indent_level = 0); + void write_source_pathnames(std::ostream &out, int indent_level = 0) const; + void write_scale_info(std::ostream &out, int indent_level = 0); private: typedef pset EggFiles; typedef pvector WorkingEggs; - typedef pmap Sources; - typedef pmap Dests; + typedef pmap Sources; + typedef pmap Dests; static int compute_egg_count(PaletteGroup *group, const WorkingEggs &egg_files); @@ -107,7 +107,7 @@ private: void remove_old_dests(const Dests &a, const Dests &b); void copy_new_dests(const Dests &a, const Dests &b); - string get_source_key(const Filename &filename, + std::string get_source_key(const Filename &filename, const Filename &alpha_filename, int alpha_file_channel); diff --git a/pandatool/src/palettizer/textureMemoryCounter.cxx b/pandatool/src/palettizer/textureMemoryCounter.cxx index 176461c832..91281670c6 100644 --- a/pandatool/src/palettizer/textureMemoryCounter.cxx +++ b/pandatool/src/palettizer/textureMemoryCounter.cxx @@ -53,11 +53,11 @@ reset() { void TextureMemoryCounter:: add_placement(TexturePlacement *placement) { TextureImage *texture = placement->get_texture(); - nassertv(texture != (TextureImage *)NULL); + nassertv(texture != nullptr); if (placement->get_omit_reason() == OR_none) { PaletteImage *image = placement->get_image(); - nassertv(image != (PaletteImage *)NULL); + nassertv(image != nullptr); add_palette(image); int bytes = count_bytes(image, placement->get_placed_x_size(), @@ -67,7 +67,7 @@ add_placement(TexturePlacement *placement) { } else { DestTextureImage *dest = placement->get_dest(); - if (dest != (DestTextureImage *)NULL) { + if (dest != nullptr) { int bytes = count_bytes(dest); add_texture(texture, bytes); @@ -81,7 +81,7 @@ add_placement(TexturePlacement *placement) { * Reports the measured texture memory usage. */ void TextureMemoryCounter:: -report(ostream &out, int indent_level) { +report(std::ostream &out, int indent_level) { indent(out, indent_level) << _num_placed << " of " << _num_textures << " textures appear on " << _num_palettes << " palette images with " << _num_unplaced @@ -120,8 +120,8 @@ report(ostream &out, int indent_level) { * Writes to the indicated ostream an indication of the fraction of the total * memory usage that is represented by fraction_bytes. */ -ostream &TextureMemoryCounter:: -format_memory_fraction(ostream &out, int fraction_bytes, int palette_bytes) { +std::ostream &TextureMemoryCounter:: +format_memory_fraction(std::ostream &out, int fraction_bytes, int palette_bytes) { out << floor(1000.0 * (double)fraction_bytes / (double)palette_bytes + 0.5) / 10.0 << "% (" << (fraction_bytes + 512) / 1024 << "k)"; return out; @@ -156,7 +156,7 @@ add_palette(PaletteImage *image) { */ void TextureMemoryCounter:: add_texture(TextureImage *texture, int bytes) { - pair result; + std::pair result; result = _textures.insert(Textures::value_type(texture, bytes)); if (result.second) { // If it was inserted, no problem--no duplicates. @@ -167,8 +167,8 @@ add_texture(TextureImage *texture, int bytes) { // If it was not inserted, we have a duplicate. Textures::iterator ti = result.first; - _duplicate_bytes += min(bytes, (*ti).second); - (*ti).second = max(bytes, (*ti).second); + _duplicate_bytes += std::min(bytes, (*ti).second); + (*ti).second = std::max(bytes, (*ti).second); } /** diff --git a/pandatool/src/palettizer/textureMemoryCounter.h b/pandatool/src/palettizer/textureMemoryCounter.h index 47d70db230..49de474732 100644 --- a/pandatool/src/palettizer/textureMemoryCounter.h +++ b/pandatool/src/palettizer/textureMemoryCounter.h @@ -37,10 +37,10 @@ public: void reset(); void add_placement(TexturePlacement *placement); - void report(ostream &out, int indent_level); + void report(std::ostream &out, int indent_level); private: - static ostream &format_memory_fraction(ostream &out, int fraction_bytes, + static std::ostream &format_memory_fraction(std::ostream &out, int fraction_bytes, int palette_bytes); void add_palette(PaletteImage *image); void add_texture(TextureImage *texture, int bytes); diff --git a/pandatool/src/palettizer/texturePlacement.cxx b/pandatool/src/palettizer/texturePlacement.cxx index 2cbea3019c..01f47b42a1 100644 --- a/pandatool/src/palettizer/texturePlacement.cxx +++ b/pandatool/src/palettizer/texturePlacement.cxx @@ -27,6 +27,9 @@ #include "bamWriter.h" #include "pnmImage.h" +using std::max; +using std::min; + TypeHandle TexturePlacement::_type_handle; /** @@ -34,10 +37,10 @@ TypeHandle TexturePlacement::_type_handle; */ TexturePlacement:: TexturePlacement() { - _texture = (TextureImage *)NULL; - _group = (PaletteGroup *)NULL; - _image = (PaletteImage *)NULL; - _dest = (DestTextureImage *)NULL; + _texture = nullptr; + _group = nullptr; + _image = nullptr; + _dest = nullptr; _has_uvs = false; _size_known = false; _is_filled = true; @@ -60,8 +63,8 @@ TexturePlacement(TextureImage *texture, PaletteGroup *group) : _omit_reason = OR_unknown; } - _image = (PaletteImage *)NULL; - _dest = (DestTextureImage *)NULL; + _image = nullptr; + _dest = nullptr; _has_uvs = false; _size_known = false; _is_filled = false; @@ -88,7 +91,7 @@ TexturePlacement:: /** * Returns the name of the texture that this placement represents. */ -const string &TexturePlacement:: +const std::string &TexturePlacement:: get_name() const { return _texture->get_name(); } @@ -443,7 +446,7 @@ get_uv_area() const { */ bool TexturePlacement:: is_placed() const { - return _image != (PaletteImage *)NULL; + return _image != nullptr; } /** @@ -451,7 +454,7 @@ is_placed() const { */ PaletteImage *TexturePlacement:: get_image() const { - nassertr(is_placed(), (PaletteImage *)NULL); + nassertr(is_placed(), nullptr); return _image; } @@ -460,7 +463,7 @@ get_image() const { */ PalettePage *TexturePlacement:: get_page() const { - nassertr(is_placed(), (PalettePage *)NULL); + nassertr(is_placed(), nullptr); return _image->get_page(); } @@ -540,9 +543,9 @@ place_at(PaletteImage *image, int x, int y) { */ void TexturePlacement:: force_replace() { - if (_image != (PaletteImage *)NULL) { + if (_image != nullptr) { _image->unplace(this); - _image = (PaletteImage *)NULL; + _image = nullptr; } if (_omit_reason == OR_none) { mark_eggs_stale(); @@ -640,7 +643,7 @@ compute_tex_matrix(LMatrix3d &transform) { * Writes the placement position information on a line by itself. */ void TexturePlacement:: -write_placed(ostream &out, int indent_level) { +write_placed(std::ostream &out, int indent_level) { indent(out, indent_level) << get_texture()->get_name(); @@ -1031,22 +1034,22 @@ int TexturePlacement:: complete_pointers(TypedWritable **p_list, BamReader *manager) { int index = TypedWritable::complete_pointers(p_list, manager); - if (p_list[index] != (TypedWritable *)NULL) { + if (p_list[index] != nullptr) { DCAST_INTO_R(_texture, p_list[index], index); } index++; - if (p_list[index] != (TypedWritable *)NULL) { + if (p_list[index] != nullptr) { DCAST_INTO_R(_group, p_list[index], index); } index++; - if (p_list[index] != (TypedWritable *)NULL) { + if (p_list[index] != nullptr) { DCAST_INTO_R(_image, p_list[index], index); } index++; - if (p_list[index] != (TypedWritable *)NULL) { + if (p_list[index] != nullptr) { DCAST_INTO_R(_dest, p_list[index], index); } index++; diff --git a/pandatool/src/palettizer/texturePlacement.h b/pandatool/src/palettizer/texturePlacement.h index be4d667a24..552f50f3d6 100644 --- a/pandatool/src/palettizer/texturePlacement.h +++ b/pandatool/src/palettizer/texturePlacement.h @@ -46,7 +46,7 @@ public: TexturePlacement(TextureImage *texture, PaletteGroup *group); ~TexturePlacement(); - const string &get_name() const; + const std::string &get_name() const; TextureImage *get_texture() const; const TextureProperties &get_properties() const; PaletteGroup *get_group() const; @@ -82,7 +82,7 @@ public: void compute_tex_matrix(LMatrix3d &transform); - void write_placed(ostream &out, int indent_level = 0); + void write_placed(std::ostream &out, int indent_level = 0); bool is_filled() const; void mark_unfilled(); @@ -127,7 +127,6 @@ private: // This value is only filled in while reading from the bam file; don't use // it otherwise. int _num_references; - int _margin_override; int _num_textureSwaps; public: diff --git a/pandatool/src/palettizer/textureProperties.cxx b/pandatool/src/palettizer/textureProperties.cxx index c8db745fc8..573dd784b3 100644 --- a/pandatool/src/palettizer/textureProperties.cxx +++ b/pandatool/src/palettizer/textureProperties.cxx @@ -20,6 +20,8 @@ #include "bamWriter.h" #include "string_utils.h" +using std::string; + TypeHandle TextureProperties::_type_handle; /** @@ -38,8 +40,8 @@ TextureProperties() { _magfilter = EggTexture::FT_unspecified; _quality_level = EggTexture::QL_unspecified; _anisotropic_degree = 0; - _color_type = (PNMFileType *)NULL; - _alpha_type = (PNMFileType *)NULL; + _color_type = nullptr; + _alpha_type = nullptr; } /** @@ -183,7 +185,7 @@ get_string() const { string result; if (_got_num_channels) { - ostringstream num; + std::ostringstream num; num << _effective_num_channels; result += num.str(); } @@ -222,7 +224,7 @@ update_properties(const TextureProperties &other) { _anisotropic_degree = other._anisotropic_degree; - if (_color_type == (PNMFileType *)NULL) { + if (_color_type == nullptr) { _color_type = other._color_type; _alpha_type = other._alpha_type; } @@ -445,7 +447,7 @@ fully_define() { break; } - if (_color_type == (PNMFileType *)NULL) { + if (_color_type == nullptr) { _color_type = pal->_color_type; _alpha_type = pal->_alpha_type; } @@ -501,7 +503,7 @@ operator < (const TextureProperties &other) const { if (_color_type != other._color_type) { return _color_type < other._color_type; } - if (_color_type != (PNMFileType *)NULL) { + if (_color_type != nullptr) { if (_alpha_type != other._alpha_type) { return _alpha_type < other._alpha_type; } @@ -520,7 +522,7 @@ operator == (const TextureProperties &other) const { _quality_level == other._quality_level && _anisotropic_degree == other._anisotropic_degree && _color_type == other._color_type && - (_color_type == (PNMFileType *)NULL || + (_color_type == nullptr || _alpha_type == other._alpha_type)); } @@ -670,10 +672,10 @@ get_quality_level_string(EggTexture::QualityLevel quality_level) { */ string TextureProperties:: get_type_string(PNMFileType *color_type, PNMFileType *alpha_type) { - if (color_type == (PNMFileType *)NULL) { + if (color_type == nullptr) { return ""; } - if (alpha_type == (PNMFileType *)NULL) { + if (alpha_type == nullptr) { return "c"; } return "a"; @@ -781,12 +783,12 @@ int TextureProperties:: complete_pointers(TypedWritable **p_list, BamReader *manager) { int index = TypedWritable::complete_pointers(p_list, manager); - if (p_list[index] != (TypedWritable *)NULL) { + if (p_list[index] != nullptr) { DCAST_INTO_R(_color_type, p_list[index], index); } index++; - if (p_list[index] != (TypedWritable *)NULL) { + if (p_list[index] != nullptr) { DCAST_INTO_R(_alpha_type, p_list[index], index); } index++; diff --git a/pandatool/src/palettizer/textureProperties.h b/pandatool/src/palettizer/textureProperties.h index cfd5fd36f8..5186f29308 100644 --- a/pandatool/src/palettizer/textureProperties.h +++ b/pandatool/src/palettizer/textureProperties.h @@ -42,7 +42,7 @@ public: void force_nonalpha(); bool uses_alpha() const; - string get_string() const; + std::string get_string() const; void update_properties(const TextureProperties &other); void fully_define(); @@ -64,11 +64,11 @@ public: PNMFileType *_alpha_type; private: - static string get_format_string(EggTexture::Format format); - static string get_filter_string(EggTexture::FilterType filter_type); - static string get_anisotropic_degree_string(int aniso_degree); - static string get_quality_level_string(EggTexture::QualityLevel quality_level); - static string get_type_string(PNMFileType *color_type, + static std::string get_format_string(EggTexture::Format format); + static std::string get_filter_string(EggTexture::FilterType filter_type); + static std::string get_anisotropic_degree_string(int aniso_degree); + static std::string get_quality_level_string(EggTexture::QualityLevel quality_level); + static std::string get_type_string(PNMFileType *color_type, PNMFileType *alpha_type); static EggTexture::Format union_format(EggTexture::Format a, diff --git a/pandatool/src/palettizer/textureReference.cxx b/pandatool/src/palettizer/textureReference.cxx index da6a2b626f..4a11b5348d 100644 --- a/pandatool/src/palettizer/textureReference.cxx +++ b/pandatool/src/palettizer/textureReference.cxx @@ -35,6 +35,10 @@ #include +using std::max; +using std::min; +using std::string; + TypeHandle TextureReference::_type_handle; /** @@ -42,12 +46,12 @@ TypeHandle TextureReference::_type_handle; */ TextureReference:: TextureReference() { - _egg_file = (EggFile *)NULL; - _egg_tex = (EggTexture *)NULL; + _egg_file = nullptr; + _egg_tex = nullptr; _tex_mat = LMatrix3d::ident_mat(); _inv_tex_mat = LMatrix3d::ident_mat(); - _source_texture = (SourceTextureImage *)NULL; - _placement = (TexturePlacement *)NULL; + _source_texture = nullptr; + _placement = nullptr; _uses_alpha = false; _any_uvs = false; _min_uv.set(0.0, 0.0); @@ -155,8 +159,8 @@ from_egg_quick(const TextureReference &other) { */ void TextureReference:: release_egg_data() { - _egg_tex = NULL; - _egg_data = NULL; + _egg_tex = nullptr; + _egg_data = nullptr; } /** @@ -192,7 +196,7 @@ get_source() const { */ TextureImage *TextureReference:: get_texture() const { - nassertr(_source_texture != (SourceTextureImage *)NULL, (TextureImage *)NULL); + nassertr(_source_texture != nullptr, nullptr); return _source_texture->get_texture(); } @@ -303,12 +307,12 @@ is_equivalent(const TextureReference &other) const { void TextureReference:: set_placement(TexturePlacement *placement) { if (_placement != placement) { - if (_placement != (TexturePlacement *)NULL) { + if (_placement != nullptr) { // Remove our reference from the old placement object. _placement->remove_egg(this); } _placement = placement; - if (_placement != (TexturePlacement *)NULL) { + if (_placement != nullptr) { // Add our reference to the new placement object. _placement->add_egg(this); } @@ -320,7 +324,7 @@ set_placement(TexturePlacement *placement) { */ void TextureReference:: clear_placement() { - set_placement((TexturePlacement *)NULL); + set_placement(nullptr); } /** @@ -338,7 +342,7 @@ get_placement() const { */ void TextureReference:: mark_egg_stale() { - if (_egg_file != (EggFile *)NULL) { + if (_egg_file != nullptr) { _egg_file->mark_stale(); } } @@ -349,12 +353,12 @@ mark_egg_stale() { */ void TextureReference:: update_egg() { - if (_egg_tex == (EggTexture *)NULL) { + if (_egg_tex == nullptr) { // Not much we can do if we don't have an actual egg file to reference. return; } - if (_placement == (TexturePlacement *)NULL) { + if (_placement == nullptr) { // Nor if we don't have an actual placement yet. This is possible if the // egg was assigned to the "null" group, and the texture hasn't been re- // assigned yet. @@ -362,7 +366,7 @@ update_egg() { } TextureImage *texture = get_texture(); - if (texture != (TextureImage *)NULL) { + if (texture != nullptr) { // Make sure the alpha mode is set according to what the texture image // wants. if (texture->has_num_channels() && @@ -406,7 +410,7 @@ update_egg() { // simply have to update the texture reference to the new texture // location. DestTextureImage *dest = _placement->get_dest(); - nassertv(dest != (DestTextureImage *)NULL); + nassertv(dest != nullptr); dest->update_egg_tex(_egg_tex); return; } @@ -415,7 +419,7 @@ update_egg() { // update the texture reference, but also adjust the UV's. In most cases, // we can do this by simply applying a texture matrix to the reference. PaletteImage *image = _placement->get_image(); - nassertv(image != (PaletteImage *)NULL); + nassertv(image != nullptr); image->update_egg_tex(_egg_tex); @@ -447,7 +451,7 @@ update_egg() { */ void TextureReference:: apply_properties_to_source() { - nassertv(_source_texture != (SourceTextureImage *)NULL); + nassertv(_source_texture != nullptr); _source_texture->update_properties(_properties); } @@ -455,7 +459,7 @@ apply_properties_to_source() { * */ void TextureReference:: -output(ostream &out) const { +output(std::ostream &out) const { out << *_source_texture; } @@ -463,7 +467,7 @@ output(ostream &out) const { * */ void TextureReference:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_texture()->get_name(); @@ -830,17 +834,17 @@ int TextureReference:: complete_pointers(TypedWritable **p_list, BamReader *manager) { int pi = TypedWritable::complete_pointers(p_list, manager); - if (p_list[pi] != (TypedWritable *)NULL) { + if (p_list[pi] != nullptr) { DCAST_INTO_R(_egg_file, p_list[pi], pi); } pi++; - if (p_list[pi] != (TypedWritable *)NULL) { + if (p_list[pi] != nullptr) { DCAST_INTO_R(_source_texture, p_list[pi], pi); } pi++; - if (p_list[pi] != (TypedWritable *)NULL) { + if (p_list[pi] != nullptr) { DCAST_INTO_R(_placement, p_list[pi], pi); } pi++; diff --git a/pandatool/src/palettizer/textureReference.h b/pandatool/src/palettizer/textureReference.h index aa555263b9..f17d8337b2 100644 --- a/pandatool/src/palettizer/textureReference.h +++ b/pandatool/src/palettizer/textureReference.h @@ -50,7 +50,7 @@ public: EggFile *get_egg_file() const; SourceTextureImage *get_source() const; TextureImage *get_texture() const; - const string &get_tref_name() const; + const std::string &get_tref_name() const; bool operator < (const TextureReference &other) const; @@ -71,8 +71,8 @@ public: void update_egg(); void apply_properties_to_source(); - void output(ostream &out) const; - void write(ostream &out, int indent_level = 0) const; + void output(std::ostream &out) const; + void write(std::ostream &out, int indent_level = 0) const; private: @@ -93,7 +93,7 @@ private: EggTexture *_egg_tex; EggData *_egg_data; - string _tref_name; + std::string _tref_name; LMatrix3d _tex_mat, _inv_tex_mat; SourceTextureImage *_source_texture; TexturePlacement *_placement; @@ -134,8 +134,8 @@ private: static TypeHandle _type_handle; }; -INLINE ostream & -operator << (ostream &out, const TextureReference &ref) { +INLINE std::ostream & +operator << (std::ostream &out, const TextureReference &ref) { ref.output(out); return out; } diff --git a/pandatool/src/palettizer/txaFile.cxx b/pandatool/src/palettizer/txaFile.cxx index 7aff6ad221..cb4cb5331d 100644 --- a/pandatool/src/palettizer/txaFile.cxx +++ b/pandatool/src/palettizer/txaFile.cxx @@ -20,6 +20,8 @@ #include "pnotify.h" #include "pnmFileTypeRegistry.h" +using std::string; + /** * */ @@ -32,7 +34,7 @@ TxaFile() { * there is an error. */ bool TxaFile:: -read(istream &in, const string &filename) { +read(std::istream &in, const string &filename) { string line; int line_number = 1; @@ -160,7 +162,7 @@ match_texture(TextureImage *texture) const { * output stream. This is primarily useful for debugging. */ void TxaFile:: -write(ostream &out) const { +write(std::ostream &out) const { Lines::const_iterator li; for (li = _lines.begin(); li != _lines.end(); ++li) { out << (*li) << "\n"; @@ -173,7 +175,7 @@ write(ostream &out) const { * line, or EOF if the end of file has been reached. */ int TxaFile:: -get_line_or_semicolon(istream &in, string &line) { +get_line_or_semicolon(std::istream &in, string &line) { line = string(); int ch = in.get(); char semicolon = ';'; diff --git a/pandatool/src/palettizer/txaFile.h b/pandatool/src/palettizer/txaFile.h index 507e0ac21a..05d0a32ae1 100644 --- a/pandatool/src/palettizer/txaFile.h +++ b/pandatool/src/palettizer/txaFile.h @@ -31,15 +31,15 @@ class TxaFile { public: TxaFile(); - bool read(istream &in, const string &filename); + bool read(std::istream &in, const std::string &filename); bool match_egg(EggFile *egg_file) const; bool match_texture(TextureImage *texture) const; - void write(ostream &out) const; + void write(std::ostream &out) const; private: - static int get_line_or_semicolon(istream &in, string &line); + static int get_line_or_semicolon(std::istream &in, std::string &line); bool parse_group_line(const vector_string &words); bool parse_palette_line(const vector_string &words); diff --git a/pandatool/src/palettizer/txaLine.cxx b/pandatool/src/palettizer/txaLine.cxx index 0d1c655658..41f9349c51 100644 --- a/pandatool/src/palettizer/txaLine.cxx +++ b/pandatool/src/palettizer/txaLine.cxx @@ -22,6 +22,8 @@ #include "pnotify.h" #include "pnmFileType.h" +using std::string; + /** * */ @@ -45,8 +47,8 @@ TxaLine() { _margin = 0; _got_coverage_threshold = false; _coverage_threshold = 0.0; - _color_type = (PNMFileType *)NULL; - _alpha_type = (PNMFileType *)NULL; + _color_type = nullptr; + _alpha_type = nullptr; } /** @@ -259,7 +261,7 @@ parse(const string &line) { } else { // Maybe it's a group name. PaletteGroup *group = pal->test_palette_group(word); - if (group != (PaletteGroup *)NULL) { + if (group != nullptr) { _palette_groups.insert(group); } else { @@ -283,7 +285,7 @@ parse(const string &line) { _quality_level = ql; } else if (word.length() > 2 && word[word.length() - 2] == '_' && - strchr("uv", word[word.length() - 1]) != NULL) { + strchr("uv", word[word.length() - 1]) != nullptr) { // It must be a wrap mode for u or v. string prefix = word.substr(0, word.length() - 2); EggTexture::WrapMode wm = EggTexture::string_wrap_mode(prefix); @@ -408,10 +410,10 @@ match_texture(TextureImage *texture) const { break; case ST_scale: - if (source != (SourceTextureImage *)NULL && source->get_size()) { + if (source != nullptr && source->get_size()) { request._got_size = true; - request._x_size = max(1, (int)(source->get_x_size() * _scale / 100.0)); - request._y_size = max(1, (int)(source->get_y_size() * _scale / 100.0)); + request._x_size = std::max(1, (int)(source->get_x_size() * _scale / 100.0)); + request._y_size = std::max(1, (int)(source->get_y_size() * _scale / 100.0)); } break; @@ -436,7 +438,7 @@ match_texture(TextureImage *texture) const { request._coverage_threshold = _coverage_threshold; } - if (_color_type != (PNMFileType *)NULL) { + if (_color_type != nullptr) { request._properties._color_type = _color_type; request._properties._alpha_type = _alpha_type; } @@ -523,7 +525,7 @@ match_texture(TextureImage *texture) const { * */ void TxaLine:: -output(ostream &out) const { +output(std::ostream &out) const { Patterns::const_iterator pi; for (pi = _texture_patterns.begin(); pi != _texture_patterns.end(); ++pi) { out << (*pi) << " "; @@ -599,9 +601,9 @@ output(ostream &out) const { } } - if (_color_type != (PNMFileType *)NULL) { + if (_color_type != nullptr) { out << " " << _color_type->get_suggested_extension(); - if (_alpha_type != (PNMFileType *)NULL) { + if (_alpha_type != nullptr) { out << "," << _alpha_type->get_suggested_extension(); } } diff --git a/pandatool/src/palettizer/txaLine.h b/pandatool/src/palettizer/txaLine.h index 98166f0bec..b0fe5e2c06 100644 --- a/pandatool/src/palettizer/txaLine.h +++ b/pandatool/src/palettizer/txaLine.h @@ -37,12 +37,12 @@ class TxaLine { public: TxaLine(); - bool parse(const string &line); + bool parse(const std::string &line); bool match_egg(EggFile *egg_file) const; bool match_texture(TextureImage *texture) const; - void output(ostream &out) const; + void output(std::ostream &out) const; private: typedef pvector Patterns; @@ -93,7 +93,7 @@ private: PNMFileType *_alpha_type; }; -INLINE ostream &operator << (ostream &out, const TxaLine &line) { +INLINE std::ostream &operator << (std::ostream &out, const TxaLine &line) { line.output(out); return out; } diff --git a/pandatool/src/pandatoolbase/animationConvert.cxx b/pandatool/src/pandatoolbase/animationConvert.cxx index 6403da48cd..d09ce0f19f 100644 --- a/pandatool/src/pandatoolbase/animationConvert.cxx +++ b/pandatool/src/pandatoolbase/animationConvert.cxx @@ -19,7 +19,7 @@ /** * Returns the string corresponding to this method. */ -string +std::string format_animation_convert(AnimationConvert convert) { switch (convert) { case AC_invalid: @@ -53,8 +53,8 @@ format_animation_convert(AnimationConvert convert) { /** * */ -ostream & -operator << (ostream &out, AnimationConvert convert) { +std::ostream & +operator << (std::ostream &out, AnimationConvert convert) { return out << format_animation_convert(convert); } @@ -63,7 +63,7 @@ operator << (ostream &out, AnimationConvert convert) { * AnimationConvert types. Returns AC_invalid if the string is unknown. */ AnimationConvert -string_animation_convert(const string &str) { +string_animation_convert(const std::string &str) { if (cmp_nocase(str, "none") == 0) { return AC_none; diff --git a/pandatool/src/pandatoolbase/animationConvert.h b/pandatool/src/pandatoolbase/animationConvert.h index b5d9ec9cda..2365cfff1e 100644 --- a/pandatool/src/pandatoolbase/animationConvert.h +++ b/pandatool/src/pandatoolbase/animationConvert.h @@ -31,9 +31,9 @@ enum AnimationConvert { AC_both, // A character model and tables in the same file. }; -string format_animation_convert(AnimationConvert unit); +std::string format_animation_convert(AnimationConvert unit); -ostream &operator << (ostream &out, AnimationConvert unit); -AnimationConvert string_animation_convert(const string &str); +std::ostream &operator << (std::ostream &out, AnimationConvert unit); +AnimationConvert string_animation_convert(const std::string &str); #endif diff --git a/pandatool/src/pandatoolbase/distanceUnit.cxx b/pandatool/src/pandatoolbase/distanceUnit.cxx index d2479de244..8ee495be3c 100644 --- a/pandatool/src/pandatoolbase/distanceUnit.cxx +++ b/pandatool/src/pandatoolbase/distanceUnit.cxx @@ -16,6 +16,10 @@ #include "string_utils.h" #include "pnotify.h" +using std::istream; +using std::ostream; +using std::string; + /** * Returns the string representing the common abbreviation for the given unit. */ diff --git a/pandatool/src/pandatoolbase/distanceUnit.h b/pandatool/src/pandatoolbase/distanceUnit.h index 4e82b74335..2030ae09e0 100644 --- a/pandatool/src/pandatoolbase/distanceUnit.h +++ b/pandatool/src/pandatoolbase/distanceUnit.h @@ -33,12 +33,12 @@ enum DistanceUnit { DU_invalid }; -string format_abbrev_unit(DistanceUnit unit); -string format_long_unit(DistanceUnit unit); +std::string format_abbrev_unit(DistanceUnit unit); +std::string format_long_unit(DistanceUnit unit); -ostream &operator << (ostream &out, DistanceUnit unit); -istream &operator >> (istream &in, DistanceUnit &unit); -DistanceUnit string_distance_unit(const string &str); +std::ostream &operator << (std::ostream &out, DistanceUnit unit); +std::istream &operator >> (std::istream &in, DistanceUnit &unit); +DistanceUnit string_distance_unit(const std::string &str); double convert_units(DistanceUnit from, DistanceUnit to); diff --git a/pandatool/src/pandatoolbase/pathReplace.I b/pandatool/src/pandatoolbase/pathReplace.I index a2fde11ad8..282c37d306 100644 --- a/pandatool/src/pandatoolbase/pathReplace.I +++ b/pandatool/src/pandatoolbase/pathReplace.I @@ -44,7 +44,7 @@ clear() { * orig_prefix, that prefix will be replaced with replacement_prefix. */ INLINE void PathReplace:: -add_pattern(const string &orig_prefix, const string &replacement_prefix) { +add_pattern(const std::string &orig_prefix, const std::string &replacement_prefix) { _entries.push_back(Entry(orig_prefix, replacement_prefix)); } @@ -59,7 +59,7 @@ get_num_patterns() const { /** * Returns the original prefix associated with the nth pattern. */ -INLINE const string &PathReplace:: +INLINE const std::string &PathReplace:: get_orig_prefix(int n) const { nassertr(n >= 0 && n < (int)_entries.size(), _entries[0]._orig_prefix); return _entries[n]._orig_prefix; @@ -68,7 +68,7 @@ get_orig_prefix(int n) const { /** * Returns the replacement prefix associated with the nth pattern. */ -INLINE const string &PathReplace:: +INLINE const std::string &PathReplace:: get_replacement_prefix(int n) const { nassertr(n >= 0 && n < (int)_entries.size(), _entries[0]._replacement_prefix); return _entries[n]._replacement_prefix; @@ -98,7 +98,7 @@ convert_path(const Filename &orig_filename, const DSearchPath &additional_path) * */ INLINE PathReplace::Component:: -Component(const string &component) : +Component(const std::string &component) : _orig_prefix(component), _double_star(component == "**") { diff --git a/pandatool/src/pandatoolbase/pathReplace.cxx b/pandatool/src/pandatoolbase/pathReplace.cxx index c3891cf047..b3b6bcb498 100644 --- a/pandatool/src/pandatoolbase/pathReplace.cxx +++ b/pandatool/src/pandatoolbase/pathReplace.cxx @@ -354,7 +354,7 @@ full_convert_path(const Filename &orig_filename, * */ void PathReplace:: -write(ostream &out, int indent_level) const { +write(std::ostream &out, int indent_level) const { Entries::const_iterator ei; for (ei = _entries.begin(); ei != _entries.end(); ++ei) { indent(out, indent_level) @@ -451,7 +451,7 @@ copy_this_file(Filename &filename) { * */ PathReplace::Entry:: -Entry(const string &orig_prefix, const string &replacement_prefix) : +Entry(const std::string &orig_prefix, const std::string &replacement_prefix) : _orig_prefix(orig_prefix), _replacement_prefix(replacement_prefix) { @@ -495,7 +495,7 @@ try_match(const Filename &filename, Filename &new_filename) const { } // We found a match. Construct the replacement string. - string result = _replacement_prefix; + std::string result = _replacement_prefix; while (mi < components.size()) { if (!result.empty()) { result += '/'; diff --git a/pandatool/src/pandatoolbase/pathReplace.h b/pandatool/src/pandatoolbase/pathReplace.h index a0ec064acd..edc69abc08 100644 --- a/pandatool/src/pandatoolbase/pathReplace.h +++ b/pandatool/src/pandatoolbase/pathReplace.h @@ -42,11 +42,11 @@ public: INLINE bool had_error() const; INLINE void clear(); - INLINE void add_pattern(const string &orig_prefix, const string &replacement_prefix); + INLINE void add_pattern(const std::string &orig_prefix, const std::string &replacement_prefix); INLINE int get_num_patterns() const; - INLINE const string &get_orig_prefix(int n) const; - INLINE const string &get_replacement_prefix(int n) const; + INLINE const std::string &get_orig_prefix(int n) const; + INLINE const std::string &get_replacement_prefix(int n) const; INLINE bool is_empty() const; @@ -62,7 +62,7 @@ public: Filename &resolved_path, Filename &output_path); - void write(ostream &out, int indent_level = 0) const; + void write(std::ostream &out, int indent_level = 0) const; public: // This is used (along with _entries) to support match_path(). @@ -88,7 +88,7 @@ private: class Component { public: - INLINE Component(const string &component); + INLINE Component(const std::string &component); INLINE Component(const Component ©); INLINE void operator = (const Component ©); @@ -99,17 +99,17 @@ private: class Entry { public: - Entry(const string &orig_prefix, const string &replacement_prefix); + Entry(const std::string &orig_prefix, const std::string &replacement_prefix); INLINE Entry(const Entry ©); INLINE void operator = (const Entry ©); bool try_match(const Filename &filename, Filename &new_filename) const; size_t r_try_match(const vector_string &components, size_t oi, size_t ci) const; - string _orig_prefix; + std::string _orig_prefix; Components _orig_components; bool _is_local; - string _replacement_prefix; + std::string _replacement_prefix; }; typedef pvector Entries; diff --git a/pandatool/src/pandatoolbase/pathStore.cxx b/pandatool/src/pandatoolbase/pathStore.cxx index d40fe3f276..dffacfe678 100644 --- a/pandatool/src/pandatoolbase/pathStore.cxx +++ b/pandatool/src/pandatoolbase/pathStore.cxx @@ -19,7 +19,7 @@ /** * Returns the string corresponding to this method. */ -string +std::string format_path_store(PathStore store) { switch (store) { case PS_invalid: @@ -47,8 +47,8 @@ format_path_store(PathStore store) { /** * */ -ostream & -operator << (ostream &out, PathStore store) { +std::ostream & +operator << (std::ostream &out, PathStore store) { return out << format_path_store(store); } @@ -57,7 +57,7 @@ operator << (ostream &out, PathStore store) { * PathStore types. Returns PS_invalid if the string is unknown. */ PathStore -string_path_store(const string &str) { +string_path_store(const std::string &str) { if (cmp_nocase(str, "relative") == 0 || cmp_nocase(str, "rel") == 0) { return PS_relative; diff --git a/pandatool/src/pandatoolbase/pathStore.h b/pandatool/src/pandatoolbase/pathStore.h index 7c15515038..30440b70a7 100644 --- a/pandatool/src/pandatoolbase/pathStore.h +++ b/pandatool/src/pandatoolbase/pathStore.h @@ -29,9 +29,9 @@ enum PathStore { PS_keep, // Don't change the filename at all. }; -string format_path_store(PathStore unit); +std::string format_path_store(PathStore unit); -ostream &operator << (ostream &out, PathStore unit); -PathStore string_path_store(const string &str); +std::ostream &operator << (std::ostream &out, PathStore unit); +PathStore string_path_store(const std::string &str); #endif diff --git a/pandatool/src/pfmprogs/pfmBba.cxx b/pandatool/src/pfmprogs/pfmBba.cxx index 5456efad27..ce0851a47f 100644 --- a/pandatool/src/pfmprogs/pfmBba.cxx +++ b/pandatool/src/pfmprogs/pfmBba.cxx @@ -73,11 +73,11 @@ process_pfm(const Filename &input_filename, PfmFile &file) { if (!bba_filename.empty()) { bba_filename.set_text(); PT(BoundingHexahedron) bounds = file.compute_planar_bounds(LPoint2f(0.5, 0.5), pfm_bba_dist[0], pfm_bba_dist[1], false); - nassertr(bounds != (BoundingHexahedron *)NULL, false); + nassertr(bounds != nullptr, false); pofstream out; if (!bba_filename.open_write(out)) { - cerr << "Unable to open " << bba_filename << "\n"; + std::cerr << "Unable to open " << bba_filename << "\n"; return false; } diff --git a/pandatool/src/pfmprogs/pfmBba.h b/pandatool/src/pfmprogs/pfmBba.h index 518f5568d2..4d01ca647d 100644 --- a/pandatool/src/pfmprogs/pfmBba.h +++ b/pandatool/src/pfmprogs/pfmBba.h @@ -43,7 +43,6 @@ private: bool _got_zero_special; bool _got_output_filename; Filename _output_filename; - int _reorder_index; }; #endif diff --git a/pandatool/src/pfmprogs/pfmTrans.cxx b/pandatool/src/pfmprogs/pfmTrans.cxx index 123b098768..ffb99b2472 100644 --- a/pandatool/src/pfmprogs/pfmTrans.cxx +++ b/pandatool/src/pfmprogs/pfmTrans.cxx @@ -21,6 +21,8 @@ #include "string_utils.h" #include "pandaFileStream.h" +using std::string; + /** * */ @@ -72,7 +74,7 @@ PfmTrans() { ("rotate", "degrees", 0, "Rotates the pfm file the specified number of degrees counterclockwise, " "which must be a multiple of 90.", - &PfmTrans::dispatch_int, NULL, &_rotate); + &PfmTrans::dispatch_int, nullptr, &_rotate); add_option ("mirror_x", "", 0, @@ -231,7 +233,7 @@ process_pfm(const Filename &input_filename, PfmFile &file) { NodePath mesh = vizzer.generate_vis_mesh(PfmVizzer::MF_both); if (_got_vistex_filename) { PT(Texture) tex = TexturePool::load_texture(_vistex_filename); - if (tex == NULL) { + if (tex == nullptr) { nout << "Couldn't find " << _vistex_filename << "\n"; } else { tex->set_minfilter(SamplerState::FT_linear_mipmap_linear); diff --git a/pandatool/src/pfmprogs/pfmTrans.h b/pandatool/src/pfmprogs/pfmTrans.h index c36a6b975d..7d79127724 100644 --- a/pandatool/src/pfmprogs/pfmTrans.h +++ b/pandatool/src/pfmprogs/pfmTrans.h @@ -38,12 +38,12 @@ public: protected: virtual bool handle_args(Args &args); - static bool dispatch_scale(const string &opt, const string &arg, void *var); - static bool dispatch_rotate_xyz(ProgramBase *self, const string &opt, const string &arg, void *var); - bool ns_dispatch_rotate_xyz(const string &opt, const string &arg, void *var); - static bool dispatch_rotate_axis(ProgramBase *self, const string &opt, const string &arg, void *var); - bool ns_dispatch_rotate_axis(const string &opt, const string &arg, void *var); - static bool dispatch_translate(const string &opt, const string &arg, void *var); + static bool dispatch_scale(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_rotate_xyz(ProgramBase *self, const std::string &opt, const std::string &arg, void *var); + bool ns_dispatch_rotate_xyz(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_rotate_axis(ProgramBase *self, const std::string &opt, const std::string &arg, void *var); + bool ns_dispatch_rotate_axis(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_translate(const std::string &opt, const std::string &arg, void *var); private: typedef pvector Filenames; diff --git a/pandatool/src/progbase/programBase.I b/pandatool/src/progbase/programBase.I index 698efedfdf..960bad09f2 100644 --- a/pandatool/src/progbase/programBase.I +++ b/pandatool/src/progbase/programBase.I @@ -15,6 +15,6 @@ * Formats the indicated text to stderr with the known _terminal_width. */ INLINE void ProgramBase:: -show_text(const string &text) { +show_text(const std::string &text) { show_text("", 0, text); } diff --git a/pandatool/src/progbase/programBase.cxx b/pandatool/src/progbase/programBase.cxx index 86a2c17c48..9cdb70263d 100644 --- a/pandatool/src/progbase/programBase.cxx +++ b/pandatool/src/progbase/programBase.cxx @@ -45,6 +45,12 @@ #endif // TIOCGWINSZ #endif // IOCTL_TERMINAL_WIDTH +using std::cerr; +using std::cout; +using std::max; +using std::min; +using std::string; + bool ProgramBase::SortOptionsByIndex:: operator () (const Option *a, const Option *b) const { if (a->_index_group != b->_index_group) { @@ -57,7 +63,7 @@ operator () (const Option *a, const Option *b) const { // properly flushed before we exit, if someone calls exit(). It's probably // not necessary, but why not be phobic about it? static void flush_nout() { - nout << flush; + nout << std::flush; } static ConfigVariableInt default_terminal_width @@ -101,7 +107,7 @@ ProgramBase(const string &name) : _name(name) { add_option("h", "", 100, "Display this help page.", - &ProgramBase::handle_help_option, NULL, (void *)this); + &ProgramBase::handle_help_option, nullptr, (void *)this); // It's nice to start with a blank line. nout << "\r"; @@ -114,7 +120,7 @@ ProgramBase:: ~ProgramBase() { // Reset Notify in case any messages get sent after our destruction--our // stream is no longer valid. - Notify::ptr()->set_ostream_ptr(NULL, false); + Notify::ptr()->set_ostream_ptr(nullptr, false); } /** @@ -181,7 +187,7 @@ show_text(const string &prefix, int indent_width, string text) { * This is useful when creating a man page for this utility. */ void ProgramBase:: -write_man_page(ostream &out) { +write_man_page(std::ostream &out) { string prog = _program_name.get_basename_wo_extension(); out << ".\\\" Automatically generated by " << prog << " -write-man\n"; @@ -196,11 +202,11 @@ write_man_page(ostream &out) { // Generate a date string for inclusion into the footer. char date_str[256]; date_str[0] = 0; - time_t current_time = time(NULL); + time_t current_time = time(nullptr); if (current_time != (time_t) -1) { tm *today = localtime(¤t_time); - if (today == NULL || 0 == strftime(date_str, 256, "%d %B %Y", today)) { + if (today == nullptr || 0 == strftime(date_str, 256, "%d %B %Y", today)) { date_str[0] = 0; } } @@ -296,7 +302,7 @@ parse_command_line(int argc, char **argv) { write_man_page(cout); } else { - pofstream man_out(argv[2], ios::out | ios::trunc); + pofstream man_out(argv[2], std::ios::out | std::ios::trunc); if (!man_out) { cerr << "Failed to open output file " << argv[2] << "!\n"; } @@ -353,7 +359,7 @@ parse_command_line(int argc, char **argv) { gopt.name = (char *)opt._option.c_str(); gopt.has_arg = (opt._parm_name.empty()) ? no_argument : required_argument; - gopt.flag = (int *)NULL; + gopt.flag = nullptr; // Return an index into the _options_by_index array, offset by 256 so we // don't confuse it with '?'. @@ -379,10 +385,10 @@ parse_command_line(int argc, char **argv) { const struct option *long_opts = &long_options[0]; int flag = - getopt_long_only(argc, argv, short_options.c_str(), long_opts, NULL); + getopt_long_only(argc, argv, short_options.c_str(), long_opts, nullptr); while (flag != EOF) { string arg; - if (optarg != NULL) { + if (optarg != nullptr) { arg = optarg; } @@ -410,13 +416,13 @@ parse_command_line(int argc, char **argv) { const Option &opt = *(*ii).second; bool okflag = true; - if (opt._option_function != (OptionDispatchFunction)NULL) { + if (opt._option_function != (OptionDispatchFunction)nullptr) { okflag = (*opt._option_function)(opt._option, arg, opt._option_data); } - if (opt._option_method != (OptionDispatchMethod)NULL) { + if (opt._option_method != (OptionDispatchMethod)nullptr) { okflag = (*opt._option_method)(this, opt._option, arg, opt._option_data); } - if (opt._bool_var != (bool *)NULL) { + if (opt._bool_var != nullptr) { (*opt._bool_var) = true; } @@ -428,7 +434,7 @@ parse_command_line(int argc, char **argv) { } flag = - getopt_long_only(argc, argv, short_options.c_str(), long_opts, NULL); + getopt_long_only(argc, argv, short_options.c_str(), long_opts, nullptr); } if (!handle_args(remaining_args)) { @@ -609,14 +615,14 @@ add_option(const string &option, const string &parm_name, opt._sequence = ++_next_sequence; opt._description = description; opt._option_function = option_function; - opt._option_method = (OptionDispatchMethod)NULL; + opt._option_method = (OptionDispatchMethod)nullptr; opt._bool_var = bool_var; opt._option_data = option_data; _options_by_name[option] = opt; _sorted_options = false; - if (bool_var != (bool *)NULL) { + if (bool_var != nullptr) { (*bool_var) = false; } } @@ -644,7 +650,7 @@ add_option(const string &option, const string &parm_name, opt._index_group = index_group; opt._sequence = ++_next_sequence; opt._description = description; - opt._option_function = (OptionDispatchFunction)NULL; + opt._option_function = (OptionDispatchFunction)nullptr; opt._option_method = option_method; opt._bool_var = bool_var; opt._option_data = option_data; @@ -652,7 +658,7 @@ add_option(const string &option, const string &parm_name, _options_by_name[option] = opt; _sorted_options = false; - if (bool_var != (bool *)NULL) { + if (bool_var != nullptr) { (*bool_var) = false; } } @@ -712,7 +718,7 @@ add_path_replace_options() { "against each specified method, in the order in which they appear in " "the command line, until the file is found. If the file is not found, " "the last matching prefix is used anyway.", - &ProgramBase::dispatch_path_replace, NULL, _path_replace.p()); + &ProgramBase::dispatch_path_replace, nullptr, _path_replace.p()); add_option ("pp", "dirname", 40, @@ -721,7 +727,7 @@ add_path_replace_options() { "only for relative paths, or for paths that are made relative by a " "-pr replacement string that doesn't begin with a leading slash. " "The model-path is always implicitly searched anyway.", - &ProgramBase::dispatch_search_path, NULL, &(_path_replace->_path)); + &ProgramBase::dispatch_search_path, nullptr, &(_path_replace->_path)); } /** @@ -1194,7 +1200,7 @@ dispatch_image_type(const string &opt, const string &arg, void *var) { (*ip) = reg->get_type_from_extension(arg); - if ((*ip) == (PNMFileType *)NULL) { + if ((*ip) == nullptr) { nout << "Invalid image type for -" << opt << ": " << arg << "\n" << "The following image types are known:\n"; reg->write(nout, 2); @@ -1277,7 +1283,7 @@ handle_help_option(const string &, const string &, void *data) { * doubled newlines. */ void ProgramBase:: -format_text(ostream &out, bool &last_newline, +format_text(std::ostream &out, bool &last_newline, const string &prefix, int indent_width, const string &text, int line_width) { indent_width = min(indent_width, line_width - 20); diff --git a/pandatool/src/progbase/programBase.h b/pandatool/src/progbase/programBase.h index e6b166172c..d3d06eb67a 100644 --- a/pandatool/src/progbase/programBase.h +++ b/pandatool/src/progbase/programBase.h @@ -33,82 +33,82 @@ */ class ProgramBase { public: - ProgramBase(const string &name = string()); + ProgramBase(const std::string &name = std::string()); virtual ~ProgramBase(); void show_description(); void show_usage(); void show_options(); - INLINE void show_text(const string &text); - void show_text(const string &prefix, int indent_width, string text); + INLINE void show_text(const std::string &text); + void show_text(const std::string &prefix, int indent_width, std::string text); - void write_man_page(ostream &out); + void write_man_page(std::ostream &out); virtual void parse_command_line(int argc, char **argv); - string get_exec_command() const; + std::string get_exec_command() const; - typedef pdeque Args; + typedef pdeque Args; Filename _program_name; Args _program_args; protected: - typedef bool (*OptionDispatchFunction)(const string &opt, const string &parm, void *data); - typedef bool (*OptionDispatchMethod)(ProgramBase *self, const string &opt, const string &parm, void *data); + typedef bool (*OptionDispatchFunction)(const std::string &opt, const std::string &parm, void *data); + typedef bool (*OptionDispatchMethod)(ProgramBase *self, const std::string &opt, const std::string &parm, void *data); virtual bool handle_args(Args &args); virtual bool post_command_line(); - void set_program_brief(const string &brief); - void set_program_description(const string &description); + void set_program_brief(const std::string &brief); + void set_program_description(const std::string &description); void clear_runlines(); - void add_runline(const string &runline); + void add_runline(const std::string &runline); void clear_options(); - void add_option(const string &option, const string &parm_name, - int index_group, const string &description, + void add_option(const std::string &option, const std::string &parm_name, + int index_group, const std::string &description, OptionDispatchFunction option_function, - bool *bool_var = (bool *)NULL, - void *option_data = (void *)NULL); - void add_option(const string &option, const string &parm_name, - int index_group, const string &description, + bool *bool_var = nullptr, + void *option_data = nullptr); + void add_option(const std::string &option, const std::string &parm_name, + int index_group, const std::string &description, OptionDispatchMethod option_method, - bool *bool_var = (bool *)NULL, - void *option_data = (void *)NULL); - bool redescribe_option(const string &option, const string &description); - bool remove_option(const string &option); + bool *bool_var = nullptr, + void *option_data = nullptr); + bool redescribe_option(const std::string &option, const std::string &description); + bool remove_option(const std::string &option); void add_path_replace_options(); void add_path_store_options(); - static bool dispatch_none(const string &opt, const string &arg, void *); - static bool dispatch_true(const string &opt, const string &arg, void *var); - static bool dispatch_false(const string &opt, const string &arg, void *var); - static bool dispatch_count(const string &opt, const string &arg, void *var); - static bool dispatch_int(const string &opt, const string &arg, void *var); - static bool dispatch_int_pair(const string &opt, const string &arg, void *var); - static bool dispatch_int_quad(const string &opt, const string &arg, void *var); - static bool dispatch_double(const string &opt, const string &arg, void *var); - static bool dispatch_double_pair(const string &opt, const string &arg, void *var); - static bool dispatch_double_triple(const string &opt, const string &arg, void *var); - static bool dispatch_double_quad(const string &opt, const string &arg, void *var); - static bool dispatch_color(const string &opt, const string &arg, void *var); - static bool dispatch_string(const string &opt, const string &arg, void *var); - static bool dispatch_vector_string(const string &opt, const string &arg, void *var); - static bool dispatch_vector_string_comma(const string &opt, const string &arg, void *var); - static bool dispatch_filename(const string &opt, const string &arg, void *var); - static bool dispatch_search_path(const string &opt, const string &arg, void *var); - static bool dispatch_coordinate_system(const string &opt, const string &arg, void *var); - static bool dispatch_units(const string &opt, const string &arg, void *var); - static bool dispatch_image_type(const string &opt, const string &arg, void *var); - static bool dispatch_path_replace(const string &opt, const string &arg, void *var); - static bool dispatch_path_store(const string &opt, const string &arg, void *var); + static bool dispatch_none(const std::string &opt, const std::string &arg, void *); + static bool dispatch_true(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_false(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_count(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_int(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_int_pair(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_int_quad(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_double(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_double_pair(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_double_triple(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_double_quad(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_color(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_string(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_vector_string(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_vector_string_comma(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_filename(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_search_path(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_coordinate_system(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_units(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_image_type(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_path_replace(const std::string &opt, const std::string &arg, void *var); + static bool dispatch_path_store(const std::string &opt, const std::string &arg, void *var); - static bool handle_help_option(const string &opt, const string &arg, void *); + static bool handle_help_option(const std::string &opt, const std::string &arg, void *); - static void format_text(ostream &out, bool &last_newline, - const string &prefix, int indent_width, - const string &text, int line_width); + static void format_text(std::ostream &out, bool &last_newline, + const std::string &prefix, int indent_width, + const std::string &text, int line_width); PT(PathReplace) _path_replace; bool _got_path_store; @@ -121,11 +121,11 @@ private: class Option { public: - string _option; - string _parm_name; + std::string _option; + std::string _parm_name; int _index_group; int _sequence; - string _description; + std::string _description; OptionDispatchFunction _option_function; OptionDispatchMethod _option_method; bool *_bool_var; @@ -137,20 +137,20 @@ private: bool operator () (const Option *a, const Option *b) const; }; - string _name; - string _brief; - string _description; + std::string _name; + std::string _brief; + std::string _description; typedef vector_string Runlines; Runlines _runlines; - typedef pmap OptionsByName; + typedef pmap OptionsByName; typedef pvector OptionsByIndex; OptionsByName _options_by_name; OptionsByIndex _options_by_index; int _next_sequence; bool _sorted_options; - typedef pmap GotOptions; + typedef pmap GotOptions; GotOptions _got_options; bool _last_newline; diff --git a/pandatool/src/progbase/test_prog.cxx b/pandatool/src/progbase/test_prog.cxx index 5123385cc5..289b68c8d7 100644 --- a/pandatool/src/progbase/test_prog.cxx +++ b/pandatool/src/progbase/test_prog.cxx @@ -46,13 +46,13 @@ TestProgram() { add_option ("b", "", 90, "Test option b", - &TestProgram::dispatch_count, NULL, &_count_b); + &TestProgram::dispatch_count, nullptr, &_count_b); _count_b = 0; add_option ("c", "integer_parameter", 90, "This is test option 'c'. It takes an integer parameter.", - &TestProgram::dispatch_int, NULL, &_int_c); + &TestProgram::dispatch_int, nullptr, &_int_c); _int_c = 0; } diff --git a/pandatool/src/progbase/withOutputFile.cxx b/pandatool/src/progbase/withOutputFile.cxx index 7ff8ea60d9..04e5005f0e 100644 --- a/pandatool/src/progbase/withOutputFile.cxx +++ b/pandatool/src/progbase/withOutputFile.cxx @@ -27,7 +27,7 @@ WithOutputFile(bool allow_last_param, bool allow_stdout, _allow_stdout = allow_stdout; _binary_output = binary_output; _got_output_filename = false; - _output_ptr = (ostream *)NULL; + _output_ptr = nullptr; _owns_output_ptr = false; } @@ -46,16 +46,16 @@ WithOutputFile:: * Returns an output stream that corresponds to the user's intended egg file * output--either stdout, or the named output file. */ -ostream &WithOutputFile:: +std::ostream &WithOutputFile:: get_output() { - if (_output_ptr == (ostream *)NULL) { + if (_output_ptr == nullptr) { if (!_got_output_filename) { // No filename given; use standard output. if (!_allow_stdout) { nout << "No output filename specified.\n"; exit(1); } - _output_ptr = &cout; + _output_ptr = &std::cout; _owns_output_ptr = false; } else { @@ -108,7 +108,7 @@ close_output() { delete _output_ptr; _owns_output_ptr = false; } - _output_ptr = NULL; + _output_ptr = nullptr; _output_stream.close(); } diff --git a/pandatool/src/progbase/withOutputFile.h b/pandatool/src/progbase/withOutputFile.h index d77627ffa7..385114c001 100644 --- a/pandatool/src/progbase/withOutputFile.h +++ b/pandatool/src/progbase/withOutputFile.h @@ -32,7 +32,7 @@ public: bool binary_output); virtual ~WithOutputFile(); - ostream &get_output(); + std::ostream &get_output(); void close_output(); bool has_output_filename() const; Filename get_output_filename() const; @@ -47,13 +47,13 @@ protected: bool _allow_last_param; bool _allow_stdout; bool _binary_output; - string _preferred_extension; + std::string _preferred_extension; bool _got_output_filename; Filename _output_filename; private: - ofstream _output_stream; - ostream *_output_ptr; + std::ofstream _output_stream; + std::ostream *_output_ptr; bool _owns_output_ptr; }; diff --git a/pandatool/src/progbase/wordWrapStream.cxx b/pandatool/src/progbase/wordWrapStream.cxx index a3ac50b99b..cd069d1eaa 100644 --- a/pandatool/src/progbase/wordWrapStream.cxx +++ b/pandatool/src/progbase/wordWrapStream.cxx @@ -19,7 +19,7 @@ */ WordWrapStream:: WordWrapStream(ProgramBase *program) : - ostream(&_lsb), + std::ostream(&_lsb), _lsb(this, program) { } diff --git a/pandatool/src/progbase/wordWrapStream.h b/pandatool/src/progbase/wordWrapStream.h index af5c2f90ab..cfa7969df1 100644 --- a/pandatool/src/progbase/wordWrapStream.h +++ b/pandatool/src/progbase/wordWrapStream.h @@ -27,7 +27,7 @@ * WordWrapStream indicates a paragraph break, and is generally printed as a * blank line. To force a line break without a paragraph break, use '\r'. */ -class WordWrapStream : public ostream { +class WordWrapStream : public std::ostream { public: WordWrapStream(ProgramBase *program); diff --git a/pandatool/src/progbase/wordWrapStreamBuf.cxx b/pandatool/src/progbase/wordWrapStreamBuf.cxx index 4280a3d394..0e0c4abbcb 100644 --- a/pandatool/src/progbase/wordWrapStreamBuf.cxx +++ b/pandatool/src/progbase/wordWrapStreamBuf.cxx @@ -17,11 +17,6 @@ #include "pnotify.h" -#ifndef HAVE_STREAMSIZE -// Some compilers--notably SGI--don't define this for us. -typedef int streamsize; -#endif - /** * */ @@ -47,7 +42,7 @@ WordWrapStreamBuf:: */ int WordWrapStreamBuf:: sync() { - streamsize n = pptr() - pbase(); + std::streamsize n = pptr() - pbase(); write_chars(pbase(), n); // Send all the data out now. @@ -62,7 +57,7 @@ sync() { */ int WordWrapStreamBuf:: overflow(int ch) { - streamsize n = pptr() - pbase(); + std::streamsize n = pptr() - pbase(); if (n != 0 && sync() != 0) { return EOF; @@ -86,10 +81,10 @@ void WordWrapStreamBuf:: write_chars(const char *start, int length) { if (length > 0) { set_literal_mode((_owner->flags() & Notify::get_literal_flag()) != 0); - string new_data(start, length); + std::string new_data(start, length); size_t newline = new_data.find_first_of("\n\r"); size_t p = 0; - while (newline != string::npos) { + while (newline != std::string::npos) { // The new data contains a newline; flush our data to that point. _data += new_data.substr(p, newline - p + 1); flush_data(); @@ -110,7 +105,7 @@ void WordWrapStreamBuf:: flush_data() { if (!_data.empty()) { if (_literal_mode) { - cerr << _data; + std::cerr << _data; } else { _program->show_text(_data); } diff --git a/pandatool/src/progbase/wordWrapStreamBuf.h b/pandatool/src/progbase/wordWrapStreamBuf.h index 506f72a6ea..0bc54b01f2 100644 --- a/pandatool/src/progbase/wordWrapStreamBuf.h +++ b/pandatool/src/progbase/wordWrapStreamBuf.h @@ -25,7 +25,7 @@ class WordWrapStream; * Used by WordWrapStream to implement an ostream that flushes its output to * ProgramBase::show_text(). */ -class WordWrapStreamBuf : public streambuf { +class WordWrapStreamBuf : public std::streambuf { public: WordWrapStreamBuf(WordWrapStream *owner, ProgramBase *program); virtual ~WordWrapStreamBuf(); @@ -39,7 +39,7 @@ private: INLINE void set_literal_mode(bool mode); void flush_data(); - string _data; + std::string _data; WordWrapStream *_owner; ProgramBase *_program; bool _literal_mode; diff --git a/pandatool/src/pstatserver/pStatClientData.cxx b/pandatool/src/pstatserver/pStatClientData.cxx index 4a3520b63f..26e06f069c 100644 --- a/pandatool/src/pstatserver/pStatClientData.cxx +++ b/pandatool/src/pstatserver/pStatClientData.cxx @@ -16,6 +16,8 @@ #include "pStatCollectorDef.h" +using std::string; + PStatCollectorDef PStatClientData::_null_collector(-1, "Unknown"); @@ -55,9 +57,9 @@ is_alive() const { */ void PStatClientData:: close() { - if (_is_alive && _reader != (PStatReader *)NULL) { + if (_is_alive && _reader != nullptr) { _reader->close(); - _reader = (PStatReader *)NULL; + _reader = nullptr; _is_alive = false; } } @@ -78,7 +80,7 @@ get_num_collectors() const { bool PStatClientData:: has_collector(int index) const { return (index >= 0 && index < (int)_collectors.size() && - _collectors[index]._def != (PStatCollectorDef *)NULL); + _collectors[index]._def != nullptr); } /** @@ -144,7 +146,7 @@ set_collector_has_level(int index, int thread_index, bool flag) { // ancestors. if (flag) { PStatCollectorDef *def = _collectors[index]._def; - if (def != (PStatCollectorDef *)NULL && def->_parent_index != 0) { + if (def != nullptr && def->_parent_index != 0) { if (set_collector_has_level(def->_parent_index, thread_index, flag)) { any_changed = true; } @@ -222,7 +224,7 @@ get_thread_name(int index) const { const PStatThreadData *PStatClientData:: get_thread_data(int index) const { ((PStatClientData *)this)->define_thread(index); - nassertr(index >= 0 && index < (int)_threads.size(), NULL); + nassertr(index >= 0 && index < (int)_threads.size(), nullptr); return _threads[index]._data; } @@ -261,7 +263,7 @@ add_collector(PStatCollectorDef *def) { slot_collector(def->_index); nassertv(def->_index >= 0 && def->_index < (int)_collectors.size()); - if (_collectors[def->_index]._def != (PStatCollectorDef *)NULL) { + if (_collectors[def->_index]._def != nullptr) { // Free the old definition, if any. delete _collectors[def->_index]._def; } @@ -330,7 +332,7 @@ slot_collector(int collector_index) { while ((int)_collectors.size() <= collector_index) { Collector collector; - collector._def = (PStatCollectorDef *)NULL; + collector._def = nullptr; _collectors.push_back(collector); } } @@ -345,7 +347,7 @@ update_toplevel_collectors() { Collectors::const_iterator ci; for (ci = _collectors.begin(); ci != _collectors.end(); ++ci) { PStatCollectorDef *def = (*ci)._def; - if (def != (PStatCollectorDef *)NULL && def->_parent_index == 0) { + if (def != nullptr && def->_parent_index == 0) { _toplevel_collectors.push_back(def->_index); } } diff --git a/pandatool/src/pstatserver/pStatClientData.h b/pandatool/src/pstatserver/pStatClientData.h index 2d4ab293d5..051bb568ae 100644 --- a/pandatool/src/pstatserver/pStatClientData.h +++ b/pandatool/src/pstatserver/pStatClientData.h @@ -44,8 +44,8 @@ public: int get_num_collectors() const; bool has_collector(int index) const; const PStatCollectorDef &get_collector_def(int index) const; - string get_collector_name(int index) const; - string get_collector_fullname(int index) const; + std::string get_collector_name(int index) const; + std::string get_collector_fullname(int index) const; bool set_collector_has_level(int index, int thread_index, bool flag); bool get_collector_has_level(int index, int thread_index) const; @@ -54,14 +54,14 @@ public: int get_num_threads() const; bool has_thread(int index) const; - string get_thread_name(int index) const; + std::string get_thread_name(int index) const; const PStatThreadData *get_thread_data(int index) const; int get_child_distance(int parent, int child) const; void add_collector(PStatCollectorDef *def); - void define_thread(int thread_index, const string &name = string()); + void define_thread(int thread_index, const std::string &name = std::string()); void record_new_frame(int thread_index, int frame_number, PStatFrameData *frame_data); @@ -87,7 +87,7 @@ private: class Thread { public: - string _name; + std::string _name; PT(PStatThreadData) _data; }; typedef pvector Threads; diff --git a/pandatool/src/pstatserver/pStatGraph.I b/pandatool/src/pstatserver/pStatGraph.I index b198296fd7..3bda0cedee 100644 --- a/pandatool/src/pstatserver/pStatGraph.I +++ b/pandatool/src/pstatserver/pStatGraph.I @@ -39,9 +39,9 @@ get_label_collector(int n) const { /** * Returns the text associated with the nth label. */ -INLINE string PStatGraph:: +INLINE std::string PStatGraph:: get_label_name(int n) const { - nassertr(n >= 0 && n < (int)_labels.size(), string()); + nassertr(n >= 0 && n < (int)_labels.size(), std::string()); return _monitor->get_client_data()->get_collector_name(_labels[n]); } @@ -117,7 +117,7 @@ get_guide_bar_units() const { * is set to GBU_named | GBU_show_units. */ INLINE void PStatGraph:: -set_guide_bar_unit_name(const string &unit_name) { +set_guide_bar_unit_name(const std::string &unit_name) { _unit_name = unit_name; } @@ -125,7 +125,7 @@ set_guide_bar_unit_name(const string &unit_name) { * Returns the name of the units to be used for the guide bars if the units * type is set to GBU_named | GBU_show_units. */ -INLINE const string &PStatGraph:: +INLINE const std::string &PStatGraph:: get_guide_bar_unit_name() const { return _unit_name; } diff --git a/pandatool/src/pstatserver/pStatGraph.cxx b/pandatool/src/pstatserver/pStatGraph.cxx index f65dafbc3b..88130ff7ab 100644 --- a/pandatool/src/pstatserver/pStatGraph.cxx +++ b/pandatool/src/pstatserver/pStatGraph.cxx @@ -20,6 +20,8 @@ #include // for sprintf +using std::string; + /** * */ diff --git a/pandatool/src/pstatserver/pStatGraph.h b/pandatool/src/pstatserver/pStatGraph.h index b7d907f52b..5b8a2d664e 100644 --- a/pandatool/src/pstatserver/pStatGraph.h +++ b/pandatool/src/pstatserver/pStatGraph.h @@ -39,7 +39,7 @@ public: INLINE int get_num_labels() const; INLINE int get_label_collector(int n) const; - INLINE string get_label_name(int n) const; + INLINE std::string get_label_name(int n) const; INLINE LRGBColor get_label_color(int n) const; INLINE void set_target_frame_rate(double frame_rate); @@ -56,11 +56,11 @@ public: class GuideBar { public: - GuideBar(double height, const string &label, GuideBarStyle style); + GuideBar(double height, const std::string &label, GuideBarStyle style); GuideBar(const GuideBar ©); double _height; - string _label; + std::string _label; GuideBarStyle _style; }; @@ -83,12 +83,12 @@ public: INLINE void set_guide_bar_units(int unit_mask); INLINE int get_guide_bar_units() const; - INLINE void set_guide_bar_unit_name(const string &unit_name); - INLINE const string &get_guide_bar_unit_name() const; + INLINE void set_guide_bar_unit_name(const std::string &unit_name); + INLINE const std::string &get_guide_bar_unit_name() const; - static string format_number(double value); - static string format_number(double value, int guide_bar_units, - const string &unit_name = string()); + static std::string format_number(double value); + static std::string format_number(double value, int guide_bar_units, + const std::string &unit_name = std::string()); protected: virtual void normal_guide_bars()=0; @@ -113,7 +113,7 @@ protected: typedef pvector GuideBars; GuideBars _guide_bars; int _guide_bar_units; - string _unit_name; + std::string _unit_name; }; #include "pStatGraph.I" diff --git a/pandatool/src/pstatserver/pStatListener.cxx b/pandatool/src/pstatserver/pStatListener.cxx index 417ad5495d..73fe3d3b04 100644 --- a/pandatool/src/pstatserver/pStatListener.cxx +++ b/pandatool/src/pstatserver/pStatListener.cxx @@ -34,7 +34,7 @@ connection_opened(const PT(Connection) &, const NetAddress &address, const PT(Connection) &new_connection) { PStatMonitor *monitor = _manager->make_monitor(); - if (monitor == (PStatMonitor *)NULL) { + if (monitor == nullptr) { nout << "Couldn't create monitor!\n"; return; } diff --git a/pandatool/src/pstatserver/pStatMonitor.I b/pandatool/src/pstatserver/pStatMonitor.I index 2b23d43a43..761b7b9a79 100644 --- a/pandatool/src/pstatserver/pStatMonitor.I +++ b/pandatool/src/pstatserver/pStatMonitor.I @@ -30,7 +30,7 @@ get_client_data() const { /** * Returns the name of the indicated collector, if it is known. */ -INLINE string PStatMonitor:: +INLINE std::string PStatMonitor:: get_collector_name(int collector_index) { if (!_client_data.is_null() && _client_data->has_collector(collector_index)) { @@ -54,7 +54,7 @@ is_client_known() const { * thereafter when we receive the client's "hello" message. See * is_client_known(). */ -INLINE string PStatMonitor:: +INLINE std::string PStatMonitor:: get_client_hostname() const { return _client_hostname; } @@ -65,7 +65,7 @@ get_client_hostname() const { * shortly thereafter when we receive the client's "hello" message. See * is_client_known(). */ -INLINE string PStatMonitor:: +INLINE std::string PStatMonitor:: get_client_progname() const { return _client_progname; } diff --git a/pandatool/src/pstatserver/pStatMonitor.cxx b/pandatool/src/pstatserver/pStatMonitor.cxx index f7e70727fe..09e22b093a 100644 --- a/pandatool/src/pstatserver/pStatMonitor.cxx +++ b/pandatool/src/pstatserver/pStatMonitor.cxx @@ -15,6 +15,8 @@ #include "pStatCollectorDef.h" +using std::string; + /** * diff --git a/pandatool/src/pstatserver/pStatMonitor.h b/pandatool/src/pstatserver/pStatMonitor.h index cd4a012069..f7e92073c4 100644 --- a/pandatool/src/pstatserver/pStatMonitor.h +++ b/pandatool/src/pstatserver/pStatMonitor.h @@ -43,8 +43,8 @@ public: PStatMonitor(PStatServer *server); virtual ~PStatMonitor(); - void hello_from(const string &hostname, const string &progname); - void bad_version(const string &hostname, const string &progname, + void hello_from(const std::string &hostname, const std::string &progname); + void bad_version(const std::string &hostname, const std::string &progname, int client_major, int client_minor, int server_major, int server_minor); void set_client_data(PStatClientData *client_data); @@ -57,12 +57,12 @@ public: INLINE PStatServer *get_server(); INLINE const PStatClientData *get_client_data() const; - INLINE string get_collector_name(int collector_index); + INLINE std::string get_collector_name(int collector_index); const LRGBColor &get_collector_color(int collector_index); INLINE bool is_client_known() const; - INLINE string get_client_hostname() const; - INLINE string get_client_progname() const; + INLINE std::string get_client_hostname() const; + INLINE std::string get_client_progname() const; PStatView &get_view(int thread_index); PStatView &get_level_view(int collector_index, int thread_index); @@ -71,7 +71,7 @@ public: // The following virtual methods may be overridden by a derived monitor // class to customize behavior. - virtual string get_monitor_name()=0; + virtual std::string get_monitor_name()=0; virtual void initialized(); virtual void got_hello(); @@ -96,8 +96,8 @@ private: PT(PStatClientData) _client_data; bool _client_known; - string _client_hostname; - string _client_progname; + std::string _client_hostname; + std::string _client_progname; typedef pmap Views; Views _views; diff --git a/pandatool/src/pstatserver/pStatReader.cxx b/pandatool/src/pstatserver/pStatReader.cxx index 7dbab59e74..02b01f26a2 100644 --- a/pandatool/src/pstatserver/pStatReader.cxx +++ b/pandatool/src/pstatserver/pStatReader.cxx @@ -123,7 +123,7 @@ get_monitor() { /** * Returns the current machine's hostname. */ -string PStatReader:: +std::string PStatReader:: get_hostname() { if (_hostname.empty()) { _hostname = ConnectionManager::get_host_name(); @@ -217,7 +217,7 @@ handle_client_control_message(const PStatClientControlMessage &message) { { for (int i = 0; i < (int)message._names.size(); i++) { int thread_index = message._first_thread_index + i; - string name = message._names[i]; + std::string name = message._names[i]; _client_data->define_thread(thread_index, name); _monitor->new_thread(thread_index); } @@ -272,7 +272,7 @@ void PStatReader:: dequeue_frame_data() { while (!_queued_frame_data.empty()) { const FrameData &data = _queued_frame_data.front(); - nassertv(_client_data != (PStatClientData *)NULL); + nassertv(_client_data != nullptr); // Check to see if any new collectors have level data. int num_levels = data._frame_data->get_num_levels(); diff --git a/pandatool/src/pstatserver/pStatReader.h b/pandatool/src/pstatserver/pStatReader.h index 4f30fd93cd..40d1d9b5e0 100644 --- a/pandatool/src/pstatserver/pStatReader.h +++ b/pandatool/src/pstatserver/pStatReader.h @@ -52,7 +52,7 @@ public: PStatMonitor *get_monitor(); private: - string get_hostname(); + std::string get_hostname(); void send_hello(); virtual void receive_datagram(const NetDatagram &datagram); @@ -72,7 +72,7 @@ private: PT(PStatClientData) _client_data; - string _hostname; + std::string _hostname; class FrameData { public: diff --git a/pandatool/src/pstatserver/pStatServer.cxx b/pandatool/src/pstatserver/pStatServer.cxx index 1e295ee4f9..23a6a62fda 100644 --- a/pandatool/src/pstatserver/pStatServer.cxx +++ b/pandatool/src/pstatserver/pStatServer.cxx @@ -122,7 +122,7 @@ poll() { */ void PStatServer:: main_loop(bool *interrupt_flag) { - while (interrupt_flag == (bool *)NULL || !*interrupt_flag) { + while (interrupt_flag == nullptr || !*interrupt_flag) { poll(); Thread::sleep(0.1); } diff --git a/pandatool/src/pstatserver/pStatServer.h b/pandatool/src/pstatserver/pStatServer.h index dca7ec2008..50128e4069 100644 --- a/pandatool/src/pstatserver/pStatServer.h +++ b/pandatool/src/pstatserver/pStatServer.h @@ -41,7 +41,7 @@ public: bool listen(int port = -1); void poll(); - void main_loop(bool *interrupt_flag = NULL); + void main_loop(bool *interrupt_flag = nullptr); virtual PStatMonitor *make_monitor()=0; void add_reader(Connection *connection, PStatReader *reader); diff --git a/pandatool/src/pstatserver/pStatStripChart.cxx b/pandatool/src/pstatserver/pStatStripChart.cxx index 9b64abaa02..c9ffcb3109 100644 --- a/pandatool/src/pstatserver/pStatStripChart.cxx +++ b/pandatool/src/pstatserver/pStatStripChart.cxx @@ -22,6 +22,9 @@ #include +using std::max; +using std::min; + /** * */ @@ -248,9 +251,9 @@ get_collector_under_pixel(int xpoint, int ypoint) { /** * Returns the text suitable for the title label on the top line. */ -string PStatStripChart:: +std::string PStatStripChart:: get_title_text() { - string text; + std::string text; _title_unknown = false; diff --git a/pandatool/src/pstatserver/pStatStripChart.h b/pandatool/src/pstatserver/pStatStripChart.h index 6cfe896bf2..5cba0164e2 100644 --- a/pandatool/src/pstatserver/pStatStripChart.h +++ b/pandatool/src/pstatserver/pStatStripChart.h @@ -68,7 +68,7 @@ public: INLINE int height_to_pixel(double value) const; INLINE double pixel_to_height(int y) const; - string get_title_text(); + std::string get_title_text(); bool is_title_unknown() const; protected: diff --git a/pandatool/src/pstatserver/pStatThreadData.cxx b/pandatool/src/pstatserver/pStatThreadData.cxx index fd5e3f411b..bef18c8a24 100644 --- a/pandatool/src/pstatserver/pStatThreadData.cxx +++ b/pandatool/src/pstatserver/pStatThreadData.cxx @@ -75,7 +75,7 @@ has_frame(int frame_number) const { int rel_frame = frame_number - _first_frame_number; return (rel_frame >= 0 && rel_frame < (int)_frames.size() && - _frames[rel_frame] != (PStatFrameData *)NULL); + _frames[rel_frame] != nullptr); } /** @@ -91,21 +91,21 @@ get_frame(int frame_number) const { rel_frame = num_frames - 1; } - while (rel_frame >= 0 && _frames[rel_frame] == (PStatFrameData *)NULL) { + while (rel_frame >= 0 && _frames[rel_frame] == nullptr) { rel_frame--; } if (rel_frame < 0) { // No frame data that old. Return the oldest frame we've got. rel_frame = 0; while (rel_frame < num_frames && - _frames[rel_frame] == (PStatFrameData *)NULL) { + _frames[rel_frame] == nullptr) { rel_frame++; } } if (rel_frame >= 0 && rel_frame < num_frames) { PStatFrameData *frame = _frames[rel_frame]; - nassertr(frame != (PStatFrameData *)NULL, _null_frame); + nassertr(frame != nullptr, _null_frame); nassertr(frame->get_start() >= 0.0, _null_frame); return *frame; } @@ -154,14 +154,14 @@ int PStatThreadData:: get_frame_number_at_time(double time, int hint) const { hint -= _first_frame_number; if (hint >= 0 && hint < (int)_frames.size()) { - if (_frames[hint] != (PStatFrameData *)NULL && + if (_frames[hint] != nullptr && _frames[hint]->get_start() <= time) { // The hint might be right. Scan forward from there. int i = hint + 1; while (i < (int)_frames.size() && - (_frames[i] == (PStatFrameData *)NULL || + (_frames[i] == nullptr || _frames[i]->get_start() <= time)) { - if (_frames[i] != (PStatFrameData *)NULL) { + if (_frames[i] != nullptr) { hint = i; } ++i; @@ -175,7 +175,7 @@ get_frame_number_at_time(double time, int hint) const { int i = _frames.size() - 1; while (i >= 0) { const PStatFrameData *frame = _frames[i]; - if (frame != (PStatFrameData *)NULL && frame->get_start() <= time) { + if (frame != nullptr && frame->get_start() <= time) { break; } --i; @@ -259,17 +259,17 @@ get_history() const { */ void PStatThreadData:: record_new_frame(int frame_number, PStatFrameData *frame_data) { - nassertv(frame_data != (PStatFrameData *)NULL); + nassertv(frame_data != nullptr); nassertv(!frame_data->is_empty()); double time = frame_data->get_start(); // First, remove all the old frames that fall outside of our history window. double oldest_allowable_time = time - _history; while (!_frames.empty() && - (_frames.front() == (PStatFrameData *)NULL || + (_frames.front() == nullptr || _frames.front()->is_empty() || _frames.front()->get_start() < oldest_allowable_time)) { - if (_frames.front() != (PStatFrameData *)NULL) { + if (_frames.front() != nullptr) { delete _frames.front(); } _frames.pop_front(); @@ -281,18 +281,18 @@ record_new_frame(int frame_number, PStatFrameData *frame_data) { // get all the frames in order or even at all. if (_frames.empty()) { _first_frame_number = frame_number; - _frames.push_back(NULL); + _frames.push_back(nullptr); } else { while (_first_frame_number + (int)_frames.size() <= frame_number) { - _frames.push_back(NULL); + _frames.push_back(nullptr); } } int index = frame_number - _first_frame_number; nassertv(index >= 0 && index < (int)_frames.size()); - if (_frames[index] != (PStatFrameData *)NULL) { + if (_frames[index] != nullptr) { nout << "Got repeated frame data for frame " << frame_number << "\n"; delete _frames[index]; } @@ -314,7 +314,7 @@ compute_elapsed_frames() { } else { _now_i = _frames.size() - 1; - while (_now_i > 0 && _frames[_now_i] == (PStatFrameData *)NULL) { + while (_now_i > 0 && _frames[_now_i] == nullptr) { _now_i--; } if (_now_i < 0) { @@ -322,7 +322,7 @@ compute_elapsed_frames() { _got_elapsed_frames = false; } else { - nassertv(_frames[_now_i] != (PStatFrameData *)NULL); + nassertv(_frames[_now_i] != nullptr); double now = _frames[_now_i]->get_end(); double then = now - pstats_average_time; @@ -332,7 +332,7 @@ compute_elapsed_frames() { while (old_i >= 0) { const PStatFrameData *frame = _frames[old_i]; - if (frame != (PStatFrameData *)NULL) { + if (frame != nullptr) { if (frame->get_start() > then) { _then_i = old_i; } else { @@ -343,7 +343,7 @@ compute_elapsed_frames() { } nassertv(_then_i >= 0); - nassertv(_frames[_then_i] != (PStatFrameData *)NULL); + nassertv(_frames[_then_i] != nullptr); _got_elapsed_frames = true; _now_i += _first_frame_number; diff --git a/pandatool/src/pstatserver/pStatView.cxx b/pandatool/src/pstatserver/pStatView.cxx index b8d6aa9793..e69959a731 100644 --- a/pandatool/src/pstatserver/pStatView.cxx +++ b/pandatool/src/pstatserver/pStatView.cxx @@ -266,7 +266,7 @@ get_level(int collector) { PStatViewLevel *level = new PStatViewLevel; level->_collector = collector; - level->_parent = NULL; + level->_parent = nullptr; _levels[collector] = level; reset_level(level); @@ -518,7 +518,7 @@ reset_level(PStatViewLevel *level) { int parent_index = _client_data->get_collector_def(level->_collector)._parent_index; - if (level->_parent == (PStatViewLevel *)NULL) { + if (level->_parent == nullptr) { // This level didn't know its parent before, but now it does. PStatViewLevel *parent_level = get_level(parent_index); nassertr(parent_level != level, true); @@ -540,7 +540,7 @@ reset_level(PStatViewLevel *level) { new_parent_level->_children.push_back(level); new_parent_level->sort_children(_client_data); } else { - level->_parent = NULL; + level->_parent = nullptr; } PStatViewLevel::Children::iterator ci = diff --git a/pandatool/src/pstatserver/pStatViewLevel.cxx b/pandatool/src/pstatserver/pStatViewLevel.cxx index 04d962e833..47ed1fae98 100644 --- a/pandatool/src/pstatserver/pStatViewLevel.cxx +++ b/pandatool/src/pstatserver/pStatViewLevel.cxx @@ -77,6 +77,6 @@ get_num_children() const { */ const PStatViewLevel *PStatViewLevel:: get_child(int n) const { - nassertr(n >= 0 && n < (int)_children.size(), NULL); + nassertr(n >= 0 && n < (int)_children.size(), nullptr); return _children[n]; } diff --git a/pandatool/src/ptloader/loaderFileTypePandatool.cxx b/pandatool/src/ptloader/loaderFileTypePandatool.cxx index 0de02c19de..9536b3fe65 100644 --- a/pandatool/src/ptloader/loaderFileTypePandatool.cxx +++ b/pandatool/src/ptloader/loaderFileTypePandatool.cxx @@ -32,7 +32,7 @@ LoaderFileTypePandatool(SomethingToEggConverter *loader, EggToSomethingConverter *saver) : _loader(loader), _saver(saver) { - if (_loader != (SomethingToEggConverter *)NULL) { + if (_loader != nullptr) { _loader->set_merge_externals(true); } } @@ -47,9 +47,9 @@ LoaderFileTypePandatool:: /** * */ -string LoaderFileTypePandatool:: +std::string LoaderFileTypePandatool:: get_name() const { - if (_loader != (SomethingToEggConverter *)NULL) { + if (_loader != nullptr) { return _loader->get_name(); } return _saver->get_name(); @@ -58,9 +58,9 @@ get_name() const { /** * */ -string LoaderFileTypePandatool:: +std::string LoaderFileTypePandatool:: get_extension() const { - if (_loader != (SomethingToEggConverter *)NULL) { + if (_loader != nullptr) { return _loader->get_extension(); } return _saver->get_extension(); @@ -70,9 +70,9 @@ get_extension() const { * Returns a space-separated list of extension, in addition to the one * returned by get_extension(), that are recognized by this converter. */ -string LoaderFileTypePandatool:: +std::string LoaderFileTypePandatool:: get_additional_extensions() const { - if (_loader != (SomethingToEggConverter *)NULL) { + if (_loader != nullptr) { return _loader->get_additional_extensions(); } return _saver->get_additional_extensions(); @@ -84,7 +84,7 @@ get_additional_extensions() const { */ bool LoaderFileTypePandatool:: supports_compressed() const { - if (_loader != (SomethingToEggConverter *)NULL) { + if (_loader != nullptr) { return _loader->supports_compressed(); } return _saver->supports_compressed(); @@ -97,7 +97,7 @@ supports_compressed() const { */ bool LoaderFileTypePandatool:: supports_load() const { - return (_loader != NULL); + return (_loader != nullptr); } /** @@ -107,7 +107,7 @@ supports_load() const { */ bool LoaderFileTypePandatool:: supports_save() const { - return (_saver != NULL); + return (_saver != nullptr); } /** @@ -125,11 +125,11 @@ resolve_filename(Filename &path) const { PT(PandaNode) LoaderFileTypePandatool:: load_file(const Filename &path, const LoaderOptions &options, BamCacheRecord *record) const { - if (_loader == NULL) { - return NULL; + if (_loader == nullptr) { + return nullptr; } - if (record != (BamCacheRecord *)NULL) { + if (record != nullptr) { record->add_dependent_file(path); } @@ -196,7 +196,7 @@ load_file(const Filename &path, const LoaderOptions &options, } delete loader; - return result.p(); + return result; } /** @@ -205,7 +205,7 @@ load_file(const Filename &path, const LoaderOptions &options, bool LoaderFileTypePandatool:: save_file(const Filename &path, const LoaderOptions &options, PandaNode *node) const { - if (_saver == NULL) { + if (_saver == nullptr) { return false; } diff --git a/pandatool/src/ptloader/loaderFileTypePandatool.h b/pandatool/src/ptloader/loaderFileTypePandatool.h index 3e38e3a8b9..f50400cd4f 100644 --- a/pandatool/src/ptloader/loaderFileTypePandatool.h +++ b/pandatool/src/ptloader/loaderFileTypePandatool.h @@ -29,12 +29,12 @@ class EggToSomethingConverter; class EXPCL_PTLOADER LoaderFileTypePandatool : public LoaderFileType { public: LoaderFileTypePandatool(SomethingToEggConverter *loader, - EggToSomethingConverter *saver = NULL); + EggToSomethingConverter *saver = nullptr); virtual ~LoaderFileTypePandatool(); - virtual string get_name() const; - virtual string get_extension() const; - virtual string get_additional_extensions() const; + virtual std::string get_name() const; + virtual std::string get_extension() const; + virtual std::string get_additional_extensions() const; virtual bool supports_compressed() const; virtual bool supports_load() const; diff --git a/pandatool/src/softegg/soft2Egg.c b/pandatool/src/softegg/soft2Egg.c index aaad102fb4..9e744b8655 100644 --- a/pandatool/src/softegg/soft2Egg.c +++ b/pandatool/src/softegg/soft2Egg.c @@ -192,10 +192,9 @@ class soft2egg : public EggBase bool has_morph; bool make_pose; - ofstream eggFile; - ofstream animFile; - ofstream texFile; - + std::ofstream eggFile; + std::ofstream animFile; + std::ofstream texFile; }; diff --git a/pandatool/src/softegg/softNodeDesc.cxx b/pandatool/src/softegg/softNodeDesc.cxx index 5be0b79246..ff0f624a20 100644 --- a/pandatool/src/softegg/softNodeDesc.cxx +++ b/pandatool/src/softegg/softNodeDesc.cxx @@ -19,48 +19,50 @@ #include "softToEggConverter.h" #include "dcast.h" +using std::endl; + TypeHandle SoftNodeDesc::_type_handle; /** * */ SoftNodeDesc:: -SoftNodeDesc(SoftNodeDesc *parent, const string &name) : +SoftNodeDesc(SoftNodeDesc *parent, const std::string &name) : Namable(name), _parent(parent) { - _model = (SAA_Elem *)NULL; - _egg_group = (EggGroup *)NULL; - _egg_table = (EggTable *)NULL; - _anim = (EggXfmSAnim *)NULL; + _model = nullptr; + _egg_group = nullptr; + _egg_table = nullptr; + _anim = nullptr; _joint_type = JT_none; // Add ourselves to our parent. - if (_parent != (SoftNodeDesc *)NULL) { + if (_parent != nullptr) { softegg_cat.spam() << "parent name " << _parent->get_name(); _parent->_children.push_back(this); } // set the _parentJoint to Null - _parentJoint = NULL; + _parentJoint = nullptr; - fullname = NULL; + fullname = nullptr; numTexLoc = 0; numTexGlb = 0; - uScale = NULL; - vScale = NULL; - uOffset = NULL; - vOffset = NULL; + uScale = nullptr; + vScale = nullptr; + uOffset = nullptr; + vOffset = nullptr; valid; uv_swap; // SAA_Boolean visible; - numTexTri = NULL; - textures = NULL; - materials = NULL; - triangles = NULL; + numTexTri = nullptr; + textures = nullptr; + materials = nullptr; + triangles = nullptr; gtype = SAA_GEOM_ORIGINAL; } @@ -140,7 +142,7 @@ force_set_parent(SoftNodeDesc *parent) { */ bool SoftNodeDesc:: has_model() const { - return (_model != (SAA_Elem *)NULL); + return (_model != nullptr); } /** @@ -149,7 +151,7 @@ has_model() const { */ SAA_Elem *SoftNodeDesc:: get_model() const { - nassertr(_model != (SAA_Elem *)NULL, _model); + nassertr(_model != nullptr, _model); return _model; } @@ -190,9 +192,9 @@ is_joint_parent() const { */ void SoftNodeDesc:: clear_egg() { - _egg_group = (EggGroup *)NULL; - _egg_table = (EggTable *)NULL; - _anim = (EggXfmSAnim *)NULL; + _egg_group = nullptr; + _egg_table = nullptr; + _anim = nullptr; Children::const_iterator ci; for (ci = _children.begin(); ci != _children.end(); ++ci) { @@ -214,7 +216,7 @@ mark_joint_parent() { else softegg_cat.spam() << " ?parent " << get_name() << " joint type " << _joint_type; - if (_parent != (SoftNodeDesc *)NULL) { + if (_parent != nullptr) { _parent->mark_joint_parent(); } softegg_cat.spam() << endl; @@ -249,13 +251,13 @@ check_junk(bool parent_junk) { _joint_type = JT_junk; softegg_cat.spam() << "junk node " << get_name() << endl; } - if ( (strstr(name, "con-") != NULL) || - (strstr(name, "con_") != NULL) || - (strstr(name, "fly_") != NULL) || - (strstr(name, "fly-") != NULL) || - (strstr(name, "camRIG") != NULL) || - (strstr(name, "cam_rig") != NULL) || - (strstr(name, "bars") != NULL) ) + if ( (strstr(name, "con-") != nullptr) || + (strstr(name, "con_") != nullptr) || + (strstr(name, "fly_") != nullptr) || + (strstr(name, "fly-") != nullptr) || + (strstr(name, "camRIG") != nullptr) || + (strstr(name, "cam_rig") != nullptr) || + (strstr(name, "bars") != nullptr) ) { _joint_type = JT_junk; softegg_cat.spam() << "junk node " << get_name() << endl; @@ -286,12 +288,12 @@ is_partial(char *search_prefix) { if (!search_prefix) return false; // if name is search_prefix, return false - if (strstr(name, search_prefix) != NULL) { + if (strstr(name, search_prefix) != nullptr) { softegg_cat.debug() << "matched " << name << " "; return false; } // if name is not search_prefix, look in its parent - if (strstr(name, search_prefix) == NULL) { + if (strstr(name, search_prefix) == nullptr) { softegg_cat.debug() << "node " << name << " "; if (_parent) return _parent->is_partial(search_prefix); @@ -322,13 +324,13 @@ set_parentJoint(SAA_Scene *scene, SoftNodeDesc *lastJoint) { // if already a joint or name has "joint" in it const char *name = get_name().c_str(); - if (is_joint() || isSkeleton || strstr(name, "joint") != NULL) { + if (is_joint() || isSkeleton || strstr(name, "joint") != nullptr) { lastJoint = this; } - if ( _parentJoint && strstr( _parentJoint->get_name().c_str(), "scale" ) != NULL ) { + if ( _parentJoint && strstr( _parentJoint->get_name().c_str(), "scale" ) != nullptr ) { // make sure _parentJoint didn't have the name "joint" in it - if (strstr(_parentJoint->get_name().c_str(), "joint") == NULL) { - _parentJoint = NULL; + if (strstr(_parentJoint->get_name().c_str(), "joint") == nullptr) { + _parentJoint = nullptr; // _parentJoint = lastJoint = NULL; softegg_cat.spam() << "scale joint flag set!\n"; } @@ -464,7 +466,7 @@ get_joint_transform(SAA_Scene *scene, EggGroup *egg_group, EggXfmSAnim *anim, b SAA_Elem *skeletonPart = _model; const char *name = get_name().c_str(); - if ( skeletonPart != NULL ) { + if ( skeletonPart != nullptr ) { PN_stdfloat i,j,k; PN_stdfloat h,p,r; PN_stdfloat x,y,z; @@ -636,7 +638,7 @@ load_poly_model(SAA_Scene *scene, SAA_ModelType type) { TEX_PER_MAT , &textures[i] ); // initialize the array value - texNameArray[i] = NULL; + texNameArray[i] = nullptr; // initialize the repeats uRepeat[i] = vRepeat[i] = 0; @@ -895,13 +897,13 @@ make_vertex_offsets(int numShapes) { int offset; int numCV; char tableName[_MAX_PATH]; - SAA_DVector *shapeVerts = NULL; - SAA_DVector *uniqueVerts = NULL; + SAA_DVector *shapeVerts = nullptr; + SAA_DVector *uniqueVerts = nullptr; SAA_Elem *model = get_model(); SAA_Scene *scene = &stec.scene; - EggVertexPool *vpool = NULL; - string vpool_name = get_name() + ".verts"; + EggVertexPool *vpool = nullptr; + std::string vpool_name = get_name() + ".verts"; EggNode *t = stec._tree.get_egg_root()->find_child(vpool_name); if (t) DCAST_INTO_V(vpool, t); @@ -988,7 +990,7 @@ make_vertex_offsets(int numShapes) { // if change isn't negligible, make a morph vertex entry double total = fabs(dx)+fabs(dy)+fabs(dz); if ( total > 0.00001 ) { - if ( vpool != NULL ) { + if ( vpool != nullptr ) { // create offset LVector3d p(dx, dy, dz); EggMorphVertex *dxyz = new EggMorphVertex(tableName, p); @@ -1011,7 +1013,7 @@ make_vertex_offsets(int numShapes) { void SoftNodeDesc:: make_morph_table( PN_stdfloat time ) { int numShapes; - SAA_Elem *model = NULL; + SAA_Elem *model = nullptr; SAA_AnimInterpType type; SAA_Scene *scene = &stec.scene; @@ -1080,7 +1082,7 @@ make_linear_morph_table(int numShapes, PN_stdfloat time) { // find the morph table associated with this key shape anim = stec.find_morph_table(tableName); - if ( anim != NULL ) { + if ( anim != nullptr ) { if ( i == (int)curveVal ) { if ( curveVal - i == 0 ) { anim->add_data(1.0f ); @@ -1151,7 +1153,7 @@ make_weighted_morph_table(int numShapes, PN_stdfloat time) { // find the morph table associated with this key shape anim = stec.find_morph_table(tableName); - if ( anim != NULL ) { + if ( anim != nullptr ) { anim->add_data(curveVal); softegg_cat.spam() << "adding element " << curveVal << endl; } @@ -1183,7 +1185,7 @@ make_expression_morph_table(int numShapes, PN_stdfloat time) // populate morph table values for this frame // compose track name - track = NULL; + track = nullptr; // find how many expressions for this shape SAA_elementGetNbExpressions( scene, model, track, FALSE, &numExp ); diff --git a/pandatool/src/softegg/softNodeDesc.h b/pandatool/src/softegg/softNodeDesc.h index 8d041377c6..c6512b7dda 100644 --- a/pandatool/src/softegg/softNodeDesc.h +++ b/pandatool/src/softegg/softNodeDesc.h @@ -42,7 +42,7 @@ class EggXfmSAnim; */ class SoftNodeDesc : public ReferenceCount, public Namable { public: - SoftNodeDesc(SoftNodeDesc *parent=NULL, const string &name = string()); + SoftNodeDesc(SoftNodeDesc *parent=nullptr, const std::string &name = std::string()); ~SoftNodeDesc(); void set_parent(SoftNodeDesc *parent); diff --git a/pandatool/src/softegg/softNodeTree.cxx b/pandatool/src/softegg/softNodeTree.cxx index f8dda53d48..3b5be3252b 100644 --- a/pandatool/src/softegg/softNodeTree.cxx +++ b/pandatool/src/softegg/softNodeTree.cxx @@ -25,19 +25,21 @@ #include +using std::endl; + /** * */ SoftNodeTree:: SoftNodeTree() { - _root = new SoftNodeDesc(NULL, "----root"); + _root = new SoftNodeDesc(nullptr, "----root"); _root->fullname = "----root"; _fps = 0.0; _use_prefix = 0; - _search_prefix = NULL; - _egg_data = (EggData *)NULL; - _egg_root = (EggGroupNode *)NULL; - _skeleton_node = (EggGroupNode *)NULL; + _search_prefix = nullptr; + _egg_data = nullptr; + _egg_root = nullptr; + _skeleton_node = nullptr; } /** * Given an element, return a copy of the element's name WITHOUT prefix. @@ -91,7 +93,7 @@ GetFullName( SAA_Scene *scene, SAA_Elem *element ) char *SoftNodeTree:: GetModelNoteInfo( SAA_Scene *scene, SAA_Elem *model ) { int size; - char *modelNote = NULL; + char *modelNote = nullptr; SAA_Boolean bigEndian; SAA_elementGetUserDataSize( scene, model, "MNOT", &size ); @@ -106,7 +108,7 @@ GetModelNoteInfo( SAA_Scene *scene, SAA_Elem *model ) { // strip off newline, if present char *eol = (char *)memchr( modelNote, '\n', size ); - if ( eol != NULL) + if ( eol != nullptr) *eol = '\0'; else modelNote[size] = '\0'; @@ -130,7 +132,7 @@ GetRootName( const char *name ) { hyphen = strchr( name, '-' ); len = hyphen-name; - if ( (hyphen != NULL) && len ) { + if ( (hyphen != nullptr) && len ) { root = new char[len+1]; strncpy( root, name, len ); root[len] = '\0'; @@ -164,7 +166,7 @@ build_complete_hierarchy(SAA_Scene &scene, SAA_Database &database) { if ( numModels ) { // allocate array of models models = (SAA_Elem *) new SAA_Elem[numModels]; - if ( models != NULL ) { + if ( models != nullptr ) { if ((status = SAA_sceneGetModels( &scene, numModels, models )) != SI_SUCCESS) { return false; } @@ -200,7 +202,7 @@ build_complete_hierarchy(SAA_Scene &scene, SAA_Database &database) { softegg_cat.spam() << "========================================================\n"; // find _parentJoint for each node - _root->set_parentJoint(&scene, NULL); + _root->set_parentJoint(&scene, nullptr); return all_ok; } @@ -280,7 +282,7 @@ get_num_nodes() const { */ SoftNodeDesc *SoftNodeTree:: get_node(int n) const { - nassertr(n >= 0 && n < (int)_nodes.size(), NULL); + nassertr(n >= 0 && n < (int)_nodes.size(), nullptr); return _nodes[n]; } @@ -288,11 +290,11 @@ get_node(int n) const { * Returns the node named 'name' in the hierarchy, in an arbitrary ordering. */ SoftNodeDesc *SoftNodeTree:: -get_node(string name) const { +get_node(std::string name) const { NodesByName::const_iterator ni = _nodes_by_name.find(name); if (ni != _nodes_by_name.end()) return (*ni).second; - return NULL; + return nullptr; } /** @@ -314,7 +316,7 @@ clear_egg(EggData *egg_data, EggGroupNode *egg_root, */ EggGroup *SoftNodeTree:: get_egg_group(SoftNodeDesc *node_desc) { - nassertr(_egg_root != (EggGroupNode *)NULL, NULL); + nassertr(_egg_root != nullptr, nullptr); // lets print some relationship softegg_cat.spam() << " group " << node_desc->get_name() << "(" << node_desc->_egg_group << ")"; @@ -324,7 +326,7 @@ get_egg_group(SoftNodeDesc *node_desc) { softegg_cat.spam() << " parent " << node_desc->_parent; softegg_cat.spam() << endl; - if (node_desc->_egg_group == (EggGroup *)NULL) { + if (node_desc->_egg_group == nullptr) { // We need to make a new group node. EggGroup *egg_group; @@ -355,8 +357,8 @@ get_egg_group(SoftNodeDesc *node_desc) { */ EggTable *SoftNodeTree:: get_egg_table(SoftNodeDesc *node_desc) { - nassertr(_skeleton_node != (EggGroupNode *)NULL, NULL); - nassertr(node_desc->is_joint(), NULL); + nassertr(_skeleton_node != nullptr, nullptr); + nassertr(node_desc->is_joint(), nullptr); // lets print some relationship softegg_cat.spam() << " group " << node_desc->get_name() << "(" << node_desc->_egg_group << ")"; @@ -366,7 +368,7 @@ get_egg_table(SoftNodeDesc *node_desc) { softegg_cat.spam() << " parent " << node_desc->_parent; softegg_cat.spam() << endl; - if (node_desc->_egg_table == (EggTable *)NULL) { + if (node_desc->_egg_table == nullptr) { softegg_cat.spam() << "creating a new table\n"; // We need to make a new table node. nassertr(node_desc->_parent != // (SoftNodeDesc *)NULL, NULL); @@ -433,7 +435,7 @@ handle_null(SAA_Scene *scene, SoftNodeDesc *node_desc, const char *node_name) { // check to see if this NULL is used as a skeleton or is animated via // constraint only ( these nodes are tagged by the animator with the // keyword "joint" somewhere in the nodes name) - if ( isSkeleton || (strstr( name, "joint" ) != NULL) ) { + if ( isSkeleton || (strstr( name, "joint" ) != nullptr) ) { // MakeJoint( &scene, lastJoint, lastAnim, model, name ); node_desc->set_joint(); softegg_cat.spam() << " animating Standard null!!!\n"; @@ -451,7 +453,7 @@ handle_null(SAA_Scene *scene, SoftNodeDesc *node_desc, const char *node_name) { SoftNodeDesc *SoftNodeTree:: build_node(SAA_Scene *scene, SAA_Elem *model) { char *name, *fullname; - string node_name; + std::string node_name; int numChildren; int thisChild; SAA_Elem *children; @@ -466,7 +468,7 @@ build_node(SAA_Scene *scene, SAA_Elem *model) { node_name = name; - SoftNodeDesc *node_desc = r_build_node(NULL, node_name); + SoftNodeDesc *node_desc = r_build_node(nullptr, node_name); node_desc->fullname = fullname; node_desc->set_model(model); @@ -475,7 +477,7 @@ build_node(SAA_Scene *scene, SAA_Elem *model) { // find out what type of node we're dealing with SAA_modelGetType( scene, node_desc->get_model(), &type ); - if (type == SAA_MJNT || isSkeleton || (strstr(node_desc->get_name().c_str(), "joint") != NULL)) + if (type == SAA_MJNT || isSkeleton || (strstr(node_desc->get_name().c_str(), "joint") != nullptr)) node_desc->set_joint(); // treat the MNILL differently, because it needs to detect and set some @@ -514,7 +516,7 @@ build_node(SAA_Scene *scene, SAA_Elem *model) { // find out what type of node we're dealing with SAA_modelGetType( scene, node_child->get_model(), &type ); - if (type == SAA_MJNT || isSkeleton || (strstr(node_child->get_name().c_str(), "joint") != NULL)) + if (type == SAA_MJNT || isSkeleton || (strstr(node_child->get_name().c_str(), "joint") != nullptr)) node_child->set_joint(); // treat the MNILL differently, because it needs to detect and set some @@ -533,7 +535,7 @@ build_node(SAA_Scene *scene, SAA_Elem *model) { * The recursive implementation of build_node(). */ SoftNodeDesc *SoftNodeTree:: -r_build_node(SoftNodeDesc *parent_node, const string &name) { +r_build_node(SoftNodeDesc *parent_node, const std::string &name) { SoftNodeDesc *node_desc; // If we have already encountered this pathname, return the corresponding diff --git a/pandatool/src/softegg/softNodeTree.h b/pandatool/src/softegg/softNodeTree.h index ba44caa810..afbef5877b 100644 --- a/pandatool/src/softegg/softNodeTree.h +++ b/pandatool/src/softegg/softNodeTree.h @@ -40,7 +40,7 @@ public: int get_num_nodes() const; SoftNodeDesc *get_node(int n) const; - SoftNodeDesc *get_node(string name) const; + SoftNodeDesc *get_node(std::string name) const; char *GetRootName(const char *); char *GetModelNoteInfo(SAA_Scene *, SAA_Elem *); @@ -66,9 +66,9 @@ private: EggGroupNode *_egg_root; EggGroupNode *_skeleton_node; - SoftNodeDesc *r_build_node(SoftNodeDesc *parent_node, const string &path); + SoftNodeDesc *r_build_node(SoftNodeDesc *parent_node, const std::string &path); - typedef pmap NodesByName; + typedef pmap NodesByName; NodesByName _nodes_by_name; typedef pvector Nodes; diff --git a/pandatool/src/softegg/softToEggConverter.cxx b/pandatool/src/softegg/softToEggConverter.cxx index 64d5da3aed..44dafefb62 100644 --- a/pandatool/src/softegg/softToEggConverter.cxx +++ b/pandatool/src/softegg/softToEggConverter.cxx @@ -32,6 +32,9 @@ #include "string_utils.h" #include "dcast.h" +using std::endl; +using std::string; + SoftToEggConverter stec; const int TEX_PER_MAT = 1; @@ -52,15 +55,15 @@ SoftToEggConverter(const string &program_name) : */ _transform_type = TT_model; - database_name = NULL; - scene_name = NULL; - model_name = NULL; - animFileName = NULL; - eggFileName = NULL; - tex_path = NULL; - eggGroupName = NULL; - tex_filename = NULL; - search_prefix = NULL; + database_name = nullptr; + scene_name = nullptr; + model_name = nullptr; + animFileName = nullptr; + eggFileName = nullptr; + tex_path = nullptr; + eggGroupName = nullptr; + tex_filename = nullptr; + search_prefix = nullptr; result = SI_SUCCESS; // skeleton = new EggGroup(); @@ -473,7 +476,7 @@ GetTextureName( SAA_Scene *scene, SAA_Elem *texture ) { strcpy(fileName, tex_path); // do some processing on the name string - char *tmpName = NULL; + char *tmpName = nullptr; tmpName = strrchr(tempName, '/'); if (tmpName) tmpName++; @@ -601,7 +604,7 @@ convert_soft(bool from_selection) { */ bool SoftToEggConverter:: open_api() { - if ((scene_name == NULL && model_name == NULL) || database_name == NULL) { + if ((scene_name == nullptr && model_name == nullptr) || database_name == nullptr) { Usage(); exit( 1 ); } @@ -637,7 +640,7 @@ open_api() { } // if no egg filename specified, make up a name - if ( eggFileName == NULL ) { + if ( eggFileName == nullptr ) { string madeName; string tempName(scene_name); string::size_type end = tempName.find(".dsc"); @@ -651,7 +654,7 @@ open_api() { strcpy(eggFileName, madeName.c_str()); // if no anim filename specified, make up a name - if ( animFileName == NULL ) { + if ( animFileName == nullptr ) { madeName.assign(tempName.substr(0,end)); madeName.insert(madeName.size(), "-chan.egg"); animFileName = new char[strlen(scene_name)+ 10]; @@ -691,7 +694,7 @@ convert_char_model() { */ EggSAnimData *SoftToEggConverter:: find_morph_table(char *name) { - EggSAnimData *anim = NULL; + EggSAnimData *anim = nullptr; MorphTable::iterator mt; for (mt = _morph_table.begin(); mt != _morph_table.end(); ++mt) { anim = (*mt); @@ -742,7 +745,7 @@ convert_char_chan() { _tree._fps = output_frame_rate / frame_inc; // _tree.clear_egg(get_egg_data(), NULL, root_node); - _tree.clear_egg(get_egg_data(), NULL, skeleton_node); + _tree.clear_egg(get_egg_data(), nullptr, skeleton_node); // Now we can get the animation data by walking through all of the frames, // one at a time, and getting the joint angles at each frame. @@ -775,7 +778,7 @@ convert_char_chan() { // if (softegg_cat.is_debug()) { softegg_cat.debug(false) softegg_cat.info() << "frame " << time << "\n"; // } else { We have to write to cerr instead of softegg_cat to allow - // flushing without writing a newline. cerr << "." << flush; } + // flushing without writing a newline. std::cerr << "." << std::flush; } // MGlobal::viewFrame(frame); for (i = 0; i < num_nodes; i++) { @@ -828,7 +831,7 @@ bool SoftToEggConverter:: convert_hierarchy(EggGroupNode *egg_root) { int num_nodes = _tree.get_num_nodes(); - _tree.clear_egg(get_egg_data(), egg_root, NULL); + _tree.clear_egg(get_egg_data(), egg_root, nullptr); softegg_cat.spam() << "num_nodes = " << num_nodes << endl; for (int i = 0; i < num_nodes; i++) { if (!process_model_node(_tree.get_node(i))) { @@ -846,9 +849,9 @@ convert_hierarchy(EggGroupNode *egg_root) { */ bool SoftToEggConverter:: process_model_node(SoftNodeDesc *node_desc) { - EggGroup *egg_group = NULL; - const char *name = NULL; - char *fullname = NULL; + EggGroup *egg_group = nullptr; + const char *name = nullptr; + char *fullname = nullptr; SAA_ModelType type; name = node_desc->get_name().c_str(); @@ -930,8 +933,8 @@ make_polyset(SoftNodeDesc *node_desc, EggGroup *egg_group, SAA_ModelType type) { int numShapes; SAA_Boolean valid; SAA_Boolean visible; - PN_stdfloat *uCoords = NULL; - PN_stdfloat *vCoords = NULL; + PN_stdfloat *uCoords = nullptr; + PN_stdfloat *vCoords = nullptr; string name = node_desc->get_name(); SAA_modelGetNodeVisibility( &scene, node_desc->get_model(), &visible ); @@ -984,8 +987,8 @@ make_polyset(SoftNodeDesc *node_desc, EggGroup *egg_group, SAA_ModelType type) { // Is this a double sided polygon? meaning check for back face flag char *modelNoteStr = _tree.GetModelNoteInfo( &scene, node_desc->get_model() ); - if ( modelNoteStr != NULL ) { - if ( strstr( modelNoteStr, "bface" ) != NULL ) + if ( modelNoteStr != nullptr ) { + if ( strstr( modelNoteStr, "bface" ) != nullptr ) egg_poly->set_bface_flag(TRUE); } @@ -1018,7 +1021,7 @@ make_polyset(SoftNodeDesc *node_desc, EggGroup *egg_group, SAA_ModelType type) { vCoords = new PN_stdfloat[3]; // read the u & v coords into the arrays - if ( uCoords != NULL && vCoords != NULL) { + if ( uCoords != nullptr && vCoords != nullptr) { for ( i = 0; i < 3; i++ ) uCoords[i] = vCoords[i] = 0.0f; @@ -1044,7 +1047,7 @@ make_polyset(SoftNodeDesc *node_desc, EggGroup *egg_group, SAA_ModelType type) { } // read the u & v coords into the arrays - if ( uCoords != NULL && vCoords != NULL) { + if ( uCoords != nullptr && vCoords != nullptr) { SAA_triCtrlVertexGetGlobalUVTxtCoords( &scene, node_desc->get_model(), 3, cvertices, node_desc->numTexGlb, node_desc->textures, uCoords, vCoords ); } @@ -1132,7 +1135,7 @@ make_polyset(SoftNodeDesc *node_desc, EggGroup *egg_group, SAA_ModelType type) { } // Now apply the shader. - if (node_desc->textures != NULL) { + if (node_desc->textures != nullptr) { if (node_desc->numTexLoc && node_desc->numTexTri[idx]) { if (!strstr(node_desc->texNameArray[idx], "noIcon")) set_shader_attributes(node_desc, *egg_poly, idx); @@ -1164,8 +1167,8 @@ make_nurb_surface(SoftNodeDesc *node_desc, EggGroup *egg_group, SAA_ModelType ty int numShapes; SAA_Boolean valid; SAA_Boolean visible; - PN_stdfloat *uCoords = NULL; - PN_stdfloat *vCoords = NULL; + PN_stdfloat *uCoords = nullptr; + PN_stdfloat *vCoords = nullptr; string name = node_desc->get_name(); SAA_modelGetNodeVisibility( &scene, node_desc->get_model(), &visible ); @@ -1261,8 +1264,8 @@ make_nurb_surface(SoftNodeDesc *node_desc, EggGroup *egg_group, SAA_ModelType ty // Is this a double sided polygon? meaning check for back face flag char *modelNoteStr = _tree.GetModelNoteInfo( &scene, node_desc->get_model() ); - if ( modelNoteStr != NULL ) { - if ( strstr( modelNoteStr, "bface" ) != NULL ) { + if ( modelNoteStr != nullptr ) { + if ( strstr( modelNoteStr, "bface" ) != nullptr ) { eggNurbs->set_bface_flag(TRUE); softegg_cat.spam() << "Set backface flag\n"; } @@ -1303,7 +1306,7 @@ make_nurb_surface(SoftNodeDesc *node_desc, EggGroup *egg_group, SAA_ModelType ty softegg_cat.spam() << numVert << " CV's\n"; // get the CV's - SAA_DVector *vertices = NULL; + SAA_DVector *vertices = nullptr; vertices = new SAA_DVector[numVert]; SAA_modelGetVertices( &scene, node_desc->get_model(), node_desc->gtype, 0, numVert, vertices ); @@ -1410,7 +1413,7 @@ make_nurb_surface(SoftNodeDesc *node_desc, EggGroup *egg_group, SAA_ModelType ty egg_group->add_child(eggNurbs); // Now apply the shader. - if (node_desc->textures != NULL) { + if (node_desc->textures != nullptr) { if (!strstr(node_desc->texNameArray[0], "noIcon")) set_shader_attributes(node_desc, *eggNurbs, 0); else @@ -1489,7 +1492,7 @@ add_knots( vector &eggKnots, double *knots, int numKnots, SAA_Boolean c int *SoftToEggConverter:: FindClosestTriVert( EggVertexPool *vpool, SAA_DVector *vertices, int numVert ) { int i,j; - int *vertMap = NULL; + int *vertMap = nullptr; int vpoolSize = (int)vpool->size(); PN_stdfloat closestDist; PN_stdfloat thisDist; @@ -1565,7 +1568,7 @@ make_soft_skin() { SAA_ModelType type; SAA_Elem *envelopes; SAA_Elem *model = node_desc->get_model(); - EggGroup *joint = NULL; + EggGroup *joint = nullptr; EggVertexPool *vpool; SAA_skeletonGetNbEnvelopes( &scene, model, &numEnv ); @@ -1579,7 +1582,7 @@ make_soft_skin() { softegg_cat.spam() << "numEnv = " << numEnv << endl; // allocate envelope array envelopes = new SAA_Elem[numEnv]; - if ( envelopes == NULL ) { + if ( envelopes == nullptr ) { softegg_cat.info() << "Out Of Memory" << endl; exit(1); } @@ -1615,13 +1618,13 @@ make_soft_skin() { if ( !hasEnvVertices ) continue; - SAA_SubElem *envVertices = NULL; + SAA_SubElem *envVertices = nullptr; int *numEnvVertices; int i,j,k; numEnvVertices = new int[numEnv]; - if ( numEnvVertices != NULL ) { + if ( numEnvVertices != nullptr ) { SAA_envelopeGetNbCtrlVertices( &scene, model, numEnv, envelopes, numEnvVertices ); int totalEnvVertices = 0; for( i = 0; i < numEnv; i++ ) { @@ -1633,7 +1636,7 @@ make_soft_skin() { continue; envVertices = new SAA_SubElem[totalEnvVertices]; - if ( envVertices != NULL ) { + if ( envVertices != nullptr ) { result = SAA_envelopeGetCtrlVertices( &scene, model, numEnv, envelopes, numEnvVertices, envVertices); if (result != SI_SUCCESS) { @@ -1642,13 +1645,13 @@ make_soft_skin() { } // loop through for each envelope for ( i = 0; i < numEnv; i++ ) { - PN_stdfloat *weights = NULL; + PN_stdfloat *weights = nullptr; int vertArrayOffset = 0; softegg_cat.spam() << "envelope[" << i << "]: "; weights = new PN_stdfloat[numEnvVertices[i]]; if ( weights ) { char *envName; - int *vpoolMap = NULL; + int *vpoolMap = nullptr; for ( j = 0; j < i; j++ ) vertArrayOffset += numEnvVertices[j]; softegg_cat.spam() << "envVertArray offset = " << vertArrayOffset; @@ -1697,7 +1700,7 @@ make_soft_skin() { else softegg_cat.spam() << "OTHER\n"; - int *envVtxIndices = NULL; + int *envVtxIndices = nullptr; envVtxIndices = new int[numEnvVertices[i]]; // Get the envelope vertex indices @@ -1714,7 +1717,7 @@ make_soft_skin() { SAA_modelGetNbVertices( &scene, &envelopes[i], &modelNumVert ); - SAA_DVector *modelVertices = NULL; + SAA_DVector *modelVertices = nullptr; modelVertices = new SAA_DVector[modelNumVert]; // get the model vertices @@ -1723,7 +1726,7 @@ make_soft_skin() { modelVertices ); // create array of global model coords - SAA_DVector *globalModelVertices = NULL; + SAA_DVector *globalModelVertices = nullptr; globalModelVertices = new SAA_DVector[modelNumVert]; PN_stdfloat matrix[4][4]; @@ -1748,7 +1751,7 @@ make_soft_skin() { string vpool_name = s_name + ".verts"; EggNode *t = _tree.get_egg_root()->find_child(vpool_name); if (t) - DCAST_INTO_R(vpool, t, NULL); + DCAST_INTO_R(vpool, t, nullptr); // find the mapping of the vertices that match this envelop if (vpool) { @@ -1841,8 +1844,8 @@ cleanup_soft_skin() continue; SAA_Elem *model = node_desc->get_model(); - EggGroup *joint = NULL; - EggVertexPool *vpool = NULL; + EggGroup *joint = nullptr; + EggVertexPool *vpool = nullptr; SAA_ModelType type; // find out what type of node we're dealing with @@ -1860,7 +1863,7 @@ cleanup_soft_skin() string vpool_name = node_desc->get_name() + ".verts"; EggNode *t = _tree.get_egg_root()->find_child(vpool_name); if (t) - DCAST_INTO_R(vpool, t, NULL); + DCAST_INTO_R(vpool, t, nullptr); if (!vpool) { // softegg_cat.spam() << "couldn't find vpool " << vpool_name << endl; @@ -2014,7 +2017,7 @@ reparent_decals(EggGroupNode *egg_parent) { // First, walk through all children of this node, looking for the one decal // base, if any. - EggGroup *decal_base = (EggGroup *)NULL; + EggGroup *decal_base = nullptr; pvector decal_children; EggGroupNode::iterator ci; @@ -2023,7 +2026,7 @@ reparent_decals(EggGroupNode *egg_parent) { if (child->is_of_type(EggGroup::get_class_type())) { EggGroup *child_group = DCAST(EggGroup, child); if (child_group->has_object_type("decalbase")) { - if (decal_base != (EggNode *)NULL) { + if (decal_base != nullptr) { softegg_cat.error() << "Two children of " << egg_parent->get_name() << " both have decalbase set: " << decal_base->get_name() @@ -2040,7 +2043,7 @@ reparent_decals(EggGroupNode *egg_parent) { } } - if (decal_base == (EggGroup *)NULL) { + if (decal_base == nullptr) { if (!decal_children.empty()) { softegg_cat.warning() << decal_children.front()->get_name() diff --git a/pandatool/src/softegg/softToEggConverter.h b/pandatool/src/softegg/softToEggConverter.h index 1ac9442263..05c26fa60f 100644 --- a/pandatool/src/softegg/softToEggConverter.h +++ b/pandatool/src/softegg/softToEggConverter.h @@ -50,7 +50,7 @@ class EggSAnimData; */ class SoftToEggConverter : public SomethingToEggConverter { public: - SoftToEggConverter(const string &program_name = ""); + SoftToEggConverter(const std::string &program_name = ""); SoftToEggConverter(const SoftToEggConverter ©); virtual ~SoftToEggConverter(); @@ -61,12 +61,12 @@ public: bool HandleGetopts(int &idx, int argc, char **argv); bool DoGetopts(int &argc, char **&argv); - SoftNodeDesc *find_node(string name); + SoftNodeDesc *find_node(std::string name); int *FindClosestTriVert( EggVertexPool *vpool, SAA_DVector *vertices, int numVert ); virtual SomethingToEggConverter *make_copy(); - virtual string get_name() const; - virtual string get_extension() const; + virtual std::string get_name() const; + virtual std::string get_extension() const; virtual bool convert_file(const Filename &filename); bool convert_soft(bool from_selection); @@ -93,7 +93,7 @@ private: bool reparent_decals(EggGroupNode *egg_parent); - string _program_name; + std::string _program_name; bool _from_selection; SI_Error result; @@ -165,7 +165,7 @@ public: }; TransformType _transform_type; - static TransformType string_transform_type(const string &arg); + static TransformType string_transform_type(const std::string &arg); typedef pvector MorphTable; MorphTable _morph_table; diff --git a/pandatool/src/softprogs/softCVS.cxx b/pandatool/src/softprogs/softCVS.cxx index 22329eb8c5..478aa682d2 100644 --- a/pandatool/src/softprogs/softCVS.cxx +++ b/pandatool/src/softprogs/softCVS.cxx @@ -18,6 +18,8 @@ #include +using std::string; + /** * */ @@ -57,7 +59,7 @@ SoftCVS() { ("cvs", "cvs_binary", 80, "Specify how to run the cvs program for adding newly-created files. " "The default is simply \"cvs\".", - &SoftCVS::dispatch_string, NULL, &_cvs_binary); + &SoftCVS::dispatch_string, nullptr, &_cvs_binary); } @@ -282,7 +284,7 @@ get_scenes() { Filename file(sf.get_dirname(), sf.get_filename()); file.set_text(); - ifstream in; + std::ifstream in; if (!file.open_read(in)) { nout << "Unable to read " << file << "\n"; } else { @@ -436,7 +438,7 @@ scan_cvs(const string &dirname, pset &cvs_elements) { return false; } - ifstream in; + std::ifstream in; cvs_entries.set_text(); if (!cvs_entries.open_read(in)) { nout << "Unable to read CVS directory.\n"; @@ -444,7 +446,7 @@ scan_cvs(const string &dirname, pset &cvs_elements) { } string line; - getline(in, line); + std::getline(in, line); while (!in.fail() && !in.eof()) { if (!line.empty() && line[0] == '/') { size_t slash = line.find('/', 1); @@ -461,7 +463,7 @@ scan_cvs(const string &dirname, pset &cvs_elements) { } } - getline(in, line); + std::getline(in, line); } return true; @@ -472,7 +474,7 @@ scan_cvs(const string &dirname, pset &cvs_elements) { * reference found, increments the appropriate element file's reference count. */ bool SoftCVS:: -scan_scene_file(istream &in, Multifile &multifile) { +scan_scene_file(std::istream &in, Multifile &multifile) { bool okflag = true; int c = in.get(); @@ -493,7 +495,7 @@ scan_scene_file(istream &in, Multifile &multifile) { SoftFilename v("", word); // Increment the use count on all matching elements of the multiset. - pair range; + std::pair range; range = _element_files.equal_range(v); ElementFiles::iterator ei; diff --git a/pandatool/src/softprogs/softCVS.h b/pandatool/src/softprogs/softCVS.h index f4907e8cbe..adbd89efa6 100644 --- a/pandatool/src/softprogs/softCVS.h +++ b/pandatool/src/softprogs/softCVS.h @@ -49,11 +49,11 @@ private: void remove_unused_elements(); bool rename_file(SceneFiles::iterator begin, SceneFiles::iterator end); - bool scan_cvs(const string &dirname, pset &cvs_elements); - bool scan_scene_file(istream &in, Multifile &multifile); + bool scan_cvs(const std::string &dirname, pset &cvs_elements); + bool scan_scene_file(std::istream &in, Multifile &multifile); - bool cvs_add(const string &path); - bool cvs_add_or_remove(const string &cvs_command, + bool cvs_add(const std::string &path); + bool cvs_add_or_remove(const std::string &cvs_command, const vector_string &paths); SceneFiles _scene_files; @@ -64,7 +64,7 @@ private: vector_string _cvs_remove; bool _no_cvs; - string _cvs_binary; + std::string _cvs_binary; }; #endif diff --git a/pandatool/src/softprogs/softFilename.cxx b/pandatool/src/softprogs/softFilename.cxx index 16d69de675..4c099c56be 100644 --- a/pandatool/src/softprogs/softFilename.cxx +++ b/pandatool/src/softprogs/softFilename.cxx @@ -15,6 +15,8 @@ #include "pnotify.h" +using std::string; + /** * */ diff --git a/pandatool/src/softprogs/softFilename.h b/pandatool/src/softprogs/softFilename.h index 3c1e448b27..0565eabf89 100644 --- a/pandatool/src/softprogs/softFilename.h +++ b/pandatool/src/softprogs/softFilename.h @@ -26,21 +26,21 @@ */ class SoftFilename { public: - SoftFilename(const string &dirname, const string &filename); + SoftFilename(const std::string &dirname, const std::string &filename); SoftFilename(const SoftFilename ©); void operator = (const SoftFilename ©); - const string &get_dirname() const; - const string &get_filename() const; + const std::string &get_dirname() const; + const std::string &get_filename() const; bool has_version() const; - string get_1_0_filename() const; + std::string get_1_0_filename() const; - const string &get_base() const; + const std::string &get_base() const; int get_major() const; int get_minor() const; - const string &get_extension() const; - string get_non_extension() const; + const std::string &get_extension() const; + std::string get_non_extension() const; bool is_1_0() const; void make_1_0(); @@ -58,13 +58,13 @@ public: int get_use_count() const; private: - string _dirname; - string _filename; + std::string _dirname; + std::string _filename; bool _has_version; - string _base; + std::string _base; int _major; int _minor; - string _ext; + std::string _ext; bool _in_cvs; bool _wants_cvs; int _use_count; diff --git a/pandatool/src/text-stats/textMonitor.cxx b/pandatool/src/text-stats/textMonitor.cxx index 69b134cc8f..2f4f458387 100644 --- a/pandatool/src/text-stats/textMonitor.cxx +++ b/pandatool/src/text-stats/textMonitor.cxx @@ -22,7 +22,7 @@ * */ TextMonitor:: -TextMonitor(TextStats *server, ostream *outStream, bool show_raw_data ) : PStatMonitor(server) { +TextMonitor(TextStats *server, std::ostream *outStream, bool show_raw_data ) : PStatMonitor(server) { _outStream = outStream; //[PECI] _show_raw_data = show_raw_data; } @@ -39,7 +39,7 @@ get_server() { * Should be redefined to return a descriptive name for the type of * PStatsMonitor this is. */ -string TextMonitor:: +std::string TextMonitor:: get_monitor_name() { return "Text Stats"; } diff --git a/pandatool/src/text-stats/textMonitor.h b/pandatool/src/text-stats/textMonitor.h index 7be48fc07c..4c88340e46 100644 --- a/pandatool/src/text-stats/textMonitor.h +++ b/pandatool/src/text-stats/textMonitor.h @@ -29,10 +29,10 @@ class TextStats; */ class TextMonitor : public PStatMonitor { public: - TextMonitor(TextStats *server, ostream *outStream, bool show_raw_data); + TextMonitor(TextStats *server, std::ostream *outStream, bool show_raw_data); TextStats *get_server(); - virtual string get_monitor_name(); + virtual std::string get_monitor_name(); virtual void got_hello(); virtual void got_bad_version(int client_major, int client_minor, @@ -45,7 +45,7 @@ public: void show_level(const PStatViewLevel *level, int indent_level); private: - ostream *_outStream; //[PECI] + std::ostream *_outStream; //[PECI] bool _show_raw_data; }; diff --git a/pandatool/src/text-stats/textStats.cxx b/pandatool/src/text-stats/textStats.cxx index cc1e2392c1..9f2929f440 100644 --- a/pandatool/src/text-stats/textStats.cxx +++ b/pandatool/src/text-stats/textStats.cxx @@ -42,20 +42,20 @@ TextStats() { ("p", "port", 0, "Specify the TCP port to listen for connections on. By default, this " "is taken from the pstats-host Config variable.", - &TextStats::dispatch_int, NULL, &_port); + &TextStats::dispatch_int, nullptr, &_port); add_option ("r", "", 0, "Show the raw frame data, in addition to boiling it down to a total " "time per collector.", - &TextStats::dispatch_none, &_show_raw_data, NULL); + &TextStats::dispatch_none, &_show_raw_data, nullptr); add_option ("o", "filename", 0, "Filename where to print. If not given then stderr is being used.", &TextStats::dispatch_string, &_got_outputFileName, &_outputFileName); - _outFile = NULL; + _outFile = nullptr; _port = pstats_port; } @@ -87,7 +87,7 @@ run() { nout << "Listening for connections.\n"; if (_got_outputFileName) { - _outFile = new ofstream(_outputFileName.c_str(), ios::out); + _outFile = new std::ofstream(_outputFileName.c_str(), std::ios::out); } else { _outFile = &(nout); } diff --git a/pandatool/src/text-stats/textStats.h b/pandatool/src/text-stats/textStats.h index 0f8ec97ed6..b6853ecb46 100644 --- a/pandatool/src/text-stats/textStats.h +++ b/pandatool/src/text-stats/textStats.h @@ -40,8 +40,8 @@ private: // [PECI] bool _got_outputFileName; - string _outputFileName; - ostream *_outFile; + std::string _outputFileName; + std::ostream *_outFile; }; #endif diff --git a/pandatool/src/vrml/parse_vrml.cxx b/pandatool/src/vrml/parse_vrml.cxx index dfa2167e7f..9ec700f19a 100644 --- a/pandatool/src/vrml/parse_vrml.cxx +++ b/pandatool/src/vrml/parse_vrml.cxx @@ -30,6 +30,10 @@ #include "zStream.h" #include "virtualFileSystem.h" +using std::istream; +using std::istringstream; +using std::string; + extern int vrmlyyparse(); extern void vrmlyyResetLineNumber(); extern int vrmlyydebug; @@ -83,9 +87,9 @@ parse_vrml(Filename filename) { filename.set_text(); VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); istream *in = vfs->open_read_file(filename, true); - if (in == (istream *)NULL) { + if (in == nullptr) { nout << "Cannot open " << filename << " for reading.\n"; - return NULL; + return nullptr; } VrmlScene *result = parse_vrml(*in, filename); vfs->close_read_file(in); @@ -99,11 +103,11 @@ parse_vrml(Filename filename) { VrmlScene * parse_vrml(istream &in, const string &filename) { if (!get_standard_nodes()) { - cerr << "Internal error--unable to parse VRML.\n"; - return NULL; + std::cerr << "Internal error--unable to parse VRML.\n"; + return nullptr; } - VrmlScene *scene = NULL; + VrmlScene *scene = nullptr; VrmlNodeType::pushNameSpace(); vrml_init_parser(in, filename); @@ -121,16 +125,16 @@ parse_vrml(istream &in, const string &filename) { int main(int argc, char *argv[]) { if (argc < 2) { - cerr << "parse_vrml filename.wrl\n"; + std::cerr << "parse_vrml filename.wrl\n"; exit(1); } VrmlScene *scene = parse_vrml(argv[1]); - if (scene == (VrmlScene *)NULL) { + if (scene == nullptr) { exit(1); } - cout << *scene << "\n"; + std::cout << *scene << "\n"; return (0); } #endif diff --git a/pandatool/src/vrml/parse_vrml.h b/pandatool/src/vrml/parse_vrml.h index 88c52e16f7..81a04847bf 100644 --- a/pandatool/src/vrml/parse_vrml.h +++ b/pandatool/src/vrml/parse_vrml.h @@ -18,6 +18,6 @@ #include "filename.h" VrmlScene *parse_vrml(Filename filename); -VrmlScene *parse_vrml(istream &in, const string &filename); +VrmlScene *parse_vrml(std::istream &in, const std::string &filename); #endif diff --git a/pandatool/src/vrml/vrmlLexer.cxx.prebuilt b/pandatool/src/vrml/vrmlLexer.cxx.prebuilt index 87565a5ea2..8022d21f4b 100644 --- a/pandatool/src/vrml/vrmlLexer.cxx.prebuilt +++ b/pandatool/src/vrml/vrmlLexer.cxx.prebuilt @@ -2723,21 +2723,18 @@ int vrmlyy_flex_debug = 0; #define YY_RESTORE_YY_MORE_OFFSET char *vrmlyytext; #line 1 "vrmlLexer.lxx" -/* -// Filename: vrmlLexer.lxx -// Created by: drose (01Oct04) -// -//////////////////////////////////////////////////////////////////// -// -// PANDA 3D SOFTWARE -// Copyright (c) Carnegie Mellon University. All rights reserved. -// -// All use of this software is subject to the terms of the revised BSD -// license. You should have received a copy of this license along -// with this source code in a file named "LICENSE." -// -//////////////////////////////////////////////////////////////////// -*/ +/** + * PANDA 3D SOFTWARE + * Copyright (c) Carnegie Mellon University. All rights reserved. + * + * All use of this software is subject to the terms of the revised BSD + * license. You should have received a copy of this license along + * with this source code in a file named "LICENSE." + * + * @file vrmlLexer.lxx + * @author drose + * @date 2004-10-01 + */ /************************************************** * VRML 2.0 Parser * Copyright (C) 1996 Silicon Graphics, Inc. @@ -2774,13 +2771,13 @@ static int error_count = 0; static int warning_count = 0; // This is the pointer to the current input stream. -static istream *input_p = NULL; +static std::istream *input_p = nullptr; // This is the name of the vrml file we're parsing. We keep it so we // can print it out for error messages. -static string vrml_filename; +static std::string vrml_filename; -extern void vrmlyyerror(const string &); +extern void vrmlyyerror(const std::string &); /* The YACC parser sets this to a token to direct the lexer */ /* in cases where just syntax isn't enough: */ @@ -2794,13 +2791,13 @@ static int sfImageIntsParsed = 0; static int sfImageIntsExpected = 0; // This is used while scanning a quoted string. -static string quoted_string; +static std::string quoted_string; // And this keeps track of the currently-parsing array. static MFArray *mfarray; void -vrml_init_lexer(istream &in, const string &filename) { +vrml_init_lexer(std::istream &in, const std::string &filename) { input_p = ∈ vrml_filename = filename; line_number = 0; @@ -2818,7 +2815,9 @@ vrmlyywrap(void) { } void -vrmlyyerror(const string &msg) { +vrmlyyerror(const std::string &msg) { + using std::cerr; + cerr << "\nError"; if (!vrml_filename.empty()) { cerr << " in " << vrml_filename; @@ -2831,7 +2830,9 @@ vrmlyyerror(const string &msg) { } void -vrmlyywarning(const string &msg) { +vrmlyywarning(const std::string &msg) { + using std::cerr; + cerr << "\nWarning"; if (!vrml_filename.empty()) { cerr << " in " << vrml_filename; @@ -2882,7 +2883,7 @@ input_chars(char *buffer, int &result, int max_size) { // Define this macro carefully, since different flex versions call it // with a different type for result. #define YY_INPUT(buffer, result, max_size) { \ - int int_result; \ + int int_result = 0; \ input_chars((buffer), int_result, (max_size)); \ (result) = int_result; \ } diff --git a/pandatool/src/vrml/vrmlLexer.lxx b/pandatool/src/vrml/vrmlLexer.lxx index e8b1290615..6b03b79894 100644 --- a/pandatool/src/vrml/vrmlLexer.lxx +++ b/pandatool/src/vrml/vrmlLexer.lxx @@ -1,18 +1,15 @@ -/* -// Filename: vrmlLexer.lxx -// Created by: drose (01Oct04) -// -//////////////////////////////////////////////////////////////////// -// -// PANDA 3D SOFTWARE -// Copyright (c) Carnegie Mellon University. All rights reserved. -// -// All use of this software is subject to the terms of the revised BSD -// license. You should have received a copy of this license along -// with this source code in a file named "LICENSE." -// -//////////////////////////////////////////////////////////////////// -*/ +/** + * PANDA 3D SOFTWARE + * Copyright (c) Carnegie Mellon University. All rights reserved. + * + * All use of this software is subject to the terms of the revised BSD + * license. You should have received a copy of this license along + * with this source code in a file named "LICENSE." + * + * @file vrmlLexer.lxx + * @author drose + * @date 2004-10-01 + */ /************************************************** * VRML 2.0 Parser @@ -50,13 +47,13 @@ static int error_count = 0; static int warning_count = 0; // This is the pointer to the current input stream. -static istream *input_p = NULL; +static std::istream *input_p = nullptr; // This is the name of the vrml file we're parsing. We keep it so we // can print it out for error messages. -static string vrml_filename; +static std::string vrml_filename; -extern void vrmlyyerror(const string &); +extern void vrmlyyerror(const std::string &); /* The YACC parser sets this to a token to direct the lexer */ /* in cases where just syntax isn't enough: */ @@ -70,13 +67,13 @@ static int sfImageIntsParsed = 0; static int sfImageIntsExpected = 0; // This is used while scanning a quoted string. -static string quoted_string; +static std::string quoted_string; // And this keeps track of the currently-parsing array. static MFArray *mfarray; void -vrml_init_lexer(istream &in, const string &filename) { +vrml_init_lexer(std::istream &in, const std::string &filename) { input_p = ∈ vrml_filename = filename; line_number = 0; @@ -94,7 +91,9 @@ vrmlyywrap(void) { } void -vrmlyyerror(const string &msg) { +vrmlyyerror(const std::string &msg) { + using std::cerr; + cerr << "\nError"; if (!vrml_filename.empty()) { cerr << " in " << vrml_filename; @@ -107,7 +106,9 @@ vrmlyyerror(const string &msg) { } void -vrmlyywarning(const string &msg) { +vrmlyywarning(const std::string &msg) { + using std::cerr; + cerr << "\nWarning"; if (!vrml_filename.empty()) { cerr << " in " << vrml_filename; @@ -123,7 +124,7 @@ vrmlyywarning(const string &msg) { // stdio FILE pointer. This is flex-specific. static void input_chars(char *buffer, int &result, int max_size) { - nassertv(input_p != NULL); + nassertv(input_p != nullptr); if (*input_p) { input_p->read(buffer, max_size); result = input_p->gcount(); @@ -143,7 +144,7 @@ input_chars(char *buffer, int &result, int max_size) { // Truncate it at the newline. char *end = strchr(current_line, '\n'); - if (end != NULL) { + if (end != nullptr) { *end = '\0'; } } @@ -158,13 +159,13 @@ input_chars(char *buffer, int &result, int max_size) { // Define this macro carefully, since different flex versions call it // with a different type for result. #define YY_INPUT(buffer, result, max_size) { \ - int int_result; \ + int int_result = 0; \ input_chars((buffer), int_result, (max_size)); \ (result) = int_result; \ } int extract_int() { - return strtol(yytext, NULL, 0); + return strtol(yytext, nullptr, 0); } double extract_float() { @@ -275,7 +276,7 @@ idRestChar ([^\x00-\x20\x22\x23\x27\x2b-\x2c\x2e\x5b-\x5d\x7b\x7d]) TO { return TO; } IS { return IS; } ROUTE { return ROUTE; } -NULL { return SFN_NULL; } +nullptr { return SFN_NULL; } eventIn { return EVENTIN; } eventOut { return EVENTOUT; } field { return FIELD; } diff --git a/pandatool/src/vrml/vrmlLexerDefs.h b/pandatool/src/vrml/vrmlLexerDefs.h index f33a444fe4..5cbdc81b14 100644 --- a/pandatool/src/vrml/vrmlLexerDefs.h +++ b/pandatool/src/vrml/vrmlLexerDefs.h @@ -16,12 +16,12 @@ #include "pandatoolbase.h" -void vrml_init_lexer(istream &in, const string &filename); +void vrml_init_lexer(std::istream &in, const std::string &filename); int vrml_error_count(); int vrml_warning_count(); -void vrmlyyerror(const string &msg); -void vrmlyywarning(const string &msg); +void vrmlyyerror(const std::string &msg); +void vrmlyywarning(const std::string &msg); int vrmlyylex(); diff --git a/pandatool/src/vrml/vrmlNode.cxx b/pandatool/src/vrml/vrmlNode.cxx index d21061cd3a..c48ce35e4a 100644 --- a/pandatool/src/vrml/vrmlNode.cxx +++ b/pandatool/src/vrml/vrmlNode.cxx @@ -39,11 +39,11 @@ get_value(const char *field_name) const { // That field was not defined. Get the default value. const VrmlNodeType::NameTypeRec *field = _type->hasField(field_name); - if (field != NULL) { + if (field != nullptr) { return field->dflt; } - cerr << "No such field defined for type " << _type->getName() << ": " + std::cerr << "No such field defined for type " << _type->getName() << ": " << field_name << "\n"; exit(1); // Just to make the compiler happy. @@ -52,7 +52,7 @@ get_value(const char *field_name) const { } void VrmlNode:: -output(ostream &out, int indent_level) const { +output(std::ostream &out, int indent_level) const { out << _type->getName() << " {\n"; Fields::const_iterator fi; for (fi = _fields.begin(); fi != _fields.end(); ++fi) { @@ -64,13 +64,13 @@ output(ostream &out, int indent_level) const { void Declaration:: -output(ostream &out, int indent) const { +output(std::ostream &out, int indent) const { VrmlFieldValue v; v._sfnode = _node; output_value(out, v, SFNODE, indent); } -ostream &operator << (ostream &out, const VrmlScene &scene) { +std::ostream &operator << (std::ostream &out, const VrmlScene &scene) { VrmlScene::const_iterator si; for (si = scene.begin(); si != scene.end(); ++si) { out << (*si) << "\n"; diff --git a/pandatool/src/vrml/vrmlNode.h b/pandatool/src/vrml/vrmlNode.h index dad8a1bce1..648f477c90 100644 --- a/pandatool/src/vrml/vrmlNode.h +++ b/pandatool/src/vrml/vrmlNode.h @@ -27,7 +27,7 @@ public: const VrmlFieldValue &get_value(const char *field_name) const; - void output(ostream &out, int indent) const; + void output(std::ostream &out, int indent) const; class Field { public: @@ -38,7 +38,7 @@ public: VrmlFieldValue _value; }; - typedef vector Fields; + typedef std::vector Fields; Fields _fields; int _use_count; @@ -46,7 +46,7 @@ public: const VrmlNodeType *_type; }; -inline ostream &operator << (ostream &out, const VrmlNode &node) { +inline std::ostream &operator << (std::ostream &out, const VrmlNode &node) { node.output(out, 0); return out; } @@ -55,16 +55,16 @@ class Declaration { public: SFNodeRef _node; - void output(ostream &out, int indent) const; + void output(std::ostream &out, int indent) const; }; -inline ostream &operator << (ostream &out, const Declaration &dec) { +inline std::ostream &operator << (std::ostream &out, const Declaration &dec) { dec.output(out, 0); return out; } typedef pvector VrmlScene; -ostream &operator << (ostream &out, const VrmlScene &scene); +std::ostream &operator << (std::ostream &out, const VrmlScene &scene); #endif diff --git a/pandatool/src/vrml/vrmlNodeType.cxx b/pandatool/src/vrml/vrmlNodeType.cxx index bfe4faf349..56652507b5 100644 --- a/pandatool/src/vrml/vrmlNodeType.cxx +++ b/pandatool/src/vrml/vrmlNodeType.cxx @@ -20,6 +20,8 @@ #include // for sprintf() +using std::ostream; + // // Static list of node types. @@ -98,7 +100,7 @@ output_value(ostream &out, const VrmlFieldValue &value, int type, return out << "NULL"; case SFNodeRef::T_unnamed: - nassertr(value._sfnode._p != NULL, out); + nassertr(value._sfnode._p != nullptr, out); value._sfnode._p->output(out, indent); return out; @@ -145,7 +147,7 @@ output_value(ostream &out, const VrmlFieldValue &value, int type, VrmlNodeType::VrmlNodeType(const char *nm) { - nassertv(nm != NULL); + nassertv(nm != nullptr); name = strdup(nm); } @@ -176,9 +178,9 @@ VrmlNodeType::~VrmlNodeType() void VrmlNodeType::addToNameSpace(VrmlNodeType *_type) { - if (find(_type->getName()) != NULL) { - cerr << "PROTO " << _type->getName() << " already defined\n"; - return; + if (find(_type->getName()) != nullptr) { + std::cerr << "PROTO " << _type->getName() << " already defined\n"; + return; } typeList.push_front(_type); } @@ -191,7 +193,7 @@ VrmlNodeType::addToNameSpace(VrmlNodeType *_type) void VrmlNodeType::pushNameSpace() { - typeList.push_front(NULL); + typeList.push_front(nullptr); } void @@ -204,7 +206,7 @@ VrmlNodeType::popNameSpace() ++i; typeList.pop_front(); - if (nodeType == NULL) { + if (nodeType == nullptr) { break; } else { @@ -224,11 +226,11 @@ VrmlNodeType::find(const char *_name) plist::iterator i; for (i = typeList.begin(); i != typeList.end(); i++) { const VrmlNodeType *nt = *i; - if (nt != NULL && strcmp(nt->getName(),_name) == 0) { + if (nt != nullptr && strcmp(nt->getName(),_name) == 0) { return nt; } } - return NULL; + return nullptr; } void @@ -268,7 +270,7 @@ VrmlNodeType::add(plist &recs, const char *name, int type, NameTypeRec *r = new NameTypeRec; r->name = strdup(name); r->type = type; - if (dflt != NULL) { + if (dflt != nullptr) { r->dflt = *dflt; } else { memset(&r->dflt, 0, sizeof(r->dflt)); @@ -305,19 +307,19 @@ VrmlNodeType::hasExposedField(const char *name) const base = has(fields, name); sprintf(tmp, "set_%s\n", name); - nassertr(strlen(tmp) < 1000, NULL); + nassertr(strlen(tmp) < 1000, nullptr); set_name = has(eventIns, tmp); sprintf(tmp, "%s_changed\n", name); - nassertr(strlen(tmp) < 1000, NULL); + nassertr(strlen(tmp) < 1000, nullptr); name_changed = has(eventOuts, tmp); - if (base == NULL || set_name == NULL || name_changed == NULL) { - return NULL; + if (base == nullptr || set_name == nullptr || name_changed == nullptr) { + return nullptr; } if (base->type != set_name->type || base->type != name_changed->type) { - return NULL; + return nullptr; } return base; @@ -331,6 +333,6 @@ VrmlNodeType::has(const plist &recs, const char *name) const if (strcmp((*i)->name, name) == 0) return (*i); } - return NULL; + return nullptr; } diff --git a/pandatool/src/vrml/vrmlNodeType.h b/pandatool/src/vrml/vrmlNodeType.h index e455cf99ca..1852429ad1 100644 --- a/pandatool/src/vrml/vrmlNodeType.h +++ b/pandatool/src/vrml/vrmlNodeType.h @@ -42,7 +42,7 @@ union VrmlFieldValue { typedef pvector MFArray; -ostream &output_value(ostream &out, const VrmlFieldValue &value, int type, +std::ostream &output_value(std::ostream &out, const VrmlFieldValue &value, int type, int indent = 0); @@ -70,13 +70,13 @@ public: // Routines for adding/getting eventIns/Outs/fields void addEventIn(const char *name, int type, - const VrmlFieldValue *dflt = NULL); + const VrmlFieldValue *dflt = nullptr); void addEventOut(const char *name, int type, - const VrmlFieldValue *dflt = NULL); + const VrmlFieldValue *dflt = nullptr); void addField(const char *name, int type, - const VrmlFieldValue *dflt = NULL); + const VrmlFieldValue *dflt = nullptr); void addExposedField(const char *name, int type, - const VrmlFieldValue *dflt = NULL); + const VrmlFieldValue *dflt = nullptr); typedef struct { char *name; diff --git a/pandatool/src/vrml/vrmlParser.cxx.prebuilt b/pandatool/src/vrml/vrmlParser.cxx.prebuilt index fb95f8075f..b94bc8d5ae 100644 --- a/pandatool/src/vrml/vrmlParser.cxx.prebuilt +++ b/pandatool/src/vrml/vrmlParser.cxx.prebuilt @@ -106,7 +106,7 @@ // Currently-being-define proto. Prototypes may be nested, so a stack // is needed: -stack< VrmlNodeType*, plist > currentProtoStack; +std::stack > currentProtoStack; // This is used to keep track of which field in which type of node is being // parsed. Field are nested (nodes are contained inside MFNode/SFNode fields) @@ -117,12 +117,12 @@ typedef struct { const VrmlNodeType::NameTypeRec *typeRec; } FieldRec; -stack< FieldRec*, plist > currentField; +std::stack > currentField; // Similarly for the node entries (which contain the actual values for // the fields as they are encountered): -stack< VrmlNode*, plist > currentNode; +std::stack > currentNode; // This is used when the parser knows what kind of token it expects // to get next-- used when parsing field values (whose types are declared @@ -151,14 +151,14 @@ void storeField(const VrmlFieldValue &value); void exitField(); void expect(int type); -extern void vrmlyyerror(const string &); +extern void vrmlyyerror(const std::string &); //////////////////////////////////////////////////////////////////// // Defining the interface to the parser. //////////////////////////////////////////////////////////////////// void -vrml_init_parser(istream &in, const string &filename) { +vrml_init_parser(std::istream &in, const std::string &filename) { //yydebug = 0; vrml_init_lexer(in, filename); } @@ -2189,7 +2189,7 @@ endProto() // Add this proto definition: if (currentProtoStack.empty()) { - cerr << "Error: Empty PROTO stack!\n"; + std::cerr << "Error: Empty PROTO stack!\n"; } else { VrmlNodeType *t = currentProtoStack.top(); @@ -2232,14 +2232,14 @@ add(void (VrmlNodeType::*func)(const char *, int, const VrmlFieldValue *), int type = fieldType(typeString); if (type == 0) { - cerr << "Error: invalid field type: " << type << "\n"; + std::cerr << "Error: invalid field type: " << type << "\n"; } // Need to add support for Script nodes: // if (inScript) ... ??? if (currentProtoStack.empty()) { - cerr << "Error: declaration outside of prototype\n"; + std::cerr << "Error: declaration outside of prototype\n"; return 0; } VrmlNodeType *t = currentProtoStack.top(); @@ -2271,7 +2271,7 @@ fieldType(const char *type) if (strcmp(type, "MFVec2f") == 0) return MFVEC2F; if (strcmp(type, "MFVec3f") == 0) return MFVEC3F; - cerr << "Illegal field type: " << type << "\n"; + std::cerr << "Illegal field type: " << type << "\n"; return 0; } @@ -2306,7 +2306,7 @@ exitNode() nassertr(node != NULL, NULL); currentNode.pop(); - // cerr << "Just defined node:\n" << *node << "\n\n"; + // std::cerr << "Just defined node:\n" << *node << "\n\n"; delete fr; return node; @@ -2346,7 +2346,7 @@ enterField(const char *fieldName) expect(typeRec->type); } else { - cerr << "Error: Nodes of type " << fr->nodeType->getName() << + std::cerr << "Error: Nodes of type " << fr->nodeType->getName() << " do not have fields/eventIn/eventOut named " << fieldName << "\n"; // expect(ANY_FIELD); diff --git a/pandatool/src/vrml/vrmlParser.yxx b/pandatool/src/vrml/vrmlParser.yxx index 3404f8c3f8..9bbdda7bf6 100644 --- a/pandatool/src/vrml/vrmlParser.yxx +++ b/pandatool/src/vrml/vrmlParser.yxx @@ -49,7 +49,7 @@ // Currently-being-define proto. Prototypes may be nested, so a stack // is needed: -stack< VrmlNodeType*, plist > currentProtoStack; +std::stack > currentProtoStack; // This is used to keep track of which field in which type of node is being // parsed. Field are nested (nodes are contained inside MFNode/SFNode fields) @@ -60,12 +60,12 @@ typedef struct { const VrmlNodeType::NameTypeRec *typeRec; } FieldRec; -stack< FieldRec*, plist > currentField; +std::stack > currentField; // Similarly for the node entries (which contain the actual values for // the fields as they are encountered): -stack< VrmlNode*, plist > currentNode; +std::stack > currentNode; // This is used when the parser knows what kind of token it expects // to get next-- used when parsing field values (whose types are declared @@ -73,15 +73,15 @@ stack< VrmlNode*, plist > currentNode; extern int expectToken; // This is where we store the parsed scene. -VrmlScene *parsed_scene = NULL; +VrmlScene *parsed_scene = nullptr; // Some helper routines defined below: static void beginProto(const char *); static void endProto(); -int addField(const char *type, const char *name, const VrmlFieldValue *dflt = NULL); -int addEventIn(const char *type, const char *name, const VrmlFieldValue *dflt = NULL); -int addEventOut(const char *type, const char *name, const VrmlFieldValue *dflt = NULL); -int addExposedField(const char *type, const char *name, const VrmlFieldValue *dflt = NULL); +int addField(const char *type, const char *name, const VrmlFieldValue *dflt = nullptr); +int addEventIn(const char *type, const char *name, const VrmlFieldValue *dflt = nullptr); +int addEventOut(const char *type, const char *name, const VrmlFieldValue *dflt = nullptr); +int addExposedField(const char *type, const char *name, const VrmlFieldValue *dflt = nullptr); int add(void (VrmlNodeType::*func)(const char *, int, const VrmlFieldValue *), const char *typeString, const char *name, const VrmlFieldValue *dflt); @@ -94,14 +94,14 @@ void storeField(const VrmlFieldValue &value); void exitField(); void expect(int type); -extern void vrmlyyerror(const string &); +extern void vrmlyyerror(const std::string &); //////////////////////////////////////////////////////////////////// // Defining the interface to the parser. //////////////////////////////////////////////////////////////////// void -vrml_init_parser(istream &in, const string &filename) { +vrml_init_parser(std::istream &in, const std::string &filename) { //yydebug = 0; vrml_init_lexer(in, filename); } @@ -132,7 +132,7 @@ vrml_cleanup_parser() { * %type vrmlscene declarations */ -%token IDENTIFIER +%token IDENTIFIER %token DEF USE PROTO EXTERNPROTO TO IS ROUTE SFN_NULL %token EVENTIN EVENTOUT FIELD EXPOSEDFIELD @@ -170,7 +170,7 @@ nodeDeclaration: { $$._p = $1; $$._type = SFNodeRef::T_unnamed; - $$._name = NULL; + $$._name = nullptr; } | DEF IDENTIFIER node { @@ -180,7 +180,7 @@ nodeDeclaration: } | USE IDENTIFIER { - $$._p = NULL; + $$._p = nullptr; $$._type = SFNodeRef::T_use; $$._name = $2; } @@ -314,9 +314,9 @@ fieldValue: | SFNODE nodeDeclaration { $$._sfnode = $2; } | SFNODE SFN_NULL { - $$._sfnode._p = NULL; + $$._sfnode._p = nullptr; $$._sfnode._type = SFNodeRef::T_null; - $$._sfnode._name = NULL; + $$._sfnode._name = nullptr; } | MFNODE mfnodeValue { $$._mf = $2; } | IS IDENTIFIER { free($2); } @@ -370,7 +370,7 @@ endProto() // Add this proto definition: if (currentProtoStack.empty()) { - cerr << "Error: Empty PROTO stack!\n"; + std::cerr << "Error: Empty PROTO stack!\n"; } else { VrmlNodeType *t = currentProtoStack.top(); @@ -413,14 +413,14 @@ add(void (VrmlNodeType::*func)(const char *, int, const VrmlFieldValue *), int type = fieldType(typeString); if (type == 0) { - cerr << "Error: invalid field type: " << type << "\n"; + std::cerr << "Error: invalid field type: " << type << "\n"; } // Need to add support for Script nodes: // if (inScript) ... ??? if (currentProtoStack.empty()) { - cerr << "Error: declaration outside of prototype\n"; + std::cerr << "Error: declaration outside of prototype\n"; return 0; } VrmlNodeType *t = currentProtoStack.top(); @@ -452,7 +452,7 @@ fieldType(const char *type) if (strcmp(type, "MFVec2f") == 0) return MFVEC2F; if (strcmp(type, "MFVec3f") == 0) return MFVEC3F; - cerr << "Illegal field type: " << type << "\n"; + std::cerr << "Illegal field type: " << type << "\n"; return 0; } @@ -461,15 +461,15 @@ void enterNode(const char *nodeType) { const VrmlNodeType *t = VrmlNodeType::find(nodeType); - if (t == NULL) { + if (t == nullptr) { char tmp[1000]; sprintf(tmp, "Unknown node type '%s'", nodeType); vrmlyyerror(tmp); } FieldRec *fr = new FieldRec; fr->nodeType = t; - fr->fieldName = NULL; - fr->typeRec = NULL; + fr->fieldName = nullptr; + fr->typeRec = nullptr; currentField.push(fr); VrmlNode *node = new VrmlNode(t); @@ -480,14 +480,14 @@ VrmlNode * exitNode() { FieldRec *fr = currentField.top(); - nassertr(fr != NULL, NULL); + nassertr(fr != nullptr, nullptr); currentField.pop(); VrmlNode *node = currentNode.top(); - nassertr(node != NULL, NULL); + nassertr(node != nullptr, nullptr); currentNode.pop(); - // cerr << "Just defined node:\n" << *node << "\n\n"; + // std::cerr << "Just defined node:\n" << *node << "\n\n"; delete fr; return node; @@ -497,7 +497,7 @@ void inScript() { FieldRec *fr = currentField.top(); - if (fr->nodeType == NULL || + if (fr->nodeType == nullptr || strcmp(fr->nodeType->getName(), "Script") != 0) { vrmlyyerror("interface declaration outside of Script or prototype"); } @@ -507,11 +507,11 @@ void enterField(const char *fieldName) { FieldRec *fr = currentField.top(); - nassertv(fr != NULL); + nassertv(fr != nullptr); fr->fieldName = fieldName; - fr->typeRec = NULL; - if (fr->nodeType != NULL) { + fr->typeRec = nullptr; + if (fr->nodeType != nullptr) { // enterField is called when parsing eventIn and eventOut IS // declarations, in which case we don't need to do anything special-- // the IS IDENTIFIER will be returned from the lexer normally. @@ -521,13 +521,13 @@ enterField(const char *fieldName) const VrmlNodeType::NameTypeRec *typeRec = fr->nodeType->hasField(fieldName); - if (typeRec != NULL) { + if (typeRec != nullptr) { fr->typeRec = typeRec; // Let the lexer know what field type to expect: expect(typeRec->type); } else { - cerr << "Error: Nodes of type " << fr->nodeType->getName() << + std::cerr << "Error: Nodes of type " << fr->nodeType->getName() << " do not have fields/eventIn/eventOut named " << fieldName << "\n"; // expect(ANY_FIELD); @@ -539,12 +539,12 @@ enterField(const char *fieldName) void storeField(const VrmlFieldValue &value) { FieldRec *fr = currentField.top(); - nassertv(fr != NULL); + nassertv(fr != nullptr); VrmlNode *node = currentNode.top(); - nassertv(node != NULL); + nassertv(node != nullptr); - if (fr->typeRec != NULL) { + if (fr->typeRec != nullptr) { node->_fields.push_back(VrmlNode::Field(fr->typeRec, value)); } } @@ -553,10 +553,10 @@ void exitField() { FieldRec *fr = currentField.top(); - nassertv(fr != NULL); + nassertv(fr != nullptr); - fr->fieldName = NULL; - fr->typeRec = NULL; + fr->fieldName = nullptr; + fr->typeRec = nullptr; } void diff --git a/pandatool/src/vrml/vrmlParserDefs.h b/pandatool/src/vrml/vrmlParserDefs.h index 75464abd46..cad0d5b263 100644 --- a/pandatool/src/vrml/vrmlParserDefs.h +++ b/pandatool/src/vrml/vrmlParserDefs.h @@ -16,7 +16,7 @@ #include "pandatoolbase.h" -void vrml_init_parser(istream &in, const string &filename); +void vrml_init_parser(std::istream &in, const std::string &filename); void vrml_cleanup_parser(); int vrmlyyparse(); diff --git a/pandatool/src/vrmlegg/indexedFaceSet.cxx b/pandatool/src/vrmlegg/indexedFaceSet.cxx index 96b5cc9194..0f0dce8e68 100644 --- a/pandatool/src/vrmlegg/indexedFaceSet.cxx +++ b/pandatool/src/vrmlegg/indexedFaceSet.cxx @@ -22,6 +22,8 @@ #include "eggVertexPool.h" #include "eggPolygon.h" +using std::cerr; + /** * */ @@ -65,7 +67,7 @@ void IndexedFaceSet:: get_coord_values() { const VrmlNode *coord = _geometry->get_value("coord")._sfnode._p; - if (coord != NULL) { + if (coord != nullptr) { const MFArray *point = coord->get_value("point")._mf; MFArray::const_iterator ci; for (ci = point->begin(); ci != point->end(); ++ci) { @@ -153,7 +155,7 @@ get_vrml_uvs(const VrmlNode *texCoord_node, bool IndexedFaceSet:: get_colors() { const VrmlNode *color = _geometry->get_value("color")._sfnode._p; - if (color != NULL) { + if (color != nullptr) { // Vertex or face colors. pvector color_list; get_vrml_colors(color, _appearance._transparency, color_list); @@ -223,7 +225,7 @@ get_colors() { bool IndexedFaceSet:: get_normals() { const VrmlNode *normal = _geometry->get_value("normal")._sfnode._p; - if (normal != NULL) { + if (normal != nullptr) { // Vertex or face normals. pvector normal_list; get_vrml_normals(normal, normal_list); @@ -375,7 +377,7 @@ assign_per_vertex_normals() { bool IndexedFaceSet:: get_uvs() { const VrmlNode *texCoord = _geometry->get_value("texCoord")._sfnode._p; - if (texCoord != NULL) { + if (texCoord != nullptr) { // Vertex or face texCoords. pvector uv_list; get_vrml_uvs(texCoord, uv_list); @@ -496,7 +498,7 @@ make_polys(EggVertexPool *vpool, EggGroup *group, poly->set_color(_appearance._color); } - if (_appearance._tex != (EggTexture *)NULL) { + if (_appearance._tex != nullptr) { poly->set_texture(_appearance._tex); } @@ -535,7 +537,7 @@ make_polys(EggVertexPool *vpool, EggGroup *group, void IndexedFaceSet:: compute_normals(EggGroup *group) { const VrmlNode *normal = _geometry->get_value("normal")._sfnode._p; - if (normal == NULL) { + if (normal == nullptr) { // Compute normals. double creaseAngle = _geometry->get_value("creaseAngle")._sffloat; if (creaseAngle == 0.0) { diff --git a/pandatool/src/vrmlegg/vrmlAppearance.cxx b/pandatool/src/vrmlegg/vrmlAppearance.cxx index fff1ec48f2..06f9186c33 100644 --- a/pandatool/src/vrmlegg/vrmlAppearance.cxx +++ b/pandatool/src/vrmlegg/vrmlAppearance.cxx @@ -22,9 +22,9 @@ VRMLAppearance(const VrmlNode *appearance) { _color.set(1.0f, 1.0f, 1.0f, 1.0f); _has_tex_transform = false; - if (appearance != NULL) { + if (appearance != nullptr) { const VrmlNode *material = appearance->get_value("material")._sfnode._p; - if (material != NULL) { + if (material != nullptr) { _has_material = true; const double *c = material->get_value("diffuseColor")._sfvec; _transparency = material->get_value("transparency")._sffloat; @@ -32,7 +32,7 @@ VRMLAppearance(const VrmlNode *appearance) { } const VrmlNode *tex_transform = appearance->get_value("textureTransform")._sfnode._p; - if (tex_transform != NULL) { + if (tex_transform != nullptr) { if (strcmp(tex_transform->_type->getName(), "TextureTransform") == 0) { _has_tex_transform = true; const double *c = tex_transform->get_value("center")._sfvec; @@ -46,7 +46,7 @@ VRMLAppearance(const VrmlNode *appearance) { } const VrmlNode *texture = appearance->get_value("texture")._sfnode._p; - if (texture != NULL) { + if (texture != nullptr) { if (strcmp(texture->_type->getName(), "ImageTexture") == 0) { MFArray *url = texture->get_value("url")._mf; if (!url->empty()) { diff --git a/pandatool/src/vrmlegg/vrmlToEggConverter.cxx b/pandatool/src/vrmlegg/vrmlToEggConverter.cxx index 4083fb0847..d308e34714 100644 --- a/pandatool/src/vrmlegg/vrmlToEggConverter.cxx +++ b/pandatool/src/vrmlegg/vrmlToEggConverter.cxx @@ -57,7 +57,7 @@ make_copy() { /** * Returns the English name of the file type this converter supports. */ -string VRMLToEggConverter:: +std::string VRMLToEggConverter:: get_name() const { return "VRML"; } @@ -65,7 +65,7 @@ get_name() const { /** * Returns the common extension of the file type this converter supports. */ -string VRMLToEggConverter:: +std::string VRMLToEggConverter:: get_extension() const { return "wrl"; } @@ -88,7 +88,7 @@ convert_file(const Filename &filename) { clear_error(); VrmlScene *scene = parse_vrml(filename); - if (scene == (VrmlScene *)NULL) { + if (scene == nullptr) { return false; } @@ -127,8 +127,8 @@ get_all_defs(SFNodeRef &vrml, VRMLToEggConverter::Nodes &nodes) { switch (vrml._type) { case SFNodeRef::T_def: // If this is a node definition, add it to the map. - nassertv(vrml._name != NULL); - nassertv(vrml._p != NULL); + nassertv(vrml._name != nullptr); + nassertv(vrml._p != nullptr); /* This happens too often to bother yelling about it. ni = nodes.find(vrml._name); @@ -142,10 +142,10 @@ get_all_defs(SFNodeRef &vrml, VRMLToEggConverter::Nodes &nodes) { case SFNodeRef::T_use: // If it's a reference, resolve it. - nassertv(vrml._name != NULL); + nassertv(vrml._name != nullptr); ni = nodes.find(vrml._name); if (ni == nodes.end()) { - cerr << "Unknown node reference: " << vrml._name << "\n"; + std::cerr << "Unknown node reference: " << vrml._name << "\n"; } else { // Increment the use count of the node. (*ni).second->_use_count++; @@ -161,7 +161,7 @@ get_all_defs(SFNodeRef &vrml, VRMLToEggConverter::Nodes &nodes) { } VrmlNode *node = vrml._p; - if (node != NULL) { + if (node != nullptr) { VrmlNode::Fields::iterator fi; for (fi = node->_fields.begin(); fi != node->_fields.end(); ++fi) { if ((*fi)._type->type == SFNODE) { @@ -185,7 +185,7 @@ void VRMLToEggConverter:: vrml_node(const SFNodeRef &vrml, EggGroupNode *egg, const LMatrix4d &net_transform) { const VrmlNode *node = vrml._p; - if (node != NULL) { + if (node != nullptr) { // Now add it to the egg file at this point. if (strcmp(node->_type->getName(), "Group") == 0) { vrml_grouping_node(vrml, egg, net_transform, @@ -213,9 +213,9 @@ vrml_grouping_node(const SFNodeRef &vrml, EggGroupNode *egg, (const VrmlNode *node, EggGroup *group, const LMatrix4d &net_transform)) { const VrmlNode *node = vrml._p; - nassertv(node != NULL); - string name; - if (vrml._name != NULL) { + nassertv(node != nullptr); + std::string name; + if (vrml._name != nullptr) { name = vrml._name; } @@ -369,14 +369,14 @@ vrml_shape(const VrmlNode *node, EggGroup *group, const LMatrix4d &net_transform) { const VrmlNode *geometry = node->get_value("geometry")._sfnode._p; - if (geometry != NULL) { + if (geometry != nullptr) { VRMLAppearance appearance(node->get_value("appearance")._sfnode._p); if (strcmp(geometry->_type->getName(), "IndexedFaceSet") == 0) { IndexedFaceSet ifs(geometry, appearance); ifs.convert_to_egg(group, net_transform); } else { - cerr << "Ignoring " << geometry->_type->getName() << "\n"; + std::cerr << "Ignoring " << geometry->_type->getName() << "\n"; } } } diff --git a/pandatool/src/vrmlegg/vrmlToEggConverter.h b/pandatool/src/vrmlegg/vrmlToEggConverter.h index 612881d770..34a9b6843d 100644 --- a/pandatool/src/vrmlegg/vrmlToEggConverter.h +++ b/pandatool/src/vrmlegg/vrmlToEggConverter.h @@ -37,14 +37,14 @@ public: virtual SomethingToEggConverter *make_copy(); - virtual string get_name() const; - virtual string get_extension() const; + virtual std::string get_name() const; + virtual std::string get_extension() const; virtual bool supports_compressed() const; virtual bool convert_file(const Filename &filename); private: - typedef pmap Nodes; + typedef pmap Nodes; void get_all_defs(SFNodeRef &vrml, Nodes &nodes); void vrml_node(const SFNodeRef &vrml, EggGroupNode *egg, diff --git a/pandatool/src/vrmlprogs/vrmlTrans.cxx b/pandatool/src/vrmlprogs/vrmlTrans.cxx index e03075b0e5..48ed508b93 100644 --- a/pandatool/src/vrmlprogs/vrmlTrans.cxx +++ b/pandatool/src/vrmlprogs/vrmlTrans.cxx @@ -53,7 +53,7 @@ run() { nout << "Reading " << _input_filename << "\n"; VrmlScene *scene = parse_vrml(_input_filename); - if (scene == (VrmlScene *)NULL) { + if (scene == nullptr) { nout << "Unable to read.\n"; exit(1); } diff --git a/pandatool/src/win-stats/winStats.cxx b/pandatool/src/win-stats/winStats.cxx index 5c54535210..7818ea5ed8 100644 --- a/pandatool/src/win-stats/winStats.cxx +++ b/pandatool/src/win-stats/winStats.cxx @@ -19,7 +19,7 @@ #include static const char *toplevel_class_name = "pstats"; -static WinStatsServer *server = NULL; +static WinStatsServer *server = nullptr; /** * @@ -62,14 +62,14 @@ create_toplevel_window(HINSTANCE application) { DWORD window_style = WS_POPUP | WS_SYSMENU | WS_ICONIC; - ostringstream strm; + std::ostringstream strm; strm << "PStats " << pstats_port; - string window_name = strm.str(); + std::string window_name = strm.str(); HWND toplevel_window = CreateWindow(toplevel_class_name, window_name.c_str(), window_style, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, - NULL, NULL, application, 0); + nullptr, nullptr, application, 0); if (!toplevel_window) { nout << "Could not create toplevel window!\n"; exit(1); @@ -79,7 +79,7 @@ create_toplevel_window(HINSTANCE application) { } int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { - HINSTANCE application = GetModuleHandle(NULL); + HINSTANCE application = GetModuleHandle(nullptr); HWND toplevel_window = create_toplevel_window(application); ShowWindow(toplevel_window, SW_SHOWMINIMIZED); @@ -87,24 +87,24 @@ int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { // Create the server object. server = new WinStatsServer; if (!server->listen()) { - ostringstream stream; + std::ostringstream stream; stream << "Unable to open port " << pstats_port << ". Try specifying a different\n" << "port number using pstats-port in your Config file."; - string str = stream.str(); + std::string str = stream.str(); MessageBox(toplevel_window, str.c_str(), "PStats error", MB_OK | MB_ICONEXCLAMATION); exit(1); } // Set up a timer to poll the pstats every so often. - SetTimer(toplevel_window, 1, 200, NULL); + SetTimer(toplevel_window, 1, 200, nullptr); // Now get lost in the Windows message loop. MSG msg; int retval; - retval = GetMessage(&msg, NULL, 0, 0); + retval = GetMessage(&msg, nullptr, 0, 0); while (retval != 0) { if (retval == -1) { nout << "Error processing message queue.\n"; @@ -112,7 +112,7 @@ int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { } TranslateMessage(&msg); DispatchMessage(&msg); - retval = GetMessage(&msg, NULL, 0, 0); + retval = GetMessage(&msg, nullptr, 0, 0); } return (0); @@ -123,5 +123,5 @@ int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { // doesn't squelch the stderr output. int main(int argc, char *argv[]) { - return WinMain(NULL, NULL, NULL, 0); + return WinMain(nullptr, nullptr, nullptr, 0); } diff --git a/pandatool/src/win-stats/winStatsChartMenu.cxx b/pandatool/src/win-stats/winStatsChartMenu.cxx index faeb59d874..c042acf8ba 100644 --- a/pandatool/src/win-stats/winStatsChartMenu.cxx +++ b/pandatool/src/win-stats/winStatsChartMenu.cxx @@ -47,7 +47,7 @@ get_menu_handle() { void WinStatsChartMenu:: add_to_menu_bar(HMENU menu_bar, int before_menu_id) { const PStatClientData *client_data = _monitor->get_client_data(); - string thread_name; + std::string thread_name; if (_thread_index == 0) { // A special case for the main thread. thread_name = "Graphs"; @@ -149,7 +149,7 @@ add_view(HMENU parent_menu, const PStatViewLevel *view_level, bool show_level) { int collector = view_level->get_collector(); const PStatClientData *client_data = _monitor->get_client_data(); - string collector_name = client_data->get_collector_name(collector); + std::string collector_name = client_data->get_collector_name(collector); WinStatsMonitor::MenuDef menu_def(_thread_index, collector, show_level); int menu_id = _monitor->get_menu_id(menu_def); @@ -169,7 +169,7 @@ add_view(HMENU parent_menu, const PStatViewLevel *view_level, bool show_level) { // If the collector has more than one child, add a menu entry to go // directly to each of its children. HMENU submenu = CreatePopupMenu(); - string submenu_name = collector_name + " components"; + std::string submenu_name = collector_name + " components"; mii.fMask = MIIM_STRING | MIIM_FTYPE | MIIM_SUBMENU; mii.fType = MFT_STRING; diff --git a/pandatool/src/win-stats/winStatsGraph.cxx b/pandatool/src/win-stats/winStatsGraph.cxx index 393f905909..4946bbc671 100644 --- a/pandatool/src/win-stats/winStatsGraph.cxx +++ b/pandatool/src/win-stats/winStatsGraph.cxx @@ -30,8 +30,8 @@ WinStatsGraph(WinStatsMonitor *monitor) : { _window = 0; _graph_window = 0; - _sizewe_cursor = LoadCursor(NULL, IDC_SIZEWE); - _hand_cursor = LoadCursor(NULL, IDC_HAND); + _sizewe_cursor = LoadCursor(nullptr, IDC_SIZEWE); + _hand_cursor = LoadCursor(nullptr, IDC_HAND); _bitmap = 0; _bitmap_dc = 0; @@ -59,7 +59,7 @@ WinStatsGraph(WinStatsMonitor *monitor) : */ WinStatsGraph:: ~WinStatsGraph() { - _monitor = (WinStatsMonitor *)NULL; + _monitor = nullptr; release_bitmap(); DeleteObject(_dark_pen); @@ -142,8 +142,8 @@ set_pause(bool pause) { */ void WinStatsGraph:: user_guide_bars_changed() { - InvalidateRect(_window, NULL, TRUE); - InvalidateRect(_graph_window, NULL, TRUE); + InvalidateRect(_window, nullptr, TRUE); + InvalidateRect(_graph_window, nullptr, TRUE); } /** @@ -160,8 +160,8 @@ clicked_label(int collector_index) { void WinStatsGraph:: close() { WinStatsMonitor *monitor = _monitor; - _monitor = (WinStatsMonitor *)NULL; - if (monitor != (WinStatsMonitor *)NULL) { + _monitor = nullptr; + if (monitor != nullptr) { monitor->remove_graph(this); } } @@ -228,7 +228,7 @@ window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { case WM_SIZE: move_label_stack(); - InvalidateRect(hwnd, NULL, TRUE); + InvalidateRect(hwnd, nullptr, TRUE); break; case WM_SIZING: @@ -286,7 +286,7 @@ window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { int16_t x = LOWORD(lparam); _left_margin += (x - _drag_start_x); _drag_start_x = x; - InvalidateRect(hwnd, NULL, TRUE); + InvalidateRect(hwnd, nullptr, TRUE); move_label_stack(); return 0; @@ -294,7 +294,7 @@ window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { int16_t x = LOWORD(lparam); _right_margin += (_drag_start_x - x); _drag_start_x = x; - InvalidateRect(hwnd, NULL, TRUE); + InvalidateRect(hwnd, nullptr, TRUE); return 0; } break; @@ -467,8 +467,8 @@ move_graph_window(int graph_left, int graph_top, int graph_xsize, int graph_ysiz void WinStatsGraph:: setup_bitmap(int xsize, int ysize) { release_bitmap(); - _bitmap_xsize = max(xsize, 0); - _bitmap_ysize = max(ysize, 0); + _bitmap_xsize = std::max(xsize, 0); + _bitmap_ysize = std::max(ysize, 0); HDC hdc = GetDC(_graph_window); _bitmap_dc = CreateCompatibleDC(hdc); @@ -505,16 +505,16 @@ create_graph_window() { return; } - HINSTANCE application = GetModuleHandle(NULL); + HINSTANCE application = GetModuleHandle(nullptr); register_graph_window_class(application); - string window_title = "graph"; + std::string window_title = "graph"; DWORD window_style = WS_CHILD | WS_CLIPSIBLINGS; _graph_window = CreateWindow(_graph_window_class_name, window_title.c_str(), window_style, 0, 0, 0, 0, - _window, NULL, application, 0); + _window, nullptr, application, 0); if (!_graph_window) { nout << "Could not create graph window!\n"; exit(1); @@ -539,9 +539,9 @@ register_graph_window_class(HINSTANCE application) { wc.style = CS_DBLCLKS; wc.lpfnWndProc = (WNDPROC)static_graph_window_proc; wc.hInstance = application; - wc.hCursor = LoadCursor(NULL, IDC_ARROW); - wc.hbrBackground = NULL; - wc.lpszMenuName = NULL; + wc.hCursor = LoadCursor(nullptr, IDC_ARROW); + wc.hbrBackground = nullptr; + wc.lpszMenuName = nullptr; wc.lpszClassName = _graph_window_class_name; // Reserve space to associate the this pointer with the window. @@ -561,7 +561,7 @@ register_graph_window_class(HINSTANCE application) { LONG WINAPI WinStatsGraph:: static_graph_window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { WinStatsGraph *self = (WinStatsGraph *)GetWindowLongPtr(hwnd, 0); - if (self != (WinStatsGraph *)NULL && self->_graph_window == hwnd) { + if (self != nullptr && self->_graph_window == hwnd) { return self->graph_window_proc(hwnd, msg, wparam, lparam); } else { return DefWindowProc(hwnd, msg, wparam, lparam); diff --git a/pandatool/src/win-stats/winStatsLabel.cxx b/pandatool/src/win-stats/winStatsLabel.cxx index 3886cb8e15..5cd744c501 100644 --- a/pandatool/src/win-stats/winStatsLabel.cxx +++ b/pandatool/src/win-stats/winStatsLabel.cxx @@ -175,7 +175,7 @@ void WinStatsLabel:: set_highlight(bool highlight) { if (_highlight != highlight) { _highlight = highlight; - InvalidateRect(_window, NULL, TRUE); + InvalidateRect(_window, nullptr, TRUE); } } @@ -194,7 +194,7 @@ void WinStatsLabel:: set_mouse_within(bool mouse_within) { if (_mouse_within != mouse_within) { _mouse_within = mouse_within; - InvalidateRect(_window, NULL, TRUE); + InvalidateRect(_window, nullptr, TRUE); } } @@ -207,13 +207,13 @@ create_window(HWND parent_window) { return; } - HINSTANCE application = GetModuleHandle(NULL); + HINSTANCE application = GetModuleHandle(nullptr); register_window_class(application); _window = CreateWindow(_window_class_name, _text.c_str(), WS_CHILD | WS_CLIPSIBLINGS, 0, 0, 0, 0, - parent_window, NULL, application, 0); + parent_window, nullptr, application, 0); if (!_window) { nout << "Could not create Label window!\n"; exit(1); @@ -238,9 +238,9 @@ register_window_class(HINSTANCE application) { wc.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = (WNDPROC)static_window_proc; wc.hInstance = application; - wc.hCursor = LoadCursor(NULL, IDC_ARROW); - wc.hbrBackground = NULL; - wc.lpszMenuName = NULL; + wc.hCursor = LoadCursor(nullptr, IDC_ARROW); + wc.hbrBackground = nullptr; + wc.lpszMenuName = nullptr; wc.lpszClassName = _window_class_name; // Reserve space to associate the this pointer with the window. @@ -260,7 +260,7 @@ register_window_class(HINSTANCE application) { LONG WINAPI WinStatsLabel:: static_window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { WinStatsLabel *self = (WinStatsLabel *)GetWindowLongPtr(hwnd, 0); - if (self != (WinStatsLabel *)NULL && self->_window == hwnd) { + if (self != nullptr && self->_window == hwnd) { return self->window_proc(hwnd, msg, wparam, lparam); } else { return DefWindowProc(hwnd, msg, wparam, lparam); diff --git a/pandatool/src/win-stats/winStatsLabel.h b/pandatool/src/win-stats/winStatsLabel.h index 8c98f09f12..0317f0dcfb 100644 --- a/pandatool/src/win-stats/winStatsLabel.h +++ b/pandatool/src/win-stats/winStatsLabel.h @@ -59,7 +59,7 @@ private: WinStatsGraph *_graph; int _thread_index; int _collector_index; - string _text; + std::string _text; HWND _window; COLORREF _bg_color; COLORREF _fg_color; diff --git a/pandatool/src/win-stats/winStatsLabelStack.cxx b/pandatool/src/win-stats/winStatsLabelStack.cxx index c3d8404aa2..af3bcccd00 100644 --- a/pandatool/src/win-stats/winStatsLabelStack.cxx +++ b/pandatool/src/win-stats/winStatsLabelStack.cxx @@ -61,7 +61,7 @@ setup(HWND parent_window) { for (li = _labels.begin(); li != _labels.end(); ++li) { WinStatsLabel *label = (*li); label->setup(_window); - _ideal_width = max(_ideal_width, label->get_ideal_width()); + _ideal_width = std::max(_ideal_width, label->get_ideal_width()); } } @@ -192,7 +192,7 @@ add_label(WinStatsMonitor *monitor, WinStatsGraph *graph, label->setup(_window); label->set_pos(0, yp, _width); } - _ideal_width = max(_ideal_width, label->get_ideal_width()); + _ideal_width = std::max(_ideal_width, label->get_ideal_width()); int label_index = (int)_labels.size(); _labels.push_back(label); @@ -235,13 +235,13 @@ create_window(HWND parent_window) { return; } - HINSTANCE application = GetModuleHandle(NULL); + HINSTANCE application = GetModuleHandle(nullptr); register_window_class(application); _window = CreateWindow(_window_class_name, "label stack", WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 0, 0, 0, 0, - parent_window, NULL, application, 0); + parent_window, nullptr, application, 0); if (!_window) { nout << "Could not create Label Stack window!\n"; exit(1); @@ -266,8 +266,8 @@ register_window_class(HINSTANCE application) { wc.style = 0; wc.lpfnWndProc = (WNDPROC)static_window_proc; wc.hInstance = application; - wc.hCursor = LoadCursor(NULL, IDC_ARROW); - wc.lpszMenuName = NULL; + wc.hCursor = LoadCursor(nullptr, IDC_ARROW); + wc.lpszMenuName = nullptr; wc.lpszClassName = _window_class_name; // Reserve space to associate the this pointer with the window. @@ -287,7 +287,7 @@ register_window_class(HINSTANCE application) { LONG WINAPI WinStatsLabelStack:: static_window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { WinStatsLabelStack *self = (WinStatsLabelStack *)GetWindowLongPtr(hwnd, 0); - if (self != (WinStatsLabelStack *)NULL && self->_window == hwnd) { + if (self != nullptr && self->_window == hwnd) { return self->window_proc(hwnd, msg, wparam, lparam); } else { return DefWindowProc(hwnd, msg, wparam, lparam); diff --git a/pandatool/src/win-stats/winStatsMonitor.cxx b/pandatool/src/win-stats/winStatsMonitor.cxx index bb412050df..50c66362d1 100644 --- a/pandatool/src/win-stats/winStatsMonitor.cxx +++ b/pandatool/src/win-stats/winStatsMonitor.cxx @@ -71,7 +71,7 @@ WinStatsMonitor:: * Should be redefined to return a descriptive name for the type of * PStatsMonitor this is. */ -string WinStatsMonitor:: +std::string WinStatsMonitor:: get_monitor_name() { return "WinStats"; } @@ -107,7 +107,7 @@ got_hello() { void WinStatsMonitor:: got_bad_version(int client_major, int client_minor, int server_major, int server_minor) { - ostringstream str; + std::ostringstream str; str << "Unable to honor connection attempt from " << get_client_progname() << " on " << get_client_hostname() << ": unsupported PStats version " @@ -121,8 +121,8 @@ got_bad_version(int client_major, int client_minor, << ".0 through " << server_major << "." << server_minor << ")."; } - string message = str.str(); - MessageBox(NULL, message.c_str(), "Bad version", + std::string message = str.str(); + MessageBox(nullptr, message.c_str(), "Bad version", MB_OK | MB_ICONINFORMATION | MB_SETFOREGROUND); } @@ -438,7 +438,7 @@ create_window() { return; } - HINSTANCE application = GetModuleHandle(NULL); + HINSTANCE application = GetModuleHandle(nullptr); register_window_class(application); _menu_bar = CreateMenu(); @@ -459,7 +459,7 @@ create_window() { _window = CreateWindow(_window_class_name, _window_title.c_str(), window_style, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, - NULL, _menu_bar, application, 0); + nullptr, _menu_bar, application, 0); if (!_window) { nout << "Could not create monitor window!\n"; exit(1); @@ -497,8 +497,8 @@ setup_options_menu() { mii.fMask = MIIM_STRING | MIIM_FTYPE | MIIM_ID | MIIM_CHECKMARKS | MIIM_STATE; mii.fType = MFT_STRING | MFT_RADIOCHECK; - mii.hbmpChecked = NULL; - mii.hbmpUnchecked = NULL; + mii.hbmpChecked = nullptr; + mii.hbmpUnchecked = nullptr; mii.fState = MFS_UNCHECKED; mii.wID = MI_time_ms; mii.dwTypeData = "ms"; @@ -531,8 +531,8 @@ setup_speed_menu() { mii.fMask = MIIM_STRING | MIIM_FTYPE | MIIM_ID | MIIM_CHECKMARKS | MIIM_STATE; mii.fType = MFT_STRING | MFT_RADIOCHECK; - mii.hbmpChecked = NULL; - mii.hbmpUnchecked = NULL; + mii.hbmpChecked = nullptr; + mii.hbmpUnchecked = nullptr; mii.fState = MFS_UNCHECKED; mii.wID = MI_speed_1; mii.dwTypeData = "1"; @@ -603,9 +603,9 @@ register_window_class(HINSTANCE application) { wc.style = 0; wc.lpfnWndProc = (WNDPROC)static_window_proc; wc.hInstance = application; - wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.hCursor = LoadCursor(nullptr, IDC_ARROW); wc.hbrBackground = (HBRUSH)COLOR_BACKGROUND; - wc.lpszMenuName = NULL; + wc.lpszMenuName = nullptr; wc.lpszClassName = _window_class_name; // Reserve space to associate the this pointer with the window. @@ -625,7 +625,7 @@ register_window_class(HINSTANCE application) { LONG WINAPI WinStatsMonitor:: static_window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { WinStatsMonitor *self = (WinStatsMonitor *)GetWindowLongPtr(hwnd, 0); - if (self != (WinStatsMonitor *)NULL && self->_window == hwnd) { + if (self != nullptr && self->_window == hwnd) { return self->window_proc(hwnd, msg, wparam, lparam); } else { return DefWindowProc(hwnd, msg, wparam, lparam); diff --git a/pandatool/src/win-stats/winStatsMonitor.h b/pandatool/src/win-stats/winStatsMonitor.h index 8d4ccf473d..de74aa0d68 100644 --- a/pandatool/src/win-stats/winStatsMonitor.h +++ b/pandatool/src/win-stats/winStatsMonitor.h @@ -47,7 +47,7 @@ public: WinStatsMonitor(WinStatsServer *server); virtual ~WinStatsMonitor(); - virtual string get_monitor_name(); + virtual std::string get_monitor_name(); virtual void initialized(); virtual void got_hello(); @@ -102,7 +102,7 @@ private: HMENU _menu_bar; HMENU _options_menu; HMENU _speed_menu; - string _window_title; + std::string _window_title; int _time_units; double _scroll_speed; bool _pause; diff --git a/pandatool/src/win-stats/winStatsPianoRoll.cxx b/pandatool/src/win-stats/winStatsPianoRoll.cxx index ef61895a6c..859de11b68 100644 --- a/pandatool/src/win-stats/winStatsPianoRoll.cxx +++ b/pandatool/src/win-stats/winStatsPianoRoll.cxx @@ -171,7 +171,7 @@ draw_bar(int row, int from_x, int to_x) { */ void WinStatsPianoRoll:: end_draw() { - InvalidateRect(_graph_window, NULL, FALSE); + InvalidateRect(_graph_window, nullptr, FALSE); } /** @@ -443,7 +443,7 @@ draw_guide_bar(HDC hdc, const PStatGraph::GuideBar &bar) { SelectObject(hdc, _dark_pen); break; } - MoveToEx(hdc, x, 0, NULL); + MoveToEx(hdc, x, 0, nullptr); LineTo(hdc, x, get_ysize()); } } @@ -468,7 +468,7 @@ draw_guide_label(HDC hdc, int y, const PStatGraph::GuideBar &bar) { } int x = height_to_pixel(bar._height); - const string &label = bar._label; + const std::string &label = bar._label; SIZE size; GetTextExtentPoint32(hdc, label.data(), label.length(), &size); @@ -497,13 +497,13 @@ create_window() { return; } - HINSTANCE application = GetModuleHandle(NULL); + HINSTANCE application = GetModuleHandle(nullptr); register_window_class(application); const PStatClientData *client_data = WinStatsGraph::_monitor->get_client_data(); - string thread_name = client_data->get_thread_name(_thread_index); - string window_title = thread_name + " thread piano roll"; + std::string thread_name = client_data->get_thread_name(_thread_index); + std::string window_title = thread_name + " thread piano roll"; RECT win_rect = { @@ -520,7 +520,7 @@ create_window() { CW_USEDEFAULT, CW_USEDEFAULT, win_rect.right - win_rect.left, win_rect.bottom - win_rect.top, - WinStatsGraph::_monitor->get_window(), NULL, application, 0); + WinStatsGraph::_monitor->get_window(), nullptr, application, 0); if (!_window) { nout << "Could not create PianoRoll window!\n"; exit(1); @@ -550,9 +550,9 @@ register_window_class(HINSTANCE application) { wc.style = 0; wc.lpfnWndProc = (WNDPROC)static_window_proc; wc.hInstance = application; - wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.hCursor = LoadCursor(nullptr, IDC_ARROW); wc.hbrBackground = (HBRUSH)COLOR_BACKGROUND; - wc.lpszMenuName = NULL; + wc.lpszMenuName = nullptr; wc.lpszClassName = _window_class_name; // Reserve space to associate the this pointer with the window. @@ -572,7 +572,7 @@ register_window_class(HINSTANCE application) { LONG WINAPI WinStatsPianoRoll:: static_window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { WinStatsPianoRoll *self = (WinStatsPianoRoll *)GetWindowLongPtr(hwnd, 0); - if (self != (WinStatsPianoRoll *)NULL && self->_window == hwnd) { + if (self != nullptr && self->_window == hwnd) { return self->window_proc(hwnd, msg, wparam, lparam); } else { return DefWindowProc(hwnd, msg, wparam, lparam); diff --git a/pandatool/src/win-stats/winStatsStripChart.cxx b/pandatool/src/win-stats/winStatsStripChart.cxx index 066673aecd..879b920673 100644 --- a/pandatool/src/win-stats/winStatsStripChart.cxx +++ b/pandatool/src/win-stats/winStatsStripChart.cxx @@ -16,6 +16,8 @@ #include "pStatCollectorDef.h" #include "numeric_types.h" +using std::string; + static const int default_strip_chart_width = 400; static const int default_strip_chart_height = 100; @@ -246,7 +248,7 @@ copy_region(int start_x, int end_x, int dest_x) { // Also shift the brush origin over, so we still get proper dithering. _brush_origin += (dest_x - start_x); - SetBrushOrgEx(_bitmap_dc, _brush_origin, 0, NULL); + SetBrushOrgEx(_bitmap_dc, _brush_origin, 0, nullptr); RECT rect = { dest_x, 0, dest_x + end_x - start_x, get_ysize() @@ -596,7 +598,7 @@ move_graph_window(int graph_left, int graph_top, int graph_xsize, int graph_ysiz _left_margin, _top_margin - _check_box_height - 1, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_SHOWWINDOW); - InvalidateRect(_smooth_check_box, NULL, TRUE); + InvalidateRect(_smooth_check_box, nullptr, TRUE); } } @@ -623,7 +625,7 @@ draw_guide_bar(HDC hdc, int from_x, int to_x, SelectObject(hdc, _dark_pen); break; } - MoveToEx(hdc, from_x, y, NULL); + MoveToEx(hdc, from_x, y, nullptr); LineTo(hdc, to_x + 1, y); } } @@ -684,7 +686,7 @@ create_window() { return; } - HINSTANCE application = GetModuleHandle(NULL); + HINSTANCE application = GetModuleHandle(nullptr); register_window_class(application); string window_title = get_title_text(); @@ -703,7 +705,7 @@ create_window() { CW_USEDEFAULT, CW_USEDEFAULT, win_rect.right - win_rect.left, win_rect.bottom - win_rect.top, - WinStatsGraph::_monitor->get_window(), NULL, application, 0); + WinStatsGraph::_monitor->get_window(), nullptr, application, 0); if (!_window) { nout << "Could not create StripChart window!\n"; exit(1); @@ -716,7 +718,7 @@ create_window() { CreateWindow("BUTTON", "", WS_CHILD | BS_AUTOCHECKBOX, 0, 0, _check_box_width, _check_box_height, - _window, NULL, application, 0); + _window, nullptr, application, 0); // Ensure that the window is on top of the stack. SetWindowPos(_window, HWND_TOP, 0, 0, 0, 0, @@ -739,9 +741,9 @@ register_window_class(HINSTANCE application) { wc.style = 0; wc.lpfnWndProc = (WNDPROC)static_window_proc; wc.hInstance = application; - wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.hCursor = LoadCursor(nullptr, IDC_ARROW); wc.hbrBackground = (HBRUSH)COLOR_BACKGROUND; - wc.lpszMenuName = NULL; + wc.lpszMenuName = nullptr; wc.lpszClassName = _window_class_name; // Reserve space to associate the this pointer with the window. @@ -761,7 +763,7 @@ register_window_class(HINSTANCE application) { LONG WINAPI WinStatsStripChart:: static_window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { WinStatsStripChart *self = (WinStatsStripChart *)GetWindowLongPtr(hwnd, 0); - if (self != (WinStatsStripChart *)NULL && self->_window == hwnd) { + if (self != nullptr && self->_window == hwnd) { return self->window_proc(hwnd, msg, wparam, lparam); } else { return DefWindowProc(hwnd, msg, wparam, lparam); diff --git a/pandatool/src/win-stats/winStatsStripChart.h b/pandatool/src/win-stats/winStatsStripChart.h index 8ca08fee23..59953fbe8c 100644 --- a/pandatool/src/win-stats/winStatsStripChart.h +++ b/pandatool/src/win-stats/winStatsStripChart.h @@ -73,7 +73,7 @@ private: static LONG WINAPI static_window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam); int _brush_origin; - string _net_value_text; + std::string _net_value_text; HWND _smooth_check_box; static size_t _check_box_height, _check_box_width; diff --git a/pandatool/src/xfile/windowsGuid.I b/pandatool/src/xfile/windowsGuid.I index 95591161d0..5d0ce22046 100644 --- a/pandatool/src/xfile/windowsGuid.I +++ b/pandatool/src/xfile/windowsGuid.I @@ -91,8 +91,8 @@ compare_to(const WindowsGuid &other) const { return memcmp(this, &other, sizeof(WindowsGuid)); } -INLINE ostream & -operator << (ostream &out, const WindowsGuid &guid) { +INLINE std::ostream & +operator << (std::ostream &out, const WindowsGuid &guid) { guid.output(out); return out; } diff --git a/pandatool/src/xfile/windowsGuid.cxx b/pandatool/src/xfile/windowsGuid.cxx index 101e2b98cf..fbe649673c 100644 --- a/pandatool/src/xfile/windowsGuid.cxx +++ b/pandatool/src/xfile/windowsGuid.cxx @@ -16,6 +16,8 @@ #include // for sscanf, sprintf +using std::string; + /** * Parses the hex representation in the indicated string and stores it in the * WindowsGuid object. Returns true if successful, false if the string @@ -69,6 +71,6 @@ format_string() const { * Outputs a hex representation of the GUID. */ void WindowsGuid:: -output(ostream &out) const { +output(std::ostream &out) const { out << format_string(); } diff --git a/pandatool/src/xfile/windowsGuid.h b/pandatool/src/xfile/windowsGuid.h index 30296782f4..ea79d0be5a 100644 --- a/pandatool/src/xfile/windowsGuid.h +++ b/pandatool/src/xfile/windowsGuid.h @@ -39,10 +39,10 @@ public: INLINE bool operator < (const WindowsGuid &other) const; INLINE int compare_to(const WindowsGuid &other) const; - bool parse_string(const string &str); - string format_string() const; + bool parse_string(const std::string &str); + std::string format_string() const; - void output(ostream &out) const; + void output(std::ostream &out) const; private: unsigned long _data1; @@ -51,7 +51,7 @@ private: unsigned char _b1, _b2, _b3, _b4, _b5, _b6, _b7, _b8; }; -INLINE ostream &operator << (ostream &out, const WindowsGuid &guid); +INLINE std::ostream &operator << (std::ostream &out, const WindowsGuid &guid); #include "windowsGuid.I" diff --git a/pandatool/src/xfile/xFile.cxx b/pandatool/src/xfile/xFile.cxx index 26791ed403..c5534e0af1 100644 --- a/pandatool/src/xfile/xFile.cxx +++ b/pandatool/src/xfile/xFile.cxx @@ -22,6 +22,11 @@ #include "virtualFileSystem.h" #include "dcast.h" +using std::istream; +using std::istringstream; +using std::ostream; +using std::string; + TypeHandle XFile::_type_handle; PT(XFile) XFile::_standard_templates; @@ -69,7 +74,7 @@ read(Filename filename) { filename.set_text(); VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); istream *in = vfs->open_read_file(filename, true); - if (in == (istream *)NULL) { + if (in == nullptr) { xfile_cat.error() << "Cannot open " << filename << " for reading.\n"; return false; @@ -123,7 +128,7 @@ read(istream &in, const string &filename) { */ bool XFile:: write(Filename filename) const { - ofstream out; + std::ofstream out; // We actually open the file to write in binary mode, to avoid the MS-DOS // newline characters (since Windows seems to do this too). @@ -171,17 +176,17 @@ write(ostream &out) const { */ XFileTemplate *XFile:: find_template(const string &name) const { - XFileTemplate *standard = (XFileTemplate *)NULL; + XFileTemplate *standard = nullptr; const XFile *standard_templates = get_standard_templates(); if (standard_templates != this) { standard = standard_templates->find_template(name); } XFileNode *child = find_child(name); - if (child != (XFileNode *)NULL && + if (child != nullptr && child->is_of_type(XFileTemplate::get_class_type())) { XFileTemplate *xtemplate = DCAST(XFileTemplate, child); - if (standard != (XFileTemplate *)NULL && xtemplate->matches(standard)) { + if (standard != nullptr && xtemplate->matches(standard)) { // If the template matches a standard template, return the standard // instead. The assumption is that code may expect a certain naming // scheme for the data elements of the standard template, so we want to @@ -200,7 +205,7 @@ find_template(const string &name) const { */ XFileTemplate *XFile:: find_template(const WindowsGuid &guid) const { - XFileTemplate *standard = (XFileTemplate *)NULL; + XFileTemplate *standard = nullptr; const XFile *standard_templates = get_standard_templates(); if (standard_templates != this) { standard = standard_templates->find_template(guid); @@ -211,7 +216,7 @@ find_template(const WindowsGuid &guid) const { if (gi != _nodes_by_guid.end() && (*gi).second->is_of_type(XFileTemplate::get_class_type())) { XFileTemplate *xtemplate = DCAST(XFileTemplate, (*gi).second); - if (standard != (XFileTemplate *)NULL && xtemplate->matches(standard)) { + if (standard != nullptr && xtemplate->matches(standard)) { // If the template matches a standard template, return the standard // instead. The assumption is that code may expect a certain naming // scheme for the data elements of the standard template, so we want to @@ -251,12 +256,12 @@ find_standard_template(const WindowsGuid &guid) { XFileDataNodeTemplate *XFile:: find_data_object(const string &name) const { XFileNode *child = find_descendent(name); - if (child != (XFileNode *)NULL && + if (child != nullptr && child->is_of_type(XFileDataNodeTemplate::get_class_type())) { return DCAST(XFileDataNodeTemplate, child); } - return NULL; + return nullptr; } /** @@ -272,7 +277,7 @@ find_data_object(const WindowsGuid &guid) const { return DCAST(XFileDataNodeTemplate, (*gi).second); } - return NULL; + return nullptr; } /** @@ -438,7 +443,7 @@ write_header(ostream &out) const { */ const XFile *XFile:: get_standard_templates() { - if (_standard_templates == (XFile *)NULL) { + if (_standard_templates == nullptr) { // The standardTemplates.x file has been compiled into this binary. // Extract it out. diff --git a/pandatool/src/xfile/xFile.h b/pandatool/src/xfile/xFile.h index fa43e5ab77..c53bdd8313 100644 --- a/pandatool/src/xfile/xFile.h +++ b/pandatool/src/xfile/xFile.h @@ -37,21 +37,21 @@ public: virtual void clear(); bool read(Filename filename); - bool read(istream &in, const string &filename = string()); + bool read(std::istream &in, const std::string &filename = std::string()); bool write(Filename filename) const; - bool write(ostream &out) const; + bool write(std::ostream &out) const; - XFileTemplate *find_template(const string &name) const; + XFileTemplate *find_template(const std::string &name) const; XFileTemplate *find_template(const WindowsGuid &guid) const; - static XFileTemplate *find_standard_template(const string &name); + static XFileTemplate *find_standard_template(const std::string &name); static XFileTemplate *find_standard_template(const WindowsGuid &guid); - XFileDataNodeTemplate *find_data_object(const string &name) const; + XFileDataNodeTemplate *find_data_object(const std::string &name) const; XFileDataNodeTemplate *find_data_object(const WindowsGuid &guid) const; - virtual void write_text(ostream &out, int indent_level) const; + virtual void write_text(std::ostream &out, int indent_level) const; enum FormatType { FT_text, @@ -64,8 +64,8 @@ public: }; private: - bool read_header(istream &in); - bool write_header(ostream &out) const; + bool read_header(std::istream &in); + bool write_header(std::ostream &out) const; static const XFile *get_standard_templates(); diff --git a/pandatool/src/xfile/xFileArrayDef.I b/pandatool/src/xfile/xFileArrayDef.I index bb06c75fb8..f231f0c6ba 100644 --- a/pandatool/src/xfile/xFileArrayDef.I +++ b/pandatool/src/xfile/xFileArrayDef.I @@ -17,7 +17,7 @@ INLINE XFileArrayDef:: XFileArrayDef(int fixed_size) : _fixed_size(fixed_size), - _dynamic_size(NULL) + _dynamic_size(nullptr) { } @@ -37,7 +37,7 @@ XFileArrayDef(XFileDataDef *dynamic_size) : */ INLINE bool XFileArrayDef:: is_fixed_size() const { - return (_dynamic_size == (XFileDataDef *)NULL); + return (_dynamic_size == nullptr); } /** @@ -55,6 +55,6 @@ get_fixed_size() const { */ INLINE XFileDataDef *XFileArrayDef:: get_dynamic_size() const { - nassertr(!is_fixed_size(), NULL); + nassertr(!is_fixed_size(), nullptr); return _dynamic_size; } diff --git a/pandatool/src/xfile/xFileArrayDef.cxx b/pandatool/src/xfile/xFileArrayDef.cxx index 7bde81d7e0..91078f5576 100644 --- a/pandatool/src/xfile/xFileArrayDef.cxx +++ b/pandatool/src/xfile/xFileArrayDef.cxx @@ -29,7 +29,7 @@ get_size(const XFileNode::PrevData &prev_data) const { XFileNode::PrevData::const_iterator pi; pi = prev_data.find(_dynamic_size); nassertr_always(pi != prev_data.end(), 0); - nassertr((*pi).second != (XFileDataObject *)NULL, 0); + nassertr((*pi).second != nullptr, 0); return (*pi).second->i(); } } @@ -38,7 +38,7 @@ get_size(const XFileNode::PrevData &prev_data) const { * */ void XFileArrayDef:: -output(ostream &out) const { +output(std::ostream &out) const { if (is_fixed_size()) { out << "[" << _fixed_size << "]"; } else { diff --git a/pandatool/src/xfile/xFileArrayDef.h b/pandatool/src/xfile/xFileArrayDef.h index 2c8f79d443..5871e6e28c 100644 --- a/pandatool/src/xfile/xFileArrayDef.h +++ b/pandatool/src/xfile/xFileArrayDef.h @@ -34,7 +34,7 @@ public: int get_size(const XFileNode::PrevData &prev_data) const; - void output(ostream &out) const; + void output(std::ostream &out) const; bool matches(const XFileArrayDef &other, const XFileDataDef *parent, const XFileDataDef *other_parent) const; diff --git a/pandatool/src/xfile/xFileDataDef.I b/pandatool/src/xfile/xFileDataDef.I index 59dd89db50..65a7d9c36a 100644 --- a/pandatool/src/xfile/xFileDataDef.I +++ b/pandatool/src/xfile/xFileDataDef.I @@ -15,7 +15,7 @@ * */ INLINE XFileDataDef:: -XFileDataDef(XFile *x_file, const string &name, +XFileDataDef(XFile *x_file, const std::string &name, XFileDataDef::Type type, XFileTemplate *xtemplate) : XFileNode(x_file, name), _type(type), diff --git a/pandatool/src/xfile/xFileDataDef.cxx b/pandatool/src/xfile/xFileDataDef.cxx index 4e47187b6a..5fe983891b 100644 --- a/pandatool/src/xfile/xFileDataDef.cxx +++ b/pandatool/src/xfile/xFileDataDef.cxx @@ -53,7 +53,7 @@ add_array_def(const XFileArrayDef &array_def) { * Writes a suitable representation of this node to an .x file in text mode. */ void XFileDataDef:: -write_text(ostream &out, int indent_level) const { +write_text(std::ostream &out, int indent_level) const { indent(out, indent_level); if (!_array_def.empty()) { @@ -175,7 +175,7 @@ repack_data(XFileDataObject *object, break; } - if (data_value != (XFileDataObject *)NULL) { + if (data_value != nullptr) { object->add_element(data_value); prev_data[this] = data_value; } @@ -219,7 +219,7 @@ fill_zero_data(XFileDataObject *object) const { break; } - if (data_value != (XFileDataObject *)NULL) { + if (data_value != nullptr) { object->add_element(data_value); } @@ -270,13 +270,13 @@ PT(XFileDataObject) XFileDataDef:: unpack_integer_value(const XFileParseDataList &parse_data_list, const XFileDataDef::PrevData &prev_data, size_t &index, size_t &sub_index) const { - nassertr(index < parse_data_list._list.size(), NULL); + nassertr(index < parse_data_list._list.size(), nullptr); const XFileParseData &parse_data = parse_data_list._list[index]; PT(XFileDataObject) data_value; if ((parse_data._parse_flags & XFileParseData::PF_int) != 0) { - nassertr(sub_index < parse_data._int_list.size(), NULL); + nassertr(sub_index < parse_data._int_list.size(), nullptr); int value = parse_data._int_list[sub_index]; data_value = new XFileDataObjectInteger(this, value); @@ -301,13 +301,13 @@ PT(XFileDataObject) XFileDataDef:: unpack_double_value(const XFileParseDataList &parse_data_list, const XFileDataDef::PrevData &prev_data, size_t &index, size_t &sub_index) const { - nassertr(index < parse_data_list._list.size(), NULL); + nassertr(index < parse_data_list._list.size(), nullptr); const XFileParseData &parse_data = parse_data_list._list[index]; PT(XFileDataObject) data_value; if ((parse_data._parse_flags & XFileParseData::PF_double) != 0) { - nassertr(sub_index < parse_data._double_list.size(), NULL); + nassertr(sub_index < parse_data._double_list.size(), nullptr); double value = parse_data._double_list[sub_index]; data_value = new XFileDataObjectDouble(this, value); @@ -318,7 +318,7 @@ unpack_double_value(const XFileParseDataList &parse_data_list, } } else if ((parse_data._parse_flags & XFileParseData::PF_int) != 0) { - nassertr(sub_index < parse_data._int_list.size(), NULL); + nassertr(sub_index < parse_data._int_list.size(), nullptr); int value = parse_data._int_list[sub_index]; data_value = new XFileDataObjectDouble(this, value); @@ -343,7 +343,7 @@ PT(XFileDataObject) XFileDataDef:: unpack_string_value(const XFileParseDataList &parse_data_list, const XFileDataDef::PrevData &prev_data, size_t &index, size_t &sub_index) const { - nassertr(index < parse_data_list._list.size(), NULL); + nassertr(index < parse_data_list._list.size(), nullptr); const XFileParseData &parse_data = parse_data_list._list[index]; PT(XFileDataObject) data_value; @@ -373,10 +373,10 @@ unpack_template_value(const XFileParseDataList &parse_data_list, PrevData nested_prev_data(prev_data); if (!_template->repack_data(data_value, parse_data_list, nested_prev_data, index, sub_index)) { - return NULL; + return nullptr; } - return data_value.p(); + return data_value; } /** @@ -394,7 +394,7 @@ unpack_value(const XFileParseDataList &parse_data_list, int array_index, if (array_index == (int)_array_def.size()) { if (index >= parse_data_list._list.size()) { xyyerror("Not enough data elements in structure at " + get_name()); - return NULL; + return nullptr; } data_value = (this->*unpack_method)(parse_data_list, prev_data, index, sub_index); @@ -405,7 +405,7 @@ unpack_value(const XFileParseDataList &parse_data_list, int array_index, for (int i = 0; i < array_size; i++) { if (index >= parse_data_list._list.size()) { - xyyerror(string("Expected ") + format_string(array_size) + xyyerror(std::string("Expected ") + format_string(array_size) + " array elements, found " + format_string(i)); return data_value; } @@ -414,7 +414,7 @@ unpack_value(const XFileParseDataList &parse_data_list, int array_index, unpack_value(parse_data_list, array_index + 1, prev_data, index, sub_index, unpack_method); - if (array_element == (XFileDataObject *)NULL) { + if (array_element == nullptr) { return data_value; } data_value->add_element(array_element); @@ -456,7 +456,7 @@ zero_fill_template_value() const { PT(XFileDataObject) data_value = new XFileDataNodeTemplate(get_x_file(), get_name(), _template); if (!_template->fill_zero_data(data_value)) { - return NULL; + return nullptr; } return data_value; @@ -485,8 +485,8 @@ zero_fill_value(int array_index, for (int i = 0; i < array_size; i++) { PT(XFileDataObject) array_element = zero_fill_value(array_index + 1, zero_fill_method); - if (array_element == (XFileDataObject *)NULL) { - return NULL; + if (array_element == nullptr) { + return nullptr; } data_value->add_element(array_element); } diff --git a/pandatool/src/xfile/xFileDataDef.h b/pandatool/src/xfile/xFileDataDef.h index 7d489ceafd..3921619cdb 100644 --- a/pandatool/src/xfile/xFileDataDef.h +++ b/pandatool/src/xfile/xFileDataDef.h @@ -45,8 +45,8 @@ public: T_template, }; - INLINE XFileDataDef(XFile *x_file, const string &name, - Type type, XFileTemplate *xtemplate = NULL); + INLINE XFileDataDef(XFile *x_file, const std::string &name, + Type type, XFileTemplate *xtemplate = nullptr); virtual ~XFileDataDef(); virtual void clear(); @@ -58,7 +58,7 @@ public: INLINE int get_num_array_defs() const; INLINE const XFileArrayDef &get_array_def(int i) const; - virtual void write_text(ostream &out, int indent_level) const; + virtual void write_text(std::ostream &out, int indent_level) const; virtual bool repack_data(XFileDataObject *object, const XFileParseDataList &parse_data_list, diff --git a/pandatool/src/xfile/xFileDataNode.I b/pandatool/src/xfile/xFileDataNode.I index 23e63eb321..5591778ee6 100644 --- a/pandatool/src/xfile/xFileDataNode.I +++ b/pandatool/src/xfile/xFileDataNode.I @@ -39,7 +39,7 @@ get_template() const { * A convenience function to return the name of the template used to define * this data object. */ -INLINE const string &XFileDataNode:: +INLINE const std::string &XFileDataNode:: get_template_name() const { return _template->get_name(); } diff --git a/pandatool/src/xfile/xFileDataNode.cxx b/pandatool/src/xfile/xFileDataNode.cxx index d0ebb6dba8..bc1326697e 100644 --- a/pandatool/src/xfile/xFileDataNode.cxx +++ b/pandatool/src/xfile/xFileDataNode.cxx @@ -20,7 +20,7 @@ TypeHandle XFileDataNode::_type_handle; * */ XFileDataNode:: -XFileDataNode(XFile *x_file, const string &name, +XFileDataNode(XFile *x_file, const std::string &name, XFileTemplate *xtemplate) : XFileNode(x_file, name), _template(xtemplate) @@ -46,7 +46,7 @@ is_object() const { * object must be of type XFileDataNode. */ bool XFileDataNode:: -is_standard_object(const string &template_name) const { +is_standard_object(const std::string &template_name) const { if (_template->is_standard() && _template->get_name() == template_name) { return true; @@ -59,7 +59,7 @@ is_standard_object(const string &template_name) const { * Returns a string that represents the type of object this data object * represents. */ -string XFileDataNode:: +std::string XFileDataNode:: get_type_name() const { return _template->get_name(); } diff --git a/pandatool/src/xfile/xFileDataNode.h b/pandatool/src/xfile/xFileDataNode.h index 78bf6da05d..c04df4a3d1 100644 --- a/pandatool/src/xfile/xFileDataNode.h +++ b/pandatool/src/xfile/xFileDataNode.h @@ -32,17 +32,17 @@ */ class XFileDataNode : public XFileNode, public XFileDataObject { public: - XFileDataNode(XFile *x_file, const string &name, + XFileDataNode(XFile *x_file, const std::string &name, XFileTemplate *xtemplate); virtual bool is_object() const; - virtual bool is_standard_object(const string &template_name) const; - virtual string get_type_name() const; + virtual bool is_standard_object(const std::string &template_name) const; + virtual std::string get_type_name() const; INLINE const XFileDataNode &get_data_child(int n) const; INLINE XFileTemplate *get_template() const; - INLINE const string &get_template_name() const; + INLINE const std::string &get_template_name() const; protected: PT(XFileTemplate) _template; diff --git a/pandatool/src/xfile/xFileDataNodeReference.cxx b/pandatool/src/xfile/xFileDataNodeReference.cxx index 157acdbba6..7796aeeeda 100644 --- a/pandatool/src/xfile/xFileDataNodeReference.cxx +++ b/pandatool/src/xfile/xFileDataNodeReference.cxx @@ -62,7 +62,7 @@ is_complex_object() const { * Writes a suitable representation of this node to an .x file in text mode. */ void XFileDataNodeReference:: -write_text(ostream &out, int indent_level) const { +write_text(std::ostream &out, int indent_level) const { indent(out, indent_level) << "{ " << _object->get_name() << " }\n"; } @@ -89,6 +89,6 @@ get_element(int n) { * name. */ XFileDataObject *XFileDataNodeReference:: -get_element(const string &name) { +get_element(const std::string &name) { return &((*_object)[name]); } diff --git a/pandatool/src/xfile/xFileDataNodeReference.h b/pandatool/src/xfile/xFileDataNodeReference.h index 294b8a105d..f1e9eb4c80 100644 --- a/pandatool/src/xfile/xFileDataNodeReference.h +++ b/pandatool/src/xfile/xFileDataNodeReference.h @@ -36,12 +36,12 @@ public: virtual bool is_reference() const; virtual bool is_complex_object() const; - virtual void write_text(ostream &out, int indent_level) const; + virtual void write_text(std::ostream &out, int indent_level) const; protected: virtual int get_num_elements() const; virtual XFileDataObject *get_element(int n); - virtual XFileDataObject *get_element(const string &name); + virtual XFileDataObject *get_element(const std::string &name); private: PT(XFileDataNodeTemplate) _object; diff --git a/pandatool/src/xfile/xFileDataNodeTemplate.cxx b/pandatool/src/xfile/xFileDataNodeTemplate.cxx index 1e0e153438..6464716964 100644 --- a/pandatool/src/xfile/xFileDataNodeTemplate.cxx +++ b/pandatool/src/xfile/xFileDataNodeTemplate.cxx @@ -17,6 +17,8 @@ #include "xLexerDefs.h" #include "config_xfile.h" +using std::string; + TypeHandle XFileDataNodeTemplate::_type_handle; /** @@ -127,7 +129,7 @@ add_element(XFileDataObject *element) { * Writes a suitable representation of this node to an .x file in text mode. */ void XFileDataNodeTemplate:: -write_text(ostream &out, int indent_level) const { +write_text(std::ostream &out, int indent_level) const { indent(out, indent_level) << _template->get_name(); if (has_name()) { @@ -149,7 +151,7 @@ write_text(ostream &out, int indent_level) const { * Writes a suitable representation of this node to an .x file in text mode. */ void XFileDataNodeTemplate:: -write_data(ostream &out, int indent_level, const char *separator) const { +write_data(std::ostream &out, int indent_level, const char *separator) const { if (!_nested_elements.empty()) { bool indented = false; for (size_t i = 0; i < _nested_elements.size() - 1; i++) { @@ -205,7 +207,7 @@ get_num_elements() const { */ XFileDataObject *XFileDataNodeTemplate:: get_element(int n) { - nassertr(n >= 0 && n < (int)_nested_elements.size(), NULL); + nassertr(n >= 0 && n < (int)_nested_elements.size(), nullptr); return _nested_elements[n]; } @@ -222,5 +224,5 @@ get_element(const string &name) { xfile_cat.warning() << "\"" << name << "\" not a member of " << _template->get_name() << "\n"; - return NULL; + return nullptr; } diff --git a/pandatool/src/xfile/xFileDataNodeTemplate.h b/pandatool/src/xfile/xFileDataNodeTemplate.h index 32c3a74460..521c3752e2 100644 --- a/pandatool/src/xfile/xFileDataNodeTemplate.h +++ b/pandatool/src/xfile/xFileDataNodeTemplate.h @@ -29,7 +29,7 @@ */ class XFileDataNodeTemplate : public XFileDataNode { public: - XFileDataNodeTemplate(XFile *x_file, const string &name, + XFileDataNodeTemplate(XFile *x_file, const std::string &name, XFileTemplate *xtemplate); void zero_fill(); @@ -38,19 +38,19 @@ public: void add_parse_double(PTA_double double_list); void add_parse_int(PTA_int int_list); - void add_parse_string(const string &str); + void add_parse_string(const std::string &str); bool finalize_parse_data(); virtual bool add_element(XFileDataObject *element); - virtual void write_text(ostream &out, int indent_level) const; - virtual void write_data(ostream &out, int indent_level, + virtual void write_text(std::ostream &out, int indent_level) const; + virtual void write_data(std::ostream &out, int indent_level, const char *separator) const; protected: virtual int get_num_elements() const; virtual XFileDataObject *get_element(int n); - virtual XFileDataObject *get_element(const string &name); + virtual XFileDataObject *get_element(const std::string &name); private: XFileParseDataList _parse_data_list; diff --git a/pandatool/src/xfile/xFileDataObject.I b/pandatool/src/xfile/xFileDataObject.I index ebe25becc1..269bc0b0e9 100644 --- a/pandatool/src/xfile/xFileDataObject.I +++ b/pandatool/src/xfile/xFileDataObject.I @@ -55,7 +55,7 @@ operator = (double double_value) { * value. */ INLINE void XFileDataObject:: -operator = (const string &string_value) { +operator = (const std::string &string_value) { set(string_value); } @@ -125,7 +125,7 @@ set(double double_value) { * value. */ INLINE void XFileDataObject:: -set(const string &string_value) { +set(const std::string &string_value) { set_string_value(string_value); } @@ -194,7 +194,7 @@ d() const { * string if the object has no string representation. See also get_data_def() * to determine what kind of representation this object has. */ -INLINE string XFileDataObject:: +INLINE std::string XFileDataObject:: s() const { return get_string_value(); } @@ -258,7 +258,7 @@ size() const { INLINE const XFileDataObject &XFileDataObject:: operator [] (int n) const { const XFileDataObject *element = ((XFileDataObject *)this)->get_element(n); - nassertr(element != (XFileDataObject *)NULL, *this); + nassertr(element != nullptr, *this); return *element; } @@ -268,9 +268,9 @@ operator [] (int n) const { * doubt. */ INLINE const XFileDataObject &XFileDataObject:: -operator [] (const string &name) const { +operator [] (const std::string &name) const { const XFileDataObject *element = ((XFileDataObject *)this)->get_element(name); - nassertr(element != (XFileDataObject *)NULL, *this); + nassertr(element != nullptr, *this); return *element; } @@ -281,7 +281,7 @@ operator [] (const string &name) const { INLINE XFileDataObject &XFileDataObject:: operator [] (int n) { XFileDataObject *element = get_element(n); - nassertr(element != (XFileDataObject *)NULL, *this); + nassertr(element != nullptr, *this); return *element; } @@ -291,14 +291,14 @@ operator [] (int n) { * doubt. */ INLINE XFileDataObject &XFileDataObject:: -operator [] (const string &name) { +operator [] (const std::string &name) { XFileDataObject *element = get_element(name); - nassertr(element != (XFileDataObject *)NULL, *this); + nassertr(element != nullptr, *this); return *element; } -INLINE ostream & -operator << (ostream &out, const XFileDataObject &data_object) { +INLINE std::ostream & +operator << (std::ostream &out, const XFileDataObject &data_object) { data_object.output_data(out); return out; } diff --git a/pandatool/src/xfile/xFileDataObject.cxx b/pandatool/src/xfile/xFileDataObject.cxx index e170b901ea..f3cf0b0303 100644 --- a/pandatool/src/xfile/xFileDataObject.cxx +++ b/pandatool/src/xfile/xFileDataObject.cxx @@ -21,6 +21,8 @@ #include "config_xfile.h" #include "indent.h" +using std::string; + TypeHandle XFileDataObject::_type_handle; /** @@ -93,7 +95,7 @@ add_string(const string &string_value) { XFileDataObject &XFileDataObject:: add_Vector(XFile *x_file, const LVecBase3d &vector) { XFileTemplate *xtemplate = XFile::find_standard_template("Vector"); - nassertr(xtemplate != (XFileTemplate *)NULL, *this); + nassertr(xtemplate != nullptr, *this); XFileDataNodeTemplate *node = new XFileDataNodeTemplate(x_file, "", xtemplate); add_element(node); @@ -110,7 +112,7 @@ add_Vector(XFile *x_file, const LVecBase3d &vector) { XFileDataObject &XFileDataObject:: add_MeshFace(XFile *x_file) { XFileTemplate *xtemplate = XFile::find_standard_template("MeshFace"); - nassertr(xtemplate != (XFileTemplate *)NULL, *this); + nassertr(xtemplate != nullptr, *this); XFileDataNodeTemplate *node = new XFileDataNodeTemplate(x_file, "", xtemplate); add_element(node); @@ -125,7 +127,7 @@ add_MeshFace(XFile *x_file) { XFileDataObject &XFileDataObject:: add_IndexedColor(XFile *x_file, int index, const LColor &color) { XFileTemplate *xtemplate = XFile::find_standard_template("IndexedColor"); - nassertr(xtemplate != (XFileTemplate *)NULL, *this); + nassertr(xtemplate != nullptr, *this); XFileDataNodeTemplate *node = new XFileDataNodeTemplate(x_file, "", xtemplate); add_element(node); @@ -143,7 +145,7 @@ add_IndexedColor(XFile *x_file, int index, const LColor &color) { XFileDataObject &XFileDataObject:: add_Coords2d(XFile *x_file, const LVecBase2d &coords) { XFileTemplate *xtemplate = XFile::find_standard_template("Coords2d"); - nassertr(xtemplate != (XFileTemplate *)NULL, *this); + nassertr(xtemplate != nullptr, *this); XFileDataNodeTemplate *node = new XFileDataNodeTemplate(x_file, "", xtemplate); add_element(node); @@ -168,7 +170,7 @@ add_element(XFileDataObject *element) { * Writes a suitable representation of this node to an .x file in text mode. */ void XFileDataObject:: -output_data(ostream &out) const { +output_data(std::ostream &out) const { out << "(" << get_type() << "::output_data() not implemented.)"; } @@ -176,7 +178,7 @@ output_data(ostream &out) const { * Writes a suitable representation of this node to an .x file in text mode. */ void XFileDataObject:: -write_data(ostream &out, int indent_level, const char *) const { +write_data(std::ostream &out, int indent_level, const char *) const { indent(out, indent_level) << "(" << get_type() << "::write_data() not implemented.)\n"; } @@ -288,7 +290,7 @@ get_element(int n) { xfile_cat.warning() << "Looking for [" << n << "] within data object of type " << get_type_name() << ", does not support nested objects.\n"; - return NULL; + return nullptr; } /** @@ -300,5 +302,5 @@ get_element(const string &name) { xfile_cat.warning() << "Looking for [\"" << name << "\"] within data object of type " << get_type_name() << ", does not support nested objects.\n"; - return NULL; + return nullptr; } diff --git a/pandatool/src/xfile/xFileDataObject.h b/pandatool/src/xfile/xFileDataObject.h index ac7d8001f3..814d5f3c3f 100644 --- a/pandatool/src/xfile/xFileDataObject.h +++ b/pandatool/src/xfile/xFileDataObject.h @@ -29,17 +29,17 @@ class XFileDataDef; */ class XFileDataObject : virtual public ReferenceCount { public: - INLINE XFileDataObject(const XFileDataDef *data_def = NULL); + INLINE XFileDataObject(const XFileDataDef *data_def = nullptr); virtual ~XFileDataObject(); INLINE const XFileDataDef *get_data_def() const; virtual bool is_complex_object() const; - virtual string get_type_name() const; + virtual std::string get_type_name() const; INLINE void operator = (int int_value); INLINE void operator = (double double_value); - INLINE void operator = (const string &string_value); + INLINE void operator = (const std::string &string_value); INLINE void operator = (const LVecBase2d &vec); INLINE void operator = (const LVecBase3d &vec); INLINE void operator = (const LVecBase4d &vec); @@ -47,7 +47,7 @@ public: INLINE void set(int int_value); INLINE void set(double double_value); - INLINE void set(const string &string_value); + INLINE void set(const std::string &string_value); INLINE void set(const LVecBase2d &vec); INLINE void set(const LVecBase3d &vec); INLINE void set(const LVecBase4d &vec); @@ -55,7 +55,7 @@ public: INLINE int i() const; INLINE double d() const; - INLINE string s() const; + INLINE std::string s() const; INLINE LVecBase2d vec2() const; INLINE LVecBase3d vec3() const; INLINE LVecBase4d vec4() const; @@ -63,17 +63,17 @@ public: INLINE int size() const; INLINE const XFileDataObject &operator [] (int n) const; - INLINE const XFileDataObject &operator [] (const string &name) const; + INLINE const XFileDataObject &operator [] (const std::string &name) const; INLINE XFileDataObject &operator [] (int n); - INLINE XFileDataObject &operator [] (const string &name); + INLINE XFileDataObject &operator [] (const std::string &name); // The following methods can be used to add elements of a specific type to a // complex object, e.g. an array or a template object. XFileDataObject &add_int(int int_value); XFileDataObject &add_double(double double_value); - XFileDataObject &add_string(const string &string_value); + XFileDataObject &add_string(const std::string &string_value); // The following methods can be used to add elements of a specific type, // based on one of the standard templates. @@ -87,24 +87,24 @@ public: public: virtual bool add_element(XFileDataObject *element); - virtual void output_data(ostream &out) const; - virtual void write_data(ostream &out, int indent_level, + virtual void output_data(std::ostream &out) const; + virtual void write_data(std::ostream &out, int indent_level, const char *separator) const; protected: virtual void set_int_value(int int_value); virtual void set_double_value(double double_value); - virtual void set_string_value(const string &string_value); + virtual void set_string_value(const std::string &string_value); void store_double_array(int num_elements, const double *values); virtual int get_int_value() const; virtual double get_double_value() const; - virtual string get_string_value() const; + virtual std::string get_string_value() const; void get_double_array(int num_elements, double *values) const; virtual int get_num_elements() const; virtual XFileDataObject *get_element(int n); - virtual XFileDataObject *get_element(const string &name); + virtual XFileDataObject *get_element(const std::string &name); const XFileDataDef *_data_def; @@ -126,7 +126,7 @@ private: static TypeHandle _type_handle; }; -INLINE ostream &operator << (ostream &out, const XFileDataObject &data_object); +INLINE std::ostream &operator << (std::ostream &out, const XFileDataObject &data_object); #include "xFileDataObject.I" diff --git a/pandatool/src/xfile/xFileDataObjectArray.cxx b/pandatool/src/xfile/xFileDataObjectArray.cxx index 90d9948860..e648ef2c17 100644 --- a/pandatool/src/xfile/xFileDataObjectArray.cxx +++ b/pandatool/src/xfile/xFileDataObjectArray.cxx @@ -41,7 +41,7 @@ add_element(XFileDataObject *element) { * Writes a suitable representation of this node to an .x file in text mode. */ void XFileDataObjectArray:: -write_data(ostream &out, int indent_level, const char *separator) const { +write_data(std::ostream &out, int indent_level, const char *separator) const { if (!_nested_elements.empty()) { bool indented = false; for (size_t i = 0; i < _nested_elements.size() - 1; i++) { @@ -98,6 +98,6 @@ get_num_elements() const { */ XFileDataObject *XFileDataObjectArray:: get_element(int n) { - nassertr(n >= 0 && n < (int)_nested_elements.size(), NULL); + nassertr(n >= 0 && n < (int)_nested_elements.size(), nullptr); return _nested_elements[n]; } diff --git a/pandatool/src/xfile/xFileDataObjectArray.h b/pandatool/src/xfile/xFileDataObjectArray.h index e42df7845d..3b9000c9ee 100644 --- a/pandatool/src/xfile/xFileDataObjectArray.h +++ b/pandatool/src/xfile/xFileDataObjectArray.h @@ -28,7 +28,7 @@ public: virtual bool add_element(XFileDataObject *element); - virtual void write_data(ostream &out, int indent_level, + virtual void write_data(std::ostream &out, int indent_level, const char *separator) const; protected: diff --git a/pandatool/src/xfile/xFileDataObjectDouble.cxx b/pandatool/src/xfile/xFileDataObjectDouble.cxx index 3abd4fa909..d17b2bbb1e 100644 --- a/pandatool/src/xfile/xFileDataObjectDouble.cxx +++ b/pandatool/src/xfile/xFileDataObjectDouble.cxx @@ -31,7 +31,7 @@ XFileDataObjectDouble(const XFileDataDef *data_def, double value) : * Writes a suitable representation of this node to an .x file in text mode. */ void XFileDataObjectDouble:: -output_data(ostream &out) const { +output_data(std::ostream &out) const { out << get_string_value(); } @@ -39,7 +39,7 @@ output_data(ostream &out) const { * Writes a suitable representation of this node to an .x file in text mode. */ void XFileDataObjectDouble:: -write_data(ostream &out, int indent_level, const char *separator) const { +write_data(std::ostream &out, int indent_level, const char *separator) const { indent(out, indent_level) << get_string_value() << separator << "\n"; } @@ -79,7 +79,7 @@ get_double_value() const { /** * Returns the object's representation as a string, if it has one. */ -string XFileDataObjectDouble:: +std::string XFileDataObjectDouble:: get_string_value() const { // It's important to format with a decimal point, even if the value is // integral, since the DirectX .x reader differentiates betweens doubles and diff --git a/pandatool/src/xfile/xFileDataObjectDouble.h b/pandatool/src/xfile/xFileDataObjectDouble.h index afa20ee859..4450f45288 100644 --- a/pandatool/src/xfile/xFileDataObjectDouble.h +++ b/pandatool/src/xfile/xFileDataObjectDouble.h @@ -25,8 +25,8 @@ class XFileDataObjectDouble : public XFileDataObject { public: XFileDataObjectDouble(const XFileDataDef *data_def, double value); - virtual void output_data(ostream &out) const; - virtual void write_data(ostream &out, int indent_level, + virtual void output_data(std::ostream &out) const; + virtual void write_data(std::ostream &out, int indent_level, const char *separator) const; protected: @@ -35,7 +35,7 @@ protected: virtual int get_int_value() const; virtual double get_double_value() const; - virtual string get_string_value() const; + virtual std::string get_string_value() const; private: double _value; diff --git a/pandatool/src/xfile/xFileDataObjectInteger.cxx b/pandatool/src/xfile/xFileDataObjectInteger.cxx index 821363f339..ee3c539d68 100644 --- a/pandatool/src/xfile/xFileDataObjectInteger.cxx +++ b/pandatool/src/xfile/xFileDataObjectInteger.cxx @@ -31,7 +31,7 @@ XFileDataObjectInteger(const XFileDataDef *data_def, int value) : * Writes a suitable representation of this node to an .x file in text mode. */ void XFileDataObjectInteger:: -output_data(ostream &out) const { +output_data(std::ostream &out) const { out << _value; } @@ -39,7 +39,7 @@ output_data(ostream &out) const { * Writes a suitable representation of this node to an .x file in text mode. */ void XFileDataObjectInteger:: -write_data(ostream &out, int indent_level, const char *separator) const { +write_data(std::ostream &out, int indent_level, const char *separator) const { indent(out, indent_level) << _value << separator << "\n"; } @@ -71,7 +71,7 @@ get_double_value() const { /** * Returns the object's representation as a string, if it has one. */ -string XFileDataObjectInteger:: +std::string XFileDataObjectInteger:: get_string_value() const { return format_string(_value); } diff --git a/pandatool/src/xfile/xFileDataObjectInteger.h b/pandatool/src/xfile/xFileDataObjectInteger.h index 59e3ea13d3..b185ea9310 100644 --- a/pandatool/src/xfile/xFileDataObjectInteger.h +++ b/pandatool/src/xfile/xFileDataObjectInteger.h @@ -25,8 +25,8 @@ class XFileDataObjectInteger : public XFileDataObject { public: XFileDataObjectInteger(const XFileDataDef *data_def, int value); - virtual void output_data(ostream &out) const; - virtual void write_data(ostream &out, int indent_level, + virtual void output_data(std::ostream &out) const; + virtual void write_data(std::ostream &out, int indent_level, const char *separator) const; protected: @@ -34,7 +34,7 @@ protected: virtual int get_int_value() const; virtual double get_double_value() const; - virtual string get_string_value() const; + virtual std::string get_string_value() const; private: int _value; diff --git a/pandatool/src/xfile/xFileDataObjectString.cxx b/pandatool/src/xfile/xFileDataObjectString.cxx index 3425925b22..99ef31a89f 100644 --- a/pandatool/src/xfile/xFileDataObjectString.cxx +++ b/pandatool/src/xfile/xFileDataObjectString.cxx @@ -15,6 +15,8 @@ #include "string_utils.h" #include "indent.h" +using std::string; + TypeHandle XFileDataObjectString::_type_handle; /** @@ -31,7 +33,7 @@ XFileDataObjectString(const XFileDataDef *data_def, const string &value) : * Writes a suitable representation of this node to an .x file in text mode. */ void XFileDataObjectString:: -output_data(ostream &out) const { +output_data(std::ostream &out) const { enquote_string(out); } @@ -39,7 +41,7 @@ output_data(ostream &out) const { * Writes a suitable representation of this node to an .x file in text mode. */ void XFileDataObjectString:: -write_data(ostream &out, int indent_level, const char *separator) const { +write_data(std::ostream &out, int indent_level, const char *separator) const { indent(out, indent_level); enquote_string(out); out << separator << "\n"; @@ -66,7 +68,7 @@ get_string_value() const { * special characters as needed. */ void XFileDataObjectString:: -enquote_string(ostream &out) const { +enquote_string(std::ostream &out) const { // Actually, the XFile spec doesn't tell us how to escape special characters // within quotation marks. We'll just take a stab in the dark here. diff --git a/pandatool/src/xfile/xFileDataObjectString.h b/pandatool/src/xfile/xFileDataObjectString.h index 20dd503e06..1fd10dea2b 100644 --- a/pandatool/src/xfile/xFileDataObjectString.h +++ b/pandatool/src/xfile/xFileDataObjectString.h @@ -23,20 +23,20 @@ */ class XFileDataObjectString : public XFileDataObject { public: - XFileDataObjectString(const XFileDataDef *data_def, const string &value); + XFileDataObjectString(const XFileDataDef *data_def, const std::string &value); - virtual void output_data(ostream &out) const; - virtual void write_data(ostream &out, int indent_level, + virtual void output_data(std::ostream &out) const; + virtual void write_data(std::ostream &out, int indent_level, const char *separator) const; protected: - virtual void set_string_value(const string &string_value); - virtual string get_string_value() const; + virtual void set_string_value(const std::string &string_value); + virtual std::string get_string_value() const; private: - void enquote_string(ostream &out) const; + void enquote_string(std::ostream &out) const; - string _value; + std::string _value; public: static TypeHandle get_class_type() { diff --git a/pandatool/src/xfile/xFileNode.I b/pandatool/src/xfile/xFileNode.I index b23bea089d..6032a749e2 100644 --- a/pandatool/src/xfile/xFileNode.I +++ b/pandatool/src/xfile/xFileNode.I @@ -34,7 +34,7 @@ get_num_children() const { */ INLINE XFileNode *XFileNode:: get_child(int n) const { - nassertr(n >= 0 && n < (int)_children.size(), NULL); + nassertr(n >= 0 && n < (int)_children.size(), nullptr); return _children[n]; } @@ -55,6 +55,6 @@ get_num_objects() const { */ INLINE XFileDataNode *XFileNode:: get_object(int n) const { - nassertr(n >= 0 && n < (int)_objects.size(), NULL); + nassertr(n >= 0 && n < (int)_objects.size(), nullptr); return _objects[n]; } diff --git a/pandatool/src/xfile/xFileNode.cxx b/pandatool/src/xfile/xFileNode.cxx index 61d9d17d8f..51c795e42a 100644 --- a/pandatool/src/xfile/xFileNode.cxx +++ b/pandatool/src/xfile/xFileNode.cxx @@ -21,6 +21,8 @@ #include "filename.h" #include "string_utils.h" +using std::string; + TypeHandle XFileNode::_type_handle; /** @@ -57,7 +59,7 @@ find_child(const string &name) const { return get_child((*ni).second); } - return NULL; + return nullptr; } /** @@ -96,19 +98,19 @@ find_child_index(const XFileNode *child) const { XFileNode *XFileNode:: find_descendent(const string &name) const { XFileNode *child = find_child(name); - if (child != (XFileNode *)NULL) { + if (child != nullptr) { return child; } Children::const_iterator ci; for (ci = _children.begin(); ci != _children.end(); ++ci) { XFileNode *child = (*ci)->find_descendent(name); - if (child != (XFileNode *)NULL){ + if (child != nullptr){ return child; } } - return NULL; + return nullptr; } /** @@ -214,7 +216,7 @@ clear() { * Writes a suitable representation of this node to an .x file in text mode. */ void XFileNode:: -write_text(ostream &out, int indent_level) const { +write_text(std::ostream &out, int indent_level) const { Children::const_iterator ci; for (ci = _children.begin(); ci != _children.end(); ++ci) { (*ci)->write_text(out, indent_level); @@ -297,7 +299,7 @@ matches(const XFileNode *other) const { XFileDataNode *XFileNode:: add_Mesh(const string &name) { XFileTemplate *xtemplate = XFile::find_standard_template("Mesh"); - nassertr(xtemplate != (XFileTemplate *)NULL, NULL); + nassertr(xtemplate != nullptr, nullptr); XFileDataNodeTemplate *node = new XFileDataNodeTemplate(get_x_file(), name, xtemplate); add_child(node); @@ -312,7 +314,7 @@ add_Mesh(const string &name) { XFileDataNode *XFileNode:: add_MeshNormals(const string &name) { XFileTemplate *xtemplate = XFile::find_standard_template("MeshNormals"); - nassertr(xtemplate != (XFileTemplate *)NULL, NULL); + nassertr(xtemplate != nullptr, nullptr); XFileDataNodeTemplate *node = new XFileDataNodeTemplate(get_x_file(), name, xtemplate); add_child(node); @@ -327,7 +329,7 @@ add_MeshNormals(const string &name) { XFileDataNode *XFileNode:: add_MeshVertexColors(const string &name) { XFileTemplate *xtemplate = XFile::find_standard_template("MeshVertexColors"); - nassertr(xtemplate != (XFileTemplate *)NULL, NULL); + nassertr(xtemplate != nullptr, nullptr); XFileDataNodeTemplate *node = new XFileDataNodeTemplate(get_x_file(), name, xtemplate); add_child(node); @@ -342,7 +344,7 @@ add_MeshVertexColors(const string &name) { XFileDataNode *XFileNode:: add_MeshTextureCoords(const string &name) { XFileTemplate *xtemplate = XFile::find_standard_template("MeshTextureCoords"); - nassertr(xtemplate != (XFileTemplate *)NULL, NULL); + nassertr(xtemplate != nullptr, nullptr); XFileDataNodeTemplate *node = new XFileDataNodeTemplate(get_x_file(), name, xtemplate); add_child(node); @@ -357,7 +359,7 @@ add_MeshTextureCoords(const string &name) { XFileDataNode *XFileNode:: add_MeshMaterialList(const string &name) { XFileTemplate *xtemplate = XFile::find_standard_template("MeshMaterialList"); - nassertr(xtemplate != (XFileTemplate *)NULL, NULL); + nassertr(xtemplate != nullptr, nullptr); XFileDataNodeTemplate *node = new XFileDataNodeTemplate(get_x_file(), name, xtemplate); add_child(node); @@ -374,7 +376,7 @@ add_Material(const string &name, const LColor &face_color, double power, const LRGBColor &specular_color, const LRGBColor &emissive_color) { XFileTemplate *xtemplate = XFile::find_standard_template("Material"); - nassertr(xtemplate != (XFileTemplate *)NULL, NULL); + nassertr(xtemplate != nullptr, nullptr); XFileDataNodeTemplate *node = new XFileDataNodeTemplate(get_x_file(), name, xtemplate); add_child(node); @@ -401,7 +403,7 @@ add_Material(const string &name, const LColor &face_color, XFileDataNode *XFileNode:: add_TextureFilename(const string &name, const Filename &filename) { XFileTemplate *xtemplate = XFile::find_standard_template("TextureFilename"); - nassertr(xtemplate != (XFileTemplate *)NULL, NULL); + nassertr(xtemplate != nullptr, nullptr); XFileDataNodeTemplate *node = new XFileDataNodeTemplate(get_x_file(), name, xtemplate); add_child(node); @@ -418,7 +420,7 @@ add_TextureFilename(const string &name, const Filename &filename) { XFileDataNode *XFileNode:: add_Frame(const string &name) { XFileTemplate *xtemplate = XFile::find_standard_template("Frame"); - nassertr(xtemplate != (XFileTemplate *)NULL, NULL); + nassertr(xtemplate != nullptr, nullptr); XFileDataNodeTemplate *node = new XFileDataNodeTemplate(get_x_file(), name, xtemplate); add_child(node); @@ -434,7 +436,7 @@ XFileDataNode *XFileNode:: add_FrameTransformMatrix(const LMatrix4d &mat) { XFileTemplate *xtemplate = XFile::find_standard_template("FrameTransformMatrix"); - nassertr(xtemplate != (XFileTemplate *)NULL, NULL); + nassertr(xtemplate != nullptr, nullptr); XFileDataNodeTemplate *node = new XFileDataNodeTemplate(get_x_file(), "", xtemplate); add_child(node); diff --git a/pandatool/src/xfile/xFileNode.h b/pandatool/src/xfile/xFileNode.h index 89ab1a1ba8..a954b8f9fd 100644 --- a/pandatool/src/xfile/xFileNode.h +++ b/pandatool/src/xfile/xFileNode.h @@ -39,17 +39,17 @@ class Filename; class XFileNode : public TypedObject, public Namable, virtual public ReferenceCount { public: - XFileNode(XFile *x_file, const string &name); + XFileNode(XFile *x_file, const std::string &name); virtual ~XFileNode(); INLINE XFile *get_x_file() const; INLINE int get_num_children() const; INLINE XFileNode *get_child(int n) const; - XFileNode *find_child(const string &name) const; - int find_child_index(const string &name) const; + XFileNode *find_child(const std::string &name) const; + int find_child_index(const std::string &name) const; int find_child_index(const XFileNode *child) const; - XFileNode *find_descendent(const string &name) const; + XFileNode *find_descendent(const std::string &name) const; INLINE int get_num_objects() const; INLINE XFileDataNode *get_object(int n) const; @@ -60,12 +60,12 @@ public: virtual bool is_template_def() const; virtual bool is_reference() const; virtual bool is_object() const; - virtual bool is_standard_object(const string &template_name) const; + virtual bool is_standard_object(const std::string &template_name) const; void add_child(XFileNode *node); virtual void clear(); - virtual void write_text(ostream &out, int indent_level) const; + virtual void write_text(std::ostream &out, int indent_level) const; typedef pmap PrevData; @@ -81,21 +81,21 @@ public: // The following methods can be used to create instances of the standard // template objects. These definitions match those defined in // standardTemplates.x in this directory (and compiled into the executable). - XFileDataNode *add_Mesh(const string &name); - XFileDataNode *add_MeshNormals(const string &name); - XFileDataNode *add_MeshVertexColors(const string &name); - XFileDataNode *add_MeshTextureCoords(const string &name); - XFileDataNode *add_MeshMaterialList(const string &name); - XFileDataNode *add_Material(const string &name, const LColor &face_color, + XFileDataNode *add_Mesh(const std::string &name); + XFileDataNode *add_MeshNormals(const std::string &name); + XFileDataNode *add_MeshVertexColors(const std::string &name); + XFileDataNode *add_MeshTextureCoords(const std::string &name); + XFileDataNode *add_MeshMaterialList(const std::string &name); + XFileDataNode *add_Material(const std::string &name, const LColor &face_color, double power, const LRGBColor &specular_color, const LRGBColor &emissive_color); - XFileDataNode *add_TextureFilename(const string &name, + XFileDataNode *add_TextureFilename(const std::string &name, const Filename &filename); - XFileDataNode *add_Frame(const string &name); + XFileDataNode *add_Frame(const std::string &name); XFileDataNode *add_FrameTransformMatrix(const LMatrix4d &mat); public: - static string make_nice_name(const string &str); + static std::string make_nice_name(const std::string &str); protected: XFile *_x_file; @@ -106,7 +106,7 @@ protected: typedef pvector Objects; Objects _objects; - typedef pmap ChildrenByName; + typedef pmap ChildrenByName; ChildrenByName _children_by_name; public: diff --git a/pandatool/src/xfile/xFileParseData.cxx b/pandatool/src/xfile/xFileParseData.cxx index aeafa42a6f..0fcd8dbef9 100644 --- a/pandatool/src/xfile/xFileParseData.cxx +++ b/pandatool/src/xfile/xFileParseData.cxx @@ -34,6 +34,6 @@ XFileParseData() : * from which this object was originally parsed. */ void XFileParseData:: -yyerror(const string &message) const { +yyerror(const std::string &message) const { xyyerror(message, _line_number, _col_number, _current_line); } diff --git a/pandatool/src/xfile/xFileParseData.h b/pandatool/src/xfile/xFileParseData.h index c31089274b..2e7ef8dbc0 100644 --- a/pandatool/src/xfile/xFileParseData.h +++ b/pandatool/src/xfile/xFileParseData.h @@ -31,7 +31,7 @@ class XFileParseData { public: XFileParseData(); - void yyerror(const string &message) const; + void yyerror(const std::string &message) const; enum ParseFlags { PF_object = 0x001, @@ -45,12 +45,12 @@ public: PT(XFileDataObject) _object; PTA_double _double_list; PTA_int _int_list; - string _string; + std::string _string; int _parse_flags; int _line_number; int _col_number; - string _current_line; + std::string _current_line; }; /** diff --git a/pandatool/src/xfile/xFileTemplate.I b/pandatool/src/xfile/xFileTemplate.I index 3d7e52ec61..d56ff28984 100644 --- a/pandatool/src/xfile/xFileTemplate.I +++ b/pandatool/src/xfile/xFileTemplate.I @@ -65,6 +65,6 @@ get_num_options() const { */ INLINE XFileTemplate *XFileTemplate:: get_option(int n) const { - nassertr(n >= 0 && n < (int)_options.size(), NULL); + nassertr(n >= 0 && n < (int)_options.size(), nullptr); return _options[n]; } diff --git a/pandatool/src/xfile/xFileTemplate.cxx b/pandatool/src/xfile/xFileTemplate.cxx index 5c9691d02a..e4ef5e2c17 100644 --- a/pandatool/src/xfile/xFileTemplate.cxx +++ b/pandatool/src/xfile/xFileTemplate.cxx @@ -20,7 +20,7 @@ TypeHandle XFileTemplate::_type_handle; * */ XFileTemplate:: -XFileTemplate(XFile *x_file, const string &name, const WindowsGuid &guid) : +XFileTemplate(XFile *x_file, const std::string &name, const WindowsGuid &guid) : XFileNode(x_file, name), _guid(guid), _is_standard(false), @@ -79,7 +79,7 @@ clear() { * Writes a suitable representation of this node to an .x file in text mode. */ void XFileTemplate:: -write_text(ostream &out, int indent_level) const { +write_text(std::ostream &out, int indent_level) const { indent(out, indent_level) << "template " << get_name() << " {\n"; indent(out, indent_level + 2) diff --git a/pandatool/src/xfile/xFileTemplate.h b/pandatool/src/xfile/xFileTemplate.h index 2f4770c66a..5acc117072 100644 --- a/pandatool/src/xfile/xFileTemplate.h +++ b/pandatool/src/xfile/xFileTemplate.h @@ -26,7 +26,7 @@ class XFileDataDef; */ class XFileTemplate : public XFileNode { public: - XFileTemplate(XFile *x_file, const string &name, const WindowsGuid &guid); + XFileTemplate(XFile *x_file, const std::string &name, const WindowsGuid &guid); virtual ~XFileTemplate(); virtual bool has_guid() const; @@ -35,7 +35,7 @@ public: virtual bool is_template_def() const; virtual void clear(); - virtual void write_text(ostream &out, int indent_level) const; + virtual void write_text(std::ostream &out, int indent_level) const; INLINE bool is_standard() const; diff --git a/pandatool/src/xfile/xLexer.cxx.prebuilt b/pandatool/src/xfile/xLexer.cxx.prebuilt index a52c858c96..92eb941a15 100644 --- a/pandatool/src/xfile/xLexer.cxx.prebuilt +++ b/pandatool/src/xfile/xLexer.cxx.prebuilt @@ -643,12 +643,11 @@ goto find_rule; \ #define YY_RESTORE_YY_MORE_OFFSET char *xyytext; #line 1 "xLexer.lxx" -/* -// Filename: xLexer.lxx -// Created by: drose (03Oct04) -// -//////////////////////////////////////////////////////////////////// -*/ +/** + * @file xLexer.lxx + * @author drose + * @date 2004-10-03 + */ #line 9 "xLexer.lxx" #include "xLexerDefs.h" #include "xParserDefs.h" @@ -678,11 +677,11 @@ static int error_count = 0; static int warning_count = 0; // This is the pointer to the current input stream. -static istream *input_p = NULL; +static std::istream *input_p = nullptr; // This is the name of the x file we're parsing. We keep it so we // can print it out for error messages. -static string x_filename; +static std::string x_filename; //////////////////////////////////////////////////////////////////// @@ -690,7 +689,7 @@ static string x_filename; //////////////////////////////////////////////////////////////////// void -x_init_lexer(istream &in, const string &filename) { +x_init_lexer(std::istream &in, const std::string &filename) { input_p = ∈ x_filename = filename; x_line_number = 0; @@ -720,13 +719,13 @@ xyywrap(void) { } void -xyyerror(const string &msg) { +xyyerror(const std::string &msg) { xyyerror(msg, x_line_number, x_col_number, x_current_line); } void -xyyerror(const string &msg, int line_number, int col_number, - const string ¤t_line) { +xyyerror(const std::string &msg, int line_number, int col_number, + const std::string ¤t_line) { xfile_cat.error(false) << "\nError"; if (!x_filename.empty()) { xfile_cat.error(false) << " in " << x_filename; @@ -741,7 +740,7 @@ xyyerror(const string &msg, int line_number, int col_number, } void -xyywarning(const string &msg) { +xyywarning(const std::string &msg) { xfile_cat.warning(false) << "\nWarning"; if (!x_filename.empty()) { xfile_cat.warning(false) << " in " << x_filename; @@ -795,7 +794,7 @@ input_chars(char *buffer, int &result, int max_size) { // Define this macro carefully, since different flex versions call it // with a different type for result. #define YY_INPUT(buffer, result, max_size) { \ - int int_result; \ + int int_result = 0; \ input_chars((buffer), int_result, (max_size)); \ (result) = int_result; \ } @@ -817,9 +816,9 @@ read_char(int &line, int &col) { // scan_quoted_string reads a string delimited by quotation marks and // returns it. -static string +static std::string scan_quoted_string(char quote_mark) { - string result; + std::string result; // We don't touch the current line number and column number during // scanning, so that if we detect an error while scanning the string @@ -939,7 +938,7 @@ scan_quoted_string(char quote_mark) { // scan_guid_string reads a string of hexadecimal digits delimited by // angle brackets and returns the corresponding string. -static string +static std::string scan_guid_string() { // We don't touch the current line number and column number during // scanning, so that if we detect an error while scanning the string @@ -956,7 +955,7 @@ scan_guid_string() { int num_digits = 0; int num_hyphens = 0; - string result; + std::string result; int c; c = read_char(line, col); @@ -971,7 +970,7 @@ scan_guid_string() { x_line_number = line; x_col_number = col; xyyerror("Invalid character in GUID."); - return string(); + return std::string(); } result += c; @@ -981,15 +980,15 @@ scan_guid_string() { if (c == EOF) { xyyerror("This GUID string is unterminated."); - return string(); + return std::string(); } else if (num_digits != 32) { xyyerror("Incorrect number of hex digits in GUID."); - return string(); + return std::string(); } else if (num_hyphens != 4) { xyyerror("Incorrect number of hyphens in GUID."); - return string(); + return std::string(); } x_line_number = line; @@ -1000,7 +999,7 @@ scan_guid_string() { // Parses the text into a list of integers and returns them. static PTA_int -scan_int_list(const string &text) { +scan_int_list(const std::string &text) { PTA_int result; vector_string words; @@ -1008,7 +1007,7 @@ scan_int_list(const string &text) { vector_string::const_iterator wi; for (wi = words.begin(); wi != words.end(); ++wi) { - string trimmed = trim(*wi); + std::string trimmed = trim(*wi); if (!trimmed.empty()) { int number = 0; string_to_int(trimmed, number); @@ -1021,7 +1020,7 @@ scan_int_list(const string &text) { // Parses the text into a list of doubles and returns them. static PTA_double -scan_double_list(const string &text) { +scan_double_list(const std::string &text) { PTA_double result; vector_string words; @@ -1029,7 +1028,7 @@ scan_double_list(const string &text) { vector_string::const_iterator wi; for (wi = words.begin(); wi != words.end(); ++wi) { - string trimmed = trim(*wi); + std::string trimmed = trim(*wi); if (!trimmed.empty()) { double number = 0.0; string_to_double(trimmed, number); @@ -1655,7 +1654,7 @@ YY_RULE_SETUP { // Any other character is invalid. accept(); - xyyerror("Invalid character '" + string(xyytext) + "'."); + xyyerror("Invalid character '" + std::string(xyytext) + "'."); } YY_BREAK case 35: diff --git a/pandatool/src/xfile/xLexer.lxx b/pandatool/src/xfile/xLexer.lxx index e3d72709b0..7a5aac98a1 100644 --- a/pandatool/src/xfile/xLexer.lxx +++ b/pandatool/src/xfile/xLexer.lxx @@ -1,9 +1,8 @@ -/* -// Filename: xLexer.lxx -// Created by: drose (03Oct04) -// -//////////////////////////////////////////////////////////////////// -*/ +/** + * @file xLexer.lxx + * @author drose + * @date 2004-10-03 + */ %{ #include "xLexerDefs.h" @@ -34,11 +33,11 @@ static int error_count = 0; static int warning_count = 0; // This is the pointer to the current input stream. -static istream *input_p = NULL; +static std::istream *input_p = nullptr; // This is the name of the x file we're parsing. We keep it so we // can print it out for error messages. -static string x_filename; +static std::string x_filename; //////////////////////////////////////////////////////////////////// @@ -46,7 +45,7 @@ static string x_filename; //////////////////////////////////////////////////////////////////// void -x_init_lexer(istream &in, const string &filename) { +x_init_lexer(std::istream &in, const std::string &filename) { input_p = ∈ x_filename = filename; x_line_number = 0; @@ -76,13 +75,13 @@ xyywrap(void) { } void -xyyerror(const string &msg) { +xyyerror(const std::string &msg) { xyyerror(msg, x_line_number, x_col_number, x_current_line); } void -xyyerror(const string &msg, int line_number, int col_number, - const string ¤t_line) { +xyyerror(const std::string &msg, int line_number, int col_number, + const std::string ¤t_line) { xfile_cat.error(false) << "\nError"; if (!x_filename.empty()) { xfile_cat.error(false) << " in " << x_filename; @@ -97,7 +96,7 @@ xyyerror(const string &msg, int line_number, int col_number, } void -xyywarning(const string &msg) { +xyywarning(const std::string &msg) { xfile_cat.warning(false) << "\nWarning"; if (!x_filename.empty()) { xfile_cat.warning(false) << " in " << x_filename; @@ -115,7 +114,7 @@ xyywarning(const string &msg) { // stdio FILE pointer. This is flex-specific. static void input_chars(char *buffer, int &result, int max_size) { - nassertv(input_p != NULL); + nassertv(input_p != nullptr); if (*input_p) { input_p->read(buffer, max_size); result = input_p->gcount(); @@ -136,7 +135,7 @@ input_chars(char *buffer, int &result, int max_size) { // Truncate it at the newline. char *end = strchr(x_current_line, '\n'); - if (end != NULL) { + if (end != nullptr) { *end = '\0'; } } @@ -151,7 +150,7 @@ input_chars(char *buffer, int &result, int max_size) { // Define this macro carefully, since different flex versions call it // with a different type for result. #define YY_INPUT(buffer, result, max_size) { \ - int int_result; \ + int int_result = 0; \ input_chars((buffer), int_result, (max_size)); \ (result) = int_result; \ } @@ -173,9 +172,9 @@ read_char(int &line, int &col) { // scan_quoted_string reads a string delimited by quotation marks and // returns it. -static string +static std::string scan_quoted_string(char quote_mark) { - string result; + std::string result; // We don't touch the current line number and column number during // scanning, so that if we detect an error while scanning the string @@ -295,7 +294,7 @@ scan_quoted_string(char quote_mark) { // scan_guid_string reads a string of hexadecimal digits delimited by // angle brackets and returns the corresponding string. -static string +static std::string scan_guid_string() { // We don't touch the current line number and column number during // scanning, so that if we detect an error while scanning the string @@ -312,7 +311,7 @@ scan_guid_string() { int num_digits = 0; int num_hyphens = 0; - string result; + std::string result; int c; c = read_char(line, col); @@ -327,7 +326,7 @@ scan_guid_string() { x_line_number = line; x_col_number = col; xyyerror("Invalid character in GUID."); - return string(); + return std::string(); } result += c; @@ -337,15 +336,15 @@ scan_guid_string() { if (c == EOF) { xyyerror("This GUID string is unterminated."); - return string(); + return std::string(); } else if (num_digits != 32) { xyyerror("Incorrect number of hex digits in GUID."); - return string(); + return std::string(); } else if (num_hyphens != 4) { xyyerror("Incorrect number of hyphens in GUID."); - return string(); + return std::string(); } x_line_number = line; @@ -356,7 +355,7 @@ scan_guid_string() { // Parses the text into a list of integers and returns them. static PTA_int -scan_int_list(const string &text) { +scan_int_list(const std::string &text) { PTA_int result; vector_string words; @@ -364,7 +363,7 @@ scan_int_list(const string &text) { vector_string::const_iterator wi; for (wi = words.begin(); wi != words.end(); ++wi) { - string trimmed = trim(*wi); + std::string trimmed = trim(*wi); if (!trimmed.empty()) { int number = 0; string_to_int(trimmed, number); @@ -377,7 +376,7 @@ scan_int_list(const string &text) { // Parses the text into a list of doubles and returns them. static PTA_double -scan_double_list(const string &text) { +scan_double_list(const std::string &text) { PTA_double result; vector_string words; @@ -385,7 +384,7 @@ scan_double_list(const string &text) { vector_string::const_iterator wi; for (wi = words.begin(); wi != words.end(); ++wi) { - string trimmed = trim(*wi); + std::string trimmed = trim(*wi); if (!trimmed.empty()) { double number = 0.0; string_to_double(trimmed, number); @@ -621,5 +620,5 @@ WHITESPACE [ ]+ . { // Any other character is invalid. accept(); - xyyerror("Invalid character '" + string(xyytext) + "'."); + xyyerror("Invalid character '" + std::string(xyytext) + "'."); } diff --git a/pandatool/src/xfile/xLexerDefs.h b/pandatool/src/xfile/xLexerDefs.h index eb600edb32..c256cd0d05 100644 --- a/pandatool/src/xfile/xLexerDefs.h +++ b/pandatool/src/xfile/xLexerDefs.h @@ -16,14 +16,14 @@ #include "pandatoolbase.h" -void x_init_lexer(istream &in, const string &filename); +void x_init_lexer(std::istream &in, const std::string &filename); int x_error_count(); int x_warning_count(); -void xyyerror(const string &msg); -void xyyerror(const string &msg, int line_number, int col_number, - const string ¤t_line); -void xyywarning(const string &msg); +void xyyerror(const std::string &msg); +void xyyerror(const std::string &msg, int line_number, int col_number, + const std::string ¤t_line); +void xyywarning(const std::string &msg); int xyylex(); diff --git a/pandatool/src/xfile/xParser.cxx.prebuilt b/pandatool/src/xfile/xParser.cxx.prebuilt index 42c65a72a6..0d12c68d03 100644 --- a/pandatool/src/xfile/xParser.cxx.prebuilt +++ b/pandatool/src/xfile/xParser.cxx.prebuilt @@ -105,7 +105,7 @@ static PT(XFileDataDef) current_data_def; //////////////////////////////////////////////////////////////////// void -x_init_parser(istream &in, const string &filename, XFile &file) { +x_init_parser(std::istream &in, const std::string &filename, XFile &file) { x_file = &file; current_node = &file; x_init_lexer(in, filename); @@ -1803,7 +1803,7 @@ yyreduce: /* Line 1464 of yacc.c */ #line 325 "xParser.yxx" { - (yyval.str) = string(); + (yyval.str) = std::string(); } break; diff --git a/pandatool/src/xfile/xParser.yxx b/pandatool/src/xfile/xParser.yxx index a98f39d177..0352a4d454 100644 --- a/pandatool/src/xfile/xParser.yxx +++ b/pandatool/src/xfile/xParser.yxx @@ -30,8 +30,8 @@ #define YYINITDEPTH 1000 #define YYMAXDEPTH 1000 -static XFile *x_file = (XFile *)NULL; -static XFileNode *current_node = (XFileNode *)NULL; +static XFile *x_file = nullptr; +static XFileNode *current_node = nullptr; static PT(XFileDataDef) current_data_def; //////////////////////////////////////////////////////////////////// @@ -39,7 +39,7 @@ static PT(XFileDataDef) current_data_def; //////////////////////////////////////////////////////////////////// void -x_init_parser(istream &in, const string &filename, XFile &file) { +x_init_parser(std::istream &in, const std::string &filename, XFile &file) { x_file = &file; current_node = &file; x_init_lexer(in, filename); @@ -47,8 +47,8 @@ x_init_parser(istream &in, const string &filename, XFile &file) { void x_cleanup_parser() { - x_file = (XFile *)NULL; - current_node = (XFileNode *)NULL; + x_file = nullptr; + current_node = nullptr; } %} @@ -172,7 +172,7 @@ template_reference: singleword_name optional_multiword_name TOKEN_SEMICOLON { XFileTemplate *xtemplate = x_file->find_template($1); - if (xtemplate == (XFileTemplate *)NULL) { + if (xtemplate == nullptr) { yyerror("Unknown template: " + $1); } else { current_data_def = new XFileDataDef(x_file, $2, XFileDataDef::T_template, xtemplate); @@ -237,7 +237,7 @@ array_data_type: | singleword_name multiword_name { XFileTemplate *xtemplate = x_file->find_template($1); - if (xtemplate == (XFileTemplate *)NULL) { + if (xtemplate == nullptr) { yyerror("Unknown template: " + $1); } else { current_data_def = new XFileDataDef(x_file, $2, XFileDataDef::T_template, xtemplate); @@ -263,7 +263,7 @@ dimension_size: | multiword_name { XFileNode *data_def = current_node->find_child($1); - if (data_def == (XFileNode *)NULL) { + if (data_def == nullptr) { yyerror("Unknown identifier: " + $1); } else { current_data_def->add_array_def(XFileArrayDef(DCAST(XFileDataDef, data_def))); @@ -284,7 +284,7 @@ template_option_part: singleword_name { XFileTemplate *xtemplate = x_file->find_template($1); - if (xtemplate == (XFileTemplate *)NULL) { + if (xtemplate == nullptr) { yyerror("Unknown template: " + $1); } else { DCAST(XFileTemplate, current_node)->add_option(xtemplate); @@ -293,7 +293,7 @@ template_option_part: | singleword_name class_id { XFileTemplate *xtemplate = x_file->find_template($2); - if (xtemplate == (XFileTemplate *)NULL) { + if (xtemplate == nullptr) { yyerror("Unknown template: " + $1); } else { if (xtemplate->get_name() != $1) { @@ -324,7 +324,7 @@ multiword_name: optional_multiword_name: empty { - $$ = string(); + $$ = std::string(); } | multiword_name ; @@ -351,7 +351,7 @@ object: XFileTemplate *xtemplate = x_file->find_template($1); $$ = current_node; - if (xtemplate == (XFileTemplate *)NULL) { + if (xtemplate == nullptr) { yyerror("Unknown template: " + $1); } else { XFileDataNodeTemplate *templ = @@ -438,7 +438,7 @@ data_reference: multiword_name { XFileDataNodeTemplate *data_object = x_file->find_data_object($1); - if (data_object == (XFileDataObject *)NULL) { + if (data_object == nullptr) { yyerror("Unknown data_object: " + $1); } @@ -447,7 +447,7 @@ data_reference: | multiword_name class_id { XFileDataNodeTemplate *data_object = x_file->find_data_object($2); - if (data_object == (XFileDataObject *)NULL) { + if (data_object == nullptr) { yyerror("Unknown data_object: " + $1); } else { if (data_object->get_name() != $1) { diff --git a/pandatool/src/xfile/xParserDefs.h b/pandatool/src/xfile/xParserDefs.h index 898d4a150e..0900ae4267 100644 --- a/pandatool/src/xfile/xParserDefs.h +++ b/pandatool/src/xfile/xParserDefs.h @@ -23,7 +23,7 @@ class XFile; class XFileNode; -void x_init_parser(istream &in, const string &filename, XFile &file); +void x_init_parser(std::istream &in, const std::string &filename, XFile &file); void x_cleanup_parser(); int xyyparse(); @@ -40,7 +40,7 @@ public: XFileNode *node; XFileDataDef::Type primitive_type; } u; - string str; + std::string str; WindowsGuid guid; PTA_double double_list; PTA_int int_list; diff --git a/pandatool/src/xfileegg/xFileAnimationSet.cxx b/pandatool/src/xfileegg/xFileAnimationSet.cxx index 25e9136c94..f76bc33ee9 100644 --- a/pandatool/src/xfileegg/xFileAnimationSet.cxx +++ b/pandatool/src/xfileegg/xFileAnimationSet.cxx @@ -59,11 +59,11 @@ create_hierarchy(XFileToEggConverter *converter) { // Now populate those empty tables with the frame data. JointData::const_iterator ji; for (ji = _joint_data.begin(); ji != _joint_data.end(); ++ji) { - const string &joint_name = (*ji).first; + const std::string &joint_name = (*ji).first; const FrameData &table = (*ji).second; EggXfmSAnim *anim_table = get_table(joint_name); - if (anim_table == (EggXfmSAnim *)NULL) { + if (anim_table == nullptr) { xfile_cat.warning() << "Frame " << joint_name << ", named by animation data, not defined.\n"; } else { @@ -81,7 +81,7 @@ create_hierarchy(XFileToEggConverter *converter) { for (ti = _tables.begin(); ti != _tables.end(); ++ti) { EggXfmSAnim *anim_table = (*ti).second._table; EggGroup *joint = (*ti).second._joint; - if (anim_table->empty() && joint != (EggGroup *)NULL) { + if (anim_table->empty() && joint != nullptr) { // If there's no animation data, assign the rest transform. anim_table->add_data(joint->get_transform3d()); } @@ -98,13 +98,13 @@ create_hierarchy(XFileToEggConverter *converter) { * Returns the table associated with the indicated joint name. */ EggXfmSAnim *XFileAnimationSet:: -get_table(const string &joint_name) const { +get_table(const std::string &joint_name) const { Tables::const_iterator ti; ti = _tables.find(joint_name); if (ti != _tables.end()) { return (*ti).second._table; } - return NULL; + return nullptr; } /** @@ -112,7 +112,7 @@ get_table(const string &joint_name) const { * joint. */ XFileAnimationSet::FrameData &XFileAnimationSet:: -create_frame_data(const string &joint_name) { +create_frame_data(const std::string &joint_name) { return _joint_data[joint_name]; } diff --git a/pandatool/src/xfileegg/xFileAnimationSet.h b/pandatool/src/xfileegg/xFileAnimationSet.h index 9ef7e1d134..a0bec7d43a 100644 --- a/pandatool/src/xfileegg/xFileAnimationSet.h +++ b/pandatool/src/xfileegg/xFileAnimationSet.h @@ -36,7 +36,7 @@ public: ~XFileAnimationSet(); bool create_hierarchy(XFileToEggConverter *converter); - EggXfmSAnim *get_table(const string &joint_name) const; + EggXfmSAnim *get_table(const std::string &joint_name) const; enum FrameDataFlags { FDF_scale = 0x01, @@ -65,7 +65,7 @@ public: int _flags; }; - FrameData &create_frame_data(const string &joint_name); + FrameData &create_frame_data(const std::string &joint_name); public: double _frame_rate; @@ -74,7 +74,7 @@ private: void mirror_table(XFileToEggConverter *converter, EggGroup *model_node, EggTable *anim_node); - typedef pmap JointData; + typedef pmap JointData; JointData _joint_data; class TablePair { @@ -83,7 +83,7 @@ private: EggXfmSAnim *_table; }; - typedef pmap Tables; + typedef pmap Tables; Tables _tables; }; diff --git a/pandatool/src/xfileegg/xFileMaker.cxx b/pandatool/src/xfileegg/xFileMaker.cxx index 915fa4ff20..e3d07cea0b 100644 --- a/pandatool/src/xfileegg/xFileMaker.cxx +++ b/pandatool/src/xfileegg/xFileMaker.cxx @@ -234,7 +234,7 @@ bool XFileMaker:: finalize_mesh(XFileNode *x_parent, XFileMesh *mesh) { // Get a unique number for each mesh. _mesh_index++; - string mesh_index = format_string(_mesh_index); + std::string mesh_index = format_string(_mesh_index); // Finally, create the Mesh object. mesh->make_x_mesh(x_parent, mesh_index); diff --git a/pandatool/src/xfileegg/xFileMaterial.cxx b/pandatool/src/xfileegg/xFileMaterial.cxx index 4efa732b4d..11457ebcd5 100644 --- a/pandatool/src/xfileegg/xFileMaterial.cxx +++ b/pandatool/src/xfileegg/xFileMaterial.cxx @@ -161,7 +161,7 @@ has_texture() const { * Creates a Material object for the material list. */ XFileDataNode *XFileMaterial:: -make_x_material(XFileNode *x_meshMaterials, const string &suffix) { +make_x_material(XFileNode *x_meshMaterials, const std::string &suffix) { XFileDataNode *x_material = x_meshMaterials->add_Material("material" + suffix, _face_color, _power, diff --git a/pandatool/src/xfileegg/xFileMaterial.h b/pandatool/src/xfileegg/xFileMaterial.h index 915bff11b0..dc6a586d09 100644 --- a/pandatool/src/xfileegg/xFileMaterial.h +++ b/pandatool/src/xfileegg/xFileMaterial.h @@ -41,7 +41,7 @@ public: bool has_material() const; bool has_texture() const; - XFileDataNode *make_x_material(XFileNode *x_meshMaterials, const string &suffix); + XFileDataNode *make_x_material(XFileNode *x_meshMaterials, const std::string &suffix); bool fill_material(XFileDataNode *obj); private: diff --git a/pandatool/src/xfileegg/xFileMesh.cxx b/pandatool/src/xfileegg/xFileMesh.cxx index 7298ef118b..4fad113ed4 100644 --- a/pandatool/src/xfileegg/xFileMesh.cxx +++ b/pandatool/src/xfileegg/xFileMesh.cxx @@ -24,6 +24,9 @@ #include "eggPolygon.h" #include "eggGroupNode.h" +using std::min; +using std::string; + /** * */ @@ -33,7 +36,7 @@ XFileMesh(CoordinateSystem cs) : _cs(cs) { _has_colors = false; _has_uvs = false; _has_materials = false; - _egg_parent = NULL; + _egg_parent = nullptr; } /** @@ -111,7 +114,7 @@ add_vertex(EggVertex *egg_vertex, EggPrimitive *egg_prim) { _has_uvs = true; } - pair result = + std::pair result = _unique_vertices.insert(UniqueVertices::value_type(vertex, next_index)); if (result.second) { @@ -140,7 +143,7 @@ add_normal(EggVertex *egg_vertex, EggPrimitive *egg_prim) { _has_normals = true; } - pair result = + std::pair result = _unique_normals.insert(UniqueNormals::value_type(normal, next_index)); if (result.second) { @@ -168,7 +171,7 @@ add_material(EggPrimitive *egg_prim) { _has_materials = true; } - pair result = + std::pair result = _unique_materials.insert(UniqueMaterials::value_type(material, next_index)); if (result.second) { @@ -257,7 +260,7 @@ set_egg_parent(EggGroupNode *egg_parent) { */ bool XFileMesh:: create_polygons(XFileToEggConverter *converter) { - nassertr(_egg_parent != (EggGroupNode *)NULL, false); + nassertr(_egg_parent != nullptr, false); EggVertexPool *vpool = new EggVertexPool(get_name()); _egg_parent->add_child(vpool); @@ -279,7 +282,7 @@ create_polygons(XFileToEggConverter *converter) { continue; } XFileVertex *vertex = _vertices[vertex_index]; - XFileNormal *normal = (XFileNormal *)NULL; + XFileNormal *normal = nullptr; if (normal_index >= 0 && normal_index < (int)_normals.size()) { normal = _normals[normal_index]; @@ -299,7 +302,7 @@ create_polygons(XFileToEggConverter *converter) { temp_vtx.set_uv(uv); } - if (normal != (XFileNormal *)NULL && normal->_has_normal) { + if (normal != nullptr && normal->_has_normal) { temp_vtx.set_normal(normal->_normal); } @@ -318,7 +321,7 @@ create_polygons(XFileToEggConverter *converter) { WeightMap::const_iterator wmi = data._weight_map.find(vertex_index); if (wmi != data._weight_map.end()) { EggGroup *joint = converter->find_joint(data._joint_name); - if (joint != (EggGroup *)NULL) { + if (joint != nullptr) { double weight = (*wmi).second; LMatrix4d mat = data._matrix_offset; mat *= joint->get_node_to_vertex(); @@ -366,7 +369,7 @@ create_polygons(XFileToEggConverter *converter) { WeightMap::const_iterator wmi = data._weight_map.find(vertex_index); if (wmi != data._weight_map.end()) { EggGroup *joint = converter->find_joint(data._joint_name); - if (joint != (EggGroup *)NULL) { + if (joint != nullptr) { double weight = (*wmi).second; joint->ref_vertex(egg_vtx, weight); } @@ -433,7 +436,7 @@ get_num_materials() const { */ XFileMaterial *XFileMesh:: get_material(int n) const { - nassertr(n >= 0 && n < (int)_materials.size(), (XFileMaterial *)NULL); + nassertr(n >= 0 && n < (int)_materials.size(), nullptr); return _materials[n]; } diff --git a/pandatool/src/xfileegg/xFileMesh.h b/pandatool/src/xfileegg/xFileMesh.h index 8c300f2db6..417d7c4253 100644 --- a/pandatool/src/xfileegg/xFileMesh.h +++ b/pandatool/src/xfileegg/xFileMesh.h @@ -68,11 +68,11 @@ public: int get_num_materials() const; XFileMaterial *get_material(int n) const; - XFileDataNode *make_x_mesh(XFileNode *x_parent, const string &suffix); - XFileDataNode *make_x_normals(XFileNode *x_mesh, const string &suffix); - XFileDataNode *make_x_colors(XFileNode *x_mesh, const string &suffix); - XFileDataNode *make_x_uvs(XFileNode *x_mesh, const string &suffix); - XFileDataNode *make_x_material_list(XFileNode *x_mesh, const string &suffix); + XFileDataNode *make_x_mesh(XFileNode *x_parent, const std::string &suffix); + XFileDataNode *make_x_normals(XFileNode *x_mesh, const std::string &suffix); + XFileDataNode *make_x_colors(XFileNode *x_mesh, const std::string &suffix); + XFileDataNode *make_x_uvs(XFileNode *x_mesh, const std::string &suffix); + XFileDataNode *make_x_material_list(XFileNode *x_mesh, const std::string &suffix); bool fill_mesh(XFileDataNode *obj); bool fill_mesh_child(XFileDataNode *obj); @@ -100,7 +100,7 @@ private: class SkinWeightsData { public: LMatrix4d _matrix_offset; - string _joint_name; + std::string _joint_name; WeightMap _weight_map; }; typedef epvector SkinWeights; diff --git a/pandatool/src/xfileegg/xFileToEggConverter.cxx b/pandatool/src/xfileegg/xFileToEggConverter.cxx index 5b1c6459af..130c42546e 100644 --- a/pandatool/src/xfileegg/xFileToEggConverter.cxx +++ b/pandatool/src/xfileegg/xFileToEggConverter.cxx @@ -26,6 +26,8 @@ #include "eggTextureCollection.h" #include "dcast.h" +using std::string; + /** * */ @@ -34,7 +36,7 @@ XFileToEggConverter() { _make_char = false; _frame_rate = 0.0; _x_file = new XFile(true); - _dart_node = NULL; + _dart_node = nullptr; } /** @@ -46,7 +48,7 @@ XFileToEggConverter(const XFileToEggConverter ©) : _make_char(copy._make_char) { _x_file = new XFile(true); - _dart_node = NULL; + _dart_node = nullptr; } /** @@ -226,9 +228,9 @@ find_joint(const string &joint_name) { ji = _joints.find(joint_name); if (ji != _joints.end()) { EggGroup *joint = (*ji).second; - if (joint == (EggGroup *)NULL) { + if (joint == nullptr) { // An invalid joint detected earlier. - return NULL; + return nullptr; } return joint; @@ -240,9 +242,9 @@ find_joint(const string &joint_name) { xfile_cat.warning() << "Joint name " << joint_name << " in animation data is undefined.\n"; } - _joints[joint_name] = NULL; + _joints[joint_name] = nullptr; - return NULL; + return nullptr; } /** diff --git a/pandatool/src/xfileegg/xFileToEggConverter.h b/pandatool/src/xfileegg/xFileToEggConverter.h index c853cae4ca..d92f4c2325 100644 --- a/pandatool/src/xfileegg/xFileToEggConverter.h +++ b/pandatool/src/xfileegg/xFileToEggConverter.h @@ -45,8 +45,8 @@ public: virtual SomethingToEggConverter *make_copy(); - virtual string get_name() const; - virtual string get_extension() const; + virtual std::string get_name() const; + virtual std::string get_extension() const; virtual bool supports_compressed() const; virtual bool convert_file(const Filename &filename); @@ -56,12 +56,12 @@ public: EggTexture *create_unique_texture(const EggTexture ©); EggMaterial *create_unique_material(const EggMaterial ©); - EggGroup *find_joint(const string &joint_name); + EggGroup *find_joint(const std::string &joint_name); void strip_nodes(TypeHandle t); public: bool _make_char; - string _char_name; + std::string _char_name; double _frame_rate; bool _keep_model; bool _keep_animation; @@ -80,10 +80,10 @@ private: bool convert_animation(XFileDataNode *obj, XFileAnimationSet &animation_set); bool convert_animation_object(XFileDataNode *obj, - const string &joint_name, FrameData &table); - bool convert_animation_key(XFileDataNode *obj, const string &joint_name, + const std::string &joint_name, FrameData &table); + bool convert_animation_key(XFileDataNode *obj, const std::string &joint_name, FrameData &table); - bool set_animation_frame(const string &joint_name, FrameData &table, + bool set_animation_frame(const std::string &joint_name, FrameData &table, int frame, int key_type, const XFileDataObject &values); bool convert_mesh(XFileDataNode *obj, EggGroupNode *egg_parent); @@ -105,7 +105,7 @@ private: typedef pvector AnimationSets; AnimationSets _animation_sets; - typedef pmap Joints; + typedef pmap Joints; Joints _joints; EggGroup *_dart_node; diff --git a/pandatool/src/xfileprogs/xFileToEgg.cxx b/pandatool/src/xfileprogs/xFileToEgg.cxx index fd0c90e77a..d3734fa803 100644 --- a/pandatool/src/xfileprogs/xFileToEgg.cxx +++ b/pandatool/src/xfileprogs/xFileToEgg.cxx @@ -51,7 +51,7 @@ XFileToEgg() : "Specify the frame rate of the resulting animation. If this is " "omitted or 0, the frame rate is inferred from the file itself; but " "note that the file must contain evenly-spaced keyframes.", - &XFileToEgg::dispatch_double, NULL, &_frame_rate); + &XFileToEgg::dispatch_double, nullptr, &_frame_rate); add_option ("anim", "", 0, diff --git a/pandatool/src/xfileprogs/xFileToEgg.h b/pandatool/src/xfileprogs/xFileToEgg.h index 2adbc7e2f7..c95815fe2c 100644 --- a/pandatool/src/xfileprogs/xFileToEgg.h +++ b/pandatool/src/xfileprogs/xFileToEgg.h @@ -31,7 +31,7 @@ public: public: bool _make_char; - string _char_name; + std::string _char_name; double _frame_rate; bool _keep_model; bool _keep_animation; diff --git a/tests/bullet/test_bullet_bam.py b/tests/bullet/test_bullet_bam.py index e22aa57ba2..386e044f9f 100644 --- a/tests/bullet/test_bullet_bam.py +++ b/tests/bullet/test_bullet_bam.py @@ -117,7 +117,7 @@ def test_plane_shape(): assert type(shape) is type(shape2) assert shape.margin == shape2.margin assert shape.name == shape2.name - assert shape.plane_normal == shape2.plane_normal + assert shape.plane_normal.almost_equal(shape2.plane_normal, 0.1) assert shape.plane_constant == shape2.plane_constant diff --git a/tests/display/conftest.py b/tests/display/conftest.py index 88a2b5f3c3..36d498b9a3 100644 --- a/tests/display/conftest.py +++ b/tests/display/conftest.py @@ -68,7 +68,9 @@ def gsg(graphics_pipe, graphics_engine): ) graphics_engine.open_windows() - assert buffer is not None + if buffer is None: + pytest.skip("GraphicsPipe cannot make offscreen buffers") + yield buffer.gsg if buffer is not None: diff --git a/tests/display/test_depth_buffer.py b/tests/display/test_depth_buffer.py new file mode 100644 index 0000000000..02b0c11b69 --- /dev/null +++ b/tests/display/test_depth_buffer.py @@ -0,0 +1,150 @@ +from panda3d import core +import pytest + + +@pytest.fixture(scope='module', params=[32, 24, 16]) +def depth_region(request, graphics_pipe): + """Creates and returns a DisplayRegion with a depth buffer.""" + + engine = core.GraphicsEngine() + engine.set_threading_model("") + + host_fbprops = core.FrameBufferProperties() + host_fbprops.force_hardware = True + + host = engine.make_output( + graphics_pipe, + 'host', + 0, + host_fbprops, + core.WindowProperties.size(32, 32), + core.GraphicsPipe.BF_refuse_window, + ) + engine.open_windows() + + if host is None: + pytest.skip("GraphicsPipe cannot make offscreen buffers") + + fbprops = core.FrameBufferProperties() + fbprops.force_hardware = True + fbprops.depth_bits = request.param + + if fbprops.depth_bits >= 32: + fbprops.float_depth = True + + buffer = engine.make_output( + graphics_pipe, + 'buffer', + 0, + fbprops, + core.WindowProperties.size(32, 32), + core.GraphicsPipe.BF_refuse_window, + host.gsg, + host + ) + engine.open_windows() + + if buffer is None: + pytest.skip("Cannot make depth buffer") + + if buffer.get_fb_properties().depth_bits != request.param: + pytest.skip("Could not make buffer with desired bit count") + + yield buffer.make_display_region() + + if buffer is not None: + engine.remove_window(buffer) + + +def render_depth_pixel(region, distance, near, far, clear=None, write=True): + """Renders a fragment at the specified distance using the specified render + settings, and returns the resulting depth value.""" + + # Set up the scene with a blank card rendering at specified distance. + scene = core.NodePath("root") + scene.set_attrib(core.DepthTestAttrib.make(core.RenderAttrib.M_always)) + scene.set_depth_write(write) + + camera = scene.attach_new_node(core.Camera("camera")) + camera.node().get_lens(0).set_near_far(near, far) + camera.node().set_cull_bounds(core.OmniBoundingVolume()) + + if distance is not None: + cm = core.CardMaker("card") + cm.set_frame(-1, 1, -1, 1) + card = scene.attach_new_node(cm.generate()) + card.set_pos(0, distance, 0) + card.set_scale(60) + + region.active = True + region.camera = camera + + if clear is not None: + region.set_clear_depth_active(True) + region.set_clear_depth(clear) + + depth_texture = core.Texture("depth") + region.window.add_render_texture(depth_texture, + core.GraphicsOutput.RTM_copy_ram, + core.GraphicsOutput.RTP_depth) + + region.window.engine.render_frame() + region.window.clear_render_textures() + + depth_texture.write("test2.png") + + col = core.LColor() + depth_texture.peek().lookup(col, 0.5, 0.5) + return col[0] + + +def test_depth_clear(depth_region): + assert 1.0 == render_depth_pixel(depth_region, None, near=1, far=10, clear=1.0) + assert 0.0 == render_depth_pixel(depth_region, None, near=1, far=10, clear=0.0) + + +def test_depth_write(depth_region): + assert 1.0 == render_depth_pixel(depth_region, 5.0, near=1, far=10, clear=1.0, write=False) + assert 0.99 > render_depth_pixel(depth_region, 5.0, near=1, far=10, clear=1.0, write=True) + + +def test_depth_far_inf(depth_region): + inf = float("inf") + assert 0.99 > render_depth_pixel(depth_region, 100.0, near=1, far=inf, clear=1.0) + + +def test_depth_clipping(depth_region): + # Get the actual depth resulting from the clear value. + clr = render_depth_pixel(depth_region, None, near=1, far=10, clear=0.5) + + # We try rendering something at various distances to make sure that the + # resulting depth value matches our expectations. + + # Too close; read clear value. + assert clr == render_depth_pixel(depth_region, 0.999, near=1, far=10, clear=0.5) + + # Too far; read clear value. + assert clr == render_depth_pixel(depth_region, 10.01, near=1, far=10, clear=0.5) + + # Just close enough; read a value close to 0.0. + assert 0.01 > render_depth_pixel(depth_region, 1.001, near=1, far=10, clear=0.5) + + # Just far enough; read 1.0. + assert 0.99 < render_depth_pixel(depth_region, 9.999, near=1, far=10, clear=0.5) + + +def test_inverted_depth_clipping(depth_region): + # Get the actual depth resulting from the clear value. + clr = render_depth_pixel(depth_region, None, near=1, far=10, clear=0.5) + + # Too close; read clear value. + assert clr == render_depth_pixel(depth_region, 0.999, near=10, far=1, clear=0.5) + + # Too far; read clear value. + assert clr == render_depth_pixel(depth_region, 10.01, near=10, far=1, clear=0.5) + + # Just close enough; read a value close to 1.0. + assert 0.99 < render_depth_pixel(depth_region, 1.001, near=10, far=1, clear=0.5) + + # Just far enough; read a value close to 0.0. + assert 0.01 > render_depth_pixel(depth_region, 9.999, near=10, far=1, clear=0.5) diff --git a/tests/display/test_fbprops.py b/tests/display/test_fbprops.py index a4620efdfc..8beff3c153 100644 --- a/tests/display/test_fbprops.py +++ b/tests/display/test_fbprops.py @@ -1,6 +1,12 @@ from panda3d.core import FrameBufferProperties +def test_fbprops_copy_ctor(): + default = FrameBufferProperties.get_default() + fbprops = FrameBufferProperties(default) + assert fbprops == default + + def test_fbquality_depth(): # We check common framebuffer depth configurations to make sure they # are rated predictably with respect to each other when requesting 1 bit. diff --git a/tests/display/test_glsl_shader.py b/tests/display/test_glsl_shader.py index f4ff2d7ea0..c13e99e92e 100644 --- a/tests/display/test_glsl_shader.py +++ b/tests/display/test_glsl_shader.py @@ -1,4 +1,5 @@ from panda3d import core +import struct import pytest from _pytest.outcomes import Failed @@ -18,6 +19,7 @@ layout(r8ui) uniform writeonly uimageBuffer _triggered; void _reset() {{ imageStore(_triggered, 0, uvec4(0, 0, 0, 0)); + memoryBarrier(); }} void _assert(bool cond, int line) {{ @@ -166,7 +168,7 @@ def test_glsl_int(gsg): inputs = dict( zero=0, intmax=0x7fffffff, - intmin=-0x80000000, + intmin=-0x7fffffff, ) preamble = """ uniform int zero; @@ -176,7 +178,7 @@ def test_glsl_int(gsg): code = """ assert(zero == 0); assert(intmax == 0x7fffffff); - assert(intmin == -0x80000000); + assert(intmin == -0x7fffffff); """ run_glsl_test(gsg, code, preamble, inputs) @@ -275,3 +277,40 @@ def test_glsl_pta_mat4(gsg): assert(pta[1][3] == vec4(28, 29, 30, 31)); """ run_glsl_test(gsg, code, preamble, {'pta': pta}), code + + +def test_glsl_write_extract_image_buffer(gsg): + # Tests that we can write to a buffer texture on the GPU, and then extract + # the data on the CPU. We test two textures since there was in the past a + # where it would only work correctly for one texture. + tex1 = core.Texture("tex1") + tex1.set_clear_color(0) + tex1.setup_buffer_texture(1, core.Texture.T_unsigned_int, core.Texture.F_r32i, + core.GeomEnums.UH_static) + tex2 = core.Texture("tex2") + tex2.set_clear_color(0) + tex2.setup_buffer_texture(1, core.Texture.T_int, core.Texture.F_r32i, + core.GeomEnums.UH_static) + + preamble = """ + layout(r32ui) uniform uimageBuffer tex1; + layout(r32i) uniform iimageBuffer tex2; + """ + code = """ + assert(imageLoad(tex1, 0).r == 0); + assert(imageLoad(tex2, 0).r == 0); + imageStore(tex1, 0, uvec4(123)); + imageStore(tex2, 0, ivec4(-456)); + memoryBarrier(); + assert(imageLoad(tex1, 0).r == 123); + assert(imageLoad(tex2, 0).r == -456); + """ + + run_glsl_test(gsg, code, preamble, {'tex1': tex1, 'tex2': tex2}) + + engine = core.GraphicsEngine.get_global_ptr() + assert engine.extract_texture_data(tex1, gsg) + assert engine.extract_texture_data(tex2, gsg) + + assert struct.unpack('I', tex1.get_ram_image()) == (123,) + assert struct.unpack('i', tex2.get_ram_image()) == (-456,) diff --git a/tests/event/test_futures.py b/tests/event/test_futures.py index 0778605da4..e120a2ab8e 100644 --- a/tests/event/test_futures.py +++ b/tests/event/test_futures.py @@ -48,10 +48,9 @@ def test_future_wait(): fut.set_result(None) thread = threading.Thread(target=thread_main) - thread.start() - # Make sure it didn't sneakily already run the thread assert not fut.done() + thread.start() assert fut.result() is None @@ -69,10 +68,9 @@ def test_future_wait_cancel(): fut.cancel() thread = threading.Thread(target=thread_main) - thread.start() - # Make sure it didn't sneakily already run the thread assert not fut.done() + thread.start() with pytest.raises(CancelledError): fut.result() diff --git a/tests/pgraph/test_nodepath.py b/tests/pgraph/test_nodepath.py index a625533634..1b98da32d7 100644 --- a/tests/pgraph/test_nodepath.py +++ b/tests/pgraph/test_nodepath.py @@ -1,3 +1,5 @@ +import pytest, sys + def test_nodepath_empty(): """Tests NodePath behavior for empty NodePaths.""" from panda3d.core import NodePath @@ -79,3 +81,45 @@ def test_nodepath_transform_composition(): leg2 = node1.get_transform().compose(node3.get_transform()) relative_transform = leg1.get_inverse().compose(leg2) assert np1.get_transform(np2) == relative_transform + + +def test_weak_nodepath_comparison(): + from panda3d.core import NodePath, WeakNodePath + + path = NodePath("node") + weak = WeakNodePath(path) + + assert path == weak + assert weak == path + assert weak <= path + assert path <= weak + assert weak >= path + assert path >= weak + assert not (path != weak) + assert not (weak != path) + assert not (weak > path) + assert not (path > weak) + assert not (weak < path) + assert not (path < weak) + + assert hash(path) == hash(weak) + assert weak.get_node_path() == path + assert weak.node() == path.node() + + +def test_nodepath_python_tags(): + from panda3d.core import NodePath + + path = NodePath("node") + + with pytest.raises(KeyError): + path.python_tags["foo"] + + path.python_tags["foo"] = "bar" + + assert path.python_tags["foo"] == "bar" + + # Make sure reference count stays the same + rc1 = sys.getrefcount(path.python_tags) + rc2 = sys.getrefcount(path.python_tags) + assert rc1 == rc2 diff --git a/tests/putil/test_bitmask.py b/tests/putil/test_bitmask.py new file mode 100644 index 0000000000..e87984cac1 --- /dev/null +++ b/tests/putil/test_bitmask.py @@ -0,0 +1,10 @@ +from panda3d import core + + +def test_bitmask_allon(): + assert core.BitMask16.all_on().is_all_on() + assert core.BitMask32.all_on().is_all_on() + assert core.BitMask64.all_on().is_all_on() + assert core.DoubleBitMaskNative.all_on().is_all_on() + assert core.QuadBitMaskNative.all_on().is_all_on() + assert core.BitArray.all_on().is_all_on() diff --git a/tests/putil/test_datagram.py b/tests/putil/test_datagram.py index 1349bd5656..171363109a 100644 --- a/tests/putil/test_datagram.py +++ b/tests/putil/test_datagram.py @@ -97,6 +97,24 @@ def test_iterator(datagram_small): verify(dgi) +# This tests the copy constructor: +def test_copy(datagram_small): + dg, verify = datagram_small + + dg2 = core.Datagram(dg) + dgi = core.DatagramIterator(dg2) + verify(dgi) + + +def test_assign(datagram_small): + dg, verify = datagram_small + + dg2 = core.Datagram() + dg2.assign(dg) + dgi = core.DatagramIterator(dg2) + verify(dgi) + + # These test DatagramInputFile/DatagramOutputFile: def do_file_test(dg, verify, filename): @@ -147,10 +165,10 @@ def test_file_corrupt(datagram_small, tmpdir): dof.put_datagram(dg) dof.close() - # Corrupt the size header to 4GB - with p.open(mode='wb') as f: + # Corrupt the size header to 1GB + with p.open(mode='r+b') as f: f.seek(0) - f.write(b'\xFF\xFF\xFF\xFF') + f.write(b'\xFF\xFF\xFF\x4F') dg2 = core.Datagram() dif = core.DatagramInputFile() @@ -158,4 +176,15 @@ def test_file_corrupt(datagram_small, tmpdir): assert not dif.get_datagram(dg2) dif.close() + # Truncate the file + for size in [12, 8, 4, 3, 2, 1, 0]: + with p.open(mode='r+b') as f: + f.truncate(size) + + dg2 = core.Datagram() + dif = core.DatagramInputFile() + dif.open(filename) + assert not dif.get_datagram(dg2) + dif.close() + # Should we test that dg2 is unmodified? diff --git a/tests/putil/test_updateseq.py b/tests/putil/test_updateseq.py new file mode 100644 index 0000000000..5cd7312595 --- /dev/null +++ b/tests/putil/test_updateseq.py @@ -0,0 +1,105 @@ +from panda3d.core import UpdateSeq + + +def test_updateseq_initial(): + seq = UpdateSeq() + assert seq == UpdateSeq.initial() + + assert seq.is_special() + assert seq.is_initial() + assert not seq.is_old() + assert not seq.is_fresh() + + assert seq.seq == 0 + + initial = UpdateSeq.initial() + assert seq == initial + assert seq >= initial + assert seq <= initial + assert not (seq != initial) + assert not (seq > initial) + assert not (seq < initial) + + fresh = UpdateSeq.fresh() + assert not (seq == fresh) + assert not (seq >= fresh) + assert seq <= fresh + assert seq != fresh + assert not (seq > fresh) + assert seq < fresh + + old = UpdateSeq.old() + assert not (seq == old) + assert not (seq >= old) + assert not (seq > old) + assert seq != old + assert seq <= old + assert seq < old + + +def test_updateseq_fresh(): + seq = UpdateSeq.fresh() + + assert seq.is_special() + assert not seq.is_initial() + assert not seq.is_old() + assert seq.is_fresh() + + initial = UpdateSeq.initial() + assert not (seq == initial) + assert seq != initial + assert seq > initial + assert seq >= initial + assert not (seq < initial) + assert not (seq <= initial) + + fresh = UpdateSeq.fresh() + assert seq == fresh + assert seq >= fresh + assert seq <= fresh + assert not (seq != fresh) + assert not (seq > fresh) + assert not (seq < fresh) + + old = UpdateSeq.old() + assert not (seq == old) + assert not (seq <= old) + assert not (seq < old) + assert seq != old + assert seq >= old + assert seq > old + + +def test_updateseq_old(): + seq = UpdateSeq.old() + + assert seq.is_special() + assert not seq.is_initial() + assert seq.is_old() + assert not seq.is_fresh() + + assert seq.seq == 1 + + initial = UpdateSeq.initial() + assert not (seq == initial) + assert not (seq <= initial) + assert not (seq < initial) + assert seq != initial + assert seq > initial + assert seq >= initial + + fresh = UpdateSeq.fresh() + assert not (seq == fresh) + assert not (seq >= fresh) + assert not (seq > fresh) + assert seq <= fresh + assert seq != fresh + assert seq < fresh + + old = UpdateSeq.old() + assert seq == old + assert seq >= old + assert seq <= old + assert not (seq != old) + assert not (seq > old) + assert not (seq < old) diff --git a/tests/tform/test_mousewatcher.py b/tests/tform/test_mousewatcher.py new file mode 100644 index 0000000000..a4eccbd47b --- /dev/null +++ b/tests/tform/test_mousewatcher.py @@ -0,0 +1,18 @@ +from panda3d.core import MouseWatcher, MouseWatcherRegion + + +def test_mousewatcher_region_add(): + region1 = MouseWatcherRegion("1", 0, 1, 0, 1) + region2 = MouseWatcherRegion("2", 0, 1, 0, 1) + + mw = MouseWatcher() + assert len(mw.regions) == 0 + + mw.add_region(region1) + assert len(mw.regions) == 1 + + mw.add_region(region2) + assert len(mw.regions) == 2 + + mw.add_region(region1) + assert len(mw.regions) == 2