예제 #1
0
PlugIterator::PlugIterator(const PlugIterator &iterator)
{
	Check_Object(&iterator);
	plug = iterator.plug;
   classToIterate = iterator.classToIterate;
	currentLink = iterator.currentLink;
	NextNode();
}
예제 #2
0
void OgreXmlSerializer::ReadAnimationTracks(Animation *dest)
{
    NextNode();
    while(m_currentNodeName == nnTrack)
    {
        VertexAnimationTrack track;
        track.type = VertexAnimationTrack::VAT_TRANSFORM;
        track.boneName = ReadAttribute<std::string>("bone");

        if (NextNode() != nnKeyFrames) {
            throw DeadlyImportError(Formatter::format() << "No <keyframes> found in <track> " << dest->name);
        }

        ReadAnimationKeyFrames(dest, &track);

        dest->tracks.push_back(track);
    }
}
예제 #3
0
void OgreXmlSerializer::ReadGeometry(VertexDataXml *dest)
{
    dest->count = ReadAttribute<uint32_t>("vertexcount");
    DefaultLogger::get()->debug(Formatter::format() << "  - Reading geometry of " << dest->count << " vertices");

    NextNode();
    while(m_currentNodeName == nnVertexBuffer) {
        ReadGeometryVertexBuffer(dest);
    }
}
예제 #4
0
int	CMorphAutomat::FindStringAndPassAnnotChar (const string& Text, size_t TextPos) const
{
    size_t TextLength = Text.length();
    int r = 0;
    for (size_t i=TextPos; i<TextLength; i++)
    {
        int nd =  NextNode(r,(BYTE)Text[i]);

        if (nd ==  -1)
        {
            return -1;
        }
        r = nd;
    };
    //assert ( r != -1);
    //  passing annotation char

    return NextNode(r,m_AnnotChar);
};
예제 #5
0
//
//#############################################################################
// PlugIterator
//#############################################################################
//
PlugIterator::PlugIterator(
	Plug *plug,
   RegisteredClass::ClassID class_to_iterate
)
{
	Check_Object(plug);
	this->plug = plug;
   classToIterate = class_to_iterate;
	currentLink = plug->linkHead;
	NextNode();
}
예제 #6
0
파일: resolver.cpp 프로젝트: 400dama/USD
bool 
Usd_Resolver::NextLayer() {
    if (not IsValid())
        return true;

    if (++_curLayer == _lastLayer) {
        // We hit the last layer in this LayerStack, move on to the next node.
        NextNode();
        return true;
    }
    return false;
}
예제 #7
0
void
nsContentIterator::Next()
{
  if (mIsDone || !mCurNode) 
    return;

  if (mCurNode == mLast) 
  {
    mIsDone = PR_TRUE;
    return;
  }

  mCurNode = NextNode(mCurNode, &mIndexes);
}
예제 #8
0
void csNodeIterator::SkipWrongClassname ()
{
  if (Classname)
    while (Iterator->HasNext ())
    {
      csRef<iKeyValuePair> KeyVal (CS::GetNamedChildObject<iKeyValuePair> (
        CurrentNode->QueryObject (), "classname"));
      if (KeyVal)
      {
        bool done = !strcmp (KeyVal->GetValue (), Classname);
	if (done) return;
      }
      NextNode ();
    }
}
예제 #9
0
	//--------------------------------------------------------------------------------
	std::string Serializer::ReadLevel()
	{
		LoadFirstItem();
		
		std::string levelscript;

		do {
			if(CheckAttribute("type", "gameobject") || CheckAttribute("type", "archetype"))
				g_FACTORY->Create(*this, GetElementName());
			else if(CheckAttribute("type", "script"))
				levelscript = GetAttributeString("name");
		} while(NextNode());

		return levelscript;
	}
예제 #10
0
파일: SOUND.C 프로젝트: ColanderCombo/SCI16
global void RestoreAllSounds() {
	Sound		*sn;
	Obj		*soundObj;
	Handle	sHandle;
	int		soundId;

	/* For every node on the sound list, load the resource in
	 *	the s_number property.  If the sState property of the node
	 *	is non-zero, restart the sound using the SRestore function
	 *	in MIDI.S
	 */

	sn = (Sound *) Native(FirstNode(&soundList));

	while(sn) {
		soundObj = (Obj *) Native(GetKey(Pseudo(sn)));
		soundId = GetProperty (soundObj, s_number);
		if(sn->sSample) {
/* put sample stuff here */
		} else {
			if(soundId) {
				ResLoad(RES_SOUND,soundId);
			}
			if(sn->sState) {
				sHandle = ResLoad(RES_SOUND,soundId);
	
				CriticalHandle(sHandle,TRUE);
				ResLock(RES_SOUND,soundId,TRUE);
		
				SetProperty(soundObj,s_handle,(uint) Pseudo(sHandle));
				sn->sPointer = (char far *) sHandle;
				DoSound(SRestore,(char far *) sn);
//				if(sn->sSample) {
//					LockHandle(sHandle);
//				}

				UpdateCues(soundObj);
			}
		}
		
		sn = (Sound *) Native(NextNode(Pseudo(sn)));
	}

	/* Reset the default reverb mode
	 */

	DoSound(SSetReverb,reverbDefault);
}
예제 #11
0
//
//#############################################################################
// ReadAndNextImplementation
//#############################################################################
//
void*
	PlugIterator::ReadAndNextImplementation()
{
	Check_Object(this);
	if (currentLink != NULL)
	{
		Node *node;

		Check_Object(currentLink);
		Check_Object(currentLink->socket);
		node = currentLink->socket->GetReleaseNode();
		currentLink = currentLink->nextLink;
		NextNode();
		return node;
	}
	return NULL;
}
예제 #12
0
std::string &OgreXmlSerializer::SkipCurrentNode()
{
#if (OGRE_XML_SERIALIZER_DEBUG == 1)
    DefaultLogger::get()->debug("Skipping node <" + m_currentNodeName + ">");
#endif

    for(;;)
    {
        if (!m_reader->read())
        {
            m_currentNodeName = "";
            return m_currentNodeName;
        }
        if (m_reader->getNodeType() != irr::io::EXN_ELEMENT_END)
            continue;
        else if (std::string(m_reader->getNodeName()) == m_currentNodeName)
            break;
    }
    return NextNode();
}
예제 #13
0
int DumpList(listPtr List, ListDumpFunc DataDump) 
/* Print List data using the DataDump function for Node Data Elements */
{
  int Count;
  listnodePtr Position;

  if (List == NULL) return LLIST_BADVALUE;

  Position = List->Current;
  List->Current = List->Head;
  
  for (Count = 1; Count <= List->Size; Count++)
    {
      DataDump(GetNodeData(List->Current));    
      NextNode(List);
    }

  List->Current = Position;

  return LLIST_NOERROR;
}
예제 #14
0
파일: linklist.c 프로젝트: Fran89/seiscomp3
/*---------------------------------------------------------------------*/
NODE *DestroyNode(NODE * node)
{
    NODE *next;

    ASSERT(node != NULL);
    ASSERT(node->next != NULL);
    ASSERT(node->prev != NULL);

    /* Save pointer to next node, this will be NULL if this is the last node */
    next = NextNode(node);

    /* Unlink this node */
    node->prev->next = node->next;
    node->next->prev = node->prev;

    /* Release data memory */
    if (node->data != NULL) {

#ifdef _DEBUG
        memset(node->data, GARBAGE_BYTE, (size_t) node->length);
#endif

        free(node->data);
        node->data = NULL;
        node->length = 0;
    }

    /* Release node memory */

#ifdef _DEBUG
    memset(node, GARBAGE_BYTE, sizeof(NODE));
#endif

    free(node);
    node = NULL;

    _allocated_nodes--;

    return (next);
}
예제 #15
0
  static void BuildLoop(ThreadState* thread_state)
  {
    BuildQueue        *queue = thread_state->m_Queue;
    ConditionVariable *cv    = &queue->m_WorkAvailable;
    Mutex             *mutex = &queue->m_Lock;

    MutexLock(mutex);

    while (ShouldKeepBuilding(queue, thread_state->m_ThreadIndex))
    {
      if (NodeState* node = NextNode(queue))
      {
        AdvanceNode(queue, thread_state, node, mutex);
      }
      else
      {
        CondWait(cv, mutex);
      }
    }

    MutexUnlock(mutex);

    Log(kSpam, "build thread %d exiting\n", thread_state->m_ThreadIndex);
  }
