コード例 #1
0
PBLOB *PBLOB::baseline_normalise(                //normalize blob
                                 ROW *row,       //row it came from
                                 DENORM *denorm  //inverse mapping
                                ) {
  TBOX blob_box = bounding_box ();
  float x_centre = (blob_box.left () + blob_box.right ()) / 2.0;
  PBLOB *bn_blob;                //copied blob

  *denorm = DENORM (x_centre, bln_x_height / row->x_height (), row);
  bn_blob = new PBLOB;           //get one
  *bn_blob = *this;              //deep copy
  bn_blob->move (FCOORD (-denorm->origin (), -row->base_line (x_centre)));
  bn_blob->scale (denorm->scale ());
  bn_blob->move (FCOORD (0.0, bln_baseline_offset));
  return bn_blob;
}
コード例 #2
0
ファイル: switch.c プロジェクト: myeongjinkim/sample
/* returns true if the player has pressed the switch (item) */
int pressed_the_switch(item_t *item, player_t *player)
{
    float a[4], b[4];

    a[0] = item->actor->position.x - item->actor->hot_spot.x;
    a[1] = item->actor->position.y - item->actor->hot_spot.y;
    a[2] = a[0] + image_width(actor_image(item->actor));
    a[3] = a[1] + image_height(actor_image(item->actor));

    b[0] = player->actor->position.x - player->actor->hot_spot.x + image_width(actor_image(player->actor)) * 0.3;
    b[1] = player->actor->position.y - player->actor->hot_spot.y + image_height(actor_image(player->actor)) * 0.5;
    b[2] = b[0] + image_width(actor_image(player->actor)) * 0.4;
    b[3] = b[1] + image_height(actor_image(player->actor)) * 0.5;

    return (!player_is_dying(player) && bounding_box(a,b));
}
コード例 #3
0
// Returns a pix of the original sample image. The pix is padded all round
// by padding wherever possible.
// The returned Pix must be pixDestroyed after use.
// If the input page_pix is nullptr, nullptr is returned.
Pix* TrainingSample::GetSamplePix(int padding, Pix* page_pix) const {
  if (page_pix == nullptr)
    return nullptr;
  int page_width = pixGetWidth(page_pix);
  int page_height = pixGetHeight(page_pix);
  TBOX padded_box = bounding_box();
  padded_box.pad(padding, padding);
  // Clip the padded_box to the limits of the page
  TBOX page_box(0, 0, page_width, page_height);
  padded_box &= page_box;
  Box* box = boxCreate(page_box.left(), page_height - page_box.top(),
                       page_box.width(), page_box.height());
  Pix* sample_pix = pixClipRectangle(page_pix, box, nullptr);
  boxDestroy(&box);
  return sample_pix;
}
コード例 #4
0
ファイル: GeoMapper.cpp プロジェクト: WenjieXu/ogs
void GeoMapper::mapData()
{
	const std::vector<GeoLib::Point*> *points (this->_geo_objects.getPointVec(this->_geo_name));
	GeoLib::Station* stn_test = dynamic_cast<GeoLib::Station*>((*points)[0]);
	bool is_borehole(false);
	if (stn_test != nullptr && static_cast<GeoLib::StationBorehole*>((*points)[0])->type() == GeoLib::Station::StationType::BOREHOLE)
		is_borehole = true;
	
	double min_val(0), max_val(0);
	if (_mesh)
	{
		GeoLib::AABB<GeoLib::Point> bounding_box (_mesh->getNodes().begin(), _mesh->getNodes().end());
		min_val = bounding_box.getMinPoint()[2];
		max_val = bounding_box.getMaxPoint()[2];
	}
	size_t nPoints (points->size());

	if (!is_borehole)
	{
		for (unsigned j=0; j<nPoints; ++j)
		{
			GeoLib::Point* pnt ((*points)[j]);
			(*pnt)[2] = (_grid) ? this->getMeshElevation((*pnt)[0],(*pnt)[1], min_val, max_val)
				                : this->getDemElevation((*pnt)[0],(*pnt)[1]);
		}
	}
	else
	{
		for (unsigned j=0; j<nPoints; ++j)
		{
			GeoLib::Point* pnt ((*points)[j]);
			double offset = (_grid) ? (this->getMeshElevation((*pnt)[0],(*pnt)[1], min_val, max_val) - (*pnt)[2])
				                    : (this->getDemElevation((*pnt)[0],(*pnt)[1]) - (*pnt)[2]);

			GeoLib::StationBorehole* borehole = static_cast<GeoLib::StationBorehole*>(pnt);
			const std::vector<GeoLib::Point*> layers = borehole->getProfile();
			size_t nLayers = layers.size();
			for (unsigned k=0; k<nLayers; ++k)
			{
				GeoLib::Point* layer_pnt = layers[k];
				(*layer_pnt)[2] = (*layer_pnt)[2] + offset;
			}
		}
	}
}
コード例 #5
0
ファイル: delaunay.cpp プロジェクト: omco/geode
static void spatial_sort(RawArray<Perturbed2> X, const int leaf_size, Random& random) {
  const int n = X.size();
  if (n<=leaf_size)
    return;

  // We determine the subdivision axis using inexact computation, which is okay since neither the result nor
  // the asymptotic worst case complexity depends upon any properties of the spatial_sort whatsoever.
  const Box<EV> box = bounding_box(X.project<EV,&Perturbed2::value_>());
  const int axis = box.sizes().argmax();

  // We use exact arithmetic to perform the partition, which is important in case many points are coincident
  const int mid = axis==0 ? spatial_partition<0>(X,random)
                          : spatial_partition<1>(X,random);

  // Recursely sort both halves
  spatial_sort(X.slice(0,mid),leaf_size,random);
  spatial_sort(X.slice(mid,n),leaf_size,random);
}
コード例 #6
0
ファイル: modelrender.cpp プロジェクト: ericandoh/Bawk
void RenderableModel::refresh() {
    bounds = bounding_box();
    for (auto &i: model_vertices) {
        bounds.expand(i);
    }
    // now set it so that our lower is at 0,0,0
    fvec3 lower_bound = bounds.lower;
    bounds.upper -= lower_bound;
    bounds.lower = fvec3(0,0,0);
    center_pos = bounds.get_world_pos();
    
    fvec3 aligned_center_pos = get_nearest_half_or_whole(center_pos);
    if (aligned_center_pos.x < 0.5f) {
        aligned_center_pos.x = 0.5f;
    }
    if (aligned_center_pos.y < 0.5f) {
        aligned_center_pos.y = 0.5f;
    }
    if (aligned_center_pos.z < 0.5f) {
        aligned_center_pos.z = 0.5f;
    }
    fvec3 center_offset = aligned_center_pos - center_pos;
    bounds.lower += center_offset;
    bounds.upper += center_offset;
    fvec3 offset = center_offset - lower_bound;
    
    for (unsigned int i = 0; i < model_vertices.size(); i++) {
        model_vertices[i] += offset;
    }
    
    bounds.lower = get_round_from_fvec3(bounds.lower);
    bounds.upper = get_round_from_fvec3(bounds.upper);
    // nothing should be 0 wide...
    if (bounds.upper.x == 0) {
        bounds.upper.x = 1.0f;
    }
    if (bounds.upper.y == 0) {
        bounds.upper.y = 1.0f;
    }
    if (bounds.upper.z == 0) {
        bounds.upper.z = 1.0f;
    }
    center_pos = bounds.get_world_pos();
}
コード例 #7
0
ファイル: entity.cpp プロジェクト: ericandoh/Bawk
Entity::Entity() {
    // identifying info for the entity. this should be overwritten
    vid = 0;
    pid = 0;
    entity_class = EntityType::ENTITY;
    can_collide = true;
    stable = false;
    bounds = bounding_box();
    velocity = fvec3(0, 0, 0);
    angular_velocity = fvec3(0, 0, 0);
    velocity_decay = DEFAULT_VELOCITY_DECAY;
    weight = 0;
    // 0 is full health
    health = 0;
    selected = false;
    
    // start out with no parent
    // damn that's depresssing
    parent = 0;
}
コード例 #8
0
ファイル: werd.cpp プロジェクト: ming-hai/tesseract
void WERD::print() {
  tprintf("Blanks= %d\n", blanks);
  bounding_box().print();
  tprintf("Flags = %d = 0%o\n", flags.val, flags.val);
  tprintf("   W_SEGMENTED = %s\n", flags.bit(W_SEGMENTED) ? "TRUE" : "FALSE ");
  tprintf("   W_ITALIC = %s\n", flags.bit(W_ITALIC) ? "TRUE" : "FALSE ");
  tprintf("   W_BOL = %s\n", flags.bit(W_BOL) ? "TRUE" : "FALSE ");
  tprintf("   W_EOL = %s\n", flags.bit(W_EOL) ? "TRUE" : "FALSE ");
  tprintf("   W_NORMALIZED = %s\n",
          flags.bit(W_NORMALIZED) ? "TRUE" : "FALSE ");
  tprintf("   W_SCRIPT_HAS_XHEIGHT = %s\n",
          flags.bit(W_SCRIPT_HAS_XHEIGHT) ? "TRUE" : "FALSE ");
  tprintf("   W_SCRIPT_IS_LATIN = %s\n",
          flags.bit(W_SCRIPT_IS_LATIN) ? "TRUE" : "FALSE ");
  tprintf("   W_DONT_CHOP = %s\n", flags.bit(W_DONT_CHOP) ? "TRUE" : "FALSE ");
  tprintf("   W_REP_CHAR = %s\n", flags.bit(W_REP_CHAR) ? "TRUE" : "FALSE ");
  tprintf("   W_FUZZY_SP = %s\n", flags.bit(W_FUZZY_SP) ? "TRUE" : "FALSE ");
  tprintf("   W_FUZZY_NON = %s\n", flags.bit(W_FUZZY_NON) ? "TRUE" : "FALSE ");
  tprintf("Correct= %s\n", correct.string());
  tprintf("Rejected cblob count = %d\n", rej_cblobs.length());
  tprintf("Script = %d\n", script_id_);
}
コード例 #9
0
ファイル: blobs.cpp プロジェクト: coffeesam/tesseract-ocr
// Normalize in-place and record the normalization in the DENORM.
void TWERD::Normalize(ROW* row, float x_height, bool numeric_mode,
                      DENORM* denorm) {
  TBOX word_box = bounding_box();
  DENORM antidote((word_box.left() + word_box.right()) / 2.0,
                  kBlnXHeight / x_height, row);
  if (row == NULL) {
    antidote = DENORM(antidote.origin(), antidote.scale(), 0.0,
                      word_box.bottom(), 0, NULL, false, NULL);
  }
  int num_segments = 0;
  DENORM_SEG *segs = new DENORM_SEG[NumBlobs()];
  for (TBLOB* blob = blobs; blob != NULL; blob = blob->next) {
    TBOX blob_box = blob->bounding_box();
    ICOORD translation(-static_cast<int>(floor(antidote.origin() + 0.5)),
                       -blob_box.bottom());
    float factor = antidote.scale();
    if (numeric_mode) {
      factor = ClipToRange(kBlnXHeight * 4.0f / (3 * blob_box.height()),
                           factor, factor * 1.5f);
      segs[num_segments].xstart = blob->bounding_box().left();
      segs[num_segments].ycoord = blob_box.bottom();
      segs[num_segments++].scale_factor = factor;
    } else {
      float blob_x_center = (blob_box.left() + blob_box.right()) / 2.0;
      float y_shift = antidote.yshift_at_orig_x(blob_x_center);
      translation.set_y(-static_cast<int>(floor(y_shift + 0.5)));
    }
    blob->Move(translation);
    blob->Scale(factor);
    blob->Move(ICOORD(0, kBlnBaselineOffset));
  }
  if (num_segments > 0) {
    antidote.set_segments(segs, num_segments);
  }
  delete [] segs;
  if (denorm != NULL)
    *denorm = antidote;
}
コード例 #10
0
ファイル: delaunay.cpp プロジェクト: omco/geode
// Greedily compute a set of nonintersecting edges in a point cloud for testing purposes
// Warning: Takes O(n^3) time.
static Array<Vector<int,2>> greedy_nonintersecting_edges(RawArray<const Vector<real,2>> X, const int limit) {
  const auto E = amap(quantizer(bounding_box(X)),X).copy();
  const int n = E.size();
  Array<Vector<int,2>> edges;
  IntervalScope scope;
  for (const int i : range(n*n)) {
    const int pi = int(random_permute(n*n,key+14,i));
    const int a = pi/n,
              b = pi-n*a;
    if (a < b) {
      const auto Ea = Perturbed2(a,E[a]),
                 Eb = Perturbed2(b,E[b]);
      for (const auto e : edges)
        if (!e.contains(a) && !e.contains(b) && segments_intersect(Ea,Eb,Perturbed2(e.x,E[e.x]),Perturbed2(e.y,E[e.y])))
          goto skip;
      edges.append(vec(a,b));
      if (edges.size()==limit || edges.size()==3*n-6)
        break;
      skip:;
    }
  }
  return edges;
}
コード例 #11
0
ファイル: PhysicsActor.cpp プロジェクト: DX94/BumpTop
Ogre::AxisAlignedBox PhysicsActor::world_bounding_box() {
  btVector3 aabbMin, aabbMax;
  rigid_body_->getAabb(aabbMin, aabbMax);
  Ogre::AxisAlignedBox bounding_box(toOgre(aabbMin), toOgre(aabbMax));
  return bounding_box;
}
コード例 #12
0
ファイル: delaunay.cpp プロジェクト: omco/geode
Ref<TriangleTopology> delaunay_points(RawArray<const Vector<real,2>> X, RawArray<const Vector<int,2>> edges,
                                      const bool validate) {
  return exact_delaunay_points(amap(quantizer(bounding_box(X)),X).copy(),edges,validate);
}
コード例 #13
0
ファイル: ntod.hpp プロジェクト: gouarin/cafes
    PetscErrorCode NtoD_matrix(Mat A, Vec x, Vec y){
      PetscErrorCode ierr;
      PetscFunctionBeginUser;

      std::size_t torque_size = (Dimensions==2)?1:3;

      Ctx *ctx;
      ierr = MatShellGetContext(A, (void**) &ctx);CHKERRQ(ierr);

      ierr = VecSet(ctx->problem.rhs, 0.);CHKERRQ(ierr);
      ierr = VecSet(ctx->problem.sol, 0.);CHKERRQ(ierr);

      auto box = fem::get_DM_bounds<Dimensions>(ctx->problem.ctx->problem.ctx->dm, 0);
      auto& h = ctx->problem.ctx->problem.ctx->h;

      std::size_t num = 0;

      if (ctx->compute_rhs)
      {
        ctx->problem.ctx->compute_rhs = true;
        ctx->problem.ctx->add_rigid_motion = false;
        ctx->problem.ctx->compute_singularity = true;
      }
      else
      {
        ctx->problem.ctx->compute_rhs = false;
        ctx->problem.ctx->add_rigid_motion = true;
        ctx->problem.ctx->compute_singularity = true;

        // set velocity and angular velocity on particles
        PetscScalar const *px;
        ierr = VecGetArrayRead(x, &px);CHKERRQ(ierr);

        std::size_t num_print = 0;
        for (std::size_t ipart=0; ipart<ctx->particles.size(); ++ipart)
        {
          auto p = ctx->particles[ipart];
          auto pbox = p.bounding_box(h);
          if (geometry::intersect(box, pbox))
          {
            for(std::size_t d=0; d<Dimensions; ++d)
              ctx->particles[ipart].velocity_[d] = px[num++];
            if (Dimensions == 2)
              ctx->particles[ipart].angular_velocity_[2] = px[num++];
            else
              for(std::size_t d=0; d<Dimensions; ++d)
                ctx->particles[ipart].angular_velocity_[d] = px[num++];
          }
        }
        ierr = VecRestoreArrayRead(x, &px);CHKERRQ(ierr);
      }

      ierr = ctx->problem.setup_RHS();CHKERRQ(ierr);

      // solve DtoN with these velocities
      ctx->problem.ctx->compute_rhs = false;
      ctx->problem.ctx->add_rigid_motion = false;
      ctx->problem.ctx->compute_singularity = false;

      ierr = ctx->problem.solve();CHKERRQ(ierr);

      std::vector<double> forces, torques;

      forces.resize(ctx->particles.size()*Dimensions);
      torques.resize(ctx->particles.size()*torque_size);

      std::fill(forces.begin(), forces.end(), 0.);
      std::fill(torques.begin(), torques.end(), 0.);

      ierr = forces_torques_with_control(ctx->particles,
                                         ctx->problem.sol,
                                         box,
                                         forces,
                                         torques,
                                         ctx->num,
                                         h,
                                         ctx->compute_singularity);CHKERRQ(ierr);

      // set y with the forces and the torques computed by DtoN
      num = 0;
      PetscScalar *py;
      ierr = VecGetArray(y, &py);CHKERRQ(ierr);

      for (std::size_t ipart=0; ipart<ctx->particles.size(); ++ipart)
      {
        auto p = ctx->particles[ipart];
        auto pbox = p.bounding_box(h);
        if (geometry::intersect(box, pbox))
        {
          for(std::size_t d=0; d<Dimensions; ++d)
            py[num++] = forces[ipart*Dimensions + d];
          for(std::size_t d=0; d<torque_size; ++d)
            py[num++] = torques[ipart*Dimensions + d];
        }
      }
      ierr = VecRestoreArray(y, &py);CHKERRQ(ierr);

      PetscFunctionReturn(0);
    }
