<commit_before>#include <string.h>
#include "dmonitoring.h"
#include "common/mat.h"
#include "common/timing.h"
#include "common/params.h"

#include <libyuv.h>

#define MODEL_WIDTH 320
#define MODEL_HEIGHT 640
#define FULL_W 852

#if defined(QCOM) || defined(QCOM2)
#define input_lambda(x) (x - 128.f) * 0.0078125f
#else
#define input_lambda(x) x // for non SNPE running platforms, assume keras model instead has lambda layer
#endif

void dmonitoring_init(DMonitoringModelState* s) {
#if defined(QCOM) || defined(QCOM2)
  const char* model_path = "../../models/dmonitoring_model_q.dlc";
#else
  const char* model_path = "../../models/dmonitoring_model.dlc";
#endif
  s->m = new DefaultRunModel(model_path, (float*)&s->output, OUTPUT_SIZE, USE_DSP_RUNTIME);
  s->is_rhd = read_db_bool("IsRHD");
}

template <class T>
static inline T *get_buffer(std::vector<T> &buf, const size_t size) {
  if (buf.size() < size) {
    buf.resize(size);
  }
  return buf.data();
}

DMonitoringResult dmonitoring_eval_frame(DMonitoringModelState* s, void* stream_buf, int width, int height) {

  uint8_t *raw_buf = (uint8_t*) stream_buf;
  uint8_t *raw_y_buf = raw_buf;
  uint8_t *raw_u_buf = raw_y_buf + (width * height);
  uint8_t *raw_v_buf = raw_u_buf + ((width/2) * (height/2));

  int cropped_width = height/2;
  int cropped_height = height;

  int resized_width = MODEL_WIDTH;
  int resized_height = MODEL_HEIGHT;

  uint8_t *cropped_y_buf = get_buffer(s->cropped_buf, cropped_width*cropped_height*3/2);
  uint8_t *cropped_u_buf = cropped_y_buf + (cropped_width * cropped_height);
  uint8_t *cropped_v_buf = cropped_u_buf + ((cropped_width/2) * (cropped_height/2));

  if (!s->is_rhd) {
    for (int r = 0; r < height/2; r++) {
      memcpy(cropped_y_buf + 2*r*cropped_width, raw_y_buf + 2*r*width + (width - cropped_width), cropped_width);
      memcpy(cropped_y_buf + (2*r+1)*cropped_width, raw_y_buf + (2*r+1)*width + (width - cropped_width), cropped_width);
      memcpy(cropped_u_buf + r*cropped_width/2, raw_u_buf + r*width/2 + ((width/2) - (cropped_width/2)), cropped_width/2);
      memcpy(cropped_v_buf + r*cropped_width/2, raw_v_buf + r*width/2 + ((width/2) - (cropped_width/2)), cropped_width/2);
    }
  } else {
    // not tested
    uint8_t *premirror_cropped_y_buf = get_buffer(s->premirror_cropped_buf, cropped_width*cropped_height*3/2);
    uint8_t *premirror_cropped_u_buf = premirror_cropped_y_buf + (cropped_width * cropped_height);
    uint8_t *premirror_cropped_v_buf = premirror_cropped_u_buf + ((cropped_width/2) * (cropped_height/2));
    for (int r = 0; r < height/2; r++) {
      memcpy(premirror_cropped_y_buf + 2*r*cropped_width, raw_y_buf + 2*r*width, cropped_width);
      memcpy(premirror_cropped_y_buf + (2*r+1)*cropped_width, raw_y_buf + (2*r+1)*width, cropped_width);
      memcpy(premirror_cropped_u_buf + r*cropped_width/2, raw_u_buf + r*width/2, cropped_width/2);
      memcpy(premirror_cropped_v_buf + r*cropped_width/2, raw_v_buf + r*width/2, cropped_width/2);
    }
    libyuv::I420Mirror(premirror_cropped_y_buf, cropped_width,
                       premirror_cropped_u_buf, cropped_width/2,
                       premirror_cropped_v_buf, cropped_width/2,
                       cropped_y_buf, cropped_width,
                       cropped_u_buf, cropped_width/2,
                       cropped_v_buf, cropped_width/2,
                       cropped_width, cropped_height);
  }

  uint8_t *resized_buf = get_buffer(s->resized_buf, resized_width*resized_height*3/2);
  uint8_t *resized_y_buf = resized_buf;
  uint8_t *resized_u_buf = resized_y_buf + (resized_width * resized_height);
  uint8_t *resized_v_buf = resized_u_buf + ((resized_width/2) * (resized_height/2));

  libyuv::FilterMode mode = libyuv::FilterModeEnum::kFilterBilinear;
  libyuv::I420Scale(cropped_y_buf, cropped_width,
                    cropped_u_buf, cropped_width/2,
                    cropped_v_buf, cropped_width/2,
                    cropped_width, cropped_height,
                    resized_y_buf, resized_width,
                    resized_u_buf, resized_width/2,
                    resized_v_buf, resized_width/2,
                    resized_width, resized_height,
                    mode);

  int yuv_buf_len = (MODEL_WIDTH/2) * (MODEL_HEIGHT/2) * 6; // Y|u|v -> y|y|y|y|u|v
  float *net_input_buf = get_buffer(s->net_input_buf, yuv_buf_len);
  // one shot conversion, O(n) anyway
  // yuvframe2tensor, normalize
  for (int r = 0; r < MODEL_HEIGHT/2; r++) {
    for (int c = 0; c < MODEL_WIDTH/2; c++) {
      // Y_ul
      net_input_buf[(c*MODEL_HEIGHT/2) + r] = input_lambda(resized_buf[(2*r*resized_width) + (2*c)]);
      // Y_ur
      net_input_buf[(c*MODEL_HEIGHT/2) + r + ((MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width) + (2*c+1)]);
      // Y_dl
      net_input_buf[(c*MODEL_HEIGHT/2) + r + (2*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width+1) + (2*c)]);
      // Y_dr
      net_input_buf[(c*MODEL_HEIGHT/2) + r + (3*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width+1) + (2*c+1)]);
      // U
      net_input_buf[(c*MODEL_HEIGHT/2) + r + (4*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(resized_width*resized_height) + (r*resized_width/2) + c]);
      // V
      net_input_buf[(c*MODEL_HEIGHT/2) + r + (5*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(resized_width*resized_height) + ((resized_width/2)*(resized_height/2)) + (r*resized_width/2) + c]);
    }
  }

  //printf("preprocess completed. %d \n", yuv_buf_len);
  //FILE *dump_yuv_file = fopen("/tmp/rawdump.yuv", "wb");
  //fwrite(raw_buf, height*width*3/2, sizeof(uint8_t), dump_yuv_file);
  //fclose(dump_yuv_file);

  //FILE *dump_yuv_file2 = fopen("/tmp/inputdump.yuv", "wb");
  //fwrite(net_input_buf, MODEL_HEIGHT*MODEL_WIDTH*3/2, sizeof(float), dump_yuv_file2);
  //fclose(dump_yuv_file2);

  s->m->execute(net_input_buf, yuv_buf_len);

  DMonitoringResult ret = {0};
  memcpy(&ret.face_orientation, &s->output[0], sizeof ret.face_orientation);
  memcpy(&ret.face_orientation_meta, &s->output[6], sizeof ret.face_orientation_meta);
  memcpy(&ret.face_position, &s->output[3], sizeof ret.face_position);
  memcpy(&ret.face_position_meta, &s->output[9], sizeof ret.face_position_meta);
  memcpy(&ret.face_prob, &s->output[12], sizeof ret.face_prob);
  memcpy(&ret.left_eye_prob, &s->output[21], sizeof ret.left_eye_prob);
  memcpy(&ret.right_eye_prob, &s->output[30], sizeof ret.right_eye_prob);
  memcpy(&ret.left_blink_prob, &s->output[31], sizeof ret.right_eye_prob);
  memcpy(&ret.right_blink_prob, &s->output[32], sizeof ret.right_eye_prob);
  memcpy(&ret.sg_prob, &s->output[33], sizeof ret.sg_prob);
  ret.face_orientation_meta[0] = softplus(ret.face_orientation_meta[0]);
  ret.face_orientation_meta[1] = softplus(ret.face_orientation_meta[1]);
  ret.face_orientation_meta[2] = softplus(ret.face_orientation_meta[2]);
  ret.face_position_meta[0] = softplus(ret.face_position_meta[0]);
  ret.face_position_meta[1] = softplus(ret.face_position_meta[1]);
  return ret;
}

void dmonitoring_publish(PubMaster &pm, uint32_t frame_id, const DMonitoringResult &res){
  // make msg
  capnp::MallocMessageBuilder msg;
  cereal::Event::Builder event = msg.initRoot<cereal::Event>();
  event.setLogMonoTime(nanos_since_boot());

  auto framed = event.initDriverState();
  framed.setFrameId(frame_id);

  kj::ArrayPtr<const float> face_orientation(&res.face_orientation[0], ARRAYSIZE(res.face_orientation));
  kj::ArrayPtr<const float> face_orientation_std(&res.face_orientation_meta[0], ARRAYSIZE(res.face_orientation_meta));
  kj::ArrayPtr<const float> face_position(&res.face_position[0], ARRAYSIZE(res.face_position));
  kj::ArrayPtr<const float> face_position_std(&res.face_position_meta[0], ARRAYSIZE(res.face_position_meta));
  framed.setFaceOrientation(face_orientation);
  framed.setFaceOrientationStd(face_orientation_std);
  framed.setFacePosition(face_position);
  framed.setFacePositionStd(face_position_std);
  framed.setFaceProb(res.face_prob);
  framed.setLeftEyeProb(res.left_eye_prob);
  framed.setRightEyeProb(res.right_eye_prob);
  framed.setLeftBlinkProb(res.left_blink_prob);
  framed.setRightBlinkProb(res.right_blink_prob);
  framed.setSgProb(res.sg_prob);

  pm.send("driverState", msg);
}