예제 #16
0
void PathPlan(Point Start,Point End,Point LastWay[],int nLastWayPts,Obstacle obs[],int nObs,Point PathWay[])
{
    ProcessIndex = CurrIndex = 0;
    if(!nodes)
        nodes = (Node *)calloc(10000,sizeof(Node));
    else
        memset(nodes,0,sizeof(Node)*10000);

    if(!BiasedWay)
        BiasedWay = (Point *)calloc(100,sizeof(Point));
    else
        memset(BiasedWay,0,sizeof(Point)*100);

    if(!NewWay)
        NewWay = (Point *)calloc(100,sizeof(Point));
    else
        memset(NewWay,0,sizeof(Point)*100);

  float NewPathLength = 0,LastPathLength = 0,checkTheta = 0,checkRadius = 0;
  int saveIndex = -1,i,nBiasedWay =0,count = 0,nNewWay = 0;
  srand(time(NULL));
  Point NewWay[100],BiasedWay[100];
    
    for(i = 0;i < nObs ;i++)
    {
        if((checkRadius = (End.x - obs[i].x)*(End.x - obs[i].x) + (End.y - obs[i].y)*(End.y - obs[i].y)) < obs[i].radius*obs[i].radius)
        {
            checkTheta = rand()%90;
            checkRadius = sqrt(checkRadius) + 40;
            if(End.x >= obs[i].x) End.x = (obs[i].x + checkRadius*cos(checkTheta*(DEG_TO_RAD)) >= 700) ? obs[i].x - checkRadius*cos(checkTheta*(DEG_TO_RAD)) : obs[i].x + checkRadius*cos(checkTheta*(DEG_TO_RAD)); 
            if(End.y >= obs[i].y) End.y = (obs[i].y + checkRadius*sin(checkTheta*(DEG_TO_RAD)) >= 500) ? obs[i].y - checkRadius*sin(checkTheta*(DEG_TO_RAD)) : obs[i].y + checkRadius*sin(checkTheta*(DEG_TO_RAD)); 
        }
        if((Start.x - obs[i].x)*(Start.x - obs[i].x) + (Start.y - obs[i].y)*(Start.y - obs[i].y) < obs[i].radius * obs[i].radius)
            obs[i].radius = 0.66*obs[i].radius;
    }
  for(i = 0; i < nLastWayPts; i++)
  {
    if((Start.x - LastWay[i].x)*(Start.x - LastWay[i].x) + (Start.y - LastWay[i].y)*(Start.y - LastWay[i].y) < DISTANCE_THRESHOLD_2)
    {
      saveIndex = i;
            break;
    }
  }

  nodes[0].Length = 0;
  nodes[0].point = Start;
  nodes[0].ParentIndex = -1;

    if(nLastWayPts > 0)
        LastPathLength += sqrt((Start.x-LastWay[0].x)*(Start.x-LastWay[0].x)+(Start.y-LastWay[0].y)*(Start.y-LastWay[0].y));
    for(i = 0; i < nLastWayPts-1; i++)
    {
        LastPathLength += sqrt((LastWay[i].x-LastWay[i+1].x)*(LastWay[i].x-LastWay[i+1].x)+(LastWay[i].y-LastWay[i+1].y)*(LastWay[i].y-LastWay[i+1].y));
    }

    if(nLastWayPts > 0)
    {
      if(saveIndex == -1)
        {
        if(Connect(Start,LastWay[0],obs,nObs))
            {
          nodes[++CurrIndex].point = LastWay[0];
          nodes[CurrIndex].ParentIndex = ProcessIndex;
          nodes[CurrIndex].Length += nodes[ProcessIndex].Length + sqrt((nodes[ProcessIndex].point.x - LastWay[0].x)*(nodes[ProcessIndex].point.x - LastWay[0].x) + (nodes[ProcessIndex].point.y - LastWay[0].y)*(nodes[ProcessIndex].point.y - LastWay[0].y));
          ProcessIndex++;
            }
          
        for(i = 0; i < nLastWayPts-1; i++)
        {
          if(Connect(LastWay[i],LastWay[i+1],obs,nObs))
          {
            nodes[++CurrIndex].point = LastWay[i+1];
            nodes[CurrIndex].ParentIndex = ProcessIndex;
            nodes[CurrIndex].Length += nodes[ProcessIndex].Length + sqrt((nodes[ProcessIndex].point.x - nodes[CurrIndex].point.x)*(nodes[ProcessIndex].point.x - nodes[CurrIndex].point.x) + (nodes[ProcessIndex].point.y - nodes[CurrIndex].point.y)*(nodes[ProcessIndex].point.y - nodes[CurrIndex].point.y));
            ProcessIndex++;
          }
          else
            break;
        }

        while(CurrIndex < 10000 && !Connect(nodes[ProcessIndex].point,End,obs,nObs) && ProcessIndex <= CurrIndex)
        {
          if(NextNode(nodes[ProcessIndex].point,End,obs,nObs) == -1)
          {
            ProcessIndex++;
          }
          else
            break;
        }
        nBiasedWay = 0;
        BiasedWay[nBiasedWay] = nodes[CurrIndex].point;
        LastPathLength = nodes[CurrIndex].Length + sqrt((nodes[CurrIndex].point.x-End.x)*(nodes[CurrIndex].point.x-End.x) + (nodes[CurrIndex].point.y-End.y)*(nodes[CurrIndex].point.y-End.y));
        nBiasedWay++;
        i = nodes[CurrIndex].ParentIndex;
        while(i != -1)
        {
          BiasedWay[nBiasedWay++] = nodes[i].point;
          i = nodes[i].ParentIndex;
        }
        }
        else
      {
        i = saveIndex;
        LastWay[i] = Start;
        for(i = saveIndex; i < nLastWayPts-1; i++)
        {
          if(Connect(LastWay[i],LastWay[i+1],obs,nObs))
          {
            nodes[++CurrIndex].point = LastWay[i+1];
            nodes[CurrIndex].ParentIndex = ProcessIndex;
            nodes[CurrIndex].Length += nodes[ProcessIndex].Length + sqrt((nodes[ProcessIndex].point.x - nodes[CurrIndex].point.x)*(nodes[ProcessIndex].point.x - nodes[CurrIndex].point.x) + (nodes[ProcessIndex].point.y - nodes[CurrIndex].point.y)*(nodes[ProcessIndex].point.y - nodes[CurrIndex].point.y));
            ProcessIndex++;
          }
          else
            break;
        }

        while(CurrIndex < 10000 && !Connect(nodes[ProcessIndex].point,End,obs,nObs) && ProcessIndex <= CurrIndex)
        {
          if(NextNode(nodes[ProcessIndex].point,End,obs,nObs) == -1)
          {
            ProcessIndex++;
          }
          else
            break;
        }
        nBiasedWay = 0;
        BiasedWay[nBiasedWay] = nodes[CurrIndex].point;
        LastPathLength = nodes[CurrIndex].Length + sqrt((nodes[CurrIndex].point.x-End.x)*(nodes[CurrIndex].point.x-End.x) + (nodes[CurrIndex].point.y-End.y)*(nodes[CurrIndex].point.y-End.y));
        nBiasedWay++;
        i = nodes[CurrIndex].ParentIndex;
        while(i != -1)
        {
          BiasedWay[nBiasedWay++] = nodes[i].point;
          i = nodes[i].ParentIndex;
        }
      }
    }
    
    memset(nodes,0,sizeof(Node)*10000);
  ProcessIndex = CurrIndex = 0;
  nodes[0].Length = 0;
  nodes[0].ParentIndex = -1;
  nodes[0].point = Start;

  while(CurrIndex < 10000 && !Connect(nodes[ProcessIndex].point,End,obs,nObs) && ProcessIndex <= CurrIndex)
  {
    if(NextNode(nodes[ProcessIndex].point,End,obs,nObs) == -1)
    {
        ProcessIndex++;
    }
    else
      break;
  }

  nNewWay = 0;
  NewWay[nNewWay] = nodes[CurrIndex].point;
  NewPathLength = nodes[CurrIndex].Length + sqrt((nodes[CurrIndex].point.x-End.x)*(nodes[CurrIndex].point.x-End.x) + (nodes[CurrIndex].point.y-End.y)*(nodes[CurrIndex].point.y-End.y));
  nNewWay++;
  i = nodes[CurrIndex].ParentIndex;
  while(i != -1)
  {
    NewWay[nNewWay++] = nodes[i].point;
    i = nodes[i].ParentIndex;
  }

  if(nLastWayPts == 0 || NewPathLength <= HYSTERESIS_PATH_GEN*LastPathLength)
  {
    for(i = 1;i < nNewWay;i++)
    {
      PathWay[i-1] = NewWay[nNewWay - i-1];
    }
  }
  else
  {
    for(i = 1;i < nBiasedWay;i++)
    {
        PathWay[i-1] = BiasedWay[nBiasedWay - i-1];
//           PathWay[i] = LastWay[i];
    }
  }
  PathWay[i-1] = End;

}
예제 #17
0
파일: state.c 프로젝트: Fran89/seiscomp3
/*---------------------------------------------------------------------*/
BOOL WriteState(H_ARCHIVE harchive)
{
    UINT32 i;
    STREAM *stream;
    NODE *node;

    if (!ValidateHandle(harchive))
        return (FALSE);

    _archive[harchive].last_error = ARC_NO_ERROR;
    _archive_error = ARC_NO_ERROR;

    if (_archive[harchive].access != ARC_WRITE) {
        _archive[harchive].last_error = ARC_PERMISSION_DENIED;
        return (FALSE);
    }

    /* Go to top of file */
    if (!FileRewind(_archive[harchive].file)) {
        _archive[harchive].last_error = ARC_FILE_IO_ERROR;
        return (FALSE);
    }

    ArchiveLog(ARC_LOG_MAXIMUM, "Writing state file: %s", _archive[harchive].filespec);

    /* Write state structure */
    if (SerializedWrite(&_archive[harchive].state, _state_template,
            _archive[harchive].file) == VOID_UINT32) {
        ArchiveLog(ARC_LOG_ERRORS, "WriteState: Error writing state file (state): %s",
            _archive[harchive].filespec);
        return (FALSE);
    }

    /* If we have streams... */
    if (_archive[harchive].state.n_streams == 0)
        return (TRUE);

    /* Write stream list structures */
    if ((node = FirstNode(&_archive[harchive].streams)) == NULL) {
        printf("\nERROR: WriteState: Unexpected empty stream list!");
        _archive[harchive].last_error = ARC_INTERNAL_ERROR;
        return (FALSE);
    }
    i = 0;
    while (TRUE) {
        stream = (STREAM *) node->data;

        if (SerializedWrite(stream, _stream_template,
                _archive[harchive].file) == VOID_UINT32) {
            ArchiveLog(ARC_LOG_ERRORS, "WriteState: Error writing state file (stream): %s",
                _archive[harchive].filespec);
            return (FALSE);
        }

        if (++i >= _archive[harchive].state.n_streams)
            break;

        if ((node = NextNode(node)) == NULL) {
            printf("\nERROR: WriteState: Unexpected end of stream list!");
            _archive[harchive].last_error = ARC_INTERNAL_ERROR;
            return (FALSE);
        }
    }

    /* Flush buffers to disk */
    if (!FileFlush(_archive[harchive].file)) {
        _archive[harchive].last_error = ARC_FILE_IO_ERROR;
        return (FALSE);
    }

    return (TRUE);
}
예제 #18
0
void OgreXmlSerializer::ReadGeometryVertexBuffer(VertexDataXml *dest)
{
    bool positions = (HasAttribute("positions") && ReadAttribute<bool>("positions"));
    bool normals   = (HasAttribute("normals") && ReadAttribute<bool>("normals"));
    bool tangents  = (HasAttribute("tangents") && ReadAttribute<bool>("tangents"));
    uint32_t uvs   = (HasAttribute("texture_coords") ? ReadAttribute<uint32_t>("texture_coords") : 0);

    // Not having positions is a error only if a previous vertex buffer did not have them.
    if (!positions && !dest->HasPositions()) {
        throw DeadlyImportError("Vertex buffer does not contain positions!");
    }

    if (positions)
    {
        DefaultLogger::get()->debug("    - Contains positions");
        dest->positions.reserve(dest->count);
    }
    if (normals)
    {
        DefaultLogger::get()->debug("    - Contains normals");
        dest->normals.reserve(dest->count);
    }
    if (tangents)
    {
        DefaultLogger::get()->debug("    - Contains tangents");
        dest->tangents.reserve(dest->count);
    }
    if (uvs > 0)
    {
        DefaultLogger::get()->debug(Formatter::format() << "    - Contains " << uvs << " texture coords");
        dest->uvs.resize(uvs);
        for(size_t i=0, len=dest->uvs.size(); i<len; ++i) {
            dest->uvs[i].reserve(dest->count);
        }
    }

    bool warnBinormal = true;
    bool warnColorDiffuse = true;
    bool warnColorSpecular = true;

    NextNode();

    while(m_currentNodeName == nnVertex       ||
          m_currentNodeName == nnPosition     ||
          m_currentNodeName == nnNormal       ||
          m_currentNodeName == nnTangent      ||
          m_currentNodeName == nnBinormal     ||
          m_currentNodeName == nnTexCoord     ||
          m_currentNodeName == nnColorDiffuse ||
          m_currentNodeName == nnColorSpecular)
    {
        if (m_currentNodeName == nnVertex) {
            NextNode();
        }

        /// @todo Implement nnBinormal, nnColorDiffuse and nnColorSpecular

        if (positions && m_currentNodeName == nnPosition)
        {
            aiVector3D pos;
            pos.x = ReadAttribute<float>(anX);
            pos.y = ReadAttribute<float>(anY);
            pos.z = ReadAttribute<float>(anZ);
            dest->positions.push_back(pos);
        }
        else if (normals && m_currentNodeName == nnNormal)
        {
            aiVector3D normal;
            normal.x = ReadAttribute<float>(anX);
            normal.y = ReadAttribute<float>(anY);
            normal.z = ReadAttribute<float>(anZ);
            dest->normals.push_back(normal);
        }
        else if (tangents && m_currentNodeName == nnTangent)
        {
            aiVector3D tangent;
            tangent.x = ReadAttribute<float>(anX);
            tangent.y = ReadAttribute<float>(anY);
            tangent.z = ReadAttribute<float>(anZ);
            dest->tangents.push_back(tangent);
        }
        else if (uvs > 0 && m_currentNodeName == nnTexCoord)
        {
            for(size_t i=0, len=dest->uvs.size(); i<len; ++i)
            {
                if (m_currentNodeName != nnTexCoord) {
                    throw DeadlyImportError("Vertex buffer declared more UVs than can be found in a vertex");
                }

                aiVector3D uv;
                uv.x = ReadAttribute<float>("u");
                uv.y = (ReadAttribute<float>("v") * -1) + 1; // Flip UV from Ogre to Assimp form
                dest->uvs[i].push_back(uv);

                NextNode();
            }
            // Continue main loop as above already read next node
            continue;
        }
        else
        {
            /// @todo Remove this stuff once implemented. We only want to log warnings once per element.
            bool warn = true;
            if (m_currentNodeName == nnBinormal)
            {
                if (warnBinormal)
                {
                    warnBinormal = false;
                }
                else
                {
                    warn = false;
                }
            }
            else if (m_currentNodeName == nnColorDiffuse)
            {
                if (warnColorDiffuse)
                {
                    warnColorDiffuse = false;
                }
                else
                {
                    warn = false;
                }
            }
            else if (m_currentNodeName == nnColorSpecular)
            {
                if (warnColorSpecular)
                {
                    warnColorSpecular = false;
                }
                else
                {
                    warn = false;
                }
            }
            if (warn) {
                DefaultLogger::get()->warn("Vertex buffer attribute read not implemented for element: " + m_currentNodeName);
            }
        }

        // Advance
        NextNode();
    }

    // Sanity checks
    if (dest->positions.size() != dest->count) {
      throw DeadlyImportError(Formatter::format() << "Read only " << dest->positions.size() << " positions when should have read " << dest->count);
    }
    if (normals && dest->normals.size() != dest->count) {
        throw DeadlyImportError(Formatter::format() << "Read only " << dest->normals.size() << " normals when should have read " << dest->count);
    }
    if (tangents && dest->tangents.size() != dest->count) {
        throw DeadlyImportError(Formatter::format() << "Read only " << dest->tangents.size() << " tangents when should have read " << dest->count);
    }
    for(unsigned int i=0; i<dest->uvs.size(); ++i)
    {
        if (dest->uvs[i].size() != dest->count) {
            throw DeadlyImportError(Formatter::format() << "Read only " << dest->uvs[i].size()
                << " uvs for uv index " << i << " when should have read " << dest->count);
        }
    }
}
예제 #19
0
void OgreXmlSerializer::ReadSubMesh(MeshXml *mesh)
{
    static const std::string anMaterial          = "material";
    static const std::string anUseSharedVertices = "usesharedvertices";
    static const std::string anCount             = "count";
    static const std::string anV1                = "v1";
    static const std::string anV2                = "v2";
    static const std::string anV3                = "v3";
    static const std::string anV4                = "v4";

    SubMeshXml* submesh = new SubMeshXml();

    if (HasAttribute(anMaterial)) {
        submesh->materialRef = ReadAttribute<std::string>(anMaterial);
    }
    if (HasAttribute(anUseSharedVertices)) {
        submesh->usesSharedVertexData = ReadAttribute<bool>(anUseSharedVertices);
    }

    DefaultLogger::get()->debug(Formatter::format() << "Reading SubMesh " << mesh->subMeshes.size());
    DefaultLogger::get()->debug(Formatter::format() << "  - Material: '" << submesh->materialRef << "'");
    DefaultLogger::get()->debug(Formatter::format() << "  - Uses shared geometry: " << (submesh->usesSharedVertexData ? "true" : "false"));

    // TODO: maybe we have always just 1 faces and 1 geometry and always in this order. this loop will only work correct, when the order
    // of faces and geometry changed, and not if we have more than one of one
    /// @todo Fix above comment with better read logic below

    bool quadWarned = false;

    NextNode();
    while(m_currentNodeName == nnFaces     ||
          m_currentNodeName == nnGeometry  ||
          m_currentNodeName == nnTextures  ||
          m_currentNodeName == nnBoneAssignments)
    {
        if (m_currentNodeName == nnFaces)
        {
            submesh->indexData->faceCount = ReadAttribute<uint32_t>(anCount);
            submesh->indexData->faces.reserve(submesh->indexData->faceCount);

            NextNode();
            while(m_currentNodeName == nnFace)
            {
                aiFace face;
                face.mNumIndices = 3;
                face.mIndices = new unsigned int[3];
                face.mIndices[0] = ReadAttribute<uint32_t>(anV1);
                face.mIndices[1] = ReadAttribute<uint32_t>(anV2);
                face.mIndices[2] = ReadAttribute<uint32_t>(anV3);

                /// @todo Support quads if Ogre even supports them in XML (I'm not sure but I doubt it)
                if (!quadWarned && HasAttribute(anV4)) {
                    DefaultLogger::get()->warn("Submesh <face> has quads with <v4>, only triangles are supported at the moment!");
                    quadWarned = true;
                }

                submesh->indexData->faces.push_back(face);

                // Advance
                NextNode();
            }

            if (submesh->indexData->faces.size() == submesh->indexData->faceCount)
            {
                DefaultLogger::get()->debug(Formatter::format() << "  - Faces " << submesh->indexData->faceCount);
            }
            else
            {
                throw DeadlyImportError(Formatter::format() << "Read only " << submesh->indexData->faces.size() << " faces when should have read " << submesh->indexData->faceCount);
            }
        }
        else if (m_currentNodeName == nnGeometry)
        {
            if (submesh->usesSharedVertexData) {
                throw DeadlyImportError("Found <geometry> in <submesh> when use shared geometry is true. Invalid mesh file.");
            }

            submesh->vertexData = new VertexDataXml();
            ReadGeometry(submesh->vertexData);
        }
        else if (m_currentNodeName == nnBoneAssignments)
        {
            ReadBoneAssignments(submesh->vertexData);
        }
        // Assimp incompatible/ignored nodes
        else
            SkipCurrentNode();
    }

    submesh->index = mesh->subMeshes.size();
    mesh->subMeshes.push_back(submesh);
}
예제 #20
0
/*
   Apply the first UPX (UPX.chpx) in std.grupx to the UPE.

   To apply a UPX.chpx to a UPE.chpx, take the grpprl in UPE.chpx.grpprl (which
   has a length of UPE.chpx.cbGrpprl) and merge the grpprl in UPX.chpx.grpprl
   into it.

   Merging grpprls is a tricky business, but for character styles it is easy
   because no prls in character style grpprls should interact with each other.
   Each prl from the source (the UPX.chpx.grpprl) should be inserted into the
   destination (the UPE.chpx.grpprl) so that the sprm of each prl is in increasing
   order, and any prls that have the same sprm are replaced by the prl in the
   source.

   UPE.chpx.cbGrpprl is then set to the length of resulting grpprl, and
   UPE.chpx.istd is set to the style's istd.
 */
