cv::Mat OpenCvDetector::calculateFeatureMatrix(const Segments& segments)
{
    cv::Mat featureMatrix(segments.size(), m_featureDimensions.size(), CV_32FC1);

    for(size_t i = 0; i < segments.size(); i++) {
        const Segment& segment = segments[i];
        std::map<FeatureDimension, float> featureValueLookup; // one entry per dimension per feature

        for(size_t j = 0; j < m_features.size(); j++) { 
            Feature::Ptr feature = m_features[j];
            Eigen::VectorXd values;
            feature->evaluate(segment, values);

            // Each feature can have multiple dimensions, store these in a map so we can look up
            // the requested dimensions in the next step
            for(size_t dim = 0; dim < feature->getNDimensions(); dim++) { 
                featureValueLookup[ feature->getDescription(dim) ] = values(dim);
            }
        }

        // Look up the requested dimensions
        for(size_t k = 0; k < m_featureDimensions.size(); k++) { 
            const FeatureDimension& featureDescription = m_featureDimensions[k];
            featureMatrix.at<float>(i, k) = featureValueLookup[featureDescription];
        }
    }

    return featureMatrix;
}
Пример #2
0
Segments Conversion::Convert(const Segments& input) const {
  Segments output;
  for (const auto& segment : input) {
    output.AddSegment(Convert(segment));
  }
  return output;
}
Пример #3
0
Segments CSGNode::intersectLocal(const ray& r) const{
	Segments ret;
	if (isLeaf){
		SegmentPoint pNear, pFar;
		isect i;
		ray backR(r.at(-10000), r.getDirection());
		if(!item->intersect(backR, i))return ret;
		pNear.t = i.t - 10000;
		pNear.normal = i.N;
		pNear.isRight = false;
		ray contiR(r.at(pNear.t+RAY_EPSILON*10),r.getDirection());
		if (!item->intersect(contiR, i))pFar = pNear;
		else {
			pFar.t = i.t + pNear.t;
			pFar.normal = i.N;
		}
		pFar.isRight = true;
		ret.addPoint(pNear);
		ret.addPoint(pFar);
		return ret;
	}
	else {
		if (!lchild || !rchild)return ret;
		Segments leftSeg, rightSeg;
		leftSeg = lchild->intersectLocal(r);
		rightSeg = rchild->intersectLocal(r);
		leftSeg.Merge(rightSeg,relation);
		return leftSeg;
	}
}
Пример #4
0
std::shared_ptr<const Table> ShowColumns::_on_execute() {
  TableColumnDefinitions column_definitions;
  column_definitions.emplace_back("column_name", DataType::String);
  column_definitions.emplace_back("column_type", DataType::String);
  column_definitions.emplace_back("is_nullable", DataType::Int);
  auto out_table = std::make_shared<Table>(column_definitions, TableType::Data);

  const auto table = StorageManager::get().get_table(_table_name);
  Segments segments;

  const auto& column_names = table->column_names();
  const auto vs_names = std::make_shared<ValueSegment<pmr_string>>(
      tbb::concurrent_vector<pmr_string>(column_names.begin(), column_names.end()));
  segments.push_back(vs_names);

  const auto& column_types = table->column_data_types();

  auto column_types_as_string = tbb::concurrent_vector<pmr_string>{};
  for (const auto column_type : column_types) {
    column_types_as_string.push_back(pmr_string{data_type_to_string.left.at(column_type)});
  }

  const auto vs_types = std::make_shared<ValueSegment<pmr_string>>(std::move(column_types_as_string));
  segments.push_back(vs_types);

  const auto& column_nullables = table->columns_are_nullable();
  const auto vs_nullables = std::make_shared<ValueSegment<int32_t>>(
      tbb::concurrent_vector<int32_t>(column_nullables.begin(), column_nullables.end()));
  segments.push_back(vs_nullables);

  out_table->append_chunk(segments);

  return out_table;
}
Пример #5
0
std::shared_ptr<Table> create_reference_table(std::shared_ptr<Table> referenced_table, size_t num_rows,
                                              size_t num_columns) {
  const auto num_rows_per_chunk = num_rows / GENERATED_TABLE_NUM_CHUNKS;

  TableColumnDefinitions column_definitions;
  for (size_t column_idx = 0; column_idx < num_columns; ++column_idx) {
    column_definitions.emplace_back("c" + std::to_string(column_idx), DataType::Int);
  }
  auto table = std::make_shared<Table>(column_definitions, TableType::References);

  for (size_t row_idx = 0; row_idx < num_rows;) {
    const auto num_rows_in_this_chunk = std::min(num_rows_per_chunk, num_rows - row_idx);

    Segments segments;
    for (auto column_idx = ColumnID{0}; column_idx < num_columns; ++column_idx) {
      /**
       * By specifying a chunk size of num_rows * 0.2f for the referenced table, we're emulating a referenced table
       * of (num_rows * 0.2f) * REFERENCED_TABLE_CHUNK_COUNT rows - i.e. twice as many rows as the referencing table
       * we're creating. So when creating TWO referencing tables, there should be a fair amount of overlap.
       */
      auto pos_list = generate_pos_list(num_rows * 0.2f, num_rows_per_chunk);
      segments.push_back(std::make_shared<ReferenceSegment>(referenced_table, column_idx, pos_list));
    }
    table->append_chunk(segments);

    row_idx += num_rows_in_this_chunk;
  }

  return table;
}
Пример #6
0
Segments loadImages(QWidget* parent){
    QStringList fileNames=QFileDialog::getOpenFileNames
        (parent,QObject::tr("open file"),QString(),"*.bmp *.jpg *.png *.gif");

    Segments ret;

    foreach(const QString& fileName,fileNames){

        if(fileName.endsWith("gif")){
            FrameSegment gifSegment(fileName);
            if(gifSegment.isValid()){
                ret.append(gifSegment);
                continue;
            }

        }

        QImage image(fileName);
        if(!image.isNull()){
            ret.append(FrameSegment(image));
        }
    }

    return ret;

}
Пример #7
0
util::json::Array
ApiResponseGenerator<DataFacadeT>::ListViaIndices(const Segments &segment_list) const
{
    util::json::Array via_indices;
    via_indices.values.insert(via_indices.values.end(), segment_list.GetViaIndices().begin(),
                              segment_list.GetViaIndices().end());
    return via_indices;
}
Пример #8
0
util::json::Value ApiResponseGenerator<DataFacadeT>::GetGeometry(const bool return_encoded,
                                                                 const Segments &segments) const
{
    if (return_encoded)
        return polylineEncodeAsJSON(segments.Get());
    else
        return polylineUnencodedAsJSON(segments.Get());
}
 Section & unless( bool const skip )
 {
     if ( skip )
     {
         if ( segments.empty() )
             throw std::runtime_error( "Curve::unless() called, but no segment present" );
         segments.pop_back();
     }
     return *this;
 }