コード例 #14
0
int visibility_test_id_histogram_renderer::
initialize(int& argc, char** argv)
{
 	namespace po = boost::program_options;
    namespace fs = boost::filesystem;

    const std::string exec_name = (argc > 0) ? fs::basename(argv[0]) : "";
    scm::shared_ptr<scm::core> scm_core(new scm::core(1, argv));

    putenv((char *)"__GL_SYNC_TO_VBLANK=0");

    std::string resource_file_path = "";

    // These value are read, but not used. Yet ignoring them in the terminal parameters would lead to misinterpretation.
    std::string pvs_output_file_path = "";
    std::string visibility_test_type = "";
    std::string grid_type = "";
    unsigned int grid_size = 1;
    unsigned int num_steps = 11;
    double oversize_factor = 1.5;
    float optimization_threshold = 1.0f;

	po::options_description desc("Usage: " + exec_name + " [OPTION]... INPUT\n\n"
                               "Allowed Options");
    desc.add_options()
      ("help", "print help message")
      ("width,w", po::value<int>(&resolution_x_)->default_value(1024), "specify window width (default=1024)")
      ("height,h", po::value<int>(&resolution_y_)->default_value(1024), "specify window height (default=1024)")
      ("resource-file,f", po::value<std::string>(&resource_file_path), "specify resource input-file")
      ("vram,v", po::value<unsigned>(&video_memory_budget_)->default_value(2048), "specify graphics memory budget in MB (default=2048)")
      ("mem,m", po::value<unsigned>(&main_memory_budget_)->default_value(4096), "specify main memory budget in MB (default=4096)")
      ("upload,u", po::value<unsigned>(&max_upload_budget_)->default_value(64), "specify maximum video memory upload budget per frame in MB (default=64)")
    // The following parameters are used by the main app only, yet must be identified nonetheless since otherwise they are dealt with as file paths.
      ("pvs-file,p", po::value<std::string>(&pvs_output_file_path), "specify output file of calculated pvs data")
      ("vistest", po::value<std::string>(&visibility_test_type)->default_value("histogramrenderer"), "specify type of visibility test to be used. ('histogramrenderer', 'randomhistogramrenderer')")
      ("gridtype", po::value<std::string>(&grid_type)->default_value("octree"), "specify type of grid to store visibility data ('regular', 'octree', 'hierarchical')")
      ("gridsize", po::value<unsigned int>(&grid_size)->default_value(1), "specify size/depth of the grid used for the visibility test (depends on chosen grid type)")
      ("oversize", po::value<double>(&oversize_factor)->default_value(1.5), "factor the grid bounds will be scaled by, default is 1.5 (grid bounds will exceed scene bounds by factor of 1.5)")
      ("optithresh", po::value<float>(&optimization_threshold)->default_value(1.0f), "specify the threshold at which common data are converged. Default is 1.0, which means data must be 100 percent equal.")
      ("numsteps,n", po::value<unsigned int>(&num_steps)->default_value(11), "specify the number of intervals the occlusion values will be split into (visibility analysis only)");
      ;

    po::variables_map vm;

    try
    {    
		auto parsed_options = po::command_line_parser(argc, argv).options(desc).allow_unregistered().run();
		po::store(parsed_options, vm);
		po::notify(vm);

		std::vector<std::string> to_pass_further = po::collect_unrecognized(parsed_options.options, po::include_positional);
		bool no_input = !vm.count("input") && to_pass_further.empty();

		if (resource_file_path == "")
		{
			if (vm.count("help") || no_input)
			{
				std::cout << desc;
				return 0;
			}
		}

		// no explicit input -> use unknown options
		if (!vm.count("input") && resource_file_path == "") 
		{
			resource_file_path = "auto_generated.rsc";
			std::fstream ofstr(resource_file_path, std::ios::out);
			if (ofstr.good()) 
			{
			for (auto argument : to_pass_further)
			{
				ofstr << argument << std::endl;
			}
		}
		else
		{
			throw std::runtime_error("Cannot open file");
		}
			ofstr.close();
		}
	}
	catch (std::exception& e)
	{
		std::cout << "Warning: No input file specified. \n" << desc;
		return 0;
	}

	lamure::pvs::glut_wrapper::initialize(argc, argv, resolution_x_, resolution_y_, nullptr);

    std::pair< std::vector<std::string>, std::vector<scm::math::mat4f> > model_attributes;
    std::set<lamure::model_t> visible_set;
    std::set<lamure::model_t> invisible_set;
    model_attributes = read_model_string(resource_file_path, &visible_set, &invisible_set);

    std::vector<scm::math::mat4f> & model_transformations = model_attributes.second;
    std::vector<std::string> const& model_filenames = model_attributes.first;

    lamure::ren::policy* policy = lamure::ren::policy::get_instance();
    policy->set_max_upload_budget_in_mb(max_upload_budget_);
    policy->set_render_budget_in_mb(video_memory_budget_);
    policy->set_out_of_core_budget_in_mb(main_memory_budget_);
    policy->set_window_width(resolution_x_);
    policy->set_window_height(resolution_y_);

	lamure::ren::model_database* database = lamure::ren::model_database::get_instance();
    management_ = new management_id_histogram_renderer(model_filenames, model_transformations, visible_set, invisible_set);
    glut_wrapper::set_management(management_);
    management_->set_pvs_file_path(pvs_output_file_path);

    // Calculate bounding box of whole scene.
    for(lamure::model_t model_id = 0; model_id < database->num_models(); ++model_id)
    {
        // Cast required from boxf to bounding_box.
        const scm::gl::boxf& box_model_root = database->get_model(model_id)->get_bvh()->get_bounding_boxes()[0];
        vec3r min_vertex(box_model_root.min_vertex() + database->get_model(model_id)->get_bvh()->get_translation());
        vec3r max_vertex(box_model_root.max_vertex() + database->get_model(model_id)->get_bvh()->get_translation());
        bounding_box model_root_box(min_vertex, max_vertex);

        if(model_id == 0)
        {
            scene_bounds_ = bounding_box(model_root_box);
        }
        else
        {
            scene_bounds_.expand(model_root_box);
        }  
    }

    return 0;
}
コード例 #15
0
ファイル: CubitEntity.cpp プロジェクト: tenpercent/cp-sandbox
CubitVector CubitEntity::center_point()
{
  return bounding_box().center();
}
コード例 #16
0
ファイル: game.cpp プロジェクト: FlibbleMr/neogfx
 virtual ng::vertex_list3 map() const
 {
     auto r = bounding_box();
     return ng::vertex_list3{ r.top_left().to_vector3(), r.top_right().to_vector3(), r.bottom_right().to_vector3(), r.bottom_left().to_vector3() };
 }
