// Writes a histogram to a file readable by gnuplot.
 void Histogram::write(string path) const {                
     std::fstream fid(path, std::ios::out);
     double x(_x0 + 0.5*_dx);
     for (auto h=histogram.begin(); h!=histogram.end(); ++h, x+=_dx) {
         fid << x << "\t" << *h << "\n";
     }
 }
Example #2
0
size_t OnlineSession::updateRead(string filename, byte*& file, size_t bytesToAdd, double& diskTime){
	
	this->filename = filename;
	fileID fid(filename);
	this->fid = fid;

	byte lowerFid[LOWERFID_SIZE];
	this->fid.getLowerID(lowerFid);
//	printhex(lowerFid, LOWERFID_SIZE, "LOWER FID");

	PRSubset prSubset(SIZE_MIN, filename);
	this->prSubset = prSubset;

	firstDAccess(filename, diskTime);
	b_index_t numBlocksAfterUpdate = (b_index_t)(ceil((double)(filesize+bytesToAdd)/(double)MAX_BLOCK_DATA_SIZE));
	numBlocks = max(numBlocks, numBlocksAfterUpdate);
	if(numBlocks*BLOW_UP > SIZE_MIN){
		secondDAccess(filename, diskTime);
	}
	else
		numBlocks = SIZE_MIN;

	file = new byte[filesize];
	memset(file, 0, filesize);
	for(int i = 1; i < fileBlocks.size(); i++){
		byte block[BLOCK_SIZE];
		memset(block, 0, BLOCK_SIZE);
		fileBlocks[i].getDecrypted(block);
		memcpy(&file[(i-1)*MAX_BLOCK_DATA_SIZE], block, fileBlocks[i].getDataSize());
	}

	return filesize;
}
    FunctionTacValue(TacFunctionPtr f) : function(f)
    {
        isFunction = true;

        IdentifierPtr fid(new Identifier);
        fid->id = Token(f->name, -1, -1);

        id = fid;
    }
QMessageFolderId::QMessageFolderId(const QString& id)
    : d_ptr(0)
{
    QMailFolderId fid(QmfHelpers::stripIdentifierPrefix(id).toULongLong());
    if (fid.isValid()) {
        d_ptr = new QMessageFolderIdPrivate;
        d_ptr->_id = fid;
    }
}
Example #5
0
void ServiceManagement::testMethod() {
    ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)\n")));
    PeerMap map;
    UUIDPtr pid(UUID::generateUUID());
    UUIDPtr pid2(UUID::generateUUID());
    UUIDPtr fid(UUID::generateUUID());
    UUIDPtr sid(UUID::generateUUID());
    UUIDPtr iid1(UUID::generateUUID());
    UUIDPtr iid2(UUID::generateUUID());
    
    SAPInfoPtr meshSAP;
    SAPInfoPtr ftSAP;
    SAPInfoPtr discoverySAP;
    
    
    PeerInfoPtr peerPtr(new PeerInfoEx(pid,fid,meshSAP,discoverySAP,ftSAP));

    map.addPeer(peerPtr);

    try{
        PeerInfoPtr pi;
        map.getPeerInfo(pid,pi);
    }catch(PeerException& ex){
      ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)ex=%s\n"),ex.toString().c_str()));
    }

    try{
        PeerInfoPtr pi;
        map.getPeerInfo(pid2,pi);
    }catch(PeerException& ex){
        ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)ex2=%s\n"),ex.toString().c_str()));
    }



    peerPtr->addServiceInstance(sid,iid1);
    
    ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)Output:\n%s\n"),peerPtr->toString().c_str()));

    list<UUIDPtr> l;
    peerPtr->getInstancesOfService(sid,l);    
    ListHelper<UUIDPtr>::printSmartPtrList(l);
    
    ServiceInstanceInfoPtr i;
    peerPtr->getInstanceOfService(sid,l.front(),i);
    ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)=====%s\n"),i->toString().c_str()));

    //bool ret = peerPtr->removeService(sid);
    //ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%t|%T)after remove = %d\n",ret);
    //delete l;
    CPPUNIT_ASSERT(true);
}
Example #6
0
void OnlineSession::updateWithInsecureAppend(string filename, byte*& file, double& diskTime){
	this->filename = filename;
	fileID fid(filename);
	this->fid = fid;

	byte lowerFid[LOWERFID_SIZE];
	this->fid.getLowerID(lowerFid);

	PRSubset prSubset(SIZE_MIN, filename);
	this->prSubset = prSubset;

	updateAccess(filename, diskTime);
}
Example #7
0
/*!
 * \example SerialExample/ex1.cpp
 *
 * A simple example of MINRES() usage without preconditioner.
 */
int main()
{
	//(1) Define the size of the problem we want to solve
	int size(1000);
	//(2) Define the linear operator "op" we want to solve.
	SimpleOperator op(size);
    //(3) Generate a random linear system
    op.Randomize(0);
	//(3) Define the exact solution (at random)
	SimpleVector sol(size);
	sol.Randomize( 1 );

	//(4) Define the "rhs" as "rhs = op*sol"
	SimpleVector rhs(size);
	op.Apply(sol, rhs);
	double rhsNorm( sqrt(InnerProduct(rhs,rhs)) );
	std::cout << "|| rhs || = " << rhsNorm << "\n";

	//(5) We don't use any preconditioner. Let prec be a null pointer.
	Preconditioner * prec = NULL;

	//(6) Use an identically zero initial guess
	SimpleVector x(size);
	x = 0;

	//(7) Set the minres parameters
	double shift(0);
	int max_iter(10000);
	double tol(1e-6);
	bool show(false);

	//(8) Solve the problem with minres
	MINRES(op, x, rhs, prec, shift, max_iter, tol, show);

	//(9) Compute the error || x_ex - x_minres ||_2
	subtract(x, sol, x);
	double err2 = InnerProduct(x,x);
	std::cout<< "|| x_ex - x_n || = " << sqrt(err2) << "\n";

	std::ofstream fid("ex3.m");
	op.Print(fid);
	fid<< "rhs = [";
	for(int i(0); i<size-1; ++i)
		fid<<rhs[i] <<"; ";
	fid<<rhs[size-1] <<"]; \n";
	fid<<"[ x, istop, itn, rnorm, Arnorm, Anorm, Acond, ynorm ] = minres(Op, rhs, [], 0, true, false, 100, 1e-6);\n";
    

	return 0;
}
Example #8
0
/******************************************************************************
    TerSetFrameTextDist:
    Set the minimum distance to maintain between text and the frame border.
******************************************************************************/
BOOL WINAPI _export TerSetFrameTextDist(HWND hWnd, int ParaFID,int dist)
{
    PTERWND w;

    if (NULL==(w=GetWindowPointer(hWnd))) return FALSE;  // get the pointer to window data

    if (ParaFID<=0) ParaFID=fid(CurLine);
    if (ParaFID<=0 || ParaFID>=TotalParaFrames || !ParaFrame[ParaFID].InUse) return false;

    ParaFrame[ParaFID].DistFromText=dist;

    RequestPagination(w,true);

    return TRUE;
}
Example #9
0
void write_to_file(int nx, int ny, double* data) {
    {
        FILE* output = fopen("output.bin", "w");
        fwrite(data, sizeof(double), nx * ny, output);
        fclose(output);
    }

    std::ofstream fid("output.bov");
    fid << "TIME: 0.0" << std::endl;
    fid << "DATA_FILE: output.bin" << std::endl;
    fid << "DATA_SIZE: " << nx << " " << ny << " 1" << std::endl;;
    fid << "DATA_FORMAT: DOUBLE" << std::endl;
    fid << "VARIABLE: phi" << std::endl;
    fid << "DATA_ENDIAN: LITTLE" << std::endl;
    fid << "CENTERING: nodal" << std::endl;
    fid << "BRICK_SIZE: 1.0 1.0 1.0" << std::endl;
}
Example #10
0
unsigned long int MP_Var_Array_c<TYPE>::save_ui_to_text( const char* fName ) {

  //FILE *fid;
  ofstream fid(fName);
  unsigned long int i;
  //if ( (fid = fopen( fName, "w" )) == NULL ) {
  if(!fid.is_open()){
    mp_error_msg( "MP_Var_Array_c::save(fName)",
		  "Failed to open the file [%s] for writing.\n",
		  fName );
    return( 0 );
  }
  for ( i = 0 ; i< nElem; i++) //fprintf (fid, "Iteration %lu Source [%lu]\n",i, elem[i]);
    fid << "Iteration " << i << " Source [" << elem[i] << "]\n";
  //fclose( fid );
  fid.close();
  return( i );
}
Example #11
0
void lemur::parse::KeyfileDocMgr::writeTOC() {
  if (_readOnly) return;
  string n = IDname + BT_TOC;
  ofstream toc(n.c_str());
  toc << "FILE_LOOKUP " << IDname << BT_LOOKUP << endl;
  toc << "POS_LOOKUP " << IDname << BT_POSITIONS << endl;
  toc << "PARSE_MODE " <<  pm << endl;
  toc << "FILE_IDS " << IDname << BT_FID << endl;
  toc << "NUM_FILES " << sources.size() << endl;
  toc << "NUM_DOCS " << numdocs << endl;
  toc.close();

  n = IDname + BT_FID;
  ofstream fid(n.c_str());
  for (int i = 0; i < sources.size(); i++) {
    fid << i << " " << sources[i] << endl;
  }
  fid.close();
}
 void onRenderRasterCompleted(const RenderData &renderData) override {
   TRasterP outputRaster = renderData.m_rasA;
   TRasterImageP img(outputRaster->clone());
   img->setDpi(m_cameraDpi.x, m_cameraDpi.y);
   if (m_outputImage)
     m_outputImage->setImg(img);
   else if (m_outputLevel) {
     std::vector<std::string> ids;
     for (int i = 0; i < (int)renderData.m_frames.size(); i++) {
       TFrameId fid((int)(renderData.m_frames[i]) + 1);
       m_outputLevel->setFrame(fid, img);
       std::string id = m_outputLevel->getSimpleLevel()->getImageId(fid);
       ids.push_back(id);
     }
     img = TImageP();
     for (int i = 0; i < (int)ids.size(); i++)
       TImageCache::instance()->compress(ids[i]);
   }
 }
