<commit_before>#include <iostream>
#include "triton/ir/basic_block.h"
#include "triton/ir/module.h"
#include "triton/ir/type.h"
#include "triton/ir/value.h"
#include "triton/ir/constant.h"
#include "triton/ir/function.h"
#include "triton/ir/instructions.h"
#include "triton/ir/print.h"

#include <map>
#include <iomanip>

namespace triton{
namespace ir{

namespace {
class SlotTracker {
  // A mapping of values to slot numbers.
  using value_map = std::map<const value*, unsigned>;

  // The module for which we are holding slot numbers.
  const module *mod_;
  bool module_processed = false;

  // The function for which we are holding slot numbers.
  const function *func_ = nullptr;
  bool function_processed = false;

  // m_map - The slot map for the module level data.
  value_map m_map;
  unsigned m_next = 0;

  // f_map - The slot map for the function level data.
  value_map f_map;
  unsigned f_next = 0;

public:
  // Construct from a module
  explicit SlotTracker(const module *mod) : mod_(mod) {}

  // Construct from a function
  explicit SlotTracker(const function *f)
    : mod_(f? f->get_parent() : nullptr), func_(f) {}

  // Return the slot number of the specified value. If something is not in
  // the SlotTracker, return -1
  int get_local_slot(const value *v);

  void initialize_if_needed();

  // If you'd like to deal with a function instead of just a module, use
  // this method to get its data into the SlotTracker
  void incorporate_function(const function *f) {
    func_ = f;
    function_processed = false;
  }

private:
  // Add all of the module level global variables (and their initializers)
  // and function declarations, but not contents of those functions.
  void process_module();

  // Add all of the functions arguments, basic blocks, and instructions.
  void process_function();

  // Insert specified value* into the slot table
  void create_function_slot(const value *v);
};

class AssemblyWriter {
  std::ostream &os;
  SlotTracker &slot_tracker;

public:
  AssemblyWriter(std::ostream &os, SlotTracker &slot_tracker)
    : os(os), slot_tracker(slot_tracker) {}

  void print_module(const module *mod);
  void print_function(const function *f);
  void print_argument(const argument *arg);
  void print_basic_block(const basic_block *bb);
  void print_instruction(const instruction *instr);
  void print_value(const value *v);

