goat3d

annotate src/node.cc @ 1:e46529a5d057

some progress
author John Tsiombikas <nuclear@member.fsf.org>
date Sat, 17 Aug 2013 23:51:24 +0300
parents
children cd71f0b92f44
rev   line source
nuclear@0 1 #include <algorithm>
nuclear@0 2 #include <string.h>
nuclear@0 3 #include "node.h"
nuclear@0 4
nuclear@0 5 Node::Node()
nuclear@0 6 {
nuclear@0 7 parent = 0;
nuclear@0 8 }
nuclear@0 9
nuclear@0 10 Node::~Node()
nuclear@0 11 {
nuclear@0 12 }
nuclear@0 13
nuclear@0 14 void Node::set_name(const char *name)
nuclear@0 15 {
nuclear@0 16 this->name = name;
nuclear@0 17 }
nuclear@0 18
nuclear@0 19 const char *Node::get_name() const
nuclear@0 20 {
nuclear@0 21 return name.c_str();
nuclear@0 22 }
nuclear@0 23
nuclear@0 24 void Node::add_child(Node *c)
nuclear@0 25 {
nuclear@0 26 // make sure we don't add it twice
nuclear@0 27 if(std::find(children.begin(), children.end(), c) != children.end()) {
nuclear@0 28 return;
nuclear@0 29 }
nuclear@0 30 children.push_back(c);
nuclear@0 31 c->parent = this;
nuclear@0 32 }
nuclear@0 33
nuclear@0 34 int Node::get_num_children() const
nuclear@0 35 {
nuclear@0 36 return (int)children.size();
nuclear@0 37 }
nuclear@0 38
nuclear@0 39 Node *Node::get_child(int idx) const
nuclear@0 40 {
nuclear@0 41 if(idx < 0 || idx >= get_num_children()) {
nuclear@0 42 return 0;
nuclear@0 43 }
nuclear@0 44 return children[idx];
nuclear@0 45 }
nuclear@0 46
nuclear@0 47 Node *Node::get_child(const char *name) const
nuclear@0 48 {
nuclear@0 49 for(size_t i=0; i<children.size(); i++) {
nuclear@0 50 if(strcmp(children[i]->get_name(), name) == 0) {
nuclear@0 51 return children[i];
nuclear@0 52 }
nuclear@0 53 }
nuclear@0 54 return 0;
nuclear@0 55 }
nuclear@0 56
nuclear@0 57 Node *Node::get_descendant(const char *name) const
nuclear@0 58 {
nuclear@0 59 Node *c = get_child(name);
nuclear@0 60 if(c) {
nuclear@0 61 return c;
nuclear@0 62 }
nuclear@0 63
nuclear@0 64 // depth first search might not be ideal in this case, but it's the simplest
nuclear@0 65 for(size_t i=0; i<children.size(); i++) {
nuclear@0 66 if((c = children[i]->get_descendant(name))) {
nuclear@0 67 return c;
nuclear@0 68 }
nuclear@0 69 }
nuclear@0 70 return 0;
nuclear@0 71 }
nuclear@0 72
nuclear@0 73 Node *Node::get_parent() const
nuclear@0 74 {
nuclear@0 75 return parent;
nuclear@0 76 }
nuclear@0 77
nuclear@0 78 Node *Node::get_ancestor(const char *name) const
nuclear@0 79 {
nuclear@0 80 Node *n = (Node*)this;
nuclear@0 81
nuclear@0 82 if(!name) {
nuclear@0 83 // just return the root
nuclear@0 84 while(n->parent) {
nuclear@0 85 n = n->parent;
nuclear@0 86 }
nuclear@0 87 return n;
nuclear@0 88 }
nuclear@0 89
nuclear@0 90 // otherwise we're looking for a specific ancestor
nuclear@0 91 while(n && strcmp(n->get_name(), name) != 0) {
nuclear@0 92 n = n->parent;
nuclear@0 93 }
nuclear@0 94 return n;
nuclear@0 95 }