Пример #10
0
Segments ReceiveBuffer::popFrame()
{
    Segments frame;
    for( SourceBufferMap::iterator it = _sourceBuffers.begin();
         it != _sourceBuffers.end(); ++it )
    {
        SourceBuffer& buffer = it->second;
        frame.insert( frame.end(), buffer.segments.front().begin(),
                      buffer.segments.front().end( ));
        buffer.pop();
    }
    ++_lastFrameComplete;
    return frame;
}
Пример #11
0
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit 2.1.4 (beta) modified by pivanof
bool KawigiEdit_RunTest(int testNum, vector <int> p0, vector <int> p1, bool hasAnswer, string p2) {
    cout << "Test " << testNum << ": [" << "{";
    for (int i = 0; int(p0.size()) > i; ++i) {
        if (i > 0) {
            cout << ",";
        }
        cout << p0[i];
    }
    cout << "}" << "," << "{";
    for (int i = 0; int(p1.size()) > i; ++i) {
        if (i > 0) {
            cout << ",";
        }
        cout << p1[i];
    }
    cout << "}";
    cout << "]" << endl;
    Segments *obj;
    string answer;
    obj = new Segments();
    clock_t startTime = clock();
    answer = obj->intersection(p0, p1);
    clock_t endTime = clock();
    delete obj;
    bool res;
    res = true;
    cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
    if (hasAnswer) {
        cout << "Desired answer:" << endl;
        cout << "\t" << "\"" << p2 << "\"" << endl;
    }
    cout << "Your answer:" << endl;
    cout << "\t" << "\"" << answer << "\"" << endl;
    if (hasAnswer) {
        res = answer == p2;
    }
    if (!res) {
        cout << "DOESN'T MATCH!!!!" << endl;
    } else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
        cout << "FAIL the timeout" << endl;
        res = false;
    } else if (hasAnswer) {
        cout << "Match :-)" << endl;
    } else {
        cout << "OK, but is it right?" << endl;
    }
    cout << "" << endl;
    return res;
}
Пример #12
0
bool CSGTree::intersect(const ray& r, isect& i) const{
	if (!root)return false;
	Segments inters = root->intersectLocal(r);
	SegmentPoint sp;
	if(!inters.firstPositive(sp))return false;
	i.t = sp.t;
	if (sp.isRight){//right - out
		if (sp.normal*r.getDirection() > RAY_EPSILON)i.N = sp.normal;
		else i.N = -sp.normal;
	}
	else {//left - in
		if (sp.normal*r.getDirection() > RAY_EPSILON)i.N = -sp.normal;
		else i.N = sp.normal;
	}
	return true;
}
Пример #13
0
util::json::Object
ApiResponseGenerator<DataFacadeT>::SummarizeRoute(const InternalRouteResult &raw_route,
                                                  const Segments &segment_list) const
{
    util::json::Object json_route_summary;
    if (!raw_route.segment_end_coordinates.empty())
    {
        const auto start_name_id = raw_route.segment_end_coordinates.front().source_phantom.name_id;
        json_route_summary.values["start_point"] = facade->get_name_for_id(start_name_id);
        const auto destination_name_id =
            raw_route.segment_end_coordinates.back().target_phantom.name_id;
        json_route_summary.values["end_point"] = facade->get_name_for_id(destination_name_id);
    }
    json_route_summary.values["total_time"] = segment_list.GetDuration();
    json_route_summary.values["total_distance"] = segment_list.GetDistance();
    return json_route_summary;
}
void OpenCvDetector::detect(const Segments& segments, Labels& labels, Confidences& confidences)
{
    cv::Mat featureMatrix = calculateFeatureMatrix(segments);

    for(size_t i = 0; i < segments.size(); i++) {
        // Implemented by the derived class.
        classifyFeatureVector(featureMatrix.row(i), labels[i], confidences[i]);
    }
}
Пример #15
0
std::shared_ptr<AbstractTask> IndexScan::_create_job_and_schedule(const ChunkID chunk_id, std::mutex& output_mutex) {
  auto job_task = std::make_shared<JobTask>([=, &output_mutex]() {
    const auto matches_out = std::make_shared<PosList>(_scan_chunk(chunk_id));

    // The output chunk is allocated on the same NUMA node as the input chunk.
    const auto chunk = _in_table->get_chunk(chunk_id);
    Segments segments;

    for (ColumnID column_id{0u}; column_id < _in_table->column_count(); ++column_id) {
      auto ref_segment_out = std::make_shared<ReferenceSegment>(_in_table, column_id, matches_out);
      segments.push_back(ref_segment_out);
    }

    std::lock_guard<std::mutex> lock(output_mutex);
    _out_table->append_chunk(segments, nullptr, chunk->get_allocator());
  });

  job_task->schedule();
  return job_task;
}
Пример #16
0
static DictEntry* ParseKeyValues(const char* buff) {
  size_t length;
  const char* pbuff = UTF8Util::FindNextInline(buff, '\t');
  if (UTF8Util::IsLineEndingOrFileEnding(*pbuff)) {
    throw InvalidFormat("Invalid text dictionary");
  }
  length = pbuff - buff;
  string key = UTF8Util::FromSubstr(buff, length);
  Segments values;
  while (!UTF8Util::IsLineEndingOrFileEnding(*pbuff)) {
    buff = pbuff = UTF8Util::NextChar(pbuff);
    pbuff = UTF8Util::FindNextInline(buff, ' ');
    length = pbuff - buff;
    const string& value = UTF8Util::FromSubstr(buff, length);
    values.AddSegment(value);
  }
  if (values.Length() == 0) {
    throw InvalidFormat("Invalid text dictionary: No value in an item");
  } else if (values.Length() == 1) {
    return new DictEntry(key, values.At(0));
  } else {
    return new MultiValueDictEntry(key, values);
  }
}
Пример #17
0
std::vector<detail::Segment>
ApiResponseGenerator<DataFacadeT>::BuildRouteSegments(const Segments &segment_list) const
{
    std::vector<detail::Segment> result;
    for (const auto &segment : segment_list.Get())
    {
        const auto current_turn = segment.turn_instruction;
        if (extractor::isTurnNecessary(current_turn) &&
            (extractor::TurnInstruction::EnterRoundAbout != current_turn))
        {

            detail::Segment seg = {segment.name_id,
                                   static_cast<int32_t>(segment.length),
                                   static_cast<std::size_t>(result.size())};
            result.emplace_back(std::move(seg));
        }
    }
    return result;
}
 Section & add( T const & segment )
 {
     segments.push_back( SegmentPtr( boost::make_shared<T>( segment ) ) );
     return *this;
 }