  void write_operand(const value *op, bool print_type = false);
};
} // anonymous namespace

//-------------------------
// SlotTracker
//-------------------------
void SlotTracker::process_module() {
  // Nothing to do at the moment.
  // Create slots for global variable & unamed functions & ...
  module_processed = true;
}

void SlotTracker::process_function() {
  f_next = 0;

  // Add all the function arguments with no names.
  for (const argument *arg : func_->args())
    if (!arg->has_name())
      create_function_slot(arg);

  // Add all of the basic blocks and instructions with no names.
  for (const basic_block *bb : func_->blocks()) {
    if (!bb->has_name())
      create_function_slot(bb);

    for (const instruction *instr : bb->get_inst_list()) {
      if (!instr->get_type()->is_void_ty() && !instr->has_name())
        create_function_slot(instr);
    }
  }

  function_processed = true;
}

void SlotTracker::create_function_slot(const value *v) {
  assert(!v->get_type()->is_void_ty() && !v->has_name() && "Doesn't need a slot");

  unsigned dst_slot = f_next++;
  f_map[v] = dst_slot;
}

int SlotTracker::get_local_slot(const value *v) {
  assert(dynamic_cast<constant>(v) == nullptr && "Can't get a constant slot");

  // Check for uninitialized state and do lazy initialization.
  initialize_if_needed();

  value_map::iterator f_iter = f_map.find(v);
  return f_iter == f_map.end() ? -1 : (int)f_iter->second;
}

void SlotTracker::initialize_if_needed() {
  if (mod_ && !module_processed)
    process_module();

  if (func_ && !function_processed)
    process_function();
}

//-------------------------------
// AssemblyWriter
//-------------------------------
void AssemblyWriter::write_operand(const value *operand, bool print_type) {
  if (!operand) {
    os << "<null operand!>";
    return;
  }

  if (auto *c = dynamic_cast<const ir::constant*>(operand)) {
    os << c->repr();
    return;
  }

  if (operand->has_name()) {
    os << operand->get_name();
    return;
  }

  // Print the normal way
  int slot_num = slot_tracker.get_local_slot(operand);

  if (slot_num != -1)
    os << "%" << slot_num;
  else
    os << "<badref>";
}

void AssemblyWriter::print_module(const module *mod) {
  slot_tracker.initialize_if_needed();
  // ;ModuleID = ...
  // source_filename = ...

  // Print all of the functions.
  for (function *f : mod->get_function_list()) {
    os << "\n";
    print_function(f);
  }
}

void AssemblyWriter::print_function(const function *f) {
  // Annotation & Attributes

  slot_tracker.incorporate_function(f);

  os << "def ";
  ir::type *rt_type = f->get_fn_type()->get_return_ty();
  // Functions must have names.
  os << rt_type->repr() << " " << f->get_name() << "(";
  // Print arguments
  for (ir::argument *arg : f->args()) {
    if (arg->get_arg_no() > 0)
      os << ", ";
    print_argument(arg);
  }
  os << ")";

  // Print function body
  os << "{";
  for (const basic_block *bb : f->blocks())
    print_basic_block(bb);
  os << "}\n";
}

void AssemblyWriter::print_argument(const argument *arg) {
  // Print type
  os << arg->get_type()->repr();

  // Print name, if available.
  if (arg->has_name())
    os << " " << arg->get_name();
  else {
    int slot_num = slot_tracker.get_local_slot(arg);
    assert(slot_num != -1 && "expect argument in function here");
    os << " %" << slot_num;
  }

  // Print attributes
  std::set<attribute> attrs = arg->get_parent()->get_attributes(arg);
  for (attribute attr : attrs)
    os << " " << attr.repr();
}

void AssemblyWriter::print_basic_block(const basic_block *bb) {
  // bb label
  if (bb->has_name()) {
    os << "\n";
    os << bb->get_name() << ":";
  } else {
    os << "\n";
    int slot_num = slot_tracker.get_local_slot(bb);
    if (slot_num != -1)
      os << slot_num << ":";
    else
      os << "<badref>:";
  }

  // Print predecessors for the block
  auto const &predecessors = bb->get_predecessors();
  if (!predecessors.empty()) {
    os << std::setw(50) << std::setfill(' ')
       << "; preds = ";
    for (size_t i=0; i<predecessors.size(); ++i) {
      if (i)
        os << ", ";
      write_operand(predecessors[i]);
    }
  }

  os << "\n";

  // Annotation?

  // Print all of the instructions in the basic block
  for (const ir::instruction *instr : bb->get_inst_list())
    print_instruction(instr);
}

void AssemblyWriter::print_instruction(const instruction *instr) {
  // Print out indentation for an instruction.
  os << "  ";

  ir::type *type = instr->get_type();
  if (instr->has_name()) {
    os << instr->get_name();
    os << " = ";
  } else if (!type->is_void_ty()) {
    // Print out the def slot taken.
    int slot_num = slot_tracker.get_local_slot(instr);
    if (slot_num == -1)
      os << "<badref> = ";
    else
      os << "%" << slot_num << " = ";
  }

  // Print out opcode
  os << instr->repr() << " " << type->repr();

  size_t num_ops = instr->get_num_operands();
  if (num_ops > 0)
    os << " ";
  ir::instruction::ops_t ops = instr->ops();
  for (unsigned i = 0; i < num_ops; ++i) {
    if (i)
      os << ", ";
    write_operand(ops[i]);
  }

  os << ";\n";
}

void AssemblyWriter::print_value(const value *v) {
  // Not implemented
}

//-------------------------------
// External interface
//-------------------------------
void module::print(std::ostream &os) {
  SlotTracker slot_tracker(this);
  AssemblyWriter writer(os, slot_tracker);
  writer.print_module(this);
}

void function::print(std::ostream &os) {
  SlotTracker slot_tracker(this);
  AssemblyWriter writer(os, slot_tracker);
  writer.print_function(this);
}

void basic_block::print(std::ostream &os) {
  SlotTracker slot_tracker(this->get_parent());
  AssemblyWriter writer(os, slot_tracker);
  writer.print_basic_block(this);
}

void instruction::print(std::ostream &os) {
  SlotTracker slot_tracker(this->get_parent()->get_parent());
  AssemblyWriter writer(os, slot_tracker);
  writer.print_instruction(this);
}

//-------------------------------
// legacy print interface
//-------------------------------
std::string get_name(ir::value *v, unsigned i) {
  if(v->get_name().empty()){
    std::string name = "%" + std::to_string(i);
    v->set_name(name);
  }
  return v->get_name();
}

void print(module &mod, std::ostream& os) {
  unsigned cnt = 0;
  for(ir::function *fn: mod.get_function_list()){
    os << "def " << fn->get_fn_type()->get_return_ty()->repr() << " " << fn->get_name() << "(" ;
    for(ir::argument* arg: fn->args()) {
      if(arg->get_arg_no() > 0)
        os << ", ";
      os << arg->get_type()->repr() << " " << arg->get_name();
      auto attrs = fn->get_attributes(arg);
      if(attrs.size() > 0)
        os << " ";
      for(ir::attribute attr: attrs)
        os << attr.repr() << " ";
    }
    os << ")" << std::endl;
    os << "{" << std::endl;
    for(ir::basic_block *block: fn->blocks()){
      auto const &predecessors = block->get_predecessors();
      os << block->get_name() << ":";
      if(!predecessors.empty()){
        os << "                 ";
        os << "; preds = ";
        auto const &predecessors = block->get_predecessors();
        for(ir::basic_block *pred: predecessors)
          os << pred->get_name() << (pred!=predecessors.back()?", ":"");
      }
      os << std::endl;
      for(ir::instruction *inst: block->get_inst_list()){
        os << "  ";
        if(!inst->get_type()->is_void_ty()){
          os << get_name(inst, cnt++);
          os << " = ";
        }
        ir::type* type = inst->get_type();
        os << inst->repr() << " " << type->repr();
        ir::instruction::ops_t ops = inst->ops();
        size_t num_ops = inst->get_num_operands();
        if(num_ops > 0)
          os << " ";;
        for(unsigned i = 0; i < num_ops; i++){
          if(auto *x = dynamic_cast<ir::constant*>(ops[i]))
            os << x->repr();
          else
            os << get_name(ops[i], cnt++);
          os << (i < num_ops - 1?", ":"");
        }
        os << ";";
//        os << " (";
//        for(ir::user* usr: inst->get_users())
//          os << get_name(usr, cnt++) << ", " ;
//        os << " )";
        os << std::endl;
      }
    }
    os << "}" << std::endl;
  }
}

void print(function &fn, std::ostream &os) {
  //
}

void print(basic_block &bb, std::ostream &os) {
  auto const &predecessors = bb.get_predecessors();
  os << bb.get_name() << ":";
  if(!predecessors.empty()){
    os << "                 ";
    os << "; preds = ";
    auto const &predecessors = bb.get_predecessors();
    for(ir::basic_block *pred: predecessors)
      os << pred->get_name() << (pred!=predecessors.back()?", ":"");
  }
  os << std::endl;
  for(ir::instruction *inst: bb.get_inst_list()){
    print(*inst, os);
  }
}

void print(instruction &instr, std::ostream &os) {
    instruction *inst = &instr;
    os << "  ";
    if(!inst->get_type()->is_void_ty()){
      os << instr.get_name();
      os << " = ";
    }
    ir::type* type = inst->get_type();
    os << inst->repr() << " " << type->repr();
    ir::instruction::ops_t ops = inst->ops();
    size_t num_ops = inst->get_num_operands();
    if(num_ops > 0)
      os << " ";;
    for(unsigned i = 0; i < num_ops; i++){
      if(auto *x = dynamic_cast<ir::constant*>(ops[i]))
        os << x->repr();
      else
        os << ops[i]->get_name();
      os << (i < num_ops - 1?", ":"");
    }
    os << ";";
//        os << " (";
//        for(ir::user* usr: inst->get_users())
//          os << get_name(usr, cnt++) << ", " ;
//        os << " )";
    os << std::endl;
}

}
}
<commit_msg>[IR] Fix error when building in debug mode (#331)<commit_after>#include <iostream>
#include "triton/ir/basic_block.h"
#include "triton/ir/module.h"
#include "triton/ir/type.h"
#include "triton/ir/value.h"
#include "triton/ir/constant.h"
#include "triton/ir/function.h"
#include "triton/ir/instructions.h"
#include "triton/ir/print.h"

#include <map>
#include <iomanip>

namespace triton{
namespace ir{

namespace {
class SlotTracker {
  // A mapping of values to slot numbers.
  using value_map = std::map<const value*, unsigned>;

  // The module for which we are holding slot numbers.
  const module *mod_;
  bool module_processed = false;

  // The function for which we are holding slot numbers.
  const function *func_ = nullptr;
  bool function_processed = false;

  // m_map - The slot map for the module level data.
  value_map m_map;
  unsigned m_next = 0;

  // f_map - The slot map for the function level data.
  value_map f_map;
  unsigned f_next = 0;

public:
  // Construct from a module
  explicit SlotTracker(const module *mod) : mod_(mod) {}

  // Construct from a function
  explicit SlotTracker(const function *f)
    : mod_(f? f->get_parent() : nullptr), func_(f) {}

  // Return the slot number of the specified value. If something is not in
  // the SlotTracker, return -1
  int get_local_slot(const value *v);

  void initialize_if_needed();

  // If you'd like to deal with a function instead of just a module, use
  // this method to get its data into the SlotTracker
  void incorporate_function(const function *f) {
    func_ = f;
    function_processed = false;
  }

private:
  // Add all of the module level global variables (and their initializers)
  // and function declarations, but not contents of those functions.
  void process_module();

  // Add all of the functions arguments, basic blocks, and instructions.
  void process_function();

  // Insert specified value* into the slot table
  void create_function_slot(const value *v);
};

class AssemblyWriter {
  std::ostream &os;
  SlotTracker &slot_tracker;

public:
  AssemblyWriter(std::ostream &os, SlotTracker &slot_tracker)
    : os(os), slot_tracker(slot_tracker) {}

  void print_module(const module *mod);
  void print_function(const function *f);
  void print_argument(const argument *arg);
  void print_basic_block(const basic_block *bb);
  void print_instruction(const instruction *instr);
  void print_value(const value *v);

  void write_operand(const value *op, bool print_type = false);
};
} // anonymous namespace

//-------------------------
// SlotTracker
//-------------------------
void SlotTracker::process_module() {
  // Nothing to do at the moment.
  // Create slots for global variable & unamed functions & ...
  module_processed = true;
}

void SlotTracker::process_function() {
  f_next = 0;

  // Add all the function arguments with no names.
  for (const argument *arg : func_->args())
    if (!arg->has_name())
      create_function_slot(arg);

  // Add all of the basic blocks and instructions with no names.
  for (const basic_block *bb : func_->blocks()) {
    if (!bb->has_name())
      create_function_slot(bb);

    for (const instruction *instr : bb->get_inst_list()) {
      if (!instr->get_type()->is_void_ty() && !instr->has_name())
        create_function_slot(instr);
    }
  }

  function_processed = true;
}

void SlotTracker::create_function_slot(const value *v) {
  assert(!v->get_type()->is_void_ty() && !v->has_name() && "Doesn't need a slot");

  unsigned dst_slot = f_next++;
  f_map[v] = dst_slot;
}

int SlotTracker::get_local_slot(const value *v) {
  assert(dynamic_cast<const constant*>(v) == nullptr && "Can't get a constant slot");

  // Check for uninitialized state and do lazy initialization.
  initialize_if_needed();

  value_map::iterator f_iter = f_map.find(v);
  return f_iter == f_map.end() ? -1 : (int)f_iter->second;
}

void SlotTracker::initialize_if_needed() {
  if (mod_ && !module_processed)
    process_module();

  if (func_ && !function_processed)
    process_function();
}

//-------------------------------
// AssemblyWriter
//-------------------------------
void AssemblyWriter::write_operand(const value *operand, bool print_type) {
  if (!operand) {
    os << "<null operand!>";
    return;
  }

  if (auto *c = dynamic_cast<const ir::constant*>(operand)) {
    os << c->repr();
    return;
  }

  if (operand->has_name()) {
    os << operand->get_name();
    return;
  }

  // Print the normal way
  int slot_num = slot_tracker.get_local_slot(operand);

  if (slot_num != -1)
    os << "%" << slot_num;
  else
    os << "<badref>";
}

void AssemblyWriter::print_module(const module *mod) {
  slot_tracker.initialize_if_needed();
  // ;ModuleID = ...
  // source_filename = ...

  // Print all of the functions.
  for (function *f : mod->get_function_list()) {
    os << "\n";
    print_function(f);
  }
}

void AssemblyWriter::print_function(const function *f) {
  // Annotation & Attributes

  slot_tracker.incorporate_function(f);

  os << "def ";
  ir::type *rt_type = f->get_fn_type()->get_return_ty();
  // Functions must have names.
  os << rt_type->repr() << " " << f->get_name() << "(";
  // Print arguments
  for (ir::argument *arg : f->args()) {
    if (arg->get_arg_no() > 0)
      os << ", ";
    print_argument(arg);
  }
  os << ")";

  // Print function body
  os << "{";
  for (const basic_block *bb : f->blocks())
    print_basic_block(bb);
  os << "}\n";
}

void AssemblyWriter::print_argument(const argument *arg) {
  // Print type
  os << arg->get_type()->repr();

  // Print name, if available.
  if (arg->has_name())
    os << " " << arg->get_name();
  else {
    int slot_num = slot_tracker.get_local_slot(arg);
    assert(slot_num != -1 && "expect argument in function here");
    os << " %" << slot_num;
  }

  // Print attributes
  std::set<attribute> attrs = arg->get_parent()->get_attributes(arg);
  for (attribute attr : attrs)
    os << " " << attr.repr();
}

void AssemblyWriter::print_basic_block(const basic_block *bb) {
  // bb label
  if (bb->has_name()) {
    os << "\n";
    os << bb->get_name() << ":";
  } else {
    os << "\n";
    int slot_num = slot_tracker.get_local_slot(bb);
    if (slot_num != -1)
      os << slot_num << ":";
    else
      os << "<badref>:";
  }

  // Print predecessors for the block
  auto const &predecessors = bb->get_predecessors();
  if (!predecessors.empty()) {
    os << std::setw(50) << std::setfill(' ')
       << "; preds = ";
    for (size_t i=0; i<predecessors.size(); ++i) {
      if (i)
        os << ", ";
      write_operand(predecessors[i]);
    }
  }

  os << "\n";

  // Annotation?

  // Print all of the instructions in the basic block
  for (const ir::instruction *instr : bb->get_inst_list())
    print_instruction(instr);
}

void AssemblyWriter::print_instruction(const instruction *instr) {
  // Print out indentation for an instruction.
  os << "  ";

  ir::type *type = instr->get_type();
  if (instr->has_name()) {
    os << instr->get_name();
    os << " = ";
  } else if (!type->is_void_ty()) {
    // Print out the def slot taken.
    int slot_num = slot_tracker.get_local_slot(instr);
    if (slot_num == -1)
      os << "<badref> = ";
    else
      os << "%" << slot_num << " = ";
  }

  // Print out opcode
  os << instr->repr() << " " << type->repr();

  size_t num_ops = instr->get_num_operands();
  if (num_ops > 0)
    os << " ";
  ir::instruction::ops_t ops = instr->ops();
  for (unsigned i = 0; i < num_ops; ++i) {
    if (i)
      os << ", ";
    write_operand(ops[i]);
  }

  os << ";\n";
}

void AssemblyWriter::print_value(const value *v) {
  // Not implemented
}

//-------------------------------
// External interface
//-------------------------------
void module::print(std::ostream &os) {
  SlotTracker slot_tracker(this);
  AssemblyWriter writer(os, slot_tracker);
  writer.print_module(this);
}

void function::print(std::ostream &os) {
  SlotTracker slot_tracker(this);
  AssemblyWriter writer(os, slot_tracker);
  writer.print_function(this);
}

void basic_block::print(std::ostream &os) {
  SlotTracker slot_tracker(this->get_parent());
  AssemblyWriter writer(os, slot_tracker);
  writer.print_basic_block(this);
}

void instruction::print(std::ostream &os) {
  SlotTracker slot_tracker(this->get_parent()->get_parent());
  AssemblyWriter writer(os, slot_tracker);
  writer.print_instruction(this);
}

//-------------------------------
// legacy print interface
//-------------------------------
std::string get_name(ir::value *v, unsigned i) {
  if(v->get_name().empty()){
    std::string name = "%" + std::to_string(i);
    v->set_name(name);
  }
  return v->get_name();
}

void print(module &mod, std::ostream& os) {
  unsigned cnt = 0;
  for(ir::function *fn: mod.get_function_list()){
    os << "def " << fn->get_fn_type()->get_return_ty()->repr() << " " << fn->get_name() << "(" ;
    for(ir::argument* arg: fn->args()) {
      if(arg->get_arg_no() > 0)
        os << ", ";
      os << arg->get_type()->repr() << " " << arg->get_name();
      auto attrs = fn->get_attributes(arg);
      if(attrs.size() > 0)
        os << " ";
      for(ir::attribute attr: attrs)
        os << attr.repr() << " ";
    }
    os << ")" << std::endl;
    os << "{" << std::endl;
    for(ir::basic_block *block: fn->blocks()){
      auto const &predecessors = block->get_predecessors();
      os << block->get_name() << ":";
      if(!predecessors.empty()){
        os << "                 ";
        os << "; preds = ";
        auto const &predecessors = block->get_predecessors();
        for(ir::basic_block *pred: predecessors)
          os << pred->get_name() << (pred!=predecessors.back()?", ":"");
      }
      os << std::endl;
      for(ir::instruction *inst: block->get_inst_list()){
        os << "  ";
        if(!inst->get_type()->is_void_ty()){
          os << get_name(inst, cnt++);
          os << " = ";
        }
        ir::type* type = inst->get_type();
        os << inst->repr() << " " << type->repr();
        ir::instruction::ops_t ops = inst->ops();
        size_t num_ops = inst->get_num_operands();
        if(num_ops > 0)
          os << " ";;
        for(unsigned i = 0; i < num_ops; i++){
          if(auto *x = dynamic_cast<ir::constant*>(ops[i]))
            os << x->repr();
          else
            os << get_name(ops[i], cnt++);
          os << (i < num_ops - 1?", ":"");
        }
        os << ";";
//        os << " (";
//        for(ir::user* usr: inst->get_users())
//          os << get_name(usr, cnt++) << ", " ;
//        os << " )";
        os << std::endl;
      }
    }
    os << "}" << std::endl;
  }
}

void print(function &fn, std::ostream &os) {
  //
}

void print(basic_block &bb, std::ostream &os) {
  auto const &predecessors = bb.get_predecessors();
  os << bb.get_name() << ":";
  if(!predecessors.empty()){
    os << "                 ";
    os << "; preds = ";
    auto const &predecessors = bb.get_predecessors();
    for(ir::basic_block *pred: predecessors)
      os << pred->get_name() << (pred!=predecessors.back()?", ":"");
  }
  os << std::endl;
  for(ir::instruction *inst: bb.get_inst_list()){
    print(*inst, os);
  }
}

void print(instruction &instr, std::ostream &os) {
    instruction *inst = &instr;
    os << "  ";
    if(!inst->get_type()->is_void_ty()){
      os << instr.get_name();
      os << " = ";
    }
    ir::type* type = inst->get_type();
    os << inst->repr() << " " << type->repr();
    ir::instruction::ops_t ops = inst->ops();
    size_t num_ops = inst->get_num_operands();
    if(num_ops > 0)
      os << " ";;
    for(unsigned i = 0; i < num_ops; i++){
      if(auto *x = dynamic_cast<ir::constant*>(ops[i]))
        os << x->repr();
      else
        os << ops[i]->get_name();
      os << (i < num_ops - 1?", ":"");
    }
    os << ";";
//        os << " (";
//        for(ir::user* usr: inst->get_users())
//          os << get_name(usr, cnt++) << ", " ;
//        os << " )";
    os << std::endl;
}

}
}
<|endoftext|>


<commit_before>#pragma once

#include <string>
#include <vector>
#include <map>

#include "rapidjson/writer.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/error/en.h"
#include "rapidjson/stringbuffer.h"

#include "acmacs-base/read-file.hh"

// ----------------------------------------------------------------------

template <typename RW> class JsonWriterT : public RW
{
 public:
    inline JsonWriterT(std::string aKeyword) : RW(mBuffer), mKeyword(aKeyword) {}
    inline operator std::string() const { return mBuffer.GetString(); }
    inline std::string keyword() const { return mKeyword; }

 private:
    rapidjson::StringBuffer mBuffer;
    std::string mKeyword;
};

// template <> inline JsonWriterT<rapidjson::PrettyWriter<rapidjson::StringBuffer>>::JsonWriterT(std::string aKeyword)
//     : rapidjson::PrettyWriter<rapidjson::StringBuffer>(mBuffer), mKeyword(aKeyword)
// {
//     SetIndent(' ', 1);
// }

typedef JsonWriterT<rapidjson::Writer<rapidjson::StringBuffer>> JsonWriter;
typedef JsonWriterT<rapidjson::PrettyWriter<rapidjson::StringBuffer>> JsonPrettyWriter;

// ----------------------------------------------------------------------

enum _StartArray { StartArray };
enum _EndArray { EndArray };
enum _StartObject { StartObject };
enum _EndObject { EndObject };

template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, _StartArray) { writer.StartArray(); return writer; }
template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, _EndArray) { writer.EndArray(); return writer; }
template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, _StartObject) { writer.StartObject(); return writer; }
template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, _EndObject) { writer.EndObject(); return writer; }