コード例 #17
0
ファイル: moebius_qt.cpp プロジェクト: UhtredBosch/mesecina
 void 
 init_coordinates(){
   xmin = -1; xmax = 1;
   ymin = -1; ymax = 1;
   bounding_box (xmin, ymin, xmax, ymax);
 }
コード例 #18
0
void PIXROW::char_clip_image(                     //box of imlines extnt
                             IMAGELINE *imlines,
                             BOX &im_box,
                             ROW *row,            //row containing word
                             IMAGE &clip_image,   //unscaled sq subimage
                             float &baseline_pos  //baseline ht in image
                            ) {
  INT16 clip_image_xsize;        //sub image x size
  INT16 clip_image_ysize;        //sub image y size
  INT16 x_shift;                 //from pixrow to subim
  INT16 y_shift;                 //from pixrow to subim
  BOX char_pix_box;              //bbox of char pixels
  INT16 y_dest;
  INT16 x_min;
  INT16 x_max;
  INT16 x_min_dest;
  INT16 x_max_dest;
  INT16 x_width;
  INT16 y;

  clip_image_xsize = clip_image.get_xsize ();
  clip_image_ysize = clip_image.get_ysize ();

  char_pix_box = bounding_box ();
  /*
    The y shift is calculated by first finding the coord of the bottom of the
    image relative to the image lines. Then reducing this so by the amount
    relative to the clip image size, necessary to vertically position the
    character.
  */
  y_shift = char_pix_box.bottom () - row_offset -
    (INT16) floor ((clip_image_ysize - char_pix_box.height () + 0.5) / 2);

  /*
    The x_shift is the shift to be applied to the page coord in the pixrow to
    generate a centred char in the clip image.  Thus the left hand edge of the
    char is shifted to the margin width of the centred character.
  */
  x_shift = char_pix_box.left () -
    (INT16) floor ((clip_image_xsize - char_pix_box.width () + 0.5) / 2);

  for (y = 0; y < row_count; y++) {
    /*
      Check that there is something in this row of the source that will fit in the
      sub image.  If there is, reduce x range if necessary, then copy it
    */
    y_dest = y - y_shift;
    if ((min[y] <= max[y]) && (y_dest >= 0) && (y_dest < clip_image_ysize)) {
      x_min = min[y];
      x_min_dest = x_min - x_shift;
      if (x_min_dest < 0) {
        x_min = x_min - x_min_dest;
        x_min_dest = 0;
      }
      x_max = max[y];
      x_max_dest = x_max - x_shift;
      if (x_max_dest > clip_image_xsize - 1) {
        x_max = x_max - (x_max_dest - (clip_image_xsize - 1));
        x_max_dest = clip_image_xsize - 1;
      }
      x_width = x_max - x_min + 1;
      if (x_width > 0) {
        x_min -= im_box.left ();
                                 //offset pixel ptr
        imlines[y].pixels += x_min;
        clip_image.put_line (x_min_dest, y_dest, x_width, imlines + y,
          0);
        imlines[y].init ();      //reset pixel ptr
      }
    }
  }
  /*
    Baseline position relative to clip image: First find the baseline relative
    to the page origin at the x coord of the centre of the character. Then
    make this relative to the character bottom. Finally shift by the margin
    between the bottom of the character and the bottom of the clip image.
  */
  if (row == NULL)
    baseline_pos = 0;            //Not needed
  else
    baseline_pos = row->base_line ((char_pix_box.left () +
      char_pix_box.right ()) / 2.0)
      - char_pix_box.bottom ()
      + ((clip_image_ysize - char_pix_box.height ()) / 2);
}
コード例 #19
0
ファイル: lock_camera.c プロジェクト: myeongjinkim/sample
void update(objectmachine_t *obj, player_t **team, int team_size, brick_list_t *brick_list, item_list_t *item_list, object_list_t *object_list)
{
    objectdecorator_t *dec = (objectdecorator_t*)obj;
    objectmachine_t *decorated_machine = dec->decorated_machine;
    object_t *object = obj->get_object_instance(obj);
    player_t *player = enemy_get_observed_player(object);
    objectdecorator_lockcamera_t *me = (objectdecorator_lockcamera_t*)obj;
    actor_t *act = object->actor, *ta;
    float rx, ry, rw, rh;
    int x1, x2, y1, y2;
    int i;

    /* configuring the rectangle */
    get_rectangle_coordinates(me, &x1, &y1, &x2, &y2);
    update_rectangle_coordinates(me, x1, y1, x2, y2);

    /* my rectangle, in world coordinates */
    rx = act->position.x + x1;
    ry = act->position.y + y1;
    rw = x2 - x1;
    rh = y2 - y1;

    /* only the observed player can enter this area */
    for(i=0; i<team_size; i++) {
        ta = team[i]->actor;

        if(team[i] != player) {
            /* hey, you can't enter here! */
            float border = 30.0f;
            if(ta->position.x > rx - border && ta->position.x < rx) {
                ta->position.x = rx - border;
                ta->speed.x = 0.0f;
            }
            if(ta->position.x > rx + rw && ta->position.x < rx + rw + border) {
                ta->position.x = rx + rw + border;
                ta->speed.x = 0.0f;
            }
        }
        else {
            /* test if the player has got inside my rectangle */
            float a[4], b[4];

            a[0] = ta->position.x;
            a[1] = ta->position.y;
            a[2] = ta->position.x + 1;
            a[3] = ta->position.y + 1;

            b[0] = rx;
            b[1] = ry;
            b[2] = rx + rw;
            b[3] = ry + rh;

            if(bounding_box(a, b)) {
                /* welcome, player! You have been locked. BWHAHAHA!!! */
                me->has_locked_somebody = TRUE;
                team[i]->in_locked_area = TRUE;
                level_lock_camera(rx, ry, rx+rw, ry+rh);
            }
        }
    }


    /* cage */
    if(me->has_locked_somebody) {
        ta = player->actor;
        if(ta->position.x < rx) {
            ta->position.x = rx;
            ta->speed.x = max(0.0f, ta->speed.x);
            player->at_some_border = TRUE;
        }
        if(ta->position.x > rx + rw) {
            ta->position.x = rx + rw;
            ta->speed.x = min(0.0f, ta->speed.x);
            player->at_some_border = TRUE;
        }
        ta->position.y = clip(ta->position.y, ry, ry + rh);
    }

    decorated_machine->update(decorated_machine, team, team_size, brick_list, item_list, object_list);
}
コード例 #20
0
// Called from the constructor.
// Set the initial bed shape from a list of points.
// Deduce the bed shape type(rect, circle, custom)
// This routine shall be smart enough if the user messes up
// with the list of points in the ini file directly.
void BedShapePanel::set_shape(ConfigOptionPoints* points)
{
	auto polygon = Polygon::new_scale(points->values);

	// is this a rectangle ?
	if (points->size() == 4) {
		auto lines = polygon.lines();
		if (lines[0].parallel_to(lines[2]) && lines[1].parallel_to(lines[3])) {
			// okay, it's a rectangle
			// find origin
			// the || 0 hack prevents "-0" which might confuse the user
			int x_min, x_max, y_min, y_max;
			x_max = x_min = points->values[0].x;
			y_max = y_min = points->values[0].y;
			for (auto pt : points->values){
				if (x_min > pt.x) x_min = pt.x;
				if (x_max < pt.x) x_max = pt.x;
				if (y_min > pt.y) y_min = pt.y;
				if (y_max < pt.y) y_max = pt.y;
			}
			if (x_min < 0) x_min = 0;
			if (x_max < 0) x_max = 0;
			if (y_min < 0) y_min = 0;
			if (y_max < 0) y_max = 0;
			auto origin = new ConfigOptionPoints{ Pointf(-x_min, -y_min) };

			m_shape_options_book->SetSelection(SHAPE_RECTANGULAR);
			auto optgroup = m_optgroups[SHAPE_RECTANGULAR];
			optgroup->set_value("rect_size", new ConfigOptionPoints{ Pointf(x_max - x_min, y_max - y_min) });//[x_max - x_min, y_max - y_min]);
			optgroup->set_value("rect_origin", origin);
			update_shape();
			return;
		}
	}

	// is this a circle ?
	{
		// Analyze the array of points.Do they reside on a circle ?
		auto center = polygon.bounding_box().center();
		std::vector<double> vertex_distances;
		double avg_dist = 0;
		for (auto pt: polygon.points)
		{
			double distance = center.distance_to(pt);
			vertex_distances.push_back(distance);
			avg_dist += distance;
		}
			
		bool defined_value = true;
		for (auto el: vertex_distances)
		{
			if (abs(el - avg_dist) > 10 * SCALED_EPSILON)
				defined_value = false;
			break;
		}
		if (defined_value) {
			// all vertices are equidistant to center
			m_shape_options_book->SetSelection(SHAPE_CIRCULAR);
			auto optgroup = m_optgroups[SHAPE_CIRCULAR];
			boost::any ret = wxNumberFormatter::ToString(unscale(avg_dist * 2), 0);
 			optgroup->set_value("diameter", ret);
			update_shape();
			return;
		}
	}

	if (points->size() < 3) {
		// Invalid polygon.Revert to default bed dimensions.
		m_shape_options_book->SetSelection(SHAPE_RECTANGULAR);
		auto optgroup = m_optgroups[SHAPE_RECTANGULAR];
		optgroup->set_value("rect_size", new ConfigOptionPoints{ Pointf(200, 200) });
		optgroup->set_value("rect_origin", new ConfigOptionPoints{ Pointf(0, 0) });
		update_shape();
		return;
	}

	// This is a custom bed shape, use the polygon provided.
	m_shape_options_book->SetSelection(SHAPE_CUSTOM);
	// Copy the polygon to the canvas, make a copy of the array.
	m_canvas->m_bed_shape = points->values;
	update_shape();
}
コード例 #21
0
ファイル: sprite.cpp プロジェクト: basisbit/neogfx
	vertex_list3 sprite::map() const
	{
		auto r = bounding_box();
		return vertex_list3{{ r.top_left().to_vector3(), r.top_right().to_vector3(), r.bottom_right().to_vector3(), r.bottom_left().to_vector3() }};
	}