Example #13
0
    // constructors
    LoHighCamera::LoHighCamera (Pvl &lab) : FramingCamera(lab) {
      // Get the Instrument label information needed to define the camera for this frame
      PvlGroup inst = lab.FindGroup ("Instrument",Pvl::Traverse);
      iString spacecraft = (string)inst["SpacecraftName"];
      iString instId = (string)inst["InstrumentId"];

      // Turn off the aberration corrections for the instrument position object
        InstrumentPosition()->SetAberrationCorrection("NONE");

        // Get the camera characteristics
      SetFocalLength ();
      SetPixelPitch ();

      // Get the start time in et
      string stime = inst["StartTime"];
      double time; 
      str2et_c(stime.c_str(),&time);

      // Setup focal plane map

      LoCameraFiducialMap fid( inst, NaifIkCode());

      // Setup detector map
      new CameraDetectorMap(this);

      // Setup focalplane map
      CameraFocalPlaneMap *focalMap = new CameraFocalPlaneMap(this,NaifIkCode());
      // Try (0.,0.)
      focalMap->SetDetectorOrigin(0.0,0.0);

      // Setup distortion map
      LoHighDistortionMap *distortionMap = new LoHighDistortionMap(this);
      distortionMap->SetDistortion(NaifIkCode());
      // Setup the ground and sky map
      new CameraGroundMap(this);
      new CameraSkyMap(this);

      SetEphemerisTime(time);
      LoadCache();
    }
void TXshSoundTextColumn::createSoundTextLevel(int row, QList<QString> textList)
{
	TXshSoundTextLevel *level = new TXshSoundTextLevel();
	level->setType(SND_TXT_XSHLEVEL);
	int i = 0;
	TXshCell cell;
	for (i; i < textList.size(); i++, row++) {
		QString str = textList.at(i);
		QString precStr = (i > 0) ? level->getFrameText(i - 1) : QString();
		if (str == QString("<none>")) {
			if (i > 0) {
				setCell(row, cell);
				continue;
			} else
				str = QString();
		}
		level->setFrameText(i, str);
		TFrameId fid(i + 1);
		cell = TXshCell(level, fid);
		setCell(row, cell);
	}
}
QScriptValue foo(QScriptContext *ctx, QScriptEngine *eng)
{
	int r = ctx->argument(0).toInteger();
	int c = ctx->argument(1).toInteger();
	QScriptValue levelArg = ctx->argument(2);

	ScriptWrapper::Level *level = dynamic_cast<ScriptWrapper::Level *>(levelArg.toQObject());
	if (level) {
		TXshSimpleLevel *sl = level->getLevel();
		if (!sl)
			return QScriptValue(0);

		TFrameId fid(1);
		if (!sl->isFid(fid))
			sl->setFrame(fid, sl->createEmptyFrame());

		ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene();
		scene->getXsheet()->setCell(r, c, TXshCell(sl, fid));
		TApp::instance()->getCurrentXsheet()->notifyXsheetChanged();
	}

	return QScriptValue(1);
}
Example #16
0
        bool CSmartFactory<FunctionIdEnum, MessageTypeEnum, StructIdEnum>::attachSchema(NsSmartDeviceLink::NsSmartObjects::SmartObject &object)
        {
            if(false == object.keyExists(strings::S_PARAMS)) return false;
            if(false == object[strings::S_PARAMS].keyExists(strings::S_MESSAGE_TYPE)) return false;
            if(false == object[strings::S_PARAMS].keyExists(strings::S_FUNCTION_ID)) return false;

            MessageTypeEnum msgtype((MessageTypeEnum)(int)object[strings::S_PARAMS][strings::S_MESSAGE_TYPE]);
            FunctionIdEnum fid((FunctionIdEnum)(int)object[strings::S_PARAMS][strings::S_FUNCTION_ID]);

            SmartSchemaKey<FunctionIdEnum, MessageTypeEnum> key(fid, msgtype);

            typename FuncionsSchemesMap::iterator schemaIterator = functions_schemes_.find(key);

            if(schemaIterator == functions_schemes_.end())
            {
                // Schema was not found
                return false;
            }

            object.setSchema(schemaIterator->second);
            schemaIterator->second.applySchema(object);

            return true;
        }