template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, const char* s) { writer.String(s, static_cast<unsigned>(strlen(s))); return writer; }
template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, std::string s) { writer.String(s.c_str(), static_cast<unsigned>(s.size())); return writer; }
template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, int value) { writer.Int(value); return writer; }
template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, double value) { writer.Double(value); return writer; }

class JsonObjectKey
{
 public:
    inline JsonObjectKey(const char* v) : value(v) {}
    inline JsonObjectKey(std::string v) : value(v.c_str()) {}
    inline operator const char*() const { return value; }

 private:
    const char* value;
};

template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, JsonObjectKey value) { writer.Key(value); return writer; }

// ----------------------------------------------------------------------

template <typename RW, typename T> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, const std::vector<T>& list)
{
    writer << StartArray;
    for (const auto& e: list)
        writer << e;
    return writer << EndArray;
}

// ----------------------------------------------------------------------

template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, const std::vector<std::vector<std::string>>& list_list_strings)
{
    writer << StartArray;
    for (const auto& e: list_list_strings)
        writer << e;
    return writer << EndArray;
}

// ----------------------------------------------------------------------

template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, const std::map<std::string, std::vector<std::string>>& map_list_strings)
{
    writer << StartObject;
    for (const auto& e: map_list_strings)
        writer << JsonObjectKey(e.first) << e.second;
    return writer << EndObject;
}

// ----------------------------------------------------------------------

template <typename Key, typename Value> class _if_not_empty
{
 public:
    inline _if_not_empty(Key&& key, Value&& value) : mKey(key), mValue(value) {}

    template <typename RW> friend inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, const _if_not_empty<Key, Value>& data)
        {
            if (!data.mValue.empty())
                writer << data.mKey << data.mValue;
            return writer;
        }

 private:
    Key mKey;
    Value mValue;
};

template <typename Key, typename Value> inline auto if_not_empty(Key&& key, Value&& value) { return _if_not_empty<Key, Value>(std::forward<Key>(key), std::forward<Value>(value)); }

// ----------------------------------------------------------------------
// ----------------------------------------------------------------------

template <typename V> inline std::string pretty_json(const V& value, std::string keyword, size_t indent, bool insert_emacs_indent_hint)
{
    JsonPrettyWriter writer(keyword);
    writer.SetIndent(' ', static_cast<unsigned int>(indent));
    writer << value;
    std::string result = writer;
    if (insert_emacs_indent_hint && result[0] == '{') {
        const std::string ind(indent - 1, ' ');
        result.insert(1, ind + "\"_\": \"-*- js-indent-level: " + std::to_string(indent) + " -*-\",");
    }
    return result;
}

template <typename V> inline std::string compact_json(const V& value, std::string keyword)
{
    JsonWriter writer(keyword);
    return writer << value;
}

template <typename V> inline std::string json(const V& value, std::string keyword, size_t indent, bool insert_emacs_indent_hint = true)
{
    if (indent)
        return pretty_json(value, keyword, indent, insert_emacs_indent_hint);
    else
        return compact_json(value, keyword);
}

// ----------------------------------------------------------------------

template <typename V> inline void export_to_json(const V& value, std::string keyword, std::string filename, size_t indent, bool insert_emacs_indent_hint = true)
{
    acmacs_base::write_file(filename, json(value, keyword, indent, insert_emacs_indent_hint));
}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>operator <<(JsonWriterT<RW>& writer, Key key)<commit_after>#pragma once

#include <string>
#include <vector>
#include <map>

#include "rapidjson/writer.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/error/en.h"
#include "rapidjson/stringbuffer.h"

#include "acmacs-base/read-file.hh"

// ----------------------------------------------------------------------

template <typename RW> class JsonWriterT : public RW
{
 public:
    inline JsonWriterT(std::string aKeyword) : RW(mBuffer), mKeyword(aKeyword) {}
    inline operator std::string() const { return mBuffer.GetString(); }
    inline std::string keyword() const { return mKeyword; }

 private:
    rapidjson::StringBuffer mBuffer;
    std::string mKeyword;
};

// template <> inline JsonWriterT<rapidjson::PrettyWriter<rapidjson::StringBuffer>>::JsonWriterT(std::string aKeyword)
//     : rapidjson::PrettyWriter<rapidjson::StringBuffer>(mBuffer), mKeyword(aKeyword)
// {
//     SetIndent(' ', 1);
// }

typedef JsonWriterT<rapidjson::Writer<rapidjson::StringBuffer>> JsonWriter;
typedef JsonWriterT<rapidjson::PrettyWriter<rapidjson::StringBuffer>> JsonPrettyWriter;

// ----------------------------------------------------------------------

enum _StartArray { StartArray };
enum _EndArray { EndArray };
enum _StartObject { StartObject };
enum _EndObject { EndObject };

template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, _StartArray) { writer.StartArray(); return writer; }
template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, _EndArray) { writer.EndArray(); return writer; }
template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, _StartObject) { writer.StartObject(); return writer; }
template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, _EndObject) { writer.EndObject(); return writer; }

template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, const char* s) { writer.String(s, static_cast<unsigned>(strlen(s))); return writer; }
template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, std::string s) { writer.String(s.c_str(), static_cast<unsigned>(s.size())); return writer; }
template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, int value) { writer.Int(value); return writer; }
template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, double value) { writer.Double(value); return writer; }

class JsonObjectKey
{
 public:
    inline JsonObjectKey(const char* v) : value(v) {}
    inline JsonObjectKey(std::string v) : value(v.c_str()) {}
    inline operator const char*() const { return value; }

 private:
    const char* value;
};

template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, JsonObjectKey value) { writer.Key(value); return writer; }

// ----------------------------------------------------------------------

template <typename RW, typename T> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, const std::vector<T>& list)
{
    writer << StartArray;
    for (const auto& e: list)
        writer << e;
    return writer << EndArray;
}

// ----------------------------------------------------------------------

template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, const std::vector<std::vector<std::string>>& list_list_strings)
{
    writer << StartArray;
    for (const auto& e: list_list_strings)
        writer << e;
    return writer << EndArray;
}

// ----------------------------------------------------------------------

template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, const std::map<std::string, std::vector<std::string>>& map_list_strings)
{
    writer << StartObject;
    for (const auto& e: map_list_strings)
        writer << JsonObjectKey(e.first) << e.second;
    return writer << EndObject;
}

// ----------------------------------------------------------------------

namespace json_writer { namespace _internal
{
      // void_t is a C++17 feature
    template<class ...> using void_t = void; // http://stackoverflow.com/questions/26513095/void-t-can-implement-concepts
    template <typename T, typename = void> struct castable_to_char : public std::false_type {};
    template <typename T> struct castable_to_char<T, void_t<decltype(static_cast<char>(std::declval<T>()))>> : public std::true_type {};
}}

template <typename RW, typename Key, typename std::enable_if<json_writer::_internal::castable_to_char<Key>{}>::type* = nullptr>
                     inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, Key key)
{
    const char k = static_cast<char>(key);
    writer.Key(&k, 1, false);
    return writer;
}

// ----------------------------------------------------------------------
// ----------------------------------------------------------------------

template <typename Key, typename Value> class _if_not_empty
{
 public:
    inline _if_not_empty(Key&& key, Value&& value) : mKey(key), mValue(value) {}

    template <typename RW> friend inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, const _if_not_empty<Key, Value>& data)
        {
            if (!data.mValue.empty())
                writer << data.mKey << data.mValue;
            return writer;
        }

 private:
    Key mKey;
    Value mValue;
};

template <typename Key, typename Value> inline auto if_not_empty(Key&& key, Value&& value) { return _if_not_empty<Key, Value>(std::forward<Key>(key), std::forward<Value>(value)); }

// ----------------------------------------------------------------------
// ----------------------------------------------------------------------

template <typename V> inline std::string pretty_json(const V& value, std::string keyword, size_t indent, bool insert_emacs_indent_hint)
{
    JsonPrettyWriter writer(keyword);
    writer.SetIndent(' ', static_cast<unsigned int>(indent));
    writer << value;
    std::string result = writer;
    if (insert_emacs_indent_hint && result[0] == '{') {
        const std::string ind(indent - 1, ' ');
        result.insert(1, ind + "\"_\": \"-*- js-indent-level: " + std::to_string(indent) + " -*-\",");
    }
    return result;
}