Пример #19
0
int main(int argc, const char* argv[])
{
	/*
	 *  Build 48 Index with Links
	 */


	// Load Circuit
    Experiment experiment;
    experiment.open(blue_config_filename);
    Microcircuit & microcircuit = experiment.microcircuit();
    const Targets & targets = experiment.targets();
    const Cell_Target target = targets.cell_target("Column");
    microcircuit.load(target, NEURONS | MORPHOLOGIES);

    //Make Neuron Rtrees
    ISpatialIndex *neuronTrees[MORPHOLOGIES_COUNT];
    string *morphologyLabels[MORPHOLOGIES_COUNT];

    int cm=0;
    Morphologies & myMorphologies = microcircuit.morphologies();
    Morphologies::iterator myMorphologiesEnd = myMorphologies.end();
      for (Morphologies::iterator i = myMorphologies.begin(); i != myMorphologiesEnd; ++i)
      {
    	  morphologyLabels[cm] = i->label();
    	  neuronTrees[cm] = RTree::createNewRTree (createNewMemoryStorageManager(), 0.7, 127, 127, 3,RTree::RV_RSTAR,indexIdentifier);
    	  cm++;
      }

    Neurons & myNeurons = microcircuit.neurons();
    Neurons::iterator myNeuronsEnd = myNeurons.end();
    for (Neurons::iterator i = myNeurons.begin(); i != myNeuronsEnd; ++i)
    {
    	cm=0;
    	for (cm=0;cm<MORPHOLOGIES_COUNT;cm++)
    		if (strcmp(i->morphology().label(),morphologyLabels[cm])==0) break;

    	Transform_3D<Micron> trafo = i->global_transform();
    	Sections mySections = i->morphology().all_sections();
    	Sections::iterator mySectionsEnd = mySections.end();
    	for (Sections::iterator s = mySections.begin(); s != mySectionsEnd; ++s)
    	    {
    		 Segments segments = s->segments();
    		 Segments::const_iterator segments_end = segments.end();
    		 for (Segments::const_iterator j = segments.begin(); j != segments_end ; ++j)
    		     {
     			 vect plow, phigh;
     			 get_segment_mbr (*j, trafo, &plow, &phigh);
     			 SpatialIndex::Region mbr = SpatialIndex::Region(plow.data(),phigh.data(),3);

     			 std::stringstream strStream;
     			 strStream << i->gid() <<"-"<< s->id()<< "-" << j->id();
     			 neuronTrees[cm]->insertData (strStream.str().length(), (byte*)(strStream.str().c_str()), mbr, segmentid);
    		     }
    	    }
    }

    // Make Morphology Rtrees
    Morphologies & myMorphologies = microcircuit.morphologies();
    Morphologies::iterator myMorphologiesEnd = myMorphologies.end();
      for (Morphologies::iterator i = myMorphologies.begin(); i != myMorphologiesEnd; ++i)
      {
      	cout << "Indexing Morphology: " << i->label();
      	string baseName = i->label();
        IStorageManager* diskfile = StorageManager::createNewDiskStorageManager(baseName, 4096);
        ISpatialIndex *tree = RTree::createNewRTree (*diskfile, 0.7, 127, 127, 3,RTree::RV_RSTAR,indexIdentifier);
        indexIdentifier++; segmentid=0;

      	Sections mySections = i->all_sections();
      	Sections::iterator mySectionsEnd = mySections.end();
      	for (Sections::iterator s = mySections.begin(); s != mySectionsEnd; ++s)
      	{
            Segments segments = s->segments();
      		Segments::const_iterator segments_end = segments.end();
      		for (Segments::const_iterator j = segments.begin(); j != segments_end ; ++j)
      		{

      			Box<bbp::Micron> Mbr = AABBCylinder::calculateAABBForCylinder(j->begin().center(),
      								  j->begin().radius(),j->end().center(),j->begin().radius());

      			vect plow, phigh;

      			plow[0] = Mbr.center().x() - Mbr.dimensions().x() / 2;
      			phigh[0] = Mbr.center().x() + Mbr.dimensions().x() / 2;
      			plow[1] = Mbr.center().y() - Mbr.dimensions().y() / 2;
      			phigh[1] = Mbr.center().y() + Mbr.dimensions().y() / 2;
      			plow[2] = Mbr.center().z() - Mbr.dimensions().z() / 2;
      			phigh[2] = Mbr.center().z() + Mbr.dimensions().z() / 2;

				SpatialIndex::Region mbr = SpatialIndex::Region(plow.data(),phigh.data(),3);

      			std::stringstream strStream;
      			strStream << s->id()<< "-" << j->id();

      			tree->insertData (strStream.str().length(), (byte*)(strStream.str().c_str()), mbr, segmentid);
      			segmentid++;
      		}
      	}
      	cout << ".. Total Segments: " << segmentid << "\n";
        tree->~ISpatialIndex();
        diskfile->~IStorageManager();
      }


    // PRELOAD the Trees amd Neuron Morphology Mapping


    ISpatialIndex *neurons[NEURONS_COUNT];
    global_transformer *transforms[NEURONS_COUNT];

    int cm=0;
    int cn=0;
    string baseName = "";
    Morphologies & myMorphologies = microcircuit.morphologies();
    Neurons & myNeurons = microcircuit.neurons();

    cout << "PreLoading Mappings \n";
    Morphologies::iterator myMorphologiesEnd = myMorphologies.end();
      for (Morphologies::iterator m = myMorphologies.begin(); m != myMorphologiesEnd; ++m)
      {
    	  baseName = m->label();
    	  m->
          IStorageManager* diskfile = StorageManager::loadDiskStorageManager(baseName);
          trees[cm] = RTree::loadRTree(*diskfile, 1);

          std::cout << "Checking R-tree structure... ";
          if (!trees[cm]->isIndexValid()) std::cerr << "R-tree internal checks failed!\n"; else std::cout << "OK\n";
          IStatistics * tree_stats;
          trees[cm]->getStatistics (&tree_stats);
          cout << *tree_stats;

          Neurons::iterator myNeuronsEnd = myNeurons.end();
          for (Neurons::iterator n = myNeurons.begin(); n != myNeuronsEnd; ++n)
              {
        	  if (strcmp(n->morphology().label().c_str(),m->label().c_str())==0)
        		  {
        		  transforms[cn] = n->global_transform().inverse();
        		  neurons[cn] = trees[cm];
        		  }
        	  cn++;
        	  if (cn>=NEURONS_COUNT) break;
              }
          cn=0;cm++;
      }




	/*
	 *  Query the Index
	 */








}
 void reset()
 {
     for ( Segments::const_iterator pos = segments.begin(); pos != segments.end(); ++pos )
         (*pos)->reset();
 }
 void apply( ScannerPtr scanner )
 {
     for ( Segments::const_iterator pos = segments.begin(); pos != segments.end(); ++pos )
         (*pos)->apply( scanner );
 }