void dmonitoring_free(DMonitoringModelState* s) {
  delete s->m;
}
<commit_msg>swap ur/dl (#2153)<commit_after>#include <string.h>
#include "dmonitoring.h"
#include "common/mat.h"
#include "common/timing.h"
#include "common/params.h"

#include <libyuv.h>

#define MODEL_WIDTH 320
#define MODEL_HEIGHT 640
#define FULL_W 852

#if defined(QCOM) || defined(QCOM2)
#define input_lambda(x) (x - 128.f) * 0.0078125f
#else
#define input_lambda(x) x // for non SNPE running platforms, assume keras model instead has lambda layer
#endif

void dmonitoring_init(DMonitoringModelState* s) {
#if defined(QCOM) || defined(QCOM2)
  const char* model_path = "../../models/dmonitoring_model_q.dlc";
#else
  const char* model_path = "../../models/dmonitoring_model.dlc";
#endif
  s->m = new DefaultRunModel(model_path, (float*)&s->output, OUTPUT_SIZE, USE_DSP_RUNTIME);
  s->is_rhd = read_db_bool("IsRHD");
}

template <class T>
static inline T *get_buffer(std::vector<T> &buf, const size_t size) {
  if (buf.size() < size) {
    buf.resize(size);
  }
  return buf.data();
}

DMonitoringResult dmonitoring_eval_frame(DMonitoringModelState* s, void* stream_buf, int width, int height) {

  uint8_t *raw_buf = (uint8_t*) stream_buf;
  uint8_t *raw_y_buf = raw_buf;
  uint8_t *raw_u_buf = raw_y_buf + (width * height);
  uint8_t *raw_v_buf = raw_u_buf + ((width/2) * (height/2));

  int cropped_width = height/2;
  int cropped_height = height;

  int resized_width = MODEL_WIDTH;
  int resized_height = MODEL_HEIGHT;

  uint8_t *cropped_y_buf = get_buffer(s->cropped_buf, cropped_width*cropped_height*3/2);
  uint8_t *cropped_u_buf = cropped_y_buf + (cropped_width * cropped_height);
  uint8_t *cropped_v_buf = cropped_u_buf + ((cropped_width/2) * (cropped_height/2));

  if (!s->is_rhd) {
    for (int r = 0; r < height/2; r++) {
      memcpy(cropped_y_buf + 2*r*cropped_width, raw_y_buf + 2*r*width + (width - cropped_width), cropped_width);
      memcpy(cropped_y_buf + (2*r+1)*cropped_width, raw_y_buf + (2*r+1)*width + (width - cropped_width), cropped_width);
      memcpy(cropped_u_buf + r*cropped_width/2, raw_u_buf + r*width/2 + ((width/2) - (cropped_width/2)), cropped_width/2);
      memcpy(cropped_v_buf + r*cropped_width/2, raw_v_buf + r*width/2 + ((width/2) - (cropped_width/2)), cropped_width/2);
    }
  } else {
    // not tested
    uint8_t *premirror_cropped_y_buf = get_buffer(s->premirror_cropped_buf, cropped_width*cropped_height*3/2);
    uint8_t *premirror_cropped_u_buf = premirror_cropped_y_buf + (cropped_width * cropped_height);
    uint8_t *premirror_cropped_v_buf = premirror_cropped_u_buf + ((cropped_width/2) * (cropped_height/2));
    for (int r = 0; r < height/2; r++) {
      memcpy(premirror_cropped_y_buf + 2*r*cropped_width, raw_y_buf + 2*r*width, cropped_width);
      memcpy(premirror_cropped_y_buf + (2*r+1)*cropped_width, raw_y_buf + (2*r+1)*width, cropped_width);
      memcpy(premirror_cropped_u_buf + r*cropped_width/2, raw_u_buf + r*width/2, cropped_width/2);
      memcpy(premirror_cropped_v_buf + r*cropped_width/2, raw_v_buf + r*width/2, cropped_width/2);
    }
    libyuv::I420Mirror(premirror_cropped_y_buf, cropped_width,
                       premirror_cropped_u_buf, cropped_width/2,
                       premirror_cropped_v_buf, cropped_width/2,
                       cropped_y_buf, cropped_width,
                       cropped_u_buf, cropped_width/2,
                       cropped_v_buf, cropped_width/2,
                       cropped_width, cropped_height);
  }

  uint8_t *resized_buf = get_buffer(s->resized_buf, resized_width*resized_height*3/2);
  uint8_t *resized_y_buf = resized_buf;
  uint8_t *resized_u_buf = resized_y_buf + (resized_width * resized_height);
  uint8_t *resized_v_buf = resized_u_buf + ((resized_width/2) * (resized_height/2));

  libyuv::FilterMode mode = libyuv::FilterModeEnum::kFilterBilinear;
  libyuv::I420Scale(cropped_y_buf, cropped_width,
                    cropped_u_buf, cropped_width/2,
                    cropped_v_buf, cropped_width/2,
                    cropped_width, cropped_height,
                    resized_y_buf, resized_width,
                    resized_u_buf, resized_width/2,
                    resized_v_buf, resized_width/2,
                    resized_width, resized_height,
                    mode);

  int yuv_buf_len = (MODEL_WIDTH/2) * (MODEL_HEIGHT/2) * 6; // Y|u|v -> y|y|y|y|u|v
  float *net_input_buf = get_buffer(s->net_input_buf, yuv_buf_len);
  // one shot conversion, O(n) anyway
  // yuvframe2tensor, normalize
  for (int r = 0; r < MODEL_HEIGHT/2; r++) {
    for (int c = 0; c < MODEL_WIDTH/2; c++) {
      // Y_ul
      net_input_buf[(c*MODEL_HEIGHT/2) + r] = input_lambda(resized_buf[(2*r*resized_width) + (2*c)]);
      // Y_ur
      net_input_buf[(c*MODEL_HEIGHT/2) + r + (2*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width) + (2*c+1)]);
      // Y_dl
      net_input_buf[(c*MODEL_HEIGHT/2) + r + ((MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width+1) + (2*c)]);
      // Y_dr
      net_input_buf[(c*MODEL_HEIGHT/2) + r + (3*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width+1) + (2*c+1)]);
      // U
      net_input_buf[(c*MODEL_HEIGHT/2) + r + (4*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(resized_width*resized_height) + (r*resized_width/2) + c]);
      // V
      net_input_buf[(c*MODEL_HEIGHT/2) + r + (5*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(resized_width*resized_height) + ((resized_width/2)*(resized_height/2)) + (r*resized_width/2) + c]);
    }
  }

  //printf("preprocess completed. %d \n", yuv_buf_len);
  //FILE *dump_yuv_file = fopen("/tmp/rawdump.yuv", "wb");
  //fwrite(raw_buf, height*width*3/2, sizeof(uint8_t), dump_yuv_file);
  //fclose(dump_yuv_file);

  //FILE *dump_yuv_file2 = fopen("/tmp/inputdump.yuv", "wb");
  //fwrite(net_input_buf, MODEL_HEIGHT*MODEL_WIDTH*3/2, sizeof(float), dump_yuv_file2);
  //fclose(dump_yuv_file2);

  s->m->execute(net_input_buf, yuv_buf_len);

  DMonitoringResult ret = {0};
  memcpy(&ret.face_orientation, &s->output[0], sizeof ret.face_orientation);
  memcpy(&ret.face_orientation_meta, &s->output[6], sizeof ret.face_orientation_meta);
  memcpy(&ret.face_position, &s->output[3], sizeof ret.face_position);
  memcpy(&ret.face_position_meta, &s->output[9], sizeof ret.face_position_meta);
  memcpy(&ret.face_prob, &s->output[12], sizeof ret.face_prob);
  memcpy(&ret.left_eye_prob, &s->output[21], sizeof ret.left_eye_prob);
  memcpy(&ret.right_eye_prob, &s->output[30], sizeof ret.right_eye_prob);
  memcpy(&ret.left_blink_prob, &s->output[31], sizeof ret.right_eye_prob);
  memcpy(&ret.right_blink_prob, &s->output[32], sizeof ret.right_eye_prob);
  memcpy(&ret.sg_prob, &s->output[33], sizeof ret.sg_prob);
  ret.face_orientation_meta[0] = softplus(ret.face_orientation_meta[0]);
  ret.face_orientation_meta[1] = softplus(ret.face_orientation_meta[1]);
  ret.face_orientation_meta[2] = softplus(ret.face_orientation_meta[2]);
  ret.face_position_meta[0] = softplus(ret.face_position_meta[0]);
  ret.face_position_meta[1] = softplus(ret.face_position_meta[1]);
  return ret;
}

void dmonitoring_publish(PubMaster &pm, uint32_t frame_id, const DMonitoringResult &res){
  // make msg
  capnp::MallocMessageBuilder msg;
  cereal::Event::Builder event = msg.initRoot<cereal::Event>();
  event.setLogMonoTime(nanos_since_boot());

  auto framed = event.initDriverState();
  framed.setFrameId(frame_id);

  kj::ArrayPtr<const float> face_orientation(&res.face_orientation[0], ARRAYSIZE(res.face_orientation));
  kj::ArrayPtr<const float> face_orientation_std(&res.face_orientation_meta[0], ARRAYSIZE(res.face_orientation_meta));
  kj::ArrayPtr<const float> face_position(&res.face_position[0], ARRAYSIZE(res.face_position));
  kj::ArrayPtr<const float> face_position_std(&res.face_position_meta[0], ARRAYSIZE(res.face_position_meta));
  framed.setFaceOrientation(face_orientation);
  framed.setFaceOrientationStd(face_orientation_std);
  framed.setFacePosition(face_position);
  framed.setFacePositionStd(face_position_std);
  framed.setFaceProb(res.face_prob);
  framed.setLeftEyeProb(res.left_eye_prob);
  framed.setRightEyeProb(res.right_eye_prob);
  framed.setLeftBlinkProb(res.left_blink_prob);
  framed.setRightBlinkProb(res.right_blink_prob);
  framed.setSgProb(res.sg_prob);

  pm.send("driverState", msg);
}

void dmonitoring_free(DMonitoringModelState* s) {
  delete s->m;
}
<|endoftext|>


<commit_before>/*
 * StochasticReleaseTestProbe.cpp
 *
 *  Created on: Aug 28, 2013
 *      Author: pschultz
 */

#include "StochasticReleaseTestProbe.hpp"