template <typename V> inline std::string compact_json(const V& value, std::string keyword)
{
    JsonWriter writer(keyword);
    return writer << value;
}

template <typename V> inline std::string json(const V& value, std::string keyword, size_t indent, bool insert_emacs_indent_hint = true)
{
    if (indent)
        return pretty_json(value, keyword, indent, insert_emacs_indent_hint);
    else
        return compact_json(value, keyword);
}

// ----------------------------------------------------------------------

template <typename V> inline void export_to_json(const V& value, std::string keyword, std::string filename, size_t indent, bool insert_emacs_indent_hint = true)
{
    acmacs_base::write_file(filename, json(value, keyword, indent, insert_emacs_indent_hint));
}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>/*
Copyright 2017 creatorlxd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "stdafx.h"
#include "../Include/LightComponent.h"

using namespace SpaceGameEngine;

REGISTERCOMPONENTCLASS(LightComponent);

SpaceGameEngine::LightComponent::LightComponent()
{
	m_TypeName = "LightComponent";
	m_pTransform = nullptr;
}

SpaceGameEngine::LightComponent::~LightComponent()
{
	Release();
}

void SpaceGameEngine::LightComponent::InitFromFile(const std::string & filename, int mode)
{
	m_Mode = mode;
	auto lightasset = ReadAssetFromFile<LightAsset>(filename);
	m_Content.m_Content = lightasset->m_Content;
	if (mode == StaticMode)
		m_Content.m_Mode = LightEx::LightMode::Normal;
	else if (mode == DynamicMode)
		m_Content.m_Mode = LightEx::LightMode::Dynamic;
}

void SpaceGameEngine::LightComponent::Start()
{
	m_Content.m_Content.m_Position = m_pTransform->GetPosition();
	m_Content.m_Content.m_Direction = GetDirectionByRotation(m_pTransform->GetRotation());
	Scene::GetMainScene()->m_LightManager.InsertLight(&m_Content);
}

void SpaceGameEngine::LightComponent::Run(float DeltaTime)
{
	if (m_Mode == StaticMode)
	{
		if (m_pFatherObject->GetComponentByMessage(Event::PositionChange) ||
			m_pFatherObject->GetComponentByMessage(Event::RotationChange))
		{
			m_Content.m_Content.m_Position = m_pTransform->GetPosition();
			m_Content.m_Content.m_Direction = GetDirectionByRotation(m_pTransform->GetRotation());
			Scene::GetMainScene()->m_LightManager.UpdateLight(&m_Content);
		}
	}
}

void SpaceGameEngine::LightComponent::Release()
{
	if (m_Mode != 0)
	{
		Scene::GetMainScene()->m_LightManager.DeleteLight(&m_Content);
		m_Mode = 0;
	}
	m_pTransform = nullptr;
}

bool SpaceGameEngine::LightComponent::IfOn()
{
	return m_Content.m_IfOn;
}

void SpaceGameEngine::LightComponent::ChangeIfOn(bool b)
{
	m_Content.m_IfOn = b;
}
<commit_msg>fix a bug<commit_after>/*
Copyright 2017 creatorlxd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "stdafx.h"
#include "../Include/LightComponent.h"

using namespace SpaceGameEngine;

REGISTERCOMPONENTCLASS(LightComponent);

SpaceGameEngine::LightComponent::LightComponent()
{
	m_TypeName = "LightComponent";
	m_pTransform = nullptr;
}

SpaceGameEngine::LightComponent::~LightComponent()
{
	Release();
}

void SpaceGameEngine::LightComponent::InitFromFile(const std::string & filename, int mode)
{
	m_Mode = mode;
	auto lightasset = ReadAssetFromFile<LightAsset>(filename);
	m_Content.m_Content = lightasset->m_Content;
	if (mode == StaticMode)
		m_Content.m_Mode = LightEx::LightMode::Normal;
	else if (mode == DynamicMode)
		m_Content.m_Mode = LightEx::LightMode::Dynamic;
}

void SpaceGameEngine::LightComponent::Start()
{
	m_pTransform = m_pFatherObject->GetComponent<TransformComponent>();
	m_Content.m_Content.m_Position = m_pTransform->GetPosition();
	m_Content.m_Content.m_Direction = GetDirectionByRotation(m_pTransform->GetRotation());
	Scene::GetMainScene()->m_LightManager.InsertLight(&m_Content);
}

void SpaceGameEngine::LightComponent::Run(float DeltaTime)
{
	if (m_Mode == StaticMode)
	{
		if (m_pFatherObject->GetComponentByMessage(Event::PositionChange) ||
			m_pFatherObject->GetComponentByMessage(Event::RotationChange))
		{
			m_Content.m_Content.m_Position = m_pTransform->GetPosition();
			m_Content.m_Content.m_Direction = GetDirectionByRotation(m_pTransform->GetRotation());
			Scene::GetMainScene()->m_LightManager.UpdateLight(&m_Content);
		}
	}
}

void SpaceGameEngine::LightComponent::Release()
{
	if (m_Mode != 0)
	{
		Scene::GetMainScene()->m_LightManager.DeleteLight(&m_Content);
		m_Mode = 0;
	}
	m_pTransform = nullptr;
}

bool SpaceGameEngine::LightComponent::IfOn()
{
	return m_Content.m_IfOn;
}

void SpaceGameEngine::LightComponent::ChangeIfOn(bool b)
{
	m_Content.m_IfOn = b;
}
<|endoftext|>


<commit_before>#include <OGRE/OgreVector3.h>
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreSceneManager.h>

#include <rviz/ogre_helpers/arrow.h>
#include <rviz/ogre_helpers/shape.h>
#include <rviz/display_context.h>
#include <rviz/display_factory.h>

#include<tf2/LinearMath/Quaternion.h>

#include "reachability_map_visual.h"
#include <iterator>

namespace workspace_visualization
{

ReachMapVisual::ReachMapVisual( Ogre::SceneManager* scene_manager, Ogre::SceneNode* parent_node, rviz::DisplayContext* display_context)
{
  scene_manager_ = scene_manager;
  frame_node_ = parent_node->createChildSceneNode();

  //arrow_.reset(new rviz::Arrow( scene_manager_, frame_node_ ));
}

ReachMapVisual::~ReachMapVisual()
{
  scene_manager_->destroySceneNode( frame_node_ );
}

void ReachMapVisual::setMessage( const map_creator::WorkSpace::ConstPtr& msg, bool do_display_arrow, bool do_display_sphere, int low_ri, int high_ri, int shape_choice, int disect_choice)
{
 int low_SphereSize, up_SphereSize;
  if(disect_choice == 0)
    {
	low_SphereSize = 0;
        up_SphereSize = msg->WsSpheres.size();
    }
  if(disect_choice == 1)
    {
        low_SphereSize = 0;
        up_SphereSize = msg->WsSpheres.size()/2;
    }
  if(disect_choice == 2)
    {
        low_SphereSize = msg->WsSpheres.size()/2;
        up_SphereSize = msg->WsSpheres.size();
    }
  if(disect_choice == 3)
    {
        low_SphereSize = msg->WsSpheres.size()/2.2;
        up_SphereSize = msg->WsSpheres.size()/1.8;
    }
  if(disect_choice == 4)
    {
        low_SphereSize = 0;
        up_SphereSize = msg->WsSpheres.size()/1.1;
    }

  if(do_display_arrow){
  boost::shared_ptr<rviz::Arrow> pose_arrow;
  for (size_t i = low_SphereSize; i < up_SphereSize; ++i) {
	for(size_t j=0;j < msg->WsSpheres[i].poses.size(); ++j){
	if(low_ri<int(msg->WsSpheres[i].ri) && int(msg->WsSpheres[i].ri)<=high_ri){

  pose_arrow.reset(new rviz::Arrow( scene_manager_, frame_node_ ));

  Ogre::Vector3 position_(msg->WsSpheres[i].poses[j].position.x,
                         msg->WsSpheres[i].poses[j].position.y,
                         msg->WsSpheres[i].poses[j].position.z);
  tf2::Quaternion quat(msg->WsSpheres[i].poses[j].orientation.x,
                               msg->WsSpheres[i].poses[j].orientation.y,
                               msg->WsSpheres[i].poses[j].orientation.z,
                               msg->WsSpheres[i].poses[j].orientation.w);

  tf2::Quaternion q2;
  q2.setRPY(0,-M_PI/2,0); //Arrows are pointed as -z direction. So rotating it is necessary

  quat*=(q2);
  quat.normalize();
  Ogre::Quaternion orientation_(quat.w(), quat.x(), quat.y(), quat.z());

  if(position_.isNaN() || orientation_.isNaN()){
    ROS_WARN("received invalid pose");
    return;
  }

  pose_arrow->setPosition(position_);
  pose_arrow->setOrientation(orientation_);

  arrow_.push_back(pose_arrow);
    }
  }
  }
 }
  if(do_display_sphere){

  boost::shared_ptr<rviz::Shape> sphere_center;
  int colorRI;

  for (size_t i = low_SphereSize; i < up_SphereSize; ++i) {
    if(low_ri<=int(msg->WsSpheres[i].ri) && int(msg->WsSpheres[i].ri<=high_ri)){

  if(shape_choice == 0){

  sphere_center.reset(new rviz::Shape(rviz::Shape::Sphere, scene_manager_,frame_node_ ));
  }

  if(shape_choice == 1){

  sphere_center.reset(new rviz::Shape(rviz::Shape::Cylinder, scene_manager_,frame_node_ ));
  }

  if(shape_choice == 2){

  sphere_center.reset(new rviz::Shape(rviz::Shape::Cone, scene_manager_,frame_node_ ));
  }

  if(shape_choice == 3){

  sphere_center.reset(new rviz::Shape(rviz::Shape::Cube, scene_manager_,frame_node_ ));
  }

  Ogre::Vector3 position_sphere(msg->WsSpheres[i].point.x,
                         msg->WsSpheres[i].point.y,
                         msg->WsSpheres[i].point.z);
  Ogre::Quaternion orientation_sphere(0,0,0,1);
  colorRI = msg->WsSpheres[i].ri;
  if(position_sphere.isNaN()){
    ROS_WARN("received invalid sphere coordinate");
    return;
    }
  sphere_center->setPosition(position_sphere);
  sphere_center->setOrientation(orientation_sphere);

  sphere_.push_back(sphere_center);
  colorRI_.push_back(colorRI);

   }
  }
 }
}

void ReachMapVisual::setFramePosition( const Ogre::Vector3& position )
{
  frame_node_->setPosition( position );
}

void ReachMapVisual::setFrameOrientation( const Ogre::Quaternion& orientation )
{
  frame_node_->setOrientation( orientation );
}

void ReachMapVisual::setColorArrow( float r, float g, float b, float a )
{
  for (int i=0;i<arrow_.size();++i)
  {
     arrow_[i]->setColor( r, g, b, a );
  }
}

void ReachMapVisual::setColorSphere( float r, float g, float b, float a )
{
  for (int i=0;i<sphere_.size();++i)
  {
     sphere_[i]->setColor( r, g, b, a );
  }
}

void ReachMapVisual::setColorSpherebyRI(float alpha )
{

  for (int i=0;i<sphere_.size();++i)
  {
     if(colorRI_[i]>=90){
     	sphere_[i]->setColor( 0, 0, 255, alpha );
     }
     else if(colorRI_[i]<90 && colorRI_[i]>=50 ){
     	sphere_[i]->setColor( 0, 255, 255, alpha );
     }
     else if(colorRI_[i]<50 && colorRI_[i]>=30 ){
     	sphere_[i]->setColor( 0, 255, 0, alpha );
     }
     else if(colorRI_[i]<30 && colorRI_[i]>=5 ){
     	sphere_[i]->setColor( 255, 255, 0, alpha );
     }
     else{
	sphere_[i]->setColor( 255, 0, 0, alpha );
     }
  }
}

void ReachMapVisual::setSizeArrow( float l )
{
  for (int i=0;i<arrow_.size();++i)
  {
     arrow_[i]->setScale( Ogre::Vector3(l, l, l));
  }
}

void ReachMapVisual::setSizeSphere( float l )
{
  for (int i=0;i<sphere_.size();++i)
  {
     sphere_[i]->setScale( Ogre::Vector3(l, l, l));
  }
}

}//end namespace workspace_visualization

<commit_msg>changed if to switch statement<commit_after>#include <OGRE/OgreVector3.h>
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreSceneManager.h>

#include <rviz/ogre_helpers/arrow.h>
#include <rviz/ogre_helpers/shape.h>
#include <rviz/display_context.h>
#include <rviz/display_factory.h>

#include<tf2/LinearMath/Quaternion.h>

#include "reachability_map_visual.h"
#include <iterator>

namespace workspace_visualization
{

ReachMapVisual::ReachMapVisual( Ogre::SceneManager* scene_manager, Ogre::SceneNode* parent_node, rviz::DisplayContext* display_context)
{
  scene_manager_ = scene_manager;
  frame_node_ = parent_node->createChildSceneNode();

  //arrow_.reset(new rviz::Arrow( scene_manager_, frame_node_ ));
}

ReachMapVisual::~ReachMapVisual()
{
  scene_manager_->destroySceneNode( frame_node_ );
}

void ReachMapVisual::setMessage( const map_creator::WorkSpace::ConstPtr& msg, bool do_display_arrow, bool do_display_sphere, int low_ri, int high_ri, int shape_choice, int disect_choice)
{
 int low_SphereSize, up_SphereSize;

  switch(disect_choice){
    case 0: {low_SphereSize = 0;
        up_SphereSize = msg->WsSpheres.size();
        break;}
    case 1: {low_SphereSize = 0;
        up_SphereSize = msg->WsSpheres.size()/2;
        break;}
    case 2: {low_SphereSize = msg->WsSpheres.size()/2;
        up_SphereSize = msg->WsSpheres.size();
        break;}
    case 3: {low_SphereSize = msg->WsSpheres.size()/2.2;
        up_SphereSize = msg->WsSpheres.size()/1.8;
        break;}
    case 4: {low_SphereSize = 0;
        up_SphereSize = msg->WsSpheres.size()/1.1;
        break;}
   }

  if(do_display_arrow){
  boost::shared_ptr<rviz::Arrow> pose_arrow;
  for (size_t i = low_SphereSize; i < up_SphereSize; ++i) {
	for(size_t j=0;j < msg->WsSpheres[i].poses.size(); ++j){
	if(low_ri<int(msg->WsSpheres[i].ri) && int(msg->WsSpheres[i].ri)<=high_ri){

  pose_arrow.reset(new rviz::Arrow( scene_manager_, frame_node_ ));

  Ogre::Vector3 position_(msg->WsSpheres[i].poses[j].position.x,
                         msg->WsSpheres[i].poses[j].position.y,
                         msg->WsSpheres[i].poses[j].position.z);
  tf2::Quaternion quat(msg->WsSpheres[i].poses[j].orientation.x,
                               msg->WsSpheres[i].poses[j].orientation.y,
                               msg->WsSpheres[i].poses[j].orientation.z,
                               msg->WsSpheres[i].poses[j].orientation.w);

  tf2::Quaternion q2;
  q2.setRPY(0,-M_PI/2,0); //Arrows are pointed as -z direction. So rotating it is necessary

  quat*=(q2);
  quat.normalize();
  Ogre::Quaternion orientation_(quat.w(), quat.x(), quat.y(), quat.z());

  if(position_.isNaN() || orientation_.isNaN()){
    ROS_WARN("received invalid pose");
    return;
  }

  pose_arrow->setPosition(position_);
  pose_arrow->setOrientation(orientation_);

  arrow_.push_back(pose_arrow);
    }
  }
  }
 }
  if(do_display_sphere){

  boost::shared_ptr<rviz::Shape> sphere_center;
  int colorRI;

  for (size_t i = low_SphereSize; i < up_SphereSize; ++i) {
    if(low_ri<=int(msg->WsSpheres[i].ri) && int(msg->WsSpheres[i].ri<=high_ri)){

  switch(shape_choice){
    case 0: {
	sphere_center.reset(new rviz::Shape(rviz::Shape::Sphere, scene_manager_,frame_node_ ));
        break;}
    case 1: {
        sphere_center.reset(new rviz::Shape(rviz::Shape::Cylinder, scene_manager_,frame_node_ ));
        break;}
    case 2: {
        sphere_center.reset(new rviz::Shape(rviz::Shape::Cone, scene_manager_,frame_node_ ));
        break;}
    case 3: {
        sphere_center.reset(new rviz::Shape(rviz::Shape::Cube, scene_manager_,frame_node_ ));
        break;}

   }

  Ogre::Vector3 position_sphere(msg->WsSpheres[i].point.x,
                         msg->WsSpheres[i].point.y,
                         msg->WsSpheres[i].point.z);
  Ogre::Quaternion orientation_sphere(0,0,0,1);
  colorRI = msg->WsSpheres[i].ri;
  if(position_sphere.isNaN()){
    ROS_WARN("received invalid sphere coordinate");
    return;
    }
  sphere_center->setPosition(position_sphere);
  sphere_center->setOrientation(orientation_sphere);

  sphere_.push_back(sphere_center);
  colorRI_.push_back(colorRI);

   }
  }
 }
}

void ReachMapVisual::setFramePosition( const Ogre::Vector3& position )
{
  frame_node_->setPosition( position );
}

void ReachMapVisual::setFrameOrientation( const Ogre::Quaternion& orientation )
{
  frame_node_->setOrientation( orientation );
}

void ReachMapVisual::setColorArrow( float r, float g, float b, float a )
{
  for (int i=0;i<arrow_.size();++i)
  {
     arrow_[i]->setColor( r, g, b, a );
  }
}

void ReachMapVisual::setColorSphere( float r, float g, float b, float a )
{
  for (int i=0;i<sphere_.size();++i)
  {
     sphere_[i]->setColor( r, g, b, a );
  }
}

void ReachMapVisual::setColorSpherebyRI(float alpha )
{

  for (int i=0;i<sphere_.size();++i)
  {
     if(colorRI_[i]>=90){
     	sphere_[i]->setColor( 0, 0, 255, alpha );
     }
     else if(colorRI_[i]<90 && colorRI_[i]>=50 ){
     	sphere_[i]->setColor( 0, 255, 255, alpha );
     }
     else if(colorRI_[i]<50 && colorRI_[i]>=30 ){
     	sphere_[i]->setColor( 0, 255, 0, alpha );
     }
     else if(colorRI_[i]<30 && colorRI_[i]>=5 ){
     	sphere_[i]->setColor( 255, 255, 0, alpha );
     }
     else{
	sphere_[i]->setColor( 255, 0, 0, alpha );
     }
  }
}

void ReachMapVisual::setSizeArrow( float l )
{
  for (int i=0;i<arrow_.size();++i)
  {
     arrow_[i]->setScale( Ogre::Vector3(l, l, l));
  }
}

void ReachMapVisual::setSizeSphere( float l )
{
  for (int i=0;i<sphere_.size();++i)
  {
     sphere_[i]->setScale( Ogre::Vector3(l, l, l));
  }
}

}//end namespace workspace_visualization
<|endoftext|>


<commit_before>/* Copyright 2007-2015 QReal Research Group
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

#include "paletteTree.h"

#include <QtCore/QUuid>
#include <QtGui/QMouseEvent>
#include <QtCore/QtAlgorithms>
#include <QtWidgets/QVBoxLayout>
#include <QtGui/QDrag>

#include <qrkernel/settingsManager.h>
#include <qrkernel/definitions.h>
#include <qrkernel/settingsManager.h>
#include <qrutils/widgets/searchLineEdit.h>

#include "mainWindow/palette/draggableElement.h"
#include "dialogs/metamodelingOnFly/propertiesDialog.h"

using namespace qReal;
using namespace gui;

PaletteTree::PaletteTree(QWidget *parent)
	: QWidget(parent)
	, mTree(nullptr)
	, mCurrentEditor(0)
{
	initUi();
}

void PaletteTree::initUi()
{
	mLayout = new QVBoxLayout(this);
	mLayout->setSpacing(0);
	QHBoxLayout * const controlButtonsLayout = new QHBoxLayout;
	controlButtonsLayout->setSpacing(0);

	mComboBox = new QComboBox;
	mComboBox->setGeometry(0, 0, 300, 50);
	mLayout->addWidget(mComboBox);
	mLayout->addLayout(controlButtonsLayout);

	ui::SearchLineEdit * const searchField = new ui::SearchLineEdit(this);
	connect(searchField, &ui::SearchLineEdit::textChanged, this, &PaletteTree::onSearchTextChanged);
	mLayout->addWidget(searchField);
	mSearchLineEdit = searchField;

	setMinimumSize(200, 100);
}

void PaletteTree::expand()
{
	mTree->expand();
}

void PaletteTree::collapse()
{
	mTree->collapse();
}

void PaletteTree::setActiveEditor(int index)
{
	if (0 <= index && index < mEditorsTrees.count()) {
		mCurrentEditor = index;
		if (mTree) {
			mTree->hide();
		}

		mTree = mEditorsTrees[index];
		mTree->show();
	}
}

void PaletteTree::setActiveEditor(const Id &id)
{
	setActiveEditor(mCategories.value(id, 0));
}

void PaletteTree::addEditorElements(EditorManagerInterface &editorManagerProxy, const Id &editor, const Id &diagram)
{
	mEditorManager = &editorManagerProxy;
	mEditorsNames.push_back(mEditorManager->friendlyName(diagram));

	mCategories[diagram] = mEditorsTrees.size();

	mComboBox->addItem(mEditorManager->friendlyName(diagram));

	PaletteTreeWidgets *editorTree = new PaletteTreeWidgets(*this, mMainWindow, *mEditorManager, editor, diagram);
	editorTree->hide();

	mEditorsTrees.push_back(editorTree);
	mLayout->addWidget(editorTree);
}

void PaletteTree::initDone()
{
	if (mComboBox->count() == 1) {
		// In case of empty combobox we do not hide it for user`s ensuring in items absence
		mComboBox->hide();
	} else {
		connect(mComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setActiveEditor(int)));
		mComboBox->show();
	}

	setActiveEditor(SettingsManager::value("CurrentIndex", 0).toInt());
	if (mTree) {
		mTree->resizeIcons();
	}
}

void PaletteTree::setComboBox(const Id &id)
{
	mComboBox->setCurrentIndex(mCategories.value(id, -1));
}

QComboBox* PaletteTree::comboBox() const
{
	return mComboBox;
}

QList<QString> PaletteTree::editorsNames() const
{
	return mEditorsNames;
}

void PaletteTree::deleteEditor(const Id &id)
{
	if (mCategories.contains(id)) {
		PaletteTreeWidgets *tree = mEditorsTrees[mCategories[id]];
		if (mTree == tree) {
			mTree = nullptr;
		}

		mComboBox->removeItem(mCategories[id]);
		mEditorsNames.removeAt(mCategories[id]);
		mEditorsTrees.removeAt(mCategories[id]);

		delete tree;
		mCategories.remove(id);
	}
}

Id PaletteTree::currentEditor() const
{
	return mCategories.key(mCurrentEditor);
}

void PaletteTree::recreateTrees()
{
	deletePaletteTree();
	createPaletteTree();
}

void PaletteTree::createPaletteTree()
{
	mTree = new PaletteTreeWidgets(*this, mMainWindow, *mEditorManager);
	mTree->setMinimumHeight(0);
	mLayout->addWidget(mTree);
}

void PaletteTree::deletePaletteTree()
{
	mComboBox->clear();
	if (mTree) {
		mEditorsTrees.removeAll(mTree);
		mLayout->removeWidget(mTree);
		delete mTree;
	}

	qDeleteAll(mEditorsTrees);
	mEditorsTrees.clear();
	mEditorsNames.clear();
	mCategories.clear();
	mCurrentEditor = 0;
}

PaletteTree::~PaletteTree()
{
	deletePaletteTree();
}

void PaletteTree::setComboBoxIndex(int index)
{
	mComboBox->setCurrentIndex(index);
}

void PaletteTree::setComboBoxIndex()
{
	mComboBox->setCurrentIndex(SettingsManager::value("CurrentIndex", 0).toInt());
}

void PaletteTree::saveConfiguration()
{
	SettingsManager::setValue("PaletteRepresentation", mIconsView);
	SettingsManager::setValue("PaletteIconsInARowCount", mItemsCountInARow);
	int diagramIndex = 0;
	for (const PaletteTreeWidgets *editorTree : mEditorsTrees) {
		editorTree->saveConfiguration(mComboBox->itemText(diagramIndex));
		diagramIndex++;
	}

	SettingsManager::setValue("CurrentIndex", mComboBox->currentIndex() >= 0 ? mComboBox->currentIndex() : 0);
}

bool PaletteTree::iconsView() const
{
	return mIconsView;
}

void PaletteTree::setIconsView(bool iconsView)
{
	mIconsView = iconsView;
}

void PaletteTree::loadEditors(EditorManagerInterface &editorManagerProxy)
{
	for (const Id &editor : editorManagerProxy.editors()) {
		for (const Id &diagram : editorManagerProxy.diagrams(editor)) {
			addEditorElements(editorManagerProxy, editor, diagram);
		}
	}

	const int index = SettingsManager::value("CurrentIndex", 0).toInt();
	SettingsManager::setValue("CurrentIndex", index >= 0 ? index : 0);
}

void PaletteTree::setItemsCountInARow(int count)
{
	mItemsCountInARow = count;
}

int PaletteTree::itemsCountInARow() const
{
	return mItemsCountInARow;
}

void PaletteTree::resizeEvent(QResizeEvent *)
{
	if (mTree) {
		mTree->resizeIcons();
	}
}

int PaletteTree::maxItemsCountInARow() const
{
	const int max = mTree->maxItemsCountInARow();
	return max ? max : mItemsCountInARow;
}

void PaletteTree::onSearchTextChanged(const QRegExp &searchText)
{
	mTree->filter(searchText);
}

void PaletteTree::changeRepresentation()
{
	loadPalette(!mIconsView, mItemsCountInARow, mEditorManager);
	SettingsManager::setValue("PaletteRepresentation", mIconsView);
	SettingsManager::setValue("PaletteIconsInARowCount", mItemsCountInARow);
	emit paletteParametersChanged();
}

void PaletteTree::loadPalette(bool isIconsView, int itemsCount, EditorManagerInterface *editorManagerProxy)
{
	if (mEditorManager) {
		recreateTrees();
	}

	mIconsView = isIconsView;
	mEditorManager = editorManagerProxy;
	mItemsCountInARow = itemsCount;
	if (mEditorManager) {
		// TODO: Can it really be nullptr?
		loadEditors(*mEditorManager);
	}

	initDone();
	setComboBoxIndex();
	mSearchLineEdit->setVisible(!isIconsView);
}

void PaletteTree::initMainWindow(MainWindow *mainWindow)
{
	mMainWindow = mainWindow;
}

void PaletteTree::installEventFilter(QObject *obj)
{
	QWidget::installEventFilter(obj);
	comboBox()->installEventFilter(obj);
}

void PaletteTree::setElementVisible(const Id &metatype, bool visible)
{
	if (mTree) {
		mTree->setElementVisible(metatype, visible);
	}
}

void PaletteTree::setVisibleForAllElements(const Id &diagram, bool visible)
{
	for (PaletteTreeWidgets * const tree : mEditorsTrees) {
		if (tree->diagram() == diagram) {
			tree->setVisibleForAllElements(visible);
		}
	}
}

void PaletteTree::setElementEnabled(const Id &metatype, bool enabled)
{
	if (mTree) {
		mTree->setElementEnabled(metatype, enabled);
	}
}

void PaletteTree::setEnabledForAllElements(const Id &diagram, bool enabled)
{
	for (PaletteTreeWidgets * const tree : mEditorsTrees) {
		if (tree->diagram() == diagram) {
			tree->setEnabledForAllElements(enabled);
		}
	}}

void PaletteTree::refreshUserPalettes()
{
	for (PaletteTreeWidgets * const tree : mEditorsTrees) {
		tree->refreshUserPalette();
	}
}

void PaletteTree::customizeExplosionTitles(const QString &userGroupTitle, const QString &userGroupDescription)
{
	for (PaletteTreeWidgets * const tree : mEditorsTrees) {
		tree->customizeExplosionTitles(userGroupTitle, userGroupDescription);
	}
}
<commit_msg>Small typo fix<commit_after>/* Copyright 2007-2015 QReal Research Group
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

#include "paletteTree.h"

#include <QtCore/QUuid>
#include <QtGui/QMouseEvent>
#include <QtCore/QtAlgorithms>
#include <QtWidgets/QVBoxLayout>
#include <QtGui/QDrag>

#include <qrkernel/settingsManager.h>
#include <qrkernel/definitions.h>
#include <qrkernel/settingsManager.h>
#include <qrutils/widgets/searchLineEdit.h>

#include "mainWindow/palette/draggableElement.h"
#include "dialogs/metamodelingOnFly/propertiesDialog.h"

using namespace qReal;
using namespace gui;

PaletteTree::PaletteTree(QWidget *parent)
	: QWidget(parent)
	, mTree(nullptr)
	, mCurrentEditor(0)
{
	initUi();
}

void PaletteTree::initUi()
{
	mLayout = new QVBoxLayout(this);
	mLayout->setSpacing(0);
	QHBoxLayout * const controlButtonsLayout = new QHBoxLayout;
	controlButtonsLayout->setSpacing(0);

	mComboBox = new QComboBox;
	mComboBox->setGeometry(0, 0, 300, 50);
	mLayout->addWidget(mComboBox);
	mLayout->addLayout(controlButtonsLayout);

	ui::SearchLineEdit * const searchField = new ui::SearchLineEdit(this);
	connect(searchField, &ui::SearchLineEdit::textChanged, this, &PaletteTree::onSearchTextChanged);
	mLayout->addWidget(searchField);
	mSearchLineEdit = searchField;

	setMinimumSize(200, 100);
}

void PaletteTree::expand()
{
	mTree->expand();
}

void PaletteTree::collapse()
{
	mTree->collapse();
}

void PaletteTree::setActiveEditor(int index)
{
	if (0 <= index && index < mEditorsTrees.count()) {
		mCurrentEditor = index;
		if (mTree) {
			mTree->hide();
		}

		mTree = mEditorsTrees[index];
		mTree->show();
	}
}

void PaletteTree::setActiveEditor(const Id &id)
{
	setActiveEditor(mCategories.value(id, 0));
}

void PaletteTree::addEditorElements(EditorManagerInterface &editorManagerProxy, const Id &editor, const Id &diagram)
{
	mEditorManager = &editorManagerProxy;
	mEditorsNames.push_back(mEditorManager->friendlyName(diagram));

	mCategories[diagram] = mEditorsTrees.size();

	mComboBox->addItem(mEditorManager->friendlyName(diagram));

	PaletteTreeWidgets *editorTree = new PaletteTreeWidgets(*this, mMainWindow, *mEditorManager, editor, diagram);
	editorTree->hide();

	mEditorsTrees.push_back(editorTree);
	mLayout->addWidget(editorTree);
}

void PaletteTree::initDone()
{
	if (mComboBox->count() == 1) {
		// In case of empty combobox we do not hide it for user`s ensuring in items absence
		mComboBox->hide();
	} else {
		connect(mComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setActiveEditor(int)));
		mComboBox->show();
	}

	setActiveEditor(SettingsManager::value("CurrentIndex", 0).toInt());
	if (mTree) {
		mTree->resizeIcons();
	}
}

void PaletteTree::setComboBox(const Id &id)
{
	mComboBox->setCurrentIndex(mCategories.value(id, -1));
}

QComboBox* PaletteTree::comboBox() const
{
	return mComboBox;
}

QList<QString> PaletteTree::editorsNames() const
{
	return mEditorsNames;
}

void PaletteTree::deleteEditor(const Id &id)
{
	if (mCategories.contains(id)) {
		PaletteTreeWidgets *tree = mEditorsTrees[mCategories[id]];
		if (mTree == tree) {
			mTree = nullptr;
		}

		mComboBox->removeItem(mCategories[id]);
		mEditorsNames.removeAt(mCategories[id]);
		mEditorsTrees.removeAt(mCategories[id]);

		delete tree;
		mCategories.remove(id);
	}
}

Id PaletteTree::currentEditor() const
{
	return mCategories.key(mCurrentEditor);
}

void PaletteTree::recreateTrees()
{
	deletePaletteTree();
	createPaletteTree();
}

void PaletteTree::createPaletteTree()
{
	mTree = new PaletteTreeWidgets(*this, mMainWindow, *mEditorManager);
	mTree->setMinimumHeight(0);
	mLayout->addWidget(mTree);
}

void PaletteTree::deletePaletteTree()
{
	mComboBox->clear();
	if (mTree) {
		mEditorsTrees.removeAll(mTree);
		mLayout->removeWidget(mTree);
		delete mTree;
	}

	qDeleteAll(mEditorsTrees);
	mEditorsTrees.clear();
	mEditorsNames.clear();
	mCategories.clear();
	mCurrentEditor = 0;
}

PaletteTree::~PaletteTree()
{
	deletePaletteTree();
}

void PaletteTree::setComboBoxIndex(int index)
{
	mComboBox->setCurrentIndex(index);
}

void PaletteTree::setComboBoxIndex()
{
	mComboBox->setCurrentIndex(SettingsManager::value("CurrentIndex", 0).toInt());
}

void PaletteTree::saveConfiguration()
{
	SettingsManager::setValue("PaletteRepresentation", mIconsView);
	SettingsManager::setValue("PaletteIconsInARowCount", mItemsCountInARow);
	int diagramIndex = 0;
	for (const PaletteTreeWidgets *editorTree : mEditorsTrees) {
		editorTree->saveConfiguration(mComboBox->itemText(diagramIndex));
		diagramIndex++;
	}

	SettingsManager::setValue("CurrentIndex", mComboBox->currentIndex() >= 0 ? mComboBox->currentIndex() : 0);
}

bool PaletteTree::iconsView() const
{
	return mIconsView;
}

void PaletteTree::setIconsView(bool iconsView)
{
	mIconsView = iconsView;
}

void PaletteTree::loadEditors(EditorManagerInterface &editorManagerProxy)
{
	for (const Id &editor : editorManagerProxy.editors()) {
		for (const Id &diagram : editorManagerProxy.diagrams(editor)) {
			addEditorElements(editorManagerProxy, editor, diagram);
		}
	}

	const int index = SettingsManager::value("CurrentIndex", 0).toInt();
	SettingsManager::setValue("CurrentIndex", index >= 0 ? index : 0);
}

void PaletteTree::setItemsCountInARow(int count)
{
	mItemsCountInARow = count;
}

int PaletteTree::itemsCountInARow() const
{
	return mItemsCountInARow;
}

void PaletteTree::resizeEvent(QResizeEvent *)
{
	if (mTree) {
		mTree->resizeIcons();
	}
}

int PaletteTree::maxItemsCountInARow() const
{
	const int max = mTree->maxItemsCountInARow();
	return max ? max : mItemsCountInARow;
}

void PaletteTree::onSearchTextChanged(const QRegExp &searchText)
{
	mTree->filter(searchText);
}

void PaletteTree::changeRepresentation()
{
	loadPalette(!mIconsView, mItemsCountInARow, mEditorManager);
	SettingsManager::setValue("PaletteRepresentation", mIconsView);
	SettingsManager::setValue("PaletteIconsInARowCount", mItemsCountInARow);
	emit paletteParametersChanged();
}

void PaletteTree::loadPalette(bool isIconsView, int itemsCount, EditorManagerInterface *editorManagerProxy)
{
	if (mEditorManager) {
		recreateTrees();
	}

	mIconsView = isIconsView;
	mEditorManager = editorManagerProxy;
	mItemsCountInARow = itemsCount;
	if (mEditorManager) {
		// TODO: Can it really be nullptr?
		loadEditors(*mEditorManager);
	}

	initDone();
	setComboBoxIndex();
	mSearchLineEdit->setVisible(!isIconsView);
}

void PaletteTree::initMainWindow(MainWindow *mainWindow)
{
	mMainWindow = mainWindow;
}

void PaletteTree::installEventFilter(QObject *obj)
{
	QWidget::installEventFilter(obj);
	comboBox()->installEventFilter(obj);
}

void PaletteTree::setElementVisible(const Id &metatype, bool visible)
{
	if (mTree) {
		mTree->setElementVisible(metatype, visible);
	}
}

void PaletteTree::setVisibleForAllElements(const Id &diagram, bool visible)
{
	for (PaletteTreeWidgets * const tree : mEditorsTrees) {
		if (tree->diagram() == diagram) {
			tree->setVisibleForAllElements(visible);
		}
	}
}

void PaletteTree::setElementEnabled(const Id &metatype, bool enabled)
{
	if (mTree) {
		mTree->setElementEnabled(metatype, enabled);
	}
}

void PaletteTree::setEnabledForAllElements(const Id &diagram, bool enabled)
{
	for (PaletteTreeWidgets * const tree : mEditorsTrees) {
		if (tree->diagram() == diagram) {
			tree->setEnabledForAllElements(enabled);
		}
	}
}

void PaletteTree::refreshUserPalettes()
{
	for (PaletteTreeWidgets * const tree : mEditorsTrees) {
		tree->refreshUserPalette();
	}
}

void PaletteTree::customizeExplosionTitles(const QString &userGroupTitle, const QString &userGroupDescription)
{
	for (PaletteTreeWidgets * const tree : mEditorsTrees) {
		tree->customizeExplosionTitles(userGroupTitle, userGroupDescription);
	}
}
<|endoftext|>


<commit_before>/*
   httptransfer.h - HTTP transfer

   Copyright (c) 2006 by Michaël Larouche <michael.larouche@kdemail.net>

   *************************************************************************
   *                                                                       *
   * This library is free software; you can redistribute it and/or         *
   * modify it under the terms of the GNU Lesser General Public            *
   * License as published by the Free Software Foundation; either          *
   * version 2 of the License, or (at your option) any later version.      *
   *                                                                       *
   *************************************************************************
*/
#include "httptransfer.h"

