Example #1
0
Foam::surfMesh::surfMesh
(
    const IOobject& io,
    const Xfer< pointField >& pointLst,
    const Xfer< faceList >& faceLst,
    const word& surfName
)
:
    surfaceRegistry(io.db(), (surfName.size() ? surfName : io.name())),
    Allocator
    (
        IOobject
        (
            "points",
            instance(),
            meshSubDir,
            *this,
            IOobject::NO_READ,
            IOobject::AUTO_WRITE
        ),
        pointLst,
        IOobject
        (
            "faces",
            instance(),
            meshSubDir,
            *this,
            IOobject::NO_READ,
            IOobject::AUTO_WRITE
        ),
        faceLst,
        IOobject
        (
            "surfZones",
            instance(),
            meshSubDir,
            *this,
            IOobject::NO_READ,
            IOobject::AUTO_WRITE
        ),
        Xfer<surfZoneList>()
    ),
    MeshReference(this->storedIOFaces(), this->storedIOPoints())
{}
Example #2
0
bool Foam::functionEntry::execute
(
    const word& functionName,
    const dictionary& parentDict,
    primitiveEntry& entry,
    Istream& is
)
{
    is.fatalCheck
    (
        "functionEntry::execute"
        "(const word&, const dictionary&, primitiveEntry&, Istream&)"
    );

    if (!executeprimitiveEntryIstreamMemberFunctionTablePtr_)
    {
        cerr<<"functionEntry::execute"
            << "(const word&, const dictionary&, primitiveEntry&, Istream&)"
            << " not yet initialized, function = "
            << functionName.c_str() << std::endl;

        // return true to keep reading anyhow
        return true;
    }

    executeprimitiveEntryIstreamMemberFunctionTable::iterator mfIter =
        executeprimitiveEntryIstreamMemberFunctionTablePtr_->find(functionName);

    if (mfIter == executeprimitiveEntryIstreamMemberFunctionTablePtr_->end())
    {
        FatalErrorIn
        (
            "functionEntry::execute"
            "(const word&, const dictionary&, primitiveEntry&, Istream&)"
        )   << "Unknown functionEntry '" << functionName
            << "' in " << is.name() << " near line " << is.lineNumber()
            << endl << endl
            << "Valid functionEntries are :" << endl
            << executeprimitiveEntryIstreamMemberFunctionTablePtr_->sortedToc()
            << exit(FatalError);
    }

    return mfIter()(parentDict, entry, is);
}
Foam::surfaceRegistry::surfaceRegistry
(
    const objectRegistry& obr,
    const word& surfName
)
:
    objectRegistry
    (
        IOobject
        (
            ( surfName.size() ? surfName : defaultName ),
            obr.time().timeName(),
            prefix,
            obr,
            IOobject::NO_READ,
            IOobject::NO_WRITE
        )
    )
{}
Example #4
0
// Construct from components
Foam::vtkMesh::vtkMesh
(
    fvMesh& baseMesh,
    const word& setName
)
:
    baseMesh_(baseMesh),
    subsetter_(baseMesh),
    setName_(setName)
{
    if (setName.size())
    {
        // Read cellSet using whole mesh
        cellSet currentSet(baseMesh_, setName_);

        // Set current subset
        subsetter_.setLargeCellSubset(currentSet);
    }
}
Example #5
0
		void map( line l) {
			int i=0;
			int j;
			//lower case the input
			for(i = 0; i<LINE; i++){
				if (l.buffer[i]== '\0')
					break;
  				l.buffer[i] = tolower(l.buffer[i]);
  			}
  			
  			for(i = 0; i<LINE; i++){
  				if(l.buffer[i]=='\0') {
  					break;
  				}
  				w.buffer[0]='\0'; //delete previus string
  				j=0;
  				while (i<LINE && j<WORD && islower(l.buffer[i])) {
  					w.buffer[j]=l.buffer[i]; //copy the word
  					j++; i++;
  				}
  				
  				if (j<WORD) 
  					w.buffer[j]='\0';
  				else
  					w.buffer[j-1]='\0';
  				
  				//if the string is not empty, emit
  				if (w.buffer[0]!='\0') {
  					#ifdef DEBUG
  					std::cout << "emitting: ";
  					w.print();
  					#endif
  					emit(&w,&one);
  				}
  				
  				if(i<LINE && l.buffer[i]=='\0') {
  					break;
  				}
  				
  			}	
		}