Example #17
0
void TarWriter::writeFile(String path, FileStatus *status)
{
    Ref<StringList> headerFields = StringList::create();

    off_t contentSize = status->size();
    if (status->type() != File::Regular) contentSize = 0;

    if (status->type() == File::Directory) {
        if (path->count() > 0) {
            if (path->at(path->count() - 1) != '/') path = path + "/";
        }
    }

    String pathField(99, '\0');
    if (status == longPathStatus_ || status == longLinkStatus_)
        *pathField = *String("././@LongLink");
    else
        *pathField = *path;
    headerFields->append(pathField);
    headerFields->append(zero_);

    headerFields->append(oct(status->mode(), 7));
    headerFields->append(zero_);
    headerFields->append(oct(status->ownerId(), 7));
    headerFields->append(zero_);
    headerFields->append(oct(status->groupId(), 7));
    headerFields->append(zero_);
    if (status == longPathStatus_ || status == longLinkStatus_)
        headerFields->append(oct(path->count() + 1, 11));
    else
        headerFields->append(oct(contentSize, 11));
    headerFields->append(zero_);
    headerFields->append(oct(status->st_mtime, 11));
    headerFields->append(zero_);

    String checksumField(6, '0');
    headerFields->append(checksumField);
    headerFields->append(String("\0 ", 2));

    String typeField, linkTarget;
    if (status == longLinkStatus_ )                   typeField = "K";
    else if (status == longPathStatus_)               typeField = "L";
    else {
             if (status->type() == File::Regular)     ;
        else if (status->type() == File::Directory)   typeField = "5";
        else if (status->type() == File::Symlink)     typeField = "2";
        else if (status->type() == File::CharDevice)  typeField = "3";
        else if (status->type() == File::BlockDevice) typeField = "4";
        else if (status->type() == File::Fifo)        typeField = "6";
        if (status->numberOfHardLinks() > 1) {
            FileId fid(status);
            if (hardLinks_->lookup(fid, &linkTarget)) typeField = "1";
            else hardLinks_->insert(fid, path);
        }
        else if (status->type() == File::Symlink) {
            linkTarget = File::readlink(path);
        }
        if (typeField == "")                          typeField = "0";
        if (typeField != "0") contentSize = 0;
    }
    headerFields->append(typeField);

    String linkField(99, '\0');
    *linkField = *linkTarget;
    headerFields->append(linkField);
    headerFields->append(zero_);

    String gnuMagicField("ustar  ");
    headerFields->append(gnuMagicField);
    headerFields->append(zero_);

    String userField(31, '\0');
    *userField = *User::lookup(status->ownerId())->name();
    headerFields->append(userField);
    headerFields->append(zero_);

    String groupField(31, '\0');
    *groupField = *Group::lookup(status->groupId())->name();
    headerFields->append(groupField);
    headerFields->append(zero_);

    if (status != longPathStatus_ && status != longLinkStatus_) {
        if (path->count() > pathField->count()) writeFile(path, longPathStatus_);
        if (linkTarget->count() > linkField->count()) writeFile(linkTarget, longLinkStatus_);
    }

    String header = headerFields->join();
    FLUX_ASSERT(header->count() == 329);
    unsigned checksum = tarHeaderSum(header);
    *checksumField = *oct(checksum, 6);
    header = headerFields->join();
    sink_->write(header);
    writePadding(header->count());

    if (status == longPathStatus_ || status == longLinkStatus_) {
        sink_->write(path);
        sink_->write(zero_);
        writePadding(path->count() + 1);
    }
    else if (contentSize > 0) {
        File::open(path)->transfer(contentSize, sink_);
        writePadding(contentSize);
    }
}
Example #18
0
void test_Polygon(int &failed_test_count, int &disabled_test_count)
{

const std::string GROUP = "Polygon";
const double EQT = 1.0e-15;

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

{
    Test t(GROUP, "set_get_my_zone", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        Face *f = new Polygon;
        size_t expected = 7;
        f->set_my_zone(expected);
        size_t actual = f->get_my_zone();

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "set_get_my_id", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        Face *f = new Polygon;
        short int expected = 7;
        f->set_my_id(expected);
        short int actual = f->get_my_id();

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "ctor_check_my_zone", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        size_t mz = 6;
        short int mi = 9;
        Face *f = new Polygon(mz, mi);
        size_t expected = mz;
        size_t actual = f->get_my_zone();

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "ctor_check_my_id", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        size_t mz = 6;
        short int mi = 9;
        Face *f = new Polygon(mz, mi);
        short int expected = mi;
        short int actual = f->get_my_id();

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "size0", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        Face *f = new Polygon;
        size_t expected = 0;
        size_t actual = f->size();

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "size", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        Vector3d v(1.0, 2.0, 3.0);
        Node n0(3, v);
        Node n1(5, v, v);
        Face *f = new Polygon;
        f->add_node(n0.geti());
        f->add_node(n1.geti());
        size_t expected = 2;
        size_t actual = f->size();

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "is_curved", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        Grid g;
        Face *f = new Polygon;
        Vector3d v(1.0, 2.0, 3.0);
        Node n0(3, v);
        f->add_node(n0.geti());
        f->add_node(n0.geti());
        f->add_node(n0.geti());
        bool expected = false;
        bool actual = f->is_curved(g);

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "is_flat", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        Grid g;
        Face *f = new Polygon;
        Vector3d v(1.0, 2.0, 3.0);
        Node n0(3, v);
        f->add_node(n0.geti());
        f->add_node(n0.geti());
        f->add_node(n0.geti());
        bool expected = true;
        bool actual = f->is_flat(g);

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "get_node_id", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        Vector3d v(1.0, 2.0, 3.0);
        Node n0(3, v);
        Node n1(5, v, v);
        Face *f = new Polygon;
        f->add_node(n0.geti());
        f->add_node(n1.geti());
        size_t expected = 5;
        size_t actual = f->get_node(1);

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "get_node_id_out_of_range", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        Vector3d v(1.0, 2.0, 3.0);
        Node n0(3, v);
        Node n1(5, v, v);
        Face *f = new Polygon;
        f->add_node(n0.geti());
        f->add_node(n1.geti());
        std::string expected = "out of range exception";
        std::string actual = UNCAUGHT_EXCEPTION;
        try
        {
            size_t n = f->get_node(2);
            std::cout << n;
        }
        catch (const std::out_of_range &oor)
        {
            actual = "out of range exception";
        }

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "abs_diff", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        Face *f = new Polygon(3, 1);
        Face *g = new Polygon(4, 5);
        f->add_node(6);
        g->add_node(2);
        g->add_node(9);
        g->add_node(4);
        double expected = 37.0;
        double actual = f->abs_diff(*g);

        failed_test_count += t.check_equal_real_num(expected, actual, EQT);
        delete f;
        delete g;
    }
}

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

{
    Test t(GROUP, "to_string", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        Face *f = new Polygon(3, 1);
        f->add_node(98765);
        f->add_node(98766);
        f->add_node(98767);
        f->add_node(98768);
        f->add_node(98769);
        std::string expected = "Polygon\n          5\n";
        expected += "          3          1\n";
        expected += "      98765      98766      98767      98768      98769";
        expected += "\n          neighbors          0";
        std::string actual = f->to_string();

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "ctor0", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        Face *expected = new Polygon(0, -2);
        Face *actual = new Polygon;

        failed_test_count += t.check_equal_real_obj(*expected, *actual, EQT);
        delete expected;
        delete actual;
    }
}

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

{
    Test t(GROUP, "assignment", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        Face *expected = new Polygon(4, 5);
        expected->add_node(2);
        expected->add_node(9);
        expected->add_node(4);
        Face *actual = new Polygon;
        *actual = *expected;

        failed_test_count += t.check_equal_real_obj(*expected, *actual, EQT);
        delete expected;
        delete actual;
    }
}

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

{
    Test t(GROUP, "add_get_neighboring_zone", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        Face *f = new Polygon(3, 1);
        f->add_neighbor(2, 4);
        f->add_neighbor(9, 5);
        size_t expected = 9;
        size_t actual = f->get_neighbor(1).my_zone;

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "add_get_neighboring_Polygon", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        Face *f = new Polygon(3, 1);
        f->add_neighbor(2, 4);
        f->add_neighbor(9, 5);
        short int expected = 5;
        short int actual = f->get_neighbor(1).my_id;

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "neighbor_count", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        Face *f = new Polygon(3, 1);
        f->add_neighbor(2, 4);
        f->add_neighbor(9, 5);
        size_t expected = 2;
        size_t actual = f->num_nbr();

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "add_get_neighbor_out_of_range", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        Face *f = new Polygon(3, 1);
        f->add_neighbor(2, 4);
        f->add_neighbor(9, 5);
        std::string expected = "out of range exception";
        std::string actual = UNCAUGHT_EXCEPTION;
        try
        {
            FaceID n = f->get_neighbor(5);
            std::cout << n.my_zone << " " << n.my_id;
        }
        catch (const std::out_of_range &oor)
        {
            actual = "out of range exception";
        }

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "area2_normal_triangle", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "triangle.inc"
        Vector3d expected(4.0, 3.0, 12.0);
        Vector3d actual = f->area2_normal_center(g, v);

        failed_test_count += t.check_equal_real_obj(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "area2_normal_rectangle", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "rectangle.inc"
        Vector3d expected(0.0, 0.0, 12.0);
        Vector3d actual = f->area2_normal_center(g, v);

        failed_test_count += t.check_equal_real_obj(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "area2_normal_trapezoid", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "trapezoid.inc"
        Vector3d expected(0.0, 0.0, 8.0);
        Vector3d actual = f->area2_normal_center(g, v);

        failed_test_count += t.check_equal_real_obj(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "area2_normal_hexagon", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "hexagon.inc"
        Vector3d expected = Vector3d(0.0, 0.0, -6.0*r*s);
        Vector3d actual = f->area2_normal_center(g, v);

        failed_test_count += t.check_equal_real_obj(expected, actual, 10*EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "center_triangle", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "triangle.inc"
        Vector3d expected(1.0, 4.0/3.0, 1.0/3.0);
        Vector3d actual;
        f->area2_normal_center(g, actual);

        failed_test_count += t.check_equal_real_obj(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "center_rectangle", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "rectangle.inc"
        Vector3d expected(2.0, 2.5, 5.0);
        Vector3d actual;
        f->area2_normal_center(g, actual);

        failed_test_count += t.check_equal_real_obj(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "center_trapezoid", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "trapezoid.inc"
        Vector3d expected(13.0/12.0, 5.0/6.0, 0.0);
        Vector3d actual;
        f->area2_normal_center(g, actual);

        failed_test_count += t.check_equal_real_obj(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "center_hexagon", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "hexagon.inc"
        Vector3d expected = center;
        Vector3d actual;
        f->area2_normal_center(g, actual);

        failed_test_count += t.check_equal_real_obj(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "normal_triangle", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "triangle.inc"
        Vector3d expected(4.0/13.0, 3.0/13.0, 12.0/13.0);
        Vector3d actual = f->normal(g);

        failed_test_count += t.check_equal_real_obj(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "normal_rectangle", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "rectangle.inc"
        Vector3d expected(0.0, 0.0, 1.0);
        Vector3d actual = f->normal(g);

        failed_test_count += t.check_equal_real_obj(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "area_triangle", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "triangle.inc"
        double expected = 6.5;
        double actual = f->area(g);

        failed_test_count += t.check_equal_real_num(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "area_rectangle", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "rectangle.inc"
        double expected = 6.0;
        double actual = f->area(g);

        failed_test_count += t.check_equal_real_num(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "signed_distance_triangle", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "triangle.inc"
        Vector3d c;
        v = Vector3d(1.0, 4.0/3.0, 1.0/3.0) + f->area2_normal_center(g, c)/5;
        double expected = 2.6;
        double actual = f->distance(g, v);

        failed_test_count += t.check_equal_real_num(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "signed_distance_rectangle", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "rectangle.inc"
        v = Vector3d(7.0, 6.0, -4.0);
        double expected = -9.0;
        double actual = f->distance(g, v);

        failed_test_count += t.check_equal_real_num(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "subpoint_triangle", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "triangle.inc"
        Vector3d expected = Vector3d(1.0, 4.0/3.0, 1.0/3.0);
        Vector3d c;
        v = expected + f->area2_normal_center(g, c)/5;
        Vector3d actual = f->subpoint(g, v);

        failed_test_count += t.check_equal_real_obj(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "subpoint_rectangle", "fast");
    
    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "rectangle.inc"
        v = Vector3d(7.0, 6.0, -4.0);
        Vector3d expected = Vector3d(7.0, 6.0, 5.0);
        Vector3d actual = f->subpoint(g, v);

        failed_test_count += t.check_equal_real_obj(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "triangle_has_point_above", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "triangle.inc"
        Vector3d c;
        v = Vector3d(1.0, 4.0/3.0, 1.0/3.0) + f->area2_normal_center(g, c)/5;
        bool expected = true;
        bool actual = f->has_above(g, v);

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "rectangle_has_point_above", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "rectangle.inc"
        v = Vector3d(7.0, 6.0, -4.0);
        bool expected = false;
        bool actual = f->has_above(g, v);

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "triangle_has_point_below", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "triangle.inc"
        Vector3d c;
        v = Vector3d(1.0, 4.0/3.0, 1.0/3.0) + f->area2_normal_center(g, c)/5;
        bool expected = false;
        bool actual = f->has_below(g, v);

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "rectangle_has_point_below", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "rectangle.inc"
        v = Vector3d(7.0, 6.0, -4.0);
        bool expected = true;
        bool actual = f->has_below(g, v);

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "triangle_contains_point", "fast");
    
    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "triangle.inc"
        v = Vector3d(1.0, 4.0/3.0, 1.0/3.0);
        bool expected = true;
        bool actual = f->contains(g, v);
        
        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "rectangle_contains_point", "fast");
    
    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "rectangle.inc"
        v = Vector3d(2.0, 3.0, 5.0);
        bool expected = true;
        bool actual = f->contains(g, v);
        
        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "rectangle_misses_point", "fast");
    
    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "rectangle.inc"
        v = Vector3d(7.0, 6.0, 5.0);
        bool expected = false;
        bool actual = f->contains(g, v);
        
        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "rectangle_first_edge_contains_point", "fast");
    
    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "rectangle.inc"
        v = Vector3d(2.0, 1.0, 5.0);
        bool expected = true;
        bool actual = f->contains(g, v);
        
        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "rectangle_first_edge_misses_point", "fast");
    
    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "rectangle.inc"
        v = Vector3d(4.0, 1.0, 5.0);
        bool expected = false;
        bool actual = f->contains(g, v);
        
        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "rectangle_another_edge_contains_point", "fast");
    
    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "rectangle.inc"
        v = Vector3d(2.0, 4.0, 5.0);
        bool expected = true;
        bool actual = f->contains(g, v);
        
        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "rectangle_another_edge_misses_point", "fast");
    
    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "rectangle.inc"
        v = Vector3d(4.0, 4.0, 5.0);
        bool expected = false;
        bool actual = f->contains(g, v);
        
        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "triangle_intercept_distance", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        FaceID fid(9, 8);
        #include "triangle.inc"
        Vector3d r(0.0, 0.0, 0.0);
        v = Vector3d(1.0, 4.0/3.0, 1.0/3.0);
        Vector3d w;
        double expected = 1.0;
        double actual = f->intercept(g, r, v, EQT, fid).t;

        failed_test_count += t.check_equal_real_num(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "triangle_intercept_point", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        FaceID fid(9, 8);
        #include "triangle.inc"
        Vector3d r(0.0, 0.0, 0.0);
        v = Vector3d(1.0, 4.0/3.0, 1.0/3.0);
        Vector3d expected = v;
        Vector3d actual = f->intercept(g, r, v, EQT, fid).w;

        failed_test_count += t.check_equal_real_obj(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "triangle_intercept_face", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        FaceID fid(9, 8);
        #include "triangle.inc"
        Vector3d r(0.0, 0.0, 0.0);
        v = Vector3d(1.0, 4.0/3.0, 1.0/3.0);
        FaceID expected = FaceID(2, 1);
        FaceID actual = f->intercept(g, r, v, EQT, fid).fid;

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "triangle_intercept_found", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        FaceID fid(9, 8);
        #include "triangle.inc"
        Vector3d r(0.0, 0.0, 0.0);
        v = Vector3d(1.0, 4.0/3.0, 1.0/3.0);
        bool expected = true;
        bool actual = f->intercept(g, r, v, EQT, fid).is_found;

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "triangle_intercept_found_same_face", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        FaceID fid(2, 1); // difference from triangle_intercept_found
        #include "triangle.inc"
        Vector3d r(0.0, 0.0, 0.0);
        v = Vector3d(1.0, 4.0/3.0, 1.0/3.0);
        bool expected = false; // difference from triangle_intercept_found
        bool actual = f->intercept(g, r, v, EQT, fid).is_found;

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "triangle_intercept_distance_negative", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        FaceID fid(9, 8);
        #include "triangle.inc"
        Vector3d r(0.0, 0.0, 0.0);
        v = Vector3d(-1.0, -4.0/3.0, -1.0/3.0);
        Vector3d w;
        double expected = -1.0;
        double actual = f->intercept(g, r, v, EQT, fid).t;

        failed_test_count += t.check_equal_real_num(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "triangle_intercept_point_negative", "fast");
    
    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        FaceID fid(9, 8);
        #include "triangle.inc"
        Vector3d r(0.0, 0.0, 0.0);
        v = Vector3d(-1.0, -4.0/3.0, -1.0/3.0);
        Vector3d expected = -v;
        Vector3d actual = f->intercept(g, r, v, EQT, fid).w;
        
        failed_test_count += t.check_equal_real_obj(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "triangle_intercept_found_negative", "fast");
    
    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        FaceID fid(9, 8);
        #include "triangle.inc"
        Vector3d r(0.0, 0.0, 0.0);
        v = Vector3d(-1.0, -4.0/3.0, -1.0/3.0);
        bool expected = false;
        bool actual = f->intercept(g, r, v, EQT, fid).is_found;
        
        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "triangle_intercept_distance_0", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        FaceID fid(9, 8);
        #include "triangle.inc"
        Vector3d r(1.0, 4.0/3.0, 1.0/3.0);
        v = Vector3d(-1.0, -4.0/3.0, -1.0/3.0);
        Vector3d w;
        double expected = 0.0;
        double actual = f->intercept(g, r, v, EQT, fid).t;

        failed_test_count += t.check_equal_real_num(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "triangle_intercept_point_0", "fast");
    
    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        FaceID fid(9, 8);
        #include "triangle.inc"
        Vector3d r(1.0, 4.0/3.0, 1.0/3.0);
        v = Vector3d(-1.0, -4.0/3.0, -1.0/3.0);
        Vector3d expected = -v;
        Vector3d actual = f->intercept(g, r, v, EQT, fid).w;
        
        failed_test_count += t.check_equal_real_obj(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "triangle_intercept_found_0", "fast");
    
    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        FaceID fid(9, 8);
        #include "triangle.inc"
        Vector3d r(1.0, 4.0/3.0, 1.0/3.0);
        v = Vector3d(-1.0, -4.0/3.0, -1.0/3.0);
        bool expected = false;
        bool actual = f->intercept(g, r, v, EQT, fid).is_found;
        
        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "triangle_intercept_distance_parallel", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        FaceID fid(9, 8);
        #include "triangle.inc"
        Vector3d r(0.0, 0.0, 0.0);
        v = Vector3d(-3.0, 0.0, 1.0); // parallel to the plane
        Vector3d w;
        double expected = -Vector3d::get_big();
        double actual = f->intercept(g, r, v, EQT, fid).t;

        failed_test_count += t.check_equal_real_num(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "triangle_intercept_point_parallel", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        FaceID fid(9, 8);
        #include "triangle.inc"
        Vector3d r(0.0, 0.0, 0.0);
        v = Vector3d(-3.0, 0.0, 1.0); // parallel to the plane
        double big = -Vector3d::get_big();
        Vector3d expected(big, big, big);
        Vector3d actual = f->intercept(g, r, v, EQT, fid).w;

        failed_test_count += t.check_equal_real_obj(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "triangle_intercept_found_parallel", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        FaceID fid(9, 8);
        #include "triangle.inc"
        Vector3d r(0.0, 0.0, 0.0);
        v = Vector3d(-3.0, 0.0, 1.0); // parallel to the plane
        bool expected = false;
        bool actual = f->intercept(g, r, v, EQT, fid).is_found;

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "rectangle_contains_intercept", "fast");
    
    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        FaceID fid(9, 8);
        #include "rectangle.inc"
        Vector3d r(2.0, 2.0, 0.0);
        v = Vector3d(0.0, 0.0, 1.0);
        bool expected = true;
        bool actual = f->intercept(g, r, v, EQT, fid).is_found;
        
        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "rectangle_does_not_contain_intercept", "fast");
    
    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        FaceID fid(9, 8);
        #include "rectangle.inc"
        Vector3d r(-2.0, -2.0, 0.0);
        v = Vector3d(0.0, 0.0, 1.0);
        bool expected = false;
        bool actual = f->intercept(g, r, v, EQT, fid).is_found;
        
        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "velocity_triangle", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "velocity_triangle.inc"
        Vector3d c(1.0, 4.0/3.0, 1.0/3.0);
        Vector3d expected(4.3677256019137740,
                          1.4401036616521570,
                          0.8384202999809531);
        Vector3d actual = f->velocity(g, c);

        failed_test_count += t.check_equal_real_obj(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "velocity_triangle_at_x", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "velocity_triangle.inc"
        Vector3d c(3.0, 0.0, 0.0);
        Vector3d expected(4.0, -3.0, 2.0);
        Vector3d actual = f->velocity(g, c);

        failed_test_count += t.check_equal_real_obj(expected, actual, EQT);
        delete f;
    }
}

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

{
    Test t(GROUP, "clear_get_size", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "velocity_triangle.inc"
        f->clear();
        size_t expected = 0;
        size_t actual = f->size();

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "clear_get_Node", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "velocity_triangle.inc"
        f->clear();
        std::string expected("out of range exception");
        std::string actual = UNCAUGHT_EXCEPTION;
        try
        {
            f->get_node(0);
        }
        catch (const std::out_of_range &oor)
        {
            actual = "out of range exception";
        }

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "clear_num_nbr", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "velocity_triangle.inc"
        f->clear();
        size_t expected = 0;
        size_t actual = f->num_nbr();

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "clear_get_Neighbor", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "velocity_triangle.inc"
        f->clear();
        std::string expected("out of range exception");
        std::string actual = UNCAUGHT_EXCEPTION;
        try
        {
            f->get_neighbor(0);
        }
        catch (const std::out_of_range &oor)
        {
            actual = "out of range exception";
        }

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "clear_get_my_zone", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "velocity_triangle.inc"
        f->clear();
        size_t expected = 0;
        size_t actual = f->get_my_zone();

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "clear_get_my_id", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        #include "velocity_triangle.inc"
        f->clear();
        short int expected = -2;
        short int actual = f->get_my_id();

        failed_test_count += t.check_equal(expected, actual);
        delete f;
    }
}

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

{
    Test t(GROUP, "load_Hydro1_Mesh0_1st_Polygon", "fast");

    check_to_disable_test(t, disabled_test_count);
    if (t.is_enabled())
    {
        std::string path(cnst::PATH + "UniTest/Hydro1/");
        std::string tlabel("0");
        std::string fname = path + "mesh_" + tlabel + ".txt";
        std::ifstream infile(fname.c_str());
        utils::find_line(infile, "Polygon");
        Polygon f(infile);
        infile.close();
        infile.clear();
        std::string expected("Polygon\n          4\n          0         -1\n");
        expected += "          0          1          5          4\n";
        expected += "          neighbors          1\n          1          0";
        std::string actual = f.to_string();

        failed_test_count += t.check_equal(expected, actual);
    }
}

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

}
int QgsTransectSample::createSample( QProgressDialog* pd )
{
  Q_UNUSED( pd );

  if ( !mStrataLayer || !mStrataLayer->isValid() )
  {
    return 1;
  }

  if ( !mBaselineLayer || !mBaselineLayer->isValid() )
  {
    return 2;
  }

  //stratum id is not necessarily an integer
  QVariant::Type stratumIdType = QVariant::Int;
  if ( !mStrataIdAttribute.isEmpty() )
  {
    stratumIdType = mStrataLayer->pendingFields().field( mStrataIdAttribute ).type();
  }

  //create vector file writers for output
  QgsFields outputPointFields;
  outputPointFields.append( QgsField( "id", stratumIdType ) );
  outputPointFields.append( QgsField( "station_id", QVariant::Int ) );
  outputPointFields.append( QgsField( "stratum_id", stratumIdType ) );
  outputPointFields.append( QgsField( "station_code", QVariant::String ) );
  outputPointFields.append( QgsField( "start_lat", QVariant::Double ) );
  outputPointFields.append( QgsField( "start_long", QVariant::Double ) );

  QgsVectorFileWriter outputPointWriter( mOutputPointLayer, "utf-8", outputPointFields, QGis::WKBPoint,
                                         &( mStrataLayer->crs() ) );
  if ( outputPointWriter.hasError() != QgsVectorFileWriter::NoError )
  {
    return 3;
  }

  outputPointFields.append( QgsField( "bearing", QVariant::Double ) ); //add bearing attribute for lines
  QgsVectorFileWriter outputLineWriter( mOutputLineLayer, "utf-8", outputPointFields, QGis::WKBLineString,
                                        &( mStrataLayer->crs() ) );
  if ( outputLineWriter.hasError() != QgsVectorFileWriter::NoError )
  {
    return 4;
  }

  QgsFields usedBaselineFields;
  usedBaselineFields.append( QgsField( "stratum_id", stratumIdType ) );
  usedBaselineFields.append( QgsField( "ok", QVariant::String ) );
  QgsVectorFileWriter usedBaselineWriter( mUsedBaselineLayer, "utf-8", usedBaselineFields, QGis::WKBLineString,
                                          &( mStrataLayer->crs() ) );
  if ( usedBaselineWriter.hasError() != QgsVectorFileWriter::NoError )
  {
    return 5;
  }

  //debug: write clipped buffer bounds with stratum id to same directory as out_point
  QFileInfo outputPointInfo( mOutputPointLayer );
  QString bufferClipLineOutput = outputPointInfo.absolutePath() + "/out_buffer_clip_line.shp";
  QgsFields bufferClipLineFields;
  bufferClipLineFields.append( QgsField( "id", stratumIdType ) );
  QgsVectorFileWriter bufferClipLineWriter( bufferClipLineOutput, "utf-8", bufferClipLineFields, QGis::WKBLineString, &( mStrataLayer->crs() ) );

  //configure distanceArea depending on minDistance units and output CRS
  QgsDistanceArea distanceArea;
  distanceArea.setSourceCrs( mStrataLayer->crs().srsid() );
  if ( mMinDistanceUnits == Meters )
  {
    distanceArea.setEllipsoidalMode( true );
  }
  else
  {
    distanceArea.setEllipsoidalMode( false );
  }

  //possibility to transform output points to lat/long
  QgsCoordinateTransform toLatLongTransform( mStrataLayer->crs(), QgsCoordinateReferenceSystem( 4326, QgsCoordinateReferenceSystem::EpsgCrsId ) );

  //init random number generator
  mt_srand( QTime::currentTime().msec() );

  QgsFeatureRequest fr;
  fr.setSubsetOfAttributes( QStringList() << mStrataIdAttribute << mMinDistanceAttribute << mNPointsAttribute, mStrataLayer->pendingFields() );
  QgsFeatureIterator strataIt = mStrataLayer->getFeatures( fr );

  QgsFeature fet;
  int nTotalTransects = 0;
  int nFeatures = 0;

  if ( pd )
  {
    pd->setMaximum( mStrataLayer->featureCount() );
  }

  while ( strataIt.nextFeature( fet ) )
  {
    if ( pd )
    {
      pd->setValue( nFeatures );
    }
    if ( pd && pd->wasCanceled() )
    {
      break;
    }

    if ( !fet.constGeometry() )
    {
      continue;
    }
    const QgsGeometry* strataGeom = fet.constGeometry();

    //find baseline for strata
    QVariant strataId = fet.attribute( mStrataIdAttribute );
    QgsGeometry* baselineGeom = findBaselineGeometry( strataId.isValid() ? strataId : -1 );
    if ( !baselineGeom )
    {
      continue;
    }

    double minDistance = fet.attribute( mMinDistanceAttribute ).toDouble();
    double minDistanceLayerUnits = minDistance;
    //if minDistance is in meters and the data in degrees, we need to apply a rough conversion for the buffer distance
    double bufferDist = bufferDistance( minDistance );
    if ( mMinDistanceUnits == Meters && mStrataLayer->crs().mapUnits() == QGis::DecimalDegrees )
    {
      minDistanceLayerUnits = minDistance / 111319.9;
    }

    QgsGeometry* clippedBaseline = strataGeom->intersection( baselineGeom );
    if ( !clippedBaseline || clippedBaseline->wkbType() == QGis::WKBUnknown )
    {
      delete clippedBaseline;
      continue;
    }
    QgsGeometry* bufferLineClipped = clipBufferLine( strataGeom, clippedBaseline, bufferDist );
    if ( !bufferLineClipped )
    {
      delete clippedBaseline;
      continue;
    }

    //save clipped baseline to file
    QgsFeature blFeature;
    blFeature.setGeometry( *clippedBaseline );
    blFeature.setAttribute( "stratum_id", strataId );
    blFeature.setAttribute( "ok", "f" );
    usedBaselineWriter.addFeature( blFeature );

    //start loop to create random points along the baseline
    int nTransects = fet.attribute( mNPointsAttribute ).toInt();
    int nCreatedTransects = 0;
    int nIterations = 0;
    int nMaxIterations = nTransects * 50;

    QgsSpatialIndex sIndex; //to check minimum distance
    QMap< QgsFeatureId, QgsGeometry* > lineFeatureMap;

    while ( nCreatedTransects < nTransects && nIterations < nMaxIterations )
    {
      double randomPosition = (( double )mt_rand() / MD_RAND_MAX ) * clippedBaseline->length();
      QgsGeometry* samplePoint = clippedBaseline->interpolate( randomPosition );
      ++nIterations;
      if ( !samplePoint )
      {
        continue;
      }
      QgsPoint sampleQgsPoint = samplePoint->asPoint();
      QgsPoint latLongSamplePoint = toLatLongTransform.transform( sampleQgsPoint );

      QgsFeature samplePointFeature;
      samplePointFeature.setGeometry( samplePoint );
      samplePointFeature.setAttribute( "id", nTotalTransects + 1 );
      samplePointFeature.setAttribute( "station_id", nCreatedTransects + 1 );
      samplePointFeature.setAttribute( "stratum_id", strataId );
      samplePointFeature.setAttribute( "station_code", strataId.toString() + "_" + QString::number( nCreatedTransects + 1 ) );
      samplePointFeature.setAttribute( "start_lat", latLongSamplePoint.y() );
      samplePointFeature.setAttribute( "start_long", latLongSamplePoint.x() );

      //find closest point on clipped buffer line
      QgsPoint minDistPoint;

      int afterVertex;
      if ( bufferLineClipped->closestSegmentWithContext( sampleQgsPoint, minDistPoint, afterVertex ) < 0 )
      {
        continue;
      }

      //bearing between sample point and min dist point (transect direction)
      double bearing = distanceArea.bearing( sampleQgsPoint, minDistPoint ) / M_PI * 180.0;

      QgsPolyline sampleLinePolyline;
      QgsPoint ptFarAway( sampleQgsPoint.x() + ( minDistPoint.x() - sampleQgsPoint.x() ) * 1000000,
                          sampleQgsPoint.y() + ( minDistPoint.y() - sampleQgsPoint.y() ) * 1000000 );
      QgsPolyline lineFarAway;
      lineFarAway << sampleQgsPoint << ptFarAway;
      QgsGeometry* lineFarAwayGeom = QgsGeometry::fromPolyline( lineFarAway );
      QgsGeometry* lineClipStratum = lineFarAwayGeom->intersection( strataGeom );
      if ( !lineClipStratum )
      {
        delete lineFarAwayGeom; delete lineClipStratum;
        continue;
      }

      //cancel if distance between sample point and line is too large (line does not start at point
      if ( lineClipStratum->distance( *samplePoint ) > 0.000001 )
      {
        delete lineFarAwayGeom; delete lineClipStratum;
        continue;
      }

      //if lineClipStratum is a multiline, take the part line closest to sampleQgsPoint
      if ( lineClipStratum->wkbType() == QGis::WKBMultiLineString
           || lineClipStratum->wkbType() == QGis::WKBMultiLineString25D )
      {
        QgsGeometry* singleLine = closestMultilineElement( sampleQgsPoint, lineClipStratum );
        if ( singleLine )
        {
          delete lineClipStratum;
          lineClipStratum = singleLine;
        }
      }

      //cancel if length of lineClipStratum is too small
      double transectLength = distanceArea.measure( lineClipStratum );
      if ( transectLength < mMinTransectLength )
      {
        delete lineFarAwayGeom; delete lineClipStratum;
        continue;
      }

      //search closest existing profile. Cancel if dist < minDist
      if ( otherTransectWithinDistance( lineClipStratum, minDistanceLayerUnits, minDistance, sIndex, lineFeatureMap, distanceArea ) )
      {
        delete lineFarAwayGeom; delete lineClipStratum;
        continue;
      }

      QgsFeatureId fid( nCreatedTransects );
      QgsFeature sampleLineFeature( fid );
      sampleLineFeature.setGeometry( lineClipStratum );
      sampleLineFeature.setAttribute( "id", nTotalTransects + 1 );
      sampleLineFeature.setAttribute( "station_id", nCreatedTransects + 1 );
      sampleLineFeature.setAttribute( "stratum_id", strataId );
      sampleLineFeature.setAttribute( "station_code", strataId.toString() + "_" + QString::number( nCreatedTransects + 1 ) );
      sampleLineFeature.setAttribute( "start_lat", latLongSamplePoint.y() );
      sampleLineFeature.setAttribute( "start_long", latLongSamplePoint.x() );
      sampleLineFeature.setAttribute( "bearing", bearing );
      outputLineWriter.addFeature( sampleLineFeature );

      //add point to file writer here.
      //It can only be written if the corresponding transect has been as well
      outputPointWriter.addFeature( samplePointFeature );

      sIndex.insertFeature( sampleLineFeature );
      Q_NOWARN_DEPRECATED_PUSH
      lineFeatureMap.insert( fid, sampleLineFeature.geometryAndOwnership() );
      Q_NOWARN_DEPRECATED_POP

      delete lineFarAwayGeom;
      ++nTotalTransects;
      ++nCreatedTransects;
    }
    delete clippedBaseline;

    QgsFeature bufferClipFeature;
    bufferClipFeature.setGeometry( bufferLineClipped );
    bufferClipFeature.setAttribute( "id", strataId );
    bufferClipLineWriter.addFeature( bufferClipFeature );
    //delete bufferLineClipped;

    //delete all line geometries in spatial index
    QMap< QgsFeatureId, QgsGeometry* >::iterator featureMapIt = lineFeatureMap.begin();
    for ( ; featureMapIt != lineFeatureMap.end(); ++featureMapIt )
    {
      delete( featureMapIt.value() );
    }
    lineFeatureMap.clear();
    delete baselineGeom;

    ++nFeatures;
  }

  if ( pd )
  {
    pd->setValue( mStrataLayer->featureCount() );
  }

  return 0;
}
    // Reads a LAMMPS input file.
    void LAMMPS_Data::read_data(string path) {
        fstream fid(path);
        if (!fid) {
            cout << "Error opening output file " << path << "!\n";  
        }
        int section=0;    
        while (fid) {
            auto line = split(read_line(fid));
            if (line.empty()) continue;
            else if (line[0]=="Masses")    section=1;
            else if (line[0]=="Pair")      section=2;
            else if (line[0]=="Bond")      section=3;
            else if (line[0]=="Angle")     section=4;
            else if (line[0]=="Dihedral")  section=5;
            else if (line[0]=="Atoms")     section=6;
            else if (line[0]=="Bonds")     section=7;
            else if (line[0]=="Angles")    section=8;
            else if (line[0]=="Dihedrals") section=9;

            switch (section) {
            case 1: 
                if (line.size()==2) { 
                    //_system.atom_types.push_back(str2u32(line[0]));
                    //_system.masses.push_back(str2dbl(line[1]));
                }
                break;
            case 6:
                Atom newatom;
                if (line.size() >= 6) { 
                    newatom.molecule   = str2u32(line[1]);
                    newatom.type       = str2u32(line[2]);
                    _system.atoms.push_back(newatom);
                }

                break;
            case 7:
                if (_system.connect.empty()) {
                    _system.connect.assign(_system.atoms.size(), vector<int>(0));
                }
                if (line.size()==4) {
                    Bond newbond;
                    //newbond.id    = str2u32(line[0]);
                    //newbond.type  = str2u32(line[1]);
                    newbond.atom1 = str2u32(line[2])-1;
                    newbond.atom2 = str2u32(line[3])-1;
                    //_system.bonds.push_back(newbond);
                    _system.connect[newbond.atom1].push_back(newbond.atom2);
                    _system.connect[newbond.atom2].push_back(newbond.atom1);
                }
                break;
            case 8: break; // No need to keep going.
            default: continue;       
            };
        }
        // Report total number of bonds.
        int num_bonds = 0;
        for (auto c=_system.connect.cbegin(); c!=_system.connect.cend(); ++c) {
            num_bonds += c->size();
        }
        cout << "Read " << num_bonds/2 << " bonds from the input file.\n";            
    }
    // Reads a LAMMPS dump output file, in atom format.
    void LAMMPS_Data::read_dump(string path) {
        fstream fid(path);
        if (!fid) cout << "Error opening output file " << path << "!\n";
        else      cout << "Opened dump " << path << ".\n";

        SnapshotDump *step=NULL;
        while (fid) {
            auto line = trim(read_line(fid));
            if (line.empty()) continue;
            else if (line=="ITEM: TIMESTEP") {
                _dump.push_back(SnapshotDump());
                step = &_dump.back(); 
                step->timestep = str2u32(trim(read_line(fid)));
            }
            else if (line=="ITEM: NUMBER OF ATOMS") {
                if (!step) { 
                    cout << "Error: NUMBER OF ATOMS specified before TIMESTEP\n";
                    exit(1);
                }
                unsigned n = str2u32(trim(read_line(fid)));
                step->scaled_coordinates.assign(n, Coord());
            }
            else if (line.find("ITEM: BOX BOUNDS")==0) {
                if (!step) { 
                    cout << "Error: BOX BOUNDS specified before TIMESTEP\n";
                    exit(1);
                }
                auto xb  = split(read_line(fid));
                auto yb  = split(read_line(fid));
                auto zb  = split(read_line(fid));
                step->dx = fabs(str2dbl(xb.at(1))-str2dbl(xb.at(0)));
                step->dy = fabs(str2dbl(yb.at(1))-str2dbl(yb.at(0)));                                
                step->dz = fabs(str2dbl(zb.at(1))-str2dbl(zb.at(0)));
            }
            // The only thing left should be the ATOMS data.
            else {
                auto pieces = split(line);
                if (pieces.size() < 4) continue;
                if (pieces[0]=="ITEM:" && pieces[1]=="ATOMS") {
                    vector<string> var(pieces.begin()+2, pieces.end());
                    // Search for coordinate and tag columns.
                    step->xc = step->yc = step->zc = step->zc = -1;
                    step->xs = step->ys = step->zs = 0;
                    for (size_t i=0; i<var.size(); ++i) {
                        if (var[i]=="x")  {step->xc=i;}
                        if (var[i]=="xs") {step->xc=i; step->xs=1; }
                        if (var[i]=="y")  {step->yc=i;}
                        if (var[i]=="ys") {step->yc=i; step->ys=1; }
                        if (var[i]=="z")  {step->zc=i;}
                        if (var[i]=="zs") {step->zc=i; step->zs=1; }
                        if (var[i]=="id")  step->tc=i;
                    }
                    if (step->xc<0 || step->yc<0 || step->zc<0) {
                        cout << "Error: coordinate column not found\n";
                        exit(1);
                    }
                    if (step->tc<0) {
                        cout << "Error: atom tag column not found.\n";
                        exit(1);
                    }
                   continue;
                }
                if (!step) { 
                    cout << "Error: data encountered before TIMESTEP\n";
                    exit(1);
                }
                auto maxc=max(step->tc,max(step->xc,max(step->yc,step->zc)));
                auto minc=min(step->tc,min(step->xc,min(step->yc,step->zc)));
                if (maxc >= (int)pieces.size()) {
                    cout << "Not enough columns in dump data.\n";
                    exit(1);
                }
                if (minc < 0) {
                    cout << "Missing data column in dump data.\n";
                    exit(1);
                }
                unsigned id = str2u32(pieces[step->tc])-1;
                if (step->scaled_coordinates.size() <= id) {
                    cout << "Error: invalid atom id found " << id << "\n";
                    exit(1);
                }
                Coord &r = step->scaled_coordinates[id];
                r.x = str2dbl(pieces[step->xc]);
                r.y = str2dbl(pieces[step->yc]);
                r.z = str2dbl(pieces[step->zc]);

                // Store coordinates scaled no matter what the input is.
                if (!step->xs) r.x = to_scaled(r.x, step->dx);
                if (!step->ys) r.y = to_scaled(r.y, step->dy);
                if (!step->zs) r.z = to_scaled(r.z, step->dz);
            }
        }
    }
Example #22
0
 format * mk_compose(ast_manager & m, unsigned num_children, format * const * children) {
     return fm(m).mk_app(fid(m), OP_COMPOSE, num_children, (expr * const *) children);
 }
Example #23
0
 format * mk_compose(ast_manager & m, format * f1, format * f2, format * f3) {
     return fm(m).mk_app(fid(m), OP_COMPOSE, f1, f2, f3);
 }
Example #24
0
 format * mk_compose(ast_manager & m, format * f1, format * f2, format * f3, format * f4) {
     expr * f[4] = { f1, f2, f3, f4 };
     return fm(m).mk_app(fid(m), OP_COMPOSE, 4, f);
 }
Example #25
0
 format * mk_nil(ast_manager & m) {
     return fm(m).mk_app(fid(m), OP_NIL);
 }
Example #26
0
/**
 * Read power management file and return contained value
 */
double read_pm_file(const std::string &fname) {
    double result = 0.;
    std::ifstream fid(fname.c_str());
    fid >> result;
    return result;
}
TPointD XshHandleManager::getHandlePos(const TStageObjectId &id,
                                       const std::string &handle,
                                       int row) const {
  static const double unit = 8.0;

  assert(m_xsh->getScene());

  if (handle == "")
    return TPointD();

  else if (handle[0] == 'H' && handle.length() > 1) {
    // Hook port case

    if (!id.isColumn()) return TPointD();

    int hookIndex = 0;
    {
      int h, hLength = handle.length();
      for (h = 1; h != hLength; ++h)
        hookIndex = hookIndex * 10 + (handle[h] - '0');
    }

    TStageObject *obj = m_xsh->getStageObject(id);
    if (const PlasticSkeletonDeformationP &def =
            obj->getPlasticSkeletonDeformation()) {
      int skelId = def->skeletonId(row);

      PlasticSkeleton skel;
      def->storeDeformedSkeleton(skelId, row, skel);

      int v = def->vertexIndex(hookIndex, skelId);
      return (v >= 0) ? TScale(1.0 / Stage::inch) * skel.vertex(v).P()
                      : TPointD();
    }

    --hookIndex;

    int col = id.getIndex();
    TXshCell cell(m_xsh->getCell(row, col));

    TXshLevel *xl = cell.m_level.getPointer();
    if (!xl) return TPointD();

    TXshSimpleLevel *sl = xl->getSimpleLevel();
    if (!sl) return TPointD();

    Hook *hook = sl->getHookSet()->getHook(hookIndex);
    if (!hook) return TPointD();

    TFrameId fid(cell.m_frameId);

    TPointD pos = hook->getAPos(fid) * (1.0 / Stage::inch);
    TPointD delta;

    for (int r = row - 1; r >= 0; --r) {
      cell = m_xsh->getCell(r, col);
      if (cell.m_level.getPointer() != xl) break;

      const TFrameId &precFid = cell.m_frameId;
      delta += computePassHook(fid, precFid, sl, hook);
      fid = precFid;
    }

    pos += delta * (1.0 / Stage::inch);
    pos = getDpiAffine(sl, cell.m_frameId, true) * pos;

    return pos;
  } else if ('A' <= handle[0] && handle[0] <= 'Z')
    return TPointD(unit * (handle[0] - 'B'), 0);
  else if ('a' <= handle[0] && handle[0] <= 'z')
    return TPointD(0.5 * unit * (handle[0] - 'b'), 0);
  else
    return TPointD();
}
Example #28
0
bool fexist(string filename){
	ifstream fid(filename.c_str());
	return fid;
}
Example #29
0
void RichQtfParser::Parse(const char *qtf, int _accesskey)
{
	accesskey = _accesskey;
	term = qtf;
	while(*term) {
		if(Key('[')) {
			Flush();
			fstack.Add(format);
			for(;;) {
				int c = *term;
				if(!c)
					Error("Unexpected end of text");
				term++;
				if(c == ' ' || c == '\n') break;
				switch(c) {
				case 's': {
					Uuid id;
					c = *term;
					if(Key('\"') || Key('\''))
						id = target.GetStyleId(GetText(c));
					else {
						int i = ReadNumber();
						if(i >= 0 && i < styleid.GetCount())
							id = styleid[i];
						else
							id = RichStyle::GetDefaultId();
					}
					const RichStyle& s = target.GetStyle(id);
					bool p = format.newpage;
					int lng = format.language;
					(RichPara::Format&) format = s.format;
					format.styleid = id;
					format.language = lng;
					format.newpage = p;
					break;
				}
				case '/': format.Italic(!format.IsItalic()); break;
				case '*': format.Bold(!format.IsBold()); break;
				case '_': format.Underline(!format.IsUnderline()); break;
				case 'T': format.NonAntiAliased(!format.IsNonAntiAliased()); break;
				case '-': format.Strikeout(!format.IsStrikeout()); break;
				case 'c': format.capitals = !format.capitals; break;
				case 'd': format.dashed = !format.dashed; break;
				case '`': format.sscript = format.sscript == 1 ? 0 : 1; break;
				case ',': format.sscript = format.sscript == 2 ? 0 : 2; break;
				case '^': format.link = GetText('^'); break;
				case 'I': format.indexentry = FromUtf8(GetText(';')); break;
				case '+': format.Height(GetNumber()); break;
				case '@': format.ink = GetColor(); break;
				case '$': format.paper = GetColor(); break;
				case 'A': format.Face(Font::ARIAL); break;
				case 'R': format.Face(Font::ROMAN); break;
				case 'C': format.Face(Font::COURIER); break;
				case 'G': format.Face(Font::STDFONT); break;
				case 'S':
#ifdef PLATFORM_WIN32
					format.Face(Font::SYMBOL);
#endif
					break;
				case '.': {
					int n = GetNumber();
					if(n >= Font::GetFaceCount())
						Error("Invalid face number");
					format.Face(n); break;
				}
				case '!': {
						String fn = GetText('!');
						int i = Font::FindFaceNameIndex(fn);
						if(i < 0)
							i = Font::ARIAL;
						format.Face(i);
					}
					break;
				case '{': {
						String cs = GetText('}');
						if(cs.GetLength() == 1) {
							int c = *cs;
							if(c == '_')
								format.charset = CHARSET_UTF8;
							if(c >= '0' && c <= '8')
								format.charset = c - '0' + CHARSET_WIN1250;
							if(c >= 'A' && c <= 'Z')
								format.charset = c - '0' + CHARSET_ISO8859_1;
						}
						else {
							for(int i = 0; i < CharsetCount(); i++)
								if(stricmp(CharsetName(i), cs) == 0) {
									format.charset = i;
									break;
								}
						}
						break;
					}
				case '%': {
						String h;
						if(*term == '-') {
							format.language = 0;
							term++;
						}
						else
						if(*term == '%') {
							format.language = LNG_ENGLISH;
							term++;
						}
						else {
							while(*term && h.GetLength() < 5)
								h.Cat(*term++);
							format.language = LNGFromText(h);
						}
						break;
					}
				case 'g':
					format.Face(Font::STDFONT);
					format.Height(GetRichTextScreenStdFontHeight());
					break;
				default:
					if(c >= '0' && c <= '9') {
						format.Height(QTFFontHeight[c - '0']);
						break;
					}
					switch(c) {
					case ':': format.label = GetText(':'); break;
					case '<': format.align = ALIGN_LEFT; break;
					case '>': format.align = ALIGN_RIGHT; break;
					case '=': format.align = ALIGN_CENTER; break;
					case '#': format.align = ALIGN_JUSTIFY; break;
					case 'l': format.lm = GetNumber(); break;
					case 'r': format.rm = GetNumber(); break;
					case 'i': format.indent = GetNumber(); break;
					case 'b': format.before = GetNumber(); break;
					case 'a': format.after = GetNumber(); break;
					case 'P': format.newpage = !format.newpage; break;
					case 'k': format.keep = !format.keep; break;
					case 'K': format.keepnext = !format.keepnext; break;
					case 'H': format.ruler = GetNumber(); break;
					case 'h': format.rulerink = GetColor(); break;
					case 'L': format.rulerstyle = GetNumber(); break;
					case 'Q': format.orphan = !format.orphan; break;
					case 'n': format.before_number = GetText(';'); break;
					case 'm': format.after_number = GetText(';'); break;
					case 'N': {
						memset(format.number, 0, sizeof(format.number));
						format.reset_number = false;
						int i = 0;
						while(i < 8) {
							int c;
							if(Key('-'))
								c = RichPara::NUMBER_NONE;
							else
							if(Key('1'))
								c = RichPara::NUMBER_1;
							else
							if(Key('0'))
								c = RichPara::NUMBER_0;
							else
							if(Key('a'))
								c = RichPara::NUMBER_a;
							else
							if(Key('A'))
								c = RichPara::NUMBER_A;
							else
							if(Key('i'))
								c = RichPara::NUMBER_i;
							else
							if(Key('I'))
								c = RichPara::NUMBER_I;
							else
								break;
							format.number[i++] = c;
						}
						if(Key('!'))
							format.reset_number = true;
						break;
					}
					case 'o': format.bullet = RichPara::BULLET_ROUND;
					          format.indent = 150; break;
					case 'O':
						if(Key('_'))
							format.bullet = RichPara::BULLET_NONE;
						else {
							int c = *term++;
							if(!c)
								Error("Unexpected end of text");
							format.bullet =
							                c == '1' ? RichPara::BULLET_ROUNDWHITE :
							                c == '2' ? RichPara::BULLET_BOX :
							                c == '3' ? RichPara::BULLET_BOXWHITE :
							                c == '9' ? RichPara::BULLET_TEXT :
							                           RichPara::BULLET_ROUND;
						}
						break;
					case 'p':
						switch(*term++) {
						case 0:   Error("Unexpected end of text");
						case 'h': format.linespacing = RichPara::LSP15; break;
						case 'd': format.linespacing = RichPara::LSP20; break;
						default:  format.linespacing = RichPara::LSP10;
						}
						break;
					case 't':
						if(*term == 'P') {
							term++;
							format.newhdrftr = true;
							format.header_qtf = GetText2('^', '^');
							format.footer_qtf = GetText2('^', '^');
						}
						else
						if(IsDigit(*term))
							format.tabsize = ReadNumber();
						break;
					case '~': {
							if(Key('~'))
								format.tab.Clear();
							else {
								RichPara::Tab tab;
								Key('<');
								if(Key('>'))
									tab.align = ALIGN_RIGHT;
								if(Key('='))
									tab.align = ALIGN_CENTER;
								if(Key('.'))
									tab.fillchar = 1;
								if(Key('-'))
									tab.fillchar = 2;
								if(Key('_'))
									tab.fillchar = 3;
								int rightpos = Key('>') ? RichPara::TAB_RIGHTPOS : 0;
								tab.pos = rightpos | ReadNumber();
								format.tab.Add(tab);
							}
						}
						break;
					default:
						continue;
					}
				}
			}
			SetFormat();
		}
		else
		if(Key(']')) {
			Flush();
			if(fstack.GetCount()) {
				format = fstack.Top();
				fstack.Drop();
			}
			else
				Error("Unmatched ']'");
		}
		else
		if(Key2('{')) {
			if(oldtab)
				Error("{{ in ++ table");
			if(text.GetLength() || paragraph.GetCount())
				EndPart();
			table.Add();
			int r = IsDigit(*term) ? ReadNumber() : 1;
			Table().AddColumn(r);
			while(Key(':'))
				Table().AddColumn(ReadNumber());
			if(breakpage) {
				RichTable& tab = Table();
				RichTable::Format tabformat = tab.GetFormat();
				tabformat.newpage = true;
				tab.SetFormat(tabformat);
				breakpage = false;
			}
			TableFormat();
			SetFormat();
		}
		else
		if(Key2('}')) {
			if(oldtab)
				Error("}} in ++ table");
			FinishTable();
		}
		else
		if(Key2('+'))
			if(oldtab)
				FinishOldTable();
			else {
				Flush();
				if(text.GetLength() || paragraph.GetCount())
					EndPart();
				Tab& b = table.Add();
				b.rown.Add(0);
				b.hspan = 1;
				b.Old();
				oldtab = true;
			}
		else
		if(Key2('|'))
			FinishCell();
		else
		if(Key2('-')) {
			FinishCell();
			table.Top().rown.Add(0);
		}
		else
		if(Key2(':')) {
			if(!oldtab)
				FinishCell();
			TableFormat(oldtab);
		}
		else
		if(Key2('^')) {
			EndPart();
			breakpage = true;
		}
		else
		if(Key2('@')) {
			ReadObject();
		}
		else
		if(Key2('@', '$')) {
			String xu;
			while(isxdigit(*term))
				xu.Cat(*term++);
			int c = stou(~xu, NULL, 16);
			if(c >= 32)
				Cat(c);
			if(*term == ';')
				term++;
			SetFormat();
		}
		else
		if(Key2('^', 'H'))
			target.SetHeaderQtf(GetText2('^', '^'));
		else
		if(Key2('^', 'F'))
			target.SetFooterQtf(GetText2('^', '^'));
		else
		if(Key2('{', ':')) {
			Flush();
			String field = GetText(':');
			String param = GetText(':');
			Id fid(field);
			if(RichPara::fieldtype().Find(fid) >= 0)
				paragraph.Cat(fid, param, format);
			Key('}');
		}
		else
		if(Key('&')) {
			SetFormat();
			EndPart();
		}
		else
		if(Key2('$')) {
			Flush();
			int i = GetNumber();
			Uuid id;
			RichStyle style;
			style.format = format;
			if(Key(','))
				stylenext.At(i, 0) = GetNumber();
			else
				stylenext.At(i, 0) = i;
			if(Key('#')) {
				String xu;
				while(isxdigit(*term))
					xu.Cat(*term++);
				if(xu.GetLength() != 32)
					Error("Invalid UUID !");
				id = ScanUuid(xu);
			}
			else
				if(i)
					id = Uuid::Create();
				else
					id = RichStyle::GetDefaultId();
			if(Key(':'))
				style.name = GetText(']');
			if(fstack.GetCount()) {
				format = fstack.Top();
				fstack.Drop();
			}
			target.SetStyle(id, style);
			styleid.At(i, RichStyle::GetDefaultId()) = id;
			if(id == RichStyle::GetDefaultId()) {
				bool p = format.newpage;
				int lng = format.language;
				(RichPara::Format&) format = style.format;
				format.styleid = id;
				format.language = lng;
				format.newpage = p;
			}
		}
		else
		if(*term == '_') {
			SetFormat();
			text.Cat(160);
			term++;
		}
		else
		if(Key2('-', '|')) {
			SetFormat();
			text.Cat(9);
		}
		else
		if(*term == '\1') {
			if(istable)
				EndPart();
			SetFormat();
			const char *b = ++term;
			for(; *term && *term != '\1'; term++) {
				if((byte)*term == '\n') {
					text.Cat(ToUnicode(b, (int)(term - b), format.charset));
					EndPart();
					b = term + 1;
				}
				if((byte)*term == '\t') {
					text.Cat(ToUnicode(b, (int)(term - b), format.charset));
					text.Cat(9);
					b = term + 1;
				}
			}
			text.Cat(ToUnicode(b, (int)(term - b), format.charset));
			if(*term == '\1')
				term++;
		}
		else {
			if(!Key('`')) Key('\\');
			if((byte)*term >= ' ') {
				SetFormat();
				do {
					if(istable)
						EndPart();
					if(format.charset == CHARSET_UTF8) {
						word code = (byte)*term++;
						if(code <= 0x7F)
							Cat(code);
						else
						if(code <= 0xDF) {
							if(*term == '\0') break;
							int c0 = (byte)*term++;
							if(c0 < 0x80)
								Error("Invalid UTF-8 sequence");
							Cat(((code - 0xC0) << 6) + c0 - 0x80);
						}
						else
						if(code <= 0xEF) {
							int c0 = (byte)*term++;
							int c1 = (byte)*term++;
							if(c0 < 0x80 || c1 < 0x80)
								Error("Invalid UTF-8 sequence");
							Cat(((code - 0xE0) << 12) + ((c0 - 0x80) << 6) + c1 - 0x80);
						}
						else
							Error("Invalid UTF-8 sequence");
					}
					else
						Cat(ToUnicode((byte)*term++, format.charset));
				}
				while((byte)*term >= 128 || s_nodeqtf[(byte)*term]);
			}
			else
			if(*term)
				term++;
		}
	}
//	if(paragraph.GetCount() == 0) // TRC 11/02/15: kills formatting of last paragraph in text
//		SetFormat();
	if(oldtab)
		FinishOldTable();
	else
		while(table.GetCount())
			FinishTable();
	EndPart();
	FlushStyles();
}
Example #30
0
 format * mk_choice(ast_manager & m, format * f1, format * f2) {
     return fm(m).mk_app(fid(m), OP_CHOICE, f1, f2);
 }