コード例 #22
0
ファイル: ocrblock.cpp プロジェクト: ErwcPKerr/node-dv
// Compute the distance from the left and right ends of each row to the
// left and right edges of the block's polyblock.  Illustration:
//  ____________________________   _______________________
//  |  Howdy neighbor!         |  |rectangular blocks look|
//  |  This text is  written to|  |more like stacked pizza|
//  |illustrate how useful poly-  |boxes.                 |
//  |blobs  are   in -----------  ------   The    polyblob|
//  |dealing    with|     _________     |for a BLOCK  rec-|
//  |harder   layout|   /===========\   |ords the possibly|
//  |issues.        |    |  _    _  |   |skewed    pseudo-|
//  |  You  see this|    | |_| \|_| |   |rectangular      |
//  |text is  flowed|    |      }   |   |boundary     that|
//  |around  a  mid-|     \   ____  |   |forms the  ideal-|
//  |cloumn portrait._____ \       /  __|ized  text margin|
//  |  Polyblobs     exist| \    /   |from which we should|
//  |to account for insets|  |   |   |measure    paragraph|
//  |which make  otherwise|  -----   |indentation.        |
//  -----------------------          ----------------------
//
// If we identify a drop-cap, we measure the left margin for the lines
// below the first line relative to one space past the drop cap.  The
// first line's margin and those past the drop cap area are measured
// relative to the enclosing polyblock.
//
// TODO(rays): Before this will work well, we'll need to adjust the
//             polyblob tighter around the text near images, as in:
//             UNLV_AUTO:mag.3G0  page 2
//             UNLV_AUTO:mag.3G4  page 16
void BLOCK::compute_row_margins() {
  if (row_list()->empty() || row_list()->singleton()) {
    return;
  }

  // If Layout analysis was not called, default to this.
  POLY_BLOCK rect_block(bounding_box(), PT_FLOWING_TEXT);
  POLY_BLOCK *pblock = &rect_block;
  if (poly_block() != NULL) {
    pblock = poly_block();
  }

  // Step One: Determine if there is a drop-cap.
  //           TODO(eger): Fix up drop cap code for RTL languages.
  ROW_IT r_it(row_list());
  ROW *first_row = r_it.data();
  ROW *second_row = r_it.data_relative(1);

  // initialize the bottom of a fictitious drop cap far above the first line.
  int drop_cap_bottom = first_row->bounding_box().top() +
                        first_row->bounding_box().height();
  int drop_cap_right = first_row->bounding_box().left();
  int mid_second_line = second_row->bounding_box().top() -
                        second_row->bounding_box().height() / 2;
  WERD_IT werd_it(r_it.data()->word_list());  // words of line one
  if (!werd_it.empty()) {
    C_BLOB_IT cblob_it(werd_it.data()->cblob_list());
    for (cblob_it.mark_cycle_pt(); !cblob_it.cycled_list();
         cblob_it.forward()) {
      TBOX bbox = cblob_it.data()->bounding_box();
      if (bbox.bottom() <= mid_second_line) {
        // we found a real drop cap
        first_row->set_has_drop_cap(true);
        if (drop_cap_bottom >  bbox.bottom())
          drop_cap_bottom = bbox.bottom();
        if (drop_cap_right < bbox.right())
          drop_cap_right = bbox.right();
      }
    }
  }

  // Step Two: Calculate the margin from the text of each row to the block
  //           (or drop-cap) boundaries.
  PB_LINE_IT lines(pblock);
  r_it.set_to_list(row_list());
  for (r_it.mark_cycle_pt(); !r_it.cycled_list(); r_it.forward()) {
    ROW *row = r_it.data();
    TBOX row_box = row->bounding_box();
    int left_y = row->base_line(row_box.left()) + row->x_height();
    int left_margin;
    ICOORDELT_LIST *segments = lines.get_line(left_y);
    LeftMargin(segments, row_box.left(), &left_margin);
    delete segments;

    if (row_box.top() >= drop_cap_bottom) {
      int drop_cap_distance = row_box.left() - row->space() - drop_cap_right;
      if (drop_cap_distance < 0)
        drop_cap_distance = 0;
      if (drop_cap_distance < left_margin)
        left_margin = drop_cap_distance;
    }

    int right_y = row->base_line(row_box.right()) + row->x_height();
    int right_margin;
    segments = lines.get_line(right_y);
    RightMargin(segments, row_box.right(), &right_margin);
    delete segments;
    row->set_lmargin(left_margin);
    row->set_rmargin(right_margin);
  }
}
コード例 #23
0
ファイル: FacetLump.cpp プロジェクト: chrismullins/cgma
CubitStatus FacetLump::mass_properties( CubitVector& centroid, double& volume )
{
  int i;
  
  DLIList<FacetShell*> shells( myShells.size() );
  CAST_LIST( myShells, shells, FacetShell );
  assert( myShells.size() == shells.size() );
  
  DLIList<FacetSurface*> surfaces;
  DLIList<FacetShell*> surf_shells;
  get_surfaces( surfaces );
  
  DLIList<CubitFacet*> facets, surf_facets;
  DLIList<CubitPoint*> junk;
  DLIList<CubitSense> senses;
  for (i = surfaces.size(); i--; )
  {
    FacetSurface* surf = surfaces.step_and_get();
    surf_shells.clean_out();
    surf->get_shells( surf_shells );
    surf_shells.intersect( shells );
    assert( surf_shells.size() );
    CubitSense sense = surf->get_shell_sense( surf_shells.get() );
    if (surf_shells.size() == 1 && CUBIT_UNKNOWN != sense)
    {
      surf_facets.clean_out();
      junk.clean_out();
      surf->get_my_facets( surf_facets, junk );
      facets += surf_facets;
      
      for (int j = surf_facets.size(); j--; )
        senses.append(sense);
    }
  }
  
  const CubitVector p0 = bounding_box().center();
  CubitVector p1, p2, p3, normal;
  centroid.set( 0.0, 0.0, 0.0 );
  volume = 0.0;
  
  facets.reset();
  senses.reset();
  for (i = facets.size(); i--; )
  {
    CubitFacet* facet = facets.get_and_step();
    CubitSense sense = senses.get_and_step();
    p1 = facet->point(0)->coordinates();
    p2 = facet->point(1)->coordinates();
    p3 = facet->point(2)->coordinates();
    normal = (p3 - p1) * (p2 - p1);

    double two_area = normal.length();
    if (two_area > CUBIT_RESABS )
    {
      if (CUBIT_REVERSED == sense)
        normal = -normal;

      normal /= two_area;

      double height = normal % (p0 - p1);
      double vol = two_area * height;

      volume += vol;
      centroid += vol * (p0 + p1 + p2 + p3);
    }
  }
  
  if (volume > CUBIT_RESABS)
    centroid /= 4.0 * volume;
  volume /= 6.0;
  return CUBIT_SUCCESS;
}
コード例 #24
0
/*-+-+-* Logger *-+-+-*/
void MapStatistics::show(bool mesh, bool geom, bool error, bool param) {
    if(mesh) {
        Logger::out("Components")
                << num_components() << std::endl ;

        Logger::out("Mesh stats")
                << num_vertex() << " vertices, "
                << num_facet() << " facets, "
                << border_size() << "/" << num_edge() << " border edges."
                << sock_factor() << " sock factor."
                << std::endl ;
    }

    if(geom) {
        bounding_box() ;
        Logger::out("Vertex bounding box")
                << "["
                << bbox_[0] << "," << bbox_[1] << "]x["
                << bbox_[2] << "," << bbox_[3] << "]x["
                << bbox_[4] << "," << bbox_[5]
                << "]" << std::endl ;

        gravity_center() ;

        Logger::out("Gravity center")
                << "("
                << G_.x() << ", " << G_.y() << ", " << G_.z()
                << ")" << std::endl ;

        Logger::out("Surface area")
                << "area2D = " << total_area_2D() << " area3D = " << total_area_3D()
                << std::endl ;

        Logger::out("Facet area 3D")
                << min_facet_area_3D() << " min. "
                << average_facet_area_3D() << " av. "
                << max_facet_area_3D() << " max."
                << std::endl ;

        if(is_parameterized()) {
            Logger::out("Facet area 2D")
                    << min_facet_area_2D() << " min. "
                    << average_facet_area_2D() << " av. "
                    << max_facet_area_2D() << " max."
                    << std::endl ;
        }

        Logger::out("Mesh length")
                << "Total length 2D = " << total_length_2D()
                << " Total length3D = " << total_length_3D()
                << std::endl ;

        if(is_parameterized_) {
            Logger::out("Edge length 2D")
                    << min_edge_length_2D() << " min. "
                    << average_edge_length_2D() << " av. "
                    << max_edge_length_2D() << " max."
                    << std::endl ;
        }

        Logger::out("Edge length 3D")
                << min_edge_length_3D() << " min. "
                << average_edge_length_3D() << " av. "
                << max_edge_length_3D() << " max."
                << std::endl ;

        if(border_size() > 0) {
            Logger::out("Border count")
                    << "Total length2D " << border_length2D()
                    << " Total length3D " << border_length3D()
                    << std::endl ;
        }
        else Logger::out("Border count") << "Surface is closed." << std::endl ;
    }


    if(error) {
        Logger::out("Errors")
                << num_null_edge_3D() << " null 3D edges, "
                << num_null_edge_2D() << " null 2D edges. "
                << num_flat_facet_3D() << " flat 3D facets, "
                << num_flat_facet_2D() << " flat 2D facets."
                << std::endl ;
    }

    if(param && is_parameterized()) {
        Logger::out("Atlas stats")
                << "Surfacic deformation: "
                << average_area_deformation() << "% av. "
                << max_area_deformation() << "% max."
                << std::endl ;
        Logger::out("Atlas stats")
                << "Error on Jacobian: "
                << jacobian_error() << "%."
                << std::endl ;

        Logger::out("Atlas stats")
                << "Angular deformation: "
                << average_angle_deformation() << "% av. "
                << max_angle_deformation() << "% max."
                << std::endl ;

        Logger::out("Atlas stats")
                << "Length deformation: "
                << average_length_deformation() << "% av. "
                << max_length_deformation() << "% max."
                << std::endl ;
    }
    else Logger::out("Atlas Stats") << "Surface is not parameterized." << std::endl ;
}
コード例 #25
0
ファイル: report.cpp プロジェクト: bear24rw/EECE6086
void write_report(rows_t& rows, channels_t& channels)
{
    printf("Number of cell: %d\n", num_cells);
    printf("Number of nets: %d\n", num_nets);
    printf("\n");


    printf("Placement\n");
    printf("---------\n");

    point_t grid_size = calculate_grid_size();
    printf("Initial grid size: %d %d\n", grid_size.x, grid_size.y);

    int num_feed_throughs = 0;
    for (auto &row : rows) {
        for (auto &cell : row) {
            if (cell->feed_through)
                num_feed_throughs++;
        }
    }
    printf("Number of feed through cells: %d\n", num_feed_throughs);
    printf("\n");

    printf("Routing\n");
    printf("-------\n");

    int num_vias = 0;
    for (auto &row : rows) {
        for (auto &cell : row) {
            for (auto &term : cell->terms) {
                if (term.dest_term == nullptr) continue;
                if (term.track_num == VERTICAL) continue;
                if (term.track_num == UNROUTED) continue;
                num_vias++;
            }
        }
    }

    printf("Number of vias: %d\n", num_vias);

    int num_tracks = 0;
    for (auto &channel : channels) {
        num_tracks += channel.tracks.size();
    }

    printf("Total number of tracks: %d\n", num_tracks);
    printf("Total wirelength: %d\n", total_wire_length(channels));
    printf("\n");

    point_t size = bounding_box(rows, &channels);
    printf("Size\n");
    printf("----\n");
    printf("Total width: %d\n", size.x);
    printf("Total height: %d\n", size.y);
    printf("Total area: %d\n", size.x*size.y);
    printf("Squareness (width/height): %f\n", (double)size.x/(double)size.y);
    printf("\n");

    printf("Time\n");
    printf("----\n");
    printf("Place time: %fs\n", double(place_time - start_time) / CLOCKS_PER_SEC);
    printf("Route time: %fs\n", double(route_time - place_time) / CLOCKS_PER_SEC);
    printf("Total time: %fs\n", double(end_time   - start_time) / CLOCKS_PER_SEC);
    printf("\n");

    // http://stackoverflow.com/a/12675172/253650

    int tSize = 0, resident = 0, share = 0;
    std::ifstream buffer("/proc/self/statm");
    buffer >> tSize >> resident >> share;
    buffer.close();

    long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
    double rss = resident * page_size_kb;
    double shared_mem = share * page_size_kb;

    printf("Memory used: %f kB\n", rss-shared_mem);

}
コード例 #26
0
ファイル: OCCSurface.cpp プロジェクト: tenpercent/cp-sandbox
CubitStatus OCCSurface::get_point_normal( CubitVector& location,
                                            CubitVector& normal )
{
  return closest_point( bounding_box().center(), &location, &normal );
}   
コード例 #27
0
ファイル: BoundingBox.cpp プロジェクト: gideonmay/PyOSG
void init_BoundingBox()
{
    class_<osg::BoundingBox> bounding_box("BoundingBox",
            "General purpose axis-aligned bounding box class for enclosing objects/vertices.\n"
            "Used to bounding the leaf objects in the scene,\n"
            "i.e. osg::Drawable's to assist in view frustum culling etc.\n");

    bounding_box
        .def_readwrite("_min", &osg::BoundingBox::_min)
        .def_readwrite("_max", &osg::BoundingBox::_max)
        .def(init<>())
        .def(init<float, float, float, float, float, float>())
            // "construct to with specified min and max values.\n")

        .def(init<osg::Vec3, osg::Vec3>())
            // "construct to with specified min and max values.\n")

        .def("init", &osg::BoundingBox::init,
            "initialize to invalid values to represent an unset bounding box.")

        .def("valid", &osg::BoundingBox::valid)

        .def("set",
            (void (osg::BoundingBox::*)(float, float, float, float, float, float))
            &osg::BoundingBox::set)
        .def("set",
            (void (osg::BoundingBox::*)(const osg::Vec3&, const osg::Vec3 &))
            &osg::BoundingBox::set)

        .def("xMin", (float (osg::BoundingBox::*)() const)&osg::BoundingBox::xMin)
        .def("yMin", (float (osg::BoundingBox::*)() const)&osg::BoundingBox::yMin)
        .def("zMin", (float (osg::BoundingBox::*)() const)&osg::BoundingBox::zMin)
        .def("xMax", (float (osg::BoundingBox::*)() const)&osg::BoundingBox::xMax)
        .def("yMax", (float (osg::BoundingBox::*)() const)&osg::BoundingBox::yMax)
        .def("zMax", (float (osg::BoundingBox::*)() const)&osg::BoundingBox::zMax)

        .def("center",
            &osg::BoundingBox::center,
            "Calculate and return the center of the bounding box.\n")

        .def("radius",
            &osg::BoundingBox::radius,
            "Calculate and return the radius of the bounding box.\n")

        .def("radius2",
            &osg::BoundingBox::radius2,
            "Calculate and return the radius squared of the bounding box.\n"
            "Note, radius2() is faster to calculate than radius().\n")

        .def("corner",
            &osg::BoundingBox::corner,
            "corner(pos) -> Vec3\n\n"
            "return the corner of the bounding box.\n"
            "Position (pos) is specified by a number between 0 and 7,\n"
            "the first bit toggles between x min and x max, second\n"
            "bit toggles between y min and y max, third bit toggles\n"
            "between z min and z max.\n")

        .def("expandBy", 
            (void(osg::BoundingBox::*)(const osg::Vec3&)) &osg::BoundingBox::expandBy)
        .def("expandBy", 
            (void(osg::BoundingBox::*)(float, float, float)) &osg::BoundingBox::expandBy)
        .def("expandBy",
            (void(osg::BoundingBox::*)(const osg::BoundingBox&)) &osg::BoundingBox::expandBy)
        .def("expandBy",
            (void(osg::BoundingBox::*)(const osg::BoundingSphere&)) &osg::BoundingBox::expandBy)
        .def("intersect",
            &osg::BoundingBox::intersect)
        .def("intersects",
            &osg::BoundingBox::intersects)
//        .def("contains",
//            &osg::BoundingBox::contains)
        .def("__str__",
            &BoundingBox_str)
        .def("__repr__",
            &BoundingBox_repr)
        ;
}
コード例 #28
0
int main (int argc, char* argv[])
{
    ApplicationsLib::LogogSetup logog_setup;

    std::vector<std::string> keywords;
    keywords.push_back("-ALL");
    keywords.push_back("-MESH");
    keywords.push_back("-LOWPASS");

    if (argc < 3)
    {
        INFO(
            "Moves mesh nodes and connected elements either by a given value "
            "or based on a list.\n");
        INFO("Usage: %s <msh-file.msh> <keyword> [<value1>] [<value2>]",
             argv[0]);
        INFO("Available keywords:");
        INFO(
            "\t-ALL <value1> <value2> : changes the elevation of all mesh "
            "nodes by <value2> in direction <value1> [x,y,z].");
        INFO(
            "\t-MESH <value1> <value2> : changes the elevation of mesh nodes "
            "based on a second mesh <value1> with a search range of <value2>.");
        INFO(
            "\t-LOWPASS : applies a lowpass filter over node elevation using "
            "directly connected nodes.");
        return EXIT_FAILURE;
    }

    const std::string msh_name(argv[1]);
    const std::string current_key(argv[2]);
    std::string const ext (BaseLib::getFileExtension(msh_name));
    if (!(ext == "msh" || ext == "vtu"))
    {
        ERR("Error: Parameter 1 must be a mesh-file (*.msh / *.vtu).");
        INFO("Usage: %s <msh-file.gml> <keyword> <value>", argv[0]);
        return EXIT_FAILURE;
    }

    bool is_keyword(false);
    for (auto & keyword : keywords)
        if (current_key.compare(keyword)==0)
        {
            is_keyword = true;
            break;
        }

    if (!is_keyword)
    {
        ERR("Keyword not recognised. Available keywords:");
        for (auto const& keyword : keywords)
            INFO("\t%s", keyword.c_str());
        return EXIT_FAILURE;
    }

    std::unique_ptr<MeshLib::Mesh> mesh (MeshLib::IO::readMeshFromFile(msh_name));
    if (mesh == nullptr)
    {
        ERR ("Error reading mesh file.");
        return 1;
    }

    // Start keyword-specific selection of nodes

    // moves the elevation of all nodes by value
    if (current_key.compare("-ALL")==0)
    {
        if (argc < 5)
        {
            ERR("Missing parameter...");
            return EXIT_FAILURE;
        }
        const std::string dir(argv[3]);
        unsigned idx = (dir.compare("x") == 0) ? 0 : (dir.compare("y") == 0) ? 1 : 2;
        const double value(strtod(argv[4],0));
        INFO("Moving all mesh nodes by %g in direction %d (%s)...", value, idx,
             dir.c_str());
        //double value(-10);
        const std::size_t nNodes(mesh->getNumberOfNodes());
        std::vector<MeshLib::Node*> nodes (mesh->getNodes());
        for (std::size_t i=0; i<nNodes; i++)
        {
            (*nodes[i])[idx] += value;
        }
    }

    // maps the elevation of mesh nodes according to a ground truth mesh whenever nodes exist within max_dist
    if (current_key.compare("-MESH")==0)
    {
        if (argc < 5)
        {
            ERR("Missing parameter...");
            return EXIT_FAILURE;
        }
        const std::string value (argv[3]);
        double max_dist(pow(strtod(argv[4],0), 2));
        double offset (0.0); // additional offset for elevation (should be 0)
        std::unique_ptr<MeshLib::Mesh> ground_truth (MeshLib::IO::readMeshFromFile(value));
        if (ground_truth == nullptr)
        {
            ERR ("Error reading mesh file.");
            return EXIT_FAILURE;
        }

        const std::vector<MeshLib::Node*>& ground_truth_nodes (ground_truth->getNodes());
        GeoLib::AABB bounding_box(ground_truth_nodes.begin(), ground_truth_nodes.end());
        MathLib::Point3d const& min(bounding_box.getMinPoint());
        MathLib::Point3d const& max(bounding_box.getMaxPoint());

        const std::size_t nNodes(mesh->getNumberOfNodes());
        std::vector<MeshLib::Node*> nodes (mesh->getNodes());

        for (std::size_t i=0; i<nNodes; i++)
        {
            bool is_inside (containsPoint(*nodes[i], min, max));
            if (is_inside)
            {
                int idx = find_closest_point(nodes[i], ground_truth_nodes, max_dist);
                if (idx>=0)
                    (*nodes[i])[2] = (*(ground_truth_nodes[idx]))[2]-offset;
            }
        }
    }

    // a simple lowpass filter for the elevation of mesh nodes using the elevation of each node
    // weighted by 2 and the elevation of each connected node weighted by 1
    if (current_key.compare("-LOWPASS")==0)
    {
        const std::size_t nNodes(mesh->getNumberOfNodes());
        std::vector<MeshLib::Node*> nodes (mesh->getNodes());

        std::vector<double> elevation(nNodes);
        for (std::size_t i=0; i<nNodes; i++)
            elevation[i] = (*nodes[i])[2];

        for (std::size_t i=0; i<nNodes; i++)
        {
            const std::vector<MeshLib::Node*> conn_nodes (nodes[i]->getConnectedNodes());
            const unsigned nConnNodes (conn_nodes.size());
            elevation[i] = (2*(*nodes[i])[2]);
            for (std::size_t j=0; j<nConnNodes; ++j)
                elevation[i] += (*conn_nodes[j])[2];
            elevation[i] /= (nConnNodes+2);
        }

        for (std::size_t i=0; i<nNodes; i++)
            (*nodes[i])[2] = elevation[i];
    }
    /**** add other keywords here ****/

    std::string const new_mesh_name (msh_name.substr(0, msh_name.length() - 4) + "_new.vtu");
    if (MeshLib::IO::writeMeshToFile(*mesh, new_mesh_name) != 0)
        return EXIT_FAILURE;

    INFO ("Result successfully written.")
    return EXIT_SUCCESS;
}
コード例 #29
0
ファイル: stepblob.cpp プロジェクト: coffeesam/tesseract-ocr
// Returns a Pix rendering of the blob. pixDestroy after use.
Pix* C_BLOB::render() {
  TBOX box = bounding_box();
  Pix* pix = pixCreate(box.width(), box.height(), 1);
  render_outline_list(&outlines, box.left(), box.top(), pix);
  return pix;
}
コード例 #30
0
ファイル: bvh_stream.cpp プロジェクト: scholli/lamure
void bvh_stream::
read_bvh(const std::string& filename, bvh& bvh) {
 
    open_stream(filename, bvh_stream_type::BVH_STREAM_IN);

    if (type_ != BVH_STREAM_IN) {
        throw std::runtime_error(
            "PLOD: bvh_stream::Failed to read bvh from: " + filename_);
    }
    if (!file_.is_open()) {
         throw std::runtime_error(
            "PLOD: bvh_stream::Failed to read bvh from: " + filename_);
    }
   
    //scan stream
    file_.seekg(0, std::ios::end);
    size_t filesize = (size_t)file_.tellg();
    file_.seekg(0, std::ios::beg);

    num_segments_ = 0;

    bvh_tree_seg tree;
    bvh_tree_extension_seg tree_ext;
    std::vector<bvh_node_seg> nodes;
    std::vector<bvh_node_extension_seg> nodes_ext;
    uint32_t tree_id = 0;
    uint32_t tree_ext_id = 0;
    uint32_t node_id = 0;
    uint32_t node_ext_id = 0;


    //go through entire stream and fetch the segments
    while (true) {
        bvh_sig sig;
        sig.deserialize(file_);
        if (sig.signature_[0] != 'B' ||
            sig.signature_[1] != 'V' ||
            sig.signature_[2] != 'H' ||
            sig.signature_[3] != 'X') {
             throw std::runtime_error(
                 "PLOD: bvh_stream::Invalid magic encountered: " + filename_);
        }
            
        size_t anchor = (size_t)file_.tellg();

        switch (sig.signature_[4]) {

            case 'F': { //"BVHXFILE"
                bvh_file_seg seg;
                seg.deserialize(file_);
                break;
            }
            case 'T': { 
                switch (sig.signature_[5]) {
                    case 'R': { //"BVHXTREE"
                        tree.deserialize(file_);
                        ++tree_id;
                        break;
                    }
                    case 'E': { //"BVHXTEXT"
                        tree_ext.deserialize(file_);
                        ++tree_ext_id;
                        break;                     
                    }
                    default: {
                        throw std::runtime_error(
                            "PLOD: bvh_stream::Stream corrupt -- Invalid segment encountered");
                        break;
                    }
                }
                break;
            }
            case 'N': { 
                switch (sig.signature_[5]) {
                    case 'O': { //"BVHXNODE"
                        bvh_node_seg node;
                        node.deserialize(file_);
                        nodes.push_back(node);
                        if (node_id != node.node_id_) {
                            throw std::runtime_error(
                                "PLOD: bvh_stream::Stream corrupt -- Invalid node order");
                        }
                        ++node_id;
                        break;
                    }
                    case 'E': { //"BVHXNEXT"
                        bvh_node_extension_seg node_ext;
                        node_ext.deserialize(file_);
                        nodes_ext.push_back(node_ext);
                        if (node_ext_id != node_ext.node_id_) {
                            throw std::runtime_error(
                                "PLOD: bvh_stream::Stream corrupt -- Invalid node extension order");
                        }
                        ++node_ext_id;
                        break;
                    }
                    default: {
                        throw std::runtime_error(
                            "PLOD: bvh_stream::Stream corrupt -- Invalid segment encountered");
                        break;
                    }
                }
                break;
            }
            default: {
                throw std::runtime_error(
                    "PLOD: bvh_stream::file corrupt -- Invalid segment encountered");
                break;
            }
        }

        if (anchor + sig.allocated_size_ < filesize) {
            file_.seekg(anchor + sig.allocated_size_, std::ios::beg);
        }
        else {
            break;
        }

    }

    close_stream(false);

    if (tree_id != 1) {
       throw std::runtime_error(
           "PLOD: bvh_stream::Stream corrupt -- Invalid number of bvh segments");
    }   

    if (tree_ext_id > 1) {
       throw std::runtime_error(
           "PLOD: bvh_stream::Stream corrupt -- Invalid number of bvh extensions");
    }    

    //Note: This is the preprocessing library version of the file reader!

    //setup bvh
    bvh.set_depth(tree.depth_);
    bvh.set_fan_factor(tree.fan_factor_);
    bvh.set_max_surfels_per_node(tree.max_surfels_per_node_);
    scm::math::vec3f translation(tree.translation_.x_,
                                 tree.translation_.y_,
                                 tree.translation_.z_);
    bvh.set_translation(vec3r(translation));
    if (tree.num_nodes_ != node_id) {
        throw std::runtime_error(
            "PLOD: bvh_stream::Stream corrupt -- Invalid number of node segments");
    }
    if (tree_ext_id > 0) {
        if (tree.num_nodes_ != node_ext_id) {
            throw std::runtime_error(
                "PLOD: bvh_stream::Stream corrupt -- Invalid number of node extensions");
        }
    }
    
    std::vector<shared_file> level_temp_files;
    
    bvh::state_type current_state = static_cast<bvh::state_type>(tree.state_);
    
    //check if intermediate state
    bool interm_state = current_state == bvh::state_type::after_downsweep
      || current_state == bvh::state_type::after_upsweep;

    boost::filesystem::path base_path;
    if (interm_state) {
        if (tree_ext_id != 1) {
            throw std::runtime_error(
                "PLOD: bvh_stream::Stream corrupt -- Stream is missing tree extension");
        }
        //working_directory = tree_ext.working_directory_.string_;
        //basename_ = boost::filesystem::path(tree_ext.filename_.string_);
        base_path = boost::filesystem::path(tree_ext.filename_.string_);

        //setup level temp files
        for (uint32_t i = 0; i < tree_ext.num_disk_accesses_; ++i) {
             level_temp_files.push_back(std::make_shared<file>());
             level_temp_files.back()->open(tree_ext.disk_accesses_[i].string_, false);
        }
    }
    else {
        base_path = boost::filesystem::canonical(boost::filesystem::path(filename));
        base_path.replace_extension("");
    }
    bvh.set_base_path(base_path);

    //setup nodes
    std::vector<bvh_node> bvh_nodes(tree.num_nodes_);

    for (uint32_t i = 0; i < tree.num_nodes_; ++i) {
       const auto& node = nodes[i];

       if (i != node.node_id_) {
           throw std::runtime_error(
               "PLOD: bvh_stream::Stream corrupt -- Invalid node ordering");
       }

       scm::math::vec3f centroid(node.centroid_.x_,
                                 node.centroid_.y_,
                                 node.centroid_.z_);
       scm::math::vec3f box_min(node.bounding_box_.min_.x_,
                                node.bounding_box_.min_.y_,
                                node.bounding_box_.min_.z_);
       scm::math::vec3f box_max(node.bounding_box_.max_.x_,
                                node.bounding_box_.max_.y_,
                                node.bounding_box_.max_.z_);

       if (interm_state) {
           const auto& node_ext = nodes_ext[i];
           if (i != node_ext.node_id_) {
               throw std::runtime_error(
                   "PLOD: bvh_stream::Stream corrupt -- Invalid extension ordering");
           }
           
           if (node_ext.empty_ == 1) {
               bvh_nodes[i] = bvh_node(node.node_id_, node.depth_, bounding_box(vec3r(box_min), vec3r(box_max)));
           }
           else {
               const auto& disk_array = node_ext.disk_array_;
               surfel_disk_array sdarray = surfel_disk_array(level_temp_files[disk_array.disk_access_ref_],
                                                                   disk_array.offset_,
                                                                   disk_array.length_);
               bvh_nodes[i] = bvh_node(node.node_id_, node.depth_, bounding_box(vec3r(box_min), vec3r(box_max)), sdarray);
           }
       }
       else {
           //init empty nodes. We don't use surfelDIskArray
           //because we deal with serialized data
           bvh_nodes[i] = bvh_node(node.node_id_, node.depth_, bounding_box(vec3r(box_min), vec3r(box_max)));
       }

       //set node params
       bvh_nodes[i].set_reduction_error(node.reduction_error_);
       bvh_nodes[i].set_centroid(vec3r(centroid));
       bvh_nodes[i].set_avg_surfel_radius(node.avg_surfel_radius_);
       bvh_nodes[i].set_visibility((bvh_node::node_visibility)node.visibility_);
       bvh_nodes[i].set_max_surfel_radius_deviation(node.max_surfel_radius_deviation_);
    }

    bvh.set_first_leaf(tree.num_nodes_ - std::pow(tree.fan_factor_, tree.depth_));
    bvh.set_state(current_state);
    bvh.set_nodes(bvh_nodes);

}