namespace PV {

StochasticReleaseTestProbe::StochasticReleaseTestProbe(const char * name, HyPerCol * hc) {
   initialize_base();
   initStochasticReleaseTestProbe(name, hc);
}

StochasticReleaseTestProbe::StochasticReleaseTestProbe() {
   initialize_base();
}

int StochasticReleaseTestProbe::initialize_base() {
   conn = NULL;
   for (int k=0; k<9; k++) {
      bins[k] = 0;
   }
   sumbins = 0;
   binprobs[0] = 0.00023262907903552502; // erfc(3.5/sqrt(2))/2
   binprobs[1] = 0.005977036246740614; // (erfc(2.5/sqrt(2))-erfc(3.5/sqrt(2)))/2
   binprobs[2] = 0.06059753594308195; // (erfc(1.5/sqrt(2))-erfc(2.5/sqrt(2)))/2
   binprobs[3] = 0.24173033745712885; // (erfc(0.5/sqrt(2))-erfc(1.5/sqrt(2)))/2
   binprobs[4] = 0.3829249225480262; // erf(0.5/sqrt(2)
   binprobs[5] = 0.24173033745712885; // (erfc(0.5/sqrt(2))-erfc(1.5/sqrt(2)))/2
   binprobs[6] = 0.06059753594308195; // (erfc(1.5/sqrt(2))-erfc(2.5/sqrt(2)))/2
   binprobs[7] = 0.005977036246740614; // (erfc(2.5/sqrt(2))-erfc(3.5/sqrt(2)))/2
   binprobs[8] = 0.00023262907903552502; // erfc(3.5/sqrt(2))/2
   return PV_SUCCESS;
}

int StochasticReleaseTestProbe::initStochasticReleaseTestProbe(const char * name, HyPerCol * hc) {
   const char * classkeyword = hc->parameters()->groupKeywordFromName(name);
   HyPerLayer * targetlayer = NULL;
   char * message = NULL;
   const char * filename;
   getLayerFunctionProbeParameters(name, classkeyword, hc, &targetlayer, &message, &filename);
   int status = initStatsProbe(filename, targetlayer, BufActivity, message);

   const int numconns = hc->numberOfConnections();
   for (int c=0; c<numconns; c++) {
      if (!strcmp(hc->getConnection(c)->getPostLayerName(),getTargetLayer()->getName())) {
         assert(conn==NULL);
         conn = hc->getConnection(c);
      }
   }
   assert(conn!=NULL);
   return PV_SUCCESS;
}

int StochasticReleaseTestProbe::outputState(double timed) {
   int status = StatsProbe::outputState(timed);
   assert(status==PV_SUCCESS);

   assert(conn->numberOfAxonalArborLists()==1);
   assert(conn->getNumDataPatches()==1);
   assert(conn->xPatchSize()==1);
   assert(conn->yPatchSize()==1);
   assert(conn->fPatchSize()==1);
   pvdata_t wgt = *conn->get_wDataStart(0);
   HyPerLayer * pre = conn->preSynapticLayer();
   const pvdata_t * preactPtr = pre->getLayerData();
   const PVLayerLoc * preLoc = pre->getLayerLoc();
   const int numPreNeurons = pre->getNumNeurons();
   bool found=false;
   pvdata_t preact = 0.0f;
   for (int n=0; n<numPreNeurons; n++) {
      int nExt = kIndexExtended(n, preLoc->nx, preLoc->ny, preLoc->nf, preLoc->nb);
      pvdata_t a = preactPtr[nExt];
      if (a!=0.0f) {
         if (found) {
            assert(preact==a);
         }
         else {
            found = true;
            preact = a;
         }
      }
   }
   if (preact < 0.0f) preact = 0.0f;
   if (preact > 1.0f) preact = 1.0f;

   const int numNeurons = getTargetLayer()->getNumNeurons();
   const PVLayerLoc * loc = getTargetLayer()->getLayerLoc();
   const pvdata_t * activity = getTargetLayer()->getLayerData();
   for (int n=0; n<numNeurons; n++) {
      int nExt = kIndexExtended(n, loc->nx, loc->ny, loc->nf, loc->nb);
      assert(activity[nExt]==0 || activity[nExt]==wgt);
   }
   const int numGlobalNeurons = getTargetLayer()->getNumGlobalNeurons();
   double mean = preact * numGlobalNeurons;
   double stddev = sqrt(numGlobalNeurons*preact*(1-preact));
   double numStdDevs = stddev==0.0 && mean==nnz ? 0.0 : (nnz-mean)/stddev;
   HyPerCol * hc = getTargetLayer()->getParent();
   if (timed>0.0 && hc->columnId()==0) {
      fprintf(outputstream->fp, "    t=%f, number of standard deviations = %f\n", timed, numStdDevs);
      int bin = numStdDevs < -3.5 ? 0 :
                numStdDevs < -2.5 ? 1 :
                numStdDevs < -1.5 ? 2 :
                numStdDevs < -0.5 ? 3 :
                numStdDevs <= 0.5 ? 4 :
                numStdDevs <= 1.5 ? 5 :
                numStdDevs <= 2.5 ? 6 :
                numStdDevs <= 3.5 ? 7 : 8;
      bins[bin]++;
      sumbins++;
      if (hc->simulationTime()+hc->getDeltaTime()>=hc->getStopTime()) {
         fprintf(outputstream->fp, "    Histogram:  ");
         for (int k=0; k<9; k++) {
            fprintf(outputstream->fp, " %7d", bins[k]);
         }
         fprintf(outputstream->fp, "\n");

         int minallowed[9];
         int maxallowed[9];

         if (stddev==0) {
            for (int k=0; k<9; k++) {
               minallowed[k] = (k==4 ? sumbins : 0);
               maxallowed[k] = (k==4 ? sumbins : 0);
               assert(bins[k]==(k==4 ? sumbins : 0));
            }
         }
         else {
            assert(preact<1.0f && preact>0.0f);
            for (int k=0; k<9; k++) {
               // find first m for which prob(bins[k]<m) >= 0.005
               double p = binprobs[k];
               double outcomeprob = pow(1-p,sumbins);
               double cumulativeprob = outcomeprob;
               double m=0;
               printf("m=%10.4f, outcomeprob=%.20f, cumulativeprob=%.20f\n", m, outcomeprob, cumulativeprob);
               while(cumulativeprob < 0.005 && m <= sumbins) {
                  m++;
                  outcomeprob *= (sumbins+1-m)/m*p/(1-p);
                  cumulativeprob += outcomeprob;
                  printf("m=%10.4f, outcomeprob=%.20f, cumulativeprob=%.20f\n", m, outcomeprob, cumulativeprob);
               }
               minallowed[k] = m;
               if (bins[k]<minallowed[k]) status = PV_FAILURE;

               // find first m for which prob(bins[k]<m) < 0.995
               while(cumulativeprob <= 0.995 && sumbins) {
                  m++;
                  outcomeprob *= (sumbins+1-m)/m*p/(1-p);
                  cumulativeprob += outcomeprob;
                  printf("m=%10.4f, outcomeprob=%.20f, cumulativeprob=%.20f\n", m, outcomeprob, cumulativeprob);
               }
               maxallowed[k] = m;
               if (bins[k]>maxallowed[k]) status = PV_FAILURE;
            }
            fprintf(outputstream->fp, "    Min allowed:");
            for (int k=0; k<9; k++) {
               fprintf(outputstream->fp, " %7d", minallowed[k]);
            }
            fprintf(outputstream->fp, "\n");
            fprintf(outputstream->fp, "    Max allowed:");
            for (int k=0; k<9; k++) {
               fprintf(outputstream->fp, " %7d", maxallowed[k]);
            }
            fprintf(outputstream->fp, "\n");
            assert(status==PV_SUCCESS);
         }
      }
   }
   return status;
}

StochasticReleaseTestProbe::~StochasticReleaseTestProbe() {
}

} /* namespace PV */
<commit_msg>Patch to StochasticReleaseTestProbe<commit_after>/*
 * StochasticReleaseTestProbe.cpp
 *
 *  Created on: Aug 28, 2013
 *      Author: pschultz
 */

#include "StochasticReleaseTestProbe.hpp"

namespace PV {

StochasticReleaseTestProbe::StochasticReleaseTestProbe(const char * name, HyPerCol * hc) {
   initialize_base();
   initStochasticReleaseTestProbe(name, hc);
}

StochasticReleaseTestProbe::StochasticReleaseTestProbe() {
   initialize_base();
}

int StochasticReleaseTestProbe::initialize_base() {
   conn = NULL;
   for (int k=0; k<9; k++) {
      bins[k] = 0;
   }
   sumbins = 0;
   binprobs[0] = 0.00023262907903552502; // erfc(3.5/sqrt(2))/2
   binprobs[1] = 0.005977036246740614; // (erfc(2.5/sqrt(2))-erfc(3.5/sqrt(2)))/2
   binprobs[2] = 0.06059753594308195; // (erfc(1.5/sqrt(2))-erfc(2.5/sqrt(2)))/2
   binprobs[3] = 0.24173033745712885; // (erfc(0.5/sqrt(2))-erfc(1.5/sqrt(2)))/2
   binprobs[4] = 0.3829249225480262; // erf(0.5/sqrt(2)
   binprobs[5] = 0.24173033745712885; // (erfc(0.5/sqrt(2))-erfc(1.5/sqrt(2)))/2
   binprobs[6] = 0.06059753594308195; // (erfc(1.5/sqrt(2))-erfc(2.5/sqrt(2)))/2
   binprobs[7] = 0.005977036246740614; // (erfc(2.5/sqrt(2))-erfc(3.5/sqrt(2)))/2
   binprobs[8] = 0.00023262907903552502; // erfc(3.5/sqrt(2))/2
   return PV_SUCCESS;
}

int StochasticReleaseTestProbe::initStochasticReleaseTestProbe(const char * name, HyPerCol * hc) {
   const char * classkeyword = hc->parameters()->groupKeywordFromName(name);
   HyPerLayer * targetlayer = NULL;
   char * message = NULL;
   const char * filename;
   getLayerFunctionProbeParameters(name, classkeyword, hc, &targetlayer, &message, &filename);
   int status = initStatsProbe(filename, targetlayer, BufActivity, message);

   return PV_SUCCESS;
}

int StochasticReleaseTestProbe::outputState(double timed) {
   // Set conn.  Can't do that in initStochasticReleaseTestProbe because we need to search for a conn with the given post, and connections' postLayerName is not necessarily set.
   if (conn==NULL) {
      HyPerCol * hc = getTargetLayer()->getParent();
      PVParams * params = hc->parameters();
      int numconns = hc->numberOfConnections();
      for (int c=0; c<numconns; c++) {
         if (!strcmp(hc->getConnection(c)->getPostLayerName(),getTargetLayer()->getName())) {
            assert(conn==NULL); // Only one connection can go to this layer for this probe to work
            conn = hc->getConnection(c);
         }
      }
      assert(conn!=NULL);
   }
   int status = StatsProbe::outputState(timed);
   assert(status==PV_SUCCESS);

   assert(conn->numberOfAxonalArborLists()==1);
   assert(conn->getNumDataPatches()==1);
   assert(conn->xPatchSize()==1);
   assert(conn->yPatchSize()==1);
   assert(conn->fPatchSize()==1);
   pvdata_t wgt = *conn->get_wDataStart(0);
   HyPerLayer * pre = conn->preSynapticLayer();
   const pvdata_t * preactPtr = pre->getLayerData();
   const PVLayerLoc * preLoc = pre->getLayerLoc();
   const int numPreNeurons = pre->getNumNeurons();
   bool found=false;
   pvdata_t preact = 0.0f;
   for (int n=0; n<numPreNeurons; n++) {
      int nExt = kIndexExtended(n, preLoc->nx, preLoc->ny, preLoc->nf, preLoc->nb);
      pvdata_t a = preactPtr[nExt];
      if (a!=0.0f) {
         if (found) {
            assert(preact==a);
         }
         else {
            found = true;
            preact = a;
         }
      }
   }
   if (preact < 0.0f) preact = 0.0f;
   if (preact > 1.0f) preact = 1.0f;

   const int numNeurons = getTargetLayer()->getNumNeurons();
   const PVLayerLoc * loc = getTargetLayer()->getLayerLoc();
   const pvdata_t * activity = getTargetLayer()->getLayerData();
   for (int n=0; n<numNeurons; n++) {
      int nExt = kIndexExtended(n, loc->nx, loc->ny, loc->nf, loc->nb);
      assert(activity[nExt]==0 || activity[nExt]==wgt);
   }
   const int numGlobalNeurons = getTargetLayer()->getNumGlobalNeurons();
   double mean = preact * numGlobalNeurons;
   double stddev = sqrt(numGlobalNeurons*preact*(1-preact));
   double numStdDevs = stddev==0.0 && mean==nnz ? 0.0 : (nnz-mean)/stddev;
   HyPerCol * hc = getTargetLayer()->getParent();
   if (timed>0.0 && hc->columnId()==0) {
      fprintf(outputstream->fp, "    t=%f, number of standard deviations = %f\n", timed, numStdDevs);
      int bin = numStdDevs < -3.5 ? 0 :
                numStdDevs < -2.5 ? 1 :
                numStdDevs < -1.5 ? 2 :
                numStdDevs < -0.5 ? 3 :
                numStdDevs <= 0.5 ? 4 :
                numStdDevs <= 1.5 ? 5 :
                numStdDevs <= 2.5 ? 6 :
                numStdDevs <= 3.5 ? 7 : 8;
      bins[bin]++;
      sumbins++;
      if (hc->simulationTime()+hc->getDeltaTime()>=hc->getStopTime()) {
         fprintf(outputstream->fp, "    Histogram:  ");
         for (int k=0; k<9; k++) {
            fprintf(outputstream->fp, " %7d", bins[k]);
         }
         fprintf(outputstream->fp, "\n");

         int minallowed[9];
         int maxallowed[9];

         if (stddev==0) {
            for (int k=0; k<9; k++) {
               minallowed[k] = (k==4 ? sumbins : 0);
               maxallowed[k] = (k==4 ? sumbins : 0);
               assert(bins[k]==(k==4 ? sumbins : 0));
            }
         }
         else {
            assert(preact<1.0f && preact>0.0f);
            for (int k=0; k<9; k++) {
               // find first m for which prob(bins[k]<m) >= 0.005
               double p = binprobs[k];
               double outcomeprob = pow(1-p,sumbins);
               double cumulativeprob = outcomeprob;
               double m=0;
               printf("m=%10.4f, outcomeprob=%.20f, cumulativeprob=%.20f\n", m, outcomeprob, cumulativeprob);
               while(cumulativeprob < 0.005 && m <= sumbins) {
                  m++;
                  outcomeprob *= (sumbins+1-m)/m*p/(1-p);
                  cumulativeprob += outcomeprob;
                  printf("m=%10.4f, outcomeprob=%.20f, cumulativeprob=%.20f\n", m, outcomeprob, cumulativeprob);
               }
               minallowed[k] = m;
               if (bins[k]<minallowed[k]) status = PV_FAILURE;

               // find first m for which prob(bins[k]<m) < 0.995
               while(cumulativeprob <= 0.995 && sumbins) {
                  m++;
                  outcomeprob *= (sumbins+1-m)/m*p/(1-p);
                  cumulativeprob += outcomeprob;
                  printf("m=%10.4f, outcomeprob=%.20f, cumulativeprob=%.20f\n", m, outcomeprob, cumulativeprob);
               }
               maxallowed[k] = m;
               if (bins[k]>maxallowed[k]) status = PV_FAILURE;
            }
            fprintf(outputstream->fp, "    Min allowed:");
            for (int k=0; k<9; k++) {
               fprintf(outputstream->fp, " %7d", minallowed[k]);
            }
            fprintf(outputstream->fp, "\n");
            fprintf(outputstream->fp, "    Max allowed:");
            for (int k=0; k<9; k++) {
               fprintf(outputstream->fp, " %7d", maxallowed[k]);
            }
            fprintf(outputstream->fp, "\n");
            assert(status==PV_SUCCESS);
         }
      }
   }
   return status;
}

StochasticReleaseTestProbe::~StochasticReleaseTestProbe() {
}

} /* namespace PV */
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