void
wvMergeCHPXFromBucket(CHPX *dest, UPXF *src) {
    BintreeInfo tree;
    Node        *testn, *testp;
    U16         i = 0, j;
    U16         sprm;
    U8          len = 0;
    U8          temp;
    Node        *test = NULL;

    U8 *pointer, *dpointer;
    U8 *grpprl = NULL;

    /*
       use a binary tree ala the wmf stuff and first insert every dest sprm into it,
       then insert every src sprm into it, take the full count and take them out of
       the tree and create the list from them
     */
    InitBintree(&tree, wvCompLT, wvCompEQ);
    pointer = dest->grpprl;

    while (i < dest->cbGrpprl) {
        wvTrace(("gotcha the sprm is %x\n", *((U16 *)pointer)));
        test = InsertNode(&tree, (void *)pointer);
        sprm = dread_16ubit(NULL, &pointer);
        wvTrace(("the sprm is %x\n", sprm));
        temp     = wvEatSprm(sprm, pointer, &i);
        pointer += temp;
        i       += 2;
        if (test)
            len += temp + 2;
    }

    i       = 0;
    pointer = src->upx.chpx.grpprl;
    i       = 0;
    while (i < src->cbUPX) {
        /*wvTrace(("gotcha 2 the sprm is %x\n",*((U16 *)pointer))); */
        test = InsertNode(&tree, (void *)pointer);
        sprm = dread_16ubit(NULL, &pointer);
        i   += 2;
        wvTrace(("the sprm is %x\n", sprm));
        temp = wvEatSprm(sprm, pointer, &i);
        wvTrace(("len of op is %d\n", temp));
        pointer += temp;
        wvTrace(("p dis is %d\n", pointer - src->upx.chpx.grpprl));
        if (test)
            len += temp + 2;
    }

    if (len != 0)
        grpprl = (U8 *)wvMalloc(len);
    else
        return;


    dpointer = grpprl;

    testn = NextNode(&tree, NULL);
    while (testn != NULL) {
        pointer = (U8 *)testn->Data;
        sprm    = sread_16ubit(pointer);
        wvTrace(("methinks the sprm is %x\n", sprm));
        pointer += 2;

        i = 0;
        wvEatSprm(sprm, pointer, &i);
        wvTrace(("i is now %d\n", i));

        pointer = (U8 *)testn->Data;
        for (j = 0; j < i + 2; j++)
            *dpointer++ = *pointer++;

        testp = NextNode(&tree, testn);
        wvDeleteNode(&tree, testn);
        testn = testp;
    }
    wvFree(dest->grpprl);
    dest->grpprl   = grpprl;
    dest->cbGrpprl = len;

    /*test */
    i       = 0;
    pointer = dest->grpprl;
    while (i < dest->cbGrpprl) {
        sprm = dread_16ubit(NULL, &pointer);
        wvTrace(("final test the sprm is %x\n", sprm));
        temp     = wvEatSprm(sprm, pointer, &i);
        pointer += temp;
        i       += 2;
        if (test)
            len += temp + 2;
    }
}
예제 #21
0
void OgreXmlSerializer::ReadBones(Skeleton *skeleton)
{
    DefaultLogger::get()->debug("  - Bones");

    NextNode();
    while(m_currentNodeName == nnBone)
    {
        Bone *bone = new Bone();
        bone->id = ReadAttribute<uint16_t>("id");
        bone->name = ReadAttribute<std::string>("name");

        NextNode();
        while(m_currentNodeName == nnPosition ||
              m_currentNodeName == nnRotation ||
              m_currentNodeName == nnScale)
        {
            if (m_currentNodeName == nnPosition)
            {
                bone->position.x = ReadAttribute<float>(anX);
                bone->position.y = ReadAttribute<float>(anY);
                bone->position.z = ReadAttribute<float>(anZ);
            }
            else if (m_currentNodeName == nnRotation)
            {
                float angle = ReadAttribute<float>("angle");

                if (NextNode() != nnAxis) {
                    throw DeadlyImportError(Formatter::format() << "No axis specified for bone rotation in bone " << bone->id);
                }

                aiVector3D axis;
                axis.x = ReadAttribute<float>(anX);
                axis.y = ReadAttribute<float>(anY);
                axis.z = ReadAttribute<float>(anZ);

                bone->rotation = aiQuaternion(axis, angle);
            }
            else if (m_currentNodeName == nnScale)
            {
                /// @todo Implement taking scale into account in matrix/pose calculations!
                if (HasAttribute("factor"))
                {
                    float factor = ReadAttribute<float>("factor");
                    bone->scale.Set(factor, factor, factor);
                }
                else
                {
                    if (HasAttribute(anX))
                        bone->scale.x = ReadAttribute<float>(anX);
                    if (HasAttribute(anY))
                        bone->scale.y = ReadAttribute<float>(anY);
                    if (HasAttribute(anZ))
                        bone->scale.z = ReadAttribute<float>(anZ);
                }
            }

            NextNode();
        }

        skeleton->bones.push_back(bone);
    }

    // Order bones by Id
    std::sort(skeleton->bones.begin(), skeleton->bones.end(), BoneCompare);

    // Validate that bone indexes are not skipped.
    /** @note Left this from original authors code, but not sure if this is strictly necessary
        as per the Ogre skeleton spec. It might be more that other (later) code in this imported does not break. */
    for (size_t i=0, len=skeleton->bones.size(); i<len; ++i)
    {
        Bone *b = skeleton->bones[i];
        DefaultLogger::get()->debug(Formatter::format() << "    " << b->id << " " << b->name);

        if (b->id != static_cast<uint16_t>(i)) {
            throw DeadlyImportError(Formatter::format() << "Bone ids are not in sequence starting from 0. Missing index " << i);
        }
    }
}
예제 #22
0
파일: table.c 프로젝트: AbiWord/wv
/*
-------------------------
|          |            |
-------------------------
|   | | |    |     |    |
-------------------------
|                       |
-------------------------
|     |         |       |
-------------------------

==>

|   | | |  | |  |  |    |

As in this example we create a list of cell begin
positions which is a superset of all begin
positions in all rows, once we have this list we
restart at the top of the table and figure out
how many spans each cell has to achieve to match
back up to its original boundaries.

We will have to match boundaries that are with in
3 units of eachother to be the same boundary as
that occurs frequently in word tables, (gagh!)
*/
void
wvSetTableInfo (wvParseStruct * ps, TAP * ptap, int no)
{
    BintreeInfo tree;
    Node *testn, *testp;
    int i, j, k;

    if (ps->vmerges)
      {
	  wvTrace (("vmerges is not NULL\n"));
	  for (i = 0; i < ps->norows; i++)
	      wvFree (ps->vmerges[i]);
	  wvFree (ps->vmerges);
	  ps->vmerges = NULL;
      }

    if (no == 0)
      {
	  wvWarning ("Broken tables, continuing and hoping for the best\n");
	  ps->nocellbounds = 0;
	  return;
      }

    InitBintree (&tree, cellCompLT, cellCompEQ);

    wvTrace (("we still ok, no is %d\n", no));

    for (i = 0; i < no; i++)
      {
		  for (j = 0; j < ptap[i].itcMac + 1; j++)
	    {
		wvTrace (("%d\n", ptap[i].rgdxaCenter[j]));
		InsertNode (&tree, (void *) &(ptap[i].rgdxaCenter[j]));
	    }
      }
    wvTrace (("end of in\n"));

    testn = NextNode (&tree, NULL);

    ps->nocellbounds = tree.no_in_tree;
    wvFree (ps->cellbounds);
    if (tree.no_in_tree)
	ps->cellbounds = (S16 *) wvMalloc (sizeof (S16) * tree.no_in_tree);
    else
	ps->cellbounds = NULL;

    i = 0;
    wvTrace (("No in tree is %d\n", tree.no_in_tree));
    while (testn != NULL)
      {
	  ps->cellbounds[i++] = *((S16 *) testn->Data);
	  wvTrace (("cellbound are %d\n", ps->cellbounds[i - 1]));
	  testp = NextNode (&tree, testn);
	  wvDeleteNode (&tree, testn);
	  testn = testp;
      }
    wvTrace (("No in tree according to i is %d\n", i));

    wvTrace (("end of out\n"));

    ps->vmerges = (S16 **) wvMalloc (sizeof (S16 *) * no);
    wvTrace (("no of rows is %d\n", no));
    for (i = 0; i < no; i++)
      {
	  ps->vmerges[i] = (S16 *) wvMalloc (sizeof (S16) * ptap[i].itcMac);
	  wvTrace (("no of cells is %d\n", ptap[i].itcMac));
	  for (j = 0; j < ptap[i].itcMac; j++)
	      ps->vmerges[i][j] = 1;
      }

    for (i = no - 1; i > 0; i--)
      {
	  for (j = 0; j < ptap[i].itcMac; j++)
	    {
		wvTrace (
			 ("Vertical merge is %d\n",
			  ptap[i].rgtc[j].fVertMerge));
		if (ptap[i].rgtc[j].fVertMerge)
		  {
		      wvTrace (
			       ("Vertical merge found, row %d, cell %d\n", i,
				j));
		      /* 
		         find a cell above me with the same boundaries
		         if it is also merged increment it, and set myself to 0
		         else leave me alone
		       */
		      for (k = 0; k < ptap[i - 1].itcMac; k++)	/* the row above */
			{
			    wvTrace (
				     ("cell begins are %d %d\n",
				      ptap[i - 1].rgdxaCenter[k],
				      ptap[i].rgdxaCenter[j]));
			    wvTrace (
				     ("cell ends are %d %d\n",
				      ptap[i - 1].rgdxaCenter[k + 1],
				      ptap[i].rgdxaCenter[j + 1]));

			    if (
				(cellCompEQ
				 ((void *) &(ptap[i - 1].rgdxaCenter[k]),
				  (void *) &(ptap[i].rgdxaCenter[j])))
				&&
				(cellCompEQ
				 ((void *) &(ptap[i - 1].rgdxaCenter[k + 1]),
				  (void *) &(ptap[i].rgdxaCenter[j + 1]))))
			      {
				  wvTrace (("found a cell above me, yippee\n"));
				  if (ptap[i - 1].rgtc[k].fVertMerge)
				    {
					ps->vmerges[i - 1][k] +=
					    ps->vmerges[i][j];
					ps->vmerges[i][j] = 0;
				    }
			      }

			}
		  }
	    }
      }


    for (i = 0; i < no; i++)
	for (j = 0; j < ptap[i].itcMac; j++)
	    wvTrace (("rowspan numbers are %d\n", ps->vmerges[i][j]));
}
예제 #23
0
//
// Find:
// Take nodes out of the tree with NextNode,
// until null (NextNode will return 0 at the end of our range).
//
NS_IMETHODIMP
nsFind::Find(const PRUnichar *aPatText, nsIDOMRange* aSearchRange,
             nsIDOMRange* aStartPoint, nsIDOMRange* aEndPoint,
             nsIDOMRange** aRangeRet)
{
#ifdef DEBUG_FIND
  printf("============== nsFind::Find('%s'%s, %p, %p, %p)\n",
         NS_LossyConvertUTF16toASCII(aPatText).get(),
         mFindBackward ? " (backward)" : " (forward)",
         (void*)aSearchRange, (void*)aStartPoint, (void*)aEndPoint);
#endif

  NS_ENSURE_ARG(aSearchRange);
  NS_ENSURE_ARG(aStartPoint);
  NS_ENSURE_ARG(aEndPoint);
  NS_ENSURE_ARG_POINTER(aRangeRet);
  *aRangeRet = 0;

  if (!aPatText)
    return NS_ERROR_NULL_POINTER;

  ResetAll();

  nsAutoString patAutoStr(aPatText);
  if (!mCaseSensitive)
    ToLowerCase(patAutoStr);

  // Ignore soft hyphens in the pattern  
  static const char kShy[] = { char(CH_SHY), 0 };
  patAutoStr.StripChars(kShy);

  const PRUnichar* patStr = patAutoStr.get();
  PRInt32 patLen = patAutoStr.Length() - 1;

  // current offset into the pattern -- reset to beginning/end:
  PRInt32 pindex = (mFindBackward ? patLen : 0);

  // Current offset into the fragment
  PRInt32 findex = 0;

  // Direction to move pindex and ptr*
  int incr = (mFindBackward ? -1 : 1);

  nsCOMPtr<nsIContent> tc;
  const nsTextFragment *frag = nsnull;
  PRInt32 fragLen = 0;

  // Pointers into the current fragment:
  const PRUnichar *t2b = nsnull;
  const char      *t1b = nsnull;

  // Keep track of when we're in whitespace:
  // (only matters when we're matching)
  bool inWhitespace = false;

  // Place to save the range start point in case we find a match:
  nsCOMPtr<nsIDOMNode> matchAnchorNode;
  PRInt32 matchAnchorOffset = 0;

  // Get the end point, so we know when to end searches:
  nsCOMPtr<nsIDOMNode> endNode;
  PRInt32 endOffset;
  aEndPoint->GetEndContainer(getter_AddRefs(endNode));
  aEndPoint->GetEndOffset(&endOffset);

  PRUnichar prevChar = 0;
  while (1)
  {
#ifdef DEBUG_FIND
    printf("Loop ...\n");
#endif

    // If this is our first time on a new node, reset the pointers:
    if (!frag)
    {

      tc = nsnull;
      NextNode(aSearchRange, aStartPoint, aEndPoint, false);
      if (!mIterNode)    // Out of nodes
      {
        // Are we in the middle of a match?
        // If so, try again with continuation.
        if (matchAnchorNode)
          NextNode(aSearchRange, aStartPoint, aEndPoint, true);

        // Reset the iterator, so this nsFind will be usable if
        // the user wants to search again (from beginning/end).
        ResetAll();
        return NS_OK;
      }

      // We have a new text content.  If its block parent is different
      // from the block parent of the last text content, then we
      // need to clear the match since we don't want to find
      // across block boundaries.
      nsCOMPtr<nsIDOMNode> blockParent;
      GetBlockParent(mIterNode, getter_AddRefs(blockParent));
#ifdef DEBUG_FIND
      printf("New node: old blockparent = %p, new = %p\n",
             (void*)mLastBlockParent.get(), (void*)blockParent.get());
#endif
      if (blockParent != mLastBlockParent)
      {
#ifdef DEBUG_FIND
        printf("Different block parent!\n");
#endif
        mLastBlockParent = blockParent;
        // End any pending match:
        matchAnchorNode = nsnull;
        matchAnchorOffset = 0;
        pindex = (mFindBackward ? patLen : 0);
        inWhitespace = false;
      }
 
      // Get the text content:
      tc = do_QueryInterface(mIterNode);
      if (!tc || !(frag = tc->GetText())) // Out of nodes
      {
        mIterator = nsnull;
        mLastBlockParent = 0;
        ResetAll();
        return NS_OK;
      }

      fragLen = frag->GetLength();

      // Set our starting point in this node.
      // If we're going back to the anchor node, which means that we
      // just ended a partial match, use the saved offset:
      if (mIterNode == matchAnchorNode)
        findex = matchAnchorOffset + (mFindBackward ? 1 : 0);

      // mIterOffset, if set, is the range's idea of an offset,
      // and points between characters.  But when translated
      // to a string index, it points to a character.  If we're
      // going backward, this is one character too late and
      // we'll match part of our previous pattern.
      else if (mIterOffset >= 0)
        findex = mIterOffset - (mFindBackward ? 1 : 0);

      // Otherwise, just start at the appropriate end of the fragment:
      else if (mFindBackward)
        findex = fragLen - 1;
      else
        findex = 0;

      // Offset can only apply to the first node:
      mIterOffset = -1;

      // If this is outside the bounds of the string, then skip this node:
      if (findex < 0 || findex > fragLen-1)
      {
#ifdef DEBUG_FIND
        printf("At the end of a text node -- skipping to the next\n");
#endif
        frag = 0;
        continue;
      }

#ifdef DEBUG_FIND
      printf("Starting from offset %d\n", findex);
#endif
      if (frag->Is2b())
      {
        t2b = frag->Get2b();
        t1b = nsnull;
#ifdef DEBUG_FIND
        nsAutoString str2(t2b, fragLen);
        printf("2 byte, '%s'\n", NS_LossyConvertUTF16toASCII(str2).get());
#endif
      }
      else
      {
        t1b = frag->Get1b();
        t2b = nsnull;
#ifdef DEBUG_FIND
        nsCAutoString str1(t1b, fragLen);
        printf("1 byte, '%s'\n", str1.get());
#endif
      }
    }
    else // still on the old node
    {
      // Still on the old node.  Advance the pointers,
      // then see if we need to pull a new node.
      findex += incr;
#ifdef DEBUG_FIND
      printf("Same node -- (%d, %d)\n", pindex, findex);
#endif
      if (mFindBackward ? (findex < 0) : (findex >= fragLen))
      {
#ifdef DEBUG_FIND
        printf("Will need to pull a new node: mAO = %d, frag len=%d\n",
               matchAnchorOffset, fragLen);
#endif
        // Done with this node.  Pull a new one.
        frag = nsnull;
        continue;
      }
    }

    // Have we gone past the endpoint yet?
    // If we have, and we're not in the middle of a match, return.
    if (mIterNode == endNode &&
        ((mFindBackward && (findex < endOffset)) ||
         (!mFindBackward && (findex > endOffset))))
    {
      ResetAll();
      return NS_OK;
    }

    // The two characters we'll be comparing:
    PRUnichar c = (t2b ? t2b[findex] : CHAR_TO_UNICHAR(t1b[findex]));
    PRUnichar patc = patStr[pindex];

#ifdef DEBUG_FIND
    printf("Comparing '%c'=%x to '%c' (%d of %d), findex=%d%s\n",
           (char)c, (int)c, patc, pindex, patLen, findex,
           inWhitespace ? " (inWhitespace)" : "");
#endif

    // Do we need to go back to non-whitespace mode?
    // If inWhitespace, then this space in the pat str
    // has already matched at least one space in the document.
    if (inWhitespace && !IsSpace(c))
    {
      inWhitespace = false;
      pindex += incr;
#ifdef DEBUG
      // This shouldn't happen -- if we were still matching, and we
      // were at the end of the pat string, then we should have
      // caught it in the last iteration and returned success.
      if (OVERFLOW_PINDEX)
        NS_ASSERTION(false, "Missed a whitespace match\n");
#endif
      patc = patStr[pindex];
    }
    if (!inWhitespace && IsSpace(patc))
      inWhitespace = true;

    // convert to lower case if necessary
    else if (!inWhitespace && !mCaseSensitive && IsUpperCase(c))
      c = ToLowerCase(c);

    // ignore soft hyphens in the document
    if (c == CH_SHY)
      continue;

    // a '\n' between CJ characters is ignored
    if (pindex != (mFindBackward ? patLen : 0) && c != patc && !inWhitespace) {
      if (c == '\n' && t2b && IS_CJ_CHAR(prevChar)) {
        PRInt32 nindex = findex + incr;
        if (mFindBackward ? (nindex >= 0) : (nindex < fragLen)) {
          if (IS_CJ_CHAR(t2b[nindex]))
            continue;
        }
      }
    }

    // Compare
    if ((c == patc) || (inWhitespace && IsSpace(c)))
    {
      prevChar = c;
#ifdef DEBUG_FIND
      if (inWhitespace)
        printf("YES (whitespace)(%d of %d)\n", pindex, patLen);
      else
        printf("YES! '%c' == '%c' (%d of %d)\n", c, patc, pindex, patLen);
#endif

      // Save the range anchors if we haven't already:
      if (!matchAnchorNode) {
        matchAnchorNode = mIterNode;
        matchAnchorOffset = findex;
      }

      // Are we done?
      if (DONE_WITH_PINDEX)
        // Matched the whole string!
      {
#ifdef DEBUG_FIND
        printf("Found a match!\n");
#endif

        // Make the range:
        nsCOMPtr<nsIDOMNode> startParent;
        nsCOMPtr<nsIDOMNode> endParent;
        nsCOMPtr<nsIDOMRange> range = CreateRange();
        if (range)
        {
          PRInt32 matchStartOffset, matchEndOffset;
          // convert char index to range point:
          PRInt32 mao = matchAnchorOffset + (mFindBackward ? 1 : 0);
          if (mFindBackward)
          {
            startParent = do_QueryInterface(tc);
            endParent = matchAnchorNode;
            matchStartOffset = findex;
            matchEndOffset = mao;
          }
          else
          {
            startParent = matchAnchorNode;
            endParent = do_QueryInterface(tc);
            matchStartOffset = mao;
            matchEndOffset = findex+1;
          }
          if (startParent && endParent && 
              IsVisibleNode(startParent) && IsVisibleNode(endParent))
          {
            range->SetStart(startParent, matchStartOffset);
            range->SetEnd(endParent, matchEndOffset);
            *aRangeRet = range.get();
            NS_ADDREF(*aRangeRet);
          }
          else {
            startParent = nsnull; // This match is no good -- invisible or bad range
          }
        }

        if (startParent) {
          // If startParent == nsnull, we didn't successfully make range
          // or, we didn't make a range because the start or end node were invisible
          // Reset the offset to the other end of the found string:
          mIterOffset = findex + (mFindBackward ? 1 : 0);
  #ifdef DEBUG_FIND
          printf("mIterOffset = %d, mIterNode = ", mIterOffset);
          DumpNode(mIterNode);
  #endif

          ResetAll();
          return NS_OK;
        }
        matchAnchorNode = nsnull;  // This match is no good, continue on in document
      }

      if (matchAnchorNode) {
        // Not done, but still matching.
        // Advance and loop around for the next characters.
        // But don't advance from a space to a non-space:
        if (!inWhitespace || DONE_WITH_PINDEX || IsSpace(patStr[pindex+incr]))
        {
          pindex += incr;
          inWhitespace = false;
#ifdef DEBUG_FIND
          printf("Advancing pindex to %d\n", pindex);
#endif
        }
      
        continue;
      }
    }

#ifdef DEBUG_FIND
    printf("NOT: %c == %c\n", c, patc);
#endif

    // If we didn't match, go back to the beginning of patStr,
    // and set findex back to the next char after
    // we started the current match.
    if (matchAnchorNode)    // we're ending a partial match
    {
      findex = matchAnchorOffset;
      mIterOffset = matchAnchorOffset;
          // +incr will be added to findex when we continue

      // Are we going back to a previous node?
      if (matchAnchorNode != mIterNode)
      {
        nsCOMPtr<nsIContent> content (do_QueryInterface(matchAnchorNode));
        nsresult rv = NS_ERROR_UNEXPECTED;
        if (content)
          rv = mIterator->PositionAt(content);
        frag = 0;
        NS_ASSERTION(NS_SUCCEEDED(rv), "Text content wasn't nsIContent!");
#ifdef DEBUG_FIND
        printf("Repositioned anchor node\n");
#endif
      }
#ifdef DEBUG_FIND
      printf("Ending a partial match; findex -> %d, mIterOffset -> %d\n",
             findex, mIterOffset);
#endif
    }
    matchAnchorNode = nsnull;
    matchAnchorOffset = 0;
    inWhitespace = false;
    pindex = (mFindBackward ? patLen : 0);
#ifdef DEBUG_FIND
    printf("Setting findex back to %d, pindex to %d\n", findex, pindex);
           
#endif
  } // end while loop

  // Out of nodes, and didn't match.
  ResetAll();
  return NS_OK;
}
예제 #24
0
bool A_Star::FindPath(TreadmillMap* map2d) {
	unordered_set<Node*> openList; // note that costList makes this redundant
	unordered_set<Node*> closedList;
	unordered_map<Node*, Node*> parentList;
	unordered_map<Node*, float> costList;

	Node* current = map2d->GetStart();
	Node* currentBest = current;
	float bestHeuristic = FLT_MAX;
	openList.insert(current);
	parentList[current] = nullptr;
	costList[current] = map2d->CalcHeuristic(current); // ->GetHeuristicDist();
	int debugCounter = 0;
	int limit = 2 * map2d->GetMapWidthNodes() * map2d->GetMapLengthNodes();

	while (debugCounter++ < limit) {
		// find lowest F cost and assign that node as current
		if (map2d->CalcHeuristic(current) < bestHeuristic) { // July 14 update: must calculate heuristic before 
			bestHeuristic = current->GetHeuristicDist();
			currentBest = current;
		}

		current = NextNode(costList);

		openList.erase(current);
		closedList.insert(current);
		if (current == nullptr || current == map2d->GetGoal()) {
			if (current == nullptr)
				current = currentBest;

			// print the final path and distance
			deque<Node*> finalPath = GetPath(parentList, current);
			float distance = 0;
			finalPath[0]->SetPath(true);
			map2d->PathNodeList.push_back(finalPath[0]);
			for (int i = 1; i < finalPath.size(); i++) {
				finalPath[i]->SetPath(true);
				map2d->PathNodeList.push_back(finalPath[i]);
				float tempDist = map2d->CalcNodeWidthCm(); // dist between two nodes
				if (finalPath[i]->GetDiagonals().count(finalPath[i - 1]) != 0)
					tempDist = sqrtf(2 * tempDist*tempDist);
				distance += tempDist;
			}
			if (current == map2d->GetGoal())
				map2d->PathNodeList.push_back(current); // pad this list with another Goal so the dynamic mapping will move the S to G
														/*for each (Node* node in closedList) {
														node->SetVisited(true);
														}*/
			/*output.algorithmName = "A Star";
			output.hasSolution = current == map2d->GetGoal();
			output.nodesTotal = map2d->GetMapWidthNodes() * map2d->GetMapLengthNodes();
			output.nodesVisited = (int)openList.size() + (int)closedList.size();
			output.percentVisited = output.nodesVisited / ((double)output.nodesTotal);
			output.solutionDistance = distance;
			output.solutionTime = duration;
			output.widthResolution = map2d->GetMapWidthNodes();*/
			return current == map2d->GetGoal();

			//break;
		}

		// note that paths contain the final node too
		deque<Node*> adjacent = current->GetAllAdjacent();
		for (int i = 0; i < adjacent.size(); i++) {
			Node* node = adjacent[i];
			if (node == nullptr || closedList.count(node) != 0) continue;
			if (node->IsOccupied() || node->IsOccupationPredicted) {
				closedList.insert(node);
				continue;
			}
			// if this is not in OPEN or if its a shorter path than the one in OPEN
			// then add/replace in OPEN as needed
			float temp = map2d->CalcHeuristic(current); // July 14 change: Heuristics must be calculated the first time they are used
			float deltaG = map2d->CalcNodeWidthCm(); // dist between two nodes
			if (current->GetDiagonals().count(node) != 0)
				deltaG = sqrtf(2 * deltaG*deltaG); // get diagonal distance
			float newPath = costList[current] - current->GetHeuristicDist() + deltaG + map2d->CalcHeuristic(node);
			if (openList.count(node) == 0) {
				openList.insert(node);
				costList[node] = newPath;
				parentList[node] = current;
			}
			else {
				// check if this path is shorter
				float oldPath = costList[node];
				if (newPath < oldPath) {
					parentList[node] = current;
					costList[node] = newPath;
				}
			}
		}
		costList.erase(current); // because it is not in the open list anymore
	}

	return false;
	//return output;
}