#include <QtNetwork/QHttpHeader>
#include <QtNetwork/QHttpRequestHeader>
#include <QtNetwork/QHttpResponseHeader>

namespace Papillon
{

class HttpTransfer::Private
{
public:
	// We use base class as a pointer for polymorphist.
	QHttpHeader *httpHeader;
};

HttpTransfer::HttpTransfer()
 : d(new Private)
{
}

HttpTransfer::~HttpTransfer()
{
	delete d;
}

}<commit_msg>SVN_SILENT: Make it compile<commit_after>/*
   httptransfer.h - HTTP transfer

   Copyright (c) 2006 by Michaël Larouche <michael.larouche@kdemail.net>

   *************************************************************************
   *                                                                       *
   * This library is free software; you can redistribute it and/or         *
   * modify it under the terms of the GNU Lesser General Public            *
   * License as published by the Free Software Foundation; either          *
   * version 2 of the License, or (at your option) any later version.      *
   *                                                                       *
   *************************************************************************
*/
#include "httptransfer.h"

#include <QtNetwork/QHttpHeader>
#include <QtNetwork/QHttpRequestHeader>
#include <QtNetwork/QHttpResponseHeader>

namespace Papillon
{

class HttpTransfer::Private
{
public:
	// We use base class as a pointer for polymorphist.
	QHttpHeader *httpHeader;
};

HttpTransfer::HttpTransfer(HttpTransferType type)
 : d(new Private)
{
}

HttpTransfer::~HttpTransfer()
{
	delete d;
}

}<|endoftext|>