// iostream is used for general output
#include <iostream>
#include <stdlib.h>

#include "otbMacro.h"
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbMapProjections.h"

#include "otbOrthoRectificationFilter.h"
#include "otbMapProjections.h"

#include "init/ossimInit.h"

int otbOrthoRectificationFilter(int argc, char* argv[])
{
  ossimInit::instance()->initialize(argc, argv);
  if (argc != 12)
    {
    std::cout << argv[0] <<
    " <input filename> <output filename> <origin easting> <origin northing> <x size> <y size> <x spacing> <y spacing> <UTM zone> <UTM hemisphere>"
              << std::endl;

    return EXIT_FAILURE;
    }

  typedef otb::Image<double, 2>                                                     ImageType;
  typedef otb::ImageFileReader<ImageType>                                           ReaderType;
  typedef otb::StreamingImageFileWriter<ImageType>                                  WriterType;
  typedef otb::UtmInverseProjection                                                 UtmMapProjectionType;
  typedef otb::OrthoRectificationFilter<ImageType, ImageType, UtmMapProjectionType> OrthoRectifFilterType;

  //Allocate pointer
  ReaderType::Pointer reader = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();

  OrthoRectifFilterType::Pointer orthoRectifFilter = OrthoRectifFilterType::New();
  UtmMapProjectionType::Pointer  utmMapProjection = UtmMapProjectionType::New();

  // Set parameters ...
  reader->SetFileName(argv[1]);
  writer->SetFileName(argv[2]);

  reader->GenerateOutputInformation();
  std::cout << reader->GetOutput() << std::endl;

  orthoRectifFilter->SetInput(reader->GetOutput());

  ImageType::IndexType start;
  start[0] = 0;
  start[1] = 0;
  orthoRectifFilter->SetOutputStartIndex(start);

  ImageType::SizeType size;
  size[0] = atoi(argv[5]);      // X size
  size[1] = atoi(argv[6]);            //Y size
  orthoRectifFilter->SetSize(size);

  ImageType::SpacingType spacing;
  spacing[0] = atof(argv[7]);
  spacing[1] = atof(argv[8]);
  orthoRectifFilter->SetOutputSpacing(spacing);

  ImageType::PointType origin;
  origin[0] = strtod(argv[3], NULL);         //Origin easting
  origin[1] = strtod(argv[4], NULL);         //Origin northing
  orthoRectifFilter->SetOutputOrigin(origin);

  utmMapProjection->SetZone(atoi(argv[9]));
  utmMapProjection->SetHemisphere(argv[10][0]);
  orthoRectifFilter->SetMapProjection(utmMapProjection);

  // Deformation Field spacing
  ImageType::SpacingType  gridSpacing;
  gridSpacing[0] = atof(argv[11]);
  gridSpacing[1] = -atof(argv[11]);
  orthoRectifFilter->SetDeformationFieldSpacing(gridSpacing);

  writer->SetInput(orthoRectifFilter->GetOutput());
  writer->SetTilingStreamDivisions(4);
  writer->Update();

  return EXIT_SUCCESS;
}
<commit_msg>COMP: do not use deprecated method<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

// iostream is used for general output
#include <iostream>
#include <stdlib.h>

#include "otbMacro.h"
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbMapProjections.h"

#include "otbOrthoRectificationFilter.h"
#include "otbMapProjections.h"

#include "init/ossimInit.h"