Example #6
0
Foam::string& Foam::stringOps::inplaceExpand
(
    string& s,
    const dictionary& dict,
    const bool allowEnvVars,
    const bool allowEmpty,
    const char sigil
)
{
    string::size_type begVar = 0;

    // Expand $VAR or ${VAR}
    // Repeat until nothing more is found
    while
    (
        (begVar = s.find(sigil, begVar)) != string::npos
     && begVar < s.size()-1
    )
    {
        if (begVar == 0 || s[begVar-1] != '\\')
        {
            if (s[begVar+1] == '{')
            {
                // Recursive variable expansion mode
                label stringStart = begVar;
                begVar += 2;
                string varValue
                (
                    expand
                    (
                        s,
                        begVar,
                        dict,
                        allowEnvVars,
                        allowEmpty
                    )
                );

                s.std::string::replace
                (
                    stringStart,
                    begVar - stringStart + 1,
                    varValue
                );

                begVar = stringStart+varValue.size();
            }
            else
            {
                string::iterator iter = s.begin() + begVar + 1;

                // more generous in accepting keywords than for env variables
                string::size_type endVar = begVar;
                while
                (
                    iter != s.end()
                 &&
                    (
                        isalnum(*iter)
                     || *iter == '.'
                     || *iter == ':'
                     || *iter == '_'
                    )
                )
                {
                    ++iter;
                    ++endVar;
                }

                const word varName
                (
                    s.substr
                    (
                        begVar + 1,
                        endVar - begVar
                    ),
                    false
                );

                string varValue
                (
                    getVariable
                    (
                        varName,
                        dict,
                        allowEnvVars,
                        allowEmpty
                    )
                );

                s.std::string::replace
                (
                    begVar,
                    varName.size()+1,
                    varValue
                );
                begVar += varValue.size();
            }
        }
        else
        {
            ++begVar;
        }
    }

    if (!s.empty())
    {
        if (s[0] == '~')
        {
            // Expand initial ~
            //   ~/        => home directory
            //   ~OpenFOAM => site/user OpenFOAM configuration directory
            //   ~user     => home directory for specified user

            string user;
            fileName file;

            if ((begVar = s.find('/')) != string::npos)
            {
                user = s.substr(1, begVar - 1);
                file = s.substr(begVar + 1);
            }
            else
            {
                user = s.substr(1);
            }

            // NB: be a bit lazy and expand ~unknownUser as an
            // empty string rather than leaving it untouched.
            // otherwise add extra test
            if (user == "OpenFOAM")
            {
                s = findEtcFile(file);
            }
            else
            {
                s = home(user)/file;
            }
        }
        else if (s[0] == '.')
        {
            // Expand a lone '.' and an initial './' into cwd
            if (s.size() == 1)
            {
                s = cwd();
            }
            else if (s[1] == '/')
            {
                s.std::string::replace(0, 1, cwd());
            }
        }
    }

    return s;
}
void setScoped
(
    dictionary& dict,
    const word& keyword,
    const bool overwrite,
    entry* d
)
{
    if (keyword[0] == ':')
    {
        // Go up to top level and recurse to find entries
        setScoped
        (
            const_cast<dictionary&>(dict.topDict()),
            keyword.substr(1, keyword.size()-1),
            overwrite,
            d
        );
        return;
    }
    else
    {
        string::size_type dotPos = keyword.find('.');

        if (dotPos == string::npos)
        {
            // Non-scoped lookup
            if (overwrite)
            {
                dict.set(d);
            }
            else
            {
                dict.add(d, false);
            }
            return;
        }
        else
        {
            if (dotPos == 0)
            {
                // Starting with a '.'. Go up for every 2nd '.' found

                const dictionary* dictPtr = &dict;

                string::size_type begVar = dotPos + 1;
                string::const_iterator iter =
                    keyword.begin() + begVar;
                string::size_type endVar = begVar;
                while
                (
                    iter != keyword.end()
                    && *iter == '.'
                )
                {
                    ++iter;
                    ++endVar;

                    // Go to parent
                    if (&dictPtr->parent() == &dictionary::null)
                    {
                        FatalIOErrorInFunction(dict)
                                << "No parent of current dictionary"
                                << " when searching for "
                                <<  keyword.substr
                                (
                                    begVar,
                                    keyword.size() - begVar
                                )
                                << exit(FatalIOError);
                    }
                    dictPtr = &dictPtr->parent();
                }

                setScoped
                (
                    const_cast<dictionary&>(*dictPtr),
                    keyword.substr(endVar),
                    overwrite,
                    d
                );
                return;
            }
            else
            {
                // Extract the first word
                word firstWord = keyword.substr(0, dotPos);

                const entry* entPtr = dict.lookupScopedEntryPtr
                                      (
                                          firstWord,
                                          false,          // Recursive
                                          false
                                      );

                if (!entPtr || !entPtr->isDict())
                {
                    FatalIOErrorInFunction(dict)
                            << "keyword " << firstWord
                            << " is undefined in dictionary "
                            << dict.name() << " or is not a dictionary"
                            << endl
                            << "Valid keywords are " << dict.keys()
                            << exit(FatalIOError);
                }

                const dictionary& firstDict = entPtr->dict();

                setScoped
                (
                    const_cast<dictionary&>(firstDict),
                    keyword.substr(dotPos, keyword.size()-dotPos),
                    overwrite,
                    d
                );
                return;
            }
        }
    }
}
Example #8
0
Foam::word Foam::Time::findInstance
(
    const fileName& dir,
    const word& name,
    const IOobject::readOption rOpt,
    const word& stopInstance
) const
{
    // Note: if name is empty, just check the directory itself

    // check the current time directory
    if
    (
        name.empty()
      ? isDir(path()/timeName()/dir)
      :
        (
            isFile(path()/timeName()/dir/name)
         && IOobject(name, timeName(), dir, *this).headerOk()
        )
    )
    {
        if (debug)
        {
            Info<< "Time::findInstance"
                "(const fileName&, const word&, const IOobject::readOption)"
                << " : found \"" << name
                << "\" in " << timeName()/dir
                << endl;
        }

        return timeName();
    }

    // Search back through the time directories to find the time
    // closest to and lower than current time

    instantList ts = times();
    label instanceI;

    for (instanceI = ts.size()-1; instanceI >= 0; --instanceI)
    {
        if (ts[instanceI].value() <= timeOutputValue())
        {
            break;
        }
    }

    // continue searching from here
    for (; instanceI >= 0; --instanceI)
    {
        if
        (
            name.empty()
          ? isDir(path()/ts[instanceI].name()/dir)
          :
            (
                isFile(path()/ts[instanceI].name()/dir/name)
             && IOobject(name, ts[instanceI].name(), dir, *this).headerOk()
            )
        )
        {
            if (debug)
            {
                Info<< "Time::findInstance"
                    "(const fileName&, const word&, const IOobject::readOption)"
                    << " : found \"" << name
                    << "\" in " << ts[instanceI].name()/dir
                    << endl;
            }

            return ts[instanceI].name();
        }

        // Check if hit minimum instance
        if (ts[instanceI].name() == stopInstance)
        {
            if (debug)
            {
                Info<< "Time::findInstance"
                    "(const fileName&, const word&"
                    ", const IOobject::readOption, const word&)"
                    << " : hit stopInstance " << stopInstance
                    << endl;
            }

            if (rOpt == IOobject::MUST_READ)
            {
                FatalErrorIn
                (
                    "Time::findInstance"
                    "(const fileName&, const word&"
                    ", const IOobject::readOption, const word&)"
                )   << "Cannot find file \"" << name << "\" in directory "
                    << dir << " in times " << timeName()
                    << " down to " << stopInstance
                    << exit(FatalError);
            }

            return ts[instanceI].name();
        }
    }

    // not in any of the time directories, try constant

    // Note. This needs to be a hard-coded constant, rather than the
    // constant function of the time, because the latter points to
    // the case constant directory in parallel cases

    if
    (
        name.empty()
      ? isDir(path()/constant()/dir)
      :
        (
            isFile(path()/constant()/dir/name)
         && IOobject(name, constant(), dir, *this).headerOk()
        )
    )
    {
        if (debug)
        {
            Info<< "Time::findInstance"
                "(const fileName&, const word&, const IOobject::readOption)"
                << " : found \"" << name
                << "\" in " << constant()/dir
                << endl;
        }

        return constant();
    }

    if (rOpt == IOobject::MUST_READ)
    {
        FatalErrorIn
        (
            "Time::findInstance"
            "(const fileName&, const word&, const IOobject::readOption)"
        )   << "Cannot find file \"" << name << "\" in directory "
            << dir << " in times " << timeName()
            << " down to " << constant()
            << exit(FatalError);
    }

    return constant();
}
Example #9
0
bool Foam::ping
(
    const word& destName,
    const label destPort,
    const label timeOut
)
{
    char *serverAddress;
    struct in_addr *ptr;
    struct hostent *hostPtr;
    volatile int sockfd;
    struct sockaddr_in destAddr;      // will hold the destination addr
    u_int addr;

    if ((hostPtr = gethostbyname(destName.c_str())) == NULL)
    {
        FatalErrorIn
        (
            "Foam::ping(const word&, const label)"
        )   << "gethostbyname error " << h_errno << " for host " << destName
            << abort(FatalError);
    }

    // Get first of the SLL of addresses
    serverAddress = *(hostPtr->h_addr_list);
    ptr = reinterpret_cast<struct in_addr*>(serverAddress);
    addr = ptr->s_addr;

    // Allocate socket
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        FatalErrorIn
        (
            "Foam::ping(const word&, const label)"
        )   << "socket error"
            << abort(FatalError);
    }

    // Fill sockaddr_in structure with dest address and port
    memset (reinterpret_cast<char *>(&destAddr), '\0', sizeof(destAddr));
    destAddr.sin_family = AF_INET;
    destAddr.sin_port = htons(ushort(destPort));
    destAddr.sin_addr.s_addr = addr;


    timer myTimer(timeOut);

    if (timedOut(myTimer))
    {
        // Setjmp from timer jumps back to here
        fdClose(sockfd);
        return false;
    }

    if
    (
        connect
        (
            sockfd,
            reinterpret_cast<struct sockaddr*>(&destAddr),
            sizeof(struct sockaddr)
        ) != 0
    )
    {
        // Connection refused. Check if network was actually used or not.

        int connectErr = errno;

        fdClose(sockfd);

        if (connectErr == ECONNREFUSED)
        {
            return true;
        }
        //perror("connect");

        return false;
    }

    fdClose(sockfd);

    return true;
}
labelList TerrainManager::walkBox
(
		label n,
		const word & HL,
		bool counterClockWise
) const{

	// preapre:
	labelList out(3,0);
	label counter = 0;
	label face    = counterClockWise ? Block::SOUTH : Block::WEST;
	bool isHigh   = HL.compare("H") == 0 ? true : false;

	// walk counter clock wise:
	if(counterClockWise){
		while(counter < n){

			// west:
			if(face == Block::WEST){
				out[2] = isHigh ? Block::NWH : Block::NWL;
				out[Block::Y]--;
				if(out[Block::Y] < 0){
					Info << "\nBLockManager: Error: walkBox overshoot." << endl;
					Info << "   n    = " << n << endl;
					Info << "   nmax = " << walkBoxMaximum() << endl;
					throw;
				}
			}

			// north:
			if(face == Block::NORTH){
				out[2] = isHigh ? Block::NEH : Block::NEL;
				out[Block::X]--;
				if(out[Block::X] < 0){
					out[Block::X]++;
					out[2] = isHigh ? Block::NWH : Block::NWL;
					face   = Block::WEST;
				}
			}

			// east:
			if(face == Block::EAST){
				out[2] = isHigh ? Block::SEH : Block::SEL;
				out[Block::Y]++;
				if(out[Block::Y] == blockNrs_[Block::Y] ){
					out[Block::Y]--;
					out[2] = isHigh ? Block::NEH : Block::NEL;
					face   = Block::NORTH;
				}
			}

			// south:
			if(face == Block::SOUTH){
				out[2] = isHigh ? Block::SWH : Block::SWL;
				out[Block::X]++;
				if(out[Block::X] == blockNrs_[Block::X] ){
					out[Block::X]--;
					out[2] = isHigh ? Block::SEH : Block::SEL;
					face   = Block::EAST;
				}
			}

			counter++;
		}
	}

	// else walk clockwise:
	else {
		while(counter < n){

			// south:
			if(face == Block::SOUTH){
				out[2] = isHigh ? Block::SEH : Block::SEL;
				out[Block::X]--;
				if(out[Block::X] < 0 ){
					Info << "\nBLockManager: Error: walkBox overshoot." << endl;
					Info << "   n    = " << n << endl;
					Info << "   nmax = " << walkBoxMaximum() << endl;
					throw;
				}
			}

			// east:
			if(face == Block::EAST){
				out[2] = isHigh ? Block::NEH : Block::NEL;
				out[Block::Y]--;
				if(out[Block::Y] < 0 ){
					out[Block::Y]++;
					out[2] = isHigh ? Block::SEH : Block::SEL;
					face   = Block::SOUTH;
				}
			}

			// north:
			if(face == Block::NORTH){
				out[2] = isHigh ? Block::NWH : Block::NWL;
				out[Block::X]++;
				if(out[Block::X] == blockNrs_[Block::X]){
					out[Block::X]--;
					out[2] = isHigh ? Block::NEH : Block::NEL;
					face   = Block::EAST;
				}
			}

			// west:
			if(face == Block::WEST){
				out[2] = isHigh ? Block::SWH : Block::SWL;
				out[Block::Y]++;
				if(out[Block::Y] == blockNrs_[Block::Y]){
					out[Block::Y]--;
					out[2] = isHigh ? Block::NWH : Block::NWL;
					face   = Block::NORTH;
				}
			}

			counter++;
		}
	}

	return out;
}
Example #11
0
Foam::instant::instant(const word& tname)
:
    value_(atof(tname.c_str())),
    name_(tname)
{}
void thermalBaffleFvPatchScalarField::createPatchMesh()
{

    const fvMesh& thisMesh = patch().boundaryMesh().mesh();

    word regionName = dict_.lookup("regionName");

    List<polyPatch*> regionPatches(3);
    List<word> patchNames(regionPatches.size());
    List<word> patchTypes(regionPatches.size());
    List<dictionary> dicts(regionPatches.size());

    patchNames[bottomPatchID] = word("bottom");
    patchNames[sidePatchID] = word("side");
    patchNames[topPatchID] = word("top");

    patchTypes[bottomPatchID] = mappedWallPolyPatch::typeName;
    patchTypes[topPatchID] = mappedWallPolyPatch::typeName;

    if (readBool(dict_.lookup("columnCells")))
    {
        patchTypes[sidePatchID] = emptyPolyPatch::typeName;
    }
    else
    {
        patchTypes[sidePatchID] = polyPatch::typeName;
    }

    const mappedPatchBase& mpp =
        refCast<const mappedPatchBase>(patch().patch());

    const word coupleGroup(mpp.coupleGroup());

    wordList inGroups(1);
    inGroups[0] = coupleGroup;

    dicts[bottomPatchID].add("coupleGroup", coupleGroup);
    dicts[bottomPatchID].add("inGroups", inGroups);
    dicts[bottomPatchID].add("sampleMode", mpp.sampleModeNames_[mpp.mode()]);

    const label sepPos = coupleGroup.find('_');

    const word coupleGroupSlave = coupleGroup(0, sepPos) + "_slave";

    inGroups[0] = coupleGroupSlave;
    dicts[topPatchID].add("coupleGroup", coupleGroupSlave);
    dicts[topPatchID].add("inGroups", inGroups);
    dicts[topPatchID].add("sampleMode", mpp.sampleModeNames_[mpp.mode()]);


    forAll (regionPatches, patchI)
    {
        dictionary&  patchDict = dicts[patchI];
        patchDict.set("nFaces", 0);
        patchDict.set("startFace", 0);

        regionPatches[patchI] = polyPatch::New
        (
            patchTypes[patchI],
            patchNames[patchI],
            dicts[patchI],
            patchI,
            thisMesh.boundaryMesh()
        ).ptr();
    }
int main(int argc, char *argv[])
{
    timeSelector::addOptions();
#   include "addRegionOption.H"
    argList::validArgs.append("patchName");
    argList::validArgs.append("firstPatchNumber");
    argList::validArgs.append("lastPatchNumber");
#   include "setRootCase.H"
#   include "createTime.H"
    instantList timeDirs = timeSelector::select0(runTime, args);
#   include "createNamedMesh.H"

    word patchName = args[1];
    const word charfirstPatchNumber = args[2];
    const word charlastPatchNumber = args[3];
    
    char* pEnd;
    int firstPatchNumber = strtod(charfirstPatchNumber.c_str(), &pEnd);  
    int lastPatchNumber  = strtod(charlastPatchNumber.c_str(), &pEnd);  

    Info << "Patch name: " << patchName << " id = ["<< charfirstPatchNumber <<":"<< charlastPatchNumber <<"]" << endl;
    Info << " " << endl;	

    OFstream* outputFile;
    fileName outpuFilename(mesh.time().path()/"wettedAreaPatch"+patchName+charfirstPatchNumber+"-"+charlastPatchNumber);
    outputFile =  new OFstream(outpuFilename);
 
    *outputFile << "#Time " << tab << "totalWettedArea" << tab;
    for(label id=firstPatchNumber; id<=lastPatchNumber; id++)
    {
    	*outputFile  << "wettedArea-" << id << tab;
    }
    *outputFile << endl;	

    forAll(timeDirs, timeI)
    {
        runTime.setTime(timeDirs[timeI], timeI);

        Info<< "Time = " << runTime.timeName() << endl;

        mesh.readUpdate();
	
	// Read gas density
	IOobject alphaheader
	(
		"alpha.water",
		runTime.timeName(),
		mesh,
		IOobject::MUST_READ	
	);

	Info<< " Reading alpha" << endl;
	volScalarField alpha(alphaheader,mesh);	
	
	scalar totalWettedArea(0);
	scalarField wettedArea(lastPatchNumber+1,scalar(0));
	scalar totalSurfaceArea(0);
	
	for(label id=firstPatchNumber; id<=lastPatchNumber; id++)
	{ 
		// Calculate wetted area on the plane
		word patchNumber;
		std::stringstream ss;
		ss << id;
		patchNumber = ss.str();
		
		const label patchI = mesh.boundaryMesh().findPatchID(patchName+patchNumber);	

        	if (patchI < 0)
        	{
        		FatalError
                	<< "Unable to find patch " << patchName << nl
                	<< exit(FatalError);
        	}

		wettedArea[id] = gSum(alpha.boundaryField()[patchI]*mesh.magSf().boundaryField()[patchI]);
		totalWettedArea += wettedArea[id];
		totalSurfaceArea += gSum(mesh.magSf().boundaryField()[patchI]);
	}

    	if(Pstream::master()) //Write only if master
    	{
    		
		Info<< " Writing mass flow rates into the file " << outpuFilename << endl;
		*outputFile	<< alpha.mesh().time().value()  << tab 
				<< totalWettedArea		<< tab;
		for(label id=firstPatchNumber; id<=lastPatchNumber; id++)
		{ 	
                	*outputFile << wettedArea[id]	<< tab << " "; 
                }		
		*outputFile	<< totalSurfaceArea << endl;

    	}
        
	Info << " " << endl;
    }
Example #14
0
bool
sMap::Save(const char* filename, IFileSystem& fs)
{
  // do some preliminary checking...
  // the start layer should not have parallax
  m_Layers[m_StartLayer].EnableParallax(false);

  IFile* file = fs.Open(filename, IFileSystem::write);
  if (file == NULL)
    return false;

  // write the map header
  MAP_HEADER header;
  memset(&header, 0, sizeof(header));
  memcpy(header.signature, ".rmp", 4);
  header.version        = 1;
  header.num_layers     = m_Layers.size();
  header.num_entities   = m_Entities.size();
  header.startx         = m_StartX;
  header.starty         = m_StartY;
  header.startlayer     = m_StartLayer;
  header.startdirection = m_StartDirection;
  header.num_strings    = 9;
  file->Write(&header, sizeof(header));

  // write the strings
  WriteMapString(file, "");  // OBSOLETE
  WriteMapString(file, m_MusicFile.c_str());
  WriteMapString(file, "");  // OBSOLETE
  WriteMapString(file, m_EntryScript.c_str());
  WriteMapString(file, m_ExitScript.c_str());
  WriteMapString(file, m_EdgeScripts[0].c_str());
  WriteMapString(file, m_EdgeScripts[1].c_str());
  WriteMapString(file, m_EdgeScripts[2].c_str());
  WriteMapString(file, m_EdgeScripts[3].c_str());
 
  // write layers
  for (int i = 0; i < m_Layers.size(); i++)
  {
    const sLayer& layer = m_Layers[i];
    const sObstructionMap& obstructions = layer.GetObstructionMap();

    // write the header
    LAYER_HEADER lh;
    memset(&lh, 0, sizeof(lh));
    lh.width        = m_Layers[i].GetWidth();
    lh.height       = m_Layers[i].GetHeight();
    lh.flags        = (m_Layers[i].IsVisible() ? 0 : 1) | (m_Layers[i].HasParallax() ? 2 : 0);
    lh.parallax_x   = m_Layers[i].GetXParallax();
    lh.parallax_y   = m_Layers[i].GetYParallax();
    lh.scrolling_x  = m_Layers[i].GetXScrolling();
    lh.scrolling_y  = m_Layers[i].GetYScrolling();
    lh.num_segments = obstructions.GetNumSegments();
    lh.reflective   = (m_Layers[i].IsReflective() ? 1 : 0);
    file->Write(&lh, sizeof(lh));

    // write the layer name
    WriteMapString(file, m_Layers[i].GetName());

    // write the layer data
    for (int iy = 0; iy < m_Layers[i].GetHeight(); iy++)
      for (int ix = 0; ix < m_Layers[i].GetWidth(); ix++)
      {
        word w = m_Layers[i].GetTile(ix, iy);
        file->Write(&w, 2);
      }

    // write the obstruction map
    for (int i = 0; i < obstructions.GetNumSegments(); i++) {
      const sObstructionMap::Segment& s = obstructions.GetSegment(i);

      dword x1 = s.x1;
      dword y1 = s.y1;
      dword x2 = s.x2;
      dword y2 = s.y2;

      file->Write(&x1, sizeof(dword));
      file->Write(&y1, sizeof(dword));
      file->Write(&x2, sizeof(dword));
      file->Write(&y2, sizeof(dword));
    }

  } // end for layer

  // write entities
  for (int i = 0; i < m_Entities.size(); i++)
  {
    // write the header
    ENTITY_HEADER eh;
    memset(&eh, 0, sizeof(eh));
    eh.mapx  = m_Entities[i]->x;
    eh.mapy  = m_Entities[i]->y;
    eh.layer = m_Entities[i]->layer;
    switch (m_Entities[i]->GetEntityType())
    {
      case sEntity::PERSON:  eh.type = 1; break;
      case sEntity::TRIGGER: eh.type = 2; break;
    }
    file->Write(&eh, sizeof(eh));

    // write the entity data
    switch (m_Entities[i]->GetEntityType())
    {
      case sEntity::PERSON:
      {
        sPersonEntity* person = (sPersonEntity*)m_Entities[i];

        WriteMapString(file, person->name.c_str());
        WriteMapString(file, person->spriteset.c_str());

        WriteMapWord(file, 5);  // four scripts
        
        // scripts
        WriteMapString(file, person->script_create.c_str());
        WriteMapString(file, person->script_destroy.c_str());
        WriteMapString(file, person->script_activate_touch.c_str());
        WriteMapString(file, person->script_activate_talk.c_str());
        WriteMapString(file, person->script_generate_commands.c_str());

        // reserved
        for (int i = 0; i < 16; i++) {
          WriteMapByte(file, 0);
        }

        break;
      }

      case sEntity::TRIGGER:
      {
        sTriggerEntity* trigger = (sTriggerEntity*)m_Entities[i];
        WriteMapString(file, trigger->script.c_str());
        break;
      }

    } // end switch entity type
  } // end for entity

  // write the zones
  for (int i = 0; i < m_Zones.size(); i++)
  {
    ZONE_HEADER zh;

    memset(&zh, 0, sizeof(zh));
    zh.x1 = m_Zones[i].x1;
    zh.y1 = m_Zones[i].y1;
    zh.x2 = m_Zones[i].x2;
    zh.y2 = m_Zones[i].y2;
    zh.layer = m_Zones[i].layer;
    zh.reactivate_in_num_steps = m_Zones[i].reactivate_in_num_steps;

    file->Write(&zh, sizeof(zh));
    WriteMapString(file, m_Zones[i].script.c_str());
  } // end for zones

  // save the tileset
  if (!m_Tileset.SaveToFile(file)) {
    file->Close();
    return false;
  }

  file->Close();
  return true;
}
Example #15
0
bool CNNM2ECC::DeleteEccEntity(word id)
{
	return DeleteEntity(id.getword());
}
Example #16
0
void Foam::MeshedSurfaceProxy<Face>::write
(
    const Time& t,
    const word& surfName
) const
{
    // the surface name to be used
    word name(surfName.size() ? surfName : surfaceRegistry::defaultName);

    if (debug)
    {
        Info<< "MeshedSurfaceProxy::write"
            "(const Time&, const word&) : "
            "writing to " << name
            << endl;
    }


    // the local location
    const fileName objectDir
    (
        t.timePath()/surfaceRegistry::prefix/name/surfMesh::meshSubDir
    );

    if (!isDir(objectDir))
    {
        mkDir(objectDir);
    }


    // write surfMesh/points
    {
        pointIOField io
        (
            IOobject
            (
                "points",
                t.timeName(),
                surfMesh::meshSubDir,
                t,
                IOobject::NO_READ,
                IOobject::NO_WRITE,
                false
            )
        );

        OFstream os
        (
            objectDir/io.name(),
            t.writeFormat(),
            IOstream::currentVersion,
            t.writeCompression()
        );

        io.writeHeader(os);

        os  << this->points();

        io.writeEndDivider(os);
    }


    // write surfMesh/faces
    {
        faceCompactIOList io
        (
            IOobject
            (
                "faces",
                t.timeName(),
                surfMesh::meshSubDir,
                t,
                IOobject::NO_READ,
                IOobject::NO_WRITE,
                false
            )
        );

        OFstream os
        (
            objectDir/io.name(),
            t.writeFormat(),
            IOstream::currentVersion,
            t.writeCompression()
        );
        io.writeHeader(os);

        if (this->useFaceMap())
        {
            // this is really a bit annoying (and wasteful) but no other way
            os  << reorder(this->faceMap(), this->faces());
        }
        else
        {
            os  << this->faces();
        }

        io.writeEndDivider(os);
    }


    // write surfMesh/surfZones
    {
        surfZoneIOList io
        (
            IOobject
            (
                "surfZones",
                t.timeName(),
                surfMesh::meshSubDir,
                t,
                IOobject::NO_READ,
                IOobject::NO_WRITE,
                false
            )
        );

        // write as ascii
        OFstream os(objectDir/io.name());
        io.writeHeader(os);

        os  << this->surfZones();

        io.writeEndDivider(os);
    }

}
 void LuaFoamDictionaryParserDriver::add(const word& name,scalar value)
 {
     lua_pushnumber(lua(),value);
     lua_setfield(lua(),-2,name.c_str());
 }
Example #18
0
bool Foam::env(const word& envName)
{
    return getenv(envName.c_str()) != NULL;
}
 void LuaFoamDictionaryParserDriver::add(const word& name,label value)
 {
     lua_pushinteger(lua(),value);
     lua_setfield(lua(),-2,name.c_str());
 }
Example #20
0
// Return components following the IOobject requirements
//
// behaviour
//    input               IOobject(instance, local, name)
//    -----               ------
//    "foo"               ("", "", "foo")
//    "foo/bar"           ("foo", "", "bar")
//    "/XXX"              ERROR - no absolute path
//    "foo/bar/"          ERROR - no name
//    "foo/xxx/bar"       ("foo", "xxx", "bar")
//    "foo/xxx/yyy/bar"   ("foo", "xxx/yyy", "bar")
bool Foam::IOobject::IOobject::fileNameComponents
(
    const fileName& path,
    fileName& instance,
    fileName& local,
    word& name
)
{
    instance.clear();
    local.clear();
    name.clear();

    // called with directory
    if (isDir(path))
    {
        WarningIn("IOobject::fileNameComponents(const fileName&, ...)")
            << " called with directory: " << path << "\n";
        return false;
    }

    string::size_type first = path.find('/');

    if (first == 0)
    {
        // called with absolute path
        WarningIn("IOobject::fileNameComponents(const fileName&, ...)")
            << "called with absolute path: " << path << "\n";
        return false;
    }

    if (first == string::npos)
    {
        // no '/' found - no instance or local

        // check afterwards
        name.string::operator=(path);
    }
    else
    {
        instance = path.substr(0, first);

        string::size_type last = path.rfind('/');
        if (last > first)
        {
            // with local
            local = path.substr(first+1, last-first-1);
        }

        // check afterwards
        name.string::operator=(path.substr(last+1));
    }


    // check for valid (and stripped) name, regardless of the debug level
    if (name.empty() || string::stripInvalid<word>(name))
    {
        WarningIn("IOobject::fileNameComponents(const fileName&, ...)")
            << "has invalid word for name: \"" << name
            << "\"\nwhile processing path: " << path << "\n";
        return false;
    }

    return true;
}
 void LuaFoamDictionaryParserDriver::add(const word& name,bool value)
 {
     lua_pushboolean(lua(),value);
     lua_setfield(lua(),-2,name.c_str());
 }
Foam::autoPtr<Foam::solidChemistryModel> Foam::solidChemistryModel::New
(
    const fvMesh& mesh
)
{
    IOdictionary chemistryPropertiesDict
    (
        IOobject
        (
            "chemistryProperties",
            mesh.time().constant(),
            mesh,
            IOobject::MUST_READ,
            IOobject::NO_WRITE,
            false
        )
    );

    const word userModel(chemistryPropertiesDict.lookup("solidChemistryModel"));

    const word ODEModelName(chemistryPropertiesDict.lookup("chemistrySolver"));
    const word gasThermoName(chemistryPropertiesDict.lookup("gasThermoModel"));

    // construct chemistry model type name by inserting first template argument
    const label tempOpen = userModel.find('<');
    const label tempClose = userModel.find('>');

    const word className = userModel(0, tempOpen);
    const word thermoTypeName =
        userModel(tempOpen + 1, tempClose - tempOpen - 1);

    const word modelType =
        ODEModelName + '<' + className
      + '<' + typeName + ',' + thermoTypeName + ',' + gasThermoName + ">>";


    if (debug)
    {
        Info<< "Selecting solidChemistryModel " << modelType << endl;
    }
    else
    {
        Info<< "Selecting solidChemistryModel " << userModel + gasThermoName
            << endl;
    }

    fvMeshConstructorTable::iterator cstrIter =
        fvMeshConstructorTablePtr_->find(modelType);

    if (cstrIter == fvMeshConstructorTablePtr_->end())
    {
        if (debug)
        {
            FatalErrorIn("solidChemistryModel::New(const mesh&)")
                << "Unknown solidChemistryModel type "
                << modelType << nl << nl
                << "Valid solidChemistryModel types are:" << nl
                << fvMeshConstructorTablePtr_->sortedToc() << nl
                << exit(FatalError);
        }
        else
        {
            wordList models = fvMeshConstructorTablePtr_->sortedToc();
            forAll(models, i)
            {
                models[i] = models[i].replace(typeName + ',', "");
            }

            FatalErrorIn("solidChemistryModel::New(const mesh&)")
                << "Unknown solidChemistryModel type "
                << userModel << nl << nl
                << "Valid solidChemistryModel types are:" << nl
                << models << nl
                << exit(FatalError);
        }
    }
 void LuaFoamDictionaryParserDriver::add(const word& name,const string &value)
 {
     lua_pushstring(lua(),value.c_str());
     lua_setfield(lua(),-2,name.c_str());
 }