Пример #22
0
int main() {
    // profiler
    Profiler profiler;
    profiler.start((char*)"main");

    // random generate 1d vector
    // assign maximum size =>
    const int max = 100;
    vector<double> main_1d_points(max);

    srand(time(NULL));
    for (int i = 0; i < max; i++) {
        main_1d_points[i] = rand() % 100;
    };

    // transform to Points, then sorting
    Points main_points;
    main_points.parse_1d_points_from(main_1d_points);
    main_points.sort_by_y();

    main_points.dump();

    Points center;
    center.create_center_from(main_points);

    center.dump();

    // create a set of points
    Point a, b, c, d, e, f, g, h;
    a.set_point( 0,  0);
    b.set_point( 5,  0);
    c.set_point( 5,  5);
    d.set_point( 0,  5);
    e.set_point(-5,  5);
    f.set_point(-5,  0);
    g.set_point(-5, -5);
    h.set_point( 0, -5);

    // form each segment
    Segment ab, bc, cd, de, ef, fg, gh, ha;
    ab.set_segment(&a, &b);
    bc.set_segment(&b, &c);
    cd.set_segment(&c, &d);
    de.set_segment(&d, &e);
    ef.set_segment(&e, &f);
    fg.set_segment(&f, &g);
    gh.set_segment(&g, &h);
    ha.set_segment(&h, &a);

    // try segment copy
    Segment copy_test;
    copy_test.copy(ab);
    printf("copy segment:\n");
    copy_test.dump();
    copy_test.free();

    // form a set of segments
    Segments all;
    all.append(&ab);
    all.append(&bc);
    all.append(&cd);
    all.append(&de);
    all.append(&ef);
    all.append(&fg);
    all.append(&gh);
    all.append(&ha);

    all.dump();

    // set the set of segments to a polygon
    // and test polygon function
    Polygon polygon1;
    polygon1.set_polygon(&all);
    polygon1.dump();
    printf("(%d) segments in this polygon\n", polygon1.get_segment_number());
    printf("center point of this polygon is (%f, %f)\n",
            polygon1.get_center().get_gx(),
            polygon1.get_center().get_gy());

    // set the set of segments to another polygon
    // yet, they reference the same segments set
    printf("\nthis is polygon2\n");
    Polygon polygon2;
    polygon2.set_polygon(&all);
    polygon2.dump();

    // try polygon copy
    printf("\nthis is polygon3\n");
    Polygon polygon3;
    polygon3.copy(polygon2);
    polygon3.dump();

    // append the polygons into a set of polygons
    Polygons polygons;
    polygons.append(&polygon1);
    polygons.append(&polygon3);

    // set segment function and loop all polygons set
    ktSetSegmentFunction(grow_45_degree);
    ktLoopSegment(&polygons);

    polygons.dump();

    // try loop segment without function set
    ktLoopSegment(&polygons);

    polygon3.free();
    profiler.end();

    return 0;
}
Пример #23
0
size_t TempSpace::allocateBatch(size_t count, size_t minSize, size_t maxSize, Segments& segments)
{
	// adjust passed chunk size to amount of free memory we have and number
	// of runs still not allocated.
	offset_t freeMem = 0;

	for (bool found = freeSegments.getFirst(); found; found = freeSegments.getNext())
		freeMem += freeSegments.current().size;

	freeMem = MIN(freeMem / count, maxSize);
	freeMem = MAX(freeMem, minSize);
	freeMem = MIN(freeMem, minBlockSize);
	freeMem &= ~(FB_ALIGNMENT - 1);

	bool is_positioned = freeSegments.getFirst();
	while (segments.getCount() < count && is_positioned)
	{
		Segment* freeSpace = &freeSegments.current();
		offset_t freeSeek = freeSpace->position;
		const offset_t freeEnd = freeSpace->position + freeSpace->size;

		UCHAR* const mem = findMemory(freeSeek, freeEnd, freeMem);

		if (mem)
		{
			fb_assert(freeSeek + freeMem <= freeEnd);
#ifdef DEV_BUILD
			offset_t seek1 = freeSeek;
			UCHAR* const p = findMemory(seek1, freeEnd, freeMem);
			fb_assert(p == mem);
			fb_assert(seek1 == freeSeek);
#endif
			if (freeSeek != freeSpace->position)
			{
				const offset_t skip_size = freeSeek - freeSpace->position;
				const Segment skip_space(freeSpace->position, skip_size);

				freeSpace->position += skip_size;
				freeSpace->size -= skip_size;
				fb_assert(freeSpace->size != 0);

				if (!freeSegments.add(skip_space))
					fb_assert(false);

				if (!freeSegments.locate(skip_space.position + skip_size))
					fb_assert(false);

				freeSpace = &freeSegments.current();
			}

			SegmentInMemory seg;
			seg.memory = mem;
			seg.position = freeSeek;
			seg.size = freeMem;
			segments.add(seg);

			freeSpace->position += freeMem;
			freeSpace->size -= freeMem;

			if (!freeSpace->size)
			{
				is_positioned = freeSegments.fastRemove();
			}
		}
		else
		{
			is_positioned = freeSegments.getNext();
		}
	}

	return segments.getCount();
}
Пример #24
0
void MainWindow::rerenderBox()
{
    m_pixmap.fill(Qt::white);

    QPainter painter(&m_pixmap);
    painter.setRenderHint(QPainter::Antialiasing);

    painter.setPen(QPen(Qt::black, 3));
    painter.drawRect(m_boxOffset, m_boxOffset, m_boxParameters.boxSize.x, m_boxParameters.boxSize.y);

    const Segments trace = getTrace();
    if (trace.empty())
    {
        return;
    }

    QPen penBuffer(QColor::fromRgb(1, 0, 0), 2, Qt::SolidLine);
    double redColorBuffer = m_boxParameters.initialRedColorValue;

    Hit firstLeftHit;
    Hit firstBottomHit;
    Hit firstRightHit;
    Hit firstTopHit;
    unsigned char seqNum = 0;

    for (Segments::const_iterator f = trace.cbegin(); f != trace.cend(); ++f)
    {
        if (f != trace.cend() - 1)
        {
            penBuffer.setColor(QColor::fromRgb((int)redColorBuffer, 0, 0));
            redColorBuffer = max(min(255.0, redColorBuffer * m_boxParameters.redColorMultiplier), 0.0);

            painter.setPen(penBuffer);
            painter.drawLine(QPointF(m_boxOffset + f->x, m_boxOffset + f->y),
                             QPointF(m_boxOffset + (f+1)->x, m_boxOffset + (f+1)->y));
        }

        if (f != trace.cbegin())
        {
            const QPointF srcPoint = QPointF(f->x, f->y);

            if (!firstLeftHit.found && abs(f->x) < m_eps)
            {
                firstLeftHit = Hit(srcPoint, seqNum++);
            }
            else if (!firstRightHit.found && abs(m_boxParameters.boxSize.x - f->x) < m_eps)
            {
                firstRightHit= Hit(srcPoint, seqNum++);
            }
            else if (!firstTopHit.found && abs(f->y) < m_eps)
            {
                firstTopHit = Hit(srcPoint, seqNum++);
            }
            else if (!firstBottomHit.found && abs(m_boxParameters.boxSize.y - f->y) < m_eps)
            {
                firstBottomHit = Hit(srcPoint, seqNum++);
            }
        }
    }

    painter.setPen(QPen(Qt::black, 4));

    const QPointF boxOffset(m_boxOffset, m_boxOffset);
    const QPointF labelXOffset(m_boxOffset / 2, 0);
    const QPointF labelYOffset(0, m_boxOffset / 2);

    if (firstLeftHit.found)
    {
        painter.drawText(boxOffset + firstLeftHit.point - labelXOffset,
                         QString::number(firstLeftHit.seqNumber));
    }

    if (firstBottomHit.found)
    {
        painter.drawText(boxOffset + firstBottomHit.point + labelYOffset,
                         QString::number(firstBottomHit.seqNumber));
    }

    if (firstRightHit.found)
    {
        painter.drawText(boxOffset + firstRightHit.point + labelXOffset,
                         QString::number(firstRightHit.seqNumber));
    }

    if (firstTopHit.found)
    {
        painter.drawText(boxOffset + firstTopHit.point - labelYOffset,
                         QString::number(firstTopHit.seqNumber));
    }

    repaint();
}