int otbOrthoRectificationFilter(int argc, char* argv[])
{
  ossimInit::instance()->initialize(argc, argv);
  if (argc != 12)
    {
    std::cout << argv[0] <<
    " <input filename> <output filename> <origin easting> <origin northing> <x size> <y size> <x spacing> <y spacing> <UTM zone> <UTM hemisphere>"
              << std::endl;

    return EXIT_FAILURE;
    }

  typedef otb::Image<double, 2>                                                     ImageType;
  typedef otb::ImageFileReader<ImageType>                                           ReaderType;
  typedef otb::StreamingImageFileWriter<ImageType>                                  WriterType;
  typedef otb::UtmInverseProjection                                                 UtmMapProjectionType;
  typedef otb::OrthoRectificationFilter<ImageType, ImageType, UtmMapProjectionType> OrthoRectifFilterType;

  //Allocate pointer
  ReaderType::Pointer reader = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();

  OrthoRectifFilterType::Pointer orthoRectifFilter = OrthoRectifFilterType::New();
  UtmMapProjectionType::Pointer  utmMapProjection = UtmMapProjectionType::New();

  // Set parameters ...
  reader->SetFileName(argv[1]);
  writer->SetFileName(argv[2]);

  reader->GenerateOutputInformation();
  std::cout << reader->GetOutput() << std::endl;

  orthoRectifFilter->SetInput(reader->GetOutput());

  ImageType::IndexType start;
  start[0] = 0;
  start[1] = 0;
  orthoRectifFilter->SetOutputStartIndex(start);

  ImageType::SizeType size;
  size[0] = atoi(argv[5]);      // X size
  size[1] = atoi(argv[6]);            //Y size
  orthoRectifFilter->SetOutputSize(size);

  ImageType::SpacingType spacing;
  spacing[0] = atof(argv[7]);
  spacing[1] = atof(argv[8]);
  orthoRectifFilter->SetOutputSpacing(spacing);

  ImageType::PointType origin;
  origin[0] = strtod(argv[3], NULL);         //Origin easting
  origin[1] = strtod(argv[4], NULL);         //Origin northing
  orthoRectifFilter->SetOutputOrigin(origin);

  utmMapProjection->SetZone(atoi(argv[9]));
  utmMapProjection->SetHemisphere(argv[10][0]);
  orthoRectifFilter->SetMapProjection(utmMapProjection);

  // Deformation Field spacing
  ImageType::SpacingType  gridSpacing;
  gridSpacing[0] = atof(argv[11]);
  gridSpacing[1] = -atof(argv[11]);
  orthoRectifFilter->SetDeformationFieldSpacing(gridSpacing);

  writer->SetInput(orthoRectifFilter->GetOutput());
  writer->SetTilingStreamDivisions(4);
  writer->Update();

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*=============================================================================
  NiftyLink:  A software library to facilitate communication over OpenIGTLink.

  Copyright (c) University College London (UCL). All rights reserved.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.

  See LICENSE.txt in the top level directory for details.
=============================================================================*/
#include "NiftyLinkUtils.h"
#include <NiftyLinkTrackingDataMessageHelpers.h>
#include <NiftyLinkTransformMessageHelpers.h>
#include <NiftyLinkImageMessageHelpers.h>

#include <igtlTrackingDataMessage.h>
#include <igtlTransformMessage.h>
#include <igtlStringMessage.h>
#include <igtlStatusMessage.h>
#include <igtlImageMessage.h>

#include <QsLog.h>
#include <QsLogDest.h>

#include <QUrl>
#include <QHostInfo>
#include <QHostAddress>
#include <QStringList>
#include <QNetworkConfigurationManager>
#include <QNetworkInterface>
#include <QNetworkSession>
#include <QDesktopServices>
#include <QDir>

#include <cmath>
#include <cassert>

namespace niftk
{

#if defined(_WIN32) && !defined(__CYGWIN__)
//-----------------------------------------------------------------------------
void InitializeWinTimers()
{
  // Use LoadLibrary used to load ntdll
  HINSTANCE hInstLibrary = LoadLibrary("ntdll.dll");

  if (hInstLibrary)
  {
    // Typedef functions to hold what is in the DLL
    FunctionPtr_SETRES _NtSetTimerResolution;
    FunctionPtr_GETRES _NtQueryTimerResolution;

    // the DLL is loaded and ready to go.
    _NtSetTimerResolution = (FunctionPtr_SETRES)GetProcAddress(hInstLibrary, "NtSetTimerResolution");
    _NtQueryTimerResolution = (FunctionPtr_GETRES)GetProcAddress(hInstLibrary, "NtQueryTimerResolution");

    if (_NtSetTimerResolution)
    {
      uint desiredResolution = 5000;
      bool setResolution = true;
      ULONG minResolution = 0;
      ULONG maxResolution = 0;
      ULONG currentResolution = 0;

      _NtQueryTimerResolution(&minResolution, &maxResolution, &currentResolution);
      QLOG_INFO() <<"Current Clock Resolution - Before: " << currentResolution;

      _NtSetTimerResolution(maxResolution, setResolution, &currentResolution);

      _NtQueryTimerResolution(&minResolution, &maxResolution, &currentResolution);
      QLOG_INFO() <<"Current Clock Resolution - After: " << currentResolution;
    }
  }
  else
  {
    QLOG_ERROR() << "Failed to load ntdll.dll to set timer resolution.";
  }
}
#endif

//-----------------------------------------------------------------------------
bool ValidateIp(const QString &inputIP)
{
  QStringList nums = inputIP.split(".");

  if (nums.count() != 4)
  {
    return false;
  }

  for (int i = 0; i < 4; i++)
  {
    bool ok = false;
    int frag = nums.at(i).toInt(&ok, 10);

    if (!ok)
    {
      return false;
    }
    else if (frag < 0 || frag > 255)
    {
      return false;
    }
  }

  return true;
}

//-----------------------------------------------------------------------------
QString ResolveHostName(const QString &input)
{
  if (ValidateIp(input))
  {
    return input;
  }

  QHostInfo info = QHostInfo::fromName(input);
  QList<QHostAddress> addresses = info.addresses();

  for (int i = 0; i < addresses.count(); i++)
  {
    if ( ValidateIp(addresses.at(i).toString()) == true )
    {
      return addresses.at(i).toString();
    }
  }

  return QString("UNKNOWN");

}

//-----------------------------------------------------------------------------
QString GetLocalHostAddress(void)
{
  QNetworkConfigurationManager mgr;
  QNetworkConfiguration nconfig = mgr.defaultConfiguration();
  QNetworkSession session ( nconfig );
  QNetworkInterface ninter = session.interface();

  // this provides more than one ip addresses
  QList<QNetworkAddressEntry> laddr = ninter.addressEntries();
  for ( QList<QNetworkAddressEntry> ::const_iterator it = laddr.begin(); it != laddr.end(); ++it )
  {
    QString ipstr = it->ip().toString();
    if (ValidateIp(ipstr))
    {
      // Need to return the one which is valid and not 'localhost'
      if (ipstr != QString("127.0.0.1"))
      {
        return ipstr;
      }
    }
  }

  return QString("UNKNOWN");
}

//-----------------------------------------------------------------------------
void CreateRandomTransformMatrix(igtl::Matrix4x4& matrix)
{
  float position[3];
  float orientation[4];

  // random position
  static float phi = 0.2;
  position[0] = 50.0 * cos(phi);
  position[1] = 50.0 * sin(phi);
  position[2] = 50.0 * cos(phi);
  phi = phi + 0.2;

  // random orientation
  static float theta = 0.0;
  orientation[0] = 0.0;
  orientation[1] = 0.6666666666 * cos(theta);
  orientation[2] = 0.577350269189626;
  orientation[3] = 0.6666666666 * sin(theta);
  theta = theta + 0.1;

  //igtl::Matrix4x4 matrix;
  igtl::QuaternionToMatrix(orientation, matrix);

  matrix[0][3] = position[0];
  matrix[1][3] = position[1];
  matrix[2][3] = position[2];

  //igtl::PrintMatrix(matrix);
}

//-----------------------------------------------------------------------------
igtlUint64 GetDifferenceInNanoSeconds(igtl::TimeStamp* timeA, igtl::TimeStamp* timeB)
{
  assert(timeA);
  assert(timeB);

  igtlUint64 a = timeA->GetTimeStampInNanoseconds();
  igtlUint64 b = timeB->GetTimeStampInNanoseconds();
  igtlUint64 d;

  if (a > b)
  {
    d = a - b;
  }
  else if (b > a)
  {
    d = b - a;
  }
  else
  {
    d = 0;
  }

  return d;
}

//-----------------------------------------------------------------------------
double CalculateMean(const QList<igtlUint64>& list)
{
  double mean = 0;
  foreach(igtlUint64 item, list)
  {
    mean += static_cast<double>(item);
  }
  if (list.size() > 1)
  {
    mean /= static_cast<double>(list.size());
  }
  return mean;
}

//-----------------------------------------------------------------------------
double CalculateStdDev(const QList<igtlUint64>& list)
{
  double stdDev = 0;
  double mean = CalculateMean(list);
  foreach(igtlUint64 item, list)
  {
    stdDev += ((static_cast<double>(item)-mean)*(static_cast<double>(item)-mean));
  }
  if (list.size() > 1)
  {
    stdDev /= static_cast<double>(list.size() - 1);
  }
  stdDev = sqrt(stdDev);
  return stdDev;
}

//-----------------------------------------------------------------------------
igtlUint64 CalculateMax(const QList<igtlUint64>& list)
{
  igtlUint64 max = 0;
  foreach(igtlUint64 item, list)
  {
    if (item > max)
    {
      max = item;
    }
  }
  return max;
}

//-----------------------------------------------------------------------------
bool IsCloseEnoughTo(double valueA, double valueB, double tolerance)
{
  return fabs(valueA - valueB) < tolerance;
}

//-----------------------------------------------------------------------------
bool IsCloseEnoughToZero(double valueA, double tolerance)
{
  return IsCloseEnoughTo(valueA, 0, tolerance);
}

//-----------------------------------------------------------------------------
void CopyMatrix(double *input, igtl::Matrix4x4& output)
{
  assert(input);

  for (unsigned int r = 0; r < 4; r++)
  {
    for (unsigned int c = 0; c < 4; c++)
    {
      output[r][c] = input[r*4+c];
    }
  }
}

//-----------------------------------------------------------------------------
QString GetTempDirectoryPath()
{
  return QDesktopServices::storageLocation(QDesktopServices::TempLocation);
}

//-----------------------------------------------------------------------------
QString GetWritableDirectoryPath(const QString& fileName)
{
  QString result;
  QDir directory;

  QString path = QDesktopServices::storageLocation(QDesktopServices::HomeLocation);
  directory.setPath(path);

  if (!directory.exists())
  {
    path = QDesktopServices::storageLocation(QDesktopServices::CacheLocation);
    directory.setPath(path);
  }
  if (!directory.exists())
  {
    path = QDesktopServices::storageLocation(QDesktopServices::TempLocation);
    directory.setPath(path);
  }
  if (!directory.exists())
  {
    path = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
    directory.setPath(path);
  }
  if (!directory.exists())
  {
    path = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
    directory.setPath(path);
  }
  if (!directory.exists())
  {
    path = QDir::currentPath();
    directory.setPath(path);
  }
  if (!directory.exists())
  {
    path = "";
  }

  result = path;

  if (fileName.length() > 0)
  {
    if (result.length() > 0)
    {
      result = result + QDir::separator() + fileName;
    }
    else
    {
      result = fileName;
    }
  }
  return result;
}

//-----------------------------------------------------------------------------
QString AppendPathSeparator(const QString& path)
{
  return path.right(1) == "/" ? path : path + "/";
}

//-----------------------------------------------------------------------------
void ExtractTextBasedMessage(const NiftyLinkMessageContainer::Pointer& message, QString& output)
{
  if (message.data() != NULL)
  {
    igtl::MessageBase::Pointer msg = dynamic_cast<igtl::MessageBase*>(message->GetMessage().GetPointer());
    if (msg.IsNotNull())
    {
      if (QString(msg->GetDeviceType()) == QString("STRING"))
      {
        igtl::StringMessage::Pointer m = dynamic_cast<igtl::StringMessage*>(msg.GetPointer());
        output = QString(m->GetString());
      }
      if (QString(msg->GetDeviceType()) == QString("STATUS"))
      {
        igtl::StatusMessage::Pointer m = dynamic_cast<igtl::StatusMessage*>(msg.GetPointer());
        output = QString(m->GetStatusString());
      }
      if (QString(msg->GetDeviceType()) == QString("TRANSFORM"))
      {
        igtl::TransformMessage::Pointer m = dynamic_cast<igtl::TransformMessage*>(msg.GetPointer());
        output = GetMatrixAsString(m);
      }
      if (QString(msg->GetDeviceType()) == QString("TDATA"))
      {
        igtl::TrackingDataMessage::Pointer m = dynamic_cast<igtl::TrackingDataMessage*>(msg.GetPointer());
        output = GetMatrixAsString(m,0);
      }
    }
  }
}

//-----------------------------------------------------------------------------
void ExtractImageMessage(const NiftyLinkMessageContainer::Pointer& message, QImage& image)
{
  if (message.data() != NULL)
  {
    igtl::ImageMessage::Pointer msg = dynamic_cast<igtl::ImageMessage*>(message->GetMessage().GetPointer());
    if (msg.IsNotNull())
    {
      GetQImage(msg, image);
    }
  }
}

//-----------------------------------------------------------------------------
bool IsKeepAlive(const igtl::MessageBase::Pointer& message)
{
  bool isKeepAlive = false;
  igtl::StatusMessage::Pointer msg = dynamic_cast<igtl::StatusMessage*>(message.GetPointer());
  if (msg.IsNotNull())
  {
    if (msg->GetCode() == igtl::StatusMessage::STATUS_OK)
    {
      isKeepAlive = true;
    }
  }
  return isKeepAlive;
}

//-----------------------------------------------------------------------------
bool IsStatsRequest(const igtl::MessageBase::Pointer& message)
{
  bool isStats = false;
  igtl::StringMessage::Pointer msg = dynamic_cast<igtl::StringMessage*>(message.GetPointer());
  if (msg.IsNotNull())
  {
    if (msg->GetString() == std::string("STATS"))
    {
      isStats = true;
    }
  }
  return isStats;
}

//-----------------------------------------------------------------------------
bool IsCloseEnoughTo(const igtl::Matrix4x4& a, const igtl::Matrix4x4& b, double tolerance)
{
  for (unsigned int r = 0; r < 4; r++)
  {
    for (unsigned int c = 0; c < 4; c++)
    {
      if (!IsCloseEnoughTo(a[r][c], b[r][c], tolerance))
      {
        return false;
      }
    }
  }
  return true;
}

} // end namespace niftk

#if defined(NIFTYLINK_STATIC)
struct InitialiseNiftyLinkResources{
  InitialiseNiftyLinkResources()
  {
    Q_INIT_RESOURCE(NiftyLink);
  }
};

static InitialiseNiftyLinkResources initialiseNiftyLinkResources;
#endif
<commit_msg>Issue #4024: Update QDesktopServices to QStandardPaths<commit_after>/*=============================================================================
  NiftyLink:  A software library to facilitate communication over OpenIGTLink.

  Copyright (c) University College London (UCL). All rights reserved.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.

  See LICENSE.txt in the top level directory for details.
=============================================================================*/
#include "NiftyLinkUtils.h"
#include <NiftyLinkTrackingDataMessageHelpers.h>
#include <NiftyLinkTransformMessageHelpers.h>
#include <NiftyLinkImageMessageHelpers.h>

#include <igtlTrackingDataMessage.h>
#include <igtlTransformMessage.h>
#include <igtlStringMessage.h>
#include <igtlStatusMessage.h>
#include <igtlImageMessage.h>

#include <QsLog.h>
#include <QsLogDest.h>

#include <QUrl>
#include <QHostInfo>
#include <QHostAddress>
#include <QStringList>
#include <QNetworkConfigurationManager>
#include <QNetworkInterface>
#include <QNetworkSession>
#if (QT_VERSION < QT_VERSION_CHECK(5,0,0))
#include <QDesktopServices>
#else
#include <QStandardPaths>
#endif
#include <QDir>

#include <cmath>
#include <cassert>

namespace niftk
{

#if defined(_WIN32) && !defined(__CYGWIN__)
//-----------------------------------------------------------------------------
void InitializeWinTimers()
{
  // Use LoadLibrary used to load ntdll
  HINSTANCE hInstLibrary = LoadLibrary("ntdll.dll");

  if (hInstLibrary)
  {
    // Typedef functions to hold what is in the DLL
    FunctionPtr_SETRES _NtSetTimerResolution;
    FunctionPtr_GETRES _NtQueryTimerResolution;

    // the DLL is loaded and ready to go.
    _NtSetTimerResolution = (FunctionPtr_SETRES)GetProcAddress(hInstLibrary, "NtSetTimerResolution");
    _NtQueryTimerResolution = (FunctionPtr_GETRES)GetProcAddress(hInstLibrary, "NtQueryTimerResolution");

    if (_NtSetTimerResolution)
    {
      uint desiredResolution = 5000;
      bool setResolution = true;
      ULONG minResolution = 0;
      ULONG maxResolution = 0;
      ULONG currentResolution = 0;

      _NtQueryTimerResolution(&minResolution, &maxResolution, &currentResolution);
      QLOG_INFO() <<"Current Clock Resolution - Before: " << currentResolution;

      _NtSetTimerResolution(maxResolution, setResolution, &currentResolution);

      _NtQueryTimerResolution(&minResolution, &maxResolution, &currentResolution);
      QLOG_INFO() <<"Current Clock Resolution - After: " << currentResolution;
    }
  }
  else
  {
    QLOG_ERROR() << "Failed to load ntdll.dll to set timer resolution.";
  }
}
#endif

//-----------------------------------------------------------------------------
bool ValidateIp(const QString &inputIP)
{
  QStringList nums = inputIP.split(".");

  if (nums.count() != 4)
  {
    return false;
  }

  for (int i = 0; i < 4; i++)
  {
    bool ok = false;
    int frag = nums.at(i).toInt(&ok, 10);

    if (!ok)
    {
      return false;
    }
    else if (frag < 0 || frag > 255)
    {
      return false;
    }
  }

  return true;
}

//-----------------------------------------------------------------------------
QString ResolveHostName(const QString &input)
{
  if (ValidateIp(input))
  {
    return input;
  }

  QHostInfo info = QHostInfo::fromName(input);
  QList<QHostAddress> addresses = info.addresses();

  for (int i = 0; i < addresses.count(); i++)
  {
    if ( ValidateIp(addresses.at(i).toString()) == true )
    {
      return addresses.at(i).toString();
    }
  }

  return QString("UNKNOWN");

}

//-----------------------------------------------------------------------------
QString GetLocalHostAddress(void)
{
  QNetworkConfigurationManager mgr;
  QNetworkConfiguration nconfig = mgr.defaultConfiguration();
  QNetworkSession session ( nconfig );
  QNetworkInterface ninter = session.interface();

  // this provides more than one ip addresses
  QList<QNetworkAddressEntry> laddr = ninter.addressEntries();
  for ( QList<QNetworkAddressEntry> ::const_iterator it = laddr.begin(); it != laddr.end(); ++it )
  {
    QString ipstr = it->ip().toString();
    if (ValidateIp(ipstr))
    {
      // Need to return the one which is valid and not 'localhost'
      if (ipstr != QString("127.0.0.1"))
      {
        return ipstr;
      }
    }
  }

  return QString("UNKNOWN");
}

//-----------------------------------------------------------------------------
void CreateRandomTransformMatrix(igtl::Matrix4x4& matrix)
{
  float position[3];
  float orientation[4];

  // random position
  static float phi = 0.2;
  position[0] = 50.0 * cos(phi);
  position[1] = 50.0 * sin(phi);
  position[2] = 50.0 * cos(phi);
  phi = phi + 0.2;

  // random orientation
  static float theta = 0.0;
  orientation[0] = 0.0;
  orientation[1] = 0.6666666666 * cos(theta);
  orientation[2] = 0.577350269189626;
  orientation[3] = 0.6666666666 * sin(theta);
  theta = theta + 0.1;

  //igtl::Matrix4x4 matrix;
  igtl::QuaternionToMatrix(orientation, matrix);

  matrix[0][3] = position[0];
  matrix[1][3] = position[1];
  matrix[2][3] = position[2];

  //igtl::PrintMatrix(matrix);
}

//-----------------------------------------------------------------------------
igtlUint64 GetDifferenceInNanoSeconds(igtl::TimeStamp* timeA, igtl::TimeStamp* timeB)
{
  assert(timeA);
  assert(timeB);

  igtlUint64 a = timeA->GetTimeStampInNanoseconds();
  igtlUint64 b = timeB->GetTimeStampInNanoseconds();
  igtlUint64 d;

  if (a > b)
  {
    d = a - b;
  }
  else if (b > a)
  {
    d = b - a;
  }
  else
  {
    d = 0;
  }

  return d;
}

//-----------------------------------------------------------------------------
double CalculateMean(const QList<igtlUint64>& list)
{
  double mean = 0;
  foreach(igtlUint64 item, list)
  {
    mean += static_cast<double>(item);
  }
  if (list.size() > 1)
  {
    mean /= static_cast<double>(list.size());
  }
  return mean;
}

//-----------------------------------------------------------------------------
double CalculateStdDev(const QList<igtlUint64>& list)
{
  double stdDev = 0;
  double mean = CalculateMean(list);
  foreach(igtlUint64 item, list)
  {
    stdDev += ((static_cast<double>(item)-mean)*(static_cast<double>(item)-mean));
  }
  if (list.size() > 1)
  {
    stdDev /= static_cast<double>(list.size() - 1);
  }
  stdDev = sqrt(stdDev);
  return stdDev;
}

//-----------------------------------------------------------------------------
igtlUint64 CalculateMax(const QList<igtlUint64>& list)
{
  igtlUint64 max = 0;
  foreach(igtlUint64 item, list)
  {
    if (item > max)
    {
      max = item;
    }
  }
  return max;
}

//-----------------------------------------------------------------------------
bool IsCloseEnoughTo(double valueA, double valueB, double tolerance)
{
  return fabs(valueA - valueB) < tolerance;
}

//-----------------------------------------------------------------------------
bool IsCloseEnoughToZero(double valueA, double tolerance)
{
  return IsCloseEnoughTo(valueA, 0, tolerance);
}

//-----------------------------------------------------------------------------
void CopyMatrix(double *input, igtl::Matrix4x4& output)
{
  assert(input);

  for (unsigned int r = 0; r < 4; r++)
  {
    for (unsigned int c = 0; c < 4; c++)
    {
      output[r][c] = input[r*4+c];
    }
  }
}

//-----------------------------------------------------------------------------
QString GetTempDirectoryPath()
{
#if (QT_VERSION < QT_VERSION_CHECK(5,0,0))
  return QDesktopServices::storageLocation(QDesktopServices::TempLocation);
#else
  QStringList paths = QStandardPaths::standardLocations(QStandardPaths::TempLocation);
  assert(paths.size() == 1);
  return paths[0];
#endif
}

//-----------------------------------------------------------------------------
QString GetWritableDirectoryPath(const QString& fileName)
{
  QString result;
  QDir directory;

  QString path;
  QStringList paths;

#if (QT_VERSION < QT_VERSION_CHECK(5,0,0))
  path = QDesktopServices::storageLocation(QDesktopServices::HomeLocation);
#else
  paths = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
  assert(paths.size() == 1);
  path = paths[0];
#endif

  directory.setPath(path);

  if (!directory.exists())
  {
#if (QT_VERSION < QT_VERSION_CHECK(5,0,0))
    path = QDesktopServices::storageLocation(QDesktopServices::CacheLocation);
#else
    paths = QStandardPaths::standardLocations(QStandardPaths::CacheLocation);
    assert(paths.size() == 1);
    path = paths[0];
#endif

    directory.setPath(path);
  }
  if (!directory.exists())
  {
#if (QT_VERSION < QT_VERSION_CHECK(5,0,0))
    path = QDesktopServices::storageLocation(QDesktopServices::TempLocation);
#else
    paths = QStandardPaths::standardLocations(QStandardPaths::TempLocation);
    assert(paths.size() == 1);
    path = paths[0];
#endif

    directory.setPath(path);
  }
  if (!directory.exists())
  {
#if (QT_VERSION < QT_VERSION_CHECK(5,0,0))
    path = QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
#else
    paths = QStandardPaths::standardLocations(QStandardPaths::DesktopLocation);
    assert(paths.size() == 1);
    path = paths[0];
#endif

    directory.setPath(path);
  }
  if (!directory.exists())
  {
#if (QT_VERSION < QT_VERSION_CHECK(5,0,0))
    path = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
#else
    paths = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation);
    assert(paths.size() == 1);
    path = paths[0];
#endif

    directory.setPath(path);
  }
  if (!directory.exists())
  {
    path = QDir::currentPath();
    directory.setPath(path);
  }
  if (!directory.exists())
  {
    path = "";
  }

  result = path;

  if (fileName.length() > 0)
  {
    if (result.length() > 0)
    {
      result = result + QDir::separator() + fileName;
    }
    else
    {
      result = fileName;
    }
  }
  return result;
}

//-----------------------------------------------------------------------------
QString AppendPathSeparator(const QString& path)
{
  return path.right(1) == "/" ? path : path + "/";
}

//-----------------------------------------------------------------------------
void ExtractTextBasedMessage(const NiftyLinkMessageContainer::Pointer& message, QString& output)
{
  if (message.data() != NULL)
  {
    igtl::MessageBase::Pointer msg = dynamic_cast<igtl::MessageBase*>(message->GetMessage().GetPointer());
    if (msg.IsNotNull())
    {
      if (QString(msg->GetDeviceType()) == QString("STRING"))
      {
        igtl::StringMessage::Pointer m = dynamic_cast<igtl::StringMessage*>(msg.GetPointer());
        output = QString(m->GetString());
      }
      if (QString(msg->GetDeviceType()) == QString("STATUS"))
      {
        igtl::StatusMessage::Pointer m = dynamic_cast<igtl::StatusMessage*>(msg.GetPointer());
        output = QString(m->GetStatusString());
      }
      if (QString(msg->GetDeviceType()) == QString("TRANSFORM"))
      {
        igtl::TransformMessage::Pointer m = dynamic_cast<igtl::TransformMessage*>(msg.GetPointer());
        output = GetMatrixAsString(m);
      }
      if (QString(msg->GetDeviceType()) == QString("TDATA"))
      {
        igtl::TrackingDataMessage::Pointer m = dynamic_cast<igtl::TrackingDataMessage*>(msg.GetPointer());
        output = GetMatrixAsString(m,0);
      }
    }
  }
}

//-----------------------------------------------------------------------------
void ExtractImageMessage(const NiftyLinkMessageContainer::Pointer& message, QImage& image)
{
  if (message.data() != NULL)
  {
    igtl::ImageMessage::Pointer msg = dynamic_cast<igtl::ImageMessage*>(message->GetMessage().GetPointer());
    if (msg.IsNotNull())
    {
      GetQImage(msg, image);
    }
  }
}

//-----------------------------------------------------------------------------
bool IsKeepAlive(const igtl::MessageBase::Pointer& message)
{
  bool isKeepAlive = false;
  igtl::StatusMessage::Pointer msg = dynamic_cast<igtl::StatusMessage*>(message.GetPointer());
  if (msg.IsNotNull())
  {
    if (msg->GetCode() == igtl::StatusMessage::STATUS_OK)
    {
      isKeepAlive = true;
    }
  }
  return isKeepAlive;
}

//-----------------------------------------------------------------------------
bool IsStatsRequest(const igtl::MessageBase::Pointer& message)
{
  bool isStats = false;
  igtl::StringMessage::Pointer msg = dynamic_cast<igtl::StringMessage*>(message.GetPointer());
  if (msg.IsNotNull())
  {
    if (msg->GetString() == std::string("STATS"))
    {
      isStats = true;
    }
  }
  return isStats;
}

//-----------------------------------------------------------------------------
bool IsCloseEnoughTo(const igtl::Matrix4x4& a, const igtl::Matrix4x4& b, double tolerance)
{
  for (unsigned int r = 0; r < 4; r++)
  {
    for (unsigned int c = 0; c < 4; c++)
    {
      if (!IsCloseEnoughTo(a[r][c], b[r][c], tolerance))
      {
        return false;
      }
    }
  }
  return true;
}

} // end namespace niftk