<commit_before>#define MS_CLASS "RTC::RtpDataCounter"
// #define MS_LOG_DEV

#include "RTC/RtpDataCounter.hpp"
#include "Logger.hpp"
#include <cmath> // std::trunc()

namespace RTC
{
	void RateCalculator::Update(size_t size, uint64_t now)
	{
		MS_TRACE();

		// Ignore too old data. Should never happen.
		if (now < this->oldestTime)
			return;

		this->RemoveOldData(now);

		// Set data in the index before the oldest index.
		uint32_t offset = this->windowSize - 1;
		uint32_t index  = this->oldestIndex + offset;

		if (index >= this->windowSize)
			index -= this->windowSize;

		this->buffer[index].count += size;
		this->totalCount += size;
	}

	uint32_t RateCalculator::GetRate(uint64_t now)
	{
		MS_TRACE();

		this->RemoveOldData(now);

		float scale = this->scale / this->windowSize;

		return static_cast<uint32_t>(std::trunc(this->totalCount * scale + 0.5f));
	}

	void RateCalculator::RemoveOldData(uint64_t now)
	{
		MS_TRACE();

		uint64_t newOldestTime = now - this->windowSize;

		// Should never happen.
		if (newOldestTime < this->oldestTime)
			return;

		// We are in the same time unit (ms) as the last entry.
		if (newOldestTime == this->oldestTime)
			return;

		// A whole window size time has elapsed since last entry. Reset the buffer.
		if (newOldestTime > this->oldestTime + this->windowSize)
		{
			this->Reset(now);

			return;
		}

		while (this->oldestTime < newOldestTime)
		{
			const BufferItem& oldestItem = buffer[this->oldestIndex];

			this->totalCount -= oldestItem.count;
			this->buffer[this->oldestIndex] = BufferItem();

			if (++this->oldestIndex >= this->windowSize)
				this->oldestIndex = 0;

			++this->oldestTime;
		}

		this->oldestTime = newOldestTime;
	}

	void RtpDataCounter::Update(RTC::RtpPacket* packet)
	{
		uint64_t now = DepLibUV::GetTime();

		this->packets++;
		this->bytes += packet->GetSize();
		this->rate.Update(packet->GetSize(), now);
	}
} // namespace RTC
<commit_msg>RTC: Add error log<commit_after>#define MS_CLASS "RTC::RtpDataCounter"
// #define MS_LOG_DEV

#include "RTC/RtpDataCounter.hpp"
#include "Logger.hpp"
#include <cmath> // std::trunc()

namespace RTC
{
	void RateCalculator::Update(size_t size, uint64_t now)
	{
		MS_TRACE();

		// Ignore too old data. Should never happen.
		if (now < this->oldestTime)
			return;

		this->RemoveOldData(now);

		// Set data in the index before the oldest index.
		uint32_t offset = this->windowSize - 1;
		uint32_t index  = this->oldestIndex + offset;

		if (index >= this->windowSize)
			index -= this->windowSize;

		this->buffer[index].count += size;
		this->totalCount += size;
	}

	uint32_t RateCalculator::GetRate(uint64_t now)
	{
		MS_TRACE();

		this->RemoveOldData(now);

		float scale = this->scale / this->windowSize;

		return static_cast<uint32_t>(std::trunc(this->totalCount * scale + 0.5f));
	}

	void RateCalculator::RemoveOldData(uint64_t now)
	{
		MS_TRACE();

		uint64_t newOldestTime = now - this->windowSize;

		// Should never happen.
		if (newOldestTime < this->oldestTime)
		{
			MS_ERROR(
			  "current time [%" PRIu64 "] is older than a previous [%" PRIu64 "]",
			  newOldestTime,
			  this->oldestTime);
			return;
		}

		// We are in the same time unit (ms) as the last entry.
		if (newOldestTime == this->oldestTime)
			return;

		// A whole window size time has elapsed since last entry. Reset the buffer.
		if (newOldestTime > this->oldestTime + this->windowSize)
		{
			this->Reset(now);

			return;
		}

		while (this->oldestTime < newOldestTime)
		{
			const BufferItem& oldestItem = buffer[this->oldestIndex];

			this->totalCount -= oldestItem.count;
			this->buffer[this->oldestIndex] = BufferItem();

			if (++this->oldestIndex >= this->windowSize)
				this->oldestIndex = 0;

			++this->oldestTime;
		}

		this->oldestTime = newOldestTime;
	}

	void RtpDataCounter::Update(RTC::RtpPacket* packet)
	{
		uint64_t now = DepLibUV::GetTime();

		this->packets++;
		this->bytes += packet->GetSize();
		this->rate.Update(packet->GetSize(), now);
	}
} // namespace RTC
<|endoftext|>


<commit_before>#include "Text.h"

using namespace agl;

const char* agl::TXT_VERTEX_SOURCE = "\
#version 330 core \n\
layout (location = 0) in vec2 pos; \n\
out vec2 texCoord; \n\
out vec2 texSize; \n\
uniform vec2 topLeft; \n\
uniform vec2 texDimensions; \n\
uniform vec2 screenDimensions; \n\
\n\
void main() { \n\
	texSize = texDimensions; \n\
	texCoord = pos; \n\
	vec2 position = (topLeft + pos * texSize) / screenDimensions; \n\
	gl_Position = vec4(position * vec2(2.0f, -2.0f) + vec2(-1.0f, 1.0f), 1.0f, 1.0f); \n\
} \
";
const char* agl::TXT_FRAGMENT_SOURCE = "\
#version 330 core \n\
in vec2 texCoord; \n\
in vec2 texSize; \n\
out vec4 color; \n\
uniform sampler2D tex; \n\
uniform vec4 topColor; \n\
uniform vec4 bottomColor; \n\
uniform float scale; \n\
\n\
void main() { \n\
	vec2 e1 = vec2(1, 0) / texSize; \n\
	vec2 e2 = vec2(0, 1) / texSize; \n\
	float a = texture(tex, texCoord).a; \n\
	a = (a - 205.0 / 255) * 255 / 50; \n\
	float an = texture(tex, texCoord + e2).a; \n\
	float as = texture(tex, texCoord - e2).a; \n\
	float aw = texture(tex, texCoord - e1).a; \n\
	float ae = texture(tex, texCoord + e1).a; \n\
	float av = (an + as + aw + ae) * 0.25; \n\
	av = (av - 205.0 / 255) * 255 / 50; \n\
	a = a + 0.5 * scale * av * (1 - a); \n\
	color = vec4(texture(tex, texCoord).rgb, a) * mix(bottomColor, topColor, texCoord.y); \n\
} \
";