#if defined(NIFTYLINK_STATIC)
struct InitialiseNiftyLinkResources{
  InitialiseNiftyLinkResources()
  {
    Q_INIT_RESOURCE(NiftyLink);
  }
};

static InitialiseNiftyLinkResources initialiseNiftyLinkResources;
#endif
<|endoftext|>


<commit_before>/*=========================================================================

Program:   ORFEO Toolbox
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include <iostream>

#include "otbGluPolygonDrawingHelper.h"
#include "otbMacro.h"

// This is defined in windows only, and it is needed for FunctionPointerType
// to be properly defined.

// There are function prototype conflits under cygwin between standard w32 API
// and standard C ones
#ifndef CALLBACK
	#if defined(__CYGWIN__)
		#define CALLBACK __stdcall
	#else
		#define CALLBACK
#endif

extern "C"
{
 typedef void (CALLBACK * FunctionPointerType)();

 void CombineCallback(GLdouble coords[3],GLdouble * data[4], GLfloat weights[4],GLdouble **dataOut)
{
  GLdouble * vertex = new GLdouble[3];
  vertex[0] = coords[0];
  vertex[1] = coords[1];
  vertex[2] = coords[2];
  *dataOut = vertex;
}

 void ErrorCallback(GLenum errorCode)
{
  const GLubyte * estring = gluErrorString(errorCode);
	std::cout<<"Glu Tesselation error: "<<estring<<std::endl;
}
} // end extern C

namespace otb
{

GluPolygonDrawingHelper::GluPolygonDrawingHelper()
{
  // Instantiation of the tesselator object
  m_PointVector.clear();
  m_GluTesselator = gluNewTess();
  // Color
  m_Color[0]=0;
  m_Color[1]=0;
  m_Color[2]=0;
  m_Color[3]=0;

  // Setting up the tesselator callbacks
  gluTessCallback(m_GluTesselator,GLU_TESS_BEGIN,(FunctionPointerType)glBegin);
  gluTessCallback(m_GluTesselator,GLU_TESS_END,(FunctionPointerType)glEnd);
  gluTessCallback(m_GluTesselator,GLU_TESS_ERROR,(FunctionPointerType)ErrorCallback);
  gluTessCallback(m_GluTesselator,GLU_TESS_VERTEX,(FunctionPointerType)glVertex3dv);
  gluTessCallback(m_GluTesselator,GLU_TESS_COMBINE,(FunctionPointerType)CombineCallback);
}

GluPolygonDrawingHelper::~GluPolygonDrawingHelper()
{
    gluDeleteTess(m_GluTesselator);
}

void  GluPolygonDrawingHelper::SetWindingRule(GLdouble windingRule)
{
   gluTessProperty(m_GluTesselator,GLU_TESS_WINDING_RULE,windingRule);
}

void GluPolygonDrawingHelper::SetBoundaryOnly(GLdouble boundaryOnly)
{
   gluTessProperty(m_GluTesselator,GLU_TESS_BOUNDARY_ONLY,boundaryOnly);
}

void GluPolygonDrawingHelper::Color3d(double r, double g, double b)
{
  m_Color[0]=r;
  m_Color[1]=g;
  m_Color[2]=b;
  m_Color[3]=1.;
}

void GluPolygonDrawingHelper::Color4d(double r, double g, double b, double alpha)
{
  m_Color[0]=r;
  m_Color[1]=g;
  m_Color[2]=b;
  m_Color[3]=alpha;
}

void GluPolygonDrawingHelper::Vertex2d(double x, double y)
{
  PointType p;
  p[0]=x;
  p[1]=y;
  p[2]=0;
  m_PointVector.push_back(p);

}

void GluPolygonDrawingHelper::Vertex3d(double x, double y, double z)
{
   PointType p;
   p[0]=x;
   p[1]=y;
   p[2]=z;
   m_PointVector.push_back(p);
}

void GluPolygonDrawingHelper::RenderPolygon()
{
  // Set up a malloced space for the polygon data.
  GLdouble ** data = new GLdouble*[m_PointVector.size()];
  unsigned int i = 0;
  PointVectorType::iterator it;
  for(it = m_PointVector.begin();it!=m_PointVector.end();++i,++it)
    {
      data[i]= new GLdouble[3];
      data[i][0]=(*it)[0];
      data[i][1]=(*it)[1];
      data[i][2]=(*it)[2];
    }
  // Set the color
  glColor4d(m_Color[0],m_Color[1],m_Color[2],m_Color[3]);
  gluTessBeginPolygon(m_GluTesselator, NULL);
  gluTessBeginContour(m_GluTesselator);

  for(i=0;i<m_PointVector.size();++i)
    {
      gluTessVertex(m_GluTesselator,data[i],data[i]);
    }
  gluTessEndContour(m_GluTesselator);
  gluTessEndPolygon(m_GluTesselator);

  for(i=0;i<m_PointVector.size();++i)
    {
      delete []data[i];
    }
  delete []data;

  m_PointVector.clear();
}
} // end namespace otb
<commit_msg>*correction manque #endif<commit_after>/*=========================================================================

Program:   ORFEO Toolbox
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include <iostream>

#include "otbGluPolygonDrawingHelper.h"
#include "otbMacro.h"

// This is defined in windows only, and it is needed for FunctionPointerType
// to be properly defined.

// There are function prototype conflits under cygwin between standard w32 API
// and standard C ones
#ifndef CALLBACK
	#if defined(__CYGWIN__)
		#define CALLBACK __stdcall
        #else
		#define CALLBACK
        #endif
#endif

extern "C"
{
 typedef void (CALLBACK * FunctionPointerType)();

 void CombineCallback(GLdouble coords[3],GLdouble * data[4], GLfloat weights[4],GLdouble **dataOut)
{
  GLdouble * vertex = new GLdouble[3];
  vertex[0] = coords[0];
  vertex[1] = coords[1];
  vertex[2] = coords[2];
  *dataOut = vertex;
}

 void ErrorCallback(GLenum errorCode)
{
  const GLubyte * estring = gluErrorString(errorCode);
	std::cout<<"Glu Tesselation error: "<<estring<<std::endl;
}
} // end extern C

namespace otb
{

GluPolygonDrawingHelper::GluPolygonDrawingHelper()
{
  // Instantiation of the tesselator object
  m_PointVector.clear();
  m_GluTesselator = gluNewTess();
  // Color
  m_Color[0]=0;
  m_Color[1]=0;
  m_Color[2]=0;
  m_Color[3]=0;

  // Setting up the tesselator callbacks
  gluTessCallback(m_GluTesselator,GLU_TESS_BEGIN,(FunctionPointerType)glBegin);
  gluTessCallback(m_GluTesselator,GLU_TESS_END,(FunctionPointerType)glEnd);
  gluTessCallback(m_GluTesselator,GLU_TESS_ERROR,(FunctionPointerType)ErrorCallback);
  gluTessCallback(m_GluTesselator,GLU_TESS_VERTEX,(FunctionPointerType)glVertex3dv);
  gluTessCallback(m_GluTesselator,GLU_TESS_COMBINE,(FunctionPointerType)CombineCallback);
}

GluPolygonDrawingHelper::~GluPolygonDrawingHelper()
{
    gluDeleteTess(m_GluTesselator);
}

void  GluPolygonDrawingHelper::SetWindingRule(GLdouble windingRule)
{
   gluTessProperty(m_GluTesselator,GLU_TESS_WINDING_RULE,windingRule);
}

void GluPolygonDrawingHelper::SetBoundaryOnly(GLdouble boundaryOnly)
{
   gluTessProperty(m_GluTesselator,GLU_TESS_BOUNDARY_ONLY,boundaryOnly);
}

void GluPolygonDrawingHelper::Color3d(double r, double g, double b)
{
  m_Color[0]=r;
  m_Color[1]=g;
  m_Color[2]=b;
  m_Color[3]=1.;
}

void GluPolygonDrawingHelper::Color4d(double r, double g, double b, double alpha)
{
  m_Color[0]=r;
  m_Color[1]=g;
  m_Color[2]=b;
  m_Color[3]=alpha;
}

void GluPolygonDrawingHelper::Vertex2d(double x, double y)
{
  PointType p;
  p[0]=x;
  p[1]=y;
  p[2]=0;
  m_PointVector.push_back(p);

}

void GluPolygonDrawingHelper::Vertex3d(double x, double y, double z)
{
   PointType p;
   p[0]=x;
   p[1]=y;
   p[2]=z;
   m_PointVector.push_back(p);
}

void GluPolygonDrawingHelper::RenderPolygon()
{
  // Set up a malloced space for the polygon data.
  GLdouble ** data = new GLdouble*[m_PointVector.size()];
  unsigned int i = 0;
  PointVectorType::iterator it;
  for(it = m_PointVector.begin();it!=m_PointVector.end();++i,++it)
    {
      data[i]= new GLdouble[3];
      data[i][0]=(*it)[0];
      data[i][1]=(*it)[1];
      data[i][2]=(*it)[2];
    }
  // Set the color
  glColor4d(m_Color[0],m_Color[1],m_Color[2],m_Color[3]);
  gluTessBeginPolygon(m_GluTesselator, NULL);
  gluTessBeginContour(m_GluTesselator);

  for(i=0;i<m_PointVector.size();++i)
    {
      gluTessVertex(m_GluTesselator,data[i],data[i]);
    }
  gluTessEndContour(m_GluTesselator);
  gluTessEndPolygon(m_GluTesselator);

  for(i=0;i<m_PointVector.size();++i)
    {
      delete []data[i];
    }
  delete []data;

  m_PointVector.clear();
}
} // end namespace otb
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "vbahelper/vbadocumentbase.hxx"
#include "vbahelper/helperdecl.hxx"

#include <com/sun/star/util/XModifiable.hpp>
#include <com/sun/star/util/XProtectable.hpp>
#include <com/sun/star/util/XCloseable.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/document/XEmbeddedScripts.hpp> //Michael E. Bohn
#include <com/sun/star/beans/XPropertySet.hpp>

#include <comphelper/unwrapargs.hxx>
#include <tools/urlobj.hxx>
#include <osl/file.hxx>

using namespace ::com::sun::star;
using namespace ::ooo::vba;

VbaDocumentBase::VbaDocumentBase( const uno::Reference< ov::XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext >& xContext) :VbaDocumentBase_BASE( xParent, xContext ), mxModel(NULL)
{
}

VbaDocumentBase::VbaDocumentBase( const uno::Reference< ov::XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext >& xContext, uno::Reference< frame::XModel > xModel ) : VbaDocumentBase_BASE( xParent, xContext ),  mxModel( xModel )
{
}

VbaDocumentBase::VbaDocumentBase( uno::Sequence< uno::Any> const & args,
    uno::Reference< uno::XComponentContext> const & xContext ) : VbaDocumentBase_BASE( getXSomethingFromArgs< XHelperInterface >( args, 0 ), xContext ),  mxModel( getXSomethingFromArgs< frame::XModel >( args, 1 ) )
{
}

::rtl::OUString
VbaDocumentBase::getName() throw (uno::RuntimeException)
{
    rtl::OUString sName = getModel()->getURL();
    if ( sName.getLength() )
    {

        INetURLObject aURL( getModel()->getURL() );
        ::osl::File::getSystemPathFromFileURL( aURL.GetLastName(), sName );
    }
    else
    {
        const static rtl::OUString sTitle( RTL_CONSTASCII_USTRINGPARAM("Title" ) );
        // process "UntitledX - $(PRODUCTNAME)"
        uno::Reference< frame::XFrame > xFrame( getModel()->getCurrentController()->getFrame(), uno::UNO_QUERY_THROW );
        uno::Reference< beans::XPropertySet > xProps( xFrame, uno::UNO_QUERY_THROW );
        xProps->getPropertyValue(sTitle ) >>= sName;
        sal_Int32 pos = 0;
        sName = sName.getToken(0,' ',pos);
    }
    return sName;
}
::rtl::OUString
VbaDocumentBase::getPath() throw (uno::RuntimeException)
{
       INetURLObject aURL( getModel()->getURL() );
    rtl::OUString sURL( aURL.GetMainURL( INetURLObject::DECODE_TO_IURI ) );
    sURL = sURL.copy( 0, sURL.getLength() - aURL.GetLastName().getLength() - 1 );
        rtl::OUString sPath;
    ::osl::File::getSystemPathFromFileURL( sURL, sPath );
    return sPath;
}

::rtl::OUString
VbaDocumentBase::getFullName() throw (uno::RuntimeException)
{
        rtl::OUString sPath;
    ::osl::File::getSystemPathFromFileURL( getModel()->getURL(), sPath );
    return sPath;
}

void
VbaDocumentBase::Close( const uno::Any &rSaveArg, const uno::Any &rFileArg,
                      const uno::Any &rRouteArg ) throw (uno::RuntimeException)
{
    sal_Bool bSaveChanges = sal_False;
    rtl::OUString aFileName;
    sal_Bool bRouteWorkbook = sal_True;

    rSaveArg >>= bSaveChanges;
    sal_Bool bFileName =  ( rFileArg >>= aFileName );
    rRouteArg >>= bRouteWorkbook;
    uno::Reference< frame::XStorable > xStorable( getModel(), uno::UNO_QUERY_THROW );
    uno::Reference< util::XModifiable > xModifiable( getModel(), uno::UNO_QUERY_THROW );

    if( bSaveChanges )
    {
        if( xStorable->isReadonly() )
        {
            throw uno::RuntimeException(::rtl::OUString(
                RTL_CONSTASCII_USTRINGPARAM( "Unable to save to a read only file ") ),
                            uno::Reference< XInterface >() );
        }
        if( bFileName )
            xStorable->storeAsURL( aFileName, uno::Sequence< beans::PropertyValue >(0) );
        else
            xStorable->store();
    }
    else
        xModifiable->setModified( false );

    uno::Reference< util::XCloseable > xCloseable( getModel(), uno::UNO_QUERY );

    if( xCloseable.is() )
        // use close(boolean DeliverOwnership)

        // The boolean parameter DeliverOwnership tells objects vetoing the close process that they may
        // assume ownership if they object the closure by throwing a CloseVetoException
        // Here we give up ownership. To be on the safe side, catch possible veto exception anyway.
        xCloseable->close(sal_True);
    // If close is not supported by this model - try to dispose it.
    // But if the model disagree with a reset request for the modify state
    // we shouldn't do so. Otherwhise some strange things can happen.
    else
    {
        uno::Reference< lang::XComponent > xDisposable ( getModel(), uno::UNO_QUERY );
        if ( xDisposable.is() )
            xDisposable->dispose();
    }
}

void
VbaDocumentBase::Protect( const uno::Any &aPassword ) throw (uno::RuntimeException)
{
    rtl::OUString rPassword;
    uno::Reference< util::XProtectable > xProt( getModel(), uno::UNO_QUERY_THROW );
    SC_VBA_FIXME(("Workbook::Protect stub"));
    if(  aPassword >>= rPassword )
        xProt->protect( rPassword );
    else
        xProt->protect( rtl::OUString() );
}

void
VbaDocumentBase::Unprotect( const uno::Any &aPassword ) throw (uno::RuntimeException)
{
    rtl::OUString rPassword;
    uno::Reference< util::XProtectable > xProt( getModel(), uno::UNO_QUERY_THROW );
    if( !xProt->isProtected() )
        throw uno::RuntimeException(::rtl::OUString(
            RTL_CONSTASCII_USTRINGPARAM( "File is already unprotected" ) ),
            uno::Reference< XInterface >() );
    else
    {
        if( aPassword >>= rPassword )
            xProt->unprotect( rPassword );
        else
            xProt->unprotect( rtl::OUString() );
    }
}

void
VbaDocumentBase::setSaved( sal_Bool bSave ) throw (uno::RuntimeException)
{
    uno::Reference< util::XModifiable > xModifiable( getModel(), uno::UNO_QUERY_THROW );
    xModifiable->setModified( !bSave );
}

sal_Bool
VbaDocumentBase::getSaved() throw (uno::RuntimeException)
{
    uno::Reference< util::XModifiable > xModifiable( getModel(), uno::UNO_QUERY_THROW );
    return !xModifiable->isModified();
}

void
VbaDocumentBase::Save() throw (uno::RuntimeException)
{
    rtl::OUString url = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(".uno:Save"));
    uno::Reference< frame::XModel > xModel = getModel();
    dispatchRequests(xModel,url);
}

void
VbaDocumentBase::Activate() throw (uno::RuntimeException)
{
    uno::Reference< frame::XFrame > xFrame( getModel()->getCurrentController()->getFrame(), uno::UNO_QUERY_THROW );
    xFrame->activate();
}

uno::Any SAL_CALL
VbaDocumentBase::getVBProject() throw (uno::RuntimeException)
{
    try // return empty object on error
    {
        uno::Sequence< uno::Any > aArgs( 2 );
        aArgs[ 0 ] <<= uno::Reference< XHelperInterface >( this );
        aArgs[ 1 ] <<= mxModel;
        uno::Reference< lang::XMultiComponentFactory > xServiceManager( mxContext->getServiceManager(), uno::UNO_SET_THROW );
        uno::Reference< uno::XInterface > xVBProjects = xServiceManager->createInstanceWithArgumentsAndContext(
            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ooo.vba.VBProject" ) ), aArgs, mxContext );
        return uno::Any( xVBProjects );
    }
    catch( uno::Exception& )
    {
    }
    return uno::Any();
}

rtl::OUString&
VbaDocumentBase::getServiceImplName()
{
    static rtl::OUString sImplName( RTL_CONSTASCII_USTRINGPARAM("VbaDocumentBase") );
    return sImplName;
}

uno::Sequence< rtl::OUString >
VbaDocumentBase::getServiceNames()
{
    static uno::Sequence< rtl::OUString > aServiceNames;
    if ( aServiceNames.getLength() == 0 )
    {
        aServiceNames.realloc( 1 );
        aServiceNames[ 0 ] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ooo.vba.VbaDocumentBase" ) );
    }
    return aServiceNames;
}

<commit_msg>mib19: #163374# Fix for vbproject inizialistion<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "vbahelper/vbadocumentbase.hxx"
#include "vbahelper/helperdecl.hxx"

#include <com/sun/star/util/XModifiable.hpp>
#include <com/sun/star/util/XProtectable.hpp>
#include <com/sun/star/util/XCloseable.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/document/XEmbeddedScripts.hpp> //Michael E. Bohn
#include <com/sun/star/beans/XPropertySet.hpp>

#include <comphelper/unwrapargs.hxx>
#include <tools/urlobj.hxx>
#include <osl/file.hxx>

using namespace ::com::sun::star;
using namespace ::ooo::vba;

VbaDocumentBase::VbaDocumentBase( const uno::Reference< ov::XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext >& xContext) :VbaDocumentBase_BASE( xParent, xContext ), mxModel(NULL)
{
}

VbaDocumentBase::VbaDocumentBase( const uno::Reference< ov::XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext >& xContext, uno::Reference< frame::XModel > xModel ) : VbaDocumentBase_BASE( xParent, xContext ),  mxModel( xModel )
{
}

VbaDocumentBase::VbaDocumentBase( uno::Sequence< uno::Any> const & args,
    uno::Reference< uno::XComponentContext> const & xContext ) : VbaDocumentBase_BASE( getXSomethingFromArgs< XHelperInterface >( args, 0 ), xContext ),  mxModel( getXSomethingFromArgs< frame::XModel >( args, 1 ) )
{
}

::rtl::OUString
VbaDocumentBase::getName() throw (uno::RuntimeException)
{
    rtl::OUString sName = getModel()->getURL();
    if ( sName.getLength() )
    {

        INetURLObject aURL( getModel()->getURL() );
        ::osl::File::getSystemPathFromFileURL( aURL.GetLastName(), sName );
    }
    else
    {
        const static rtl::OUString sTitle( RTL_CONSTASCII_USTRINGPARAM("Title" ) );
        // process "UntitledX - $(PRODUCTNAME)"
        uno::Reference< frame::XFrame > xFrame( getModel()->getCurrentController()->getFrame(), uno::UNO_QUERY_THROW );
        uno::Reference< beans::XPropertySet > xProps( xFrame, uno::UNO_QUERY_THROW );
        xProps->getPropertyValue(sTitle ) >>= sName;
        sal_Int32 pos = 0;
        sName = sName.getToken(0,' ',pos);
    }
    return sName;
}
::rtl::OUString
VbaDocumentBase::getPath() throw (uno::RuntimeException)
{
       INetURLObject aURL( getModel()->getURL() );
    rtl::OUString sURL( aURL.GetMainURL( INetURLObject::DECODE_TO_IURI ) );
    sURL = sURL.copy( 0, sURL.getLength() - aURL.GetLastName().getLength() - 1 );
        rtl::OUString sPath;
    ::osl::File::getSystemPathFromFileURL( sURL, sPath );
    return sPath;
}

::rtl::OUString
VbaDocumentBase::getFullName() throw (uno::RuntimeException)
{
        rtl::OUString sPath;
    ::osl::File::getSystemPathFromFileURL( getModel()->getURL(), sPath );
    return sPath;
}

void
VbaDocumentBase::Close( const uno::Any &rSaveArg, const uno::Any &rFileArg,
                      const uno::Any &rRouteArg ) throw (uno::RuntimeException)
{
    sal_Bool bSaveChanges = sal_False;
    rtl::OUString aFileName;
    sal_Bool bRouteWorkbook = sal_True;

    rSaveArg >>= bSaveChanges;
    sal_Bool bFileName =  ( rFileArg >>= aFileName );
    rRouteArg >>= bRouteWorkbook;
    uno::Reference< frame::XStorable > xStorable( getModel(), uno::UNO_QUERY_THROW );
    uno::Reference< util::XModifiable > xModifiable( getModel(), uno::UNO_QUERY_THROW );

    if( bSaveChanges )
    {
        if( xStorable->isReadonly() )
        {
            throw uno::RuntimeException(::rtl::OUString(
                RTL_CONSTASCII_USTRINGPARAM( "Unable to save to a read only file ") ),
                            uno::Reference< XInterface >() );
        }
        if( bFileName )
            xStorable->storeAsURL( aFileName, uno::Sequence< beans::PropertyValue >(0) );
        else
            xStorable->store();
    }
    else
        xModifiable->setModified( false );

    uno::Reference< util::XCloseable > xCloseable( getModel(), uno::UNO_QUERY );

    if( xCloseable.is() )
        // use close(boolean DeliverOwnership)

        // The boolean parameter DeliverOwnership tells objects vetoing the close process that they may
        // assume ownership if they object the closure by throwing a CloseVetoException
        // Here we give up ownership. To be on the safe side, catch possible veto exception anyway.
        xCloseable->close(sal_True);
    // If close is not supported by this model - try to dispose it.
    // But if the model disagree with a reset request for the modify state
    // we shouldn't do so. Otherwhise some strange things can happen.
    else
    {
        uno::Reference< lang::XComponent > xDisposable ( getModel(), uno::UNO_QUERY );
        if ( xDisposable.is() )
            xDisposable->dispose();
    }
}

void
VbaDocumentBase::Protect( const uno::Any &aPassword ) throw (uno::RuntimeException)
{
    rtl::OUString rPassword;
    uno::Reference< util::XProtectable > xProt( getModel(), uno::UNO_QUERY_THROW );
    SC_VBA_FIXME(("Workbook::Protect stub"));
    if(  aPassword >>= rPassword )
        xProt->protect( rPassword );
    else
        xProt->protect( rtl::OUString() );
}

void
VbaDocumentBase::Unprotect( const uno::Any &aPassword ) throw (uno::RuntimeException)
{
    rtl::OUString rPassword;
    uno::Reference< util::XProtectable > xProt( getModel(), uno::UNO_QUERY_THROW );
    if( !xProt->isProtected() )
        throw uno::RuntimeException(::rtl::OUString(
            RTL_CONSTASCII_USTRINGPARAM( "File is already unprotected" ) ),
            uno::Reference< XInterface >() );
    else
    {
        if( aPassword >>= rPassword )
            xProt->unprotect( rPassword );
        else
            xProt->unprotect( rtl::OUString() );
    }
}

void
VbaDocumentBase::setSaved( sal_Bool bSave ) throw (uno::RuntimeException)
{
    uno::Reference< util::XModifiable > xModifiable( getModel(), uno::UNO_QUERY_THROW );
    xModifiable->setModified( !bSave );
}

sal_Bool
VbaDocumentBase::getSaved() throw (uno::RuntimeException)
{
    uno::Reference< util::XModifiable > xModifiable( getModel(), uno::UNO_QUERY_THROW );
    return !xModifiable->isModified();
}

void
VbaDocumentBase::Save() throw (uno::RuntimeException)
{
    rtl::OUString url = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(".uno:Save"));
    uno::Reference< frame::XModel > xModel = getModel();
    dispatchRequests(xModel,url);
}

void
VbaDocumentBase::Activate() throw (uno::RuntimeException)
{
    uno::Reference< frame::XFrame > xFrame( getModel()->getCurrentController()->getFrame(), uno::UNO_QUERY_THROW );
    xFrame->activate();
}

uno::Any SAL_CALL
VbaDocumentBase::getVBProject() throw (uno::RuntimeException)
{
    try // return empty object on error
    {
        uno::Sequence< uno::Any > aArgs( 2 );
        aArgs[ 0 ] <<= uno::Reference< XHelperInterface >( this );
        aArgs[ 1 ] <<= getModel();
        uno::Reference< lang::XMultiComponentFactory > xServiceManager( mxContext->getServiceManager(), uno::UNO_SET_THROW );
        uno::Reference< uno::XInterface > xVBProjects = xServiceManager->createInstanceWithArgumentsAndContext(
            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ooo.vba.VBProject" ) ), aArgs, mxContext );
        return uno::Any( xVBProjects );
    }
    catch( uno::Exception& )
    {
    }
    return uno::Any();
}

rtl::OUString&
VbaDocumentBase::getServiceImplName()
{
    static rtl::OUString sImplName( RTL_CONSTASCII_USTRINGPARAM("VbaDocumentBase") );
    return sImplName;
}

uno::Sequence< rtl::OUString >
VbaDocumentBase::getServiceNames()
{
    static uno::Sequence< rtl::OUString > aServiceNames;
    if ( aServiceNames.getLength() == 0 )
    {
        aServiceNames.realloc( 1 );
        aServiceNames[ 0 ] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ooo.vba.VbaDocumentBase" ) );
    }
    return aServiceNames;
}

<|endoftext|>