Text::Text() {
	texture = new Texture();
	width = 0;
	height = 0;
	margin = 999;
	size = 1;
	app = nullptr;
	hasInitializedProgram = false;
	topColor = bottomColor = glm::vec4(0, 0, 0, 1);
	position = glm::vec2(0, 0);
	font = "VL Gothic";
}

Text::~Text() {
	delete texture;
}

GLfloat TEXT_BORDER_COLOR[] = { 1.0f, 1.0f, 1.0f, 0.0f };

void agl::Text::setText(std::string txt, bool relayout) {
	if (relayout) {
		renderText(txt.c_str(), font.c_str(), width, height, margin, size, *texture);
		texture->bind();
		glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, TEXT_BORDER_COLOR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
	}
	text = txt;
}

void agl::Text::setUp() {
	if (app == nullptr)
		throw "Current app must be set first!";
	Shader vertex(TXT_VERTEX_SOURCE, GL_VERTEX_SHADER);
	Shader fragment(TXT_FRAGMENT_SOURCE, GL_FRAGMENT_SHADER);
	program.attach(vertex);
	program.attach(fragment);
	program.link(); // There you go!
	hasInitializedProgram = true;
	vao.setActive();
	// Vertex data
	vbo.feedData(sizeof(rectangleVertices), (void*) rectangleVertices, GL_DYNAMIC_DRAW);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), (GLvoid*) 0);
	resetVBO();
	resetVAO();
}

void agl::Text::tick() {
	glEnable(GL_BLEND);
	BM_ALPHA.use();
	glDisable(GL_CULL_FACE);
	glDisable(GL_DEPTH_TEST);
	vao.setActive();
	program.use();
	texture->bindTo(0);
	if (app == nullptr) throw "App must be set first";
	SETUNSP(program, 1i, "tex", 0);
	SETUNSP(program, 1f, "scale", (GLfloat) size);
	SETUNSP2(program, 2f, "topLeft", position.x, position.y);
	SETUNSP2(program, 2f, "texDimensions", (GLfloat) width, (GLfloat) height);
	SETUNSP2(program, 2f, "screenDimensions", (GLfloat) app->getWidth(), (GLfloat) app->getHeight());
	SETUNSPV(program, 4fv, "topColor", topColor.data);
	SETUNSPV(program, 4fv, "bottomColor", bottomColor.data);
	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
	resetVAO();
}

void agl::Text::update() {
}

void agl::Text::_tearDown() {
}
<commit_msg>Do more experiments with text FXAA<commit_after>#include "Text.h"

using namespace agl;

const char* agl::TXT_VERTEX_SOURCE = "\
#version 330 core \n\
layout (location = 0) in vec2 pos; \n\
out vec2 texCoord; \n\
out vec2 texSize; \n\
uniform vec2 topLeft; \n\
uniform vec2 texDimensions; \n\
uniform vec2 screenDimensions; \n\
\n\
void main() { \n\
	texSize = texDimensions; \n\
	texCoord = pos; \n\
	vec2 position = (topLeft + pos * texSize) / screenDimensions; \n\
	gl_Position = vec4(position * vec2(2.0f, -2.0f) + vec2(-1.0f, 1.0f), 1.0f, 1.0f); \n\
} \
";
const char* agl::TXT_FRAGMENT_SOURCE = "\
#version 330 core \n\
in vec2 texCoord; \n\
in vec2 texSize; \n\
out vec4 color; \n\
uniform sampler2D tex; \n\
uniform vec4 topColor; \n\
uniform vec4 bottomColor; \n\
uniform float scale; \n\
\n\
void main() { \n\
	vec2 e1 = vec2(0.5 * scale, 0) / texSize; \n\
	vec2 e2 = vec2(0, 0.5 * scale) / texSize; \n\
	float a = texture(tex, texCoord).a; \n\
	a = (a - 205.0 / 255) * 255 / 50; \n\
	float an = texture(tex, texCoord + e2).a; \n\
	float as = texture(tex, texCoord - e2).a; \n\
	float aw = texture(tex, texCoord - e1).a; \n\
	float ae = texture(tex, texCoord + e1).a; \n\
	float ann = texture(tex, texCoord + 2 * e2).a; \n\
	float ass = texture(tex, texCoord - 2 * e2).a; \n\
	float aww = texture(tex, texCoord - 2 * e1).a; \n\
	float aee = texture(tex, texCoord + 2 * e1).a; \n\
	float av = (an + as + aw + ae + ann + ass + aww + aee) * 0.125; \n\
	av = (av - 205.0 / 255) * 255 / 50; \n\
	a = a + (av - 0.5) * (1 - a); \n\
	a = clamp(a, 0, 1); \n\
	color = vec4(texture(tex, texCoord).rgb, a) * mix(bottomColor, topColor, texCoord.y); \n\
} \
";

Text::Text() {
	texture = new Texture();
	width = 0;
	height = 0;
	margin = 999;
	size = 1;
	app = nullptr;
	hasInitializedProgram = false;
	topColor = bottomColor = glm::vec4(0, 0, 0, 1);
	position = glm::vec2(0, 0);
	font = "VL Gothic";
}

Text::~Text() {
	delete texture;
}

GLfloat TEXT_BORDER_COLOR[] = { 1.0f, 1.0f, 1.0f, 0.0f };

void agl::Text::setText(std::string txt, bool relayout) {
	if (relayout) {
		renderText(txt.c_str(), font.c_str(), width, height, margin, size, *texture);
		texture->bind();
		glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, TEXT_BORDER_COLOR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
	}
	text = txt;
}

void agl::Text::setUp() {
	if (app == nullptr)
		throw "Current app must be set first!";
	Shader vertex(TXT_VERTEX_SOURCE, GL_VERTEX_SHADER);
	Shader fragment(TXT_FRAGMENT_SOURCE, GL_FRAGMENT_SHADER);
	program.attach(vertex);
	program.attach(fragment);
	program.link(); // There you go!
	hasInitializedProgram = true;
	vao.setActive();
	// Vertex data
	vbo.feedData(sizeof(rectangleVertices), (void*) rectangleVertices, GL_DYNAMIC_DRAW);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), (GLvoid*) 0);
	resetVBO();
	resetVAO();
}

void agl::Text::tick() {
	glEnable(GL_BLEND);
	BM_ALPHA.use();
	glDisable(GL_CULL_FACE);
	glDisable(GL_DEPTH_TEST);
	vao.setActive();
	program.use();
	texture->bindTo(0);
	if (app == nullptr) throw "App must be set first";
	SETUNSP(program, 1i, "tex", 0);
	SETUNSP(program, 1f, "scale", (GLfloat) size);
	SETUNSP2(program, 2f, "topLeft", position.x, position.y);
	SETUNSP2(program, 2f, "texDimensions", (GLfloat) width, (GLfloat) height);
	SETUNSP2(program, 2f, "screenDimensions", (GLfloat) app->getWidth(), (GLfloat) app->getHeight());
	SETUNSPV(program, 4fv, "topColor", topColor.data);
	SETUNSPV(program, 4fv, "bottomColor", bottomColor.data);
	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
	resetVAO();
}

void agl::Text::update() {
}

void agl::Text::_tearDown() {
}
<|endoftext|>


<commit_before>#include <WProgram.h>
#include "aLM335.h"

/* aLM335 Copyright 2011 Kes Calhoun
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    Redistributions of source code must retain the above copyright notice,
	this list of conditions and the following disclaimer.

    Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

aLM335::aLM335() {
  _pin = 0;
  _refVoltage = 5;
  refFactorMetric = _refVoltage * 100 / 1024;
  refFactorImperial = _refVoltage * 180 / 1024;
}

aLM335::aLM335(int input) {
  _pin = input;
  _refVoltage = 5;
  refFactorMetric = _refVoltage * 100 / 1024;
  refFactorImperial = _refVoltage * 180 / 1024;
}

aLM335::aLM335(int input, float voltage) {
  _pin = input;
  _refVoltage = voltage;
  refFactorMetric = _refVoltage * 100 / 1024;
  refFactorImperial = _refVoltage * 180 / 1024;
}

aLM335::aLM335(int input, float voltage, bool externalReference) {
  _pin = input;
  if (externalReference) {
    analogReference(EXTERNAL);
  }
  else {
    analogReference(DEFAULT);
  }
  _refVoltage = voltage;
  refFactorMetric = _refVoltage * 100 / 1024;
  refFactorImperial = _refVoltage * 180 / 1024;
}

int aLM335::getRaw() {

  return (analogRead(_pin));

}

float aLM335::getKelvin() {

  float temperature = getRaw();
  temperature *= refFactorMetric;

  return (temperature);

}

float aLM335::getCelsius() {

  float temperature = getRaw();
  temperature *= refFactorMetric;
  temperature -= 273;

  return (temperature);

}

float aLM335::getFahrenheit() {

  float temperature = getRaw();
  temperature *= refFactorImperial;
  temperature -= 459.67;

  return (temperature);

}
<commit_msg>Fixed formulas for slightly better accuracy.<commit_after>#include <WProgram.h>
#include "aLM335.h"

/* aLM335 Copyright 2011 Kes Calhoun
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    Redistributions of source code must retain the above copyright notice,
	this list of conditions and the following disclaimer.

    Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

aLM335::aLM335() {
  _pin = 0;
  _refVoltage = 5;
  refFactorMetric = _refVoltage * 100 / 1023;
  refFactorImperial = _refVoltage * 180 / 1023;
}

aLM335::aLM335(int input) {
  _pin = input;
  _refVoltage = 5;
  refFactorMetric = _refVoltage * 100 / 1023;
  refFactorImperial = _refVoltage * 180 / 1023;
}

aLM335::aLM335(int input, float voltage) {
  _pin = input;
  _refVoltage = voltage;
  refFactorMetric = _refVoltage * 100 / 1023;
  refFactorImperial = _refVoltage * 180 / 1023;
}

aLM335::aLM335(int input, float voltage, bool externalReference) {
  _pin = input;
  if (externalReference) {
    analogReference(EXTERNAL);
  }
  else {
    analogReference(DEFAULT);
  }
  _refVoltage = voltage;
  refFactorMetric = _refVoltage * 100 / 1023;
  refFactorImperial = _refVoltage * 180 / 1023;
}

int aLM335::getRaw() {

  return (analogRead(_pin));

}

float aLM335::getKelvin() {

  float temperature = getRaw();
  temperature *= refFactorMetric;

  return (temperature);

}

float aLM335::getCelsius() {

  float temperature = getRaw();
  temperature *= refFactorMetric;
  temperature -= 273;

  return (temperature);

}

float aLM335::getFahrenheit() {

  float temperature = getRaw();
  temperature *= refFactorImperial;
  temperature -= 459.67;

  return (temperature);

}
<|endoftext|>